58 lines
1.4 KiB
Go
58 lines
1.4 KiB
Go
package message
|
|
|
|
import (
|
|
"fmt"
|
|
"trbot/utils"
|
|
"trbot/utils/handler_params"
|
|
"trbot/utils/type/contain"
|
|
|
|
"github.com/go-telegram/bot/models"
|
|
)
|
|
|
|
type SlashCommand struct {
|
|
SlashCommand string // the "command" in "/command"
|
|
ForChatType []models.ChatType // default for private, group, supergroup
|
|
|
|
MessageHandler func(*handler_params.Message) error
|
|
}
|
|
|
|
type SlashCommandHandlers []SlashCommand
|
|
|
|
func (hs *SlashCommandHandlers) Add(handler SlashCommand) bool {
|
|
if handler.SlashCommand == "" {
|
|
return false
|
|
}
|
|
if handler.ForChatType == nil {
|
|
handler.ForChatType = []models.ChatType{
|
|
models.ChatTypePrivate,
|
|
models.ChatTypeGroup,
|
|
models.ChatTypeSupergroup,
|
|
}
|
|
}
|
|
*hs = append(*hs, handler)
|
|
return true
|
|
}
|
|
|
|
func (hs *SlashCommandHandlers) Remove(slashCommand string) {
|
|
for i, h := range *hs {
|
|
if h.SlashCommand == slashCommand {
|
|
*hs = append((*hs)[:i], (*hs)[i + 1:]...)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (hs *SlashCommandHandlers) RunMessage(params *handler_params.Message) (bool, error) {
|
|
for _, plugin := range *hs {
|
|
if plugin.MessageHandler == nil { continue }
|
|
if contain.AnyType(params.Message.Chat.Type, plugin.ForChatType...) && utils.CommandMaybeWithSuffixUsername(params.Fields, "/" + plugin.SlashCommand) {
|
|
err := plugin.MessageHandler(params)
|
|
if err != nil {
|
|
return true, fmt.Errorf("error in slash command handler: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
}
|
|
return false, nil
|
|
}
|