tg

package
v0.8.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 2, 2023 License: GPL-3.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SummaryPrefix string      = "sh_"
	Near          SummaryType = "near"
	Day           SummaryType = "day"
	Week          SummaryType = "week"
	ICS           SummaryType = "ics"
)

Variables

View Source
var AdminKey = []string{"scream", "stat"}
View Source
var Comm = map[database.Kind]string{
	database.Lection:    "Лекция",
	database.Practice:   "Практика",
	database.Lab:        "Лаба",
	database.Other:      "Прочее",
	database.Military:   "",
	database.Window:     "",
	database.Exam:       "Экзамен",
	database.Consult:    "Консультация",
	database.CourseWork: "Курсовая",
}
View Source
var Icons = map[database.Kind]string{
	database.Lection:    "📗",
	database.Practice:   "📕",
	database.Lab:        "📘",
	database.Other:      "📙",
	database.Military:   "🫡",
	database.Window:     "🏝",
	database.Exam:       "💀",
	database.Consult:    "🗨",
	database.CourseWork: "🤯",
}
View Source
var Month = []string{
	"января",
	"февраля",
	"марта",
	"апреля",
	"мая",
	"июня",
	"июля",
	"августа",
	"сентября",
	"октября",
	"ноября",
	"декабря",
}
View Source
var SumKey = []string{"near", "day", "week"}

Functions

func AppendSearchResults

func AppendSearchResults(
	list ssauparser.SearchResults,
	groups []database.Group,
	teachers []database.Teacher,
) (
	[]database.Group,
	[]database.Teacher,
)

func CancelKey

func CancelKey() tgbotapi.InlineKeyboardMarkup

Inline-кнопка отмены

func CheckEnv

func CheckEnv() error

func CreateCondition

func CreateCondition(shedule database.ShedulesInUser) string

Создать условие поиска группы/преподавателя

func DayStr

func DayStr(day time.Time) string

Строка даты формата "среду, 1 января"

func GeneralKeyboard

func GeneralKeyboard(options bool) tgbotapi.ReplyKeyboardMarkup

Основные кнопки действий: "Моё расписание" и "Настройки" (опционально)

func GenerateButtonTail

func GenerateButtonTail(sheduleID int64, dt int, isGroup bool) string

func GenerateGroupsArray

func GenerateGroupsArray(groups []database.Group, isAdd bool) []tgbotapi.InlineKeyboardButton

Создание ряда кнопок из списка групп

func GenerateKeyboard

Создание полноценной клавиатуры выбора

func GenerateName

func GenerateName(t database.Teacher) string

Создать имя преподавателя формата Фамилия И.О.

func GeneratePath

func GeneratePath(sh database.ShedulesInUser, isPersonal bool, userID int64) string

func GenerateTeachersArray

func GenerateTeachersArray(teachers []database.Teacher, isAdd bool) []tgbotapi.InlineKeyboardButton

Создание ряда кнопок из списка преподавателей

func GroupPairs

func GroupPairs(lessons []database.Lesson) [][]database.Lesson

Группировка занятий по парам

func InitUser

func InitUser(db *xorm.Engine, user *tgbotapi.User) (*database.TgUser, error)

Получение данных о пользователе из БД и создание нового при необходимости

func KeywordContains

func KeywordContains(str string, keywords []string) bool

Проверить строку на наличие одного из ключевых слов

func LessonHTML

func LessonHTML(bot *Bot, l []database.Lesson, isGroup bool) string

Вёрстка пары в HTML

func PairToStr

func PairToStr(pair []database.Lesson, db *xorm.Engine, isGroup bool) (string, error)

Конвертация занятий с текст

func SummaryKeyboard

func SummaryKeyboard(
	clickedButton SummaryType,
	shedule database.ShedulesInUser,
	isPersonal bool,
	dt int,
) tgbotapi.InlineKeyboardMarkup

Inline-клавиатура карточки с расписанием

func Swap

Меняем шило на мыло

Types

type Bot

type Bot struct {
	TG        *tgbotapi.BotAPI
	DB        *xorm.Engine
	TestUser  int64
	HelpTxt   string
	Week      int
	WkPath    string
	Debug     *log.Logger
	Updates   *tgbotapi.UpdatesChannel
	Messages  int64
	Callbacks int64
	Build     string
}

func InitBot

func InitBot(db database.DB, token string, build string) (*Bot, error)

Полная инициализация бота со стороны Telegram и БД

func (*Bot) ActShedule

func (bot *Bot) ActShedule(isPersonal bool, user *database.TgUser, shedule *database.ShedulesInUser) error

Актуализация запроса на расписание для персональных расписаний

func (*Bot) AdminHandle

func (bot *Bot) AdminHandle(msg *tgbotapi.Message) (tgbotapi.Message, error)

func (*Bot) AutoGenKeyboard

func (bot *Bot) AutoGenKeyboard(user *database.TgUser) tgbotapi.ReplyKeyboardMarkup

Основные кнопки действий с автоопределением необходимости кнопки "Настройки"

func (*Bot) Cancel

func (bot *Bot) Cancel(user *database.TgUser, query *tgbotapi.CallbackQuery) error

func (*Bot) CheckBlocked

func (bot *Bot) CheckBlocked(err error, user database.TgUser)

func (*Bot) CheckWeek

func (bot *Bot) CheckWeek(now time.Time, week *int, shedule database.ShedulesInUser) (bool, error)

Проверка, не закончились ли пары на этой неделе

При week == -1 неделя определяется автоматически

func (*Bot) CreateHTMLShedule

func (bot *Bot) CreateHTMLShedule(
	isGroup bool,
	header string,
	shedule [][6][]database.Lesson,
	dates []time.Time,
	times []ssauparser.Pair,
) string

TODO: подумать о своём поведении и сделать эти процессы покрасивее

func (*Bot) CreateICS

func (bot *Bot) CreateICS(
	now time.Time,
	user *database.TgUser,
	shedule database.ShedulesInUser,
	isPersonal bool,
	week int,
	query ...tgbotapi.CallbackQuery,
) error

Создание и отправка .ics файла с расписанием указанной недели для приложений календаря

При week == -1 неделя определяется автоматически

func (*Bot) CreateWeekImg

func (bot *Bot) CreateWeekImg(
	now time.Time,
	user *database.TgUser,
	shedule database.ShedulesInUser,
	week int,
	isPersonal bool,
	caption string,
	editMsg ...tgbotapi.Message,
) error

func (*Bot) DeleteGroup

func (bot *Bot) DeleteGroup(user *database.TgUser, text string) (tgbotapi.Message, error)

func (*Bot) DeleteUser

func (bot *Bot) DeleteUser(user database.TgUser) error

func (*Bot) EditOrSend

func (bot *Bot) EditOrSend(
	id int64,
	str string,
	imageID string,
	markup tgbotapi.InlineKeyboardMarkup,
	editMsg ...tgbotapi.Message,
) (
	tgbotapi.Message,
	error,
)

Отправка сообщения или его редактирование, если в editMsg указано сообщение TODO: Обрабатывать старые сообщения, которые уже нельзя редактировать (message can't be deleted for everyone)

func (*Bot) Etc

func (bot *Bot) Etc(user *database.TgUser) (tgbotapi.Message, error)

func (*Bot) Find

func (bot *Bot) Find(now time.Time, user *database.TgUser, query string) (tgbotapi.Message, error)

Поиск расписания по запросу

func (*Bot) GenerateICS

func (bot *Bot) GenerateICS(
	lessons []database.Lesson,
	shedule database.ShedulesInUser,
) (
	string,
	error,
)

Создание непосредственно ICS файла

func (*Bot) GetDaySummary

func (bot *Bot) GetDaySummary(
	now time.Time,
	user *database.TgUser,
	shedule database.ShedulesInUser,
	dt int,
	isPersonal bool,
	editMsg ...tgbotapi.Message,
) (
	tgbotapi.Message,
	error,
)

Получить расписание на день

Если isPersonal == false, то обязательно заполнение объекта shedule

При isPersonal == true, объект shedule игнорируется

func (*Bot) GetLessons

func (bot *Bot) GetLessons(shedule database.ShedulesInUser, now time.Time, limit int) ([]database.Lesson, error)

Получить список ближайших занятий (для краткой сводки или расписания на день)

func (*Bot) GetOptions

func (bot *Bot) GetOptions(user *database.TgUser) (tgbotapi.Message, error)

func (*Bot) GetPersonal

func (bot *Bot) GetPersonal(
	now time.Time,
	user *database.TgUser,
	editMsg ...tgbotapi.Message,
) (
	tgbotapi.Message,
	error,
)

func (*Bot) GetShedule

func (bot *Bot) GetShedule(user *database.TgUser, query *tgbotapi.CallbackQuery, now ...time.Time) error

Получить расписание из кнопки

func (*Bot) GetShortSummary

func (bot *Bot) GetShortSummary(
	now time.Time,
	user *database.TgUser,
	shedule database.ShedulesInUser,
	isPersonal bool,
	editMsg ...tgbotapi.Message,
) (
	tgbotapi.Message,
	error,
)

Получить краткую сводку

Если isPersonal == false, то обязательно заполнение объекта shedule

При isPersonal == true, объект shedule игнорируется

func (*Bot) GetUpdates

func (bot *Bot) GetUpdates()

func (*Bot) GetWeekLessons

func (bot *Bot) GetWeekLessons(shedule database.ShedulesInUser, week int) ([]database.Lesson, error)

func (*Bot) GetWeekSummary

func (bot *Bot) GetWeekSummary(
	now time.Time,
	user *database.TgUser,
	shedule database.ShedulesInUser,
	week int,
	isPersonal bool,
	caption string,
	editMsg ...tgbotapi.Message,
) error

Получить расписание на неделю При week == -1 неделя определяется автоматически

Если isPersonal == false, то обязательно заполнение объекта shedule

При isPersonal == true, объект shedule игнорируется

func (*Bot) HandleCallback

func (bot *Bot) HandleCallback(query *tgbotapi.CallbackQuery, now time.Time) (tgbotapi.Message, error)

func (*Bot) HandleMessage

func (bot *Bot) HandleMessage(msg *tgbotapi.Message, now time.Time) (tgbotapi.Message, error)

func (*Bot) HandleOptions

func (bot *Bot) HandleOptions(user *database.TgUser, query *tgbotapi.CallbackQuery) error

func (*Bot) HandleSummary

func (bot *Bot) HandleSummary(user *database.TgUser, query *tgbotapi.CallbackQuery, now ...time.Time) error

func (*Bot) HandleUpdate

func (bot *Bot) HandleUpdate(update tgbotapi.Update, now ...time.Time) (tgbotapi.Message, error)

func (*Bot) LoadShedule

func (bot *Bot) LoadShedule(shedule ssauparser.WeekShedule, now time.Time, fast bool) (
	[]database.Lesson,
	[]database.Lesson,
	error,
)

Загрузка расписания из ssau.ru/rasp

func (*Bot) ReturnSummary

func (bot *Bot) ReturnSummary(
	notExists bool,
	isAdd bool,
	user *database.TgUser,
	shedule ssauparser.WeekShedule,
	now time.Time,
) (
	tgbotapi.Message,
	error,
)

func (*Bot) Scream

func (bot *Bot) Scream(msg *tgbotapi.Message) (tgbotapi.Message, error)

func (*Bot) SendMsg

func (bot *Bot) SendMsg(user *database.TgUser, text string, markup interface{}) (tgbotapi.Message, error)

func (*Bot) SetFirstTime

func (bot *Bot) SetFirstTime(msg *tgbotapi.Message, user *database.TgUser) (tgbotapi.Message, error)

func (*Bot) Start

func (bot *Bot) Start(user *database.TgUser) (tgbotapi.Message, error)

Приветственное сообщение

func (*Bot) Stat

func (bot *Bot) Stat() (tgbotapi.Message, error)

func (*Bot) StrDayShedule

func (bot *Bot) StrDayShedule(lessons [][]database.Lesson, isGroup bool) (string, error)

Текст расписания на день

type LessonStr

type LessonStr struct {
	TypeIcon    string
	TypeStr     string
	Name        string
	Begin       time.Time
	End         time.Time
	SubGroup    int64
	TeacherName string
	Place       string
	Comment     string
}

type Line

type Line struct {
	Begin   time.Time
	End     time.Time
	Lessons [6]string
}

type SheduleData

type SheduleData struct {
	IsGroup bool
	Header  string
	Week    []WeekHead
	Lines   []Line
}

type SummaryType

type SummaryType string

func ParseQuery

func ParseQuery(data []string) (SummaryType, database.ShedulesInUser, int, error)

Расшифровывать содержимое кнопки из карточки с расписанием

type WeekHead

type WeekHead struct {
	WeekDay string
	Day     time.Time
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL