Compare commits
16 Commits
7f248fff62
...
v0.2.3
| Author | SHA1 | Date | |
|---|---|---|---|
| d1c75ac0a6 | |||
| 75be66d5a9 | |||
| ee51d29c30 | |||
| 8f8182039d | |||
| 05dadc3de3 | |||
| 37397ba90f | |||
| c503b68814 | |||
| 49ec217d33 | |||
| 7a3e40a74d | |||
| ce13b19676 | |||
| 684d56acba | |||
| 21623788c6 | |||
| b88715d6d3 | |||
| 0cc146edd9 | |||
| 3d1263b3e0 | |||
| c6b47d18f6 |
355
bot.go
355
bot.go
@@ -1,355 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ParseMode string
|
|
||||||
|
|
||||||
const (
|
|
||||||
ParseMDV2 ParseMode = "MarkdownV2"
|
|
||||||
ParseHTML ParseMode = "HTML"
|
|
||||||
ParseMD ParseMode = "Markdown"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Bot struct {
|
|
||||||
token string
|
|
||||||
debug bool
|
|
||||||
errorTemplate string
|
|
||||||
|
|
||||||
logger *Logger
|
|
||||||
requestLogger *Logger
|
|
||||||
|
|
||||||
plugins []*Plugin
|
|
||||||
prefixes []string
|
|
||||||
|
|
||||||
updateOffset int
|
|
||||||
updateTypes []string
|
|
||||||
updateQueue *Queue[*Update]
|
|
||||||
}
|
|
||||||
|
|
||||||
type BotSettings struct {
|
|
||||||
Token string
|
|
||||||
Debug bool
|
|
||||||
ErrorTemplate string
|
|
||||||
Prefixes []string
|
|
||||||
UpdateTypes []string
|
|
||||||
LoggerBasePath string
|
|
||||||
UseRequestLogger bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func LoadSettingsFromEnv() *BotSettings {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
type MsgContext struct {
|
|
||||||
Bot *Bot
|
|
||||||
Msg *Message
|
|
||||||
Update *Update
|
|
||||||
FromID int
|
|
||||||
Prefix string
|
|
||||||
Text string
|
|
||||||
Args []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBot(settings *BotSettings) *Bot {
|
|
||||||
updateQueue := CreateQueue[*Update](256)
|
|
||||||
bot := &Bot{
|
|
||||||
updateOffset: 0, plugins: make([]*Plugin, 0), debug: settings.Debug, errorTemplate: "%s",
|
|
||||||
prefixes: settings.Prefixes, updateTypes: make([]string, 0),
|
|
||||||
updateQueue: updateQueue,
|
|
||||||
token: settings.Token,
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(settings.ErrorTemplate) > 0 {
|
|
||||||
bot.errorTemplate = settings.ErrorTemplate
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(settings.LoggerBasePath) == 0 {
|
|
||||||
settings.LoggerBasePath = "./"
|
|
||||||
}
|
|
||||||
level := FATAL
|
|
||||||
if settings.Debug {
|
|
||||||
level = DEBUG
|
|
||||||
}
|
|
||||||
bot.logger = CreateLogger().Level(level).OpenFile(fmt.Sprintf("%s/main.log", strings.TrimRight(settings.LoggerBasePath, "/")))
|
|
||||||
if settings.UseRequestLogger {
|
|
||||||
bot.requestLogger = CreateLogger().Level(level).Prefix("REQUESTS").OpenFile(fmt.Sprintf("%s/requests.log", strings.TrimRight(settings.LoggerBasePath, "/")))
|
|
||||||
}
|
|
||||||
|
|
||||||
return bot
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) Close() {
|
|
||||||
err := b.logger.f.Close()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println(err)
|
|
||||||
} else {
|
|
||||||
fmt.Println("log closed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
b.prefixes = append(b.prefixes, prefixes...)
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func LoadPrefixesFromEnv() []string {
|
|
||||||
prefixesS, exists := os.LookupEnv("PREFIXES")
|
|
||||||
if !exists {
|
|
||||||
return []string{"!"}
|
|
||||||
}
|
|
||||||
return strings.Split(prefixesS, ";")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) ErrorTemplate(s string) *Bot {
|
|
||||||
b.errorTemplate = s
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) Debug(debug bool) *Bot {
|
|
||||||
b.debug = debug
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) AddPlugins(plugin ...*Plugin) *Bot {
|
|
||||||
b.plugins = append(b.plugins, plugin...)
|
|
||||||
for _, p := range plugin {
|
|
||||||
b.logger.Debug(fmt.Sprintf("plugins with name \"%s\" was registered", p.Name))
|
|
||||||
}
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
b.logger.Info("Bot running. Press CTRL+C to exit.")
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
_, err := b.Updates()
|
|
||||||
if err != nil {
|
|
||||||
b.logger.Error(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
for {
|
|
||||||
queue := b.updateQueue
|
|
||||||
if queue.IsEmpty() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
u := queue.Dequeue()
|
|
||||||
if u.CallbackQuery != nil {
|
|
||||||
b.handleCallback(u)
|
|
||||||
} else {
|
|
||||||
b.handleMessage(u)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// {"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}
|
|
||||||
|
|
||||||
func (b *Bot) handleMessage(update *Update) {
|
|
||||||
ctx := &MsgContext{
|
|
||||||
Bot: b,
|
|
||||||
Update: update,
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, plugin := range b.plugins {
|
|
||||||
if plugin.UpdateListener != nil {
|
|
||||||
(*plugin.UpdateListener)(ctx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var text string
|
|
||||||
if update.Message == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(update.Message.Text) > 0 {
|
|
||||||
text = update.Message.Text
|
|
||||||
} else {
|
|
||||||
text = update.Message.Caption
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.FromID = update.Message.From.ID
|
|
||||||
ctx.Msg = update.Message
|
|
||||||
text = strings.TrimSpace(text)
|
|
||||||
prefix, hasPrefix := b.checkPrefixes(text)
|
|
||||||
if !hasPrefix {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.Prefix = prefix
|
|
||||||
|
|
||||||
text = strings.TrimSpace(text[len(prefix):])
|
|
||||||
|
|
||||||
for _, plugin := range b.plugins {
|
|
||||||
|
|
||||||
// Check every command
|
|
||||||
for cmd := range plugin.Commands {
|
|
||||||
if !strings.HasPrefix(text, cmd) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.Text = strings.TrimSpace(text[len(cmd):])
|
|
||||||
ctx.Args = strings.Split(ctx.Text, " ")
|
|
||||||
|
|
||||||
go plugin.Execute(cmd, ctx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
go plugin.ExecutePayload(payload, ctx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) checkPrefixes(text string) (string, bool) {
|
|
||||||
for _, prefix := range b.prefixes {
|
|
||||||
if strings.HasPrefix(text, prefix) {
|
|
||||||
return prefix, true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ctx *MsgContext) Answer(text string) {
|
|
||||||
_, err := ctx.Bot.SendMessage(&SendMessageP{
|
|
||||||
ChatID: ctx.Msg.Chat.ID,
|
|
||||||
Text: text,
|
|
||||||
ParseMode: "markdown",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
ctx.Bot.logger.Error(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ctx *MsgContext) AnswerPhoto(photoId string, text string) {
|
|
||||||
_, err := ctx.Bot.SendPhoto(&SendPhotoP{
|
|
||||||
ChatID: ctx.Msg.Chat.ID,
|
|
||||||
Caption: text,
|
|
||||||
Photo: photoId,
|
|
||||||
ParseMode: ParseMD,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
ctx.Bot.logger.Error(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ctx *MsgContext) Error(err error) {
|
|
||||||
_, sendErr := ctx.Bot.SendMessage(&SendMessageP{
|
|
||||||
ChatID: ctx.Msg.Chat.ID,
|
|
||||||
Text: fmt.Sprintf(ctx.Bot.errorTemplate, err.Error()),
|
|
||||||
})
|
|
||||||
|
|
||||||
if sendErr != nil {
|
|
||||||
ctx.Bot.logger.Error(sendErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) Logger() *Logger {
|
|
||||||
return b.logger
|
|
||||||
}
|
|
||||||
|
|
||||||
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 && b.requestLogger != nil {
|
|
||||||
b.requestLogger.Debug(strings.ReplaceAll(fmt.Sprintf(
|
|
||||||
"POST https://api.telegram.org/bot%s/%s %s",
|
|
||||||
"<TOKEN>",
|
|
||||||
methodName,
|
|
||||||
buf.String(),
|
|
||||||
), "\n", ""))
|
|
||||||
}
|
|
||||||
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
|
|
||||||
}
|
|
||||||
28
go.mod
Normal file
28
go.mod
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
module git.nix13.pw/scuroneko/laniakea
|
||||||
|
|
||||||
|
go 1.25.6
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/fatih/color v1.18.0
|
||||||
|
github.com/redis/go-redis/v9 v9.17.3
|
||||||
|
github.com/vinovest/sqlx v1.7.1
|
||||||
|
go.mongodb.org/mongo-driver/v2 v2.4.2
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
|
github.com/golang/snappy v1.0.0 // indirect
|
||||||
|
github.com/klauspost/compress v1.16.7 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/muir/sqltoken v0.1.0 // indirect
|
||||||
|
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||||
|
github.com/xdg-go/scram v1.1.2 // indirect
|
||||||
|
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||||
|
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||||
|
golang.org/x/crypto v0.33.0 // indirect
|
||||||
|
golang.org/x/sync v0.11.0 // indirect
|
||||||
|
golang.org/x/sys v0.30.0 // indirect
|
||||||
|
golang.org/x/text v0.22.0 // indirect
|
||||||
|
)
|
||||||
87
go.sum
Normal file
87
go.sum
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||||
|
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||||
|
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||||
|
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||||
|
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||||
|
github.com/go-sql-driver/mysql v1.9.0 h1:Y0zIbQXhQKmQgTp44Y1dp3wTXcn804QoTptLZT1vtvo=
|
||||||
|
github.com/go-sql-driver/mysql v1.9.0/go.mod h1:pDetrLJeA3oMujJuvXc8RJoasr589B6A9fwzD3QMrqw=
|
||||||
|
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
|
||||||
|
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||||
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
|
github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I=
|
||||||
|
github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||||
|
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||||
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||||
|
github.com/muir/sqltoken v0.1.0 h1:edosEGsOClOZNfgGQNQSgxR9O6LiVefm2rDRqp2InuI=
|
||||||
|
github.com/muir/sqltoken v0.1.0/go.mod h1:lgOIORnKekMsuc/ZwdPOfwz/PtWLPCke43cEbT3uDuY=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4=
|
||||||
|
github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||||
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
|
github.com/vinovest/sqlx v1.7.1 h1:kdq4v0N9kRLpytWGSWOw4aulOGdQPmIoMR6Y+cTBxow=
|
||||||
|
github.com/vinovest/sqlx v1.7.1/go.mod h1:3fAv74r4iDMv2PpFomADb+vex5ukzfYn4GseC9KngD8=
|
||||||
|
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||||
|
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||||
|
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
|
||||||
|
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
|
||||||
|
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||||
|
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||||
|
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
|
||||||
|
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
|
||||||
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
|
go.mongodb.org/mongo-driver/v2 v2.4.2 h1:HrJ+Auygxceby9MLp3YITobef5a8Bv4HcPFIkml1U7U=
|
||||||
|
go.mongodb.org/mongo-driver/v2 v2.4.2/go.mod h1:jHeEDJHJq7tm6ZF45Issun9dbogjfnPySb1vXA7EeAI=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
|
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
||||||
|
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||||
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
|
||||||
|
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||||
|
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||||
|
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||||
|
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
type InlineKeyboard struct {
|
|
||||||
}
|
|
||||||
560
laniakea/bot.go
Normal file
560
laniakea/bot.go
Normal file
@@ -0,0 +1,560 @@
|
|||||||
|
package laniakea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"github.com/vinovest/sqlx"
|
||||||
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ParseMode string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ParseMDV2 ParseMode = "MarkdownV2"
|
||||||
|
ParseHTML ParseMode = "HTML"
|
||||||
|
ParseMD ParseMode = "Markdown"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Bot struct {
|
||||||
|
token string
|
||||||
|
debug bool
|
||||||
|
errorTemplate string
|
||||||
|
|
||||||
|
logger *Logger
|
||||||
|
requestLogger *Logger
|
||||||
|
|
||||||
|
plugins []*Plugin
|
||||||
|
middlewares []*Middleware
|
||||||
|
prefixes []string
|
||||||
|
|
||||||
|
dbContext *DatabaseContext
|
||||||
|
|
||||||
|
updateOffset int
|
||||||
|
updateTypes []string
|
||||||
|
updateQueue *Queue[*Update]
|
||||||
|
}
|
||||||
|
|
||||||
|
type BotSettings struct {
|
||||||
|
Token string
|
||||||
|
Debug bool
|
||||||
|
ErrorTemplate string
|
||||||
|
Prefixes []string
|
||||||
|
UpdateTypes []string
|
||||||
|
LoggerBasePath string
|
||||||
|
UseRequestLogger bool
|
||||||
|
WriteToFile bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadSettingsFromEnv() *BotSettings {
|
||||||
|
return &BotSettings{
|
||||||
|
Token: os.Getenv("TG_TOKEN"),
|
||||||
|
Debug: os.Getenv("DEBUG") == "true",
|
||||||
|
ErrorTemplate: os.Getenv("ERROR_TEMPLATE"),
|
||||||
|
Prefixes: LoadPrefixesFromEnv(),
|
||||||
|
UpdateTypes: strings.Split(os.Getenv("UPDATE_TYPES"), ";"),
|
||||||
|
UseRequestLogger: os.Getenv("USE_REQ_LOG") == "true",
|
||||||
|
WriteToFile: os.Getenv("WRITE_TO_FILE") == "true",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type MsgContext struct {
|
||||||
|
Bot *Bot
|
||||||
|
Msg *Message
|
||||||
|
Update *Update
|
||||||
|
From *User
|
||||||
|
CallbackMsgId int
|
||||||
|
FromID int
|
||||||
|
Prefix string
|
||||||
|
Text string
|
||||||
|
Args []string
|
||||||
|
}
|
||||||
|
|
||||||
|
type DatabaseContext struct {
|
||||||
|
PostgresSQL *sqlx.DB
|
||||||
|
MongoDB *mongo.Client
|
||||||
|
Redis *redis.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBot(settings *BotSettings) *Bot {
|
||||||
|
updateQueue := CreateQueue[*Update](256)
|
||||||
|
bot := &Bot{
|
||||||
|
updateOffset: 0, plugins: make([]*Plugin, 0), debug: settings.Debug, errorTemplate: "%s",
|
||||||
|
prefixes: settings.Prefixes, updateTypes: make([]string, 0),
|
||||||
|
updateQueue: updateQueue,
|
||||||
|
token: settings.Token,
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(settings.ErrorTemplate) > 0 {
|
||||||
|
bot.errorTemplate = settings.ErrorTemplate
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(settings.LoggerBasePath) == 0 {
|
||||||
|
settings.LoggerBasePath = "./"
|
||||||
|
}
|
||||||
|
level := FATAL
|
||||||
|
if settings.Debug {
|
||||||
|
level = DEBUG
|
||||||
|
}
|
||||||
|
|
||||||
|
bot.logger = CreateLogger().Level(level)
|
||||||
|
bot.logger.AddWriter(bot.logger.CreateJsonStdoutWriter())
|
||||||
|
if settings.WriteToFile {
|
||||||
|
path := fmt.Sprintf("%s/main.log", strings.TrimRight(settings.LoggerBasePath, "/"))
|
||||||
|
fileWriter, err := bot.logger.CreateTextFileWriter(path)
|
||||||
|
if err != nil {
|
||||||
|
bot.logger.Fatal(err)
|
||||||
|
}
|
||||||
|
bot.logger.AddWriter(fileWriter)
|
||||||
|
}
|
||||||
|
|
||||||
|
if settings.UseRequestLogger {
|
||||||
|
bot.requestLogger = CreateLogger().Level(level).Prefix("REQUESTS")
|
||||||
|
bot.requestLogger.AddWriter(bot.requestLogger.CreateJsonStdoutWriter())
|
||||||
|
if settings.WriteToFile {
|
||||||
|
path := fmt.Sprintf("%s/requests.log", strings.TrimRight(settings.LoggerBasePath, "/"))
|
||||||
|
fileWriter, err := bot.requestLogger.CreateTextFileWriter(path)
|
||||||
|
if err != nil {
|
||||||
|
bot.logger.Fatal(err)
|
||||||
|
}
|
||||||
|
bot.requestLogger.AddWriter(fileWriter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bot
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) Close() {
|
||||||
|
for _, writer := range b.logger.writers {
|
||||||
|
err := writer.Close()
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) InitDatabaseContext(ctx *DatabaseContext) *Bot {
|
||||||
|
b.dbContext = ctx
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
func (b *Bot) AddDatabaseLogger(writer func(db *DatabaseContext) LoggerWriter) *Bot {
|
||||||
|
w := writer(b.dbContext)
|
||||||
|
b.logger.AddWriter(w)
|
||||||
|
if b.requestLogger != nil {
|
||||||
|
b.requestLogger.AddWriter(w)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
b.prefixes = append(b.prefixes, prefixes...)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadPrefixesFromEnv() []string {
|
||||||
|
prefixesS, exists := os.LookupEnv("PREFIXES")
|
||||||
|
if !exists {
|
||||||
|
return []string{"!"}
|
||||||
|
}
|
||||||
|
return strings.Split(prefixesS, ";")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) ErrorTemplate(s string) *Bot {
|
||||||
|
b.errorTemplate = s
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) Debug(debug bool) *Bot {
|
||||||
|
b.debug = debug
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) AddPlugins(plugin ...*Plugin) *Bot {
|
||||||
|
b.plugins = append(b.plugins, plugin...)
|
||||||
|
for _, p := range plugin {
|
||||||
|
b.logger.Debug(fmt.Sprintf("plugins with name \"%s\" registered", p.Name))
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) AddMiddleware(middleware ...*Middleware) *Bot {
|
||||||
|
sort.Slice(middleware, func(a, b int) bool {
|
||||||
|
first := middleware[a]
|
||||||
|
second := middleware[b]
|
||||||
|
if first.Order == second.Order {
|
||||||
|
return first.Name < second.Name
|
||||||
|
}
|
||||||
|
return middleware[a].Order < middleware[b].Order
|
||||||
|
})
|
||||||
|
|
||||||
|
b.middlewares = append(b.middlewares, middleware...)
|
||||||
|
for _, m := range middleware {
|
||||||
|
b.logger.Debug(fmt.Sprintf("middleware with name \"%s\" registered", m.Name))
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
b.logger.Info("Bot running. Press CTRL+C to exit.")
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
_, err := b.Updates()
|
||||||
|
if err != nil {
|
||||||
|
b.logger.Error(err)
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond * 10)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
for {
|
||||||
|
queue := b.updateQueue
|
||||||
|
if queue.IsEmpty() {
|
||||||
|
time.Sleep(time.Millisecond * 25)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
u := queue.Dequeue()
|
||||||
|
if u == nil {
|
||||||
|
b.logger.Error("update is nil")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ctx := &MsgContext{
|
||||||
|
Bot: b,
|
||||||
|
Update: u,
|
||||||
|
}
|
||||||
|
for _, middleware := range b.middlewares {
|
||||||
|
middleware.Execute(ctx, b.dbContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, plugin := range b.plugins {
|
||||||
|
if plugin.UpdateListener != nil {
|
||||||
|
(*plugin.UpdateListener)(ctx, b.dbContext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if u.CallbackQuery != nil {
|
||||||
|
b.handleCallback(u, ctx)
|
||||||
|
} else {
|
||||||
|
b.handleMessage(u, ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// {"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}
|
||||||
|
|
||||||
|
func (b *Bot) handleMessage(update *Update, ctx *MsgContext) {
|
||||||
|
var text string
|
||||||
|
if update.Message == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(update.Message.Text) > 0 {
|
||||||
|
text = update.Message.Text
|
||||||
|
} else {
|
||||||
|
text = update.Message.Caption
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.FromID = update.Message.From.ID
|
||||||
|
ctx.From = update.Message.From
|
||||||
|
ctx.Msg = update.Message
|
||||||
|
text = strings.TrimSpace(text)
|
||||||
|
prefix, hasPrefix := b.checkPrefixes(text)
|
||||||
|
if !hasPrefix {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx.Prefix = prefix
|
||||||
|
|
||||||
|
text = strings.TrimSpace(text[len(prefix):])
|
||||||
|
|
||||||
|
for _, plugin := range b.plugins {
|
||||||
|
// Check every command
|
||||||
|
for cmd := range plugin.Commands {
|
||||||
|
if !strings.HasPrefix(text, cmd) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.Text = strings.TrimSpace(text[len(cmd):])
|
||||||
|
ctx.Args = strings.Split(ctx.Text, " ")
|
||||||
|
|
||||||
|
go plugin.Execute(cmd, ctx, b.dbContext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) handleCallback(update *Update, ctx *MsgContext) {
|
||||||
|
data := new(CallbackData)
|
||||||
|
err := json.Unmarshal([]byte(update.CallbackQuery.Data), data)
|
||||||
|
if err != nil {
|
||||||
|
b.logger.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.FromID = update.CallbackQuery.From.ID
|
||||||
|
ctx.From = update.CallbackQuery.From
|
||||||
|
ctx.Msg = update.CallbackQuery.Message
|
||||||
|
ctx.CallbackMsgId = update.CallbackQuery.Message.MessageID
|
||||||
|
ctx.Args = data.Args
|
||||||
|
|
||||||
|
for _, plugin := range b.plugins {
|
||||||
|
_, ok := plugin.Payloads[data.Command]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
go plugin.ExecutePayload(data.Command, ctx, b.dbContext)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) checkPrefixes(text string) (string, bool) {
|
||||||
|
for _, prefix := range b.prefixes {
|
||||||
|
if strings.HasPrefix(text, prefix) {
|
||||||
|
return prefix, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
type AnswerMessage struct {
|
||||||
|
MessageID int
|
||||||
|
Text string
|
||||||
|
IsMedia bool
|
||||||
|
Keyboard *InlineKeyboard
|
||||||
|
ctx *MsgContext
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *MsgContext) edit(messageId int, text string, keyboard *InlineKeyboard) *AnswerMessage {
|
||||||
|
params := &EditMessageTextP{
|
||||||
|
MessageID: messageId,
|
||||||
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
|
Text: text,
|
||||||
|
ParseMode: ParseMD,
|
||||||
|
}
|
||||||
|
if keyboard != nil {
|
||||||
|
params.ReplyMarkup = keyboard.Get()
|
||||||
|
}
|
||||||
|
msg, err := ctx.Bot.EditMessageText(params)
|
||||||
|
if err != nil {
|
||||||
|
ctx.Bot.logger.Error(err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &AnswerMessage{
|
||||||
|
MessageID: msg.MessageID, ctx: ctx, Text: text, IsMedia: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (m *AnswerMessage) Edit(text string) *AnswerMessage {
|
||||||
|
return m.ctx.edit(m.MessageID, text, nil)
|
||||||
|
}
|
||||||
|
func (ctx *MsgContext) EditCallback(text string, keyboard *InlineKeyboard) *AnswerMessage {
|
||||||
|
if ctx.CallbackMsgId == 0 {
|
||||||
|
ctx.Bot.logger.Error("Can't edit non-callback update message")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return ctx.edit(ctx.CallbackMsgId, text, keyboard)
|
||||||
|
}
|
||||||
|
func (ctx *MsgContext) EditCallbackf(format string, keyboard *InlineKeyboard, args ...any) *AnswerMessage {
|
||||||
|
return ctx.EditCallback(fmt.Sprintf(format, args...), keyboard)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *MsgContext) editPhotoText(messageId int, text string, kb *InlineKeyboard) *AnswerMessage {
|
||||||
|
params := &EditMessageCaptionP{
|
||||||
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
|
MessageID: messageId,
|
||||||
|
Caption: text,
|
||||||
|
ParseMode: ParseMD,
|
||||||
|
}
|
||||||
|
if kb != nil {
|
||||||
|
params.ReplyMarkup = kb.Get()
|
||||||
|
}
|
||||||
|
msg, err := ctx.Bot.EditMessageCaption(params)
|
||||||
|
if err != nil {
|
||||||
|
ctx.Bot.logger.Error(err)
|
||||||
|
}
|
||||||
|
return &AnswerMessage{
|
||||||
|
MessageID: msg.MessageID, ctx: ctx, Text: text, IsMedia: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (m *AnswerMessage) EditCaption(text string) *AnswerMessage {
|
||||||
|
return m.ctx.editPhotoText(m.MessageID, text, nil)
|
||||||
|
}
|
||||||
|
func (m *AnswerMessage) EditCaptionKeyboard(text string, kb *InlineKeyboard) *AnswerMessage {
|
||||||
|
return m.ctx.editPhotoText(m.MessageID, text, kb)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *MsgContext) answer(text string, keyboard *InlineKeyboard) *AnswerMessage {
|
||||||
|
params := &SendMessageP{
|
||||||
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
|
Text: text,
|
||||||
|
ParseMode: ParseMD,
|
||||||
|
}
|
||||||
|
if keyboard != nil {
|
||||||
|
params.ReplyMarkup = keyboard.Get()
|
||||||
|
}
|
||||||
|
|
||||||
|
msg, err := ctx.Bot.SendMessage(params)
|
||||||
|
if err != nil {
|
||||||
|
ctx.Bot.logger.Error(err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &AnswerMessage{
|
||||||
|
MessageID: msg.MessageID, ctx: ctx, IsMedia: false, Text: text,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (ctx *MsgContext) Answer(text string) *AnswerMessage {
|
||||||
|
return ctx.answer(text, nil)
|
||||||
|
}
|
||||||
|
func (ctx *MsgContext) Answerf(template string, args ...any) *AnswerMessage {
|
||||||
|
return ctx.answer(fmt.Sprintf(template, args...), nil)
|
||||||
|
}
|
||||||
|
func (ctx *MsgContext) Keyboard(text string, kb *InlineKeyboard) *AnswerMessage {
|
||||||
|
return ctx.answer(text, kb)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *MsgContext) answerPhoto(photoId, text string, kb *InlineKeyboard) *AnswerMessage {
|
||||||
|
params := &SendPhotoP{
|
||||||
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
|
Caption: text,
|
||||||
|
Photo: photoId,
|
||||||
|
ParseMode: ParseMD,
|
||||||
|
}
|
||||||
|
if kb != nil {
|
||||||
|
params.ReplyMarkup = kb.Get()
|
||||||
|
}
|
||||||
|
msg, err := ctx.Bot.SendPhoto(params)
|
||||||
|
if err != nil {
|
||||||
|
ctx.Bot.logger.Error(err)
|
||||||
|
}
|
||||||
|
return &AnswerMessage{
|
||||||
|
MessageID: msg.MessageID, ctx: ctx, Text: text, IsMedia: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (ctx *MsgContext) AnswerPhoto(photoId, text string) *AnswerMessage {
|
||||||
|
return ctx.answerPhoto(photoId, text, nil)
|
||||||
|
}
|
||||||
|
func (ctx *MsgContext) AnswerPhotoKeyboard(photoId, text string, kb *InlineKeyboard) *AnswerMessage {
|
||||||
|
return ctx.answerPhoto(photoId, text, kb)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *MsgContext) delete(messageId int) {
|
||||||
|
_, err := ctx.Bot.DeleteMessage(&DeleteMessageP{
|
||||||
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
|
MessageID: messageId,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
ctx.Bot.logger.Error(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (m *AnswerMessage) Delete() {
|
||||||
|
m.ctx.delete(m.MessageID)
|
||||||
|
}
|
||||||
|
func (ctx *MsgContext) CallbackDelete() {
|
||||||
|
ctx.delete(ctx.CallbackMsgId)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *MsgContext) Error(err error) {
|
||||||
|
_, sendErr := ctx.Bot.SendMessage(&SendMessageP{
|
||||||
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
|
Text: fmt.Sprintf(ctx.Bot.errorTemplate, EscapeMarkdown(err.Error())),
|
||||||
|
})
|
||||||
|
ctx.Bot.logger.Error(err)
|
||||||
|
|
||||||
|
if sendErr != nil {
|
||||||
|
ctx.Bot.logger.Error(sendErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) Logger() *Logger {
|
||||||
|
return b.logger
|
||||||
|
}
|
||||||
|
|
||||||
|
type ApiResponse struct {
|
||||||
|
Ok bool `json:"ok"`
|
||||||
|
Result map[string]any `json:"result,omitempty"`
|
||||||
|
Description string `json:"description,omitempty"`
|
||||||
|
ErrorCode int `json:"error_code,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ApiResponseA struct {
|
||||||
|
Ok bool `json:"ok"`
|
||||||
|
Result []any `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 any) (map[string]interface{}, error) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err := json.NewEncoder(&buf).Encode(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.debug && b.requestLogger != nil {
|
||||||
|
b.requestLogger.Debug(strings.ReplaceAll(fmt.Sprintf(
|
||||||
|
"POST https://api.telegram.org/bot%s/%s %s",
|
||||||
|
"<TOKEN>",
|
||||||
|
methodName,
|
||||||
|
buf.String(),
|
||||||
|
), "\n", ""))
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
data, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
b.requestLogger.Debug(fmt.Sprintf("RES %s %s", methodName, string(data)))
|
||||||
|
response := new(ApiResponse)
|
||||||
|
|
||||||
|
var result map[string]any
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
74
laniakea/keyboard.go
Normal file
74
laniakea/keyboard.go
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
package laniakea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type InlineKeyboard struct {
|
||||||
|
CurrentLine []InlineKeyboardButton
|
||||||
|
Lines [][]InlineKeyboardButton
|
||||||
|
maxRow int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInlineKeyboard(maxRow int) *InlineKeyboard {
|
||||||
|
return &InlineKeyboard{
|
||||||
|
CurrentLine: make([]InlineKeyboardButton, 0),
|
||||||
|
Lines: make([][]InlineKeyboardButton, 0),
|
||||||
|
maxRow: maxRow,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in *InlineKeyboard) append(button InlineKeyboardButton) *InlineKeyboard {
|
||||||
|
if len(in.CurrentLine) == in.maxRow {
|
||||||
|
in.AddLine()
|
||||||
|
}
|
||||||
|
in.CurrentLine = append(in.CurrentLine, button)
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
func (in *InlineKeyboard) AddUrlButton(text, url string) *InlineKeyboard {
|
||||||
|
return in.append(InlineKeyboardButton{Text: text, URL: url})
|
||||||
|
}
|
||||||
|
func (in *InlineKeyboard) AddCallbackButton(text string, cmd string, args ...any) *InlineKeyboard {
|
||||||
|
return in.append(InlineKeyboardButton{Text: text, CallbackData: NewCallbackData(cmd, args...).ToJson()})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in *InlineKeyboard) AddLine() *InlineKeyboard {
|
||||||
|
if len(in.CurrentLine) == 0 {
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
in.Lines = append(in.Lines, in.CurrentLine)
|
||||||
|
in.CurrentLine = make([]InlineKeyboardButton, 0)
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
func (in *InlineKeyboard) Get() InlineKeyboardMarkup {
|
||||||
|
if len(in.CurrentLine) > 0 {
|
||||||
|
in.Lines = append(in.Lines, in.CurrentLine)
|
||||||
|
}
|
||||||
|
return InlineKeyboardMarkup{
|
||||||
|
InlineKeyboard: in.Lines,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type CallbackData struct {
|
||||||
|
Command string `json:"cmd"`
|
||||||
|
Args []string `json:"args"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCallbackData(command string, args ...any) *CallbackData {
|
||||||
|
stringArgs := make([]string, len(args))
|
||||||
|
for i, arg := range args {
|
||||||
|
stringArgs[i] = fmt.Sprint(arg)
|
||||||
|
}
|
||||||
|
return &CallbackData{
|
||||||
|
Command: command,
|
||||||
|
Args: stringArgs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (d *CallbackData) ToJson() string {
|
||||||
|
data, err := json.Marshal(d)
|
||||||
|
if err != nil {
|
||||||
|
return `{"cmd":""}`
|
||||||
|
}
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
372
laniakea/logger.go
Normal file
372
laniakea/logger.go
Normal file
@@ -0,0 +1,372 @@
|
|||||||
|
package laniakea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/fatih/color"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LoggerWriter interface {
|
||||||
|
Close() error
|
||||||
|
Write(p []byte) (n int, err error)
|
||||||
|
Print(level LogLevel, prefix string, traceback []*MethodTraceback, messages ...any) error
|
||||||
|
}
|
||||||
|
type LoggerTextWriter struct {
|
||||||
|
LoggerWriter
|
||||||
|
writer io.Writer
|
||||||
|
printTraceback bool
|
||||||
|
printTime bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *LoggerTextWriter) Write(p []byte) (n int, err error) {
|
||||||
|
n, err = w.writer.Write(p)
|
||||||
|
if err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
err = bufio.NewWriter(w.writer).Flush()
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
func (w *LoggerTextWriter) Print(level LogLevel, prefix string, tb []*MethodTraceback, messages ...any) error {
|
||||||
|
s := buildString(level, prefix, true, w.printTraceback, w.printTime, messages...)
|
||||||
|
_, err := w.Write([]byte(s))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func (w *LoggerTextWriter) Close() error {
|
||||||
|
return w.writer.(io.Closer).Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoggerJsonWriter struct {
|
||||||
|
LoggerWriter
|
||||||
|
writer io.Writer
|
||||||
|
pretty bool
|
||||||
|
}
|
||||||
|
type LoggerJsonMessage struct {
|
||||||
|
Time time.Time `json:"time"`
|
||||||
|
Level string `json:"level"`
|
||||||
|
Prefix string `json:"prefix"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Traceback []*MethodTraceback `json:"traceback"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *LoggerJsonWriter) Write(data []byte) (int, error) {
|
||||||
|
n, err := w.writer.Write(data)
|
||||||
|
if err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
err = bufio.NewWriter(w.writer).Flush()
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
func (w *LoggerJsonWriter) Print(level LogLevel, prefix string, traceback []*MethodTraceback, messages ...any) error {
|
||||||
|
msg := Map(messages, func(el any) string {
|
||||||
|
return fmt.Sprintf("%v", el)
|
||||||
|
})
|
||||||
|
m := LoggerJsonMessage{
|
||||||
|
Time: time.Now(),
|
||||||
|
Level: level.GetName(),
|
||||||
|
Prefix: prefix,
|
||||||
|
Message: strings.Join(msg, " "),
|
||||||
|
Traceback: traceback,
|
||||||
|
}
|
||||||
|
var data []byte
|
||||||
|
var err error
|
||||||
|
if w.pretty {
|
||||||
|
data, err = json.MarshalIndent(m, "", " ")
|
||||||
|
} else {
|
||||||
|
data, err = json.Marshal(m)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = w.Write(append(data, []byte("\n")...))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func (w *LoggerJsonWriter) Close() error {
|
||||||
|
return w.writer.(io.Closer).Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
type Logger struct {
|
||||||
|
prefix string
|
||||||
|
level LogLevel
|
||||||
|
printTraceback bool
|
||||||
|
printTime bool
|
||||||
|
jsonPretty bool
|
||||||
|
writers []LoggerWriter
|
||||||
|
}
|
||||||
|
|
||||||
|
type LogLevel struct {
|
||||||
|
n uint8
|
||||||
|
t string
|
||||||
|
c color.Attribute
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *LogLevel) GetName() string {
|
||||||
|
return l.t
|
||||||
|
}
|
||||||
|
|
||||||
|
type MethodTraceback struct {
|
||||||
|
Package string `json:"package"`
|
||||||
|
Method string `json:"method"`
|
||||||
|
fullPath string
|
||||||
|
signature string
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
Line int `json:"line"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
INFO = LogLevel{n: 0, t: "info", c: color.FgWhite}
|
||||||
|
WARN = LogLevel{n: 1, t: "warn", c: color.FgHiYellow}
|
||||||
|
ERROR = LogLevel{n: 2, t: "error", c: color.FgHiRed}
|
||||||
|
FATAL = LogLevel{n: 3, t: "fatal", c: color.FgRed}
|
||||||
|
DEBUG = LogLevel{n: 4, t: "debug", c: color.FgGreen}
|
||||||
|
)
|
||||||
|
|
||||||
|
func CreateLogger() *Logger {
|
||||||
|
return &Logger{
|
||||||
|
prefix: "LOG",
|
||||||
|
level: FATAL,
|
||||||
|
printTraceback: false,
|
||||||
|
printTime: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) CreateTextFileWriter(path string) (*LoggerTextWriter, error) {
|
||||||
|
err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
writer := &LoggerTextWriter{
|
||||||
|
writer: file, printTraceback: l.printTraceback, printTime: l.printTime,
|
||||||
|
}
|
||||||
|
return writer, nil
|
||||||
|
}
|
||||||
|
func (l *Logger) CreateTextStdoutWriter() *LoggerTextWriter {
|
||||||
|
writer := &LoggerTextWriter{
|
||||||
|
writer: os.Stdout, printTraceback: l.printTraceback, printTime: l.printTime,
|
||||||
|
}
|
||||||
|
return writer
|
||||||
|
}
|
||||||
|
func (l *Logger) CreateJsonStdoutWriter() *LoggerJsonWriter {
|
||||||
|
writer := &LoggerJsonWriter{
|
||||||
|
writer: os.Stdout, pretty: l.jsonPretty,
|
||||||
|
}
|
||||||
|
return writer
|
||||||
|
}
|
||||||
|
func (l *Logger) CreateJsonFileWriter(path string) (*LoggerJsonWriter, error) {
|
||||||
|
err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
writer := &LoggerJsonWriter{
|
||||||
|
writer: file, pretty: l.jsonPretty,
|
||||||
|
}
|
||||||
|
return writer, nil
|
||||||
|
}
|
||||||
|
func (l *Logger) CreateTextWriter(w io.Writer) *LoggerTextWriter {
|
||||||
|
writer := &LoggerTextWriter{
|
||||||
|
writer: w, printTraceback: l.printTraceback, printTime: l.printTime,
|
||||||
|
}
|
||||||
|
return writer
|
||||||
|
}
|
||||||
|
func (l *Logger) CreateJsonWriter(w io.Writer) *LoggerJsonWriter {
|
||||||
|
writer := &LoggerJsonWriter{
|
||||||
|
writer: w, pretty: l.jsonPretty,
|
||||||
|
}
|
||||||
|
return writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) Prefix(prefix string) *Logger {
|
||||||
|
l.prefix = prefix
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
func (l *Logger) Level(level LogLevel) *Logger {
|
||||||
|
l.level = level
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
func (l *Logger) PrintTraceback(b bool) *Logger {
|
||||||
|
l.printTraceback = b
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
func (l *Logger) PrintTime(b bool) *Logger {
|
||||||
|
l.printTime = b
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
func (l *Logger) JsonPretty(b bool) *Logger {
|
||||||
|
l.jsonPretty = b
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
func (l *Logger) AddWriters(writers ...LoggerWriter) *Logger {
|
||||||
|
l.writers = append(l.writers, writers...)
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
func (l *Logger) AddWriter(writer LoggerWriter) *Logger {
|
||||||
|
l.writers = append(l.writers, writer)
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) Infof(format string, args ...any) {
|
||||||
|
l.print(INFO, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
func (l *Logger) Info(m ...any) {
|
||||||
|
l.println(INFO, m...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) Warnf(format string, args ...any) {
|
||||||
|
l.print(WARN, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
func (l *Logger) Warn(m ...any) {
|
||||||
|
l.println(WARN, m...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) Error(m ...any) {
|
||||||
|
l.println(ERROR, m...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) Fatal(m ...any) {
|
||||||
|
l.println(FATAL, m...)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) Debug(m ...any) {
|
||||||
|
l.println(DEBUG, m...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatTime(t time.Time) string {
|
||||||
|
return fmt.Sprintf("%02d.%02d.%02d %02d:%02d:%02d", t.Day(), t.Month(), t.Year(), t.Hour(), t.Minute(), t.Second())
|
||||||
|
}
|
||||||
|
func formatTraceback(mt *MethodTraceback) string {
|
||||||
|
return fmt.Sprintf("%s:%s:%d", mt.Filename, mt.Method, mt.Line)
|
||||||
|
}
|
||||||
|
func FormatFullTraceback(tracebacks []*MethodTraceback) string {
|
||||||
|
formatted := make([]string, 0)
|
||||||
|
for _, tb := range tracebacks {
|
||||||
|
formatted = append(formatted, formatTraceback(tb))
|
||||||
|
}
|
||||||
|
return strings.Join(formatted, "->")
|
||||||
|
}
|
||||||
|
|
||||||
|
func getTraceback() *MethodTraceback {
|
||||||
|
caller, _, _, _ := runtime.Caller(4)
|
||||||
|
details := runtime.FuncForPC(caller)
|
||||||
|
signature := details.Name()
|
||||||
|
path, line := details.FileLine(caller)
|
||||||
|
splitPath := strings.Split(path, "/")
|
||||||
|
|
||||||
|
splitSignature := strings.Split(signature, ".")
|
||||||
|
pkg, method := splitSignature[0], splitSignature[len(splitSignature)-1]
|
||||||
|
|
||||||
|
tb := &MethodTraceback{
|
||||||
|
Filename: splitPath[len(splitPath)-1],
|
||||||
|
fullPath: path,
|
||||||
|
Line: line,
|
||||||
|
signature: signature,
|
||||||
|
Package: pkg,
|
||||||
|
Method: method,
|
||||||
|
}
|
||||||
|
|
||||||
|
return tb
|
||||||
|
}
|
||||||
|
func getFullTraceback(skip int) []*MethodTraceback {
|
||||||
|
pc := make([]uintptr, 15)
|
||||||
|
runtime.Callers(skip, pc)
|
||||||
|
list := make([]*MethodTraceback, 0)
|
||||||
|
frames := runtime.CallersFrames(pc)
|
||||||
|
for {
|
||||||
|
frame, more := frames.Next()
|
||||||
|
if !more {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
details := runtime.FuncForPC(frame.PC)
|
||||||
|
signature := details.Name()
|
||||||
|
path, line := details.FileLine(frame.PC)
|
||||||
|
splitPath := strings.Split(path, "/")
|
||||||
|
|
||||||
|
splitSignature := strings.Split(signature, ".")
|
||||||
|
pkg, method := splitSignature[0], splitSignature[len(splitSignature)-1]
|
||||||
|
|
||||||
|
tb := &MethodTraceback{
|
||||||
|
Filename: splitPath[len(splitPath)-1],
|
||||||
|
fullPath: path,
|
||||||
|
Line: line,
|
||||||
|
signature: signature,
|
||||||
|
Package: pkg,
|
||||||
|
Method: method,
|
||||||
|
}
|
||||||
|
list = append(list, tb)
|
||||||
|
}
|
||||||
|
sort.Slice(list, func(i, j int) bool {
|
||||||
|
return j < i
|
||||||
|
})
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildString(level LogLevel, prefix string, newline, printTime, printTraceback bool, m ...any) string {
|
||||||
|
args := []string{
|
||||||
|
fmt.Sprintf("[%s]", prefix),
|
||||||
|
fmt.Sprintf("[%s]", strings.ToUpper(level.t)),
|
||||||
|
}
|
||||||
|
|
||||||
|
if printTraceback {
|
||||||
|
args = append(args, fmt.Sprintf("[%s]", formatTraceback(getTraceback())))
|
||||||
|
}
|
||||||
|
|
||||||
|
if printTime {
|
||||||
|
args = append(args, fmt.Sprintf("[%s]", formatTime(time.Now())))
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := Map(m, func(el any) string {
|
||||||
|
return fmt.Sprintf("%v", el)
|
||||||
|
})
|
||||||
|
s := fmt.Sprintf("%s %s", strings.Join(args, " "), strings.Join(msg, " "))
|
||||||
|
if newline {
|
||||||
|
s += "\n"
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) print(level LogLevel, m ...any) {
|
||||||
|
if l.level.n < level.n {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tb := getFullTraceback(0)
|
||||||
|
for _, writer := range l.writers {
|
||||||
|
err := writer.Print(level, l.prefix, tb, m...)
|
||||||
|
if err != nil {
|
||||||
|
l.Error(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Docker requires "\n" at end to write to log.
|
||||||
|
// print not work for docker, otherwise it will work and write into stdout
|
||||||
|
func (l *Logger) println(level LogLevel, m ...any) {
|
||||||
|
if l.level.n < level.n {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tb := getFullTraceback(0)
|
||||||
|
for _, writer := range l.writers {
|
||||||
|
err := writer.Print(level, l.prefix, tb, m...)
|
||||||
|
if err != nil {
|
||||||
|
l.Error(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
169
laniakea/methods.go
Normal file
169
laniakea/methods.go
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
package laniakea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
var NoParams = make(map[string]any)
|
||||||
|
|
||||||
|
func (b *Bot) Updates() ([]*Update, error) {
|
||||||
|
params := make(map[string]any)
|
||||||
|
params["offset"] = b.updateOffset
|
||||||
|
params["timeout"] = 30
|
||||||
|
params["allowed_updates"] = b.updateTypes
|
||||||
|
|
||||||
|
data, err := b.request("getUpdates", params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := make([]*Update, 0)
|
||||||
|
for _, u := range data["data"].([]any) {
|
||||||
|
updateObj := new(Update)
|
||||||
|
data, err := json.Marshal(u)
|
||||||
|
if err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(data, updateObj)
|
||||||
|
if err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
//err = MapToStruct(u.(map[string]any), updateObj)
|
||||||
|
//if err != nil {
|
||||||
|
// return res, err
|
||||||
|
//}
|
||||||
|
b.updateOffset = updateObj.UpdateID + 1
|
||||||
|
err = b.updateQueue.Enqueue(updateObj)
|
||||||
|
if err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
res = append(res, updateObj)
|
||||||
|
|
||||||
|
if b.debug && b.requestLogger != nil {
|
||||||
|
j, err := MapToJson(u.(map[string]interface{}))
|
||||||
|
if err != nil {
|
||||||
|
b.logger.Error(err)
|
||||||
|
}
|
||||||
|
b.requestLogger.Debug(fmt.Sprintf("UPDATE %s", j))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) GetMe() (*User, error) {
|
||||||
|
data, err := b.request("getMe", NoParams)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
user := new(User)
|
||||||
|
err = MapToStruct(data, user)
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type SendMessageP struct {
|
||||||
|
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||||
|
ChatID int `json:"chat_id"`
|
||||||
|
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||||
|
ParseMode ParseMode `json:"parse_mode,omitempty"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Entities []*MessageEntity `json:"entities,omitempty"`
|
||||||
|
LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"`
|
||||||
|
DisableNotifications bool `json:"disable_notifications,omitempty"`
|
||||||
|
ProtectContent bool `json:"protect_content,omitempty"`
|
||||||
|
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
|
||||||
|
MessageEffectID string `json:"message_effect_id,omitempty"`
|
||||||
|
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
|
||||||
|
ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) SendMessage(params *SendMessageP) (*Message, error) {
|
||||||
|
data, err := b.request("sendMessage", params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
message := new(Message)
|
||||||
|
err = MapToStruct(data, message)
|
||||||
|
return message, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type SendPhotoP struct {
|
||||||
|
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||||
|
ChatID int `json:"chat_id"`
|
||||||
|
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||||
|
ParseMode ParseMode `json:"parse_mode,omitempty"`
|
||||||
|
Photo string `json:"photo"`
|
||||||
|
Caption string `json:"caption,omitempty"`
|
||||||
|
CaptionEntities []*MessageEntity `json:"caption_entities,omitempty"`
|
||||||
|
ShowCaptionAboveMedia bool `json:"show_caption_above_media"`
|
||||||
|
HasSpoiler bool `json:"has_spoiler"`
|
||||||
|
DisableNotifications bool `json:"disable_notifications,omitempty"`
|
||||||
|
ProtectContent bool `json:"protect_content,omitempty"`
|
||||||
|
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
|
||||||
|
MessageEffectID string `json:"message_effect_id,omitempty"`
|
||||||
|
ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) SendPhoto(params *SendPhotoP) (*Message, error) {
|
||||||
|
data, err := b.request("sendPhoto", params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
message := new(Message)
|
||||||
|
err = MapToStruct(data, message)
|
||||||
|
return message, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type EditMessageTextP struct {
|
||||||
|
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||||
|
ChatID int `json:"chat_id,omitempty"`
|
||||||
|
MessageID int `json:"message_id,omitempty"`
|
||||||
|
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
ParseMode ParseMode `json:"parse_mode,omitempty"`
|
||||||
|
ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) EditMessageText(params *EditMessageTextP) (*Message, error) {
|
||||||
|
data, err := b.request("editMessageText", params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
message := new(Message)
|
||||||
|
err = MapToStruct(data, message)
|
||||||
|
return message, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type EditMessageCaptionP struct {
|
||||||
|
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||||
|
ChatID int `json:"chat_id,omitempty"`
|
||||||
|
MessageID int `json:"message_id,omitempty"`
|
||||||
|
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||||
|
Caption string `json:"caption"`
|
||||||
|
ParseMode ParseMode `json:"parse_mode,omitempty"`
|
||||||
|
ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) EditMessageCaption(params *EditMessageCaptionP) (*Message, error) {
|
||||||
|
data, err := b.request("editMessageCaption", params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
message := new(Message)
|
||||||
|
err = MapToStruct(data, message)
|
||||||
|
return message, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteMessageP struct {
|
||||||
|
ChatID int `json:"chat_id"`
|
||||||
|
MessageID int `json:"message_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) DeleteMessage(params *DeleteMessageP) (*Message, error) {
|
||||||
|
data, err := b.request("deleteMessage", params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
message := new(Message)
|
||||||
|
err = MapToStruct(data, message)
|
||||||
|
return message, err
|
||||||
|
}
|
||||||
116
laniakea/plugins.go
Normal file
116
laniakea/plugins.go
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
package laniakea
|
||||||
|
|
||||||
|
import "log"
|
||||||
|
|
||||||
|
type CommandExecutor func(ctx *MsgContext, dbContext *DatabaseContext)
|
||||||
|
|
||||||
|
type PluginBuilder struct {
|
||||||
|
name string
|
||||||
|
commands map[string]*CommandExecutor
|
||||||
|
payloads map[string]*CommandExecutor
|
||||||
|
updateListener *CommandExecutor
|
||||||
|
}
|
||||||
|
|
||||||
|
type Plugin struct {
|
||||||
|
Name string
|
||||||
|
Commands map[string]*CommandExecutor
|
||||||
|
Payloads map[string]*CommandExecutor
|
||||||
|
UpdateListener *CommandExecutor
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPlugin(name string) *PluginBuilder {
|
||||||
|
return &PluginBuilder{
|
||||||
|
name: name,
|
||||||
|
commands: make(map[string]*CommandExecutor),
|
||||||
|
payloads: make(map[string]*CommandExecutor),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PluginBuilder) Command(f CommandExecutor, cmd ...string) *PluginBuilder {
|
||||||
|
for _, c := range cmd {
|
||||||
|
p.commands[c] = &f
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PluginBuilder) Payload(f CommandExecutor, payloads ...string) *PluginBuilder {
|
||||||
|
for _, payload := range payloads {
|
||||||
|
p.payloads[payload] = &f
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PluginBuilder) UpdateListener(listener CommandExecutor) *PluginBuilder {
|
||||||
|
p.updateListener = &listener
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PluginBuilder) Build() *Plugin {
|
||||||
|
if len(p.commands) == 0 && len(p.payloads) == 0 {
|
||||||
|
log.Println("no command or payloads")
|
||||||
|
}
|
||||||
|
plugin := &Plugin{
|
||||||
|
Name: p.name,
|
||||||
|
Commands: p.commands,
|
||||||
|
Payloads: p.payloads,
|
||||||
|
UpdateListener: p.updateListener,
|
||||||
|
}
|
||||||
|
return plugin
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Execute(cmd string, ctx *MsgContext, dbContext *DatabaseContext) {
|
||||||
|
(*p.Commands[cmd])(ctx, dbContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) ExecutePayload(payload string, ctx *MsgContext, dbContext *DatabaseContext) {
|
||||||
|
(*p.Payloads[payload])(ctx, dbContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Middleware struct {
|
||||||
|
Name string
|
||||||
|
Executor *CommandExecutor
|
||||||
|
Order int
|
||||||
|
Async bool
|
||||||
|
}
|
||||||
|
type MiddlewareBuilder struct {
|
||||||
|
name string
|
||||||
|
executor *CommandExecutor
|
||||||
|
order int
|
||||||
|
async bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMiddleware(name string) *MiddlewareBuilder {
|
||||||
|
return &MiddlewareBuilder{name: name, async: false}
|
||||||
|
}
|
||||||
|
func (m *MiddlewareBuilder) SetName(name string) *MiddlewareBuilder {
|
||||||
|
m.name = name
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
func (m *MiddlewareBuilder) SetExecutor(executor CommandExecutor) *MiddlewareBuilder {
|
||||||
|
m.executor = &executor
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
func (m *MiddlewareBuilder) SetOrder(order int) *MiddlewareBuilder {
|
||||||
|
m.order = order
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
func (m *MiddlewareBuilder) SetAsync(async bool) *MiddlewareBuilder {
|
||||||
|
m.async = async
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
func (m *MiddlewareBuilder) Build() *Middleware {
|
||||||
|
return &Middleware{
|
||||||
|
Name: m.name,
|
||||||
|
Executor: m.executor,
|
||||||
|
Order: m.order,
|
||||||
|
Async: m.async,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (m *Middleware) Execute(ctx *MsgContext, db *DatabaseContext) {
|
||||||
|
exec := *m.Executor
|
||||||
|
if m.Async {
|
||||||
|
go exec(ctx, db)
|
||||||
|
} else {
|
||||||
|
exec(ctx, db)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
package laniakea
|
package laniakea
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
type Queue[T any] struct {
|
type Queue[T any] struct {
|
||||||
queue []T
|
|
||||||
size uint64
|
size uint64
|
||||||
|
mu sync.RWMutex
|
||||||
|
queue []T
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateQueue[T any](size uint64) *Queue[T] {
|
func CreateQueue[T any](size uint64) *Queue[T] {
|
||||||
@@ -23,11 +27,13 @@ func (q *Queue[T]) Enqueue(el T) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queue[T]) Peak() T {
|
func (q *Queue[T]) Peak() T {
|
||||||
|
q.mu.RLock()
|
||||||
|
defer q.mu.RUnlock()
|
||||||
return q.queue[0]
|
return q.queue[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queue[T]) IsEmpty() bool {
|
func (q *Queue[T]) IsEmpty() bool {
|
||||||
return len(q.queue) == 0
|
return q.Length() == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queue[T]) IsFull() bool {
|
func (q *Queue[T]) IsFull() bool {
|
||||||
@@ -35,16 +41,26 @@ func (q *Queue[T]) IsFull() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queue[T]) Length() uint64 {
|
func (q *Queue[T]) Length() uint64 {
|
||||||
|
q.mu.RLock()
|
||||||
|
defer q.mu.RUnlock()
|
||||||
return uint64(len(q.queue))
|
return uint64(len(q.queue))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queue[T]) Dequeue() T {
|
func (q *Queue[T]) Dequeue() T {
|
||||||
|
q.mu.RLock()
|
||||||
el := q.queue[0]
|
el := q.queue[0]
|
||||||
|
q.mu.RUnlock()
|
||||||
|
|
||||||
if q.Length() == 1 {
|
if q.Length() == 1 {
|
||||||
|
q.mu.Lock()
|
||||||
q.queue = make([]T, 0)
|
q.queue = make([]T, 0)
|
||||||
|
q.mu.Unlock()
|
||||||
return el
|
return el
|
||||||
}
|
}
|
||||||
|
|
||||||
|
q.mu.Lock()
|
||||||
q.queue = q.queue[1:]
|
q.queue = q.queue[1:]
|
||||||
|
q.mu.Unlock()
|
||||||
return el
|
return el
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -12,9 +12,9 @@ type Update struct {
|
|||||||
DeletedBusinessMessage *Message `json:"deleted_business_messages,omitempty"`
|
DeletedBusinessMessage *Message `json:"deleted_business_messages,omitempty"`
|
||||||
MessageReaction *MessageReactionUpdated `json:"message_reaction,omitempty"`
|
MessageReaction *MessageReactionUpdated `json:"message_reaction,omitempty"`
|
||||||
MessageReactionCount *MessageReactionCountUpdated `json:"message_reaction_count,omitempty"`
|
MessageReactionCount *MessageReactionCountUpdated `json:"message_reaction_count,omitempty"`
|
||||||
|
CallbackQuery *CallbackQuery `json:"callback_query,omitempty"`
|
||||||
InlineQuery int
|
InlineQuery int
|
||||||
ChosenInlineResult int
|
ChosenInlineResult int
|
||||||
CallbackQuery *CallbackQuery `json:"callback_query,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
@@ -43,6 +43,10 @@ type Chat struct {
|
|||||||
IsForum bool `json:"is_forum,omitempty"`
|
IsForum bool `json:"is_forum,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type MessageReplyMarkup struct {
|
||||||
|
InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"`
|
||||||
|
}
|
||||||
|
|
||||||
type Message struct {
|
type Message struct {
|
||||||
MessageID int `json:"message_id"`
|
MessageID int `json:"message_id"`
|
||||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||||
@@ -53,6 +57,8 @@ type Message struct {
|
|||||||
Photo []*PhotoSize `json:"photo,omitempty"`
|
Photo []*PhotoSize `json:"photo,omitempty"`
|
||||||
Caption string `json:"caption,omitempty"`
|
Caption string `json:"caption,omitempty"`
|
||||||
ReplyToMessage *Message `json:"reply_to_message"`
|
ReplyToMessage *Message `json:"reply_to_message"`
|
||||||
|
|
||||||
|
ReplyMarkup *MessageReplyMarkup `json:"reply_markup,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type InaccessableMessage struct {
|
type InaccessableMessage struct {
|
||||||
@@ -62,8 +68,6 @@ type InaccessableMessage struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type MaybeInaccessibleMessage struct {
|
type MaybeInaccessibleMessage struct {
|
||||||
Message
|
|
||||||
InaccessableMessage
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type MessageEntity struct {
|
type MessageEntity struct {
|
||||||
@@ -103,7 +107,7 @@ type LinkPreviewOptions struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type InlineKeyboardMarkup struct {
|
type InlineKeyboardMarkup struct {
|
||||||
InlineKeyboard [][]*InlineKeyboardButton `json:"inline_keyboard"`
|
InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type InlineKeyboardButton struct {
|
type InlineKeyboardButton struct {
|
||||||
@@ -117,9 +121,9 @@ type ReplyKeyboardMarkup struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CallbackQuery struct {
|
type CallbackQuery struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
From *User `json:"user"`
|
From *User `json:"from"`
|
||||||
Message *MaybeInaccessibleMessage `json:"message"`
|
Message *Message `json:"message"`
|
||||||
|
|
||||||
Data string `json:"data"`
|
Data string `json:"data"`
|
||||||
}
|
}
|
||||||
108
laniakea/utils.go
Normal file
108
laniakea/utils.go
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
package laniakea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func MapToStruct(m map[string]interface{}, s interface{}) error {
|
||||||
|
data, err := json.Marshal(m)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(data, s)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func MapToJson(m map[string]interface{}) (string, error) {
|
||||||
|
data, err := json.Marshal(m)
|
||||||
|
return string(data), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func StructToMap(s interface{}) (map[string]interface{}, error) {
|
||||||
|
data, err := json.Marshal(s)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
m := make(map[string]interface{})
|
||||||
|
err = json.Unmarshal(data, &m)
|
||||||
|
return m, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func Map[T, V any](ts []T, fn func(T) V) []V {
|
||||||
|
result := make([]V, len(ts))
|
||||||
|
for i, t := range ts {
|
||||||
|
result[i] = fn(t)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func EscapeMarkdown(s string) string {
|
||||||
|
s = strings.ReplaceAll(s, "_", `\_`)
|
||||||
|
s = strings.ReplaceAll(s, "*", `\*`)
|
||||||
|
s = strings.ReplaceAll(s, "[", `\[`)
|
||||||
|
return strings.ReplaceAll(s, "`", "\\`")
|
||||||
|
}
|
||||||
|
|
||||||
|
func EscapeMarkdownV2(s string) string {
|
||||||
|
symbols := []string{"_", "*", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
|
||||||
|
for _, symbol := range symbols {
|
||||||
|
s = strings.ReplaceAll(s, symbol, fmt.Sprintf("\\%s", symbol))
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUnclosedTag(markdown string) string {
|
||||||
|
// order is important!
|
||||||
|
var tags = []string{
|
||||||
|
"```",
|
||||||
|
"`",
|
||||||
|
"*",
|
||||||
|
"_",
|
||||||
|
}
|
||||||
|
var currentTag = ""
|
||||||
|
|
||||||
|
markdownRunes := []rune(markdown)
|
||||||
|
|
||||||
|
var i = 0
|
||||||
|
outer:
|
||||||
|
for i < len(markdownRunes) {
|
||||||
|
// skip escaped characters (only outside tags)
|
||||||
|
if markdownRunes[i] == '\\' && currentTag == "" {
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if currentTag != "" {
|
||||||
|
if strings.HasPrefix(string(markdownRunes[i:]), currentTag) {
|
||||||
|
// turn a tag off
|
||||||
|
i += len(currentTag)
|
||||||
|
currentTag = ""
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for _, tag := range tags {
|
||||||
|
if strings.HasPrefix(string(markdownRunes[i:]), tag) {
|
||||||
|
// turn a tag on
|
||||||
|
currentTag = tag
|
||||||
|
i += len(currentTag)
|
||||||
|
continue outer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
|
||||||
|
return currentTag
|
||||||
|
}
|
||||||
|
func IsValid(markdown string) bool {
|
||||||
|
return GetUnclosedTag(markdown) == ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func FixMarkdown(markdown string) string {
|
||||||
|
tag := GetUnclosedTag(markdown)
|
||||||
|
if tag == "" {
|
||||||
|
return markdown
|
||||||
|
}
|
||||||
|
return markdown + tag
|
||||||
|
}
|
||||||
12
laniakea/version.go
Normal file
12
laniakea/version.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package laniakea
|
||||||
|
|
||||||
|
import "os"
|
||||||
|
|
||||||
|
const (
|
||||||
|
VersionString = "0.2.0"
|
||||||
|
VersionMajor = 0
|
||||||
|
VersionMinor = 2
|
||||||
|
VersionPatch = 0
|
||||||
|
)
|
||||||
|
|
||||||
|
var GoVersion = os.Getenv("GoV")
|
||||||
162
logger.go
162
logger.go
@@ -1,162 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/fatih/color"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Logger struct {
|
|
||||||
prefix string
|
|
||||||
level LogLevel
|
|
||||||
printTraceback bool
|
|
||||||
printTime bool
|
|
||||||
|
|
||||||
f *os.File
|
|
||||||
}
|
|
||||||
|
|
||||||
type LogLevel struct {
|
|
||||||
n uint8
|
|
||||||
t string
|
|
||||||
c color.Attribute
|
|
||||||
}
|
|
||||||
|
|
||||||
type MethodTraceback struct {
|
|
||||||
Package string
|
|
||||||
Method string
|
|
||||||
fullPath string
|
|
||||||
signature string
|
|
||||||
filename string
|
|
||||||
line int
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
INFO LogLevel = LogLevel{n: 0, t: "info", c: color.FgWhite}
|
|
||||||
WARN LogLevel = LogLevel{n: 1, t: "warn", c: color.FgHiYellow}
|
|
||||||
ERROR LogLevel = LogLevel{n: 2, t: "error", c: color.FgHiRed}
|
|
||||||
FATAL LogLevel = LogLevel{n: 3, t: "fatal", c: color.FgRed}
|
|
||||||
DEBUG LogLevel = LogLevel{n: 4, t: "debug", c: color.FgGreen}
|
|
||||||
)
|
|
||||||
|
|
||||||
func CreateLogger() *Logger {
|
|
||||||
return &Logger{
|
|
||||||
prefix: "LOG",
|
|
||||||
level: FATAL,
|
|
||||||
printTraceback: false,
|
|
||||||
printTime: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) OpenFile(name string) *Logger {
|
|
||||||
err := os.MkdirAll(filepath.Dir(name), os.ModePerm)
|
|
||||||
if err != nil {
|
|
||||||
l.Fatal(err)
|
|
||||||
}
|
|
||||||
l.f, err = os.OpenFile(name, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
|
||||||
if err != nil {
|
|
||||||
l.Fatal(err)
|
|
||||||
}
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) Prefix(prefix string) *Logger {
|
|
||||||
l.prefix = prefix
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
func (l *Logger) Level(level LogLevel) *Logger {
|
|
||||||
l.level = level
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
func (l *Logger) PrintTraceback(b bool) *Logger {
|
|
||||||
l.printTraceback = b
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) Info(m ...any) {
|
|
||||||
l.print(INFO, m)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) Warn(m ...any) {
|
|
||||||
l.print(WARN, m)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) Error(m ...any) {
|
|
||||||
l.print(ERROR, m)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) Fatal(m ...any) {
|
|
||||||
l.print(FATAL, m)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) Debug(m ...any) {
|
|
||||||
l.print(DEBUG, m)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) formatTime(t time.Time) string {
|
|
||||||
return fmt.Sprintf("%02d.%02d.%02d %02d:%02d:%02d", t.Day(), t.Month(), t.Year(), t.Hour(), t.Minute(), t.Second())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) getTraceback() *MethodTraceback {
|
|
||||||
caller, _, _, _ := runtime.Caller(4)
|
|
||||||
details := runtime.FuncForPC(caller)
|
|
||||||
signature := details.Name()
|
|
||||||
path, line := details.FileLine(caller)
|
|
||||||
splitPath := strings.Split(path, "/")
|
|
||||||
|
|
||||||
splitSignature := strings.Split(signature, ".")
|
|
||||||
pkg, method := splitSignature[0], splitSignature[len(splitSignature)-1]
|
|
||||||
|
|
||||||
tb := &MethodTraceback{
|
|
||||||
filename: splitPath[len(splitPath)-1],
|
|
||||||
fullPath: path,
|
|
||||||
line: line,
|
|
||||||
signature: signature,
|
|
||||||
Package: pkg,
|
|
||||||
Method: method,
|
|
||||||
}
|
|
||||||
|
|
||||||
return tb
|
|
||||||
}
|
|
||||||
func (l *Logger) formatTraceback(mt *MethodTraceback) string {
|
|
||||||
return fmt.Sprintf("%s:%s:%d", mt.filename, mt.Method, mt.line)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) buildString(level LogLevel, m []any) string {
|
|
||||||
args := []string{
|
|
||||||
fmt.Sprintf("[%s]", l.prefix),
|
|
||||||
fmt.Sprintf("[%s]", strings.ToUpper(level.t)),
|
|
||||||
}
|
|
||||||
|
|
||||||
if l.printTraceback {
|
|
||||||
args = append(args, fmt.Sprintf("[%s]", l.formatTraceback(l.getTraceback())))
|
|
||||||
}
|
|
||||||
|
|
||||||
if l.printTime {
|
|
||||||
args = append(args, fmt.Sprintf("[%s]", l.formatTime(time.Now())))
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := Map(m, func(el any) string {
|
|
||||||
return fmt.Sprintf("%v", el)
|
|
||||||
})
|
|
||||||
|
|
||||||
return fmt.Sprintf("%s %v", strings.Join(args, " "), strings.Join(msg, " "))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) print(level LogLevel, m []any) {
|
|
||||||
if l.level.n < level.n {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
color.New(level.c).Println(l.buildString(level, m))
|
|
||||||
|
|
||||||
if l.f != nil {
|
|
||||||
if _, err := l.f.Write([]byte(l.buildString(level, m) + "\n")); err != nil {
|
|
||||||
l.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
111
methods.go
111
methods.go
@@ -1,111 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
var NO_PARAMS = make(map[string]interface{})
|
|
||||||
|
|
||||||
func (b *Bot) Updates() ([]*Update, error) {
|
|
||||||
params := make(map[string]interface{})
|
|
||||||
params["offset"] = b.updateOffset
|
|
||||||
params["timeout"] = 30
|
|
||||||
params["allowed_updates"] = b.updateTypes
|
|
||||||
|
|
||||||
data, err := b.request("getUpdates", params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res := make([]*Update, 0)
|
|
||||||
for _, u := range data["data"].([]interface{}) {
|
|
||||||
updateObj := new(Update)
|
|
||||||
err = MapToStruct(u.(map[string]interface{}), updateObj)
|
|
||||||
if err != nil {
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
b.updateOffset = updateObj.UpdateID + 1
|
|
||||||
err = b.updateQueue.Enqueue(updateObj)
|
|
||||||
if err != nil {
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
res = append(res, updateObj)
|
|
||||||
|
|
||||||
if b.debug && b.requestLogger != nil {
|
|
||||||
j, err := MapToJson(u.(map[string]interface{}))
|
|
||||||
if err != nil {
|
|
||||||
b.logger.Error(err)
|
|
||||||
}
|
|
||||||
b.requestLogger.Debug(fmt.Sprintf("UPDATE %s", j))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) GetMe() (*User, error) {
|
|
||||||
data, err := b.request("getMe", NO_PARAMS)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
user := new(User)
|
|
||||||
err = MapToStruct(data, user)
|
|
||||||
return user, err
|
|
||||||
}
|
|
||||||
|
|
||||||
type SendMessageP struct {
|
|
||||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
|
||||||
ChatID int `json:"chat_id"`
|
|
||||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
|
||||||
Text string `json:"text"`
|
|
||||||
ParseMode ParseMode `json:"parse_mode,omitempty"`
|
|
||||||
Entities []*MessageEntity `json:"entities,omitempty"`
|
|
||||||
LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"`
|
|
||||||
DisableNotifications bool `json:"disable_notifications,omitempty"`
|
|
||||||
ProtectContent bool `json:"protect_content,omitempty"`
|
|
||||||
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
|
|
||||||
MessageEffectID string `json:"message_effect_id,omitempty"`
|
|
||||||
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
|
|
||||||
InlineKeyboardMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
|
|
||||||
// ReplyKeyboardMarkup *ReplyKeyboardMarkup `json:"reply_markup,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) SendMessage(params *SendMessageP) (*Message, error) {
|
|
||||||
dataP, err := StructToMap(params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
data, err := b.request("sendMessage", dataP)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
message := new(Message)
|
|
||||||
err = MapToStruct(data, message)
|
|
||||||
return message, err
|
|
||||||
}
|
|
||||||
|
|
||||||
type SendPhotoP struct {
|
|
||||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
|
||||||
ChatID int `json:"chat_id"`
|
|
||||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
|
||||||
Photo string `json:"photo"`
|
|
||||||
Caption string `json:"caption,omitempty"`
|
|
||||||
ParseMode ParseMode `json:"parse_mode,omitempty"`
|
|
||||||
CaptionEntities []*MessageEntity `json:"caption_entities,omitempty"`
|
|
||||||
ShowCaptionAboveMedia bool `json:"show_caption_above_media"`
|
|
||||||
HasSpoiler bool `json:"has_spoiler"`
|
|
||||||
DisableNotifications bool `json:"disable_notifications,omitempty"`
|
|
||||||
ProtectContent bool `json:"protect_content,omitempty"`
|
|
||||||
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
|
|
||||||
MessageEffectID string `json:"message_effect_id,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) SendPhoto(params *SendPhotoP) (*Message, error) {
|
|
||||||
dataP, err := StructToMap(params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
data, err := b.request("sendPhoto", dataP)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
message := new(Message)
|
|
||||||
err = MapToStruct(data, message)
|
|
||||||
return message, err
|
|
||||||
}
|
|
||||||
65
plugins.go
65
plugins.go
@@ -1,65 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
type CommandExecutor func(ctx *MsgContext)
|
|
||||||
|
|
||||||
type PluginBuilder struct {
|
|
||||||
name string
|
|
||||||
commands map[string]*CommandExecutor
|
|
||||||
payloads map[string]*CommandExecutor
|
|
||||||
updateListener *CommandExecutor
|
|
||||||
}
|
|
||||||
|
|
||||||
type Plugin struct {
|
|
||||||
Name string
|
|
||||||
Commands map[string]*CommandExecutor
|
|
||||||
Payloads map[string]*CommandExecutor
|
|
||||||
UpdateListener *CommandExecutor
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPlugin(name string) *PluginBuilder {
|
|
||||||
return &PluginBuilder{
|
|
||||||
name: name,
|
|
||||||
commands: make(map[string]*CommandExecutor),
|
|
||||||
payloads: make(map[string]*CommandExecutor),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *PluginBuilder) Command(f CommandExecutor, cmd ...string) *PluginBuilder {
|
|
||||||
for _, c := range cmd {
|
|
||||||
p.commands[c] = &f
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *PluginBuilder) Payload(f CommandExecutor, payloads ...string) *PluginBuilder {
|
|
||||||
for _, payload := range payloads {
|
|
||||||
p.payloads[payload] = &f
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *PluginBuilder) UpdateListener(listener CommandExecutor) *PluginBuilder {
|
|
||||||
p.updateListener = &listener
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *PluginBuilder) Build() *Plugin {
|
|
||||||
if len(p.commands) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
plugin := &Plugin{
|
|
||||||
Name: p.name,
|
|
||||||
Commands: p.commands,
|
|
||||||
Payloads: p.payloads,
|
|
||||||
UpdateListener: p.updateListener,
|
|
||||||
}
|
|
||||||
return plugin
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Plugin) Execute(cmd string, ctx *MsgContext) {
|
|
||||||
(*p.Commands[cmd])(ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Plugin) ExecutePayload(payload string, ctx *MsgContext) {
|
|
||||||
(*p.Payloads[payload])(ctx)
|
|
||||||
}
|
|
||||||
35
utils.go
35
utils.go
@@ -1,35 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
func MapToStruct(m map[string]interface{}, s interface{}) error {
|
|
||||||
data, err := json.Marshal(m)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = json.Unmarshal(data, s)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapToJson(m map[string]interface{}) (string, error) {
|
|
||||||
data, err := json.Marshal(m)
|
|
||||||
return string(data), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func StructToMap(s interface{}) (map[string]interface{}, error) {
|
|
||||||
data, err := json.Marshal(s)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
m := make(map[string]interface{})
|
|
||||||
err = json.Unmarshal(data, &m)
|
|
||||||
return m, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func Map[T, V any](ts []T, fn func(T) V) []V {
|
|
||||||
result := make([]V, len(ts))
|
|
||||||
for i, t := range ts {
|
|
||||||
result[i] = fn(t)
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
const (
|
|
||||||
VERSION_STRING = "0.1.4"
|
|
||||||
VERSION_MAJOR = 0
|
|
||||||
VERSION_MINOR = 1
|
|
||||||
VERSION_PATCH = 4
|
|
||||||
)
|
|
||||||
Reference in New Issue
Block a user