Compare commits

...

20 commits

Author SHA1 Message Date
9bfc53bf37
fix: delete error container 2025-05-25 16:49:20 +09:00
d41e74bb55
feat: recreated delete learn data command 2025-05-24 23:44:37 +09:00
fbef008f4f
fix: pagination embed 2025-05-24 23:33:02 +09:00
4cf4b42989
feat: learn command componentsV2 2025-05-24 16:31:49 +09:00
3a5cfd6a58
feat: data length command componentsV2 2025-05-24 16:10:51 +09:00
6468521ee1
feat: Add help command componentsV2 2025-05-24 15:52:27 +09:00
6fd272ef5f
chore: add AddPrefix method 2025-05-24 15:52:16 +09:00
35347edb85
feat: information command componentsV2 2025-05-24 14:33:28 +09:00
b6ac950f2e
feat!: change to PaginationEmbed embed to ComponentsV2's container 2025-05-23 23:33:19 +09:00
218c019989
fix: edit type deferReply argument 2025-05-23 23:31:34 +09:00
0fdfd1cbd7
fix: edit type editReply argument 2025-05-23 23:28:37 +09:00
aaf5246218
fix: showModal 2025-05-23 23:22:49 +09:00
15fe432feb
chore: remove unused dependencies 2025-05-21 19:45:54 +09:00
0f911f58be
remove: database migrate 2025-05-19 19:53:20 +09:00
fb58599991
fix: edit next, prev 2025-05-19 19:44:45 +09:00
7390cc31ed
feat: add AllowedMentions 2025-05-18 17:57:32 +09:00
20c0debf4a
chore: use init 2025-05-18 15:02:51 +09:00
797bd56b3d
fix!: remove AddEmbed, AddComponent and add AddEmbeds, AddComponents 2025-05-17 22:04:05 +09:00
5f0bb32e9b
fix!: remove deprecated value in MuffinConfig 2025-05-17 21:12:14 +09:00
63a820f946
feat: MessageSender 2025-05-17 15:09:42 +09:00
24 changed files with 826 additions and 1038 deletions

View file

@ -29,7 +29,7 @@ const (
userLearn
)
var dataLengthCh chan chStruct = make(chan chStruct)
// var dataLengthCh chan chStruct = make(chan chStruct)
var dataLengthWg sync.WaitGroup
var DataLengthCommand *Command = &Command{
@ -44,14 +44,18 @@ var DataLengthCommand *Command = &Command{
},
Category: General,
MessageRun: func(ctx *MsgContext) {
dataLengthRun(ctx.Session, ctx.Msg)
dataLengthRun(ctx.Msg.Session, ctx.Msg, ctx.Msg.Author.Username, ctx.Msg.Author.ID)
},
ChatInputRun: func(ctx *ChatInputContext) {
dataLengthRun(ctx.Session, ctx.Inter)
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
})
dataLengthRun(ctx.Inter.Session, ctx.Inter, ctx.Inter.Member.User.Username, ctx.Inter.Member.User.ID)
},
}
func getLength(dType dataType, coll *mongo.Collection, filter bson.D) {
func getLength(ch chan chStruct, dType dataType, coll *mongo.Collection, filter bson.D) {
defer dataLengthWg.Done()
var err error
var cur *mongo.Cursor
@ -65,33 +69,21 @@ func getLength(dType dataType, coll *mongo.Collection, filter bson.D) {
defer cur.Close(context.TODO())
cur.All(context.TODO(), &data)
dataLengthCh <- chStruct{name: dType, length: len(data)}
ch <- chStruct{name: dType, length: len(data)}
}
func dataLengthRun(s *discordgo.Session, m any) {
var username, userId, channelId string
func dataLengthRun(s *discordgo.Session, m any, username, userId string) {
ch := make(chan chStruct)
var textLength,
muffinLength,
nsfwLength,
learnLength,
userLearnLength int
switch m := m.(type) {
case *discordgo.MessageCreate:
username = m.Author.Username
userId = m.Author.ID
channelId = m.ChannelID
case *utils.InteractionCreate:
m.DeferReply(true)
username = m.Member.User.Username
userId = m.Member.User.ID
channelId = m.ChannelID
}
dataLengthWg.Add(5)
go getLength(text, databases.Database.Texts, bson.D{{}})
go getLength(muffin, databases.Database.Texts, bson.D{{Key: "persona", Value: "muffin"}})
go getLength(nsfw, databases.Database.Texts, bson.D{
go getLength(ch, text, databases.Database.Texts, bson.D{{}})
go getLength(ch, muffin, databases.Database.Texts, bson.D{{Key: "persona", Value: "muffin"}})
go getLength(ch, nsfw, databases.Database.Texts, bson.D{
{
Key: "persona",
Value: bson.M{
@ -99,15 +91,15 @@ func dataLengthRun(s *discordgo.Session, m any) {
},
},
})
go getLength(learn, databases.Database.Learns, bson.D{{}})
go getLength(userLearn, databases.Database.Learns, bson.D{{Key: "user_id", Value: userId}})
go getLength(ch, learn, databases.Database.Learns, bson.D{{}})
go getLength(ch, userLearn, databases.Database.Learns, bson.D{{Key: "user_id", Value: userId}})
go func() {
dataLengthWg.Wait()
close(dataLengthCh)
close(ch)
}()
for resp := range dataLengthCh {
for resp := range ch {
switch dataType(resp.name) {
case text:
textLength = resp.length
@ -124,46 +116,39 @@ func dataLengthRun(s *discordgo.Session, m any) {
sum := textLength + learnLength
// 나중에 djs처럼 Embed 만들어 주는 함수 만들어야겠다
// 지금은 임시방편
embed := &discordgo.MessageEmbed{
Title: "저장된 데이터량",
Description: fmt.Sprintf("총합: %s개", utils.InlineCode(strconv.Itoa(sum))),
Color: utils.EmbedDefault,
Fields: []*discordgo.MessageEmbedField{
{
Name: "총 채팅 데이터량",
Value: utils.InlineCode(strconv.Itoa(textLength)) + "개",
Inline: true,
},
{
Name: "총 지식 데이터량",
Value: utils.InlineCode(strconv.Itoa(learnLength)) + "개",
Inline: true,
},
{
Name: "머핀 데이터량",
Value: utils.InlineCode(strconv.Itoa(muffinLength)) + "개",
},
{
Name: "nsfw 데이터량",
Value: utils.InlineCode(strconv.Itoa(nsfwLength)) + "개",
Inline: true,
},
{
Name: fmt.Sprintf("%s님이 가르쳐준 데이터량", username),
Value: utils.InlineCode(strconv.Itoa(userLearnLength)) + "개",
Inline: true,
utils.NewMessageSender(m).
AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{
discordgo.Section{
Accessory: discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{
URL: s.State.User.AvatarURL("512"),
},
},
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(channelId, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
Components: []discordgo.MessageComponent{
discordgo.TextDisplay{
Content: fmt.Sprintf("### 저장된 데이터량\n총합: %s", utils.InlineCode(strconv.Itoa(sum)+"개")),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **총 채팅 데이터량**\n> %s", utils.InlineCode(strconv.Itoa(textLength))+"개"),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **머핀 데이터량**\n> %s", utils.InlineCode(strconv.Itoa(muffinLength))+"개"),
},
},
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **nsfw 데이터량**\n> %s", utils.InlineCode(strconv.Itoa(nsfwLength))+"개"),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **총 지식 데이터량**\n> %s", utils.InlineCode(strconv.Itoa(learnLength))+"개"),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **%s님이 가르쳐준 데이터량**\n> %s", username, utils.InlineCode(strconv.Itoa(userLearnLength))+"개"),
},
},
}).
SetComponentsV2(true).
SetReply(true).
Send()
}

View file

@ -31,139 +31,100 @@ var DeleteLearnedDataCommand *Command = &Command{
},
Category: Chatting,
MessageRun: func(ctx *MsgContext) {
deleteLearnedDataRun(ctx.Command, ctx.Session, ctx.Msg, ctx.Args)
command := strings.Join(*ctx.Args, " ")
if command == "" {
utils.NewMessageSender(ctx.Msg).
AddComponents(utils.GetErrorContainer(
discordgo.TextDisplay{
Content: "올바르지 않ㅇ은 용법이에요.",
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **사용법**\n> %s", ctx.Command.DetailedDescription.Usage),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **예시**\n%s", strings.Join(utils.AddPrefix("> ", ctx.Command.DetailedDescription.Examples), "\n")),
},
)).
SetComponentsV2(true).
SetReply(true).
Send()
}
deleteLearnedDataRun(ctx.Msg, strings.Join(*ctx.Args, " "), ctx.Msg.Author.ID)
},
ChatInputRun: func(ctx *ChatInputContext) {
deleteLearnedDataRun(ctx.Command, ctx.Session, ctx.Inter, nil)
},
}
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
})
func deleteLearnedDataRun(c *Command, s *discordgo.Session, m any, args *[]string) {
var command, userId, description string
var data []databases.Learn
var options []discordgo.SelectMenuOption
var command string
switch m := m.(type) {
case *discordgo.MessageCreate:
command = strings.Join(*args, " ")
userId = m.Author.ID
if command == "" {
s.ChannelMessageSendEmbedReply(m.ChannelID, &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "올바르지 않ㅇ은 용법이에요.",
Fields: []*discordgo.MessageEmbedField{
{
Name: "사용법",
Value: utils.InlineCode(c.DetailedDescription.Usage),
},
{
Name: "예시",
Value: utils.CodeBlock("md", strings.Join(addPrefix(c.DetailedDescription.Examples), "\n")),
},
},
Color: utils.EmbedFail,
}, m.Reference())
}
case *utils.InteractionCreate:
m.DeferReply(true)
if opt, ok := m.Options["단어"]; ok {
if opt, ok := ctx.Inter.Options["단어"]; ok {
command = opt.StringValue()
}
userId = m.Member.User.ID
deleteLearnedDataRun(ctx.Inter, command, ctx.Inter.Member.User.ID)
},
}
func deleteLearnedDataRun(m any, command, userId string) {
var data []databases.Learn
var sections []discordgo.Section
var containers []*discordgo.Container
cur, err := databases.Database.Learns.Find(context.TODO(), bson.M{"user_id": userId, "command": command})
if err != nil {
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "데이터를 가져오는데 실패했어요.",
Color: utils.EmbedFail,
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "데이터를 가져오는데 실패했어요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
cur.All(context.TODO(), &data)
if len(data) < 1 {
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "해당 하는 지식ㅇ을 찾을 수 없어요.",
Color: utils.EmbedFail,
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "해당 하는 지식ㅇ을 찾을 수 없어요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
for i := range len(data) {
data := data[i]
options = append(options, discordgo.SelectMenuOption{
Label: fmt.Sprintf("%d번 지식", i+1),
Description: data.Result,
Value: utils.MakeDeleteLearnedData(data.Id.Hex(), i+1),
})
description += fmt.Sprintf("%d. %s\n", i+1, data.Result)
}
embed := &discordgo.MessageEmbed{
Title: fmt.Sprintf("%s 삭제", command),
Description: utils.CodeBlock("md", fmt.Sprintf("# %s에 대한 대답 중 하나를 선ㅌ택하여 삭제해주세요.\n%s", command, description)),
Color: utils.EmbedDefault,
}
components := []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.SelectMenu{
MenuType: discordgo.StringSelectMenu,
CustomID: utils.MakeDeleteLearnedDataUserId(userId),
Options: options,
Placeholder: "ㅈ지울 응답을 선택해주세요.",
},
},
},
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.Button{
CustomID: utils.MakeDeleteLearnedDataCancel(userId),
Label: "취소하기",
for i, data := range data {
sections = append(sections, discordgo.Section{
Accessory: discordgo.Button{
Label: "삭제",
Style: discordgo.DangerButton,
Disabled: false,
},
CustomID: utils.MakeDeleteLearnedData(data.Id.Hex(), i+1, userId),
},
Components: []discordgo.MessageComponent{
discordgo.TextDisplay{
Content: fmt.Sprintf("%d. %s\n", i+1, data.Result),
},
},
})
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendComplex(m.ChannelID, &discordgo.MessageSend{
Embeds: []*discordgo.MessageEmbed{embed},
Components: components,
Reference: m.Reference(),
})
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
Components: &components,
})
textDisplay := discordgo.TextDisplay{Content: fmt.Sprintf("### %s 삭제", command)}
container := &discordgo.Container{Components: []discordgo.MessageComponent{textDisplay}}
for i, section := range sections {
container.Components = append(container.Components, section, discordgo.Separator{})
if (i+1)%10 == 0 {
containers = append(containers, container)
container = &discordgo.Container{Components: []discordgo.MessageComponent{textDisplay}}
continue
}
}
if len(container.Components) > 1 {
containers = append(containers, container)
}
utils.PaginationEmbedBuilder(m).
AddContainers(containers...).
Start()
}

View file

@ -39,20 +39,17 @@ type DiscommandStruct struct {
}
type MsgContext struct {
Session *discordgo.Session
Msg *discordgo.MessageCreate
Msg *utils.MessageCreate
Args *[]string
Command *Command
}
type ChatInputContext struct {
Session *discordgo.Session
Inter *utils.InteractionCreate
Command *Command
}
type ComponentContext struct {
Session *discordgo.Session
Inter *utils.InteractionCreate
Component *Component
}
@ -83,14 +80,15 @@ var (
modalMutex sync.Mutex
)
func new() *DiscommandStruct {
discommand := DiscommandStruct{
var Discommand *DiscommandStruct
func init() {
Discommand = &DiscommandStruct{
Commands: map[string]*Command{},
Aliases: map[string]string{},
Components: []*Component{},
Modals: []*Modal{},
}
return &discommand
}
func (d *DiscommandStruct) LoadCommand(c *Command) {
@ -118,13 +116,16 @@ func (d *DiscommandStruct) LoadModal(m *Modal) {
func (d *DiscommandStruct) MessageRun(name string, s *discordgo.Session, m *discordgo.MessageCreate, args []string) {
if command, ok := d.Commands[name]; ok {
command.MessageRun(&MsgContext{s, m, &args, command})
command.MessageRun(&MsgContext{&utils.MessageCreate{
MessageCreate: m,
Session: s,
}, &args, command})
}
}
func (d *DiscommandStruct) ChatInputRun(name string, s *discordgo.Session, i *discordgo.InteractionCreate) {
if command, ok := d.Commands[name]; ok {
command.ChatInputRun(&ChatInputContext{s, &utils.InteractionCreate{
command.ChatInputRun(&ChatInputContext{&utils.InteractionCreate{
InteractionCreate: i,
Session: s,
Options: utils.GetInteractionOptions(i),
@ -134,7 +135,6 @@ func (d *DiscommandStruct) ChatInputRun(name string, s *discordgo.Session, i *di
func (d *DiscommandStruct) ComponentRun(s *discordgo.Session, i *discordgo.InteractionCreate) {
data := &ComponentContext{
Session: s,
Inter: &utils.InteractionCreate{
InteractionCreate: i,
Session: s,
@ -172,5 +172,3 @@ func (d *DiscommandStruct) ModalRun(s *discordgo.Session, i *discordgo.Interacti
break
}
}
var Discommand *DiscommandStruct = new()

View file

@ -30,10 +30,16 @@ var HelpCommand *Command = &Command{
},
Category: General,
MessageRun: func(ctx *MsgContext) {
helpRun(ctx.Session, ctx.Msg, ctx.Args)
helpRun(ctx.Msg.Session, ctx.Msg, strings.Join(*ctx.Args, " "))
},
ChatInputRun: func(ctx *ChatInputContext) {
helpRun(ctx.Session, ctx.Inter, nil)
var command string
if opt, ok := ctx.Inter.Options["명령어"]; ok {
command = opt.StringValue()
}
helpRun(ctx.Inter.Session, ctx.Inter, command)
},
}
@ -41,108 +47,100 @@ func getCommandsByCategory(d *DiscommandStruct, category Category) []string {
commands := []string{}
for _, command := range d.Commands {
if command.Category == category {
commands = append(commands, fmt.Sprintf("- %s: %s", command.Name, command.Description))
commands = append(commands, fmt.Sprintf("> **%s**: %s", command.Name, command.Description))
}
}
return commands
}
func helpRun(s *discordgo.Session, m any, args *[]string) {
var commandName string
embed := &discordgo.MessageEmbed{
Color: utils.EmbedDefault,
Footer: &discordgo.MessageEmbedFooter{
Text: fmt.Sprintf("버전: %s", configs.MUFFIN_VERSION),
},
Thumbnail: &discordgo.MessageEmbedThumbnail{
func helpRun(s *discordgo.Session, m any, commandName string) {
section := &discordgo.Section{
Accessory: discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{
URL: s.State.User.AvatarURL("512"),
},
},
}
switch m := m.(type) {
case *discordgo.MessageCreate:
commandName = Discommand.Aliases[strings.Join(*args, " ")]
case *utils.InteractionCreate:
if opt, ok := m.Options["명령어"]; ok {
commandName = opt.StringValue()
} else {
commandName = ""
}
}
commandName = Discommand.Aliases[commandName]
if commandName == "" || Discommand.Commands[commandName] == nil {
embed.Title = fmt.Sprintf("%s의 도움말", s.State.User.Username)
embed.Description = utils.CodeBlock(
"md",
fmt.Sprintf("# 일반\n%s\n\n# 채팅\n%s",
strings.Join(getCommandsByCategory(Discommand, General), "\n"),
strings.Join(getCommandsByCategory(Discommand, Chatting), "\n")),
section.Components = append(section.Components,
discordgo.TextDisplay{
Content: fmt.Sprintf("### %s의 도움말", s.State.User.Username),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **일반**\n%s", strings.Join(getCommandsByCategory(Discommand, General), "\n")),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **채팅**\n%s", strings.Join(getCommandsByCategory(Discommand, Chatting), "\n")),
},
)
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.Reply(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{embed},
})
}
utils.NewMessageSender(m).
AddComponents(&discordgo.Container{
Components: []discordgo.MessageComponent{section},
}).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
var aliases, examples discordgo.TextDisplay
command := Discommand.Commands[commandName]
embed.Title = fmt.Sprintf("%s의 %s 명령어의 도움말", s.State.User.Username, command.Name)
embed.Fields = []*discordgo.MessageEmbedField{
{
Name: "설명",
Value: utils.InlineCode(command.Description),
Inline: true,
section.Components = append(section.Components,
discordgo.TextDisplay{
Content: fmt.Sprintf("### %s의 %s 명령어의 도움말", s.State.User.Username, command.Name),
},
{
Name: "사용법",
Value: utils.InlineCode(command.DetailedDescription.Usage),
Inline: true,
discordgo.TextDisplay{
Content: fmt.Sprintf("- **설명**\n> %s", command.Description),
},
}
if command.Name == LearnCommand.Name {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "대답에 쓸 수 있는 인자",
Value: learnArguments,
})
}
discordgo.TextDisplay{
Content: fmt.Sprintf("- **사용법**\n> %s", command.DetailedDescription.Usage),
},
)
if command.Aliases != nil {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "별칭",
Value: utils.CodeBlock("md", strings.Join(addPrefix(command.Aliases), "\n")),
})
aliases = discordgo.TextDisplay{
Content: fmt.Sprintf("- **별칭**\n%s", strings.Join(utils.AddPrefix("> ", command.Aliases), "\n")),
}
} else {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "별칭",
Value: "없음",
})
aliases = discordgo.TextDisplay{
Content: "- **별칭**\n> 없음",
}
}
if command.DetailedDescription.Examples != nil {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "예시",
Value: utils.CodeBlock("md", strings.Join(addPrefix(command.DetailedDescription.Examples), "\n")),
})
examples = discordgo.TextDisplay{
Content: fmt.Sprintf("- **예시**\n%s", strings.Join(utils.AddPrefix("> ", command.DetailedDescription.Examples), "\n")),
}
} else {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "예시",
Value: "없음",
})
aliases = discordgo.TextDisplay{
Content: "- **예시**\n> 없음",
}
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.Reply(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{embed},
})
if command.Name == LearnCommand.Name {
learnArgs := discordgo.TextDisplay{
Content: fmt.Sprintf("- **대답에 쓸 수 있는 인자**\n%s", learnArguments),
}
utils.NewMessageSender(m).
AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{section, aliases, examples, learnArgs},
}).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
utils.NewMessageSender(m).
AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{section, aliases, examples},
}).
SetComponentsV2(true).
SetReply(true).
Send()
}

View file

@ -2,7 +2,6 @@ package commands
import (
"fmt"
"runtime"
"git.wh64.net/muffin/goMuffin/configs"
"git.wh64.net/muffin/goMuffin/utils"
@ -19,53 +18,45 @@ var InformationCommand *Command = &Command{
},
Category: General,
MessageRun: func(ctx *MsgContext) {
informationRun(ctx.Session, ctx.Msg)
informationRun(ctx.Msg.Session, ctx.Msg)
},
ChatInputRun: func(ctx *ChatInputContext) {
informationRun(ctx.Session, ctx.Inter)
informationRun(ctx.Inter.Session, ctx.Inter)
},
}
func informationRun(s *discordgo.Session, m any) {
owner, _ := s.User(configs.Config.Bot.OwnerId)
embed := &discordgo.MessageEmbed{
Title: fmt.Sprintf("%s의 정보", s.State.User.Username),
Fields: []*discordgo.MessageEmbedField{
{
Name: "운영 체제",
Value: utils.InlineCode(fmt.Sprintf("%s %s", runtime.GOARCH, runtime.GOOS)),
},
{
Name: "제작자",
Value: utils.InlineCode(owner.Username),
},
{
Name: "버전",
Value: utils.InlineCode(configs.MUFFIN_VERSION),
},
{
Name: "최근에 업데이트된 날짜",
Value: utils.Time(configs.UpdatedAt, utils.RelativeTime),
Inline: true,
},
{
Name: "시작한 시각",
Value: utils.Time(configs.StartedAt, utils.RelativeTime),
Inline: true,
},
},
Color: utils.EmbedDefault,
Thumbnail: &discordgo.MessageEmbedThumbnail{
utils.NewMessageSender(m).
AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{
discordgo.Section{
Accessory: discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{
URL: s.State.User.AvatarURL("512"),
},
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.Reply(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{embed},
})
}
},
Components: []discordgo.MessageComponent{
discordgo.TextDisplay{
Content: fmt.Sprintf("### %s의 정보", s.State.User.Username),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **제작자**\n> %s", owner.Username),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **버전**\n> %s", configs.MUFFIN_VERSION),
},
},
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **최근에 업데이트된 날짜**\n> %s", utils.Time(configs.UpdatedAt, utils.RelativeTime)),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **봇이 시작한 시각**\n> %s", utils.Time(configs.StartedAt, utils.RelativeTime)),
},
},
}).
SetComponentsV2(true).
SetReply(true).
Send()
}

View file

@ -3,6 +3,7 @@ package commands
import (
"context"
"fmt"
"log"
"strings"
"time"
@ -13,17 +14,17 @@ import (
"github.com/bwmarrin/discordgo"
)
var learnArguments = utils.InlineCode("{user.name}") + "\n" +
utils.InlineCode("{user.mention}") + "\n" +
utils.InlineCode("{user.globalName}") + "\n" +
utils.InlineCode("{user.id}") + "\n" +
utils.InlineCode("{user.createdAt}") + "\n" +
utils.InlineCode("{user.joinedAt}") + "\n" +
utils.InlineCode("{muffin.version}") + "\n" +
utils.InlineCode("{muffin.updatedAt}") + "\n" +
utils.InlineCode("{muffin.statedAt}") + "\n" +
utils.InlineCode("{muffin.name}") + "\n" +
utils.InlineCode("{muffin.id}")
var learnArguments = "> " + utils.InlineCode("{user.name}") + "\n" +
"> " + utils.InlineCode("{user.mention}") + "\n" +
"> " + utils.InlineCode("{user.globalName}") + "\n" +
"> " + utils.InlineCode("{user.id}") + "\n" +
"> " + utils.InlineCode("{user.createdAt}") + "\n" +
"> " + utils.InlineCode("{user.joinedAt}") + "\n" +
"> " + utils.InlineCode("{muffin.version}") + "\n" +
"> " + utils.InlineCode("{muffin.updatedAt}") + "\n" +
"> " + utils.InlineCode("{muffin.statedAt}") + "\n" +
"> " + utils.InlineCode("{muffin.name}") + "\n" +
"> " + utils.InlineCode("{muffin.id}")
var LearnCommand *Command = &Command{
ApplicationCommand: &discordgo.ApplicationCommand{
@ -57,69 +58,52 @@ var LearnCommand *Command = &Command{
},
Category: Chatting,
MessageRun: func(ctx *MsgContext) {
learnRun(ctx.Command, ctx.Session, ctx.Msg, ctx.Args)
if len(*ctx.Args) < 2 {
utils.NewMessageSender(ctx.Msg).
AddComponents(utils.GetErrorContainer(
discordgo.TextDisplay{
Content: "올바르지 않ㅇ은 용법이에요.",
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **사용법**\n> %s", ctx.Command.DetailedDescription.Usage),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **예시**\n%s", strings.Join(utils.AddPrefix("> ", ctx.Command.DetailedDescription.Examples), "\n")),
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **사용 가능한 인자**\n%s", learnArguments),
},
)).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
learnRun(ctx.Msg, ctx.Msg.Author.ID, strings.ReplaceAll((*ctx.Args)[0], "_", " "), strings.ReplaceAll((*ctx.Args)[1], "_", " "))
},
ChatInputRun: func(ctx *ChatInputContext) {
learnRun(ctx.Command, ctx.Session, ctx.Inter, nil)
},
}
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
})
func addPrefix(arr []string) (newArr []string) {
for _, item := range arr {
newArr = append(newArr, fmt.Sprintf("- %s", item))
}
return
}
var command, result string
func learnRun(c *Command, s *discordgo.Session, m any, args *[]string) {
var userId, command, result string
igCommands := []string{}
switch m := m.(type) {
case *discordgo.MessageCreate:
userId = m.Author.ID
if len(*args) < 2 {
s.ChannelMessageSendEmbedReply(m.ChannelID, &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "올바르지 않ㅇ은 용법이에요.",
Fields: []*discordgo.MessageEmbedField{
{
Name: "사용법",
Value: utils.InlineCode(c.DetailedDescription.Usage),
Inline: true,
},
{
Name: "사용 가능한 인자",
Value: learnArguments,
Inline: true,
},
{
Name: "예시",
Value: utils.CodeBlock("md", strings.Join(addPrefix(c.DetailedDescription.Examples), "\n")),
},
},
Color: utils.EmbedFail,
}, m.Reference())
return
}
command = strings.ReplaceAll((*args)[0], "_", " ")
result = strings.ReplaceAll((*args)[1], "_", " ")
case *utils.InteractionCreate:
m.DeferReply(true)
userId = m.Member.User.ID
if opt, ok := m.Options["단어"]; ok {
if opt, ok := ctx.Inter.Options["단어"]; ok {
command = opt.StringValue()
}
if opt, ok := m.Options["대답"]; ok {
if opt, ok := ctx.Inter.Options["대답"]; ok {
result = opt.StringValue()
}
learnRun(ctx.Inter, ctx.Inter.Member.User.ID, command, result)
},
}
func learnRun(m any, userId, command, result string) {
igCommands := []string{}
for _, command := range Discommand.Commands {
igCommands = append(igCommands, command.Name)
igCommands = append(igCommands, command.Aliases...)
@ -136,40 +120,23 @@ func learnRun(c *Command, s *discordgo.Session, m any, args *[]string) {
for _, ig := range ignores {
if strings.Contains(command, ig) {
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "해ㄷ당 단어는 배우기 껄끄ㄹ럽네요.",
Color: utils.EmbedFail,
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "해ㄷ당 단어는 배우기 껄끄ㄹ럽네요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
}
for _, di := range disallows {
if strings.Contains(result, di) {
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "해당 단ㅇ어의 대답으로 하기 좀 그렇ㄴ네요.",
Color: utils.EmbedFail,
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "해당 단ㅇ어의 대답으로 하기 좀 그렇ㄴ네요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
}
@ -180,36 +147,23 @@ func learnRun(c *Command, s *discordgo.Session, m any, args *[]string) {
CreatedAt: time.Now(),
})
if err != nil {
fmt.Println(err)
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "단어를 배우는데 오류가 생겼어요.",
Color: utils.EmbedFail,
}
log.Println(err)
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "단어를 배우는데 오류가 생겼어요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
}
embed := &discordgo.MessageEmbed{
Title: "✅ 성공",
Description: fmt.Sprintf("%s 배웠어요.", hangul.GetJosa(command, hangul.EUL_REUL)),
Color: utils.EmbedSuccess,
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
utils.NewMessageSender(m).
AddComponents(utils.GetSuccessContainer(
discordgo.TextDisplay{
Content: fmt.Sprintf("%s 배웠어요.", hangul.GetJosa(command, hangul.EUL_REUL)),
},
)).
SetComponentsV2(true).
SetReply(true).
Send()
}

View file

@ -58,10 +58,102 @@ var LearnedDataListCommand *Command = &Command{
},
Category: Chatting,
MessageRun: func(ctx *MsgContext) {
learnedDataListRun(ctx.Session, ctx.Msg, ctx.Args)
var length int
filter := bson.D{{Key: "user_id", Value: ctx.Msg.Author.ID}}
query := strings.Join(*ctx.Args, " ")
if match := utils.RegexpLearnQueryCommand.FindStringSubmatch(query); match != nil {
filter = append(filter, bson.E{
Key: "command",
Value: bson.M{
"$regex": match[1],
},
})
}
if match := utils.RegexpLearnQueryResult.FindStringSubmatch(query); match != nil {
filter = append(filter, bson.E{
Key: "result",
Value: bson.M{
"$regex": match[1],
},
})
}
if match := utils.RegexpLearnQueryLength.FindStringSubmatch(query); match != nil {
var err error
length, err := strconv.Atoi(match[1])
if err != nil {
utils.NewMessageSender(ctx.Msg).
AddEmbeds(&discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "개수의 값은 숫자여야해요.",
Color: utils.EmbedFail,
}).
SetReply(true).
Send()
return
}
if float64(length) < LIST_MIN_VALUE {
utils.NewMessageSender(ctx.Msg).
AddEmbeds(&discordgo.MessageEmbed{
Title: "❌ 오류",
Description: fmt.Sprintf("개수의 값은 %d보다 커야해요.", int(LIST_MIN_VALUE)),
Color: utils.EmbedFail,
}).
SetReply(true).
Send()
return
}
if float64(length) > LIST_MAX_VALUE {
utils.NewMessageSender(ctx.Msg).
AddEmbeds(&discordgo.MessageEmbed{
Title: "❌ 오류",
Description: fmt.Sprintf("개수의 값은 %d보다 작아야해요.", int(LIST_MAX_VALUE)),
Color: utils.EmbedFail,
}).
SetReply(true).
Send()
return
}
}
learnedDataListRun(ctx.Msg, ctx.Msg.Author.GlobalName, ctx.Msg.Author.AvatarURL("512"), filter, length)
},
ChatInputRun: func(ctx *ChatInputContext) {
learnedDataListRun(ctx.Session, ctx.Inter, nil)
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
})
var length int
filter := bson.D{{Key: "user_id", Value: ctx.Inter.Member.User.ID}}
if opt, ok := ctx.Inter.Options["단어"]; ok {
filter = append(filter, bson.E{
Key: "command",
Value: bson.M{
"$regex": opt.StringValue(),
},
})
}
if opt, ok := ctx.Inter.Options["대답"]; ok {
filter = append(filter, bson.E{
Key: "result",
Value: bson.M{
"$regex": opt.StringValue(),
},
})
}
if opt, ok := ctx.Inter.Options["개수"]; ok {
length = int(opt.IntValue())
}
learnedDataListRun(ctx.Inter, ctx.Inter.Member.User.GlobalName, ctx.Inter.Member.User.AvatarURL("512"), filter, length)
},
}
@ -105,134 +197,70 @@ func getDescriptions(data *[]databases.Learn, length int) (descriptions []string
return
}
func learnedDataListRun(s *discordgo.Session, m any, args *[]string) {
var globalName, avatarUrl string
func getContainers(accessory *discordgo.Thumbnail, defaultDesc string, data *[]databases.Learn, length int) []*discordgo.Container {
var containers []*discordgo.Container
descriptions := getDescriptions(data, length)
if len(descriptions) <= 0 {
containers = append(containers, &discordgo.Container{
Components: []discordgo.MessageComponent{
discordgo.Section{
Accessory: accessory,
Components: []discordgo.MessageComponent{
discordgo.TextDisplay{
Content: utils.MakeDesc(defaultDesc, "없음"),
},
},
},
},
})
}
for _, desc := range descriptions {
containers = append(containers, &discordgo.Container{
Components: []discordgo.MessageComponent{
discordgo.Section{
Accessory: accessory,
Components: []discordgo.MessageComponent{
discordgo.TextDisplay{
Content: utils.MakeDesc(defaultDesc, desc),
},
},
},
},
})
}
return containers
}
func learnedDataListRun(m any, globalName, avatarUrl string, filter bson.D, length int) {
var data []databases.Learn
var filter bson.D
var length int
switch m := m.(type) {
case *discordgo.MessageCreate:
filter = bson.D{{Key: "user_id", Value: m.Author.ID}}
globalName = m.Author.GlobalName
avatarUrl = m.Author.AvatarURL("512")
query := strings.Join(*args, " ")
if match := utils.RegexpLearnQueryCommand.FindStringSubmatch(query); match != nil {
filter = append(filter, bson.E{
Key: "command",
Value: bson.M{
"$regex": match[1],
},
})
}
if match := utils.RegexpLearnQueryResult.FindStringSubmatch(query); match != nil {
filter = append(filter, bson.E{
Key: "result",
Value: bson.M{
"$regex": match[1],
},
})
}
if match := utils.RegexpLearnQueryLength.FindStringSubmatch(query); match != nil {
var err error
length, err = strconv.Atoi(match[1])
if err != nil {
s.ChannelMessageSendEmbedReply(m.ChannelID, &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "개수의 값은 숫자여야해요.",
Color: utils.EmbedFail,
}, m.Reference())
return
}
if float64(length) < LIST_MIN_VALUE {
s.ChannelMessageSendEmbedReply(m.ChannelID, &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: fmt.Sprintf("개수의 값은 %d보다 커야해요.", int(LIST_MIN_VALUE)),
Color: utils.EmbedFail,
}, m.Reference())
return
}
if float64(length) > LIST_MAX_VALUE {
s.ChannelMessageSendEmbedReply(m.ChannelID, &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: fmt.Sprintf("개수의 값은 %d보다 작아야해요.", int(LIST_MAX_VALUE)),
Color: utils.EmbedFail,
}, m.Reference())
return
}
}
case *utils.InteractionCreate:
m.DeferReply(true)
filter = bson.D{{Key: "user_id", Value: m.Member.User.ID}}
globalName = m.Member.User.GlobalName
avatarUrl = m.Member.User.AvatarURL("512")
if opt, ok := m.Options["단어"]; ok {
filter = append(filter, bson.E{
Key: "command",
Value: bson.M{
"$regex": opt.StringValue(),
},
})
}
if opt, ok := m.Options["대답"]; ok {
filter = append(filter, bson.E{
Key: "result",
Value: bson.M{
"$regex": opt.StringValue(),
},
})
}
if opt, ok := m.Options["개수"]; ok {
length = int(opt.IntValue())
}
}
cur, err := databases.Database.Learns.Find(context.TODO(), filter)
if err != nil {
if err == mongo.ErrNoDocuments {
embed := &discordgo.MessageEmbed{
utils.NewMessageSender(m).
AddEmbeds(&discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "당신은 지식ㅇ을 가르쳐준 적이 없어요!",
Color: utils.EmbedFail,
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
}).
SetReply(true).
Send()
return
}
fmt.Println(err)
embed := &discordgo.MessageEmbed{
utils.NewMessageSender(m).
AddEmbeds(&discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "데이터를 가져오는데 실패했어요.",
Color: utils.EmbedFail,
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(m.ChannelID, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
}).
SetReply(true).
Send()
return
}
@ -240,13 +268,13 @@ func learnedDataListRun(s *discordgo.Session, m any, args *[]string) {
cur.All(context.TODO(), &data)
embed := &discordgo.MessageEmbed{
Title: fmt.Sprintf("%s님이 알려주신 지식", globalName),
Color: utils.EmbedDefault,
Thumbnail: &discordgo.MessageEmbedThumbnail{
containers := getContainers(&discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{
URL: avatarUrl,
},
}
}, fmt.Sprintf("### %s님이 알려주신 지식\n%s", globalName, utils.CodeBlock("md", fmt.Sprintf("# 총 %d개에요.\n", len(data))+"%s")), &data, length)
utils.StartPaginationEmbed(s, m, embed, getDescriptions(&data, length), utils.CodeBlock("md", fmt.Sprintf("# 총 %d개에요.\n", len(data))+"%s"))
utils.PaginationEmbedBuilder(m).
AddContainers(containers...).
Start()
}

View file

@ -14,48 +14,21 @@ import (
var DeleteLearnedDataComponent *commands.Component = &commands.Component{
Parse: func(ctx *commands.ComponentContext) bool {
var userId string
i := ctx.Inter
customId := i.MessageComponentData().CustomID
if i.MessageComponentData().ComponentType == discordgo.ButtonComponent {
if !strings.HasPrefix(customId, utils.DeleteLearnedDataCancel) {
if !strings.HasPrefix(customId, utils.DeleteLearnedData) {
return false
}
userId = utils.GetDeleteLearnedDataUserId(customId)
if i.Member.User.ID == userId {
i.Update(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 취소",
Description: "지식 삭제 작업ㅇ을 취소했어요.",
Color: utils.EmbedFail,
},
},
})
return false
}
} else {
if !strings.HasPrefix(customId, utils.DeleteLearnedDataUserId) {
return false
}
userId = utils.GetDeleteLearnedDataUserId(customId)
}
userId := utils.GetDeleteLearnedDataUserId(customId)
if i.Member.User.ID != userId {
i.Reply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "당신은 해당 권한이 없ㅇ어요.",
Color: utils.EmbedFail,
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
Components: []discordgo.MessageComponent{
utils.GetErrorContainer(discordgo.TextDisplay{Content: "당신은 해당 권한이 없ㅇ어요."}),
},
},
Components: []discordgo.MessageComponent{},
},
)
return false
}
@ -66,19 +39,17 @@ var DeleteLearnedDataComponent *commands.Component = &commands.Component{
i.DeferUpdate()
id, itemId := utils.GetDeleteLearnedDataId(i.MessageComponentData().Values[0])
id, itemId := utils.GetDeleteLearnedDataId(i.MessageComponentData().CustomID)
fmt.Println(id, itemId)
databases.Database.Learns.DeleteOne(context.TODO(), bson.D{{Key: "_id", Value: id}})
i.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{
{
Title: "✅ 삭제 완료",
Description: fmt.Sprintf("%d번을 삭ㅈ제했어요.", itemId),
Color: utils.EmbedSuccess,
flags := discordgo.MessageFlagsIsComponentsV2
i.EditReply(&utils.InteractionEdit{
Flags: &flags,
Components: &[]discordgo.MessageComponent{
utils.GetSuccessContainer(discordgo.TextDisplay{Content: fmt.Sprintf("%d번을 삭ㅈ제했어요.", itemId)}),
},
},
Components: &[]discordgo.MessageComponent{},
})
},
}

View file

@ -34,12 +34,6 @@ type MuffinConfig struct {
Bot botConfig
Train trainConfig
Database databaseConfig
// Deprecated: Use Database.URL
DatabaseURL string
// Deprecated: Use Database.Name
DatabaseName string
}
var Config *MuffinConfig
@ -90,8 +84,4 @@ func setConfig(config *MuffinConfig) {
if config.Database.URL == "" {
config.Database.URL = fmt.Sprintf("mongodb://%s:%s@%s:%d/?authSource=%s", config.Database.Username, config.Database.Password, config.Database.HostName, config.Database.Port, config.Database.AuthSource)
}
// Deprecated된 Value
config.DatabaseURL = config.Database.URL
config.DatabaseName = config.Database.Name
}

View file

@ -7,7 +7,7 @@ import (
"git.wh64.net/muffin/goMuffin/utils"
)
const MUFFIN_VERSION = "5.1.0-gopher_dev.250517c"
const MUFFIN_VERSION = "0.0.0-souffle_canary.250525a-componentsv2"
var updatedString string = utils.RegexpDecimals.FindAllStringSubmatch(MUFFIN_VERSION, -1)[3][0]

View file

@ -26,13 +26,13 @@ func init() {
}
func Connect() (*MuffinDatabase, error) {
client, err := mongo.Connect(options.Client().ApplyURI(configs.Config.DatabaseURL))
client, err := mongo.Connect(options.Client().ApplyURI(configs.Config.Database.URL))
if err != nil {
return nil, err
}
return &MuffinDatabase{
Client: client,
Learns: client.Database(configs.Config.DatabaseName).Collection("learn"),
Texts: client.Database(configs.Config.DatabaseName).Collection("text"),
Learns: client.Database(configs.Config.Database.Name).Collection("learn"),
Texts: client.Database(configs.Config.Database.Name).Collection("text"),
}, nil
}

4
go.mod
View file

@ -4,15 +4,13 @@ go 1.24.1
require (
github.com/LoperLee/golang-hangul-toolkit v1.1.0
github.com/bwmarrin/discordgo v0.28.1
github.com/bwmarrin/discordgo v0.28.2-0.20250520184322-b9883c495955
github.com/devproje/commando v0.1.0-alpha.1
github.com/go-sql-driver/mysql v1.9.2
github.com/joho/godotenv v1.5.1
go.mongodb.org/mongo-driver/v2 v2.1.0
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/golang/snappy v1.0.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/klauspost/compress v1.18.0 // indirect

6
go.sum
View file

@ -1,15 +1,13 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/LoperLee/golang-hangul-toolkit v1.1.0 h1:JEyLpLyA2hDQwWY9oCprHClnKIdkYVOSJzAat2uFX/A=
github.com/LoperLee/golang-hangul-toolkit v1.1.0/go.mod h1:CDbZ23/IL4v2ovWIOb7xDEiFcSc0pIIbbYTpg+gP+Sk=
github.com/bwmarrin/discordgo v0.28.1 h1:gXsuo2GBO7NbR6uqmrrBDplPUx2T3nzu775q/Rd1aG4=
github.com/bwmarrin/discordgo v0.28.1/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY=
github.com/bwmarrin/discordgo v0.28.2-0.20250520184322-b9883c495955 h1:ReUA/wL53HdO2jlzwwl5kVa2UJInBtHzqrvf3eVTEvk=
github.com/bwmarrin/discordgo v0.28.2-0.20250520184322-b9883c495955/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/devproje/commando v0.1.0-alpha.1 h1:JU6CKIdt1otjUKh+asCJC0yTzwVj+4Yh8KoTdzaKAkU=
github.com/devproje/commando v0.1.0-alpha.1/go.mod h1:OhrPX3mZUGSyEX/E7d1o0vaQIYkjG/N5rk6Nqwgyc7k=
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=

View file

@ -14,7 +14,6 @@ import (
"git.wh64.net/muffin/goMuffin/utils"
"github.com/bwmarrin/discordgo"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
)
func argParser(content string) (args []string) {
@ -109,9 +108,6 @@ func MessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
go func() {
cur, err := databases.Database.Learns.Find(context.TODO(), bson.D{{Key: "command", Value: content}})
if err != nil {
if err == mongo.ErrNilDocument {
learnData = []databases.Learn{}
}
log.Fatalln(err)
}
@ -131,27 +127,27 @@ func MessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
user, _ := s.User(data.UserId)
result := resultParser(data.Result, s, m)
s.ChannelMessageSendComplex(m.ChannelID, &discordgo.MessageSend{
Reference: m.Reference(),
Content: fmt.Sprintf("%s\n%s", result, utils.InlineCode(fmt.Sprintf("%s님이 알려주셨어요.", user.Username))),
AllowedMentions: &discordgo.MessageAllowedMentions{
utils.NewMessageSender(m).
SetContent(fmt.Sprintf("%s\n%s", result, utils.InlineCode(fmt.Sprintf("%s님이 알려주셨어요.", user.Username)))).
SetAllowedMentions(discordgo.MessageAllowedMentions{
Roles: []string{},
Parse: []discordgo.AllowedMentionType{},
Users: []string{},
},
})
}).
SetReply(true).
Send()
return
}
s.ChannelMessageSendComplex(m.ChannelID, &discordgo.MessageSend{
Reference: m.Reference(),
Content: data[rand.Intn(len(data))].Text,
AllowedMentions: &discordgo.MessageAllowedMentions{
utils.NewMessageSender(m).
SetContent(data[rand.Intn(len(data))].Text).
SetAllowedMentions(discordgo.MessageAllowedMentions{
Roles: []string{},
Parse: []discordgo.AllowedMentionType{},
Users: []string{},
},
})
}).
SetReply(true).
Send()
return
}

27
main.go
View file

@ -21,12 +21,25 @@ import (
"github.com/devproje/commando/types"
)
func init() {
go commands.Discommand.LoadCommand(commands.HelpCommand)
go commands.Discommand.LoadCommand(commands.DataLengthCommand)
go commands.Discommand.LoadCommand(commands.LearnCommand)
go commands.Discommand.LoadCommand(commands.LearnedDataListCommand)
go commands.Discommand.LoadCommand(commands.InformationCommand)
go commands.Discommand.LoadCommand(commands.DeleteLearnedDataCommand)
go commands.Discommand.LoadComponent(components.DeleteLearnedDataComponent)
go commands.Discommand.LoadComponent(components.PaginationEmbedComponent)
go commands.Discommand.LoadModal(modals.PaginationEmbedModal)
}
func main() {
command := commando.NewCommando(os.Args[1:])
config := configs.Config
if len(os.Args) > 1 {
command.Root("db-migrate", "봇의 데이터를 MariaDB에서 MongoDB로 옮깁니다.", scripts.DBMigrate)
command.Root("delete-all-commands", "봇의 모든 슬래시 커맨드를 삭제합니다.", scripts.DeleteAllCommands,
types.OptionData{
Name: "id",
@ -68,18 +81,6 @@ func main() {
dg, _ := discordgo.New("Bot " + config.Bot.Token)
go commands.Discommand.LoadCommand(commands.HelpCommand)
go commands.Discommand.LoadCommand(commands.DataLengthCommand)
go commands.Discommand.LoadCommand(commands.LearnCommand)
go commands.Discommand.LoadCommand(commands.LearnedDataListCommand)
go commands.Discommand.LoadCommand(commands.InformationCommand)
go commands.Discommand.LoadCommand(commands.DeleteLearnedDataCommand)
go commands.Discommand.LoadComponent(components.DeleteLearnedDataComponent)
go commands.Discommand.LoadComponent(components.PaginationEmbedComponent)
go commands.Discommand.LoadModal(modals.PaginationEmbedModal)
go dg.AddHandler(handler.MessageCreate)
go dg.AddHandler(handler.InteractionCreate)

View file

@ -1,194 +0,0 @@
package scripts
import (
"context"
"database/sql"
"fmt"
"os"
"sync"
"time"
"git.wh64.net/muffin/goMuffin/configs"
"github.com/devproje/commando"
_ "github.com/go-sql-driver/mysql"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
var wg sync.WaitGroup
// 이 스크립트는 MariaDB -> MongoDB로의 전환을 위해 만들었음.
func DBMigrate(n *commando.Node) error {
mariaURL := os.Getenv("PREVIOUS_DATABASE_URL")
mongoURL := configs.Config.DatabaseURL
dbName := configs.Config.DatabaseName
dbConnectionQuery := "?parseTime=true"
wg.Add(3)
// statement -> text
go func() {
defer wg.Done()
newDataList := []any{}
mariaDB, err := sql.Open("mysql", mariaURL+dbConnectionQuery)
if err != nil {
panic(err)
}
mongoDB, err := mongo.Connect(options.Client().ApplyURI(mongoURL))
if err != nil {
panic(err)
}
defer mongoDB.Disconnect(context.TODO())
defer mariaDB.Close()
rows, err := mariaDB.Query("select text, persona, created_at from statement;")
if err != nil {
panic(err)
}
defer rows.Close()
i := 1
for rows.Next() {
var text, persona string
var createdAt time.Time
fmt.Printf("statement %d\n", i)
err = rows.Scan(&text, &persona, &createdAt)
if err != nil {
panic(err)
}
if text == "" {
text = "살ㄹ려주세요"
}
newDataList = append(newDataList, bson.M{
"text": text,
"persona": persona,
"created_at": createdAt,
})
i++
}
_, err = mongoDB.Database(dbName).Collection("text").InsertMany(context.TODO(), newDataList)
if err != nil {
panic(err)
}
}()
// nsfw_content -> text
go func() {
defer wg.Done()
newDataList := []any{}
mariaDB, err := sql.Open("mysql", mariaURL+dbConnectionQuery)
if err != nil {
panic(err)
}
mongoDB, err := mongo.Connect(options.Client().ApplyURI(mongoURL))
if err != nil {
panic(err)
}
defer mongoDB.Disconnect(context.TODO())
defer mariaDB.Close()
rows, err := mariaDB.Query("select text, persona, created_at from nsfw_content;")
if err != nil {
panic(err)
}
defer rows.Close()
i := 1
for rows.Next() {
var text, persona string
var createdAt time.Time
fmt.Printf("nsfw_content %d\n", i)
err = rows.Scan(&text, &persona, &createdAt)
if err != nil {
panic(err)
}
if text == "" {
text = "살ㄹ려주세요"
}
newDataList = append(newDataList, bson.M{
"text": text,
"persona": persona,
"created_at": createdAt,
})
i++
}
_, err = mongoDB.Database(dbName).Collection("text").InsertMany(context.TODO(), newDataList)
if err != nil {
panic(err)
}
}()
// learn -> learn
go func() {
defer wg.Done()
newDataList := []any{}
mariaDB, err := sql.Open("mysql", mariaURL+dbConnectionQuery)
if err != nil {
panic(err)
}
mongoDB, err := mongo.Connect(options.Client().ApplyURI(mongoURL))
if err != nil {
panic(err)
}
defer mongoDB.Disconnect(context.TODO())
defer mariaDB.Close()
rows, err := mariaDB.Query("select command, result, user_id, created_at from learn;")
if err != nil {
panic(err)
}
defer rows.Close()
i := 1
for rows.Next() {
var command, result, userId string
var createdAt time.Time
fmt.Printf("learn %d\n", i)
err = rows.Scan(&command, &result, &userId, &createdAt)
if err != nil {
panic(err)
}
newDataList = append(newDataList, bson.M{
"command": command,
"result": result,
"user_id": userId,
"created_at": createdAt,
})
i++
}
_, err = mongoDB.Database(dbName).Collection("learn").InsertMany(context.TODO(), newDataList)
if err != nil {
panic(err)
}
}()
// 모든 고루틴이 끝날 떄 까지 대기
wg.Wait()
fmt.Println("데이터 마이그레이션이 끝났어요.")
return nil
}

View file

@ -10,8 +10,6 @@ import (
const (
DeleteLearnedData = "#muffin/deleteLearnedData@"
DeleteLearnedDataUserId = "#muffin/deleteLearnedData@"
DeleteLearnedDataCancel = "#muffin/deleteLearnedData/cancel@"
PaginationEmbedPrev = "#muffin-pages/prev$"
PaginationEmbedPages = "#muffin-pages/pages$"
@ -20,31 +18,19 @@ const (
PaginationEmbedSetPage = "#muffin-pages/modal/set$"
)
func MakeDeleteLearnedData(id string, number int) string {
return fmt.Sprintf("%s%s&No.%d", DeleteLearnedData, id, number)
}
func MakeDeleteLearnedDataUserId(userId string) string {
return fmt.Sprintf("%s%s", DeleteLearnedDataUserId, userId)
}
func MakeDeleteLearnedDataCancel(id string) string {
return fmt.Sprintf("%s%s", DeleteLearnedDataCancel, id)
func MakeDeleteLearnedData(id string, number int, userId string) string {
return fmt.Sprintf("%sid=%s&no=%d&user_id=%s", DeleteLearnedData, id, number, userId)
}
func GetDeleteLearnedDataId(customId string) (id bson.ObjectID, itemId int) {
id, _ = bson.ObjectIDFromHex(strings.ReplaceAll(RegexpItemId.ReplaceAllString(customId[len(DeleteLearnedData):], ""), "&", ""))
stringItemId := strings.ReplaceAll(RegexpItemId.FindAllString(customId, 1)[0], "No.", "")
id, _ = bson.ObjectIDFromHex(strings.ReplaceAll(RegexpDLDId.FindAllString(customId, 1)[0], "id=", ""))
stringItemId := strings.ReplaceAll(RegexpDLDItemId.FindAllString(customId, 1)[0], "no=", "")
itemId, _ = strconv.Atoi(stringItemId)
return
}
func GetDeleteLearnedDataUserId(customId string) string {
if strings.HasPrefix(customId, DeleteLearnedDataCancel) {
return customId[len(DeleteLearnedDataCancel):]
} else {
return customId[len(DeleteLearnedDataUserId):]
}
return strings.ReplaceAll(RegexpDLDUserId.FindAllString(customId, 1)[0], "user_id=", "")
}
func MakePaginationEmbedPrev(id string) string {

35
utils/embed.go Normal file
View file

@ -0,0 +1,35 @@
package utils
import "github.com/bwmarrin/discordgo"
const (
EmbedDefault int = 0xaddb87
EmbedFail int = 0xff0000
EmbedSuccess int = 0x00ff00
)
func GetErrorContainer(components ...discordgo.MessageComponent) *discordgo.Container {
c := &discordgo.Container{
Components: []discordgo.MessageComponent{
discordgo.TextDisplay{
Content: "### ❌ 오류",
},
},
}
c.Components = append(c.Components, components...)
return c
}
func GetSuccessContainer(components ...discordgo.MessageComponent) *discordgo.Container {
c := &discordgo.Container{
Components: []discordgo.MessageComponent{
discordgo.TextDisplay{
Content: "### ✅ 성공",
},
},
}
c.Components = append(c.Components, components...)
return c
}

View file

@ -1,7 +0,0 @@
package utils
const (
EmbedDefault int = 0xaddb87
EmbedFail int = 0xff0000
EmbedSuccess int = 0x00ff00
)

View file

@ -1,12 +1,6 @@
package utils
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/bwmarrin/discordgo"
)
@ -16,20 +10,37 @@ type ModalData struct {
Components []discordgo.MessageComponent `json:"components"`
}
type InteractionEdit struct {
Content *string `json:"content,omitempty"`
Components *[]discordgo.MessageComponent `json:"components,omitempty"`
Embeds *[]*discordgo.MessageEmbed `json:"embeds,omitempty"`
Flags *discordgo.MessageFlags `json:"flags,omitempty"`
Attachments *[]*discordgo.MessageAttachment `json:"attachments,omitempty"`
AllowedMentions *discordgo.MessageAllowedMentions `json:"allowed_mentions,omitempty"`
}
// InteractionCreate custom data of discordgo.InteractionCreate
type InteractionCreate struct {
*discordgo.InteractionCreate
Session *discordgo.Session
// NOTE: It's only can ApplicationCommand
Options map[string]*discordgo.ApplicationCommandInteractionDataOption
Deferred bool
Replied bool
}
// Reply to this interaction.
func (i *InteractionCreate) Reply(data *discordgo.InteractionResponseData) {
i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
func (i *InteractionCreate) Reply(data *discordgo.InteractionResponseData) error {
err := i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: data,
})
if err != nil {
return err
}
i.Replied = true
return nil
}
// GetInteractionOptions to this interaction.
@ -43,38 +54,54 @@ func GetInteractionOptions(i *discordgo.InteractionCreate) map[string]*discordgo
}
// DeferReply to this interaction.
func (i *InteractionCreate) DeferReply(ephemeral bool) {
var flags discordgo.MessageFlags
if ephemeral {
flags = discordgo.MessageFlagsEphemeral
func (i *InteractionCreate) DeferReply(data *discordgo.InteractionResponseData) error {
err := i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: data,
})
if err != nil {
return err
}
i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: flags,
},
})
i.Deferred = true
return err
}
// DeferUpdate to this interaction.
func (i *InteractionCreate) DeferUpdate() {
i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
func (i *InteractionCreate) DeferUpdate() error {
err := i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredMessageUpdate,
})
if err != nil {
return err
}
i.Deferred = true
return err
}
// EditReply to this interaction.
func (i *InteractionCreate) EditReply(data *discordgo.WebhookEdit) {
i.Session.InteractionResponseEdit(i.Interaction, data)
func (i *InteractionCreate) EditReply(data *InteractionEdit) error {
endpoint := discordgo.EndpointWebhookMessage(i.AppID, i.Token, "@original")
_, err := i.Session.RequestWithBucketID("PATCH", endpoint, *data, discordgo.EndpointWebhookToken("", ""))
i.Replied = true
return err
}
// Update to this interaction.
func (i *InteractionCreate) Update(data *discordgo.InteractionResponseData) {
i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
func (i *InteractionCreate) Update(data *discordgo.InteractionResponseData) error {
err := i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: data,
})
if err != nil {
return err
}
i.Replied = true
return err
}
func (i *InteractionCreate) ShowModal(data *ModalData) error {
@ -85,35 +112,8 @@ func (i *InteractionCreate) ShowModal(data *ModalData) error {
reqData.Type = discordgo.InteractionResponseModal
reqData.Data = *data
bin, err := json.Marshal(reqData)
if err != nil {
endpoint := discordgo.EndpointInteractionResponse(i.ID, i.Token)
_, err := i.Session.RequestWithBucketID("POST", endpoint, reqData, endpoint)
return err
}
buf := bytes.NewBuffer(bin)
req, err := http.NewRequest("POST", discordgo.EndpointInteractionResponse(i.ID, i.Token), buf)
if err != nil {
return err
}
req.Header.Add("Authorization", i.Session.Identify.Token)
req.Header.Add("Content-Type", "application/json")
resp, err := i.Session.Client.Do(req)
if err != nil {
return err
}
respBin, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("%s", string(respBin))
}
defer resp.Body.Close()
return nil
}

110
utils/messageBuilder.go Normal file
View file

@ -0,0 +1,110 @@
package utils
import (
"github.com/bwmarrin/discordgo"
)
type MessageCreate struct {
*discordgo.MessageCreate
Session *discordgo.Session
}
type MessageSender struct {
Embeds []*discordgo.MessageEmbed
Content string
Components []discordgo.MessageComponent
Ephemeral bool
Reply bool
ComponentsV2 bool
AllowedMentions *discordgo.MessageAllowedMentions
m any
}
func NewMessageSender(m any) *MessageSender {
return &MessageSender{m: m}
}
func (s *MessageSender) AddEmbeds(embeds ...*discordgo.MessageEmbed) *MessageSender {
s.Embeds = append(s.Embeds, embeds...)
return s
}
func (s *MessageSender) AddComponents(components ...discordgo.MessageComponent) *MessageSender {
s.Components = append(s.Components, components...)
return s
}
func (s *MessageSender) SetContent(content string) *MessageSender {
s.Content = content
return s
}
func (s *MessageSender) SetEphemeral(ephemeral bool) *MessageSender {
s.Ephemeral = ephemeral
return s
}
func (s *MessageSender) SetReply(reply bool) *MessageSender {
s.Reply = reply
return s
}
func (s *MessageSender) SetAllowedMentions(allowedMentions discordgo.MessageAllowedMentions) *MessageSender {
s.AllowedMentions = &allowedMentions
return s
}
func (s *MessageSender) SetComponentsV2(componentsV2 bool) *MessageSender {
s.ComponentsV2 = componentsV2
return s
}
func (s *MessageSender) Send() error {
var flags discordgo.MessageFlags
if s.ComponentsV2 {
flags = flags | discordgo.MessageFlagsIsComponentsV2
}
switch m := s.m.(type) {
case *MessageCreate:
var reference *discordgo.MessageReference = nil
if s.Reply {
reference = m.Reference()
}
_, err := m.Session.ChannelMessageSendComplex(m.ChannelID, &discordgo.MessageSend{
Content: s.Content,
Embeds: s.Embeds,
Components: s.Components,
AllowedMentions: s.AllowedMentions,
Flags: flags,
Reference: reference,
})
return err
case *InteractionCreate:
if s.Ephemeral {
flags = flags | discordgo.MessageFlagsEphemeral
}
if m.Replied || m.Deferred {
err := m.EditReply(&InteractionEdit{
Content: &s.Content,
Embeds: &s.Embeds,
Components: &s.Components,
Flags: &flags,
})
return err
}
err := m.Reply(&discordgo.InteractionResponseData{
Content: s.Content,
Embeds: s.Embeds,
Components: s.Components,
Flags: flags,
})
return err
}
return nil
}

View file

@ -9,25 +9,57 @@ import (
// PaginationEmbed is embed with page
type PaginationEmbed struct {
Embed *discordgo.MessageEmbed
Data []string
Container *discordgo.Container
Containers []*discordgo.Container
Current int
Total int
id string
desc string
Id string
m any
}
var PaginationEmbeds = make(map[string]*PaginationEmbed)
func makeComponents(id string, current, total int) *[]discordgo.MessageComponent {
func PaginationEmbedBuilder(m any) *PaginationEmbed {
var userId string
switch m := m.(type) {
case *MessageCreate:
userId = m.Author.ID
case *InteractionCreate:
userId = m.Member.User.ID
}
id := fmt.Sprintf("%s/%d", userId, rand.Intn(100))
return &PaginationEmbed{
Current: 1,
Id: id,
m: m,
}
}
func (p *PaginationEmbed) SetContainer(container discordgo.Container) *PaginationEmbed {
p.Container = &container
return p
}
func (p *PaginationEmbed) AddContainers(container ...*discordgo.Container) *PaginationEmbed {
p.Total += len(container)
p.Containers = append(p.Containers, container...)
return p
}
func (p *PaginationEmbed) Start() error {
return startPaginationEmbed(p)
}
func makeComponents(id string, current, total int) *discordgo.ActionsRow {
disabled := false
if total == 1 {
disabled = true
}
return &[]discordgo.MessageComponent{
discordgo.ActionsRow{
return &discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.Button{
Style: discordgo.PrimaryButton,
@ -48,11 +80,10 @@ func makeComponents(id string, current, total int) *[]discordgo.MessageComponent
Disabled: disabled,
},
},
},
}
}
func makeDesc(desc, item string) string {
func MakeDesc(desc, item string) string {
var newDesc string
if desc == "" {
@ -63,49 +94,19 @@ func makeDesc(desc, item string) string {
return newDesc
}
// StartPaginationEmbed starts new PaginationEmbed struct
func StartPaginationEmbed(s *discordgo.Session, m any, e *discordgo.MessageEmbed, data []string, defaultDesc string) {
var userId string
func startPaginationEmbed(p *PaginationEmbed) error {
container := *p.Containers[0]
container.Components = append(container.Components, makeComponents(p.Id, p.Current, p.Total))
switch m := m.(type) {
case *discordgo.MessageCreate:
userId = m.Author.ID
case *InteractionCreate:
userId = m.Member.User.ID
}
PaginationEmbeds[p.Id] = p
id := fmt.Sprintf("%s/%d", userId, rand.Intn(12))
p := &PaginationEmbed{
Embed: e,
Data: data,
Current: 1,
Total: len(data),
id: id,
desc: defaultDesc,
}
if len(data) <= 0 {
p.Embed.Description = makeDesc(p.desc, "없음")
p.Total = 1
} else {
p.Embed.Description = makeDesc(p.desc, data[0])
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendComplex(m.ChannelID, &discordgo.MessageSend{
Reference: m.Reference(),
Embeds: []*discordgo.MessageEmbed{p.Embed},
Components: *makeComponents(id, p.Current, p.Total),
})
case *InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{p.Embed},
Components: makeComponents(id, p.Current, p.Total),
})
}
PaginationEmbeds[id] = p
err := NewMessageSender(p.m).
AddComponents(container).
SetReply(true).
SetEphemeral(true).
SetComponentsV2(true).
Send()
return err
}
func GetPaginationEmbed(id string) *PaginationEmbed {
@ -118,101 +119,77 @@ func GetPaginationEmbed(id string) *PaginationEmbed {
func (p *PaginationEmbed) Prev(i *InteractionCreate) {
if p.Current == 1 {
i.Reply(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "해당 페이지가 처음ㅇ이에요.",
Color: EmbedFail,
Components: []discordgo.MessageComponent{
GetErrorContainer(discordgo.TextDisplay{Content: "해당 페이지가 처음ㅇ이에요."}),
},
},
Flags: discordgo.MessageFlagsEphemeral,
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
})
return
}
p.Current -= 1
p.Embed.Description = makeDesc(p.desc, p.Data[p.Current-1])
i.Update(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{p.Embed},
Components: *makeComponents(p.id, p.Current, p.Total),
})
p.Set(i, p.Current)
}
func (p *PaginationEmbed) Next(i *InteractionCreate) {
if p.Current >= p.Total {
i.Reply(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "해당 페이지가 마지막ㅇ이에요.",
Color: EmbedFail,
Components: []discordgo.MessageComponent{
GetErrorContainer(discordgo.TextDisplay{Content: "해당 페이지가 마지막ㅇ이에요."}),
},
},
Flags: discordgo.MessageFlagsEphemeral,
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
})
return
}
p.Current += 1
p.Embed.Description = makeDesc(p.desc, p.Data[p.Current-1])
i.Update(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{p.Embed},
Components: *makeComponents(p.id, p.Current, p.Total),
})
p.Set(i, p.Current)
}
func (p *PaginationEmbed) Set(i *InteractionCreate, page int) {
func (p *PaginationEmbed) Set(i *InteractionCreate, page int) error {
if page <= 0 {
i.Reply(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "해당 값은 0보다 커야해요.",
Color: EmbedFail,
Components: []discordgo.MessageComponent{
GetErrorContainer(discordgo.TextDisplay{Content: "해당 값은 0보다 커야해요."}),
},
},
Flags: discordgo.MessageFlagsEphemeral,
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
})
return
return nil
}
if page >= p.Total {
if page > p.Total {
i.Reply(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "해당 값은 총 페이지의 수보다 작아야해요.",
Color: EmbedFail,
Components: []discordgo.MessageComponent{
GetErrorContainer(discordgo.TextDisplay{Content: "해당 값은 총 페이지의 수보다 작아야해요."}),
},
},
Flags: discordgo.MessageFlagsEphemeral,
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
})
return
return nil
}
p.Current = page
p.Embed.Description = makeDesc(p.desc, p.Data[p.Current-1])
container := *p.Containers[p.Current-1]
container.Components = append(container.Components, makeComponents(p.Id, p.Current, p.Total))
i.Update(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{p.Embed},
Components: *makeComponents(p.id, p.Current, p.Total),
err := i.Update(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsIsComponentsV2,
Components: []discordgo.MessageComponent{container},
})
return err
}
func (p *PaginationEmbed) ShowModal(i *InteractionCreate) {
i.ShowModal(&ModalData{
CustomId: MakePaginationEmbedModal(p.id),
CustomId: MakePaginationEmbedModal(p.Id),
Title: fmt.Sprintf("%s의 리스트", i.Session.State.User.Username),
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.TextInput{
CustomID: MakePaginationEmbedSetPage(p.id),
CustomID: MakePaginationEmbedSetPage(p.Id),
Label: "페이지",
Style: discordgo.TextInputShort,
Placeholder: "이동할 페이지를 여기에 적어주세요.",

View file

@ -5,7 +5,9 @@ import "regexp"
var (
RegexpFlexibleString = regexp.MustCompile(`[^\s"'「」«»]+|"([^"]*)"|'([^']*)'|「([^」]*)」|«([^»]*)»`)
RegexpDecimals = regexp.MustCompile(`\d+`)
RegexpItemId = regexp.MustCompile(`No.\d+`)
RegexpDLDItemId = regexp.MustCompile(`no=\d+`)
RegexpDLDUserId = regexp.MustCompile(`user_id=\d+`)
RegexpDLDId = regexp.MustCompile(`id=[^&]*`)
RegexpEmoji = regexp.MustCompile(`<a?:\w+:\d+>`)
RegexpLearnQueryCommand = regexp.MustCompile(`단어:([^\n대답개수:]*)`)
RegexpLearnQueryResult = regexp.MustCompile(`대답:([^\n단어개수:]*)`)

10
utils/strings.go Normal file
View file

@ -0,0 +1,10 @@
package utils
import "fmt"
func AddPrefix(prefix string, arr []string) (newArr []string) {
for _, item := range arr {
newArr = append(newArr, fmt.Sprintf("%s%s", prefix, item))
}
return
}