110 lines
2.3 KiB
Go
110 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
tgadaptor "github.com/tgckpg/golifehk/adaptors/tg"
|
|
cjlookup "github.com/tgckpg/golifehk/datasources/cjlookup"
|
|
kmb "github.com/tgckpg/golifehk/datasources/kmb"
|
|
mtrbus "github.com/tgckpg/golifehk/datasources/mtr/bus"
|
|
query "github.com/tgckpg/golifehk/query"
|
|
utils "github.com/tgckpg/golifehk/utils"
|
|
)
|
|
|
|
func main() {
|
|
bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_API_TOKEN"))
|
|
if err != nil {
|
|
log.Panic(err)
|
|
}
|
|
|
|
bot.Debug = true
|
|
|
|
log.Printf("Authorized on account %s", bot.Self.UserName)
|
|
|
|
u := tgbotapi.NewUpdate(0)
|
|
u.Timeout = 60
|
|
|
|
updates := bot.GetUpdatesChan(u)
|
|
|
|
for update := range updates {
|
|
|
|
if update.CallbackQuery != nil {
|
|
callback := tgbotapi.NewCallback(update.CallbackQuery.ID, "")
|
|
bot.Request(callback)
|
|
|
|
q := query.QueryMessage{Lang: "zh-Hant", Text: update.CallbackQuery.Data}
|
|
f_sent, f_err := processQuery(bot, &update, q)
|
|
|
|
if !f_sent && f_err != nil {
|
|
mesg := utils.MDv2Text(fmt.Sprintf("%s", f_err))
|
|
tgadaptor.BotSendText(bot, &update, &mesg)
|
|
}
|
|
|
|
continue
|
|
}
|
|
|
|
if update.Message == nil {
|
|
continue
|
|
}
|
|
|
|
log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
|
|
isGroup := (update.Message.Chat.ID < 0)
|
|
|
|
mesg, processed := utils.SystemControl(update.Message)
|
|
if processed {
|
|
if mesg != "" {
|
|
tgadaptor.BotSendText(bot, &update, &mesg)
|
|
}
|
|
continue
|
|
}
|
|
|
|
tgMesg := update.Message
|
|
q := query.QueryMessage{Lang: "zh-Hant", Text: tgMesg.Text}
|
|
|
|
if tgMesg.Location != nil {
|
|
q.Location = &query.GeoLocation{tgMesg.Location.Latitude, tgMesg.Location.Longitude}
|
|
}
|
|
|
|
f_sent, f_err := processQuery(bot, &update, q)
|
|
|
|
if !isGroup && !f_sent && f_err != nil {
|
|
mesg := utils.MDv2Text(fmt.Sprintf("%s", f_err))
|
|
tgadaptor.BotSendText(bot, &update, &mesg)
|
|
}
|
|
}
|
|
}
|
|
|
|
func processQuery(bot *tgbotapi.BotAPI, update *tgbotapi.Update, q query.QueryMessage) (bool, error) {
|
|
var f_sent bool = false
|
|
var f_err error = nil
|
|
|
|
f_queries := []func(query.QueryMessage) query.IQueryResult{
|
|
cjlookup.Query,
|
|
mtrbus.Query,
|
|
kmb.Query,
|
|
}
|
|
|
|
for _, Query := range f_queries {
|
|
|
|
qResult := Query(q)
|
|
sent, err := tgadaptor.BotSend(bot, update, qResult)
|
|
|
|
if sent {
|
|
f_sent = true
|
|
}
|
|
|
|
if err != nil {
|
|
f_err = err
|
|
}
|
|
|
|
if qResult.Consumed() {
|
|
break
|
|
}
|
|
}
|
|
|
|
return f_sent, f_err
|
|
}
|