Merge pull request #103 from matthe815/feature/discord-login

feat: Password resetting by Discord integration
This commit is contained in:
wish
2024-01-02 19:58:02 +11:00
committed by GitHub
9 changed files with 164 additions and 22 deletions

View File

@@ -84,7 +84,11 @@
"Discord": {
"Enabled": false,
"BotToken": "",
"RealtimeChannelID": ""
"RealTimeChannel": {
"Enabled": false,
"MaxMessageLength": 183,
"RealTimeChannelID": ""
}
},
"Commands": [
{
@@ -127,6 +131,11 @@
"Enabled": true,
"Description": "Link a PlayStation Network ID to your account",
"Prefix": "psn"
}, {
"Name": "Discord",
"Enabled": true,
"Description": "Generate a token to link your Discord account",
"Prefix": "discord"
}
],
"Courses": [

View File

@@ -171,9 +171,15 @@ type GameplayOptions struct {
// Discord holds the discord integration config.
type Discord struct {
Enabled bool
BotToken string
RealtimeChannelID string
Enabled bool
BotToken string
RelayChannel DiscordRelay
}
type DiscordRelay struct {
Enabled bool
MaxMessageLength int
RelayChannelID string
}
// Command is a channelserver chat command

View File

@@ -91,6 +91,12 @@ func main() {
}
discordBot = bot
_, err = discordBot.Session.ApplicationCommandBulkOverwrite(discordBot.Session.State.User.ID, "", discordbot.Commands)
if err != nil {
preventClose(fmt.Sprintf("Discord: Failed to start, %s", err.Error()))
}
logger.Info("Discord: Started successfully")
} else {
logger.Info("Discord: Disabled")

View File

@@ -0,0 +1,6 @@
BEGIN;
ALTER TABLE IF EXISTS public.users ADD COLUMN discord_token text;
ALTER TABLE IF EXISTS public.users ADD COLUMN discord_id text;
END;

View File

@@ -1,6 +1,7 @@
package channelserver
import (
"crypto/rand"
"encoding/hex"
"erupe-ce/common/byteframe"
"erupe-ce/common/mhfcourse"
@@ -322,6 +323,20 @@ func parseChatCommand(s *Session, command string) {
} else {
sendDisabledCommandMessage(s, commands["Teleport"])
}
case commands["Discord"].Prefix:
if commands["Discord"].Enabled {
var _token string
err := s.server.db.QueryRow(`SELECT discord_token FROM users u WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$1)`, s.charID).Scan(&_token)
if err != nil {
randToken := make([]byte, 4)
rand.Read(randToken)
_token = fmt.Sprintf("%x-%x", randToken[:2], randToken[2:])
s.server.db.Exec(`UPDATE users u SET discord_token = $1 WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$2)`, _token, s.charID)
}
sendServerChatMessage(s, fmt.Sprintf(s.server.dict["commandDiscordSuccess"], _token))
} else {
sendDisabledCommandMessage(s, commands["Discord"])
}
case commands["Help"].Prefix:
if commands["Help"].Enabled {
for _, command := range commands {

View File

@@ -3,6 +3,7 @@ package channelserver
import (
"fmt"
"github.com/bwmarrin/discordgo"
"golang.org/x/crypto/bcrypt"
"sort"
"strings"
"unicode"
@@ -66,10 +67,56 @@ func getCharacterList(s *Server) string {
return message
}
// onInteraction handles slash commands
func (s *Server) onInteraction(ds *discordgo.Session, i *discordgo.InteractionCreate) {
switch i.Interaction.ApplicationCommandData().Name {
case "link":
var temp string
err := s.db.QueryRow(`UPDATE users SET discord_id = $1 WHERE discord_token = $2 RETURNING discord_id`, i.Member.User.ID, i.ApplicationCommandData().Options[0].StringValue()).Scan(&temp)
if err == nil {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Your Erupe account was linked successfully.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
} else {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Failed to link Erupe account.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
case "password":
password, _ := bcrypt.GenerateFromPassword([]byte(i.ApplicationCommandData().Options[0].StringValue()), 10)
_, err := s.db.Exec(`UPDATE users SET password = $1 WHERE discord_id = $2`, password, i.Member.User.ID)
if err == nil {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Your Erupe account password has been updated.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
} else {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Failed to update Erupe account password.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
}
}
// onDiscordMessage handles receiving messages from discord and forwarding them ingame.
func (s *Server) onDiscordMessage(ds *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore messages from our bot, or ones that are not in the correct channel.
if m.Author.Bot || m.ChannelID != s.erupeConfig.Discord.RealtimeChannelID {
// Ignore messages from bots, or messages that are not in the correct channel.
if m.Author.Bot || m.ChannelID != s.erupeConfig.Discord.RelayChannel.RelayChannelID {
return
}
@@ -79,11 +126,24 @@ func (s *Server) onDiscordMessage(ds *discordgo.Session, m *discordgo.MessageCre
}
return r
}, m.Author.Username))
for i := 0; i < 8-len(m.Author.Username); i++ {
paddedName += " "
}
message := s.discordBot.NormalizeDiscordMessage(fmt.Sprintf("[D] %s > %s", paddedName, m.Content))
if len(message) > s.erupeConfig.Discord.RelayChannel.MaxMessageLength {
return
}
message := fmt.Sprintf("[D] %s > %s", paddedName, m.Content)
s.BroadcastChatMessage(s.discordBot.NormalizeDiscordMessage(message))
var messages []string
lineLength := 61
for i := 0; i < len(message); i += lineLength {
end := i + lineLength
if end > len(message) {
end = len(message)
}
messages = append(messages, message[i:end])
}
for i := range messages {
s.BroadcastChatMessage(messages[i])
}
}

View File

@@ -211,6 +211,7 @@ func (s *Server) Start() error {
// Start the discord bot for chat integration.
if s.erupeConfig.Discord.Enabled && s.discordBot != nil {
s.discordBot.Session.AddHandler(s.onDiscordMessage)
s.discordBot.Session.AddHandler(s.onInteraction)
}
return nil

View File

@@ -25,6 +25,8 @@ func getLangStrings(s *Server) map[string]string {
strings["commandPSNSuccess"] = "PSN「%s」が連携されています"
strings["commandPSNExists"] = "PSNは既存のユーザに接続されています"
strings["commandDiscordSuccess"] = "あなたのDiscordトークン%s"
strings["commandRaviNoCommand"] = "ラヴィコマンドが指定されていません"
strings["commandRaviStartSuccess"] = "大討伐を開始します"
strings["commandRaviStartError"] = "大討伐は既に開催されています"
@@ -78,6 +80,8 @@ func getLangStrings(s *Server) map[string]string {
strings["commandPSNSuccess"] = "Connected PSN ID: %s"
strings["commandPSNExists"] = "PSN ID is connected to another account!"
strings["commandDiscordSuccess"] = "Your Discord token: %s"
strings["commandRaviNoCommand"] = "No Raviente command specified!"
strings["commandRaviStartSuccess"] = "The Great Slaying will begin in a moment"
strings["commandRaviStartError"] = "The Great Slaying has already begun!"

View File

@@ -7,12 +7,39 @@ import (
"regexp"
)
var Commands = []*discordgo.ApplicationCommand{
{
Name: "link",
Description: "Link your Erupe account to Discord",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "token",
Description: "The token provided by the Discord command in-game",
Required: true,
},
},
},
{
Name: "password",
Description: "Change your Erupe account password",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "password",
Description: "Your new password",
Required: true,
},
},
},
}
type DiscordBot struct {
Session *discordgo.Session
config *_config.Config
logger *zap.Logger
MainGuild *discordgo.Guild
RealtimeChannel *discordgo.Channel
Session *discordgo.Session
config *_config.Config
logger *zap.Logger
MainGuild *discordgo.Guild
RelayChannel *discordgo.Channel
}
type Options struct {
@@ -28,18 +55,22 @@ func NewDiscordBot(options Options) (discordBot *DiscordBot, err error) {
return nil, err
}
realtimeChannel, err := session.Channel(options.Config.Discord.RealtimeChannelID)
var relayChannel *discordgo.Channel
if options.Config.Discord.RelayChannel.Enabled {
relayChannel, err = session.Channel(options.Config.Discord.RelayChannel.RelayChannelID)
}
if err != nil {
options.Logger.Fatal("Discord failed to create realtimeChannel", zap.Error(err))
options.Logger.Fatal("Discord failed to create relayChannel", zap.Error(err))
return nil, err
}
discordBot = &DiscordBot{
config: options.Config,
logger: options.Logger,
Session: session,
RealtimeChannel: realtimeChannel,
config: options.Config,
logger: options.Logger,
Session: session,
RelayChannel: relayChannel,
}
return
@@ -51,7 +82,7 @@ func (bot *DiscordBot) Start() (err error) {
return
}
// Replace all mentions to real name from the message.
// NormalizeDiscordMessage replaces all mentions to real name from the message.
func (bot *DiscordBot) NormalizeDiscordMessage(message string) string {
userRegex := regexp.MustCompile(`<@!?(\d{17,19})>`)
emojiRegex := regexp.MustCompile(`(?:<a?)?:(\w+):(?:\d{18}>)?`)
@@ -74,7 +105,11 @@ func (bot *DiscordBot) NormalizeDiscordMessage(message string) string {
}
func (bot *DiscordBot) RealtimeChannelSend(message string) (err error) {
_, err = bot.Session.ChannelMessageSend(bot.RealtimeChannel.ID, message)
if bot.RelayChannel == nil {
return
}
_, err = bot.Session.ChannelMessageSend(bot.RelayChannel.ID, message)
return
}