Files
himbot/lib/command.go
Atridad Lahiji 221c5cec97
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m23s
PiZzA
2026-01-27 13:52:57 -07:00

66 lines
1.8 KiB
Go

package lib
import (
"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) {
if !CheckAndApplyCooldown(s, i, commandName, cooldownDuration) {
return
}
// Get user information (handle both guild and DM contexts)
user, userErr := GetUser(i)
if userErr != nil {
RespondWithError(s, i, "Error getting user information: "+userErr.Error())
return
}
// Get or create user and guild profile
_, createUserError := GetOrCreateUserWithGuild(user.ID, user.Username, i.GuildID)
if createUserError != nil {
RespondWithError(s, i, "Error creating user profile: "+createUserError.Error())
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 {
s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "Error processing command: " + handlerErr.Error(),
})
return
}
if response == "" {
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())
}
}
}