laniakea/bot.go

259 lines
5.5 KiB
Go
Raw Permalink Normal View History

2024-12-16 00:52:43 +03:00
package laniakea
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
type Bot struct {
token string
2024-12-16 00:56:15 +03:00
logger *Logger
2024-12-16 00:52:43 +03:00
debug bool
plugins []*Plugin
prefixes []string
updateOffset int
2024-12-17 09:23:53 +03:00
updateTypes []string
2024-12-16 00:56:15 +03:00
updateQueue *Queue[*Update]
2024-12-16 00:52:43 +03:00
}
type MsgContext struct {
Bot *Bot
Msg *Message
2024-12-17 09:23:53 +03:00
Update *Update
2024-12-16 00:52:43 +03:00
FromID int
Prefix string
Text string
}
func NewBot(token string) *Bot {
2024-12-16 00:56:15 +03:00
logger := CreateLogger()
2024-12-17 09:23:53 +03:00
logger.Level(DEBUG)
2024-12-16 00:56:15 +03:00
updateQueue := CreateQueue[*Update](256)
2024-12-16 00:52:43 +03:00
bot := &Bot{
updateOffset: 0, plugins: make([]*Plugin, 0), debug: false,
2024-12-17 09:23:53 +03:00
prefixes: make([]string, 0), updateTypes: make([]string, 0),
2024-12-16 00:52:43 +03:00
updateQueue: updateQueue,
token: token, logger: logger,
}
return bot
}
2024-12-17 09:23:53 +03:00
func (b *Bot) UpdateTypes(t ...string) *Bot {
b.updateTypes = make([]string, 0)
b.updateTypes = append(b.updateTypes, t...)
return b
}
func (b *Bot) AddUpdateType(t ...string) *Bot {
b.updateTypes = append(b.updateTypes, t...)
return b
}
func (b *Bot) AddPrefixes(prefixes ...string) *Bot {
2024-12-16 00:52:43 +03:00
b.prefixes = append(b.prefixes, prefixes...)
2024-12-17 09:23:53 +03:00
return b
2024-12-16 00:52:43 +03:00
}
func (b *Bot) Run() {
if len(b.prefixes) == 0 {
b.logger.Fatal("no prefixes defined")
return
}
if len(b.plugins) == 0 {
b.logger.Fatal("no plugins defined")
return
}
2024-12-17 09:23:53 +03:00
b.logger.Info("Bot running. Press CTRL+C to exit.")
2024-12-16 00:52:43 +03:00
go func() {
for {
2024-12-17 09:23:53 +03:00
_, err := b.Updates()
2024-12-16 00:52:43 +03:00
if err != nil {
b.logger.Error(err)
}
}
}()
for {
2024-12-17 09:23:53 +03:00
queue := b.updateQueue
2024-12-16 00:52:43 +03:00
if queue.IsEmpty() {
continue
}
u := queue.Dequeue()
2024-12-17 09:23:53 +03:00
if u.CallbackQuery != nil {
b.handleCallback(u)
} else {
b.handleMessage(u)
}
2024-12-16 00:52:43 +03:00
}
}
2024-12-17 09:23:53 +03:00
// {"callback_query":{"chat_instance":"6202057960757700762","data":"aboba","from":{"first_name":"scuroneko","id":314834933,"is_bot":false,"language_code":"ru","username":"scuroneko"},"id":"1352205741990111553","message":{"chat":{"first_name":"scuroneko","id":314834933,"type":"private","username":"scuroneko"},"date":1734338107,"from":{"first_name":"Kurumi","id":7718900880,"is_bot":true,"username":"kurumi_game_bot"},"message_id":19,"reply_markup":{"inline_keyboard":[[{"callback_data":"aboba","text":"Test"},{"callback_data":"another","text":"Another"}]]},"text":"Aboba"}},"update_id":350979488}
2024-12-16 00:52:43 +03:00
func (b *Bot) handleMessage(update *Update) {
2024-12-17 09:23:53 +03:00
ctx := &MsgContext{
Bot: b,
Update: update,
}
for _, plugin := range b.plugins {
if plugin.UpdateListener != nil {
(*plugin.UpdateListener)(ctx)
}
}
if update.Message == nil {
return
}
ctx.FromID = update.Message.From.ID
ctx.Msg = update.Message
2024-12-16 00:52:43 +03:00
text := strings.TrimSpace(update.Message.Text)
prefix, hasPrefix := b.checkPrefixes(text)
if !hasPrefix {
return
}
2024-12-17 09:23:53 +03:00
ctx.Prefix = prefix
2024-12-16 00:52:43 +03:00
text = strings.TrimSpace(text[len(prefix):])
for _, plugin := range b.plugins {
2024-12-17 09:23:53 +03:00
// Check every command
for cmd := range plugin.Commands {
2024-12-16 00:52:43 +03:00
if !strings.HasPrefix(text, cmd) {
continue
}
2024-12-17 09:23:53 +03:00
ctx.Text = text[len(cmd):]
2024-12-16 00:52:43 +03:00
plugin.Execute(cmd, ctx)
}
}
}
2024-12-17 09:23:53 +03:00
func (b *Bot) handleCallback(update *Update) {
ctx := &MsgContext{
Bot: b,
Update: update,
}
for _, plugin := range b.plugins {
if plugin.UpdateListener != nil {
(*plugin.UpdateListener)(ctx)
}
}
for _, plugin := range b.plugins {
for payload := range plugin.Payloads {
if !strings.HasPrefix(update.CallbackQuery.Data, payload) {
continue
}
plugin.ExecutePayload(payload, ctx)
}
}
}
2024-12-16 00:52:43 +03:00
func (b *Bot) checkPrefixes(text string) (string, bool) {
for _, prefix := range b.prefixes {
if strings.HasPrefix(text, prefix) {
return prefix, true
}
}
return "", false
}
2024-12-17 09:23:53 +03:00
func (b *Bot) AddPlugins(plugin ...*Plugin) *Bot {
2024-12-16 00:52:43 +03:00
b.plugins = append(b.plugins, plugin...)
2024-12-17 09:23:53 +03:00
return b
2024-12-16 00:52:43 +03:00
}
2024-12-17 09:23:53 +03:00
func (b *Bot) Debug(debug bool) *Bot {
2024-12-16 00:52:43 +03:00
b.debug = debug
2024-12-17 09:23:53 +03:00
return b
2024-12-16 00:52:43 +03:00
}
func (ctx *MsgContext) Answer(text string) {
_, err := ctx.Bot.SendMessage(&SendMessageP{
ChatID: ctx.Msg.Chat.ID,
Text: text,
})
if err != nil {
ctx.Bot.logger.Error(err)
}
}
2024-12-17 09:23:53 +03:00
func (b *Bot) Logger() *Logger {
return b.logger
}
2024-12-16 00:52:43 +03:00
type ApiResponse struct {
Ok bool `json:"ok"`
Result map[string]interface{} `json:"result,omitempty"`
Description string `json:"description,omitempty"`
ErrorCode int `json:"error_code,omitempty"`
}
type ApiResponseA struct {
Ok bool `json:"ok"`
Result []interface{} `json:"result,omitempty"`
Description string `json:"description,omitempty"`
ErrorCode int `json:"error_code,omitempty"`
}
// request is a low-level call to api.
func (b *Bot) request(methodName string, params map[string]interface{}) (map[string]interface{}, error) {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(params)
if err != nil {
return nil, err
}
if b.debug {
2024-12-17 09:23:53 +03:00
b.logger.Debug(fmt.Sprintf(
"POST https://api.telegram.org/bot%s/%s %s",
"<TOKEN>",
methodName,
string(buf.Bytes()),
))
2024-12-16 00:52:43 +03:00
}
r, err := http.Post(fmt.Sprintf("https://api.telegram.org/bot%s/%s", b.token, methodName), "application/json", &buf)
if err != nil {
return nil, err
}
data, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
response := new(ApiResponse)
var result map[string]interface{}
err = json.Unmarshal(data, &response)
if err != nil {
responseArray := new(ApiResponseA)
err = json.Unmarshal(data, responseArray)
if err != nil {
return nil, err
}
result = map[string]interface{}{
"data": responseArray.Result,
}
} else {
result = response.Result
}
if !response.Ok {
return nil, fmt.Errorf("[%d] %s", response.ErrorCode, response.Description)
}
return result, err
}