8 Commits

Author SHA1 Message Date
b47c979e3b pushing code for channel lockdowns
- honestly not sure if its worth adding
2025-08-13 15:42:06 -04:00
bfe9601cd3 emoji updates 2025-07-16 15:53:22 -04:00
c6d877b101 correcting unicode for built-in bolt emojis 2025-07-16 13:35:39 -04:00
3bf763f196 adding proper intents for reactions 2025-07-16 13:04:39 -04:00
8f9205fbf0 adding emojis 2025-07-15 19:06:44 -04:00
e1bae3edea adding more emojis 2025-07-10 15:36:25 -04:00
34fdf453c1 readme update 2025-07-10 14:36:21 -04:00
113c6927cb better errors
- no fatal calls
- more descriptive errors
2025-07-09 18:05:55 -04:00
4 changed files with 98 additions and 45 deletions

View File

@@ -58,7 +58,10 @@ import (
func main() { func main() {
//bolt defaults the command indicator to '.' however that can be changed with the options //bolt defaults the command indicator to '.' however that can be changed with the options
//Example: bolt.New(bolt.WithIndicator('!')) would support commands like !ping //Example: bolt.New(bolt.WithIndicator('!')) would support commands like !ping
b := bolt.New(bolt.WithLogLevel(bolt.LogLevelCmd)) b, err := bolt.New(bolt.WithLogLevel(bolt.LogLevelCmd))
if err != nil {
panic(err)
}
b.AddCommands( b.AddCommands(
// basic ping pong command, .ping can be run at anytime by anyone and will reply "pong" // basic ping pong command, .ping can be run at anytime by anyone and will reply "pong"
@@ -95,11 +98,12 @@ func main() {
) )
//start is a blocking call that handles safe-shutdown, all configuration and setup should be done before calling Start() //start is a blocking call that handles safe-shutdown, all configuration and setup should be done before calling Start()
err := b.Start() err = b.Start()
if err != nil { if err != nil {
panic(err) panic(err)
} }
} }
``` ```
## Development ## Development

87
bolt.go
View File

@@ -14,21 +14,24 @@ import (
) )
const ( const (
TOKEN_ENV_VAR = "DISCORD_TOKEN" //label for token environment variable //Discord auth token must be saved as an environment variable using this label/name
//in order for bolt to detect it
TOKEN_ENV_VAR = "DISCORD_TOKEN"
BOT_INTENTS = dg.IntentGuilds | BOT_INTENTS = dg.IntentGuilds |
dg.IntentGuildMembers | dg.IntentGuildMembers |
dg.IntentGuildPresences | dg.IntentGuildPresences |
dg.IntentMessageContent | dg.IntentMessageContent |
dg.IntentsGuildMessages dg.IntentsGuildMessages |
dg.IntentGuildMessageReactions
) )
// basic bot structure containing discordgo connection as well as the command map
type bolt struct { type bolt struct {
*dg.Session //holds discordgo internals *dg.Session //holds discordgo internals
commands map[string]Command //maps trigger phrase to command struct for fast lookup 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 indicator string //the indicator used to detect whether a message is a command
logLvl LogLevel //determines how much the bot logs logLvl LogLevel //determines how much the bot logs
channels []string //optional list of channels that the bot listens in, all channels are used if list is empty
} }
type Bolt interface { type Bolt interface {
@@ -44,20 +47,16 @@ type Bolt interface {
timeoutCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error) timeoutCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error)
} }
// setup // creates and returns a new bolt interface after ensuring token is present and applying option functions
func init() { func New(opts ...Option) (Bolt, error) {
//validate environment variables
_, check := os.LookupEnv(TOKEN_ENV_VAR) _, check := os.LookupEnv(TOKEN_ENV_VAR)
if !check { if !check {
log.Fatalf("the %s environment variable must be set", TOKEN_ENV_VAR) return nil, fmt.Errorf("environment variable %s must be set", TOKEN_ENV_VAR)
}
} }
// create a new bolt interface
func New(opts ...Option) Bolt {
bot, err := dg.New(fmt.Sprintf("Bot %s", os.Getenv(TOKEN_ENV_VAR))) bot, err := dg.New(fmt.Sprintf("Bot %s", os.Getenv(TOKEN_ENV_VAR)))
if err != nil { if err != nil {
log.Fatal(err) return nil, fmt.Errorf("failed to create Discord session: %e", err)
} }
bot.Identify.Intents = BOT_INTENTS bot.Identify.Intents = BOT_INTENTS
@@ -74,18 +73,18 @@ func New(opts ...Option) Bolt {
opt(b) opt(b)
} }
return b return b, nil
} }
// starts the bot, commands are added and the connection to Discord is opened, this is a BLOCKING // 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 // call that handles safe shutdown
func (b *bolt) Start() error { func (b *bolt) Start() error {
//register commands and open connection //registers the message handler used internally to detect commands
b.AddHandler(b.messageHandler) b.AddHandler(b.messageHandler)
err := b.Open() err := b.Open()
if err != nil { if err != nil {
return err return fmt.Errorf("failed to open websocket connection with Discord: %e", err)
} }
//safe shutdown handler //safe shutdown handler
@@ -107,22 +106,40 @@ func (b *bolt) stop() error {
// adds commands to bot command map for use // adds commands to bot command map for use
func (b *bolt) AddCommands(cmd ...Command) { func (b *bolt) AddCommands(cmd ...Command) {
//command trigger words are mapped directly to payload functions to prevent
//extra loops when searching for the appropriate payload
for _, c := range cmd { for _, c := range cmd {
b.commands[c.Trigger] = c b.commands[c.Trigger] = c
} }
} }
// handler function that parses message data and executes any command payloads // internal message handler function. Ensure's the message is a message the bot should interpret
// and checks to see if it contains a command then executes the proper payload function
func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) { func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
//get server information //get channel name to, idk if i like this
server, err := s.Guild(msg.GuildID)
if err != nil {
log.Println(err)
return
}
channel, err := s.Channel(msg.ChannelID) channel, err := s.Channel(msg.ChannelID)
if err != nil { if err != nil {
log.Println(err) log.Printf("failed to get channel from guild: %e\n", err)
return
}
if len(b.channels) > 0 {
var check bool
for _, c := range b.channels {
if channel.Name == c {
check = true
}
}
//not a channel we care about
if !check {
return
}
}
server, err := s.Guild(msg.GuildID)
if err != nil {
log.Printf("failed to get guild: %e\n", err)
return return
} }
@@ -132,20 +149,20 @@ func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
msg.Content = "[Embedded Content]" msg.Content = "[Embedded Content]"
} }
if b.logLvl == LogLevelAll {
//log message
log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content)
}
//the bot will ignore it's own messages to prevent command loops //the bot will ignore it's own messages to prevent command loops
if msg.Author.ID == s.State.User.ID { if msg.Author.ID == s.State.User.ID {
if b.logLvl == LogLevelCmd { if b.logLvl == LogLevelCmd {
//log commands //log command responses
log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content) log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content)
} }
return 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 //does the message have the command indicator
lg := len(b.indicator) lg := len(b.indicator)
if msg.Content[:lg] == b.indicator { if msg.Content[:lg] == b.indicator {
@@ -173,7 +190,7 @@ func (b *bolt) handleCommand(msg *dg.MessageCreate, s *dg.Session, server *dg.Gu
//has command met its timeout requirements //has command met its timeout requirements
tc, err := b.timeoutCheck(msg, s, run) tc, err := b.timeoutCheck(msg, s, run)
if err != nil { if err != nil {
return err return fmt.Errorf("failed to calculate timeout for %s\n%e", run.Trigger, err)
} }
if !tc { if !tc {
return nil return nil
@@ -183,7 +200,7 @@ func (b *bolt) handleCommand(msg *dg.MessageCreate, s *dg.Session, server *dg.Gu
if run.Roles != nil { if run.Roles != nil {
check, err := b.roleCheck(msg, s, run) check, err := b.roleCheck(msg, s, run)
if err != nil { if err != nil {
return err return fmt.Errorf("failed to perform permission checks for %s\n%e", run.Trigger, err)
} }
if !check { if !check {
return nil return nil
@@ -226,7 +243,7 @@ func (b *bolt) handleCommand(msg *dg.MessageCreate, s *dg.Session, server *dg.Gu
//run command payload //run command payload
err = run.Payload(plMsg) err = run.Payload(plMsg)
if err != nil { if err != nil {
return err return fmt.Errorf("failed to execute payload function: %e", err)
} }
//update run time //update run time
@@ -279,7 +296,7 @@ func (b *bolt) roleCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (boo
//get role name from ID //get role name from ID
n, err := s.State.Role(msg.GuildID, r) n, err := s.State.Role(msg.GuildID, r)
if err != nil { if err != nil {
return false, err return false, fmt.Errorf("failed to get role from ID %s\n%e", msg.GuildID, err)
} }
//does this role exist in command roles //does this role exist in command roles
check := slices.Contains(run.Roles, n.Name) check := slices.Contains(run.Roles, n.Name)
@@ -294,7 +311,7 @@ func (b *bolt) roleCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (boo
reply := b.createReply("you do not have permissions to run that command", msg.ID, msg.ChannelID, msg.GuildID) reply := b.createReply("you do not have permissions to run that command", msg.ID, msg.ChannelID, msg.GuildID)
_, err := s.ChannelMessageSendComplex(msg.ChannelID, reply) _, err := s.ChannelMessageSendComplex(msg.ChannelID, reply)
if err != nil { if err != nil {
return false, err return false, fmt.Errorf("failed to send permission response: %e", err)
} }
return false, nil return false, nil
} }
@@ -309,7 +326,7 @@ func (b *bolt) timeoutCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (
reply := b.createReply(fmt.Sprintf("that command cannot be run for another %s", b.getRemainingTimeout(wait)), msg.ID, msg.ChannelID, msg.GuildID) reply := b.createReply(fmt.Sprintf("that command cannot be run for another %s", b.getRemainingTimeout(wait)), msg.ID, msg.ChannelID, msg.GuildID)
_, err := s.ChannelMessageSendComplex(msg.ChannelID, reply) _, err := s.ChannelMessageSendComplex(msg.ChannelID, reply)
if err != nil { if err != nil {
return false, err return false, fmt.Errorf("failed to send timeout response: %e", err)
} }
return false, nil return false, nil
} }

View File

@@ -5,15 +5,40 @@ import "fmt"
//built-in Discord reactions //built-in Discord reactions
type Reaction string type Reaction string
//a few easy-to-use emojis, Discordgo/Discord API requires them to be saved like this.
const ( const (
ReactionThumbsUp Reaction = ":+1:" ReactionThumbsUp Reaction = "👍"
ReactionThumbsDown Reaction = ":-1:" ReactionThumbsDown Reaction = "👎"
ReactionPointUp Reaction = ":point_up:" ReactionHundred Reaction = "💯"
ReactionPointDown Reaction = ":point_down:" ReactionHeart Reaction = "❤️"
ReactionHotdog Reaction = ":hotdog:" ReactionPinkHeart Reaction = "🩷"
ReactionGiraffe Reaction = ":giraffe:" ReactionOrangeHeart Reaction = "🧡"
ReactionWatermelon Reaction = ":watermelon:" ReactionYellowHeart Reaction = "💛"
ReactionNoPedestrians Reaction = ":no_pedestrian:" ReactionGreenHeart Reaction = "💚"
ReactionBlueHeart Reaction = "💙"
ReactionBlackHeart Reaction = "🖤"
ReactionPointUp Reaction = "☝️"
ReactionPointDown Reaction = "👇"
ReactionHotdog Reaction = "🌭"
ReactionDog Reaction = "🐶"
ReactionCat Reaction = "🐱"
ReactionMonkey Reaction = "🐒"
ReactionGiraffe Reaction = "🦒"
ReactionDuck Reaction = "🦆"
ReactionGoose Reaction = "🪿"
ReactionWatermelon Reaction = "🍉"
ReactionHoney Reaction = "🍯"
ReactionSandwich Reaction = "🥪"
ReactionPepper Reaction = "🌶️"
ReactionNoPedestrians Reaction = "🚷"
ReactionExclamation Reaction = "❗"
ReactionDoubleExclamation Reaction = "‼️"
ReactionSkull Reaction = "💀"
ReactionSpeakingHead Reaction = "🗣️"
ReactionGreenCheck Reaction = "✅"
ReactionDragon Reaction = "🐉"
ReactionLizard Reaction = "🦎"
ReactionTakeAKnee Reaction = "🧎‍♂️‍➡️"
) )
// information about attachments to messages // information about attachments to messages

View File

@@ -23,3 +23,10 @@ func WithLogLevel(lvl LogLevel) Option {
b.logLvl = lvl b.logLvl = lvl
} }
} }
// restrict the channels the bot listens in and responds to, must be a list of channel names
func WithListenChannels(channels []string) Option {
return func(b *bolt) {
b.channels = channels
}
}