fix: error handling (maybe)

This commit is contained in:
Siwoo Jeon 2025-07-02 13:59:44 +09:00
parent ee6b2712c3
commit 5f5c14df7e
Signed by: migan
GPG key ID: 036E9A8C5E8E48DA
19 changed files with 191 additions and 154 deletions

View file

@ -29,7 +29,7 @@ var ChatCommand *Command = &Command{
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
RegisterMessageCommand: false, RegisterMessageCommand: false,
Flags: CommandFlagsIsRegistered, Flags: CommandFlagsIsRegistered,
ChatInputRun: func(ctx *ChatInputContext) { ChatInputRun: func(ctx *ChatInputContext) error {
i := ctx.Inter i := ctx.Inter
i.DeferReply(&discordgo.InteractionResponseData{}) i.DeferReply(&discordgo.InteractionResponseData{})
@ -39,11 +39,11 @@ var ChatCommand *Command = &Command{
i.EditReply(&utils.InteractionEdit{ i.EditReply(&utils.InteractionEdit{
Content: &str, Content: &str,
}) })
return return nil
} }
result := chatbot.ParseResult(str, ctx.Inter.Session, i) result := chatbot.ParseResult(str, ctx.Inter.Session, i)
i.EditReply(&utils.InteractionEdit{ return i.EditReply(&utils.InteractionEdit{
Content: &result, Content: &result,
}) })
}, },

View file

@ -43,17 +43,17 @@ var DataLengthCommand *Command = &Command{
}, },
Category: General, Category: General,
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
RegisterMessageCommand: true, RegisterMessageCommand: true,
Flags: CommandFlagsIsRegistered, Flags: CommandFlagsIsRegistered,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
dataLengthRun(ctx.Msg.Session, ctx.Msg, ctx.Msg.Author.Username, ctx.Msg.Author.ID) return dataLengthRun(ctx.Msg.Session, ctx.Msg, ctx.Msg.Author.Username, ctx.Msg.Author.ID)
}, },
ChatInputRun: func(ctx *ChatInputContext) { ChatInputRun: func(ctx *ChatInputContext) error {
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{ ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral, Flags: discordgo.MessageFlagsEphemeral,
}) })
dataLengthRun(ctx.Inter.Session, ctx.Inter, ctx.Inter.Member.User.Username, ctx.Inter.Member.User.ID) return dataLengthRun(ctx.Inter.Session, ctx.Inter, ctx.Inter.Member.User.Username, ctx.Inter.Member.User.ID)
}, },
} }
@ -74,7 +74,7 @@ func getLength(ch chan chStruct, dType dataType, coll *mongo.Collection, filter
ch <- chStruct{name: dType, length: len(data)} ch <- chStruct{name: dType, length: len(data)}
} }
func dataLengthRun(s *discordgo.Session, m any, username, userId string) { func dataLengthRun(s *discordgo.Session, m any, username, userId string) error {
ch := make(chan chStruct) ch := make(chan chStruct)
var textLength, var textLength,
muffinLength, muffinLength,
@ -118,7 +118,7 @@ func dataLengthRun(s *discordgo.Session, m any, username, userId string) {
sum := textLength + learnLength sum := textLength + learnLength
utils.NewMessageSender(m). return utils.NewMessageSender(m).
AddComponents(discordgo.Container{ AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{ Components: []discordgo.MessageComponent{
discordgo.Section{ discordgo.Section{

View file

@ -33,7 +33,7 @@ var DeleteLearnedDataCommand *Command = &Command{
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
RegisterMessageCommand: true, RegisterMessageCommand: true,
Flags: CommandFlagsIsRegistered, Flags: CommandFlagsIsRegistered,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
command := strings.Join(*ctx.Args, " ") command := strings.Join(*ctx.Args, " ")
if command == "" { if command == "" {
utils.NewMessageSender(ctx.Msg). utils.NewMessageSender(ctx.Msg).
@ -51,13 +51,17 @@ var DeleteLearnedDataCommand *Command = &Command{
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return nil
} }
deleteLearnedDataRun(ctx.Msg, strings.Join(*ctx.Args, " "), ctx.Msg.Author.ID) return deleteLearnedDataRun(ctx.Msg, strings.Join(*ctx.Args, " "), ctx.Msg.Author.ID)
}, },
ChatInputRun: func(ctx *ChatInputContext) { ChatInputRun: func(ctx *ChatInputContext) error {
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{ err := ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral, Flags: discordgo.MessageFlagsEphemeral,
}) })
if err != nil {
return err
}
var command string var command string
@ -65,23 +69,18 @@ var DeleteLearnedDataCommand *Command = &Command{
command = opt.StringValue() command = opt.StringValue()
} }
deleteLearnedDataRun(ctx.Inter, command, ctx.Inter.Member.User.ID) return deleteLearnedDataRun(ctx.Inter, command, ctx.Inter.Member.User.ID)
}, },
} }
func deleteLearnedDataRun(m any, command, userId string) { func deleteLearnedDataRun(m any, command, userId string) error {
var data []databases.Learn var data []databases.Learn
var sections []discordgo.Section var sections []discordgo.Section
var containers []*discordgo.Container var containers []*discordgo.Container
cur, err := databases.Database.Learns.Find(context.TODO(), bson.M{"user_id": userId, "command": command}) cur, err := databases.Database.Learns.Find(context.TODO(), bson.M{"user_id": userId, "command": command})
if err != nil { if err != nil {
utils.NewMessageSender(m). return err
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "데이터를 가져오는데 실패했어요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
} }
cur.All(context.TODO(), &data) cur.All(context.TODO(), &data)
@ -92,7 +91,7 @@ func deleteLearnedDataRun(m any, command, userId string) {
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
for i, data := range data { for i, data := range data {
@ -127,7 +126,7 @@ func deleteLearnedDataRun(m any, command, userId string) {
containers = append(containers, container) containers = append(containers, container)
} }
utils.PaginationEmbedBuilder(m). return utils.PaginationEmbedBuilder(m).
AddContainers(containers...). AddContainers(containers...).
Start() Start()
} }

View file

@ -20,13 +20,13 @@ var DeregisterCommand *Command = &Command{
RegisterMessageCommand: true, RegisterMessageCommand: true,
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
Flags: CommandFlagsIsRegistered, Flags: CommandFlagsIsRegistered,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
deregisterRun(ctx.Msg, ctx.Msg.Author.ID, ctx.Msg.Session.State.User.Username) return deregisterRun(ctx.Msg, ctx.Msg.Author.ID, ctx.Msg.Session.State.User.Username)
}, },
} }
func deregisterRun(m any, userId, botName string) { func deregisterRun(m any, userId, botName string) error {
utils.NewMessageSender(m). return utils.NewMessageSender(m).
AddComponents(discordgo.Container{ AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{ Components: []discordgo.MessageComponent{
discordgo.TextDisplay{ discordgo.TextDisplay{

View file

@ -9,10 +9,10 @@ import (
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
) )
type modalRun func(ctx *ModalContext) type modalRun func(ctx *ModalContext) error
type messageRun func(ctx *MsgContext) type messageRun func(ctx *MsgContext) error
type chatInputRun func(ctx *ChatInputContext) type chatInputRun func(ctx *ChatInputContext) error
type componentRun func(ctx *ComponentContext) type componentRun func(ctx *ComponentContext) error
type modalParse func(ctx *ModalContext) bool type modalParse func(ctx *ModalContext) bool
type componentParse func(ctx *ComponentContext) bool type componentParse func(ctx *ComponentContext) bool
@ -126,7 +126,7 @@ func (d *DiscommandStruct) LoadModal(m *Modal) {
d.Modals = append(d.Modals, m) d.Modals = append(d.Modals, m)
} }
func (d *DiscommandStruct) MessageRun(name string, s *discordgo.Session, msg *discordgo.MessageCreate, args []string) { func (d *DiscommandStruct) MessageRun(name string, s *discordgo.Session, msg *discordgo.MessageCreate, args []string) error {
m := &utils.MessageCreate{ m := &utils.MessageCreate{
MessageCreate: msg, MessageCreate: msg,
Session: s, Session: s,
@ -139,7 +139,7 @@ func (d *DiscommandStruct) MessageRun(name string, s *discordgo.Session, msg *di
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
if command.Flags&CommandFlagsIsRegistered != 0 && !databases.Database.IsUser(m.Author.ID) { if command.Flags&CommandFlagsIsRegistered != 0 && !databases.Database.IsUser(m.Author.ID) {
@ -148,14 +148,15 @@ func (d *DiscommandStruct) MessageRun(name string, s *discordgo.Session, msg *di
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
command.MessageRun(&MsgContext{m, &args, command}) return command.MessageRun(&MsgContext{m, &args, command})
} }
return nil
} }
func (d *DiscommandStruct) ChatInputRun(name string, s *discordgo.Session, inter *discordgo.InteractionCreate) { func (d *DiscommandStruct) ChatInputRun(name string, s *discordgo.Session, inter *discordgo.InteractionCreate) error {
i := &utils.InteractionCreate{ i := &utils.InteractionCreate{
InteractionCreate: inter, InteractionCreate: inter,
Session: s, Session: s,
@ -172,7 +173,7 @@ func (d *DiscommandStruct) ChatInputRun(name string, s *discordgo.Session, inter
SetEphemeral(true). SetEphemeral(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
if command.Flags&CommandFlagsIsRegistered != 0 && !databases.Database.IsUser(i.User.ID) { if command.Flags&CommandFlagsIsRegistered != 0 && !databases.Database.IsUser(i.User.ID) {
@ -182,14 +183,17 @@ func (d *DiscommandStruct) ChatInputRun(name string, s *discordgo.Session, inter
SetEphemeral(true). SetEphemeral(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
command.ChatInputRun(&ChatInputContext{i, command}) return command.ChatInputRun(&ChatInputContext{i, command})
} }
return nil
} }
func (d *DiscommandStruct) ComponentRun(s *discordgo.Session, inter *discordgo.InteractionCreate) { func (d *DiscommandStruct) ComponentRun(s *discordgo.Session, inter *discordgo.InteractionCreate) error {
var err error
i := &utils.InteractionCreate{ i := &utils.InteractionCreate{
InteractionCreate: inter, InteractionCreate: inter,
Session: s, Session: s,
@ -207,12 +211,15 @@ func (d *DiscommandStruct) ComponentRun(s *discordgo.Session, inter *discordgo.I
continue continue
} }
c.Run(data) err = c.Run(data)
break break
} }
return err
} }
func (d *DiscommandStruct) ModalRun(s *discordgo.Session, i *discordgo.InteractionCreate) { func (d *DiscommandStruct) ModalRun(s *discordgo.Session, i *discordgo.InteractionCreate) error {
var err error
data := &ModalContext{ data := &ModalContext{
Inter: &utils.InteractionCreate{ Inter: &utils.InteractionCreate{
InteractionCreate: i, InteractionCreate: i,
@ -227,7 +234,8 @@ func (d *DiscommandStruct) ModalRun(s *discordgo.Session, i *discordgo.Interacti
continue continue
} }
m.Run(data) err = m.Run(data)
break break
} }
return err
} }

View file

@ -31,17 +31,17 @@ var HelpCommand *Command = &Command{
Category: General, Category: General,
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
RegisterMessageCommand: true, RegisterMessageCommand: true,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
helpRun(ctx.Msg.Session, ctx.Msg, strings.Join(*ctx.Args, " ")) return helpRun(ctx.Msg.Session, ctx.Msg, strings.Join(*ctx.Args, " "))
}, },
ChatInputRun: func(ctx *ChatInputContext) { ChatInputRun: func(ctx *ChatInputContext) error {
var command string var command string
if opt, ok := ctx.Inter.Options["명령어"]; ok { if opt, ok := ctx.Inter.Options["명령어"]; ok {
command = opt.StringValue() command = opt.StringValue()
} }
helpRun(ctx.Inter.Session, ctx.Inter, command) return helpRun(ctx.Inter.Session, ctx.Inter, command)
}, },
} }
@ -55,7 +55,7 @@ func getCommandsByCategory(d *DiscommandStruct, category Category) []string {
return commands return commands
} }
func helpRun(s *discordgo.Session, m any, commandName string) { func helpRun(s *discordgo.Session, m any, commandName string) error {
section := &discordgo.Section{ section := &discordgo.Section{
Accessory: discordgo.Thumbnail{ Accessory: discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{ Media: discordgo.UnfurledMediaItem{
@ -78,14 +78,13 @@ func helpRun(s *discordgo.Session, m any, commandName string) {
Content: fmt.Sprintf("- **채팅**\n%s", strings.Join(getCommandsByCategory(Discommand, Chatting), "\n")), Content: fmt.Sprintf("- **채팅**\n%s", strings.Join(getCommandsByCategory(Discommand, Chatting), "\n")),
}, },
) )
utils.NewMessageSender(m). return utils.NewMessageSender(m).
AddComponents(&discordgo.Container{ AddComponents(&discordgo.Container{
Components: []discordgo.MessageComponent{section}, Components: []discordgo.MessageComponent{section},
}). }).
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return
} }
var aliases, examples discordgo.TextDisplay var aliases, examples discordgo.TextDisplay
@ -128,17 +127,16 @@ func helpRun(s *discordgo.Session, m any, commandName string) {
learnArgs := discordgo.TextDisplay{ learnArgs := discordgo.TextDisplay{
Content: fmt.Sprintf("- **대답에 쓸 수 있는 인자**\n%s", learnArguments), Content: fmt.Sprintf("- **대답에 쓸 수 있는 인자**\n%s", learnArguments),
} }
utils.NewMessageSender(m). return utils.NewMessageSender(m).
AddComponents(discordgo.Container{ AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{section, aliases, examples, learnArgs}, Components: []discordgo.MessageComponent{section, aliases, examples, learnArgs},
}). }).
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return
} }
utils.NewMessageSender(m). return utils.NewMessageSender(m).
AddComponents(discordgo.Container{ AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{section, aliases, examples}, Components: []discordgo.MessageComponent{section, aliases, examples},
}). }).

View file

@ -19,17 +19,20 @@ var InformationCommand *Command = &Command{
Category: General, Category: General,
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
RegisterMessageCommand: true, RegisterMessageCommand: true,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
informationRun(ctx.Msg.Session, ctx.Msg) return informationRun(ctx.Msg.Session, ctx.Msg)
}, },
ChatInputRun: func(ctx *ChatInputContext) { ChatInputRun: func(ctx *ChatInputContext) error {
informationRun(ctx.Inter.Session, ctx.Inter) return informationRun(ctx.Inter.Session, ctx.Inter)
}, },
} }
func informationRun(s *discordgo.Session, m any) { func informationRun(s *discordgo.Session, m any) error {
owner, _ := s.User(configs.Config.Bot.OwnerId) owner, err := s.User(configs.Config.Bot.OwnerId)
utils.NewMessageSender(m). if err != nil {
return err
}
return utils.NewMessageSender(m).
AddComponents(discordgo.Container{ AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{ Components: []discordgo.MessageComponent{
discordgo.Section{ discordgo.Section{

View file

@ -3,7 +3,6 @@ package commands
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"strings" "strings"
"time" "time"
@ -60,7 +59,7 @@ var LearnCommand *Command = &Command{
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
RegisterMessageCommand: true, RegisterMessageCommand: true,
Flags: CommandFlagsIsRegistered, Flags: CommandFlagsIsRegistered,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
if len(*ctx.Args) < 2 { if len(*ctx.Args) < 2 {
utils.NewMessageSender(ctx.Msg). utils.NewMessageSender(ctx.Msg).
AddComponents(utils.GetErrorContainer( AddComponents(utils.GetErrorContainer(
@ -80,15 +79,18 @@ var LearnCommand *Command = &Command{
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
learnRun(ctx.Msg, ctx.Msg.Author.ID, strings.ReplaceAll((*ctx.Args)[0], "_", " "), strings.ReplaceAll((*ctx.Args)[1], "_", " ")) return learnRun(ctx.Msg, ctx.Msg.Author.ID, strings.ReplaceAll((*ctx.Args)[0], "_", " "), strings.ReplaceAll((*ctx.Args)[1], "_", " "))
}, },
ChatInputRun: func(ctx *ChatInputContext) { ChatInputRun: func(ctx *ChatInputContext) error {
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{ err := ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral, Flags: discordgo.MessageFlagsEphemeral,
}) })
if err != nil {
return err
}
var command, result string var command, result string
@ -100,11 +102,11 @@ var LearnCommand *Command = &Command{
result = opt.StringValue() result = opt.StringValue()
} }
learnRun(ctx.Inter, ctx.Inter.Member.User.ID, command, result) return learnRun(ctx.Inter, ctx.Inter.Member.User.ID, command, result)
}, },
} }
func learnRun(m any, userId, command, result string) { func learnRun(m any, userId, command, result string) error {
igCommands := []string{} igCommands := []string{}
for _, command := range Discommand.Commands { for _, command := range Discommand.Commands {
@ -128,7 +130,7 @@ func learnRun(m any, userId, command, result string) {
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
} }
@ -139,7 +141,7 @@ func learnRun(m any, userId, command, result string) {
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
} }
@ -149,6 +151,7 @@ func learnRun(m any, userId, command, result string) {
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return nil
} }
_, err := databases.Database.Learns.InsertOne(context.TODO(), databases.InsertLearn{ _, err := databases.Database.Learns.InsertOne(context.TODO(), databases.InsertLearn{
@ -158,17 +161,15 @@ func learnRun(m any, userId, command, result string) {
CreatedAt: time.Now(), CreatedAt: time.Now(),
}) })
if err != nil { if err != nil {
log.Println(err)
utils.NewMessageSender(m). utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "단어를 배우는데 오류가 생겼어요."})). AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "단어를 배우는데 오류가 생겼어요."})).
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return err
} }
utils.NewMessageSender(m). return utils.NewMessageSender(m).
AddComponents(utils.GetSuccessContainer( AddComponents(utils.GetSuccessContainer(
discordgo.TextDisplay{ discordgo.TextDisplay{
Content: fmt.Sprintf("%s 배웠어요.", hangul.GetJosa(command, hangul.EUL_REUL)), Content: fmt.Sprintf("%s 배웠어요.", hangul.GetJosa(command, hangul.EUL_REUL)),

View file

@ -54,7 +54,7 @@ var LearnedDataListCommand *Command = &Command{
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
RegisterMessageCommand: true, RegisterMessageCommand: true,
Flags: CommandFlagsIsRegistered, Flags: CommandFlagsIsRegistered,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
var length int var length int
filter := bson.D{{Key: "user_id", Value: ctx.Msg.Author.ID}} filter := bson.D{{Key: "user_id", Value: ctx.Msg.Author.ID}}
@ -76,7 +76,7 @@ var LearnedDataListCommand *Command = &Command{
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
if float64(length) > LIST_MAX_VALUE { if float64(length) > LIST_MAX_VALUE {
@ -85,15 +85,18 @@ var LearnedDataListCommand *Command = &Command{
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
} }
learnedDataListRun(ctx.Msg, ctx.Msg.Author.GlobalName, ctx.Msg.Author.AvatarURL("512"), filter, length) return learnedDataListRun(ctx.Msg, ctx.Msg.Author.GlobalName, ctx.Msg.Author.AvatarURL("512"), filter, length)
}, },
ChatInputRun: func(ctx *ChatInputContext) { ChatInputRun: func(ctx *ChatInputContext) error {
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{ err := ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral, Flags: discordgo.MessageFlagsEphemeral,
}) })
if err != nil {
return err
}
var length int var length int
@ -109,7 +112,7 @@ var LearnedDataListCommand *Command = &Command{
if opt, ok := ctx.Inter.Options["개수"]; ok { if opt, ok := ctx.Inter.Options["개수"]; ok {
length = int(opt.IntValue()) length = int(opt.IntValue())
} }
learnedDataListRun(ctx.Inter, ctx.Inter.Member.User.GlobalName, ctx.Inter.Member.User.AvatarURL("512"), filter, length) return learnedDataListRun(ctx.Inter, ctx.Inter.Member.User.GlobalName, ctx.Inter.Member.User.AvatarURL("512"), filter, length)
}, },
} }
@ -173,7 +176,7 @@ func getContainers(accessory *discordgo.Thumbnail, defaultDesc string, items []s
return containers return containers
} }
func learnedDataListRun(m any, globalName, avatarUrl string, filter bson.D, length int) { func learnedDataListRun(m any, globalName, avatarUrl string, filter bson.D, length int) error {
var data []databases.Learn var data []databases.Learn
itemsMap := map[string]string{} itemsMap := map[string]string{}
@ -187,17 +190,15 @@ func learnedDataListRun(m any, globalName, avatarUrl string, filter bson.D, leng
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
fmt.Println(err)
utils.NewMessageSender(m). utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "데이터를 가져오는데 실패했어요."})). AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "데이터를 가져오는데 실패했어요."})).
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return err
} }
defer cur.Close(context.TODO()) defer cur.Close(context.TODO())
@ -217,10 +218,9 @@ func learnedDataListRun(m any, globalName, avatarUrl string, filter bson.D, leng
}, },
}, fmt.Sprintf("### %s님이 알려주신 지식\n- **%s**\n", globalName, command)+"%s", items, length) }, fmt.Sprintf("### %s님이 알려주신 지식\n- **%s**\n", globalName, command)+"%s", items, length)
utils.PaginationEmbedBuilder(m). return utils.PaginationEmbedBuilder(m).
AddContainers(containers...). AddContainers(containers...).
Start() Start()
return
} }
for _, data := range data { for _, data := range data {
@ -241,7 +241,7 @@ func learnedDataListRun(m any, globalName, avatarUrl string, filter bson.D, leng
}, },
}, fmt.Sprintf("### %s님이 알려주신 지식\n총 %d개에요.\n", globalName, len(items))+"%s", items, length) }, fmt.Sprintf("### %s님이 알려주신 지식\n총 %d개에요.\n", globalName, len(items))+"%s", items, length)
utils.PaginationEmbedBuilder(m). return utils.PaginationEmbedBuilder(m).
AddContainers(containers...). AddContainers(containers...).
Start() Start()
} }

View file

@ -20,25 +20,25 @@ var RegisterCommand *Command = &Command{
Category: General, Category: General,
RegisterMessageCommand: true, RegisterMessageCommand: true,
RegisterApplicationCommand: true, RegisterApplicationCommand: true,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
registerRun(ctx.Msg, ctx.Msg.Author.ID, ctx.Msg.Session.State.User.Username) return registerRun(ctx.Msg, ctx.Msg.Author.ID, ctx.Msg.Session.State.User.Username)
}, },
ChatInputRun: func(ctx *ChatInputContext) { ChatInputRun: func(ctx *ChatInputContext) error {
registerRun(ctx.Inter, ctx.Inter.User.ID, ctx.Inter.Session.State.User.Username) return registerRun(ctx.Inter, ctx.Inter.User.ID, ctx.Inter.Session.State.User.Username)
}, },
} }
func registerRun(m any, userId, botName string) { func registerRun(m any, userId, botName string) error {
if databases.Database.IsUser(userId) { if databases.Database.IsUser(userId) {
utils.NewMessageSender(m). utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: fmt.Sprintf("당신은 이미 가입되어있어요. 만약 탈퇴를 원하시면 %s탈퇴를 이용해주세요.", configs.Config.Bot.Prefix)})). AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: fmt.Sprintf("당신은 이미 가입되어있어요. 만약 탈퇴를 원하시면 %s탈퇴를 이용해주세요.", configs.Config.Bot.Prefix)})).
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).
Send() Send()
return return nil
} }
utils.NewMessageSender(m). return utils.NewMessageSender(m).
AddComponents(discordgo.Container{ AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{ Components: []discordgo.MessageComponent{
discordgo.TextDisplay{ discordgo.TextDisplay{

View file

@ -2,7 +2,6 @@ package commands
import ( import (
"fmt" "fmt"
"log"
"git.wh64.net/muffin/goMuffin/chatbot" "git.wh64.net/muffin/goMuffin/chatbot"
"git.wh64.net/muffin/goMuffin/configs" "git.wh64.net/muffin/goMuffin/configs"
@ -22,19 +21,13 @@ var ReloadPromptCommand *Command = &Command{
RegisterApplicationCommand: false, RegisterApplicationCommand: false,
RegisterMessageCommand: true, RegisterMessageCommand: true,
Flags: CommandFlagsIsDeveloper, Flags: CommandFlagsIsDeveloper,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
err := chatbot.ChatBot.ReloadPrompt() err := chatbot.ChatBot.ReloadPrompt()
if err != nil { if err != nil {
log.Fatalln(err) return err
utils.NewMessageSender(ctx.Msg).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "프롬프트를 다시 불러오는 데 문제가 생겼어요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
} }
utils.NewMessageSender(ctx.Msg). return utils.NewMessageSender(ctx.Msg).
AddComponents(utils.GetSuccessContainer(discordgo.TextDisplay{Content: "프롬프트를 다시 불러왔어요."})). AddComponents(utils.GetSuccessContainer(discordgo.TextDisplay{Content: "프롬프트를 다시 불러왔어요."})).
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).

View file

@ -21,10 +21,10 @@ var SwitchModeCommand *Command = &Command{
RegisterApplicationCommand: false, RegisterApplicationCommand: false,
RegisterMessageCommand: true, RegisterMessageCommand: true,
Flags: CommandFlagsIsDeveloper, Flags: CommandFlagsIsDeveloper,
MessageRun: func(ctx *MsgContext) { MessageRun: func(ctx *MsgContext) error {
chatbot.ChatBot.SwitchMode() chatbot.ChatBot.SwitchMode()
utils.NewMessageSender(ctx.Msg). return utils.NewMessageSender(ctx.Msg).
AddComponents(utils.GetSuccessContainer(discordgo.TextDisplay{Content: fmt.Sprintf("모드를 %s로 바꾸었어요.", chatbot.ChatBot.ModeString())})). AddComponents(utils.GetSuccessContainer(discordgo.TextDisplay{Content: fmt.Sprintf("모드를 %s로 바꾸었어요.", chatbot.ChatBot.ModeString())})).
SetComponentsV2(true). SetComponentsV2(true).
SetReply(true). SetReply(true).

View file

@ -34,10 +34,13 @@ var DeleteLearnedDataComponent *commands.Component = &commands.Component{
} }
return true return true
}, },
Run: func(ctx *commands.ComponentContext) { Run: func(ctx *commands.ComponentContext) error {
i := ctx.Inter i := ctx.Inter
i.DeferUpdate() err := i.DeferUpdate()
if err != nil {
return err
}
id, itemId := utils.GetDeleteLearnedDataId(i.MessageComponentData().CustomID) id, itemId := utils.GetDeleteLearnedDataId(i.MessageComponentData().CustomID)
fmt.Println(id, itemId) fmt.Println(id, itemId)
@ -45,7 +48,7 @@ var DeleteLearnedDataComponent *commands.Component = &commands.Component{
databases.Database.Learns.DeleteOne(context.TODO(), bson.D{{Key: "_id", Value: id}}) databases.Database.Learns.DeleteOne(context.TODO(), bson.D{{Key: "_id", Value: id}})
flags := discordgo.MessageFlagsIsComponentsV2 flags := discordgo.MessageFlagsIsComponentsV2
i.EditReply(&utils.InteractionEdit{ return i.EditReply(&utils.InteractionEdit{
Flags: &flags, Flags: &flags,
Components: &[]discordgo.MessageComponent{ Components: &[]discordgo.MessageComponent{
utils.GetSuccessContainer(discordgo.TextDisplay{Content: fmt.Sprintf("%d번을 삭ㅈ제했어요.", itemId)}), utils.GetSuccessContainer(discordgo.TextDisplay{Content: fmt.Sprintf("%d번을 삭ㅈ제했어요.", itemId)}),

View file

@ -2,7 +2,6 @@ package components
import ( import (
"context" "context"
"log"
"strings" "strings"
"git.wh64.net/muffin/goMuffin/commands" "git.wh64.net/muffin/goMuffin/commands"
@ -24,8 +23,12 @@ var DeregisterComponent *commands.Component = &commands.Component{
} }
return true return true
}, },
Run: func(ctx *commands.ComponentContext) { Run: func(ctx *commands.ComponentContext) error {
ctx.Inter.DeferUpdate() err := ctx.Inter.DeferUpdate()
if err != nil {
return err
}
customId := ctx.Inter.MessageComponentData().CustomID customId := ctx.Inter.MessageComponentData().CustomID
flags := discordgo.MessageFlagsIsComponentsV2 flags := discordgo.MessageFlagsIsComponentsV2
@ -34,26 +37,20 @@ var DeregisterComponent *commands.Component = &commands.Component{
filter := bson.D{{Key: "user_id", Value: ctx.Inter.User.ID}} filter := bson.D{{Key: "user_id", Value: ctx.Inter.User.ID}}
_, err := databases.Database.Users.DeleteOne(context.TODO(), filter) _, err := databases.Database.Users.DeleteOne(context.TODO(), filter)
if err != nil { if err != nil {
log.Println(err) return err
// 나중에 에러처리 바꿔야지 :(
return
} }
_, err = databases.Database.Learns.DeleteMany(context.TODO(), filter) _, err = databases.Database.Learns.DeleteMany(context.TODO(), filter)
if err != nil { if err != nil {
log.Println(err) return err
// 나중에 에러처리 바꿔야지 :(
return
} }
_, err = databases.Database.Memory.DeleteMany(context.TODO(), filter) _, err = databases.Database.Memory.DeleteMany(context.TODO(), filter)
if err != nil { if err != nil {
log.Println(err) return err
// 나중에 에러처리 바꿔야지 :(
return
} }
ctx.Inter.EditReply(&utils.InteractionEdit{ return ctx.Inter.EditReply(&utils.InteractionEdit{
Flags: &flags, Flags: &flags,
Components: &[]discordgo.MessageComponent{ Components: &[]discordgo.MessageComponent{
utils.GetSuccessContainer(discordgo.TextDisplay{ utils.GetSuccessContainer(discordgo.TextDisplay{
@ -61,9 +58,8 @@ var DeregisterComponent *commands.Component = &commands.Component{
}), }),
}, },
}) })
return
case strings.HasPrefix(customId, utils.DeregisterDisagree): case strings.HasPrefix(customId, utils.DeregisterDisagree):
ctx.Inter.EditReply(&utils.InteractionEdit{ return ctx.Inter.EditReply(&utils.InteractionEdit{
Flags: &flags, Flags: &flags,
Components: &[]discordgo.MessageComponent{ Components: &[]discordgo.MessageComponent{
utils.GetDeclineContainer(discordgo.TextDisplay{ utils.GetDeclineContainer(discordgo.TextDisplay{
@ -71,7 +67,7 @@ var DeregisterComponent *commands.Component = &commands.Component{
}), }),
}, },
}) })
return
} }
return nil
}, },
} }

View file

@ -33,17 +33,20 @@ var PaginationEmbedComponent *commands.Component = &commands.Component{
} }
return true return true
}, },
Run: func(ctx *commands.ComponentContext) { Run: func(ctx *commands.ComponentContext) error {
customId := ctx.Inter.MessageComponentData().CustomID customId := ctx.Inter.MessageComponentData().CustomID
id := utils.GetPaginationEmbedId(customId) id := utils.GetPaginationEmbedId(customId)
p := utils.GetPaginationEmbed(id) p := utils.GetPaginationEmbed(id)
if strings.HasPrefix(customId, utils.PaginationEmbedPrev) { if strings.HasPrefix(customId, utils.PaginationEmbedPrev) {
p.Prev(ctx.Inter) p.Prev(ctx.Inter)
return nil
} else if strings.HasPrefix(customId, utils.PaginationEmbedNext) { } else if strings.HasPrefix(customId, utils.PaginationEmbedNext) {
p.Next(ctx.Inter) p.Next(ctx.Inter)
return nil
} else { } else {
p.ShowModal(ctx.Inter) p.ShowModal(ctx.Inter)
return nil
} }
}, },
} }

View file

@ -3,7 +3,7 @@ package components
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"strings" "strings"
"time" "time"
@ -25,8 +25,12 @@ var RegisterComponent *commands.Component = &commands.Component{
} }
return true return true
}, },
Run: func(ctx *commands.ComponentContext) { Run: func(ctx *commands.ComponentContext) error {
ctx.Inter.DeferUpdate() err := ctx.Inter.DeferUpdate()
if err != nil {
return err
}
customId := ctx.Inter.MessageComponentData().CustomID customId := ctx.Inter.MessageComponentData().CustomID
flags := discordgo.MessageFlagsIsComponentsV2 flags := discordgo.MessageFlagsIsComponentsV2
@ -37,19 +41,10 @@ var RegisterComponent *commands.Component = &commands.Component{
CreatedAt: time.Now(), CreatedAt: time.Now(),
}) })
if err != nil { if err != nil {
log.Println(err) return err
ctx.Inter.EditReply(&utils.InteractionEdit{
Flags: &flags,
Components: &[]discordgo.MessageComponent{
utils.GetErrorContainer(discordgo.TextDisplay{
Content: "가입을 하다가 오류가 생겼어요.",
}),
},
})
return
} }
ctx.Inter.EditReply(&utils.InteractionEdit{ return ctx.Inter.EditReply(&utils.InteractionEdit{
Flags: &flags, Flags: &flags,
Components: &[]discordgo.MessageComponent{ Components: &[]discordgo.MessageComponent{
utils.GetSuccessContainer(discordgo.TextDisplay{ utils.GetSuccessContainer(discordgo.TextDisplay{
@ -57,9 +52,8 @@ var RegisterComponent *commands.Component = &commands.Component{
}), }),
}, },
}) })
return
case strings.HasPrefix(customId, utils.ServiceDisagree): case strings.HasPrefix(customId, utils.ServiceDisagree):
ctx.Inter.EditReply(&utils.InteractionEdit{ return ctx.Inter.EditReply(&utils.InteractionEdit{
Flags: &flags, Flags: &flags,
Components: &[]discordgo.MessageComponent{ Components: &[]discordgo.MessageComponent{
utils.GetDeclineContainer(discordgo.TextDisplay{ utils.GetDeclineContainer(discordgo.TextDisplay{
@ -67,7 +61,7 @@ var RegisterComponent *commands.Component = &commands.Component{
}), }),
}, },
}) })
return
} }
return nil
}, },
} }

View file

@ -1,18 +1,45 @@
package handler package handler
import ( import (
"fmt"
"log"
"git.wh64.net/muffin/goMuffin/commands" "git.wh64.net/muffin/goMuffin/commands"
"git.wh64.net/muffin/goMuffin/configs"
"git.wh64.net/muffin/goMuffin/utils"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
) )
func InteractionCreate(s *discordgo.Session, i *discordgo.InteractionCreate) { func InteractionCreate(s *discordgo.Session, i *discordgo.InteractionCreate) {
var err error
switch i.Type { switch i.Type {
case discordgo.InteractionApplicationCommand: case discordgo.InteractionApplicationCommand:
commands.Discommand.ChatInputRun(i.ApplicationCommandData().Name, s, i) err = commands.Discommand.ChatInputRun(i.ApplicationCommandData().Name, s, i)
return if err != nil {
goto ErrMsg
}
case discordgo.InteractionMessageComponent: case discordgo.InteractionMessageComponent:
commands.Discommand.ComponentRun(s, i) err = commands.Discommand.ComponentRun(s, i)
if err != nil {
goto ErrMsg
}
case discordgo.InteractionModalSubmit: case discordgo.InteractionModalSubmit:
commands.Discommand.ModalRun(s, i) err = commands.Discommand.ModalRun(s, i)
if err != nil {
goto ErrMsg
}
} }
// 아 몰라 goto 쓸래
ErrMsg:
log.Println(err)
owner, _ := s.User(configs.Config.Bot.OwnerId)
utils.NewMessageSender(&utils.InteractionCreate{
InteractionCreate: i,
Session: s,
}).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: fmt.Sprintf("오류가 발생하였어요. 만약 계속 발생한다면, %s으로 연락해주세요.", utils.InlineCode(owner.Username))})).
SetComponentsV2(true).
SetReply(true).
Send()
} }

View file

@ -75,7 +75,19 @@ func MessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
return return
} }
commands.Discommand.MessageRun(command, s, m, args[1:]) err := commands.Discommand.MessageRun(command, s, m, args[1:])
if err != nil {
log.Println(err)
utils.NewMessageSender(&utils.MessageCreate{
MessageCreate: m,
Session: s,
}).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "오류가 발생하였어요. 만약 계속 발생한다면, `migan.`으로 연락해주세요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
return return
} else { } else {
if m.Author.ID == config.Chatbot.Train.UserId { if m.Author.ID == config.Chatbot.Train.UserId {

View file

@ -52,7 +52,7 @@ var PaginationEmbedModal *commands.Modal = &commands.Modal{
return true return true
}, },
Run: func(ctx *commands.ModalContext) { Run: func(ctx *commands.ModalContext) error {
data := ctx.Inter.ModalSubmitData() data := ctx.Inter.ModalSubmitData()
customId := data.CustomID customId := data.CustomID
id := utils.GetPaginationEmbedId(customId) id := utils.GetPaginationEmbedId(customId)
@ -61,6 +61,6 @@ var PaginationEmbedModal *commands.Modal = &commands.Modal{
page, _ := strconv.Atoi(cmp.Value) page, _ := strconv.Atoi(cmp.Value)
p.Set(ctx.Inter, page) return p.Set(ctx.Inter, page)
}, },
} }