code cleanup, split handler func
This commit is contained in:
parent
d1a5de82fe
commit
b8bfb76b83
18
LICENSE
18
LICENSE
@ -1,7 +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:
|
||||
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 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.
|
||||
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.
|
||||
|
12
README.md
12
README.md
@ -6,7 +6,7 @@ Base Discord bot framework
|
||||
bolt is a wrapper for Discordgo to provide very quick and easy setup for simple Discord bots. The only code required to run bolt are 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. Any strings returned from the Payload function will be sent back to the Discord server as a reply to the command message.
|
||||
|
||||
## Basic Usage
|
||||
bolt allows developers to create a Discord bot with simply a discord bot token and a few lines of Go code, the below example creates a Discord bot and registers three commands: ".ping", ".time", and ".role" the "." character is the default command indicator but that can be changed using the WithIndicator option.
|
||||
bolt allows developers to create a Discord bot with a discord bot token and a few lines of Go code, discord tokens must be set as an environment variable labeled DISCORD_TOKEN. The below example creates a Discord bot and registers three commands: ".ping", ".time", and ".role" the "." character is the default command indicator but that can be changed using the WithIndicator option.
|
||||
```go
|
||||
package main
|
||||
|
||||
@ -22,20 +22,22 @@ import (
|
||||
)
|
||||
|
||||
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()
|
||||
|
||||
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) (res string, err error) {
|
||||
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) (res string, err error) {
|
||||
Payload: func(msg bolt.Message) (string, error) {
|
||||
return "yer", nil
|
||||
},
|
||||
Timeout: time.Second * 25,
|
||||
@ -43,7 +45,7 @@ func main() {
|
||||
// .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) (res string, err error) {
|
||||
Payload: func(msg bolt.Message) (string, error) {
|
||||
return "hi", nil
|
||||
},
|
||||
Timeout: time.Second * 10,
|
||||
@ -60,4 +62,4 @@ func main() {
|
||||
```
|
||||
|
||||
## 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
|
113
bolt.go
113
bolt.go
@ -32,11 +32,15 @@ type bolt struct {
|
||||
|
||||
type Bolt interface {
|
||||
Start() error
|
||||
AddCommands(cmd ...Command)
|
||||
//filtered methods
|
||||
stop() error
|
||||
AddCommands(cmd Command)
|
||||
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,7 +53,7 @@ func init() {
|
||||
}
|
||||
|
||||
// create a new bolt interface
|
||||
func New(opts ...Option) *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)
|
||||
@ -70,10 +74,8 @@ func New(opts ...Option) *bolt {
|
||||
return b
|
||||
}
|
||||
|
||||
// adds command handler and starts the bot, this is a BLOCKING CALL
|
||||
|
||||
// starts the bot, commands are added and the connection to Discord is opened, this is a BLOCKING
|
||||
// call and handles safe shutdown of the bot
|
||||
// call that handles safe shutdown of the bot
|
||||
func (b *bolt) Start() error {
|
||||
//register commands and open connection
|
||||
b.AddHandler(b.messageHandler)
|
||||
@ -137,46 +139,39 @@ func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
|
||||
//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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
words := strings.Split(msg.Content, " ")
|
||||
run, ok := b.Commands[words[0][lg:]]
|
||||
if !ok {
|
||||
return //command doesn't exist, maybe log or respond to author
|
||||
return nil //command doesn't exist, maybe log or respond to author
|
||||
}
|
||||
|
||||
//has command met its timeout requirements
|
||||
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)
|
||||
tc, err := b.timeoutCheck(msg, s, run)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return err
|
||||
}
|
||||
return //running too soon
|
||||
if !tc {
|
||||
return nil
|
||||
}
|
||||
|
||||
//does user have correct permissions
|
||||
if run.Roles != nil {
|
||||
var found bool
|
||||
for _, r := range msg.Member.Roles {
|
||||
n, err := s.State.Role(msg.GuildID, r)
|
||||
check, err := b.roleCheck(msg, s, run)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
check := slices.Contains(run.Roles, n.Name)
|
||||
if check {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
|
||||
//can't find role, don't run command
|
||||
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 {
|
||||
log.Println(err)
|
||||
}
|
||||
return
|
||||
if !check {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@ -190,8 +185,7 @@ func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
|
||||
//if a reply is returned send back to Discord
|
||||
@ -199,15 +193,14 @@ func (b *bolt) messageHandler(s *dg.Session, msg *dg.MessageCreate) {
|
||||
reply := b.createReply(res, msg.ID, msg.ChannelID, msg.GuildID)
|
||||
_, err := s.ChannelMessageSendComplex(msg.ChannelID, reply)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
//update run time
|
||||
run.LastRun = time.Now()
|
||||
run.lastRun = time.Now()
|
||||
b.Commands[run.Trigger] = run
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// basic wrapper function to create easy Discord responses
|
||||
@ -244,3 +237,49 @@ func (b *bolt) getRemainingTimeout(timeout time.Time) string {
|
||||
|
||||
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
|
||||
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
|
||||
}
|
||||
|
@ -6,7 +6,7 @@ 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 run again
|
||||
LastRun time.Time //timestamp of last command run
|
||||
lastRun time.Time //timestamp of last command run
|
||||
Roles []string //roles that can use command
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user