Compare commits
2 Commits
13eb3d45de
...
3d1263b3e0
| Author | SHA1 | Date | |
|---|---|---|---|
| 3d1263b3e0 | |||
| c6b47d18f6 |
73
bot.go
73
bot.go
@@ -7,7 +7,12 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ParseMode string
|
type ParseMode string
|
||||||
@@ -27,8 +32,11 @@ type Bot struct {
|
|||||||
requestLogger *Logger
|
requestLogger *Logger
|
||||||
|
|
||||||
plugins []*Plugin
|
plugins []*Plugin
|
||||||
|
middlewares []*Middleware
|
||||||
prefixes []string
|
prefixes []string
|
||||||
|
|
||||||
|
dbContext *DatabaseContext
|
||||||
|
|
||||||
updateOffset int
|
updateOffset int
|
||||||
updateTypes []string
|
updateTypes []string
|
||||||
updateQueue *Queue[*Update]
|
updateQueue *Queue[*Update]
|
||||||
@@ -45,7 +53,14 @@ type BotSettings struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func LoadSettingsFromEnv() *BotSettings {
|
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",
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type MsgContext struct {
|
type MsgContext struct {
|
||||||
@@ -58,6 +73,12 @@ type MsgContext struct {
|
|||||||
Args []string
|
Args []string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DatabaseContext struct {
|
||||||
|
PostgresSQL *gorm.DB
|
||||||
|
MongoDB *mongo.Client
|
||||||
|
Redis *redis.Client
|
||||||
|
}
|
||||||
|
|
||||||
func NewBot(settings *BotSettings) *Bot {
|
func NewBot(settings *BotSettings) *Bot {
|
||||||
updateQueue := CreateQueue[*Update](256)
|
updateQueue := CreateQueue[*Update](256)
|
||||||
bot := &Bot{
|
bot := &Bot{
|
||||||
@@ -79,6 +100,7 @@ func NewBot(settings *BotSettings) *Bot {
|
|||||||
level = DEBUG
|
level = DEBUG
|
||||||
}
|
}
|
||||||
bot.logger = CreateLogger().Level(level).OpenFile(fmt.Sprintf("%s/main.log", strings.TrimRight(settings.LoggerBasePath, "/")))
|
bot.logger = CreateLogger().Level(level).OpenFile(fmt.Sprintf("%s/main.log", strings.TrimRight(settings.LoggerBasePath, "/")))
|
||||||
|
bot.logger = bot.logger.PrintTraceback(true)
|
||||||
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").OpenFile(fmt.Sprintf("%s/requests.log", strings.TrimRight(settings.LoggerBasePath, "/")))
|
||||||
}
|
}
|
||||||
@@ -95,6 +117,19 @@ func (b *Bot) Close() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *Bot) InitDatabaseContext(ctx *DatabaseContext) *Bot {
|
||||||
|
b.dbContext = ctx
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
func (b *Bot) AddDatabaseLogger(writer func(db *DatabaseContext) LoggerWriter) *Bot {
|
||||||
|
w := []LoggerWriter{writer(b.dbContext)}
|
||||||
|
b.logger.AddWriters(w)
|
||||||
|
if b.requestLogger != nil {
|
||||||
|
b.requestLogger.AddWriters(w)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
func (b *Bot) UpdateTypes(t ...string) *Bot {
|
func (b *Bot) UpdateTypes(t ...string) *Bot {
|
||||||
b.updateTypes = make([]string, 0)
|
b.updateTypes = make([]string, 0)
|
||||||
b.updateTypes = append(b.updateTypes, t...)
|
b.updateTypes = append(b.updateTypes, t...)
|
||||||
@@ -136,6 +171,23 @@ func (b *Bot) AddPlugins(plugin ...*Plugin) *Bot {
|
|||||||
return b
|
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\" was registered", m.Name))
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
func (b *Bot) Run() {
|
func (b *Bot) Run() {
|
||||||
if len(b.prefixes) == 0 {
|
if len(b.prefixes) == 0 {
|
||||||
b.logger.Fatal("no prefixes defined")
|
b.logger.Fatal("no prefixes defined")
|
||||||
@@ -181,9 +233,13 @@ func (b *Bot) handleMessage(update *Update) {
|
|||||||
Update: update,
|
Update: update,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, middleware := range b.middlewares {
|
||||||
|
middleware.Execute(ctx, b.dbContext)
|
||||||
|
}
|
||||||
|
|
||||||
for _, plugin := range b.plugins {
|
for _, plugin := range b.plugins {
|
||||||
if plugin.UpdateListener != nil {
|
if plugin.UpdateListener != nil {
|
||||||
(*plugin.UpdateListener)(ctx)
|
(*plugin.UpdateListener)(ctx, b.dbContext)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,7 +275,7 @@ func (b *Bot) handleMessage(update *Update) {
|
|||||||
ctx.Text = strings.TrimSpace(text[len(cmd):])
|
ctx.Text = strings.TrimSpace(text[len(cmd):])
|
||||||
ctx.Args = strings.Split(ctx.Text, " ")
|
ctx.Args = strings.Split(ctx.Text, " ")
|
||||||
|
|
||||||
go plugin.Execute(cmd, ctx)
|
go plugin.Execute(cmd, ctx, b.dbContext)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -230,9 +286,14 @@ func (b *Bot) handleCallback(update *Update) {
|
|||||||
Update: update,
|
Update: update,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, m := range b.middlewares {
|
||||||
|
m.Execute(ctx, b.dbContext)
|
||||||
|
}
|
||||||
|
|
||||||
for _, plugin := range b.plugins {
|
for _, plugin := range b.plugins {
|
||||||
if plugin.UpdateListener != nil {
|
if plugin.UpdateListener != nil {
|
||||||
(*plugin.UpdateListener)(ctx)
|
lis := *plugin.UpdateListener
|
||||||
|
lis(ctx, b.dbContext)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,7 +302,7 @@ func (b *Bot) handleCallback(update *Update) {
|
|||||||
if !strings.HasPrefix(update.CallbackQuery.Data, payload) {
|
if !strings.HasPrefix(update.CallbackQuery.Data, payload) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
go plugin.ExecutePayload(payload, ctx)
|
go plugin.ExecutePayload(payload, ctx, b.dbContext)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -259,7 +320,7 @@ func (ctx *MsgContext) Answer(text string) {
|
|||||||
_, err := ctx.Bot.SendMessage(&SendMessageP{
|
_, err := ctx.Bot.SendMessage(&SendMessageP{
|
||||||
ChatID: ctx.Msg.Chat.ID,
|
ChatID: ctx.Msg.Chat.ID,
|
||||||
Text: text,
|
Text: text,
|
||||||
ParseMode: "markdown",
|
ParseMode: ParseMD,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx.Bot.logger.Error(err)
|
ctx.Bot.logger.Error(err)
|
||||||
|
|||||||
35
logger.go
35
logger.go
@@ -11,11 +11,14 @@ import (
|
|||||||
"github.com/fatih/color"
|
"github.com/fatih/color"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type LoggerWriter func(level LogLevel, prefix, traceback string, message []any)
|
||||||
|
|
||||||
type Logger struct {
|
type Logger struct {
|
||||||
prefix string
|
prefix string
|
||||||
level LogLevel
|
level LogLevel
|
||||||
printTraceback bool
|
printTraceback bool
|
||||||
printTime bool
|
printTime bool
|
||||||
|
writers []LoggerWriter
|
||||||
|
|
||||||
f *os.File
|
f *os.File
|
||||||
}
|
}
|
||||||
@@ -26,6 +29,10 @@ type LogLevel struct {
|
|||||||
c color.Attribute
|
c color.Attribute
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (l *LogLevel) GetName() string {
|
||||||
|
return l.t
|
||||||
|
}
|
||||||
|
|
||||||
type MethodTraceback struct {
|
type MethodTraceback struct {
|
||||||
Package string
|
Package string
|
||||||
Method string
|
Method string
|
||||||
@@ -36,11 +43,11 @@ type MethodTraceback struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
INFO LogLevel = LogLevel{n: 0, t: "info", c: color.FgWhite}
|
INFO = LogLevel{n: 0, t: "info", c: color.FgWhite}
|
||||||
WARN LogLevel = LogLevel{n: 1, t: "warn", c: color.FgHiYellow}
|
WARN = LogLevel{n: 1, t: "warn", c: color.FgHiYellow}
|
||||||
ERROR LogLevel = LogLevel{n: 2, t: "error", c: color.FgHiRed}
|
ERROR = LogLevel{n: 2, t: "error", c: color.FgHiRed}
|
||||||
FATAL LogLevel = LogLevel{n: 3, t: "fatal", c: color.FgRed}
|
FATAL = LogLevel{n: 3, t: "fatal", c: color.FgRed}
|
||||||
DEBUG LogLevel = LogLevel{n: 4, t: "debug", c: color.FgGreen}
|
DEBUG = LogLevel{n: 4, t: "debug", c: color.FgGreen}
|
||||||
)
|
)
|
||||||
|
|
||||||
func CreateLogger() *Logger {
|
func CreateLogger() *Logger {
|
||||||
@@ -76,6 +83,14 @@ func (l *Logger) PrintTraceback(b bool) *Logger {
|
|||||||
l.printTraceback = b
|
l.printTraceback = b
|
||||||
return l
|
return l
|
||||||
}
|
}
|
||||||
|
func (l *Logger) PrintTime(b bool) *Logger {
|
||||||
|
l.printTime = b
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
func (l *Logger) AddWriters(writers []LoggerWriter) *Logger {
|
||||||
|
l.writers = append(l.writers, writers...)
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
func (l *Logger) Info(m ...any) {
|
func (l *Logger) Info(m ...any) {
|
||||||
l.print(INFO, m)
|
l.print(INFO, m)
|
||||||
@@ -152,7 +167,15 @@ func (l *Logger) print(level LogLevel, m []any) {
|
|||||||
if l.level.n < level.n {
|
if l.level.n < level.n {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
color.New(level.c).Println(l.buildString(level, m))
|
_, err := color.New(level.c).Println(l.buildString(level, m))
|
||||||
|
if err != nil {
|
||||||
|
l.Fatal(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, writer := range l.writers {
|
||||||
|
writer(level, l.prefix, l.formatTraceback(l.getTraceback()), m)
|
||||||
|
}
|
||||||
|
|
||||||
if l.f != nil {
|
if l.f != nil {
|
||||||
if _, err := l.f.Write([]byte(l.buildString(level, m) + "\n")); err != nil {
|
if _, err := l.f.Write([]byte(l.buildString(level, m) + "\n")); err != nil {
|
||||||
|
|||||||
59
plugins.go
59
plugins.go
@@ -1,6 +1,6 @@
|
|||||||
package laniakea
|
package laniakea
|
||||||
|
|
||||||
type CommandExecutor func(ctx *MsgContext)
|
type CommandExecutor func(ctx *MsgContext, dbContext *DatabaseContext)
|
||||||
|
|
||||||
type PluginBuilder struct {
|
type PluginBuilder struct {
|
||||||
name string
|
name string
|
||||||
@@ -56,10 +56,59 @@ func (p *PluginBuilder) Build() *Plugin {
|
|||||||
return plugin
|
return plugin
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) Execute(cmd string, ctx *MsgContext) {
|
func (p *Plugin) Execute(cmd string, ctx *MsgContext, dbContext *DatabaseContext) {
|
||||||
(*p.Commands[cmd])(ctx)
|
(*p.Commands[cmd])(ctx, dbContext)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) ExecutePayload(payload string, ctx *MsgContext) {
|
func (p *Plugin) ExecutePayload(payload string, ctx *MsgContext, dbContext *DatabaseContext) {
|
||||||
(*p.Payloads[payload])(ctx)
|
(*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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
22
queue.go
22
queue.go
@@ -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
version.go
12
version.go
@@ -1,8 +1,12 @@
|
|||||||
package laniakea
|
package laniakea
|
||||||
|
|
||||||
|
import "os"
|
||||||
|
|
||||||
const (
|
const (
|
||||||
VERSION_STRING = "0.1.4"
|
VersionString = "0.1.4"
|
||||||
VERSION_MAJOR = 0
|
VersionMajor = 0
|
||||||
VERSION_MINOR = 1
|
VersionMinor = 1
|
||||||
VERSION_PATCH = 4
|
VersionPatch = 4
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var GoVersion = os.Getenv("GoV")
|
||||||
|
|||||||
Reference in New Issue
Block a user