bolt/bolt.go

359 lines
9.5 KiB
Go
Raw Normal View History

2025-06-04 16:00:53 -04:00
package bolt
import (
2025-08-17 20:37:22 -04:00
"errors"
2025-06-04 16:00:53 -04:00
"fmt"
"log"
"os"
"os/signal"
"slices"
2025-06-04 16:00:53 -04:00
"strings"
"syscall"
2025-06-04 16:00:53 -04:00
"time"
dg "github.com/bwmarrin/discordgo"
)
const (
TOKEN_ENV_VAR = "DISCORD_TOKEN" //label for token environment variable
BOT_INTENTS = dg.IntentGuilds |
dg.IntentGuildMembers |
2025-06-04 16:00:53 -04:00
dg.IntentGuildPresences |
2025-06-04 16:18:18 -04:00
dg.IntentMessageContent |
2025-07-16 13:04:39 -04:00
dg.IntentsGuildMessages |
dg.IntentGuildMessageReactions
2025-06-04 16:00:53 -04:00
)
// basic bot structure containing discordgo connection as well as the command map
type bolt struct {
*dg.Session //holds discordgo internals
commands map[string]Command //maps trigger phrase to command struct for fast lookup
indicator string //the indicator used to detect whether a message is a command
logLvl LogLevel //determines how much the bot logs
2025-06-04 16:00:53 -04:00
}
type Bolt interface {
Start() error
2025-06-07 00:34:26 -04:00
AddCommands(cmd ...Command)
//filtered methods
stop() error
2025-06-04 16:00:53 -04:00
messageHandler(s *dg.Session, msg *dg.MessageCreate)
2025-08-17 20:37:22 -04:00
handleCommand(msgEvent *MessageCreateEvent, s *dg.Session, lg int) error
2025-06-04 16:00:53 -04:00
createReply(content, message, channel, guild string) *dg.MessageSend
getRemainingTimeout(timeout time.Time) string
2025-08-17 20:37:22 -04:00
roleCheck(guild string, roles []string, s *dg.Session, run Command) (bool, error)
timeoutCheck(msgID, channelID, guildID string, s *dg.Session, run Command) (bool, error)
joinUserVoice(guild, user string, s *dg.Session) (*dg.VoiceConnection, error)
2025-06-04 16:00:53 -04:00
}
// create a new bolt interface
func New(opts ...Option) (Bolt, error) {
2025-06-04 16:00:53 -04:00
_, check := os.LookupEnv(TOKEN_ENV_VAR)
if !check {
return nil, fmt.Errorf("environment variable %s must be set", TOKEN_ENV_VAR)
2025-06-04 16:00:53 -04:00
}
bot, err := dg.New(fmt.Sprintf("Bot %s", os.Getenv(TOKEN_ENV_VAR)))
if err != nil {
return nil, fmt.Errorf("failed to create Discord session: %e", err)
2025-06-04 16:00:53 -04:00
}
bot.Identify.Intents = BOT_INTENTS
b := &bolt{
2025-06-04 16:08:35 -04:00
Session: bot,
commands: make(map[string]Command, 0),
logLvl: LogLevelAll,
2025-06-04 16:00:53 -04:00
}
//set default command indicator
b.indicator = "."
2025-08-17 20:37:22 -04:00
//apply options
for _, opt := range opts {
opt(b)
}
return b, nil
2025-06-04 16:00:53 -04:00
}
2025-08-17 20:37:22 -04:00
// starts the bot, commands are added and the connection to Discord is opened, this is a BLOCKING call
// that handles safe shutdown of the bot
2025-06-04 16:00:53 -04:00
func (b *bolt) Start() error {
//register commands and open connection
b.AddHandler(b.messageHandler)
err := b.Open()
if err != nil {
return fmt.Errorf("failed to open websocket connection with Discord: %e", err)
}
2025-06-07 09:31:00 -04:00
//safe shutdown handler
sigChannel := make(chan os.Signal, 1)
signal.Notify(sigChannel, syscall.SIGINT)
<-sigChannel
if err := b.stop(); err != nil {
return err
}
return nil
2025-06-04 16:00:53 -04:00
}
// stops the bot
func (b *bolt) stop() error {
2025-06-04 16:00:53 -04:00
return b.Close()
}
// adds commands to bot command map for use
func (b *bolt) AddCommands(cmd ...Command) {
for _, c := range cmd {
b.commands[c.Trigger] = c
2025-06-04 16:00:53 -04:00
}
}
2025-08-17 20:37:22 -04:00
// handler function that parses message data, handles logging the message based on logLevel, and executes
// the payload function in a goroutine
2025-06-04 16:00:53 -04:00
func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
//get server information
server, err := s.Guild(msg.GuildID)
if err != nil {
log.Printf("failed to get guild: %e\n", err)
2025-06-04 16:00:53 -04:00
return
}
channel, err := s.Channel(msg.ChannelID)
if err != nil {
log.Printf("failed to get channel from guild: %e\n", err)
2025-06-04 16:00:53 -04:00
return
}
//if there is no content it is likely an image, gif, or sticker, updating message content for
2025-06-04 16:00:53 -04:00
//better logging and to avoid confusion
if len(msg.Content) == 0 {
msg.Content = "[Embedded Content]"
2025-06-04 16:00:53 -04:00
}
//the bot will ignore it's own messages to prevent command loops
if msg.Author.ID == s.State.User.ID {
2025-08-17 20:37:22 -04:00
if b.logLvl == LogLevelCmd || b.logLvl == LogLevelAll {
//log command responses
log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content)
}
2025-06-04 16:00:53 -04:00
return
}
if b.logLvl == LogLevelAll {
//log message
log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content)
}
//does the message have the command indicator
lg := len(b.indicator)
if msg.Content[:lg] == b.indicator {
2025-08-17 20:37:22 -04:00
mCreate := &MessageCreateEvent{
AuthorUsername: msg.Author.Username,
AuthorID: msg.Author.ID,
AuthorRoles: msg.Member.Roles,
MsgID: msg.ID,
Msg: msg.Content,
MsgChanID: msg.ChannelID,
MsgGuildID: msg.GuildID,
MsgAttachments: msg.Attachments,
}
if b.logLvl == LogLevelCmd {
//log commands
log.Printf("< %s | %s | %s > %s\n", mCreate.MsgGuildName, mCreate.MsgChanName, mCreate.AuthorUsername, mCreate.Msg)
2025-06-04 16:00:53 -04:00
}
2025-08-17 20:37:22 -04:00
//handled in its own goroutine to allow for async commands
go func() {
err := b.handleCommand(mCreate, s, lg)
if err != nil {
log.Println(err)
}
}()
2025-06-07 00:34:26 -04:00
}
}
2025-06-04 16:00:53 -04:00
2025-06-07 00:34:26 -04:00
// parses command from message and handles timeout checks, role checks, and command execution. All command responses are sent back to Discord
2025-08-17 20:37:22 -04:00
func (b *bolt) handleCommand(msgEvent *MessageCreateEvent, s *dg.Session, lg int) error {
words := strings.Split(msgEvent.Msg, " ")
run, ok := b.commands[words[0][lg:]]
2025-06-07 00:34:26 -04:00
if !ok {
return nil //command doesn't exist, maybe log or respond to author
}
2025-06-07 00:34:26 -04:00
//has command met its timeout requirements
2025-08-17 20:37:22 -04:00
tc, err := b.timeoutCheck(msgEvent.MsgID, msgEvent.MsgChanID, msgEvent.MsgGuildID, s, run)
2025-06-07 00:34:26 -04:00
if err != nil {
return fmt.Errorf("failed to calculate timeout for %s\n%e", run.Trigger, err)
2025-06-07 00:34:26 -04:00
}
if !tc {
return nil
}
2025-06-04 16:00:53 -04:00
2025-06-07 00:34:26 -04:00
//does user have correct permissions
if run.Roles != nil {
2025-08-17 20:37:22 -04:00
check, err := b.roleCheck(msgEvent.MsgGuildID, msgEvent.AuthorRoles, s, run)
2025-06-04 16:00:53 -04:00
if err != nil {
return fmt.Errorf("failed to perform permission checks for %s\n%e", run.Trigger, err)
2025-06-04 16:00:53 -04:00
}
2025-06-07 00:34:26 -04:00
if !check {
2025-08-17 20:37:22 -04:00
reply := b.createReply("you do not have permissions to run that command", msgEvent.MsgID, msgEvent.MsgChanID, msgEvent.MsgGuildID)
_, err := s.ChannelMessageSendComplex(msgEvent.MsgChanID, reply)
if err != nil {
return err
}
2025-06-07 00:34:26 -04:00
return nil
2025-06-04 16:00:53 -04:00
}
2025-06-07 00:34:26 -04:00
}
2025-08-17 20:37:22 -04:00
//populate message struct exposed to client
plMsg := Message{
2025-08-17 20:37:22 -04:00
Author: msgEvent.AuthorUsername,
ID: msgEvent.AuthorID,
msgID: msgEvent.MsgID,
Words: words,
2025-08-17 20:37:22 -04:00
Content: msgEvent.Msg,
Channel: msgEvent.MsgChanName,
channelID: msgEvent.MsgChanID,
Server: msgEvent.MsgGuildName,
serverID: msgEvent.MsgGuildID,
sesh: b,
}
//check for file attachments
2025-08-17 20:37:22 -04:00
if len(msgEvent.MsgAttachments) > 0 {
var att []MessageAttachment
2025-08-17 20:37:22 -04:00
for _, a := range msgEvent.MsgAttachments {
att = append(att, MessageAttachment{
ID: a.ID,
URL: a.URL,
ProxyURL: a.ProxyURL,
Filename: a.Filename,
ContentType: a.ContentType,
Width: a.Width,
Height: a.Height,
Size: a.Size,
DurationSecs: a.DurationSecs,
})
}
2025-06-07 00:34:26 -04:00
plMsg.Attachments = att
2025-06-07 00:34:26 -04:00
}
2025-06-04 16:07:09 -04:00
//run command payload
err = run.Payload(plMsg)
if err != nil {
return fmt.Errorf("failed to execute payload function: %e", err)
2025-06-04 16:00:53 -04:00
}
2025-06-07 00:34:26 -04:00
//update run time
run.lastRun = time.Now()
b.commands[run.Trigger] = run
2025-06-07 00:34:26 -04:00
return nil
2025-06-04 16:00:53 -04:00
}
// basic wrapper function to create easy Discord responses
func (b *bolt) createReply(content, message, channel, guild string) *dg.MessageSend {
details := &dg.MessageReference{
MessageID: message,
ChannelID: channel,
GuildID: guild,
}
return &dg.MessageSend{
Content: content,
Reference: details,
}
}
// used to calculate the remaining time left in a timeout and returning it in a human-readable format
func (b *bolt) getRemainingTimeout(timeout time.Time) string {
r := time.Until(timeout)
var (
timeLeft int
metric string
)
timeLeft = int(r.Hours())
metric = "h"
if timeLeft < 1 {
timeLeft = int(r.Minutes())
metric = "m"
if timeLeft < 1 {
timeLeft = int(r.Seconds())
metric = "s"
}
}
return fmt.Sprintf("%d%s", timeLeft, metric)
}
2025-06-07 00:34:26 -04:00
// checks if the author of msg has the correct role to run the requested command
2025-08-17 20:37:22 -04:00
func (b *bolt) roleCheck(guild string, roles []string, s *dg.Session, run Command) (bool, error) {
2025-06-07 00:34:26 -04:00
var found bool
2025-06-07 09:31:00 -04:00
//loop thru author roles, there may be a better way to check for this UNION
//TODO: improve role search performance to support bigger lists
2025-08-17 20:37:22 -04:00
for _, r := range roles {
2025-06-07 00:34:26 -04:00
//get role name from ID
2025-08-17 20:37:22 -04:00
n, err := s.State.Role(guild, r)
2025-06-07 00:34:26 -04:00
if err != nil {
2025-08-17 20:37:22 -04:00
return false, fmt.Errorf("failed to get role from ID %s\n%e", guild, err)
2025-06-07 00:34:26 -04:00
}
//does this role exist in command roles
check := slices.Contains(run.Roles, n.Name)
if check {
found = true
break
}
}
2025-08-17 20:37:22 -04:00
//can't find role, don't run command
2025-06-07 00:34:26 -04:00
if !found {
return false, nil
}
return true, nil
}
// check if the command timeout has been met, responding with remaining time if timeout has not been met yet.
2025-08-17 20:37:22 -04:00
func (b *bolt) timeoutCheck(msgID, channelID, guildID string, s *dg.Session, run Command) (bool, error) {
2025-06-07 00:34:26 -04:00
wait := run.lastRun.Add(run.Timeout)
if !time.Now().After(wait) {
2025-08-17 20:37:22 -04:00
reply := b.createReply(fmt.Sprintf("that command cannot be run for another %s", b.getRemainingTimeout(wait)), msgID, channelID, guildID)
_, err := s.ChannelMessageSendComplex(channelID, reply)
2025-06-07 00:34:26 -04:00
if err != nil {
return false, fmt.Errorf("failed to send timeout response: %e", err)
2025-06-07 00:34:26 -04:00
}
return false, nil
}
return true, nil
}
2025-08-17 20:37:22 -04:00
func (b *bolt) joinUserVoice(guild, user string, s *dg.Session) (*dg.VoiceConnection, error) {
g, err := s.State.Guild(guild)
if err != nil {
return nil, err
}
var chanID string
for _, x := range g.VoiceStates {
if user == x.UserID {
chanID = x.ChannelID
}
}
if chanID == "" {
return nil, errors.New("user is not in a voice channel")
}
//joining voice channel: false = not muted, true = deafened
dgv, err := s.ChannelVoiceJoin(guild, chanID, false, true)
if err != nil {
return nil, err
}
return dgv, nil
}