Feat(Initial): Initial Go codebase
All checks were successful
Webhook-Everything/Webhook-Everything/pipeline/head This commit looks good
All checks were successful
Webhook-Everything/Webhook-Everything/pipeline/head This commit looks good
This commit is contained in:
52
backend/internal/telegrampackage/main.go
Normal file
52
backend/internal/telegrampackage/main.go
Normal file
@@ -0,0 +1,52 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user