Compare commits

..

8 commits

Author SHA1 Message Date
ea0dd64df8
chore: version 2025-05-26 22:50:18 +09:00
a76d0344c9
Merge branch 'hotfix/train' 2025-05-26 22:49:31 +09:00
b074e49909
fix: train 2025-05-26 22:48:23 +09:00
e5090fa35d
Merge branch 'release/5.1.0-gopher' 2025-05-24 23:47:55 +09:00
dc57303dfa
feat: add knowledge length limit 2025-05-22 19:07:39 +09:00
b573016d0e
chore: Add deprecated alert 2025-05-19 19:51:49 +09:00
fce4dc2e73
chore: edit version 2025-05-18 15:09:50 +09:00
eb7a41e669
chore: version 2025-05-11 12:11:21 +09:00
24 changed files with 1085 additions and 855 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,18 +44,14 @@ var DataLengthCommand *Command = &Command{
},
Category: General,
MessageRun: func(ctx *MsgContext) {
dataLengthRun(ctx.Msg.Session, ctx.Msg, ctx.Msg.Author.Username, ctx.Msg.Author.ID)
dataLengthRun(ctx.Session, ctx.Msg)
},
ChatInputRun: func(ctx *ChatInputContext) {
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
})
dataLengthRun(ctx.Inter.Session, ctx.Inter, ctx.Inter.Member.User.Username, ctx.Inter.Member.User.ID)
dataLengthRun(ctx.Session, ctx.Inter)
},
}
func getLength(ch chan chStruct, dType dataType, coll *mongo.Collection, filter bson.D) {
func getLength(dType dataType, coll *mongo.Collection, filter bson.D) {
defer dataLengthWg.Done()
var err error
var cur *mongo.Cursor
@ -69,21 +65,33 @@ func getLength(ch chan chStruct, dType dataType, coll *mongo.Collection, filter
defer cur.Close(context.TODO())
cur.All(context.TODO(), &data)
ch <- chStruct{name: dType, length: len(data)}
dataLengthCh <- chStruct{name: dType, length: len(data)}
}
func dataLengthRun(s *discordgo.Session, m any, username, userId string) {
ch := make(chan chStruct)
func dataLengthRun(s *discordgo.Session, m any) {
var username, userId, channelId string
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(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{
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{
{
Key: "persona",
Value: bson.M{
@ -91,15 +99,15 @@ func dataLengthRun(s *discordgo.Session, m any, username, userId string) {
},
},
})
go getLength(ch, learn, databases.Database.Learns, bson.D{{}})
go getLength(ch, userLearn, databases.Database.Learns, bson.D{{Key: "user_id", Value: userId}})
go getLength(learn, databases.Database.Learns, bson.D{{}})
go getLength(userLearn, databases.Database.Learns, bson.D{{Key: "user_id", Value: userId}})
go func() {
dataLengthWg.Wait()
close(ch)
close(dataLengthCh)
}()
for resp := range ch {
for resp := range dataLengthCh {
switch dataType(resp.name) {
case text:
textLength = resp.length
@ -116,39 +124,46 @@ func dataLengthRun(s *discordgo.Session, m any, username, userId string) {
sum := textLength + learnLength
utils.NewMessageSender(m).
AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{
discordgo.Section{
Accessory: discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{
URL: s.State.User.AvatarURL("512"),
// 나중에 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,
},
},
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()
}
switch m := m.(type) {
case *discordgo.MessageCreate:
s.ChannelMessageSendEmbedReply(channelId, embed, m.Reference())
case *utils.InteractionCreate:
m.EditReply(&discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{embed},
})
}
}

View file

@ -31,100 +31,139 @@ var DeleteLearnedDataCommand *Command = &Command{
},
Category: Chatting,
MessageRun: func(ctx *MsgContext) {
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)
deleteLearnedDataRun(ctx.Command, ctx.Session, ctx.Msg, ctx.Args)
},
ChatInputRun: func(ctx *ChatInputContext) {
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
})
var command string
if opt, ok := ctx.Inter.Options["단어"]; ok {
command = opt.StringValue()
}
deleteLearnedDataRun(ctx.Inter, command, ctx.Inter.Member.User.ID)
deleteLearnedDataRun(ctx.Command, ctx.Session, ctx.Inter, nil)
},
}
func deleteLearnedDataRun(m any, command, userId string) {
func deleteLearnedDataRun(c *Command, s *discordgo.Session, m any, args *[]string) {
var command, userId, description string
var data []databases.Learn
var sections []discordgo.Section
var containers []*discordgo.Container
var options []discordgo.SelectMenuOption
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 {
command = opt.StringValue()
}
userId = m.Member.User.ID
}
cur, err := databases.Database.Learns.Find(context.TODO(), bson.M{"user_id": userId, "command": command})
if err != nil {
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "데이터를 가져오는데 실패했어요."})).
SetComponentsV2(true).
SetReply(true).
Send()
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},
})
}
return
}
cur.All(context.TODO(), &data)
if len(data) < 1 {
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "해당 하는 지식ㅇ을 찾을 수 없어요."})).
SetComponentsV2(true).
SetReply(true).
Send()
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},
})
}
return
}
for i, data := range data {
sections = append(sections, discordgo.Section{
Accessory: discordgo.Button{
Label: "삭제",
Style: discordgo.DangerButton,
CustomID: utils.MakeDeleteLearnedData(data.Id.Hex(), i+1, userId),
},
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.TextDisplay{
Content: fmt.Sprintf("%d. %s\n", i+1, data.Result),
discordgo.SelectMenu{
MenuType: discordgo.StringSelectMenu,
CustomID: utils.MakeDeleteLearnedDataUserId(userId),
Options: options,
Placeholder: "ㅈ지울 응답을 선택해주세요.",
},
},
},
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.Button{
CustomID: utils.MakeDeleteLearnedDataCancel(userId),
Label: "취소하기",
Style: discordgo.DangerButton,
Disabled: false,
},
},
},
}
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,17 +39,20 @@ type DiscommandStruct struct {
}
type MsgContext struct {
Msg *utils.MessageCreate
Session *discordgo.Session
Msg *discordgo.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
}
@ -80,15 +83,14 @@ var (
modalMutex sync.Mutex
)
var Discommand *DiscommandStruct
func init() {
Discommand = &DiscommandStruct{
func new() *DiscommandStruct {
discommand := DiscommandStruct{
Commands: map[string]*Command{},
Aliases: map[string]string{},
Components: []*Component{},
Modals: []*Modal{},
}
return &discommand
}
func (d *DiscommandStruct) LoadCommand(c *Command) {
@ -116,16 +118,13 @@ 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{&utils.MessageCreate{
MessageCreate: m,
Session: s,
}, &args, command})
command.MessageRun(&MsgContext{s, m, &args, command})
}
}
func (d *DiscommandStruct) ChatInputRun(name string, s *discordgo.Session, i *discordgo.InteractionCreate) {
if command, ok := d.Commands[name]; ok {
command.ChatInputRun(&ChatInputContext{&utils.InteractionCreate{
command.ChatInputRun(&ChatInputContext{s, &utils.InteractionCreate{
InteractionCreate: i,
Session: s,
Options: utils.GetInteractionOptions(i),
@ -135,6 +134,7 @@ 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,3 +172,5 @@ func (d *DiscommandStruct) ModalRun(s *discordgo.Session, i *discordgo.Interacti
break
}
}
var Discommand *DiscommandStruct = new()

View file

@ -30,16 +30,10 @@ var HelpCommand *Command = &Command{
},
Category: General,
MessageRun: func(ctx *MsgContext) {
helpRun(ctx.Msg.Session, ctx.Msg, strings.Join(*ctx.Args, " "))
helpRun(ctx.Session, ctx.Msg, ctx.Args)
},
ChatInputRun: func(ctx *ChatInputContext) {
var command string
if opt, ok := ctx.Inter.Options["명령어"]; ok {
command = opt.StringValue()
}
helpRun(ctx.Inter.Session, ctx.Inter, command)
helpRun(ctx.Session, ctx.Inter, nil)
},
}
@ -47,100 +41,108 @@ 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, commandName string) {
section := &discordgo.Section{
Accessory: discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{
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{
URL: s.State.User.AvatarURL("512"),
},
},
}
commandName = Discommand.Aliases[commandName]
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 = ""
}
}
if commandName == "" || Discommand.Commands[commandName] == nil {
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")),
},
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")),
)
utils.NewMessageSender(m).
AddComponents(&discordgo.Container{
Components: []discordgo.MessageComponent{section},
}).
SetComponentsV2(true).
SetReply(true).
Send()
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},
})
}
return
}
var aliases, examples discordgo.TextDisplay
command := Discommand.Commands[commandName]
section.Components = append(section.Components,
discordgo.TextDisplay{
Content: fmt.Sprintf("### %s의 %s 명령어의 도움말", s.State.User.Username, command.Name),
embed.Title = fmt.Sprintf("%s의 %s 명령어의 도움말", s.State.User.Username, command.Name)
embed.Fields = []*discordgo.MessageEmbedField{
{
Name: "설명",
Value: utils.InlineCode(command.Description),
Inline: true,
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **설명**\n> %s", command.Description),
{
Name: "사용법",
Value: utils.InlineCode(command.DetailedDescription.Usage),
Inline: true,
},
discordgo.TextDisplay{
Content: fmt.Sprintf("- **사용법**\n> %s", command.DetailedDescription.Usage),
},
)
if command.Aliases != nil {
aliases = discordgo.TextDisplay{
Content: fmt.Sprintf("- **별칭**\n%s", strings.Join(utils.AddPrefix("> ", command.Aliases), "\n")),
}
} else {
aliases = discordgo.TextDisplay{
Content: "- **별칭**\n> 없음",
}
}
if command.DetailedDescription.Examples != nil {
examples = discordgo.TextDisplay{
Content: fmt.Sprintf("- **예시**\n%s", strings.Join(utils.AddPrefix("> ", command.DetailedDescription.Examples), "\n")),
}
} else {
aliases = discordgo.TextDisplay{
Content: "- **예시**\n> 없음",
}
}
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
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "대답에 쓸 수 있는 인자",
Value: learnArguments,
})
}
utils.NewMessageSender(m).
AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{section, aliases, examples},
}).
SetComponentsV2(true).
SetReply(true).
Send()
if command.Aliases != nil {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "별칭",
Value: utils.CodeBlock("md", strings.Join(addPrefix(command.Aliases), "\n")),
})
} else {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "별칭",
Value: "없음",
})
}
if command.DetailedDescription.Examples != nil {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "예시",
Value: utils.CodeBlock("md", strings.Join(addPrefix(command.DetailedDescription.Examples), "\n")),
})
} else {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "예시",
Value: "없음",
})
}
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},
})
}
}

View file

@ -2,6 +2,7 @@ package commands
import (
"fmt"
"runtime"
"git.wh64.net/muffin/goMuffin/configs"
"git.wh64.net/muffin/goMuffin/utils"
@ -18,45 +19,53 @@ var InformationCommand *Command = &Command{
},
Category: General,
MessageRun: func(ctx *MsgContext) {
informationRun(ctx.Msg.Session, ctx.Msg)
informationRun(ctx.Session, ctx.Msg)
},
ChatInputRun: func(ctx *ChatInputContext) {
informationRun(ctx.Inter.Session, ctx.Inter)
informationRun(ctx.Session, ctx.Inter)
},
}
func informationRun(s *discordgo.Session, m any) {
owner, _ := s.User(configs.Config.Bot.OwnerId)
utils.NewMessageSender(m).
AddComponents(discordgo.Container{
Components: []discordgo.MessageComponent{
discordgo.Section{
Accessory: discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{
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{
URL: s.State.User.AvatarURL("512"),
},
},
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()
}
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},
})
}
}

View file

@ -3,7 +3,6 @@ package commands
import (
"context"
"fmt"
"log"
"strings"
"time"
@ -14,17 +13,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{
@ -58,51 +57,68 @@ var LearnCommand *Command = &Command{
},
Category: Chatting,
MessageRun: func(ctx *MsgContext) {
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], "_", " "))
learnRun(ctx.Command, ctx.Session, ctx.Msg, ctx.Args)
},
ChatInputRun: func(ctx *ChatInputContext) {
ctx.Inter.DeferReply(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
})
var command, result string
if opt, ok := ctx.Inter.Options["단어"]; ok {
command = opt.StringValue()
}
if opt, ok := ctx.Inter.Options["대답"]; ok {
result = opt.StringValue()
}
learnRun(ctx.Inter, ctx.Inter.Member.User.ID, command, result)
learnRun(ctx.Command, ctx.Session, ctx.Inter, nil)
},
}
func learnRun(m any, userId, command, result string) {
func addPrefix(arr []string) (newArr []string) {
for _, item := range arr {
newArr = append(newArr, fmt.Sprintf("- %s", item))
}
return
}
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 {
command = opt.StringValue()
}
if opt, ok := m.Options["대답"]; ok {
result = opt.StringValue()
}
}
for _, command := range Discommand.Commands {
igCommands = append(igCommands, command.Name)
@ -120,23 +136,57 @@ func learnRun(m any, userId, command, result string) {
for _, ig := range ignores {
if strings.Contains(command, ig) {
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "해ㄷ당 단어는 배우기 껄끄ㄹ럽네요."})).
SetComponentsV2(true).
SetReply(true).
Send()
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},
})
}
return
}
}
for _, di := range disallows {
if strings.Contains(result, di) {
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "해당 단ㅇ어의 대답으로 하기 좀 그렇ㄴ네요."})).
SetComponentsV2(true).
SetReply(true).
Send()
return
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},
})
}
}
}
if len([]rune(command)) > 100 {
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "단어는 100글자를 못 넘ㅇ어가요.",
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},
})
}
}
@ -147,23 +197,36 @@ func learnRun(m any, userId, command, result string) {
CreatedAt: time.Now(),
})
if err != nil {
log.Println(err)
fmt.Println(err)
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "단어를 배우는데 오류가 생겼어요.",
Color: utils.EmbedFail,
}
utils.NewMessageSender(m).
AddComponents(utils.GetErrorContainer(discordgo.TextDisplay{Content: "단어를 배우는데 오류가 생겼어요."})).
SetComponentsV2(true).
SetReply(true).
Send()
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},
})
}
return
}
utils.NewMessageSender(m).
AddComponents(utils.GetSuccessContainer(
discordgo.TextDisplay{
Content: fmt.Sprintf("%s 배웠어요.", hangul.GetJosa(command, hangul.EUL_REUL)),
},
)).
SetComponentsV2(true).
SetReply(true).
Send()
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},
})
}
}

View file

@ -58,102 +58,10 @@ var LearnedDataListCommand *Command = &Command{
},
Category: Chatting,
MessageRun: func(ctx *MsgContext) {
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)
learnedDataListRun(ctx.Session, ctx.Msg, ctx.Args)
},
ChatInputRun: func(ctx *ChatInputContext) {
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)
learnedDataListRun(ctx.Session, ctx.Inter, nil)
},
}
@ -197,70 +105,134 @@ func getDescriptions(data *[]databases.Learn, length int) (descriptions []string
return
}
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) {
func learnedDataListRun(s *discordgo.Session, m any, args *[]string) {
var globalName, avatarUrl string
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 {
utils.NewMessageSender(m).
AddEmbeds(&discordgo.MessageEmbed{
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "당신은 지식ㅇ을 가르쳐준 적이 없어요!",
Color: utils.EmbedFail,
}).
SetReply(true).
Send()
}
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},
})
}
return
}
fmt.Println(err)
utils.NewMessageSender(m).
AddEmbeds(&discordgo.MessageEmbed{
embed := &discordgo.MessageEmbed{
Title: "❌ 오류",
Description: "데이터를 가져오는데 실패했어요.",
Color: utils.EmbedFail,
}).
SetReply(true).
Send()
}
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},
})
}
return
}
@ -268,13 +240,13 @@ func learnedDataListRun(m any, globalName, avatarUrl string, filter bson.D, leng
cur.All(context.TODO(), &data)
containers := getContainers(&discordgo.Thumbnail{
Media: discordgo.UnfurledMediaItem{
embed := &discordgo.MessageEmbed{
Title: fmt.Sprintf("%s님이 알려주신 지식", globalName),
Color: utils.EmbedDefault,
Thumbnail: &discordgo.MessageEmbedThumbnail{
URL: avatarUrl,
},
}, fmt.Sprintf("### %s님이 알려주신 지식\n%s", globalName, utils.CodeBlock("md", fmt.Sprintf("# 총 %d개에요.\n", len(data))+"%s")), &data, length)
}
utils.PaginationEmbedBuilder(m).
AddContainers(containers...).
Start()
utils.StartPaginationEmbed(s, m, embed, getDescriptions(&data, length), utils.CodeBlock("md", fmt.Sprintf("# 총 %d개에요.\n", len(data))+"%s"))
}

View file

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

View file

@ -34,6 +34,12 @@ type MuffinConfig struct {
Bot botConfig
Train trainConfig
Database databaseConfig
// Deprecated: Use Database.URL
DatabaseURL string
// Deprecated: Use Database.Name
DatabaseName string
}
var Config *MuffinConfig
@ -84,4 +90,8 @@ 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 = "0.0.0-souffle_canary.250525a-componentsv2"
const MUFFIN_VERSION = "5.1.1-gopher_release.250526a"
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.Database.URL))
client, err := mongo.Connect(options.Client().ApplyURI(configs.Config.DatabaseURL))
if err != nil {
return nil, err
}
return &MuffinDatabase{
Client: client,
Learns: client.Database(configs.Config.Database.Name).Collection("learn"),
Texts: client.Database(configs.Config.Database.Name).Collection("text"),
Learns: client.Database(configs.Config.DatabaseName).Collection("learn"),
Texts: client.Database(configs.Config.DatabaseName).Collection("text"),
}, nil
}

4
go.mod
View file

@ -4,13 +4,15 @@ go 1.24.1
require (
github.com/LoperLee/golang-hangul-toolkit v1.1.0
github.com/bwmarrin/discordgo v0.28.2-0.20250520184322-b9883c495955
github.com/bwmarrin/discordgo v0.28.1
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,13 +1,15 @@
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,6 +14,7 @@ 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) {
@ -58,16 +59,6 @@ func MessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
args := argParser(content)
command := commands.Discommand.Aliases[args[0]]
if m.Author.ID == config.Train.UserID {
if _, err := databases.Database.Texts.InsertOne(context.TODO(), databases.InsertText{
Text: content,
Persona: "muffin",
CreatedAt: time.Now(),
}); err != nil {
log.Fatalln(err)
}
}
if command == "" {
s.ChannelTyping(m.ChannelID)
@ -108,6 +99,9 @@ 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)
}
@ -127,33 +121,42 @@ func MessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
user, _ := s.User(data.UserId)
result := resultParser(data.Result, s, m)
utils.NewMessageSender(m).
SetContent(fmt.Sprintf("%s\n%s", result, utils.InlineCode(fmt.Sprintf("%s님이 알려주셨어요.", user.Username)))).
SetAllowedMentions(discordgo.MessageAllowedMentions{
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{
Roles: []string{},
Parse: []discordgo.AllowedMentionType{},
Users: []string{},
}).
SetReply(true).
Send()
},
})
return
}
utils.NewMessageSender(m).
SetContent(data[rand.Intn(len(data))].Text).
SetAllowedMentions(discordgo.MessageAllowedMentions{
s.ChannelMessageSendComplex(m.ChannelID, &discordgo.MessageSend{
Reference: m.Reference(),
Content: data[rand.Intn(len(data))].Text,
AllowedMentions: &discordgo.MessageAllowedMentions{
Roles: []string{},
Parse: []discordgo.AllowedMentionType{},
Users: []string{},
}).
SetReply(true).
Send()
},
})
return
}
commands.Discommand.MessageRun(command, s, m, args[1:])
return
} else {
if m.Author.ID == config.Train.UserID {
if _, err := databases.Database.Texts.InsertOne(context.TODO(), databases.InsertText{
Text: m.Content,
Persona: "muffin",
CreatedAt: time.Now(),
}); err != nil {
log.Fatalln(err)
}
}
return
}
}

27
main.go
View file

@ -21,25 +21,12 @@ 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",
@ -81,6 +68,18 @@ 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)

196
scripts/dbMigrate.go Normal file
View file

@ -0,0 +1,196 @@
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)
fmt.Println("[경고] 해당 명령어는 다음 버전에서 사라져요.")
// 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,6 +10,8 @@ import (
const (
DeleteLearnedData = "#muffin/deleteLearnedData@"
DeleteLearnedDataUserId = "#muffin/deleteLearnedData@"
DeleteLearnedDataCancel = "#muffin/deleteLearnedData/cancel@"
PaginationEmbedPrev = "#muffin-pages/prev$"
PaginationEmbedPages = "#muffin-pages/pages$"
@ -18,19 +20,31 @@ const (
PaginationEmbedSetPage = "#muffin-pages/modal/set$"
)
func MakeDeleteLearnedData(id string, number int, userId string) string {
return fmt.Sprintf("%sid=%s&no=%d&user_id=%s", DeleteLearnedData, id, number, userId)
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 GetDeleteLearnedDataId(customId string) (id bson.ObjectID, itemId int) {
id, _ = bson.ObjectIDFromHex(strings.ReplaceAll(RegexpDLDId.FindAllString(customId, 1)[0], "id=", ""))
stringItemId := strings.ReplaceAll(RegexpDLDItemId.FindAllString(customId, 1)[0], "no=", "")
id, _ = bson.ObjectIDFromHex(strings.ReplaceAll(RegexpItemId.ReplaceAllString(customId[len(DeleteLearnedData):], ""), "&", ""))
stringItemId := strings.ReplaceAll(RegexpItemId.FindAllString(customId, 1)[0], "No.", "")
itemId, _ = strconv.Atoi(stringItemId)
return
}
func GetDeleteLearnedDataUserId(customId string) string {
return strings.ReplaceAll(RegexpDLDUserId.FindAllString(customId, 1)[0], "user_id=", "")
if strings.HasPrefix(customId, DeleteLearnedDataCancel) {
return customId[len(DeleteLearnedDataCancel):]
} else {
return customId[len(DeleteLearnedDataUserId):]
}
}
func MakePaginationEmbedPrev(id string) string {

View file

@ -1,35 +0,0 @@
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
}

7
utils/embedColor.go Normal file
View file

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

View file

@ -1,6 +1,12 @@
package utils
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/bwmarrin/discordgo"
)
@ -10,37 +16,20 @@ 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) error {
err := i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
func (i *InteractionCreate) Reply(data *discordgo.InteractionResponseData) {
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.
@ -54,54 +43,38 @@ func GetInteractionOptions(i *discordgo.InteractionCreate) map[string]*discordgo
}
// DeferReply to this interaction.
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
func (i *InteractionCreate) DeferReply(ephemeral bool) {
var flags discordgo.MessageFlags
if ephemeral {
flags = discordgo.MessageFlagsEphemeral
}
i.Deferred = true
return err
i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: flags,
},
})
}
// DeferUpdate to this interaction.
func (i *InteractionCreate) DeferUpdate() error {
err := i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
func (i *InteractionCreate) DeferUpdate() {
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 *InteractionEdit) error {
endpoint := discordgo.EndpointWebhookMessage(i.AppID, i.Token, "@original")
_, err := i.Session.RequestWithBucketID("PATCH", endpoint, *data, discordgo.EndpointWebhookToken("", ""))
i.Replied = true
return err
func (i *InteractionCreate) EditReply(data *discordgo.WebhookEdit) {
i.Session.InteractionResponseEdit(i.Interaction, data)
}
// Update to this interaction.
func (i *InteractionCreate) Update(data *discordgo.InteractionResponseData) error {
err := i.Session.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
func (i *InteractionCreate) Update(data *discordgo.InteractionResponseData) {
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 {
@ -112,8 +85,35 @@ func (i *InteractionCreate) ShowModal(data *ModalData) error {
reqData.Type = discordgo.InteractionResponseModal
reqData.Data = *data
endpoint := discordgo.EndpointInteractionResponse(i.ID, i.Token)
_, err := i.Session.RequestWithBucketID("POST", endpoint, reqData, endpoint)
bin, err := json.Marshal(reqData)
if err != nil {
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
}

View file

@ -1,110 +0,0 @@
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,57 +9,25 @@ import (
// PaginationEmbed is embed with page
type PaginationEmbed struct {
Container *discordgo.Container
Containers []*discordgo.Container
Embed *discordgo.MessageEmbed
Data []string
Current int
Total int
Id string
m any
id string
desc string
}
var PaginationEmbeds = make(map[string]*PaginationEmbed)
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 {
func makeComponents(id string, current, total int) *[]discordgo.MessageComponent {
disabled := false
if total == 1 {
disabled = true
}
return &discordgo.ActionsRow{
return &[]discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.Button{
Style: discordgo.PrimaryButton,
@ -80,10 +48,11 @@ func makeComponents(id string, current, total int) *discordgo.ActionsRow {
Disabled: disabled,
},
},
},
}
}
func MakeDesc(desc, item string) string {
func makeDesc(desc, item string) string {
var newDesc string
if desc == "" {
@ -94,19 +63,49 @@ func MakeDesc(desc, item string) string {
return newDesc
}
func startPaginationEmbed(p *PaginationEmbed) error {
container := *p.Containers[0]
container.Components = append(container.Components, makeComponents(p.Id, p.Current, p.Total))
// StartPaginationEmbed starts new PaginationEmbed struct
func StartPaginationEmbed(s *discordgo.Session, m any, e *discordgo.MessageEmbed, data []string, defaultDesc string) {
var userId string
PaginationEmbeds[p.Id] = p
switch m := m.(type) {
case *discordgo.MessageCreate:
userId = m.Author.ID
case *InteractionCreate:
userId = m.Member.User.ID
}
err := NewMessageSender(p.m).
AddComponents(container).
SetReply(true).
SetEphemeral(true).
SetComponentsV2(true).
Send()
return err
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
}
func GetPaginationEmbed(id string) *PaginationEmbed {
@ -119,77 +118,101 @@ func GetPaginationEmbed(id string) *PaginationEmbed {
func (p *PaginationEmbed) Prev(i *InteractionCreate) {
if p.Current == 1 {
i.Reply(&discordgo.InteractionResponseData{
Components: []discordgo.MessageComponent{
GetErrorContainer(discordgo.TextDisplay{Content: "해당 페이지가 처음ㅇ이에요."}),
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "해당 페이지가 처음ㅇ이에요.",
Color: EmbedFail,
},
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
},
Flags: discordgo.MessageFlagsEphemeral,
})
return
}
p.Current -= 1
p.Set(i, p.Current)
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),
})
}
func (p *PaginationEmbed) Next(i *InteractionCreate) {
if p.Current >= p.Total {
i.Reply(&discordgo.InteractionResponseData{
Components: []discordgo.MessageComponent{
GetErrorContainer(discordgo.TextDisplay{Content: "해당 페이지가 마지막ㅇ이에요."}),
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "해당 페이지가 마지막ㅇ이에요.",
Color: EmbedFail,
},
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
},
Flags: discordgo.MessageFlagsEphemeral,
})
return
}
p.Current += 1
p.Set(i, p.Current)
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),
})
}
func (p *PaginationEmbed) Set(i *InteractionCreate, page int) error {
func (p *PaginationEmbed) Set(i *InteractionCreate, page int) {
if page <= 0 {
i.Reply(&discordgo.InteractionResponseData{
Components: []discordgo.MessageComponent{
GetErrorContainer(discordgo.TextDisplay{Content: "해당 값은 0보다 커야해요."}),
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "해당 값은 0보다 커야해요.",
Color: EmbedFail,
},
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
},
Flags: discordgo.MessageFlagsEphemeral,
})
return nil
return
}
if page > p.Total {
if page >= p.Total {
i.Reply(&discordgo.InteractionResponseData{
Components: []discordgo.MessageComponent{
GetErrorContainer(discordgo.TextDisplay{Content: "해당 값은 총 페이지의 수보다 작아야해요."}),
Embeds: []*discordgo.MessageEmbed{
{
Title: "❌ 오류",
Description: "해당 값은 총 페이지의 수보다 작아야해요.",
Color: EmbedFail,
},
Flags: discordgo.MessageFlagsEphemeral | discordgo.MessageFlagsIsComponentsV2,
},
Flags: discordgo.MessageFlagsEphemeral,
})
return nil
return
}
p.Current = page
container := *p.Containers[p.Current-1]
container.Components = append(container.Components, makeComponents(p.Id, p.Current, p.Total))
p.Embed.Description = makeDesc(p.desc, p.Data[p.Current-1])
err := i.Update(&discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsIsComponentsV2,
Components: []discordgo.MessageComponent{container},
i.Update(&discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{p.Embed},
Components: *makeComponents(p.id, p.Current, p.Total),
})
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,9 +5,7 @@ import "regexp"
var (
RegexpFlexibleString = regexp.MustCompile(`[^\s"'「」«»]+|"([^"]*)"|'([^']*)'|「([^」]*)」|«([^»]*)»`)
RegexpDecimals = regexp.MustCompile(`\d+`)
RegexpDLDItemId = regexp.MustCompile(`no=\d+`)
RegexpDLDUserId = regexp.MustCompile(`user_id=\d+`)
RegexpDLDId = regexp.MustCompile(`id=[^&]*`)
RegexpItemId = regexp.MustCompile(`No.\d+`)
RegexpEmoji = regexp.MustCompile(`<a?:\w+:\d+>`)
RegexpLearnQueryCommand = regexp.MustCompile(`단어:([^\n대답개수:]*)`)
RegexpLearnQueryResult = regexp.MustCompile(`대답:([^\n단어개수:]*)`)

View file

@ -1,10 +0,0 @@
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
}