Compare commits
13 Commits
7f248fff62
...
v0.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f8182039d | |||
| 05dadc3de3 | |||
| 37397ba90f | |||
| c503b68814 | |||
| 49ec217d33 | |||
| 7a3e40a74d | |||
| ce13b19676 | |||
| 684d56acba | |||
| 21623788c6 | |||
| b88715d6d3 | |||
| 0cc146edd9 | |||
| 3d1263b3e0 | |||
| c6b47d18f6 |
@@ -1,4 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
type InlineKeyboard struct {
|
|
||||||
}
|
|
||||||
@@ -5,14 +5,16 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
|
"github.com/vinovest/sqlx"
|
||||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type ParseMode string
|
type ParseMode string
|
||||||
@@ -50,6 +52,7 @@ type BotSettings struct {
|
|||||||
UpdateTypes []string
|
UpdateTypes []string
|
||||||
LoggerBasePath string
|
LoggerBasePath string
|
||||||
UseRequestLogger bool
|
UseRequestLogger bool
|
||||||
|
WriteToFile bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func LoadSettingsFromEnv() *BotSettings {
|
func LoadSettingsFromEnv() *BotSettings {
|
||||||
@@ -60,6 +63,7 @@ func LoadSettingsFromEnv() *BotSettings {
|
|||||||
Prefixes: LoadPrefixesFromEnv(),
|
Prefixes: LoadPrefixesFromEnv(),
|
||||||
UpdateTypes: strings.Split(os.Getenv("UPDATE_TYPES"), ";"),
|
UpdateTypes: strings.Split(os.Getenv("UPDATE_TYPES"), ";"),
|
||||||
UseRequestLogger: os.Getenv("USE_REQ_LOG") == "true",
|
UseRequestLogger: os.Getenv("USE_REQ_LOG") == "true",
|
||||||
|
WriteToFile: os.Getenv("WRITE_TO_FILE") == "true",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,6 +71,8 @@ type MsgContext struct {
|
|||||||
Bot *Bot
|
Bot *Bot
|
||||||
Msg *Message
|
Msg *Message
|
||||||
Update *Update
|
Update *Update
|
||||||
|
From *User
|
||||||
|
CallbackMsgId int
|
||||||
FromID int
|
FromID int
|
||||||
Prefix string
|
Prefix string
|
||||||
Text string
|
Text string
|
||||||
@@ -74,7 +80,7 @@ type MsgContext struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type DatabaseContext struct {
|
type DatabaseContext struct {
|
||||||
PostgresSQL *gorm.DB
|
PostgresSQL *sqlx.DB
|
||||||
MongoDB *mongo.Client
|
MongoDB *mongo.Client
|
||||||
Redis *redis.Client
|
Redis *redis.Client
|
||||||
}
|
}
|
||||||
@@ -99,21 +105,40 @@ func NewBot(settings *BotSettings) *Bot {
|
|||||||
if settings.Debug {
|
if settings.Debug {
|
||||||
level = DEBUG
|
level = DEBUG
|
||||||
}
|
}
|
||||||
bot.logger = CreateLogger().Level(level).OpenFile(fmt.Sprintf("%s/main.log", strings.TrimRight(settings.LoggerBasePath, "/")))
|
|
||||||
bot.logger = bot.logger.PrintTraceback(true)
|
bot.logger = CreateLogger().Level(level).PrintTraceback(true)
|
||||||
|
bot.logger.AddWriter(bot.logger.CreateStdoutWriter())
|
||||||
|
if settings.WriteToFile {
|
||||||
|
path := fmt.Sprintf("%s/main.log", strings.TrimRight(settings.LoggerBasePath, "/"))
|
||||||
|
fileWriter, err := bot.logger.CreateFileWriter(path)
|
||||||
|
if err != nil {
|
||||||
|
bot.logger.Fatal(err)
|
||||||
|
}
|
||||||
|
bot.logger.AddWriter(fileWriter)
|
||||||
|
}
|
||||||
|
|
||||||
if settings.UseRequestLogger {
|
if settings.UseRequestLogger {
|
||||||
bot.requestLogger = CreateLogger().Level(level).Prefix("REQUESTS").OpenFile(fmt.Sprintf("%s/requests.log", strings.TrimRight(settings.LoggerBasePath, "/")))
|
bot.requestLogger = CreateLogger().Level(level).Prefix("REQUESTS")
|
||||||
|
bot.requestLogger.AddWriter(bot.requestLogger.CreateStdoutWriter())
|
||||||
|
if settings.WriteToFile {
|
||||||
|
path := fmt.Sprintf("%s/requests.log", strings.TrimRight(settings.LoggerBasePath, "/"))
|
||||||
|
fileWriter, err := bot.requestLogger.CreateFileWriter(path)
|
||||||
|
if err != nil {
|
||||||
|
bot.logger.Fatal(err)
|
||||||
|
}
|
||||||
|
bot.requestLogger.AddWriter(fileWriter)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return bot
|
return bot
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bot) Close() {
|
func (b *Bot) Close() {
|
||||||
err := b.logger.f.Close()
|
for _, writer := range b.logger.writers {
|
||||||
|
err := writer.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
log.Println(err)
|
||||||
} else {
|
}
|
||||||
fmt.Println("log closed")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,11 +146,11 @@ func (b *Bot) InitDatabaseContext(ctx *DatabaseContext) *Bot {
|
|||||||
b.dbContext = ctx
|
b.dbContext = ctx
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
func (b *Bot) AddDatabaseLogger(writer func(db *DatabaseContext) LoggerWriter) *Bot {
|
func (b *Bot) AddDatabaseLogger(writer func(db *DatabaseContext) *LoggerWriter) *Bot {
|
||||||
w := []LoggerWriter{writer(b.dbContext)}
|
w := writer(b.dbContext)
|
||||||
b.logger.AddWriters(w)
|
b.logger.AddWriter(w)
|
||||||
if b.requestLogger != nil {
|
if b.requestLogger != nil {
|
||||||
b.requestLogger.AddWriters(w)
|
b.requestLogger.AddWriter(w)
|
||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
@@ -146,11 +171,11 @@ func (b *Bot) AddPrefixes(prefixes ...string) *Bot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func LoadPrefixesFromEnv() []string {
|
func LoadPrefixesFromEnv() []string {
|
||||||
prefixes, exists := os.LookupEnv("PREFIXES")
|
prefixesS, exists := os.LookupEnv("PREFIXES")
|
||||||
if !exists {
|
if !exists {
|
||||||
return []string{"!"}
|
return []string{"!"}
|
||||||
}
|
}
|
||||||
return strings.Split(prefixes, ";")
|
return strings.Split(prefixesS, ";")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bot) ErrorTemplate(s string) *Bot {
|
func (b *Bot) ErrorTemplate(s string) *Bot {
|
||||||
@@ -166,7 +191,7 @@ func (b *Bot) Debug(debug bool) *Bot {
|
|||||||
func (b *Bot) AddPlugins(plugin ...*Plugin) *Bot {
|
func (b *Bot) AddPlugins(plugin ...*Plugin) *Bot {
|
||||||
b.plugins = append(b.plugins, plugin...)
|
b.plugins = append(b.plugins, plugin...)
|
||||||
for _, p := range plugin {
|
for _, p := range plugin {
|
||||||
b.logger.Debug(fmt.Sprintf("plugins with name \"%s\" was registered", p.Name))
|
b.logger.Debug(fmt.Sprintf("plugins with name \"%s\" registered", p.Name))
|
||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
@@ -183,7 +208,7 @@ func (b *Bot) AddMiddleware(middleware ...*Middleware) *Bot {
|
|||||||
|
|
||||||
b.middlewares = append(b.middlewares, middleware...)
|
b.middlewares = append(b.middlewares, middleware...)
|
||||||
for _, m := range middleware {
|
for _, m := range middleware {
|
||||||
b.logger.Debug(fmt.Sprintf("middleware with name \"%s\" was registered", m.Name))
|
b.logger.Debug(fmt.Sprintf("middleware with name \"%s\" registered", m.Name))
|
||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
@@ -207,16 +232,22 @@ func (b *Bot) Run() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
b.logger.Error(err)
|
b.logger.Error(err)
|
||||||
}
|
}
|
||||||
|
time.Sleep(time.Millisecond * 10)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
queue := b.updateQueue
|
queue := b.updateQueue
|
||||||
if queue.IsEmpty() {
|
if queue.IsEmpty() {
|
||||||
|
time.Sleep(time.Millisecond * 25)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
u := queue.Dequeue()
|
u := queue.Dequeue()
|
||||||
|
if u == nil {
|
||||||
|
b.logger.Error("update is nil")
|
||||||
|
continue
|
||||||
|
}
|
||||||
ctx := &MsgContext{
|
ctx := &MsgContext{
|
||||||
Bot: b,
|
Bot: b,
|
||||||
Update: u,
|
Update: u,
|
||||||
@@ -253,6 +284,7 @@ func (b *Bot) handleMessage(update *Update, ctx *MsgContext) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ctx.FromID = update.Message.From.ID
|
ctx.FromID = update.Message.From.ID
|
||||||
|
ctx.From = update.Message.From
|
||||||
ctx.Msg = update.Message
|
ctx.Msg = update.Message
|
||||||
text = strings.TrimSpace(text)
|
text = strings.TrimSpace(text)
|
||||||
prefix, hasPrefix := b.checkPrefixes(text)
|
prefix, hasPrefix := b.checkPrefixes(text)
|
||||||
@@ -279,13 +311,26 @@ func (b *Bot) handleMessage(update *Update, ctx *MsgContext) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bot) handleCallback(update *Update, ctx *MsgContext) {
|
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 {
|
for _, plugin := range b.plugins {
|
||||||
for payload := range plugin.Payloads {
|
_, ok := plugin.Payloads[data.Command]
|
||||||
if !strings.HasPrefix(update.CallbackQuery.Data, payload) {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
go plugin.ExecutePayload(payload, ctx, b.dbContext)
|
go plugin.ExecutePayload(data.Command, ctx, b.dbContext)
|
||||||
}
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,34 +343,149 @@ func (b *Bot) checkPrefixes(text string) (string, bool) {
|
|||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ctx *MsgContext) Answer(text string) {
|
type AnswerMessage struct {
|
||||||
_, err := ctx.Bot.SendMessage(&SendMessageP{
|
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,
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
Text: text,
|
Text: text,
|
||||||
ParseMode: ParseMD,
|
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 {
|
if err != nil {
|
||||||
ctx.Bot.logger.Error(err)
|
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) AnswerPhoto(photoId string, text string) {
|
func (ctx *MsgContext) answer(text string, keyboard *InlineKeyboard) *AnswerMessage {
|
||||||
_, err := ctx.Bot.SendPhoto(&SendPhotoP{
|
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,
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
Caption: text,
|
Caption: text,
|
||||||
Photo: photoId,
|
Photo: photoId,
|
||||||
ParseMode: ParseMD,
|
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 {
|
if err != nil {
|
||||||
ctx.Bot.logger.Error(err)
|
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) {
|
func (ctx *MsgContext) Error(err error) {
|
||||||
_, sendErr := ctx.Bot.SendMessage(&SendMessageP{
|
_, sendErr := ctx.Bot.SendMessage(&SendMessageP{
|
||||||
ChatID: ctx.Msg.Chat.ID,
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
Text: fmt.Sprintf(ctx.Bot.errorTemplate, err.Error()),
|
Text: fmt.Sprintf(ctx.Bot.errorTemplate, EscapeMarkdown(err.Error())),
|
||||||
})
|
})
|
||||||
|
ctx.Bot.logger.Error(err)
|
||||||
|
|
||||||
if sendErr != nil {
|
if sendErr != nil {
|
||||||
ctx.Bot.logger.Error(sendErr)
|
ctx.Bot.logger.Error(sendErr)
|
||||||
@@ -351,7 +511,7 @@ type ApiResponseA struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// request is a low-level call to api.
|
// request is a low-level call to api.
|
||||||
func (b *Bot) request(methodName string, params map[string]any) (map[string]any, error) {
|
func (b *Bot) request(methodName string, params any) (map[string]interface{}, error) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
err := json.NewEncoder(&buf).Encode(params)
|
err := json.NewEncoder(&buf).Encode(params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -370,10 +530,12 @@ func (b *Bot) request(methodName string, params map[string]any) (map[string]any,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
data, err := io.ReadAll(r.Body)
|
data, err := io.ReadAll(r.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
b.requestLogger.Debug(fmt.Sprintf("RES %s %s", methodName, string(data)))
|
||||||
response := new(ApiResponse)
|
response := new(ApiResponse)
|
||||||
|
|
||||||
var result map[string]any
|
var result map[string]any
|
||||||
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)
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package laniakea
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
@@ -12,16 +13,30 @@ import (
|
|||||||
"github.com/fatih/color"
|
"github.com/fatih/color"
|
||||||
)
|
)
|
||||||
|
|
||||||
type LoggerWriter func(level LogLevel, prefix, traceback string, message []any)
|
type LoggerWriter struct {
|
||||||
|
writer io.Writer
|
||||||
|
writeFn LoggerWriterFn
|
||||||
|
logger *Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *LoggerWriter) SetFn(fn LoggerWriterFn) {
|
||||||
|
w.writeFn = fn
|
||||||
|
}
|
||||||
|
func (w *LoggerWriter) Write(p []byte) (n int, err error) {
|
||||||
|
return w.writer.Write(p)
|
||||||
|
}
|
||||||
|
func (w *LoggerWriter) Close() error {
|
||||||
|
return w.writer.(io.Closer).Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoggerWriterFn func(level LogLevel, prefix, traceback string, message []any) error
|
||||||
|
|
||||||
type Logger struct {
|
type Logger struct {
|
||||||
prefix string
|
prefix string
|
||||||
level LogLevel
|
level LogLevel
|
||||||
printTraceback bool
|
printTraceback bool
|
||||||
printTime bool
|
printTime bool
|
||||||
writers []LoggerWriter
|
writers []*LoggerWriter
|
||||||
|
|
||||||
f *os.File
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type LogLevel struct {
|
type LogLevel struct {
|
||||||
@@ -60,16 +75,34 @@ func CreateLogger() *Logger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Logger) OpenFile(name string) *Logger {
|
func (l *Logger) CreateFileWriter(path string) (*LoggerWriter, error) {
|
||||||
err := os.MkdirAll(filepath.Dir(name), os.ModePerm)
|
err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Fatal(err)
|
return nil, err
|
||||||
}
|
}
|
||||||
l.f, err = os.OpenFile(name, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Fatal(err)
|
return nil, err
|
||||||
}
|
}
|
||||||
return l
|
|
||||||
|
writer := &LoggerWriter{
|
||||||
|
writer: file, logger: l,
|
||||||
|
}
|
||||||
|
writer.writeFn = func(level LogLevel, prefix, traceback string, message []any) error {
|
||||||
|
_, err = writer.Write([]byte(writer.logger.buildString(level, message) + "\n"))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return writer, nil
|
||||||
|
}
|
||||||
|
func (l *Logger) CreateStdoutWriter() *LoggerWriter {
|
||||||
|
writer := &LoggerWriter{
|
||||||
|
writer: os.Stdout, logger: l,
|
||||||
|
}
|
||||||
|
writer.writeFn = func(level LogLevel, prefix, traceback string, message []any) error {
|
||||||
|
_, err := color.New(level.c).Fprint(writer.writer, writer.logger.buildString(level, message))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return writer
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Logger) Prefix(prefix string) *Logger {
|
func (l *Logger) Prefix(prefix string) *Logger {
|
||||||
@@ -88,11 +121,18 @@ func (l *Logger) PrintTime(b bool) *Logger {
|
|||||||
l.printTime = b
|
l.printTime = b
|
||||||
return l
|
return l
|
||||||
}
|
}
|
||||||
func (l *Logger) AddWriters(writers []LoggerWriter) *Logger {
|
func (l *Logger) AddWriters(writers ...*LoggerWriter) *Logger {
|
||||||
l.writers = append(l.writers, writers...)
|
l.writers = append(l.writers, writers...)
|
||||||
return l
|
return l
|
||||||
}
|
}
|
||||||
|
func (l *Logger) AddWriter(writer *LoggerWriter) *Logger {
|
||||||
|
l.writers = append(l.writers, writer)
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) Infof(format string, m ...any) {
|
||||||
|
l.print(INFO, []any{fmt.Sprintf(format, m...)})
|
||||||
|
}
|
||||||
func (l *Logger) Info(m ...any) {
|
func (l *Logger) Info(m ...any) {
|
||||||
l.print(INFO, m)
|
l.print(INFO, m)
|
||||||
}
|
}
|
||||||
@@ -209,22 +249,11 @@ func (l *Logger) print(level LogLevel, m []any) {
|
|||||||
if l.level.n < level.n {
|
if l.level.n < level.n {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err := color.New(level.c).Println(l.buildString(level, m))
|
|
||||||
if err != nil {
|
|
||||||
l.Fatal(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, writer := range l.writers {
|
for _, writer := range l.writers {
|
||||||
writer(level, l.prefix, l.formatFullTraceback(l.getFullTraceback(4)), m)
|
err := writer.writeFn(level, l.prefix, l.formatFullTraceback(l.getFullTraceback(0)), m)
|
||||||
}
|
if err != nil {
|
||||||
|
l.Error(err)
|
||||||
if l.f != nil {
|
|
||||||
writeToFiles := os.Getenv("WRITE_TO_FILE")
|
|
||||||
if writeToFiles != "false" {
|
|
||||||
if _, err := l.f.Write([]byte(l.buildString(level, m) + "\n")); err != nil {
|
|
||||||
l.Fatal(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
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
package laniakea
|
package laniakea
|
||||||
|
|
||||||
|
import "log"
|
||||||
|
|
||||||
type CommandExecutor func(ctx *MsgContext, dbContext *DatabaseContext)
|
type CommandExecutor func(ctx *MsgContext, dbContext *DatabaseContext)
|
||||||
|
|
||||||
type PluginBuilder struct {
|
type PluginBuilder struct {
|
||||||
@@ -44,8 +46,8 @@ func (p *PluginBuilder) UpdateListener(listener CommandExecutor) *PluginBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *PluginBuilder) Build() *Plugin {
|
func (p *PluginBuilder) Build() *Plugin {
|
||||||
if len(p.commands) == 0 {
|
if len(p.commands) == 0 && len(p.payloads) == 0 {
|
||||||
return nil
|
log.Println("no command or payloads")
|
||||||
}
|
}
|
||||||
plugin := &Plugin{
|
plugin := &Plugin{
|
||||||
Name: p.name,
|
Name: p.name,
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package laniakea
|
package laniakea
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -11,8 +11,6 @@ type Queue[T any] struct {
|
|||||||
queue []T
|
queue []T
|
||||||
}
|
}
|
||||||
|
|
||||||
var QueueFullError = errors.New("queue full")
|
|
||||||
|
|
||||||
func CreateQueue[T any](size uint64) *Queue[T] {
|
func CreateQueue[T any](size uint64) *Queue[T] {
|
||||||
return &Queue[T]{
|
return &Queue[T]{
|
||||||
queue: make([]T, 0),
|
queue: make([]T, 0),
|
||||||
@@ -22,7 +20,7 @@ func CreateQueue[T any](size uint64) *Queue[T] {
|
|||||||
|
|
||||||
func (q *Queue[T]) Enqueue(el T) error {
|
func (q *Queue[T]) Enqueue(el T) error {
|
||||||
if q.IsFull() {
|
if q.IsFull() {
|
||||||
return QueueFullError
|
return fmt.Errorf("queue full")
|
||||||
}
|
}
|
||||||
q.queue = append(q.queue, el)
|
q.queue = append(q.queue, el)
|
||||||
return nil
|
return nil
|
||||||
@@ -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 {
|
||||||
@@ -118,8 +122,8 @@ 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
|
||||||
|
}
|
||||||
@@ -3,10 +3,10 @@ package laniakea
|
|||||||
import "os"
|
import "os"
|
||||||
|
|
||||||
const (
|
const (
|
||||||
VersionString = "0.1.4"
|
VersionString = "0.2.0"
|
||||||
VersionMajor = 0
|
VersionMajor = 0
|
||||||
VersionMinor = 1
|
VersionMinor = 2
|
||||||
VersionPatch = 4
|
VersionPatch = 0
|
||||||
)
|
)
|
||||||
|
|
||||||
var GoVersion = os.Getenv("GoV")
|
var GoVersion = os.Getenv("GoV")
|
||||||
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
|
|
||||||
}
|
|
||||||
35
utils.go
35
utils.go
@@ -1,35 +0,0 @@
|
|||||||
package laniakea
|
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
func MapToStruct(m map[string]any, dst interface{}) error {
|
|
||||||
data, err := json.Marshal(m)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = json.Unmarshal(data, dst)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapToJson(m map[string]any) (string, error) {
|
|
||||||
data, err := json.Marshal(m)
|
|
||||||
return string(data), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func StructToMap(s interface{}) (map[string]any, error) {
|
|
||||||
data, err := json.Marshal(s)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
m := make(map[string]any)
|
|
||||||
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
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user