43 Commits

Author SHA1 Message Date
a07c071dc2 removing printlns on successful shutdown 2026-03-01 00:17:58 -05:00
b9ec31da95 readme and comments 2026-02-25 15:44:44 -05:00
130d1c573f Merge pull request 'feature/improvements' (#8) from feature/improvements into main
Reviewed-on: #8
2026-02-25 19:22:27 +00:00
b9c26c6319 [chore] cleaning
- removing old or commented code
- removing unused or deprecated types
- commenting everything, probably too much
- split msgEventHandler logic into methods
- readme update, removed most docs the pkg site looks good
- adjusted intents option, no need for a type
2026-02-25 13:24:27 -05:00
4732e94c1b starting comment mountain 2026-02-24 19:04:33 -05:00
01dd3633ef adding Context
- converting messages and methods into one context per event
2026-02-24 18:45:00 -05:00
5297a480b8 updates from testing 2026-02-24 18:19:41 -05:00
6816d7359b WIP
started the facelift of the repo, adding in bans and timeouts. That comes with some restructure.
Also implementing a goroutine limit for command handlers and options around that, as well as moving
the intents to options to allow stronger restrictions
2026-02-24 16:54:25 -05:00
c291f68005 Merge pull request 'Properly handling message overflows' (#6) from fix/msg-length into main
Reviewed-on: #6
2026-01-27 16:23:08 +00:00
759a188a8e chunking messages that overflow 2026-01-26 22:59:13 -05:00
7376e8f857 Merge pull request 'new/message-deletes' (#5) from new/message-deletes into main
Reviewed-on: #5
2025-09-08 21:05:53 +00:00
c196e25e0c update readme 2025-09-08 17:02:22 -04:00
d70dd8c3a4 updates
- moved reaction to own file
- added message delete method
2025-09-07 01:10:48 -04:00
6504336d01 Merge pull request 'fix/async' (#4) from fix/async into main
Reviewed-on: #4
2025-08-18 03:25:47 +00:00
a310fd4533 better async handling 2025-08-17 20:45:51 -04:00
eb64bdf803 starting research for vc support 2025-08-17 20:37:22 -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
90a17ded2b adding reaction support (#2)
- some rework of structure to allow for more puposeful response usage
- react and response now live on the message itself
- message structs split into own file
- readme updated to use new methods

Reviewed-on: #2
Co-authored-by: jake <jake.young.dev@gmail.com>
Co-committed-by: jake <jake.young.dev@gmail.com>
2025-07-09 20:11:12 +00:00
113fcbf2d1 adding author id to message struct 2025-06-25 19:12:34 -04:00
dd20b73b76 adding log level option (#1)
Reviewed-on: #1
Co-authored-by: jake <jake.young.dev@gmail.com>
Co-committed-by: jake <jake.young.dev@gmail.com>
2025-06-25 22:51:32 +00:00
5f72f58c74 readme update 2025-06-11 17:37:59 -04:00
2d70c450a9 merge fix 2025-06-08 02:27:46 -04:00
08ffade13d [chore] comments and function scope
- methods no longer exported if not used
- readme update
- comments updated
2025-06-08 02:26:06 -04:00
0b39a0996f Update README.md 2025-06-07 13:41:19 +00:00
9ffab89ebf adding TODO comments 2025-06-07 09:31:00 -04:00
b8bfb76b83 code cleanup, split handler func 2025-06-07 00:34:26 -04:00
d1a5de82fe removing named return values
- avoiding confusion w long functions for naked returns
2025-06-04 23:22:10 -04:00
5b32d09a27 better naming standards 2025-06-04 23:15:00 -04:00
cc77adeadc adding license file 2025-06-04 21:03:17 -04:00
4e44b972d8 readme update 2025-06-04 21:00:23 -04:00
dc3ef04778 removing public stop method
- safe shutdown handled in library
2025-06-04 20:44:25 -04:00
55b7a717f6 adding options
- ability to update indicator
2025-06-04 18:28:27 -04:00
d9ff09da6b readme update 2025-06-04 17:08:50 -04:00
ca67dc71ca response and readme updates
- fixed example syntax
- framework now response on timeout skips
- framework will now alert of missing permissions
2025-06-04 17:06:13 -04:00
6ae84c0d5b role updates
- bolt will now ensure role is present before exec payload
- readme updates
- removed author struct since roles are checked in bolt framework
2025-06-04 16:47:50 -04:00
381073dc39 readme update 2025-06-04 16:36:11 -04:00
dc25c6e3ec readme and comments 2025-06-04 16:31:33 -04:00
10 changed files with 679 additions and 123 deletions

2
.gitignore vendored
View File

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

19
LICENSE Normal file
View File

@@ -0,0 +1,19 @@
Copyright 2025 jake
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

103
README.md
View File

@@ -1,9 +1,104 @@
# bolt # bolt
Base Discord bot framework A fast [discordgo](https://github.com/bwmarrin/discordgo) wrapper for bootstrapping Discord bots.
## Introduction ## Usage
bolt is a wrapper for Discordgo to provide very quick and easy setup for simple Discord bots. The only code required to run bolt is the command handler functions, this provides developers with the ability to have text-based commands on a Discord server without all the bootstrapping and setup usually required. ### Prerequisites
Bolt requires a Discord bot token to run, the token must be set as an environment variable labeled "DISCORD_TOKEN"
### Example
```go
package main
import (
"fmt"
"strings"
"time"
"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() {
b, err := bolt.New()
if err != nil {
panic(err)
}
b.AddCommands(
bolt.Command{
Trigger: "ping",
Payload: func(c *bolt.Context) error {
return c.Respond("pong")
},
},
bolt.Command{
Trigger: "wait",
Payload: func(c *bolt.Context) error {
return c.Respond("okay")
},
Timeout: time.Second * 25,
Roles: []string{"user"},
},
bolt.Command{
Trigger: "timeout",
Payload: func(c *bolt.Context) error {
if len(c.Message.Mentions) > 0 {
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
},
Roles: []string{"admin"},
},
)
b.AddMessageHandler(func(c *bolt.Context) error {
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()
if err != nil {
panic(err)
}
}
```
## Development ## Development
bolt is in heavy development at the moment and may break occasionally before a v1 release, it is currently in a testing phase and should not be used until tagged. bolt is in early development and may encounter breaking changes until a full v1 rollout, I will do my best to communicate
these changes. Use a tagged version to avoid any surprises with live code in main

394
bolt.go
View File

@@ -1,163 +1,326 @@
package bolt package bolt
import ( import (
"context"
"fmt" "fmt"
"log" "log"
"os" "os"
"os/signal"
"slices"
"strings" "strings"
"sync"
"time" "time"
dg "github.com/bwmarrin/discordgo" dg "github.com/bwmarrin/discordgo"
) )
const ( const (
TOKEN_ENV_VAR = "DISCORD_TOKEN" //label for token environment variable //the name of the environment variable that should contain the token for the bot, it is
//required for bolt to run
TOKEN_ENV_VAR = "DISCORD_TOKEN"
// BOT_INTENTS = dg.IntentsAllWithoutPrivileged | //bot default command indicator, if messages begin with this substring they are processed
// dg.IntentGuildMembers | //through the command handler instead of the generic message handler
// dg.IntentGuildPresences | DEFAULT_INDICATOR = "."
// dg.IntentMessageContent | //max amount of concurrent goroutines that bolt can use for events. A lower amount
// dg.IntentsGuildMessages //may lower the resource usage of bolt but may cause a delay in event handling
DEFAULT_MAX_GOROUTINES = 250
BOT_INTENTS = dg.IntentGuildMembers | //minimum intents for bots to function, intents can be changed with options
DEFAULT_INTENTS = dg.IntentGuilds |
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 //discordgo internals
Commands map[string]Command //maps trigger phrase to command struct for fast lookup *dg.Session
//maps trigger phrase to command struct for instant lookup
commands map[string]Command
//used to detect whether a message is a command
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
Stop() error AddCommands(cmd ...Command)
AddCommands(cmd Command) AddMessageHandler(p Payload)
messageHandler(s *dg.Session, msg *dg.MessageCreate) //filtered methods
stop() error
msgEventHandler(s *dg.Session, msg *dg.MessageCreate)
mapEventToMsg(msg *dg.MessageCreate, channel *dg.Channel, server *dg.Guild) Message
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
roleCheck(guild string, roles []string, s *dg.Session, run Command) (bool, error)
timeoutCheck(msgID, channelID, guildID string, s *dg.Session, run Command) (bool, error)
} }
// setup // New creates a new bolt instance and applies any supplied options
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() *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 b := &bolt{
return &bolt{
Session: bot, Session: bot,
Commands: make(map[string]Command, 0), commands: make(map[string]Command, 0),
} logLvl: LogLevelAll,
indicator: DEFAULT_INDICATOR,
wg: sync.WaitGroup{},
maxRoutines: DEFAULT_MAX_GOROUTINES,
} }
// adds command handler and starts the bot b.Identify.Intents = DEFAULT_INTENTS
for _, opt := range opts {
opt(b)
}
//options can change max routine number, so create after
b.pool = make(chan struct{}, b.maxRoutines)
return b, nil
}
// Start applies the message event handler function to the bot and opens the initial websocket connection
// with Discord. Start is a blocking call that also handles safe shutdown, on Interrupt, bolt will give
// command routines a window to finish before closing the connection.
func (b *bolt) Start() error { func (b *bolt) Start() error {
//register commands and open connection b.AddHandler(b.msgEventHandler)
b.AddHandler(b.messageHandler) err := b.Open()
if err != nil {
return b.Open() return fmt.Errorf("failed to open websocket connection with Discord: %e", err)
} }
// stops the bot sigChannel := make(chan os.Signal, 1)
func (b *bolt) Stop() error { signal.Notify(sigChannel, os.Interrupt)
<-sigChannel
//give handler routines a 5 second window to finish processes before closing connection
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
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:
}
return b.stop()
}
// AddCommands registers command handlers. Any messages that begin with the command indicator will be forwarded
// to the handler
func (b *bolt) AddCommands(cmd ...Command) {
for _, c := range cmd {
b.commands[c.Trigger] = c
}
}
// AddMessageHandler registers the generic message handler, any messages that are not commands will be forwarded
// to the handler
func (b *bolt) AddMessageHandler(p Payload) {
b.msgHandlerf = p
}
// stop closes the websocket connection to Discord
func (b *bolt) stop() error {
return b.Close() return b.Close()
} }
// adds commands to bot command map for use // msgEventHandler handles the routing of messages to either the command or message handlers. If LogLvl is set, logging is handled here before
func (b *bolt) AddCommands(cmd ...Command) { // 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
for _, c := range cmd { // is set as a default and can be altered using options for better performance.
b.Commands[c.Trigger] = c func (b *bolt) msgEventHandler(s *dg.Session, msg *dg.MessageCreate) {
}
}
// handler function that parses message data and executes any command payloads
func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
//get server information //get server information
server, err := s.Guild(msg.GuildID) server, err := s.Guild(msg.GuildID)
if err != nil { if err != nil {
log.Println(err) log.Printf("failed to get guild: %e\n", err)
return 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 return
} }
//if there is no content it is likely an image or a GIF, updating message content for
//better logging and to avoid confusion
if len(msg.Content) == 0 {
msg.Content = "GIF/IMAGE"
}
//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 != LogLevelErr {
log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content)
}
return return
} }
//does the message have the command indicator "." if b.logLvl == LogLevelAll {
if msg.Content[:1] == "." { log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content)
words := strings.Split(msg.Content, " ")
run, ok := b.Commands[words[0]]
if !ok {
return //command doesn't exist, maybe log or respond to author
} }
//has command met its timeout requirements m := b.mapEventToMsg(msg, channel, server)
if !time.Now().After(run.LastRun.Add(run.Timeout)) { lg := len(b.indicator)
return //running too soon, maybe respond letting know time remaining if msg.Content[:lg] == b.indicator {
if b.logLvl == LogLevelCmd {
log.Printf("< %s | %s | %s > %s\n", m.Server, m.Channel, m.Author.Name, m.Content)
} }
//run command payload b.pool <- struct{}{} //'aquire' a routine
res, err := run.Payload(Message{ b.wg.Go(func() {
err := b.handleCommand(&m, lg)
if err != nil {
log.Println(err)
}
<-b.pool //release routine
})
} else {
b.pool <- struct{}{} //'aquire' a routine
b.wg.Go(func() {
err := b.handleMessage(&m)
if err != nil {
log.Println(err)
}
<-b.pool //release routine
})
}
}
// mapEventToMsg maps the Discord event message struct into bolt's user-friendly Message struct
func (b *bolt) mapEventToMsg(msg *dg.MessageCreate, channel *dg.Channel, server *dg.Guild) Message {
m := Message{
Author: Author{ Author: Author{
Username: msg.Author.Username, Name: msg.Author.Username,
ID: msg.Author.ID,
Roles: msg.Member.Roles, Roles: msg.Member.Roles,
}, },
Words: words, ID: msg.ID,
Message: msg.Content, Content: msg.Content,
Channel: channel.Name, Channel: channel.Name,
ChannelID: channel.ID,
Server: server.Name, Server: server.Name,
ServerID: server.ID,
}
w := strings.Fields(msg.Content)
if len(w) > 0 {
m.Words = w
}
if len(msg.Mentions) > 0 {
m.Mentions = msg.Mentions
}
if len(msg.Attachments) > 0 {
var att []MessageAttachment
for _, a := range msg.Attachments {
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,
}) })
if err != nil {
log.Println(err)
return
} }
//if a reply is returned send back to Discord m.Attachments = att
if res != "" {
reply := b.createReply(res, msg.ID, msg.ChannelID, msg.GuildID)
_, err := s.ChannelMessageSendComplex(msg.ChannelID, reply)
if err != nil {
log.Println(err)
return
} }
return m
}
// 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 {
return fmt.Errorf("failed to calculate timeout for %s\n%e", run.Trigger, 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
run.LastRun = time.Now() run.lastRun = time.Now()
b.Commands[run.Trigger] = run b.commands[run.Trigger] = run
} return nil
} }
// basic wrapper function to create easy Discord responses // createReploy is a basic wrapper function to map message data to the actual MessageSend struct
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,
@@ -170,3 +333,68 @@ func (b *bolt) createReply(content, message, channel, guild string) *dg.MessageS
Reference: details, Reference: details,
} }
} }
// remainingTimeout calculates the amount of time left before a command can be run again. Returning a string
// representing a readable version of the time left, example: 1h (1 hour)
func (b *bolt) remainingTimeout(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"
}
}
//provide a user-friendly time string to send back to the user
return fmt.Sprintf("%d%s", timeLeft, metric)
}
// checks if the author of msg has the correct role to run the requested command
// 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
//this needs a bit of love, looping through roles could get messy as server and role lists grow on big servers
//especially with the Role() call inside of the loop
for _, r := range roles {
//get role name from ID
n, err := s.State.Role(guild, r)
if err != nil {
return false, fmt.Errorf("failed to get role from ID %s\n%e", guild, err)
}
//does this role exist in command roles
check := slices.Contains(run.Roles, n.Name)
if check {
found = true
break
}
}
return found, 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
// of the remaining time
func (b *bolt) timeoutCheck(msgID, channelID, guildID string, s *dg.Session, run Command) (bool, error) {
wait := run.lastRun.Add(run.Timeout)
now := time.Now()
if !now.After(wait) && !now.Equal(wait) {
reply := b.createReply(fmt.Sprintf("that command cannot be run for another %s", b.remainingTimeout(wait)), msgID, channelID, guildID)
_, err := s.ChannelMessageSendComplex(channelID, reply)
if err != nil {
return false, fmt.Errorf("failed to send timeout response: %e", err)
}
return false, nil
}
return true, nil
}

View File

@@ -1,30 +1,21 @@
package bolt package bolt
import "time" import (
"time"
)
// Command represents a bolt command in its entirety
type Command struct { type Command struct {
Trigger string //.command that triggers payload INCLUDING the '.' //the trigger phrase for the command, this field cannot include the command indicator. If the command is .ping
Payload Payload //payload function to run when a command is detected //Trigger should be "ping"
Timeout time.Duration //the amount of time before command can run again Trigger string
LastRun time.Time //timestamp of last command run //handler function to run when command is detected
Roles []string //roles that can use command Payload Payload
} //the amount of time that must pass before a command can be run again
Timeout time.Duration
// payload function type handling commands. The returned error is parsed and, if no error, //timestamp of last command run
// is detected then the response string (res) will be sent in response to the command message lastRun time.Time
type Payload func(msg Message) (res string, err error) //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
// contains the basic information needed for a message command
type Message struct {
Author Author
Words []string //words from message split on whitespace
Message string //entire message content
Channel string //channel message was sent in
Server string //guild message was sent in
}
// username and roles of message authors
type Author struct {
Username string
Roles []string Roles []string
} }

7
go.mod
View File

@@ -1,8 +1,11 @@
module code.jakeyoungdev.com/jake/bolt module code.jakeyoungdev.com/jake/bolt
go 1.24.0 go 1.25.0
require github.com/bwmarrin/discordgo v0.29.0 require (
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,6 +2,8 @@ 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=

128
message.go Normal file
View File

@@ -0,0 +1,128 @@
package bolt
import (
"fmt"
"time"
dg "github.com/bwmarrin/discordgo"
)
const (
// the max length allowed for basic messages, if the message content exceeds this amount
// then messages are split unto chunks of max size
MSG_MAX_LENGTH = 2000
)
// command and message payload function type
type Payload func(c *Context) error
type MessageAttachment struct {
ID string
URL string
ProxyURL string
Filename string
ContentType string
Width int
Height int
Size int
DurationSecs float64
}
// Author contains basic information about message authors
type Author struct {
Name string
ID string
Roles []string
}
// Message contains all needed data to handle message events
type Message struct {
Author Author
//current message ID
ID string
//message content split on whitespace to allow for easy argument parsing with commands
Words []string
//entire message content unchanged
Content string
//channel message was sent in, name and ID
Channel string
ChannelID string
//guild message was sent in, name and ID
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
// some methods to make interaction with the message as easy as possible
type Context struct {
Message *Message
bolt *bolt
}
// React applies the reaction to the message
func (c *Context) React(emoji Reaction) error {
return c.bolt.MessageReactionAdd(c.Message.ChannelID, c.Message.ID, fmt.Sprint(emoji))
}
// 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
}
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)
}

50
option.go Normal file
View File

@@ -0,0 +1,50 @@
package bolt
import (
dg "github.com/bwmarrin/discordgo"
)
type Option func(b *bolt)
type LogLevel int
const (
LogLevelAll LogLevel = iota //log all messages, and errors
LogLevelCmd LogLevel = iota //log only commands and responses, and errors
LogLevelErr LogLevel = iota //log only errors
)
// WithIntents provides an option to use custom intents for the bot. Bolt comes preconfigured with the basic
// 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 {
return func(b *bolt) {
b.indicator = i
}
}
// WithLogLevel adjusts bolt logging verbosity
func WithLogLevel(lvl LogLevel) Option {
return func(b *bolt) {
b.logLvl = lvl
}
}

38
reaction.go Normal file
View File

@@ -0,0 +1,38 @@
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 = "🐉"
)