You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.5 KiB
52 lines
1.5 KiB
package telegrampackage
|
|
|
|
import (
|
|
"fmt"
|
|
"math/rand"
|
|
"strings"
|
|
"time"
|
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type TelegramHandlerFunction func(shortCode string, text string) (handled bool, responseText *string)
|
|
|
|
type Env struct {
|
|
DB *gorm.DB
|
|
TelegramAPIKey string
|
|
HandlerFunctions []TelegramHandlerFunction
|
|
}
|
|
|
|
func NewEnv(db *gorm.DB, telegramAPIKey string, handlerFunctions []TelegramHandlerFunction) *Env {
|
|
var env Env
|
|
env.DB = db
|
|
env.TelegramAPIKey = telegramAPIKey
|
|
env.HandlerFunctions = handlerFunctions
|
|
// Example handler function
|
|
_ = env.telegramHandlerExample
|
|
|
|
// Seed random
|
|
rand.Seed(time.Now().UnixNano())
|
|
|
|
// Start listening job
|
|
go env.TelegramListenAndGen()
|
|
|
|
return &env
|
|
}
|
|
|
|
func (env *Env) AddTelegramHandlerFunc(handlerFunction TelegramHandlerFunction) {
|
|
env.HandlerFunctions = append(env.HandlerFunctions, handlerFunction)
|
|
}
|
|
|
|
// Not used normally. Shown here as example only
|
|
func (env *Env) telegramHandlerExample(shortCode string, text string) (bool, *string) {
|
|
commandSplitted := ParseTelegramBotCommand(text)
|
|
if len(commandSplitted) > 0 && commandSplitted[0] == "/command" {
|
|
responseText := fmt.Sprintf("Your short code is %s.\n\nYour message is %s", shortCode, text)
|
|
responseText = responseText + fmt.Sprintf("\n\nYour parameters are: %s", strings.Join(commandSplitted[1:], "\n - "))
|
|
responseText = "<code>" + tgbotapi.EscapeText("HTML", responseText) + "</code>"
|
|
return true, &responseText
|
|
}
|
|
return false, nil
|
|
}
|