Compare commits

...

19 Commits
v0.0.4 ... main

Author SHA1 Message Date
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
5 changed files with 320 additions and 81 deletions

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.

View File

@ -1,9 +1,79 @@
# bolt
Base Discord bot framework
The nuts and bolts of a Discord bots. Bolt is a wrapper for [discordgo](https://github.com/bwmarrin/discordgo) that provides very quick bootstrapping for simple Discord bots.
## Introduction
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.
## Usage
### 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. Any roles in the Command struct can run the command, if the Roles field is empty anyone can 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 the command
}
```
### Payload
Payload functions are executed when a command is detected, if no errors are returned and the returned string is not empty, then the returned string is sent in reply to the command message.
```go
type Payload func(msg Message) (string, error)
```
### Example
```go
package main
import (
"time"
"code.jakeyoungdev.com/jake/bolt"
_ "github.com/joho/godotenv/autoload"
)
func main() {
//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 := bolt.New(bolt.WithLogLevel(bolt.LogLevelCmd))
b.AddCommands(
// .ping can be run at any time by anyone and will respond with 'pong'
bolt.Command{
Trigger: "ping",
Payload: func(msg bolt.Message) (string, error) {
return "pong", nil //any strings returned will be sent in response to the Discord message
},
},
// .time can be run every 25 seconds by anyone and will respond with 'yer'
bolt.Command{
Trigger: "time",
Payload: func(msg bolt.Message) (string, error) {
return "yer", nil
},
Timeout: time.Second * 25,
},
// .role can be run every 10 seconds by anyone with the 'admin' role and will respond with 'hi'
bolt.Command{
Trigger: "role",
Payload: func(msg bolt.Message) (string, error) {
return "hi", nil
},
Timeout: time.Second * 10,
Roles: []string{"admin"},
},
)
//start is a blocking call that handles safe-shutdown, all configuration and setup should be done before calling Start()
err := b.Start()
if err != nil {
panic(err)
}
}
```
## 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 development at the moment and may break occasionally before a v1 release

248
bolt.go
View File

@ -4,7 +4,10 @@ import (
"fmt"
"log"
"os"
"os/signal"
"slices"
"strings"
"syscall"
"time"
dg "github.com/bwmarrin/discordgo"
@ -13,13 +16,8 @@ import (
const (
TOKEN_ENV_VAR = "DISCORD_TOKEN" //label for token environment variable
// BOT_INTENTS = dg.IntentsAllWithoutPrivileged |
// dg.IntentGuildMembers |
// dg.IntentGuildPresences |
// dg.IntentMessageContent |
// dg.IntentsGuildMessages
BOT_INTENTS = dg.IntentGuildMembers |
BOT_INTENTS = dg.IntentGuilds |
dg.IntentGuildMembers |
dg.IntentGuildPresences |
dg.IntentMessageContent |
dg.IntentsGuildMessages
@ -28,15 +26,22 @@ const (
// 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
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
}
type Bolt interface {
Start() error
Stop() error
AddCommands(cmd Command)
AddCommands(cmd ...Command)
//filtered methods
stop() error
messageHandler(s *dg.Session, msg *dg.MessageCreate)
handleCommand(msg *dg.MessageCreate, s *dg.Session, server *dg.Guild, channel *dg.Channel, lg int) error
createReply(content, message, channel, guild string) *dg.MessageSend
getRemainingTimeout(timeout time.Time) string
roleCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error)
timeoutCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error)
}
// setup
@ -49,37 +54,61 @@ func init() {
}
// create a new bolt interface
func New() *bolt {
func New(opts ...Option) Bolt {
bot, err := dg.New(fmt.Sprintf("Bot %s", os.Getenv(TOKEN_ENV_VAR)))
if err != nil {
log.Fatal(err)
}
bot.Identify.Intents = BOT_INTENTS
return &bolt{
b := &bolt{
Session: bot,
Commands: make(map[string]Command, 0),
commands: make(map[string]Command, 0),
logLvl: LogLevelAll,
}
//set default command indicator
b.indicator = "."
//apply options to bolt
for _, opt := range opts {
opt(b)
}
return b
}
// adds command handler and starts the bot
// 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
func (b *bolt) Start() error {
//register commands and open connection
b.AddHandler(b.messageHandler)
return b.Open()
err := b.Open()
if err != nil {
return err
}
//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
}
// stops the bot
func (b *bolt) Stop() error {
func (b *bolt) stop() error {
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
b.commands[c.Trigger] = c
}
}
@ -103,60 +132,93 @@ func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
msg.Content = "GIF/IMAGE"
}
//log message
log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.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
if msg.Author.ID == s.State.User.ID {
if b.logLvl == LogLevelCmd {
//log commands
log.Printf("< %s | %s | %s > %s\n", server.Name, channel.Name, msg.Author.Username, msg.Content)
}
return
}
//does the message have the command indicator "."
if msg.Content[:1] == "." {
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
if !time.Now().After(run.LastRun.Add(run.Timeout)) {
return //running too soon, maybe respond letting know time remaining
}
//run command payload
res, err := run.Payload(Message{
Author: Author{
Username: msg.Author.Username,
Roles: msg.Member.Roles,
},
Words: words,
Message: msg.Content,
Channel: channel.Name,
Server: server.Name,
})
//does the message have the command indicator
lg := len(b.indicator)
if msg.Content[:lg] == b.indicator {
err := b.handleCommand(msg, s, server, channel, lg)
if err != nil {
log.Println(err)
return
}
//if a reply is returned send back to Discord
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
}
}
//update run time
run.LastRun = time.Now()
b.Commands[run.Trigger] = run
}
}
// 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 {
//log commands
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][lg:]]
if !ok {
return nil //command doesn't exist, maybe log or respond to author
}
//has command met its timeout requirements
tc, err := b.timeoutCheck(msg, s, run)
if err != nil {
return err
}
if !tc {
return nil
}
//does user have correct permissions
if run.Roles != nil {
check, err := b.roleCheck(msg, s, run)
if err != nil {
return err
}
if !check {
return nil
}
}
//run command payload
res, err := run.Payload(Message{
Author: msg.Author.Username,
ID: msg.Author.ID,
Words: words,
Content: msg.Content,
Channel: channel.Name,
Server: server.Name,
})
if err != nil {
return err
}
//if a reply is returned send back to Discord
if res != "" {
reply := b.createReply(res, msg.ID, msg.ChannelID, msg.GuildID)
_, err := s.ChannelMessageSendComplex(msg.ChannelID, reply)
if err != nil {
return err
}
}
//update run time
run.lastRun = time.Now()
b.commands[run.Trigger] = run
return nil
}
// basic wrapper function to create easy Discord responses
func (b *bolt) createReply(content, message, channel, guild string) *dg.MessageSend {
details := &dg.MessageReference{
@ -170,3 +232,71 @@ func (b *bolt) createReply(content, message, channel, guild string) *dg.MessageS
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)
}
// 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) {
var found bool
//loop thru author roles, there may be a better way to check for this UNION
//TODO: improve role search performance to support bigger lists
for _, r := range msg.Member.Roles {
//get role name from ID
n, err := s.State.Role(msg.GuildID, r)
if err != nil {
return false, err
}
//does this role exist in command roles
check := slices.Contains(run.Roles, n.Name)
if check {
found = true
break
}
}
//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, err
}
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.
func (b *bolt) timeoutCheck(msg *dg.MessageCreate, s *dg.Session, run Command) (bool, error) {
wait := run.lastRun.Add(run.Timeout)
if !time.Now().After(wait) {
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)
if err != nil {
return false, err
}
return false, nil
}
return true, nil
}

View File

@ -2,29 +2,24 @@ package bolt
import "time"
// custom Discord commands
type Command struct {
Trigger string //.command that triggers payload INCLUDING the '.'
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 run again
LastRun time.Time //timestamp of last command run
Roles []string //roles that can use command
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 the command
}
// payload function type handling commands. The returned error is parsed and, if no error,
// is detected then the response string (res) will be sent in response to the command message
type Payload func(msg Message) (res string, err error)
// command payload functions, any strings returned are sent as a response to the command
type Payload func(msg Message) (string, error)
// contains the basic information needed for a message command
// message information passed to payload function
type Message struct {
Author Author
Author string //username of message author
ID string //discord ID of message 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
Content string //entire message content
Channel string //message channel
Server string //message guild
}

25
option.go Normal file
View File

@ -0,0 +1,25 @@
package bolt
type Option func(b *bolt)
type LogLevel int
const (
LogLevelAll LogLevel = iota //logs all messages, and errors
LogLevelCmd LogLevel = iota //log only commands and responses, and errors
LogLevelErr LogLevel = iota //logs only errors
)
// sets the substring that must be present at the beginning of the message to indicate a command
func WithIndicator(i string) Option {
return func(b *bolt) {
b.indicator = i
}
}
// sets the log level to determine how much bolt logs
func WithLogLevel(lvl LogLevel) Option {
return func(b *bolt) {
b.logLvl = lvl
}
}