himbot/lib/command.go
2024-11-04 01:23:57 -06:00

64 lines
1.7 KiB
Go

package lib
import (
"log"
"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) {
// 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)
}
// Rest of your existing HandleCommand logic...
if !CheckAndApplyCooldown(s, i, commandName, cooldownDuration) {
return
}
if !CheckAndApplyCooldown(s, i, commandName, cooldownDuration) {
return
}
// Acknowledge the interaction immediately
interactErr := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
})
if interactErr != nil {
ThrowWithError(commandName, "Error deferring response: "+interactErr.Error())
return
}
// Execute the command handler
response, handlerErr := handler(s, i)
if handlerErr != nil {
RespondWithError(s, i, "Error processing command: "+handlerErr.Error())
return
}
// Send the follow-up message with the response
_, followErr := s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: response,
})
if followErr != nil {
ThrowWithError(commandName, "Error sending follow-up message: "+followErr.Error())
}
}
}