himbot/lib/command.go

60 lines
1.6 KiB
Go
Raw Normal View History

2024-10-22 17:07:53 -06:00
package lib
import (
2024-11-04 01:23:57 -06:00
"log"
2024-10-22 17:07:53 -06:00
"time"
"github.com/bwmarrin/discordgo"
)
type CommandFunc func(s *discordgo.Session, i *discordgo.InteractionCreate) (string, error)
func HandleCommand(commandName string, cooldownDuration time.Duration, handler CommandFunc) func(s *discordgo.Session, i *discordgo.InteractionCreate) {
return func(s *discordgo.Session, i *discordgo.InteractionCreate) {
2024-11-04 01:23:57 -06:00
// Get user information first
user, userErr := GetUser(i)
if userErr != nil {
RespondWithError(s, i, "Error processing command: "+userErr.Error())
return
}
// Store user in database
dbErr := StoreUser(user.ID, user.Username)
if dbErr != nil {
// Log the error but don't stop command execution
log.Printf("Error storing user: %v", dbErr)
}
2024-10-22 17:07:53 -06:00
if !CheckAndApplyCooldown(s, i, commandName, cooldownDuration) {
return
}
// Acknowledge the interaction immediately
2024-11-04 01:23:57 -06:00
interactErr := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
2024-10-22 17:07:53 -06:00
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
})
2024-11-04 01:23:57 -06:00
if interactErr != nil {
ThrowWithError(commandName, "Error deferring response: "+interactErr.Error())
2024-10-22 17:07:53 -06:00
return
}
// Execute the command handler
2024-11-04 01:23:57 -06:00
response, handlerErr := handler(s, i)
2024-10-22 17:07:53 -06:00
2024-11-04 01:23:57 -06:00
if handlerErr != nil {
RespondWithError(s, i, "Error processing command: "+handlerErr.Error())
2024-10-22 17:07:53 -06:00
return
}
// Send the follow-up message with the response
2024-11-04 01:23:57 -06:00
_, followErr := s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
2024-10-22 17:07:53 -06:00
Content: response,
})
2024-11-04 01:23:57 -06:00
if followErr != nil {
ThrowWithError(commandName, "Error sending follow-up message: "+followErr.Error())
2024-10-22 17:07:53 -06:00
}
}
}