Skip to content

Commit

Permalink
feat: schedule, marks
Browse files Browse the repository at this point in the history
  • Loading branch information
oddyamill committed Sep 17, 2024
1 parent 931cace commit 0a8ad0d
Show file tree
Hide file tree
Showing 17 changed files with 426 additions and 36 deletions.
8 changes: 4 additions & 4 deletions cmd/discord/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ func main() {
}

if user == nil {
responder.Respond("Ты кто такой? Cъебал.")
_ = responder.Respond("Ты кто такой? Cъебал.")
return
}

if user.State != users.Ready {
responder.Respond("Пошел нахуй.")
_ = responder.Respond("Пошел нахуй.")
return
}

Expand All @@ -67,9 +67,9 @@ func main() {
User: *user,
}

formatter := commands.DiscordFormatter{}
formatter := helpers.DiscordFormatter{}

if len(data) != 0 {
if len(data) > 0 {
commands.HandleCallback(context, &responder, &formatter, data)
return
}
Expand Down
10 changes: 5 additions & 5 deletions cmd/telegram/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func handleMessage(update tgbotapi.Update) {
user = users.GetByTelegramID(update.Message.ForwardFrom.ID)

if user == nil {
responder.Respond("Пользователь не зарегистрирован")
_ = responder.Respond("Пользователь не зарегистрирован")
return
}

Expand All @@ -74,12 +74,12 @@ func handleMessage(update tgbotapi.Update) {
user = users.GetByTelegramID(update.Message.From.ID)

if user == nil {
responder.Respond("Ты кто такой? Уйди.")
_ = responder.Respond("Ты кто такой? Уйди.")
return
}

if user.State != users.Ready {
responder.Respond("Пошел отсюда.")
_ = responder.Respond("Пошел отсюда.")
return
}

Expand All @@ -95,7 +95,7 @@ func handleMessage(update tgbotapi.Update) {
User: *user,
}

formatter := commands.TelegramFormatter{}
formatter := helpers.TelegramFormatter{}

commands.HandleCommand(context, &responder, &formatter)
}
Expand Down Expand Up @@ -125,7 +125,7 @@ func handleCallbackQuery(update tgbotapi.Update) {
Update: update,
}

formatter := commands.TelegramFormatter{}
formatter := helpers.TelegramFormatter{}

commands.HandleCallback(context, &responder, &formatter, data)
}
28 changes: 25 additions & 3 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"github.com/kiasuo/bot/internal/helpers"
"github.com/kiasuo/bot/internal/users"
"net/http"
"strconv"
"time"
)

const BaseUrl = "https://kiasuo-proxy.oddya.ru/diary"
Expand Down Expand Up @@ -69,7 +71,7 @@ func RefreshToken(client *Client) error {
return nil
}

func ClientRequest[T any](client Client, pathname string, method string) (*T, error) {
func requestWithClient[T any](client Client, pathname string, method string) (*T, error) {
request, err := http.NewRequest(method, BaseUrl+pathname, nil)

if err != nil {
Expand Down Expand Up @@ -100,11 +102,11 @@ func ClientRequest[T any](client Client, pathname string, method string) (*T, er
}

func (c Client) GetUser() (*User, error) {
return ClientRequest[User](c, "/api/user", "GET")
return requestWithClient[User](c, "/api/user", "GET")
}

func (c Client) GetRecipients() (*Recipients, error) {
rawRecipients, err := ClientRequest[RawRecipient](c, "/api/recipients", "GET")
rawRecipients, err := requestWithClient[RawRecipient](c, "/api/recipients", "GET")

if err != nil {
return nil, err
Expand All @@ -113,3 +115,23 @@ func (c Client) GetRecipients() (*Recipients, error) {
recipients := (*rawRecipients)[c.User.StudentID]
return &recipients, nil
}

func (c Client) GetStudyPeriods() (*[]StudyPeriod, error) {
return requestWithClient[[]StudyPeriod](c, "/api/study_periods", "GET")
}

func (c Client) GetLessons(id int) (*[]Lesson, error) {
rawMarks, err := requestWithClient[RawLessons](c, "/api/lesson_marks/"+strconv.Itoa(id), "GET")

if err != nil {
return nil, err
}

return &rawMarks.Lessons, nil
}

func (c Client) GetSchedule(time time.Time) (*RawSchedule, error) {
year, week := time.ISOWeek()

return requestWithClient[RawSchedule](c, "/api/schedule?year="+strconv.Itoa(year)+"&week="+strconv.Itoa(week), "GET")
}
94 changes: 94 additions & 0 deletions internal/client/types.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package client

import (
"github.com/kiasuo/bot/internal/helpers"
"strconv"
"time"
)

type Token struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
Expand Down Expand Up @@ -37,3 +43,91 @@ type Student struct {
Parents any `json:"parents"`
ID *int `json:"id"`
}

type StudyPeriod struct {
ID int `json:"id"`
Text string `json:"text"`
From string `json:"from"`
To string `json:"to"`
}

func (p StudyPeriod) Match(t time.Time) bool {
from, _ := time.Parse(time.DateOnly, p.From)

if t.After(from) {
to, _ := time.Parse(time.DateOnly, p.To)

if t.Before(to) {
return true
}
}

return false
}

type RawLessons struct {
Lessons []Lesson `json:"lessons"`
}

type Lesson struct {
Subject string `json:"subject"`
Marks []Mark `json:"marks"`
}

func (l Lesson) String() string {
return helpers.HumanizeLesson(l.Subject)
}

type Mark struct {
// эта ебола будет мне порядок нарушать или нет?
LessonDate string `json:"lesson_date"`
Mark string `json:"mark"`
UpdatedAt time.Time `json:"updated_at"`
}

type RawSchedule struct {
Schedule []Event `json:"schedule"`
Homeworks []Homework `json:"homeworks"`
}

type Event struct {
Subject string `json:"subject"`
LessonDate string `json:"lesson_date"`
Number int `json:"lesson_number"`
Homeworks []int `json:"homework_to_check_ids"`
Marks []Mark `json:"marks"`
}

func (e Event) Date() time.Time {
date, _ := time.Parse(time.DateOnly, e.LessonDate)
return date
}

func (e Event) String() string {
return strconv.Itoa(e.Number) + ". " + helpers.HumanizeLesson(e.Subject)
}

type Homework struct {
ID int `json:"id"`
Text string `json:"text"`
Files []File `json:"files"`
Links []Link `json:"links"`
}

type File struct {
Url string `json:"url"`
Title string `json:"title"`
}

func (f File) String(formatter helpers.Formatter) string {
return formatter.Link(f.Title, f.Url)
}

type Link struct {
Url string `json:"url"`
Title string `json:"title"`
}

func (l Link) String(formatter helpers.Formatter) string {
return formatter.Link(l.Title, l.Url)
}
6 changes: 3 additions & 3 deletions internal/commands/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

const AdminCommandName string = "-internal-admin"

var AdminCommand = Command(func(context Context, responder Responder, formatter Formatter) error {
var AdminCommand = Command(func(context Context, responder Responder, formatter helpers.Formatter) error {
user := context.User

state := map[users.UserState]string{
Expand All @@ -27,7 +27,7 @@ var AdminCommand = Command(func(context Context, responder Responder, formatter
KeyboardRow{
KeyboardButton{
Text: helpers.If(user.State == users.Blacklisted, "Разблокировать", "Заблокировать"),
Callback: AdminCommandName + ":blacklist:" + string(rune(user.ID)),
Callback: AdminCommandName + ":blacklist:" + strconv.Itoa(user.ID),
},
},
}
Expand All @@ -41,7 +41,7 @@ var AdminCommand = Command(func(context Context, responder Responder, formatter
)
})

var AdminCallback = Callback(func(context Context, responder Responder, formatter Formatter, data []string) error {
var AdminCallback = Callback(func(context Context, responder Responder, formatter helpers.Formatter, data []string) error {
switch data[1] {
case "blacklist":
isBlacklisted := context.User.State == users.Blacklisted
Expand Down
7 changes: 5 additions & 2 deletions internal/commands/classmates.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package commands

import "sort"
import (
"github.com/kiasuo/bot/internal/helpers"
"sort"
)

var ClassmatesCommand = Command(func(context Context, responder Responder, formatter Formatter) error {
var ClassmatesCommand = Command(func(context Context, responder Responder, formatter helpers.Formatter) error {
recipients, err := context.GetClient().GetRecipients()

if err != nil {
Expand Down
28 changes: 21 additions & 7 deletions internal/commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@ package commands
import (
"github.com/bwmarrin/discordgo"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/kiasuo/bot/internal/helpers"
"log"
)

type Command func(Context, Responder, Formatter) error
type Command func(Context, Responder, helpers.Formatter) error

var commandMap = map[string]Command{
AdminCommandName: AdminCommand,
"start": StartCommand,
"stop": StopCommand,
"settings": SettingsCommand,
"schedule": ScheduleCommand,
"marks": MarksCommand,
"classmates": ClassmatesCommand,
"teachers": TeachersCommand,
}
Expand All @@ -38,6 +41,14 @@ var publicCommands = []commandConfig{
Name: "settings",
Description: "Настройки",
},
{
Name: "schedule",
Description: "Расписание",
},
{
Name: "marks",
Description: "Оценки",
},
{
Name: "classmates",
Description: "Список одноклассников",
Expand Down Expand Up @@ -78,15 +89,17 @@ func ParseTelegramCommands() tgbotapi.SetMyCommandsConfig {
return tgbotapi.NewSetMyCommands(commands...)
}

type Callback func(Context, Responder, Formatter, []string) error
type Callback func(Context, Responder, helpers.Formatter, []string) error

var callbackMap = map[string]Callback{
AdminCommandName: AdminCallback,
"stop": StopCallback,
"settings": SettingsCallback,
"schedule": ScheduleCallback,
"marks": MarksCallback,
}

func HandleCommand(context Context, responder Responder, formatter Formatter) {
func HandleCommand(context Context, responder Responder, formatter helpers.Formatter) {
command := commandMap[context.Command]

if command == nil {
Expand All @@ -95,10 +108,10 @@ func HandleCommand(context Context, responder Responder, formatter Formatter) {
}

log.Println("Handling command", context.Command)
handleError(command(context, responder, formatter))
handleError(responder, command(context, responder, formatter))
}

func HandleCallback(context Context, responder Responder, formatter Formatter, data []string) {
func HandleCallback(context Context, responder Responder, formatter helpers.Formatter, data []string) {
callback := callbackMap[context.Command]

if callback == nil {
Expand All @@ -107,11 +120,12 @@ func HandleCallback(context Context, responder Responder, formatter Formatter, d
}

log.Println("Handling callback", context.Command)
handleError(callback(context, responder, formatter, data))
handleError(responder, callback(context, responder, formatter, data))
}

func handleError(err error) {
func handleError(responder Responder, err error) {
if err != nil {
log.Printf("Error: %v", err)
_ = responder.Respond("Произошла ошибка. Попробуйте позже.")
}
}
Loading

0 comments on commit 0a8ad0d

Please sign in to comment.