From e181a09b4b2b7877e273a345fd4a03ed19a6eece Mon Sep 17 00:00:00 2001 From: Luther Wen Xu Date: Sat, 12 Oct 2019 21:49:41 +0800 Subject: [PATCH] go: Refactor messageutil.go --- GoBot/discord/config/translate.go | 33 +++++ GoBot/discord/modules/embed.go | 9 ++ GoBot/discord/modules/invite.go | 211 ++++++++++++--------------- GoBot/discord/modules/messageutil.go | 130 ++++++++--------- GoBot/discord/modules/trust.go | 81 +++++----- GoBot/discord/modules/vote.go | 54 ++++--- GoBot/discord/modules/vote_invite.go | 6 +- GoBot/discord/modules/vote_result.go | 15 +- 8 files changed, 284 insertions(+), 255 deletions(-) diff --git a/GoBot/discord/config/translate.go b/GoBot/discord/config/translate.go index 46e5ce4..84ead57 100644 --- a/GoBot/discord/config/translate.go +++ b/GoBot/discord/config/translate.go @@ -4,8 +4,33 @@ package config const UsageTitle = "使用方法Command Usage" const UsageColour = 0xF00000 const ErrorStack = "纠错信息Debug Info" +const ErrorColour = 0xE00000 const SuccessTitle = "成功Success" const SuccessColour = 0x00E000 +const PermissionErrorTitle = "没有权限Forbidden" +const ErrorCannotFindMember = "请确保你已经加入伺服器。Please make sure that you're in the server." +const ErrorMustNotBeMember = "这个指令不能被会员使用。This command cannot be used by server members." +const ErrorMustBeMember = "这个指令只能在成为会员后使用。This command can only be used by server members." +const ErrorMustDMTitle = "私信保护 DM Protection" +const ErrorMustDMDescription = "<@%s>,这个指令只能在私信中使用。<@%s>, this command can only be used in DMs." +const AuditInfoTitle = "记录Audit Info" +const AuditInfoColour = 0xA0A0A0 +const InternalErrorDescription = "发生了不明错误。An unknown error has occurred." + +//==Vote== +const VoteErrorTitle = "投票错误Vote Error" +const ErrorForceRejectionReuse = "您在这个月内已使用过:x:。请选择其他选项。\nYou have used :x: this month. Please choose another option." +const ErrorVoteHasEnded = "无法投票给已经结束的投票。\nCannot vote in a vote that has already ended." +const VoteSuccessfulTitle = "投票成功Voted Successfully" +const VoteSuccessfulVoteID = "投票编号Vote ID" +const VoteSuccessfulVoteName = "投票名称Vote Name" +const VoteSuccessfulDetectedVote = "所投的票Your Vote" + +const VoteSuggestionNote = "\n备注:这个系统即将被一个指令代替。\nNote: This system is going to be replaced by a command soon." +const VoteSuggestionErrorTitle = "开始新的投票错误Vote Suggestion Error" +const ErrorVoteSuggestionNotEnoughInfo = "请提供更多资料。\nPlease provide more information." +const ErrorVoteSuggestionTooLong = "你投票的内容过长了。请使用少过500个字符。\nYour vote is too long. Please use a maximum of 500 characters." +const ErrorVoteSuggestionUnknownType = "未知投票种类Unknown Vote Type: %s" //==Commands== const SendAsUsage = "!sendas <频道ID> <信息>\n!sendas " @@ -23,3 +48,11 @@ const VTLSingleUserServerTotal = "伺服器总分 Server Total" const VTLSingleUserPercentage = "百分比 Percentage" const VTLGlobalTitle = "伺服器信誉分报告 Server Trust Score Report" const VTLGlobalFieldFormat = "%.1f/%.1f (%.2f%%)" + +const ValidateUsage = "!validate <验证码> <为自己拉票的字>\n!validate " +const ValidateSuccess = "已向验证码制造者发送了请求。\nSent a request to use the validation code to its creator." +const ErrorValidateTitle = "验证错误Validation Error" +const ErrorValidationCodeReuse = "该验证码已被使用过。请向验证码制造者要求新的验证码。\nThis validation code has been used before. Please request a new one from its creator." +const ErrorValidationCodeNotExist = "该验证码不存在。请使用一位会员给你的验证码。\nThis validation code doesn't exist. Please use one given by a member." +const ErrorValidationCodeNotOwnedByMember = "验证码制造者不是会员。\nvalidation code creator is no longer a member." +const ErrorValidationCodeCreatorDisabledPM = "验证码制造者关闭了私信。\nValidation code creator did not enable DMs." diff --git a/GoBot/discord/modules/embed.go b/GoBot/discord/modules/embed.go index 46bc794..9fb84b8 100644 --- a/GoBot/discord/modules/embed.go +++ b/GoBot/discord/modules/embed.go @@ -61,3 +61,12 @@ func (e *embed) Build() *discordgo.MessageEmbed { func (e *embed) Send(s *discordgo.Session, channelID string) { s.ChannelMessageSendEmbed(channelID, e.Build()) } + +func (e *embed) SendPM(s *discordgo.Session, userID string) { + channel, err := s.UserChannelCreate(userID) + if err != nil { + auditError(s, "", err) + return + } + e.Send(s, channel.ID) +} diff --git a/GoBot/discord/modules/invite.go b/GoBot/discord/modules/invite.go index 43e7e19..03e4348 100644 --- a/GoBot/discord/modules/invite.go +++ b/GoBot/discord/modules/invite.go @@ -2,7 +2,6 @@ package modules import ( "fmt" - "strings" "github.com/bwmarrin/discordgo" @@ -17,120 +16,110 @@ type invite struct { Reason string } -func createInvite(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { - if !enforceDM(s, m) { - return - } - if !membersOnly(s, m) { - return - } - if len(command) < 2 { - s.ChannelMessageSend(m.ChannelID, "指令的使用方法是`!invite <你所要设置的验证码>`.\nUsage: `!invite `") - return - } - if len(command) > 2 { - s.ChannelMessageSend(m.ChannelID, "所提供的验证码不得有任何空格。\nThe provided validation code cannot contain any spaces.") - return - } +var createInvite = enforceDM(memberFilter(true, + func(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { + if len(command) < 2 { + s.ChannelMessageSend(m.ChannelID, "指令的使用方法是`!invite <你所要设置的验证码>`.\nUsage: `!invite `") + return + } + if len(command) > 2 { + s.ChannelMessageSend(m.ChannelID, "所提供的验证码不得有任何空格。\nThe provided validation code cannot contain any spaces.") + return + } - err := db.SetInviteOwner(command[1], m.Author.ID) - switch err { - case db.ErrAlreadyExists: - owner, _ := db.GetInviteOwner(command[1]) - if owner == m.Author.ID { + err := db.SetInviteOwner(command[1], m.Author.ID) + switch err { + case db.ErrAlreadyExists: + owner, _ := db.GetInviteOwner(command[1]) + if owner == m.Author.ID { + s.ChannelMessageSend( + m.ChannelID, + "这个验证码归你所有,它仍然未被使用。请把它告诉你要邀请的人。\nThis validation code belongs to you. Please give it to the person you want to invite.", + ) + return + } + s.ChannelMessageSend( + m.ChannelID, + "这个验证码已被其他会员注册。请使用别的验证码。\nThis validation code is already registered. Please try another one.", + ) + case db.ErrInviteUsed: + s.ChannelMessageSend( + m.ChannelID, + "这个验证码已被使用。请使用别的验证码。\nThis validation code has already been used. Please try another one.", + ) + case nil: s.ChannelMessageSend( m.ChannelID, - "这个验证码归你所有,它仍然未被使用。请把它告诉你要邀请的人。\nThis validation code belongs to you. Please give it to the person you want to invite.", + "这个验证码现在属于你了。请好好保管并把它交给你要邀请的人。\nThis validation code now belongs to you! Pass it on to the person you want to invite.", ) + default: + s.ChannelMessageSend( + m.ChannelID, + "不明错误已发生,请把这个错误信息发在群里。\nAn unknown error has occurred. Please pass this error message on.\n"+err.Error(), + ) + } + }, +)) + +var checkUseInvite = enforceDM(memberFilter(false, enforceArgumentCount( + config.ValidateUsage, 3, + func(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { + inviter, err := db.GetInviteOwner(command[1]) + if err == db.ErrInviteUsed { + initNewEmbed(config.ErrorValidateTitle, config.ErrorValidationCodeReuse, config.ErrorColour). + Send(s, m.ChannelID) + return + } + if err == db.ErrNotFound { + initNewEmbed(config.ErrorValidateTitle, config.ErrorValidationCodeNotExist, config.ErrorColour). + SendPM(s, m.ChannelID) + return + } + if err != nil { + auditError(s, m.ChannelID, err) return } - s.ChannelMessageSend( - m.ChannelID, - "这个验证码已被其他会员注册。请使用别的验证码。\nThis validation code is already registered. Please try another one.", - ) - case db.ErrInviteUsed: - s.ChannelMessageSend( - m.ChannelID, - "这个验证码已被使用。请使用别的验证码。\nThis validation code has already been used. Please try another one.", - ) - case nil: - s.ChannelMessageSend( - m.ChannelID, - "这个验证码现在属于你了。请好好保管并把它交给你要邀请的人。\nThis validation code now belongs to you! Pass it on to the person you want to invite.", - ) - default: - s.ChannelMessageSend( - m.ChannelID, - "不明错误已发生,请把这个错误信息发在群里。\nAn unknown error has occurred. Please pass this error message on.\n"+err.Error(), - ) - } -} - -func checkUseInvite(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { - if !enforceDM(s, m) { - return - } - if !nonMembersOnly(s, m) { - return - } - s.ChannelMessageDelete(m.ChannelID, m.ID) - if len(command) < 3 { - sendPrivateMessage(s, m.Author.ID, "指令的使用方法是`!validate <验证码> <原因>`.\nUsage: `!validate `") - return - } - - messageSplit := strings.SplitN(m.Content, " ", 3) - inviter, err := db.GetInviteOwner(messageSplit[1]) - if err == db.ErrInviteUsed { - sendPrivateMessage(s, m.Author.ID, "该验证码已被使用过。请向验证码制造者要求新的验证码。\nThis validation code has been used before. Please request a new one.") - return - } - if err == db.ErrNotFound { - sendPrivateMessage(s, m.Author.ID, "该验证码不存在。请使用存在的验证码。\nThis validation code doesn't exist. Please use an existing one.") - return - } - if err != nil { - sendPrivateMessage(s, m.Author.ID, "错误已发生。请稍候尝试。\nAn error has occurred. Please try again later.") - auditLog(s, err.Error()) - return - } - db.UseInvite(messageSplit[1]) - member, err := s.GuildMember(config.GuildID, inviter) - if err != nil { - sendPrivateMessage(s, m.Author.ID, "验证码制造者不是会员。\nValidation code creator is no longer a member.") - return - } + db.UseInvite(command[1]) + member, err := s.GuildMember(config.GuildID, inviter) + if err != nil { + auditErrorPM(s, m.ChannelID, err) + return + } - isMember := false - for _, v := range member.Roles { - if v == config.MemberRoleID { - isMember = true + isMember := false + for _, v := range member.Roles { + if v == config.MemberRoleID { + isMember = true + } + } + if !isMember { + initNewEmbed(config.ErrorValidateTitle, config.ErrorValidationCodeNotOwnedByMember, config.ErrorColour). + SendPM(s, m.ChannelID) + return } - } - if !isMember { - sendPrivateMessage(s, m.Author.ID, "验证码制造者不是会员。\nValidation code creator is no longer a member.") - return - } - channel, err := s.UserChannelCreate(inviter) - if err != nil { - sendPrivateMessage(s, m.Author.ID, "验证码制造者关闭了私信。\nValidation code creator did not enable DMs.") - return - } - msg, err := s.ChannelMessageSend(channel.ID, fmt.Sprintf("<@%s>正在尝试使用验证码%s。请问是否同意该使用?", m.Author.ID, messageSplit[1])) - if err != nil { - sendPrivateMessage(s, m.Author.ID, "验证码制造者关闭了私信。\nValidation code creator did not enable DMs.") - return - } - pendingInviteConfirmation[msg.ID] = invite{ - User: m.Author.ID, - Reason: messageSplit[2], - } - s.MessageReactionAdd(channel.ID, msg.ID, emojiX) - s.MessageReactionAdd(channel.ID, msg.ID, emojiCheck) - sendPrivateMessage(s, m.Author.ID, "已向验证码制造者发送了请求。\nSent a request to use the validation code to its creator.") -} + channel, err := s.UserChannelCreate(inviter) + if err != nil { + initNewEmbed(config.ErrorValidateTitle, config.ErrorValidationCodeCreatorDisabledPM, config.ErrorColour). + SendPM(s, m.ChannelID) + return + } + msg, err := s.ChannelMessageSend(channel.ID, fmt.Sprintf("<@%s>正在尝试使用验证码%s。请问是否同意该使用?", m.Author.ID, command[1])) + if err != nil { + auditErrorPM(s, m.ChannelID, err) + return + } + pendingInviteConfirmation[msg.ID] = invite{ + User: m.Author.ID, + Reason: command[2], + } + s.MessageReactionAdd(channel.ID, msg.ID, emojiX) + s.MessageReactionAdd(channel.ID, msg.ID, emojiCheck) + initNewEmbed(config.SuccessTitle, config.ValidateSuccess, config.SuccessColour). + SendPM(s, m.ChannelID) + }, +))) func CheckForInvite(s *discordgo.Session, r *discordgo.MessageReactionAdd) { if r.UserID == s.State.User.ID { @@ -156,21 +145,15 @@ func CheckForInvite(s *discordgo.Session, r *discordgo.MessageReactionAdd) { msg, err := s.ChannelMessageSend(config.VoteChannel, "正在准备新的一个投票…… Preparing for the next vote...") if err != nil { - sendPrivateMessage(s, r.UserID, "创造投票失败。Failed to create vote.") - auditLog(s, - fmt.Sprintf("Error occurred while creating vote for <@%s>.\n%v\nError: %s", r.UserID, *r, err.Error()), - ) + auditErrorPM(s, r.UserID, err) return } id, err := db.CreateInviteVote(msg.ID, invite.User, invite.Reason) if err != nil { - sendPrivateMessage(s, r.UserID, "创造投票失败。Failed to create vote.") - auditLog(s, - fmt.Sprintf("Error occurred while creating vote for <@%s>.\n%v\nError: %s", r.UserID, *r, err.Error()), - ) + auditErrorPM(s, r.UserID, err) return } - auditLog(s, fmt.Sprintf("Vote ID %d has been created by <@%s>.", id, r.UserID)) + auditInfo(s, fmt.Sprintf("Vote ID %d has been created by <@%s>.", id, r.UserID)) s.ChannelMessageEdit(config.VoteChannel, msg.ID, "") s.ChannelMessageEditEmbed(config.VoteChannel, msg.ID, createInviteEmbed(id, invite.User+":"+invite.Reason)) s.MessageReactionAdd(config.VoteChannel, msg.ID, emojiX) diff --git a/GoBot/discord/modules/messageutil.go b/GoBot/discord/modules/messageutil.go index dde7ff3..45086ba 100644 --- a/GoBot/discord/modules/messageutil.go +++ b/GoBot/discord/modules/messageutil.go @@ -11,82 +11,55 @@ import ( "TerraOceanBot/discord/config" ) -func enforceDM(s *discordgo.Session, m *discordgo.MessageCreate) bool { - if m.GuildID != "" { - //This command can only be used in DM to protect the invite creator. - s.ChannelMessageDelete(m.ChannelID, m.ID) - s.ChannelMessageSend( - m.ChannelID, - m.Author.Mention()+",这个指令只能在私信中使用。\n"+m.Author.Mention()+", this command can only be used in DM.", - ) - return false - } - return true -} - -func membersOnly(s *discordgo.Session, m *discordgo.MessageCreate) bool { - member, err := s.GuildMember(config.GuildID, m.Author.ID) - if err != nil { - s.ChannelMessageSend( - m.ChannelID, - m.Author.Mention()+",请在成为会员后才使用这个指令。\n"+m.Author.Mention()+", please use this command after you become a member.", - ) - return false - } - for _, v := range member.Roles { - if v == config.MemberRoleID { - return true +func enforceDM(passOn CommandHandler) CommandHandler { + return func(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { + if m.GuildID != "" { + //This command can only be used in DM to protect the invite creator. + s.ChannelMessageDelete(m.ChannelID, m.ID) + initNewEmbed( + config.ErrorMustDMTitle, + fmt.Sprintf(config.ErrorMustDMDescription, m.Author.ID, m.Author.ID), + config.ErrorColour, + ).Send(s, m.ChannelID) + return } + passOn(s, m, command) } - s.ChannelMessageSend( - m.ChannelID, - m.Author.Mention()+",请在成为会员后才使用这个指令。\n"+m.Author.Mention()+", please use this command after you become a member.", - ) - return false } -func nonMembersOnly(s *discordgo.Session, m *discordgo.MessageCreate) bool { - member, err := s.GuildMember(config.GuildID, m.Author.ID) - if err != nil { - return false - } - for _, v := range member.Roles { - if v == config.MemberRoleID { - s.ChannelMessageSend( - m.ChannelID, - m.Author.Mention()+",该指令只能被非会员使用。\n"+m.Author.Mention()+", this command can only be used by non-member.", - ) - return false +func memberFilter(mustBeMember bool, passOn CommandHandler) CommandHandler { + return func(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { + member, err := s.GuildMember(config.GuildID, m.Author.ID) + if err != nil { + initNewEmbed(config.PermissionErrorTitle, config.ErrorCannotFindMember, config.ErrorColour). + Send(s, m.ChannelID) + return + } + for _, v := range member.Roles { + if v == config.MemberRoleID { + if mustBeMember { + passOn(s, m, command) + } else { + initNewEmbed(config.PermissionErrorTitle, config.ErrorMustNotBeMember, config.ErrorColour). + Send(s, m.ChannelID) + } + return + } + } + if mustBeMember { + initNewEmbed(config.PermissionErrorTitle, config.ErrorMustBeMember, config.ErrorColour). + Send(s, m.ChannelID) + } else { + passOn(s, m, command) } - } - return true -} - -func sendPrivateMessage(s *discordgo.Session, recipient, message string) error { - channel, err := s.UserChannelCreate(recipient) - if err != nil { - return err - } - _, err = s.ChannelMessageSend(channel.ID, message) - return err -} - -func auditLog(s *discordgo.Session, message string) { - _, err := s.ChannelMessageSend(config.AuditChannel, message) - if err != nil { - fmt.Println("==Audit Log==") - fmt.Println(message) - fmt.Println(err) } } func enforceArgumentCount(usage string, count int, passOn CommandHandler) CommandHandler { return func(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { if len(command) < count { - s.ChannelMessageSendEmbed( - m.ChannelID, - newEmbed().SetTitle(config.UsageTitle).SetDescription(usage).SetColour(config.UsageColour).Build(), - ) + initNewEmbed(config.UsageTitle, usage, config.UsageColour). + Send(s, m.ChannelID) return } command[count-1] = strings.Join(command[count-1:], " ") @@ -101,7 +74,32 @@ func sendError(s *discordgo.Session, channelID string, err error) { if count == 512 { stack += "..." } - initNewErrorEmbed(err.Error()).AddField(config.ErrorStack, stack).Send(s, channelID) + initNewErrorEmbed(err.Error()). + AddField(config.ErrorStack, stack). + Send(s, channelID) +} + +func auditInfo(s *discordgo.Session, message string) { + initNewEmbed(config.AuditInfoTitle, message, config.AuditInfoColour). + Send(s, config.AuditChannel) +} + +func auditError(s *discordgo.Session, sourceChannel string, err error) { + if sourceChannel != "" { + initNewErrorEmbed(config.InternalErrorDescription). + Send(s, sourceChannel) + } + sendError(s, config.AuditChannel, err) +} + +func auditErrorPM(s *discordgo.Session, sourceUser string, err error) { + channel, channelErr := s.UserChannelCreate(sourceUser) + if channelErr != nil { + auditError(s, "", channelErr) + auditError(s, "", err) + return + } + auditError(s, channel.ID, err) } func formatFloat(n float64, precision int) string { diff --git a/GoBot/discord/modules/trust.go b/GoBot/discord/modules/trust.go index 40dc997..6a4f41b 100644 --- a/GoBot/discord/modules/trust.go +++ b/GoBot/discord/modules/trust.go @@ -1,7 +1,6 @@ package modules import ( - "fmt" "strings" "github.com/bwmarrin/discordgo" @@ -12,46 +11,42 @@ import ( var trustMessage = make(map[string]string) -func changeTrust(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { - if !enforceDM(s, m) { - return - } - if !membersOnly(s, m) { - return - } - if len(command) < 2 { - s.ChannelMessageSend(m.ChannelID, "指令的使用方法是`!trust <你要改信任度的人>`.\nUsage: `!trust `") - return - } - - member, err := backend.GetMemberFromUserFriendlyName(s, strings.SplitN(m.Content, " ", 2)[1]) - if err == backend.ErrMemberNotFound { - s.ChannelMessageSend(m.ChannelID, "无法找到您所要求的玩家。\nCannot find the requested player.") - return - } - if err != nil { - auditLog(s, fmt.Sprintf("Error while processing change trust request for <@%s>: %s", m.Author.ID, err.Error())) - return - } - - message, err := s.ChannelMessageSendEmbed( - m.ChannelID, - createTrustEmbed(member.User.Username+"#"+member.User.Discriminator, member.Nick), - ) - if err != nil { - auditLog(s, fmt.Sprintf("Error while sending change trust request for <@%s>: %s", m.Author.ID, err.Error())) - return - } - - trustMessage[message.ID] = member.User.ID - - s.MessageReactionAdd(m.ChannelID, message.ID, emojiOne) - s.MessageReactionAdd(m.ChannelID, message.ID, emojiTwo) - s.MessageReactionAdd(m.ChannelID, message.ID, emojiThree) - s.MessageReactionAdd(m.ChannelID, message.ID, emojiFour) - s.MessageReactionAdd(m.ChannelID, message.ID, emojiFive) - s.MessageReactionAdd(m.ChannelID, message.ID, emojiCheck) -} +var changeTrust = enforceDM(memberFilter(true, + func(s *discordgo.Session, m *discordgo.MessageCreate, command []string) { + if len(command) < 2 { + s.ChannelMessageSend(m.ChannelID, "指令的使用方法是`!trust <你要改信任度的人>`.\nUsage: `!trust `") + return + } + + member, err := backend.GetMemberFromUserFriendlyName(s, strings.SplitN(m.Content, " ", 2)[1]) + if err == backend.ErrMemberNotFound { + s.ChannelMessageSend(m.ChannelID, "无法找到您所要求的玩家。\nCannot find the requested player.") + return + } + if err != nil { + auditError(s, m.ChannelID, err) + return + } + + message, err := s.ChannelMessageSendEmbed( + m.ChannelID, + createTrustEmbed(member.User.Username+"#"+member.User.Discriminator, member.Nick), + ) + if err != nil { + auditError(s, m.ChannelID, err) + return + } + + trustMessage[message.ID] = member.User.ID + + s.MessageReactionAdd(m.ChannelID, message.ID, emojiOne) + s.MessageReactionAdd(m.ChannelID, message.ID, emojiTwo) + s.MessageReactionAdd(m.ChannelID, message.ID, emojiThree) + s.MessageReactionAdd(m.ChannelID, message.ID, emojiFour) + s.MessageReactionAdd(m.ChannelID, message.ID, emojiFive) + s.MessageReactionAdd(m.ChannelID, message.ID, emojiCheck) + }, +)) func createTrustEmbed(username, nick string) *discordgo.MessageEmbed { embed := newEmbed().SetColour(0x00FFFF).SetTitle("更新玩家评分Update Player Score").AddField("ID", username) @@ -89,7 +84,7 @@ func CheckForTrustUpdate(s *discordgo.Session, r *discordgo.MessageReactionAdd) case emojiCheck: value = db.NuclearOptionVote default: - auditLog(s, "Reaction "+r.Emoji.Name+" was added to trust message ID "+r.MessageID) + auditInfo(s, "Reaction "+r.Emoji.Name+" was added to trust message ID "+r.MessageID) return } @@ -99,7 +94,7 @@ func CheckForTrustUpdate(s *discordgo.Session, r *discordgo.MessageReactionAdd) return } if err != nil { - auditLog(s, fmt.Sprintf("Error while changing the trust value for <@%s> with target <@%s>: %s", r.UserID, target, err.Error())) + auditError(s, r.ChannelID, err) return } diff --git a/GoBot/discord/modules/vote.go b/GoBot/discord/modules/vote.go index 6668f07..7c4a08d 100644 --- a/GoBot/discord/modules/vote.go +++ b/GoBot/discord/modules/vote.go @@ -46,7 +46,7 @@ func CheckForVote(s *discordgo.Session, r *discordgo.MessageReactionAdd) { return } if err != nil { - auditLog(s, "Error while checking for vote: "+err.Error()) + auditError(s, r.ChannelID, err) return } @@ -69,18 +69,20 @@ func CheckForVote(s *discordgo.Session, r *discordgo.MessageReactionAdd) { case emojiCheck: value = db.NuclearOptionVote default: - auditLog(s, "Reaction "+r.Emoji.Name+" was added to vote #"+strconv.Itoa(voteID)) + auditInfo(s, "Reaction "+r.Emoji.Name+" was added to vote #"+strconv.Itoa(voteID)) return } err = db.UpdateVote(voteID, r.UserID, value) if err == db.ErrForceRejectionVoteReuse { - sendPrivateMessage(s, r.UserID, "您在这个月内已使用过:x:。请选择其他选项。\nYou have used :x: this month. Please choose another option.") + initNewEmbed(config.VoteErrorTitle, config.ErrorForceRejectionReuse, config.ErrorColour). + SendPM(s, r.UserID) return } if err == db.ErrVoteIsOver { - sendPrivateMessage(s, r.UserID, "这个投票已结束。你投的票没有被记录。\nThe vote is over so your vote is not recorded.") + initNewEmbed(config.VoteErrorTitle, config.ErrorVoteHasEnded, config.ErrorColour). + SendPM(s, r.UserID) return } @@ -90,29 +92,39 @@ func CheckForVote(s *discordgo.Session, r *discordgo.MessageReactionAdd) { } if err != nil { - sendPrivateMessage(s, r.UserID, "一个错误已发生,请重新尝试。\nAn error has occurred while voting. Please try again.") - auditLog(s, - fmt.Sprintf("Error occurred while processing vote for <@%s>.\n%v\nError: %s", r.UserID, *r, err.Error()), - ) + auditErrorPM(s, r.UserID, err) return } - sendPrivateMessage(s, r.UserID, "您投票已成功。\nYou have voted successfully.\n名字Vote Name: "+voteName+"\n目前投的票: :"+r.Emoji.Name+":") - auditLog(s, fmt.Sprintf("<@%s> has chosen %s for vote ID %d.", r.UserID, r.Emoji.Name, voteID)) + initNewEmbed(config.VoteSuccessfulTitle, "", config.SuccessColour). + AddField(config.VoteSuccessfulVoteID, strconv.Itoa(voteID)). + AddField(config.VoteSuccessfulVoteName, voteName). + AddField(config.VoteSuccessfulDetectedVote, r.Emoji.Name). + SendPM(s, r.UserID) + auditInfo(s, fmt.Sprintf("<@%s> has chosen %s for vote ID %d.", r.UserID, r.Emoji.Name, voteID)) checkForVoteResult(s, voteID) } +//TODO Replace with a command. func VoteSuggestion(s *discordgo.Session, m *discordgo.MessageCreate) { s.ChannelMessageDelete(m.ChannelID, m.ID) args := strings.SplitN(m.Content, " ", 2) if len(args) == 1 { - sendPrivateMessage(s, m.Author.ID, "请提供更多资料。\nPlease provide more information.") + initNewEmbed( + config.VoteSuggestionErrorTitle, + config.ErrorVoteSuggestionNotEnoughInfo+config.VoteSuggestionNote, + config.ErrorColour, + ).SendPM(s, m.Author.ID) return } if len(args[1]) > 500 { - sendPrivateMessage(s, m.Author.ID, "你投票的内容过长了。请使用少过500个字符。\nYour vote is too long. Please use a maximum of 500 characters.") + initNewEmbed( + config.VoteSuggestionErrorTitle, + config.ErrorVoteSuggestionTooLong+config.VoteSuggestionNote, + config.ErrorColour, + ).SendPM(s, m.Author.ID) return } @@ -120,21 +132,15 @@ func VoteSuggestion(s *discordgo.Session, m *discordgo.MessageCreate) { case "custom": msg, err := s.ChannelMessageSend(config.VoteChannel, "正在准备新的一个投票…… Preparing for the next vote...") if err != nil { - sendPrivateMessage(s, m.Author.ID, "创造投票失败。Failed to create vote.") - auditLog(s, - fmt.Sprintf("Error occurred while creating vote for <@%s>.\n%v\nError: %s", m.Author.ID, *m, err.Error()), - ) + auditErrorPM(s, m.Author.ID, err) return } id, err := db.CreateCustomVote(msg.ID, args[1]) if err != nil { - sendPrivateMessage(s, m.Author.ID, "创造投票失败。Failed to create vote.") - auditLog(s, - fmt.Sprintf("Error occurred while creating vote for <@%s>.\n%v\nError: %s", m.Author.ID, *m, err.Error()), - ) + auditErrorPM(s, m.Author.ID, err) return } - auditLog(s, fmt.Sprintf("Vote ID %d has been created by <@%s>.", id, m.Author.ID)) + auditInfo(s, fmt.Sprintf("Vote ID %d has been created by <@%s>.", id, m.Author.ID)) s.ChannelMessageEdit(config.VoteChannel, msg.ID, "") s.ChannelMessageEditEmbed(config.VoteChannel, msg.ID, createCustomEmbed(id, args[1])) s.MessageReactionAdd(config.VoteChannel, msg.ID, emojiOne) @@ -143,7 +149,11 @@ func VoteSuggestion(s *discordgo.Session, m *discordgo.MessageCreate) { s.MessageReactionAdd(config.VoteChannel, msg.ID, emojiFour) s.MessageReactionAdd(config.VoteChannel, msg.ID, emojiFive) default: - sendPrivateMessage(s, m.Author.ID, "未知投票种类:"+args[0]+"\nUnknown vote type: "+args[0]) + initNewEmbed( + config.VoteSuggestionErrorTitle, + fmt.Sprintf(config.ErrorVoteSuggestionUnknownType, args[1])+config.VoteSuggestionNote, + config.ErrorColour, + ).SendPM(s, m.Author.ID) } } diff --git a/GoBot/discord/modules/vote_invite.go b/GoBot/discord/modules/vote_invite.go index b151139..c107ac0 100644 --- a/GoBot/discord/modules/vote_invite.go +++ b/GoBot/discord/modules/vote_invite.go @@ -25,18 +25,18 @@ func handleInviteResult(s *discordgo.Session, id int, name string, isPositive bo } member, err := backend.GetMemberFromUserFriendlyName(s, strings.SplitN(name, ":", 2)[0]) if err != nil { - auditLog(s, "Error while getting member from user friendly name in invite result. "+err.Error()) + auditError(s, "", err) return } err = s.GuildMemberRoleAdd(config.GuildID, member.User.ID, config.MemberRoleID) if err != nil { - auditLog(s, fmt.Sprintf("Fail to give user <@%s> the member role: %s", member.User.ID, err.Error())) + auditError(s, "", err) return } s.ChannelMessageSend(announceInviteChannel, fmt.Sprintf("欢迎<@%s>的加入!Welcome <@%s> to this server!", member.User.ID, member.User.ID)) choices, err := db.GetAllVoteChoices(id) if err != nil { - auditLog(s, "Error while pulling vote choices. "+err.Error()) + auditError(s, "", err) return } for _, choice := range choices { diff --git a/GoBot/discord/modules/vote_result.go b/GoBot/discord/modules/vote_result.go index 29a67f3..2a34755 100644 --- a/GoBot/discord/modules/vote_result.go +++ b/GoBot/discord/modules/vote_result.go @@ -24,9 +24,10 @@ func ListenToVoteFinishes(s *discordgo.Session) { for { voteMutex.Lock() for _, v := range toAnnounceResultList { - auditLog(s, fmt.Sprintf("Announcing the result of vote %d.", v.VoteID)) + auditInfo(s, fmt.Sprintf("Announcing the result of vote %d.", v.VoteID)) if err := db.FinishVote(v.VoteID); err != nil { - auditLog(s, fmt.Sprintf("Error while finishing vote %d.", v.VoteID)) + auditError(s, "", err) + continue } voteType, _ := db.GetVoteType(v.VoteID) voteName, _ := db.GetVoteName(v.VoteID) @@ -43,7 +44,7 @@ func ListenToVoteFinishes(s *discordgo.Session) { func checkForVoteResult(s *discordgo.Session, id int) { votes, err := db.GetAllVoteChoices(id) if err != nil { - auditLog(s, fmt.Sprintf("Error while calculating vote result for ID %d: %s", id, err.Error())) + auditError(s, "", err) return } var currentScore, totalTrust float64 @@ -54,7 +55,7 @@ func checkForVoteResult(s *discordgo.Session, id int) { } trust, err := backend.GetTrust(s, vote.UserID) if err != nil { - auditLog(s, fmt.Sprintf("Error while getting vote trust for user ID %d: %s", vote.UserID, err.Error())) + auditError(s, "", err) return } currentScore += float64(vote.Value) * trust @@ -63,7 +64,7 @@ func checkForVoteResult(s *discordgo.Session, id int) { totalGlobalTrust, err := backend.GetTotalTrust(s) if err != nil { - auditLog(s, fmt.Sprintf("Error while getting total vote trust: %s", err.Error())) + auditError(s, "", err) return } remainingTrust := totalGlobalTrust - totalTrust @@ -80,7 +81,7 @@ func checkForVoteResult(s *discordgo.Session, id int) { return } } - auditLog(s, fmt.Sprintf("Rejection of vote ID %d has been confirmed.", id)) + auditInfo(s, fmt.Sprintf("Rejection of vote ID %d has been confirmed.", id)) toAnnounceResultList = append(toAnnounceResultList, confirmedResult{ VoteID: id, IsPositive: false, @@ -97,7 +98,7 @@ func checkForVoteResult(s *discordgo.Session, id int) { return } } - auditLog(s, fmt.Sprintf("Acceptance of vote ID %d has been confirmed.", id)) + auditInfo(s, fmt.Sprintf("Acceptance of vote ID %d has been confirmed.", id)) toAnnounceResultList = append(toAnnounceResultList, confirmedResult{ VoteID: id, IsPositive: true,