1 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
9 changed files with 294 additions and 473 deletions

2
.gitignore vendored
View File

@@ -25,5 +25,3 @@ go.work.sum
# env file # env file
.env .env
/cmd/*
/cmd

124
README.md
View File

@@ -1,96 +1,103 @@
# bolt # bolt
A fast [discordgo](https://github.com/bwmarrin/discordgo) wrapper for bootstrapping Discord bots. The nuts-and-bolts of Discord bots. Bolt is a wrapper for [discordgo](https://github.com/bwmarrin/discordgo) that provides quick and easy bootstrapping for simple Discord bots.
## Usage ## Usage
### Prerequisites ### Token
Bolt requires a Discord bot token to run, the token must be set as an environment variable labeled "DISCORD_TOKEN" Bolt requires a Discord bot token to run, the token must be set as an environment variable labeled "DISCORD_TOKEN"
### Commands
Commands are represented by the command struct and contain all needed information for bolt to handle the command payload. Including the command timeout as well as the Roles allowed to run the command.
```go
type Command struct {
Trigger string //command that triggers payload NOT including the indicator
Payload Payload //payload function to run when a command is detected
Timeout time.Duration //the amount of time before command can be run again
lastRun time.Time //timestamp of last command run
Roles []string //roles that can use command, if none are set anyone can run
}
```
### Payload
Payload functions are executed when a command is detected
```go
type Payload func(msg Message) error
```
Payload functions are given a Message argument containing the needed data for handling commands
```go
type Message struct {
Author string //username of message author
ID string //discord ID of message author
Words []string //words from message split on whitespace
Content string //entire message content
Channel string //message channel
Server string //message guild
Attachments []MessageAttachment //message attachments
}
```
The Message struct also exposes some methods to support replying to, or acknowledging command messages
```go
func (m *Message) React(emoji Reaction) error
```
The React method will react to the command message by adding the requested emoji as a reaction. Bolt comes with a few preset emoji's for easy handling but any valid emoji string can be passed.
```go
func (m *Message) Respond(res string) error
```
The Respond method will send the value of <b>res</b> in response to the command message.
### Example ### Example
```go ```go
package main package main
import ( import (
"fmt"
"strings"
"time" "time"
"code.jakeyoungdev.com/jake/bolt" "code.jakeyoungdev.com/jake/bolt"
_ "github.com/joho/godotenv/autoload"
) )
/*
A basic example of a bot with two commands and a general message handler for non-command messages. The bot uses a
verbose log level which will log everything for debugging purposes, and registers Discord Intents for message and admin
related permissions. This allows the bot to parse messages, send them, delete them, etc. as well as timeout and mute users.
This example registers three commands:
1. .ping - a basic ping/pong command that can be run by anyone at any time
2. .wait - a dummy command that replies "okay" it can only be run by users with the "user" role and can only be ran once every 25 seconds
3. .timeout - a admin command that can only be run by users with an "admin" role, this command will timeout any mentioned users for 5 minutes
A message handler is also registered in this example, message handlers are used to handle messages that do not contain a command. This enables
auto-moderation from the bot without manual intervention. The example message handler does two arbitrary things to demo functionality:
1. Checks the message content for the phrase "swear word" and, if found, times the user out for 5 minutes
2. Checks the message for the phrase "im going to yell in VoiceChat" and mutes the message author until Unmute is called on them
*/
func main() { func main() {
b, err := bolt.New(bolt.WithLogLevel(bolt.LogLevelAll)) //bolt defaults the command indicator to '.' however that can be changed with the options
//Example: bolt.New(bolt.WithIndicator('!')) would support commands like !ping
b, err := bolt.New(bolt.WithLogLevel(bolt.LogLevelCmd))
if err != nil { if err != nil {
panic(err) panic(err)
} }
b.AddCommands( b.AddCommands(
// basic ping pong command, .ping can be run at anytime by anyone and will reply "pong"
bolt.Command{ bolt.Command{
Trigger: "ping", Trigger: "ping",
Payload: func(c *bolt.Context) error { Payload: func(msg bolt.Message) error {
return c.Respond("pong") return msg.Respond("pong")
}, },
}, },
// .react will add a +1 reaction to the command message, .react can be run by anyone at any rate
bolt.Command{ bolt.Command{
Trigger: "wait", Trigger: "react",
Payload: func(c *bolt.Context) error { Payload: func(msg bolt.Message) error {
return c.Respond("okay") return msg.React(bolt.ReactionThumbsUp)
},
},
// .time responds with the current date/time, .time can be run once every 25 seconds by any role
bolt.Command{
Trigger: "time",
Payload: func(msg bolt.Message) error {
return msg.Respond(time.Now().String())
}, },
Timeout: time.Second * 25, Timeout: time.Second * 25,
Roles: []string{"user"},
}, },
// .role command can be ran every 10 seconds by anyone with the admin role and will return the string "admin"
bolt.Command{ bolt.Command{
Trigger: "timeout", Trigger: "role",
Payload: func(c *bolt.Context) error { Payload: func(msg bolt.Message) error {
if len(c.Message.Mentions) > 0 { return msg.Respond("admin")
count := 0
for _, m := range c.Message.Mentions {
err := c.Timeout(m.ID, time.Now().Add(time.Minute*5))
if err != nil {
return err
}
count++
}
return c.Respond(fmt.Sprintf("timed out %d users\n", count))
}
return nil
}, },
Timeout: time.Second * 10,
Roles: []string{"admin"}, Roles: []string{"admin"},
}, },
) )
b.AddMessageHandler(func(c *bolt.Context) error { //start is a blocking call that handles safe-shutdown, all configuration and setup should be done before calling Start()
if strings.Contains(c.Message.Content, "swear word") {
return c.Timeout(c.Message.Author.ID, time.Now().Add(time.Hour*1))
}
if c.Message.Content == "im going to yell in VoiceChat" {
return c.Mute(c.Message.Author.ID)
}
return nil
})
err = b.Start() err = b.Start()
if err != nil { if err != nil {
panic(err) panic(err)
@@ -100,5 +107,4 @@ func main() {
``` ```
## Development ## Development
bolt is in early development and may encounter breaking changes until a full v1 rollout, I will do my best to communicate bolt is in development at the moment and may break occasionally before a v1 release
these changes. Use a tagged version to avoid any surprises with live code in main

352
bolt.go
View File

@@ -1,33 +1,24 @@
package bolt package bolt
import ( import (
"context"
"fmt" "fmt"
"log" "log"
"os" "os"
"os/signal" "os/signal"
"slices" "slices"
"strings" "strings"
"sync" "syscall"
"time" "time"
dg "github.com/bwmarrin/discordgo" dg "github.com/bwmarrin/discordgo"
) )
const ( const (
//the name of the environment variable that should contain the token for the bot, it is //Discord auth token must be saved as an environment variable using this label/name
//required for bolt to run //in order for bolt to detect it
TOKEN_ENV_VAR = "DISCORD_TOKEN" TOKEN_ENV_VAR = "DISCORD_TOKEN"
//bot default command indicator, if messages begin with this substring they are processed BOT_INTENTS = dg.IntentGuilds |
//through the command handler instead of the generic message handler
DEFAULT_INDICATOR = "."
//max amount of concurrent goroutines that bolt can use for events. A lower amount
//may lower the resource usage of bolt but may cause a delay in event handling
DEFAULT_MAX_GOROUTINES = 250
//minimum intents for bots to function, intents can be changed with options
DEFAULT_INTENTS = dg.IntentGuilds |
dg.IntentGuildMembers | dg.IntentGuildMembers |
dg.IntentGuildPresences | dg.IntentGuildPresences |
dg.IntentMessageContent | dg.IntentMessageContent |
@@ -36,41 +27,27 @@ const (
) )
type bolt struct { type bolt struct {
//discordgo internals *dg.Session //holds discordgo internals
*dg.Session commands map[string]Command //maps trigger phrase to command struct for fast lookup
//maps trigger phrase to command struct for instant lookup indicator string //the indicator used to detect whether a message is a command
commands map[string]Command logLvl LogLevel //determines how much the bot logs
//used to detect whether a message is a command channels []string //optional list of channels that the bot listens in, all channels are used if list is empty
indicator string
//verbosity of logs bolt outputs
logLvl LogLevel
//waitgroup for event routines
wg sync.WaitGroup
//pool is a buffered channel used as a semaphore for event handler routines, it is limited to
//only spawn maxRoutines to handle events
pool chan struct{}
maxRoutines int
//generic message handler func
msgHandlerf Payload
} }
type Bolt interface { type Bolt interface {
Start() error Start() error
AddCommands(cmd ...Command) AddCommands(cmd ...Command)
AddMessageHandler(p Payload)
//filtered methods //filtered methods
stop() error stop() error
msgEventHandler(s *dg.Session, msg *dg.MessageCreate) messageHandler(s *dg.Session, msg *dg.MessageCreate)
mapEventToMsg(msg *dg.MessageCreate, channel *dg.Channel, server *dg.Guild) Message handleCommand(msg *dg.MessageCreate, s *dg.Session, server *dg.Guild, channel *dg.Channel, lg int) error
handleCommand(msgEvent *Message, lg int) error
handleMessage(event *Message) error
createReply(content, message, channel, guild string) *dg.MessageSend createReply(content, message, channel, guild string) *dg.MessageSend
remainingTimeout(timeout time.Time) string getRemainingTimeout(timeout time.Time) string
roleCheck(guild string, roles []string, s *dg.Session, run Command) (bool, error) roleCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error)
timeoutCheck(msgID, channelID, guildID string, s *dg.Session, run Command) (bool, error) timeoutCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error)
} }
// New creates a new bolt instance and applies any supplied options // creates and returns a new bolt interface after ensuring token is present and applying option functions
func New(opts ...Option) (Bolt, error) { func New(opts ...Option) (Bolt, error) {
_, check := os.LookupEnv(TOKEN_ENV_VAR) _, check := os.LookupEnv(TOKEN_ENV_VAR)
if !check { if !check {
@@ -81,165 +58,169 @@ func New(opts ...Option) (Bolt, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create Discord session: %e", err) return nil, fmt.Errorf("failed to create Discord session: %e", err)
} }
bot.Identify.Intents = BOT_INTENTS
b := &bolt{ b := &bolt{
Session: bot, Session: bot,
commands: make(map[string]Command, 0), commands: make(map[string]Command, 0),
logLvl: LogLevelAll, logLvl: LogLevelAll,
indicator: DEFAULT_INDICATOR,
wg: sync.WaitGroup{},
maxRoutines: DEFAULT_MAX_GOROUTINES,
} }
//set default command indicator
b.indicator = "."
b.Identify.Intents = DEFAULT_INTENTS //apply options to bolt
for _, opt := range opts { for _, opt := range opts {
opt(b) opt(b)
} }
//options can change max routine number, so create after
b.pool = make(chan struct{}, b.maxRoutines)
return b, nil return b, nil
} }
// Start applies the message event handler function to the bot and opens the initial websocket connection // starts the bot, commands are added and the connection to Discord is opened, this is a BLOCKING
// with Discord. Start is a blocking call that also handles safe shutdown, on Interrupt, bolt will give // call that handles safe shutdown
// command routines a window to finish before closing the connection.
func (b *bolt) Start() error { func (b *bolt) Start() error {
b.AddHandler(b.msgEventHandler) //registers the message handler used internally to detect commands
b.AddHandler(b.messageHandler)
err := b.Open() err := b.Open()
if err != nil { if err != nil {
return fmt.Errorf("failed to open websocket connection with Discord: %e", err) return fmt.Errorf("failed to open websocket connection with Discord: %e", err)
} }
log.Println("bot started") //safe shutdown handler
sigChannel := make(chan os.Signal, 1) sigChannel := make(chan os.Signal, 1)
signal.Notify(sigChannel, os.Interrupt) signal.Notify(sigChannel, syscall.SIGINT)
<-sigChannel <-sigChannel
//give handler routines a 5 second window to finish processes before closing connection if err := b.stop(); err != nil {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) return err
defer cancel()
closeChan := make(chan struct{}, 0)
go func() {
b.wg.Wait()
close(closeChan)
}()
select {
case <-ctx.Done():
log.Println("shutdown timed out waiting for handlers to finish, some may have been incomplete")
case <-closeChan:
log.Println("handler routines cleaned")
} }
log.Println("exiting") return nil
return b.stop()
} }
// AddCommands registers command handlers. Any messages that begin with the command indicator will be forwarded // stops the bot
// to the handler func (b *bolt) stop() error {
return b.Close()
}
// 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
} }
} }
// AddMessageHandler registers the generic message handler, any messages that are not commands will be forwarded // internal message handler function. Ensure's the message is a message the bot should interpret
// to the handler // and checks to see if it contains a command then executes the proper payload function
func (b *bolt) AddMessageHandler(p Payload) { func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
b.msgHandlerf = p //get channel name to, idk if i like this
}
// stop closes the websocket connection to Discord
func (b *bolt) stop() error {
return b.Close()
}
// msgEventHandler is a beefy boy that handles message logging, command parsing, and executing payload functions. It needs cleanup then
// i'll worry about this comment
// msgEventHandler handles the routing of messages to either the command or message handlers. If LogLvl is set, logging is handled here before
// the event is mapped to the Message struct and forwarded to the handlers. Each message is handled in its own goroutine, the max allowed goroutines
// is set as a default and can be altered using options for better performance.
func (b *bolt) msgEventHandler(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)
return
}
channel, err := s.Channel(msg.ChannelID) channel, err := s.Channel(msg.ChannelID)
if err != nil { if err != nil {
log.Printf("failed to get channel from guild: %e\n", err) log.Printf("failed to get channel from guild: %e\n", err)
return 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
}
//if there is no content it is likely an image, gif, or sticker, updating message content for
//better logging and to avoid confusion
if len(msg.Content) == 0 {
msg.Content = "[Embedded 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 != LogLevelErr { if b.logLvl == LogLevelCmd {
//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 { if b.logLvl == LogLevelAll {
//log message
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)
} }
m := b.mapEventToMsg(msg, channel, server) //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 {
err := b.handleCommand(msg, s, server, channel, lg)
if err != nil {
log.Println(err)
return
}
}
}
// parses command from message and handles timeout checks, role checks, and command execution. All command responses are sent back to Discord
func (b *bolt) handleCommand(msg *dg.MessageCreate, s *dg.Session, server *dg.Guild, channel *dg.Channel, lg int) error {
if b.logLvl == LogLevelCmd { if b.logLvl == LogLevelCmd {
log.Printf("< %s | %s | %s > %s\n", m.Server, m.Channel, m.Author.Name, m.Content) //log commands
log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content)
} }
b.pool <- struct{}{} //'aquire' a routine words := strings.Split(msg.Content, " ")
b.wg.Go(func() { run, ok := b.commands[words[0][lg:]]
err := b.handleCommand(&m, lg) if !ok {
if err != nil { return nil //command doesn't exist, maybe log or respond to author
log.Println(err)
} }
<-b.pool //release routine
}) //has command met its timeout requirements
} else { tc, err := b.timeoutCheck(msg, s, run)
b.pool <- struct{}{} //'aquire' a routine
b.wg.Go(func() {
err := b.handleMessage(&m)
if err != nil { if err != nil {
log.Println(err) return fmt.Errorf("failed to calculate timeout for %s\n%e", run.Trigger, err)
} }
<-b.pool //release routine if !tc {
}) return nil
}
//does user have correct permissions
if run.Roles != nil {
check, err := b.roleCheck(msg, s, run)
if err != nil {
return fmt.Errorf("failed to perform permission checks for %s\n%e", run.Trigger, err)
}
if !check {
return nil
} }
} }
// mapEventToMsg maps the Discord event message struct into bolt's user-friendly Message struct plMsg := Message{
func (b *bolt) mapEventToMsg(msg *dg.MessageCreate, channel *dg.Channel, server *dg.Guild) Message { Author: msg.Author.Username,
m := Message{
Author: Author{
Name: msg.Author.Username,
ID: msg.Author.ID, ID: msg.Author.ID,
Roles: msg.Member.Roles, msgID: msg.ID,
}, Words: words,
ID: msg.ID,
Content: msg.Content, Content: msg.Content,
Channel: channel.Name, Channel: channel.Name,
ChannelID: channel.ID, channelID: msg.ChannelID,
Server: server.Name, Server: server.Name,
ServerID: server.ID, serverID: server.ID,
} sesh: b,
w := strings.Fields(msg.Content)
if len(w) > 0 {
m.Words = w
}
if len(msg.Mentions) > 0 {
m.Mentions = msg.Mentions
} }
//check for file attachments
if len(msg.Attachments) > 0 { if len(msg.Attachments) > 0 {
var att []MessageAttachment var att []MessageAttachment
for _, a := range msg.Attachments { for _, a := range msg.Attachments {
@@ -256,69 +237,13 @@ func (b *bolt) mapEventToMsg(msg *dg.MessageCreate, channel *dg.Channel, server
}) })
} }
m.Attachments = att plMsg.Attachments = att
} }
return m //run command payload
} err = run.Payload(plMsg)
// handleMessage forwards the message data to the handler function, if one is set
func (b *bolt) handleMessage(event *Message) error {
if b.msgHandlerf != nil {
return b.msgHandlerf(&Context{
Message: event,
bolt: b,
})
}
return nil
}
// handleCommand maps the first word of the message to the command payload, if it exists. It then forwards the message
// data to the handler after checking the timeout and role restrictions. If restrictions have not been met a generic
// response is sent to the message
// TODO: accept a string for timeout/role rejection messages to allow customization
func (b *bolt) handleCommand(msg *Message, lg int) error {
run, ok := b.commands[msg.Words[0][lg:]]
if !ok {
return nil //command doesn't exist
}
//has command met its timeout requirements, if timeout has not expired a response is sent to the message
//from the timeoutCheck method
tc, err := b.timeoutCheck(msg.ID, msg.ChannelID, msg.ServerID, b.Session, run)
if err != nil { if err != nil {
return fmt.Errorf("failed to calculate timeout for %s\n%e", run.Trigger, err) return fmt.Errorf("failed to execute payload function: %e", err)
}
//method handles sending a response, so we do not need to send another here, simply return
if !tc {
return nil
}
//does user have correct permissions to run this command
if run.Roles != nil {
check, err := b.roleCheck(msg.ServerID, msg.Author.Roles, b.Session, run)
if err != nil {
return fmt.Errorf("failed to perform permission checks for %s\n%e", run.Trigger, err)
}
if !check {
//this alert should probably be moved into the roleCheck function to match the pattern of the timeoutCheck method
reply := b.createReply("you do not have permissions to run that command", msg.ID, msg.ChannelID, msg.ServerID)
_, err := b.Session.ChannelMessageSendComplex(msg.ChannelID, reply)
if err != nil {
return err
}
return nil
}
}
//execute handler func with message context
err = run.Payload(&Context{
Message: msg,
bolt: b,
})
if err != nil {
return fmt.Errorf("encountered an error while handling command (%s): %e", msg.Words[0], err)
} }
//update run time //update run time
@@ -327,7 +252,7 @@ func (b *bolt) handleCommand(msg *Message, lg int) error {
return nil return nil
} }
// createReploy is a basic wrapper function to map message data to the actual MessageSend struct // basic wrapper function to create easy Discord responses
func (b *bolt) createReply(content, message, channel, guild string) *dg.MessageSend { func (b *bolt) createReply(content, message, channel, guild string) *dg.MessageSend {
details := &dg.MessageReference{ details := &dg.MessageReference{
MessageID: message, MessageID: message,
@@ -341,9 +266,8 @@ func (b *bolt) createReply(content, message, channel, guild string) *dg.MessageS
} }
} }
// remainingTimeout calculates the amount of time left before a command can be run again. Returning a string // used to calculate the remaining time left in a timeout and returning it in a human-readable format
// representing a readable version of the time left, example: 1h (1 hour) func (b *bolt) getRemainingTimeout(timeout time.Time) string {
func (b *bolt) remainingTimeout(timeout time.Time) string {
r := time.Until(timeout) r := time.Until(timeout)
var ( var (
timeLeft int timeLeft int
@@ -360,23 +284,19 @@ func (b *bolt) remainingTimeout(timeout time.Time) string {
} }
} }
//provide a user-friendly time string to send back to the user
return fmt.Sprintf("%d%s", timeLeft, metric) return fmt.Sprintf("%d%s", timeLeft, metric)
} }
// checks if the author of msg has the correct role to run the requested command // checks if the author of msg has the correct role to run the requested command
func (b *bolt) roleCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error) {
// roleCheck loops through the provided user role ID's grabs the role "name" and ensures the role is present
// in the commands whitelist. If the role exists in the Command whitelist a true response is returned
func (b *bolt) roleCheck(guild string, roles []string, s *dg.Session, run Command) (bool, error) {
var found bool var found bool
//this needs a bit of love, looping through roles could get messy as server and role lists grow on big servers //loop thru author roles, there may be a better way to check for this UNION
//especially with the Role() call inside of the loop //TODO: improve role search performance to support bigger lists
for _, r := range roles { for _, r := range msg.Member.Roles {
//get role name from ID //get role name from ID
n, err := s.State.Role(guild, r) n, err := s.State.Role(msg.GuildID, r)
if err != nil { if err != nil {
return false, fmt.Errorf("failed to get role from ID %s\n%e", guild, 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)
@@ -386,17 +306,25 @@ func (b *bolt) roleCheck(guild string, roles []string, s *dg.Session, run Comman
} }
} }
return found, nil //can't find role, don't run command, alert user of missing permissions
if !found {
reply := b.createReply("you do not have permissions to run that command", msg.ID, msg.ChannelID, msg.GuildID)
_, err := s.ChannelMessageSendComplex(msg.ChannelID, reply)
if err != nil {
return false, fmt.Errorf("failed to send permission response: %e", err)
}
return false, nil
} }
// timeoutCheck determines if a Command timeout has expired, if it hasn't expired a response is sent back to the message alerting the user return true, nil
// of the remaining time }
func (b *bolt) timeoutCheck(msgID, channelID, guildID string, s *dg.Session, run Command) (bool, error) {
// check if the command timeout has been met, responding with remaining time if timeout has not been met yet.
func (b *bolt) timeoutCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error) {
wait := run.lastRun.Add(run.Timeout) wait := run.lastRun.Add(run.Timeout)
now := time.Now() if !time.Now().After(wait) {
if !now.After(wait) && !now.Equal(wait) { 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.remainingTimeout(wait)), msgID, channelID, guildID) _, err := s.ChannelMessageSendComplex(msg.ChannelID, reply)
_, err := s.ChannelMessageSendComplex(channelID, reply)
if err != nil { if err != nil {
return false, fmt.Errorf("failed to send timeout response: %e", err) return false, fmt.Errorf("failed to send timeout response: %e", err)
} }

View File

@@ -4,18 +4,14 @@ import (
"time" "time"
) )
// Command represents a bolt command in its entirety // custom Discord commands
type Command struct { type Command struct {
//the trigger phrase for the command, this field cannot include the command indicator. If the command is .ping Trigger string //command that triggers payload NOT including the indicator
//Trigger should be "ping" Payload Payload //payload function to run when a command is detected
Trigger string Timeout time.Duration //the amount of time before command can be run again
//handler function to run when command is detected lastRun time.Time //timestamp of last command run
Payload Payload Roles []string //roles that can use command, if none are set anyone can run the command
//the amount of time that must pass before a command can be run again
Timeout time.Duration
//timestamp of last command run
lastRun time.Time
//the roles that are allowed to execute this command, the command author must have at least one of these roles
//in order to use the command
Roles []string
} }
// command payload functions, any strings returned are sent as a response to the command
type Payload func(msg Message) error

7
go.mod
View File

@@ -1,11 +1,8 @@
module code.jakeyoungdev.com/jake/bolt module code.jakeyoungdev.com/jake/bolt
go 1.25.0 go 1.24.0
require ( require github.com/bwmarrin/discordgo v0.29.0
github.com/bwmarrin/discordgo v0.29.0
github.com/joho/godotenv v1.5.1
)
require ( require (
github.com/gorilla/websocket v1.4.2 // indirect github.com/gorilla/websocket v1.4.2 // indirect

2
go.sum
View File

@@ -2,8 +2,6 @@ github.com/bwmarrin/discordgo v0.29.0 h1:FmWeXFaKUwrcL3Cx65c20bTRW+vOb6k8AnaP+Eg
github.com/bwmarrin/discordgo v0.29.0/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY= github.com/bwmarrin/discordgo v0.29.0/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=

View File

@@ -1,21 +1,47 @@
package bolt package bolt
import ( import "fmt"
"fmt"
"time"
dg "github.com/bwmarrin/discordgo" //built-in Discord reactions
) type Reaction string
//a few easy-to-use emojis, Discordgo/Discord API requires them to be saved like this.
const ( const (
// the max length allowed for basic messages, if the message content exceeds this amount ReactionThumbsUp Reaction = "👍"
// then messages are split unto chunks of max size ReactionThumbsDown Reaction = "👎"
MSG_MAX_LENGTH = 2000 ReactionHundred Reaction = "💯"
ReactionHeart Reaction = "❤️"
ReactionPinkHeart Reaction = "🩷"
ReactionOrangeHeart Reaction = "🧡"
ReactionYellowHeart Reaction = "💛"
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 = "🧎‍♂️‍➡️"
) )
// command and message payload function type // information about attachments to messages
type Payload func(c *Context) error
type MessageAttachment struct { type MessageAttachment struct {
ID string ID string
URL string URL string
@@ -28,101 +54,29 @@ type MessageAttachment struct {
DurationSecs float64 DurationSecs float64
} }
// Author contains basic information about message authors // represents a Discord message
type Author struct {
Name string
ID string
Roles []string
}
// Message contains all needed data to handle message events
type Message struct { type Message struct {
Author Author Author string //username of message author
//current message ID ID string //discord ID of message author
ID string msgID string //id string of message
//message content split on whitespace to allow for easy argument parsing with commands Words []string //words from message split on whitespace
Words []string Content string //entire message content
//entire message content unchanged Channel string //message channel
Content string channelID string //id of channel message was sent in
//channel message was sent in, name and ID Server string //message guild
Channel string serverID string //id of guild message was sent in
ChannelID string Attachments []MessageAttachment
//guild message was sent in, name and ID sesh *bolt
Server string
ServerID string
//message extras
Attachments []MessageAttachment //any attachments bound to the message
Mentions []*dg.User //users mention in the message with @
} }
// Context is the struct passed to message and command handlers, it contains all needed message data as well as // applies reaction to message
// some methods to make interaction with the message as easy as possible func (m *Message) React(emoji Reaction) error {
type Context struct { return m.sesh.MessageReactionAdd(m.channelID, m.msgID, fmt.Sprint(emoji))
Message *Message
bolt *bolt
} }
// React applies the reaction to the message // sends the value of res in response to the message
func (c *Context) React(emoji Reaction) error { func (m *Message) Respond(res string) error {
return c.bolt.MessageReactionAdd(c.Message.ChannelID, c.Message.ID, fmt.Sprint(emoji)) rep := m.sesh.createReply(res, m.msgID, m.channelID, m.serverID)
} _, err := m.sesh.ChannelMessageSendComplex(m.channelID, rep)
// Respond sends a response to the message, handling chunking if the message exceeds max length
func (c *Context) Respond(res string) error {
if len(res) > MSG_MAX_LENGTH {
for len(res) > 0 {
//send full chunk size allowed by discord
sc := res[:MSG_MAX_LENGTH]
rep := c.bolt.createReply(sc, c.Message.ID, c.Message.ChannelID, c.Message.ServerID)
_, err := c.bolt.ChannelMessageSendComplex(c.Message.ChannelID, rep)
if err != nil {
return err return err
} }
res = res[MSG_MAX_LENGTH:]
//if we have left than a full chunk send the rest and break the loop
if len(res) < MSG_MAX_LENGTH {
final := c.bolt.createReply(res, c.Message.ID, c.Message.ChannelID, c.Message.ServerID)
_, err := c.bolt.ChannelMessageSendComplex(c.Message.ChannelID, final)
if err != nil {
return err
}
break
}
}
return nil
}
//short enough message to send in one go, so ship it
rep := c.bolt.createReply(res, c.Message.ID, c.Message.ChannelID, c.Message.ServerID)
_, err := c.bolt.ChannelMessageSendComplex(c.Message.ChannelID, rep)
return err
}
// Delete removes the message from the current channel
func (c *Context) Delete() error {
return c.bolt.ChannelMessageDelete(c.Message.ChannelID, c.Message.ID, nil)
}
// Timeout creates a user timeout for the supplied userID that lasts until duration is exceeded or the
// timeout is cleared
func (c *Context) Timeout(userId string, duration time.Time) error {
return c.bolt.GuildMemberTimeout(c.Message.ServerID, userId, &duration)
}
// ClearTimeout clears existing user timeouts, allowing them access again
func (c *Context) ClearTimeout(userId string) error {
return c.bolt.GuildMemberTimeout(c.Message.ServerID, userId, nil)
}
// Mute handles muting a user from Voice Chat, this mute stays until it is Unmute()'d
func (c *Context) Mute(userId string) error {
return c.bolt.GuildMemberMute(c.Message.ServerID, userId, true)
}
// Unmute removes a mute on the user, allowing them vc access again
func (c *Context) Unmute(userId string) error {
return c.bolt.GuildMemberMute(c.Message.ServerID, userId, false)
}

View File

@@ -1,50 +1,32 @@
package bolt package bolt
import (
dg "github.com/bwmarrin/discordgo"
)
type Option func(b *bolt) type Option func(b *bolt)
type LogLevel int type LogLevel int
const ( const (
LogLevelAll LogLevel = iota //log all messages, and errors LogLevelAll LogLevel = iota //logs all messages, and errors
LogLevelCmd LogLevel = iota //log only commands and responses, and errors LogLevelCmd LogLevel = iota //log only commands and responses, and errors
LogLevelErr LogLevel = iota //log only errors LogLevelErr LogLevel = iota //logs only errors
) )
// WithIntents provides an option to use custom intents for the bot. Bolt comes preconfigured with the basic // sets the substring that must be present at the beginning of the message to indicate a command
// intents needed to run a bot but those are completely overwritten by any supplied here
func WithIntents(intents ...dg.Intent) Option {
return func(b *bolt) {
var full dg.Intent
for _, i := range intents {
full |= i
}
b.Identify.Intents = full
}
}
// WithMaxGoroutines limits the amount of handler routines the bot is able to spawn at the same time. A lower value
// may cause higher latency but may reduce resources needed to run bolt
func WithMaxGoroutines(max int) Option {
return func(b *bolt) {
b.maxRoutines = max
}
}
// WithIndicator sets the substring that must be present at the beginning of a message to trigger a
// command, for example "." or "!"
func WithIndicator(i string) Option { func WithIndicator(i string) Option {
return func(b *bolt) { return func(b *bolt) {
b.indicator = i b.indicator = i
} }
} }
// WithLogLevel adjusts bolt logging verbosity // sets the log level to determine how much bolt logs
func WithLogLevel(lvl LogLevel) Option { func WithLogLevel(lvl LogLevel) Option {
return func(b *bolt) { return func(b *bolt) {
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
}
}

View File

@@ -1,38 +0,0 @@
package bolt
type Reaction string
// a few easy-to-use emojis, Discordgo/Discord API requires them to be saved like this. Some appear "broken" but do not play friendly
// when saved in-file
const (
ReactionThumbsUp Reaction = "👍"
ReactionThumbsDown Reaction = "👎"
ReactionHundred Reaction = "💯"
ReactionHeart Reaction = "❤️"
ReactionPinkHeart Reaction = "🩷"
ReactionOrangeHeart Reaction = "🧡"
ReactionYellowHeart Reaction = "💛"
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 = "🐉"
)