Skip to content

Commit

Permalink
Use shared library for unibo APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
VaiTon committed Nov 4, 2023
1 parent 7012bef commit 917e3c9
Show file tree
Hide file tree
Showing 15 changed files with 343 additions and 260 deletions.
14 changes: 7 additions & 7 deletions bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import (
"log"
"strings"

"github.com/csunibo/informabot/model"
"github.com/csunibo/informabot/utils"
tgbotapi "github.com/musianisamuele/telegram-bot-api"
"golang.org/x/exp/slices"

"github.com/csunibo/informabot/model"
"github.com/csunibo/informabot/utils"
)

func StartInformaBot(token string, debug bool) {
Expand Down Expand Up @@ -42,19 +43,18 @@ func run(bot *tgbotapi.BotAPI) {
handleCommand(bot, &update)
} else {
// text message
for i := 0; i < len(model.Autoreplies); i++ {
for i := 0; i < len(model.AutoReplies); i++ {
if strings.Contains(strings.ToLower(update.Message.Text),
strings.ToLower(model.Autoreplies[i].Text)) {
strings.ToLower(model.AutoReplies[i].Text)) {
var msg tgbotapi.MessageConfig

if update.Message.IsTopicMessage {
msg = tgbotapi.NewThreadMessage(update.Message.Chat.ID,
update.Message.MessageThreadID, model.Autoreplies[i].Reply)
update.Message.MessageThreadID, model.AutoReplies[i].Reply)
} else {
msg = tgbotapi.NewMessage(update.Message.Chat.ID,
model.Autoreplies[i].Reply)
model.AutoReplies[i].Reply)
}

msg.ReplyToMessageID = update.Message.MessageID
utils.SendHTML(bot, msg)
}
Expand Down
49 changes: 26 additions & 23 deletions commands/uni.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package commands
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"sort"
"strings"
"time"

"github.com/csunibo/unibo-go/timetable"
"golang.org/x/exp/slices"
)

const TIMEFORMAT = "2006-01-02T15:04:05"
Expand Down Expand Up @@ -47,32 +48,34 @@ func (t *LezioniTime) UnmarshalJSON(data []byte) error {
return nil
}

// GetTimeTable returns the timetable for the Unibo url
// returns empty string if there are no lessons.
func GetTimeTable(url string) string {
resp, err := http.Get(url)
// GetTimeTable returns an HTML string containing the timetable for the given
// course on the given date. Returns an empty string if there are no lessons.
func GetTimeTable(courseType, courseName string, year int, day time.Time) (string, error) {

interval := &timetable.Interval{Start: day, End: day}
events, err := timetable.FetchTimetable(courseType, courseName, "", year, interval)
if err != nil {
log.Printf("Error getting json when requesting orario lezioni: %s\n", err)
log.Printf("Error getting timetable: %s\n", err)
return "", err
}
defer resp.Body.Close()

result := []OrarioLezioni{}
body, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(body, &result)

sort.Slice(result, func(i, j int) bool {
return (*time.Time)(&result[i].StartTime).Before((time.Time)(result[j].StartTime))
// Sort the events by start time
slices.SortFunc(events, func(a, b timetable.Event) int {
return int(b.Start.Time.Sub(a.Start.Time).Nanoseconds())
})

var message string = ""
for _, lezione := range result {
message += fmt.Sprintf(` 🕘 <b><a href="%s">%s</a></b>`, lezione.Teams, lezione.Title) +
"\n" + lezione.Time + "\n"
if len(lezione.Aule) > 0 {
message += fmt.Sprintf(" 🏢 %s - %s\n", lezione.Aule[0].Edificio, lezione.Aule[0].Piano)
message += fmt.Sprintf(" 📍 %s\n", lezione.Aule[0].Indirizzo)
b := strings.Builder{}
for _, event := range events {
b.WriteString(fmt.Sprintf(` 🕘 <b><a href="%s">%s</a></b>`, event.Teams, event.Title))
b.WriteString("\n")
b.WriteString(event.Start.Format("15:04"))
b.WriteString("\n")
if len(event.Classrooms) > 0 {
// TODO(VaiTon): Re-implement this
//b.WriteString(fmt.Sprintf(" 🏢 %s - %s\n", event.Classrooms[0].Edificio, event.Aule[0].Piano))
//b.WriteString(fmt.Sprintf(" 📍 %s\n", event.Classrooms[0].Indirizzo))
}
}

return message
return b.String(), nil
}
66 changes: 47 additions & 19 deletions commands/uni_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func TestLezioniTime_Format(t *testing.T) {
}

func TestLezioniTime_UnmarshalJSON(t *testing.T) {
var time LezioniTime
var lezioniTime LezioniTime
type args struct {
data []byte
}
Expand All @@ -59,31 +59,31 @@ func TestLezioniTime_UnmarshalJSON(t *testing.T) {
}{
{
name: "Not an error",
tr: &time,
tr: &lezioniTime,
args: args{
data: []byte{34, 50, 48, 50, 51, 45, 48, 51, 45, 49, 51, 84, 49, 50, 58, 48, 48, 58, 48, 48, 34},
},
wantErr: false,
},
{
name: "Error #1",
tr: &time,
tr: &lezioniTime,
args: args{
data: []byte("A"),
},
wantErr: true,
},
{
name: "Error #2",
tr: &time,
tr: &lezioniTime,
args: args{
data: []byte{},
},
wantErr: true,
},
{
name: "Error #2",
tr: &time,
tr: &lezioniTime,
args: args{
data: []byte{34},
},
Expand All @@ -102,44 +102,72 @@ func TestLezioniTime_UnmarshalJSON(t *testing.T) {

func TestGetTimeTable(t *testing.T) {
type args struct {
url string
courseType string
courseName string
year int
day time.Time
}
tests := []struct {
name string
args args
want string
name string
args args
want string
error bool
}{
{
name: "Weekend",
args: args{
url: "https://corsi.unibo.it/laurea/informatica/orario-lezioni/@@orario_reale_json?anno=1&start=2023-03-11&end=2023-03-11",
courseType: "laurea",
courseName: "informatica",
year: 1,
day: time.Date(2023, 3, 11, 0, 0, 0, 0, time.UTC),
},
want: "",
},
{
name: "Weekday",
args: args{
url: "https://corsi.unibo.it/laurea/informatica/orario-lezioni/@@orario_reale_json?anno=1&start=2023-10-31&end=2023-10-31",
courseType: "laurea",
courseName: "informatica",
year: 1,
day: time.Date(2023, 10, 31, 0, 0, 0, 0, time.UTC),
},
want: `🕘`,
},
{
name: "Not a valid url",
args: args{
url: "https://example.com",
courseType: "test",
courseName: "test",
},
want: "",
want: "",
error: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := GetTimeTable(tt.args.url)
got = strings.ReplaceAll(got, " ", "")
want := strings.ReplaceAll(tt.want, " ", "")
want = strings.ReplaceAll(want, "\t", "")
if !strings.Contains(got, want) {
t.Errorf("GetTimeTable() = %v, want %v", got, want)
got, err := GetTimeTable(tt.args.courseType, tt.args.courseName, tt.args.year, tt.args.day)
if err != nil && !tt.error {
t.Errorf("GetTimeTable() error = %v", err)
return
} else {
got = strings.ReplaceAll(got, " ", "")
want := strings.ReplaceAll(tt.want, " ", "")
want = strings.ReplaceAll(want, "\t", "")
if !strings.Contains(got, want) {
t.Errorf("GetTimeTable() = %v, want %v", got, want)
}
}
})
}
}
func TestWeekend(t *testing.T) {

date := time.Date(2023, 3, 11, 0, 0, 0, 0, time.UTC)
result, err := GetTimeTable("laurea", "informatica", 1, date)
if err != nil {
t.Fatalf("Error while getting timetable: %s", err)
}
if result != "" {
t.Errorf("Expected empty string in weekend, got %s", result)
}
}
6 changes: 2 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ module github.com/csunibo/informabot
go 1.18

require (
github.com/csunibo/unibo-go v0.0.6
github.com/mitchellh/mapstructure v1.5.0
github.com/musianisamuele/telegram-bot-api v0.0.4
)

require (
golang.org/x/exp v0.0.0-20230809094429-853ea248256d
golang.org/x/exp v0.0.0-20230905200255-921286631fa9
golang.org/x/text v0.13.0
)
6 changes: 4 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
github.com/csunibo/unibo-go v0.0.6 h1:7VDtXVTiwJwGveLyG7vP62aKMg/WpqSx2iJiGRaPlDU=
github.com/csunibo/unibo-go v0.0.6/go.mod h1:h2+xnccHa7x48RNB6d07bpHQ01ozw4oihgDOlvVrJ9U=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/musianisamuele/telegram-bot-api v0.0.4 h1:kQoE4Ih/rnyf2i8iCOwcN+zflx+H1A7+PhZx9Kkqppk=
github.com/musianisamuele/telegram-bot-api v0.0.4/go.mod h1:f8epVo400dyxqaQpXt3la1mnhdQW25R1w3yqYT3GQc4=
golang.org/x/exp v0.0.0-20230809094429-853ea248256d h1:wu5bD43Ana/nF1ZmaLr3lW/FQeJU8CcI+Ln7yWHViXE=
golang.org/x/exp v0.0.0-20230809094429-853ea248256d/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
36 changes: 30 additions & 6 deletions json/actions.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,11 @@
"type": "todayLectures",
"data": {
"description": "Orari lezioni di oggi (1\u00b0 anno)",
"url": "https://corsi.unibo.it/laurea/informatica/orario-lezioni/@@orario_reale_json?anno=1",
"course": {
"year": 1,
"type": "laurea",
"name": "Informatica"
},
"title": "<b>Lezioni di oggi (1\u00b0 anno):</b>\n",
"fallbackText": "Non ci sono lezioni oggi. SMETTILA DI PRESSARMI"
}
Expand All @@ -96,7 +100,11 @@
"type": "todayLectures",
"data": {
"description": "Orari lezioni di oggi (2\u00b0 anno)",
"url": "https://corsi.unibo.it/laurea/informatica/orario-lezioni/@@orario_reale_json?anno=2",
"course": {
"year": 2,
"type": "laurea",
"name": "Informatica"
},
"title": "<b>Lezioni di oggi (2\u00b0 anno):</b>\n",
"fallbackText": "Non ci sono lezioni oggi. SMETTILA DI PRESSARMI"
}
Expand All @@ -105,7 +113,11 @@
"type": "todayLectures",
"data": {
"description": "Orari lezioni di oggi (3\u00b0 anno)",
"url": "https://corsi.unibo.it/laurea/informatica/orario-lezioni/@@orario_reale_json?anno=3",
"course": {
"year": 3,
"type": "laurea",
"name": "Informatica"
},
"title": "<b>Lezioni di oggi:</b>\n",
"fallbackText": "Non ci sono lezioni oggi. SMETTILA DI PRESSARMI"
}
Expand All @@ -122,7 +134,11 @@
"type": "tomorrowLectures",
"data": {
"description": "Orari lezioni di domani (1\u00b0 anno)",
"url": "https://corsi.unibo.it/laurea/informatica/orario-lezioni/@@orario_reale_json?anno=1",
"course": {
"year": 1,
"type": "laurea",
"name": "Informatica"
},
"title": "<b>Lezioni di domani (1\u00b0 anno):</b>\n",
"fallbackText": "Non ci sono lezioni domani. SMETTILA DI PRESSARMI"
}
Expand All @@ -131,7 +147,11 @@
"type": "tomorrowLectures",
"data": {
"description": "Orari lezioni di domani (2\u00b0 anno)",
"url": "https://corsi.unibo.it/laurea/informatica/orario-lezioni/@@orario_reale_json?anno=2",
"course": {
"year": 2,
"type": "laurea",
"name": "Informatica"
},
"title": "<b>Lezioni di domani (2\u00b0 anno):</b>\n",
"fallbackText": "Non ci sono lezioni domani. SMETTILA DI PRESSARMI"
}
Expand All @@ -140,7 +160,11 @@
"type": "tomorrowLectures",
"data": {
"description": "Orari lezioni di domani (3\u00b0 anno)",
"url": "https://corsi.unibo.it/laurea/informatica/orario-lezioni/@@orario_reale_json?anno=3",
"course": {
"year": 3,
"type": "laurea",
"name": "Informatica"
},
"title": "<b>Lezioni di domani (3\u00b0 anno):</b>\n",
"fallbackText": "Non ci sono lezioni domani. SMETTILA DI PRESSARMI"
}
Expand Down
Loading

0 comments on commit 917e3c9

Please sign in to comment.