diff --git a/.gitignore b/.gitignore index 50dad15..4901c3a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ config.json .env .sqlite database.sqlite -temp.js \ No newline at end of file +temp.js +INTERACTION.txt \ No newline at end of file diff --git a/commands/buttonhandler.js b/commands/buttonhandler.js new file mode 100644 index 0000000..e69de29 diff --git a/commands/db/THREAD_INTERACTION.txt b/commands/db/THREAD_INTERACTION.txt new file mode 100644 index 0000000..5c0bc23 --- /dev/null +++ b/commands/db/THREAD_INTERACTION.txt @@ -0,0 +1,145 @@ +ButtonInteraction { + type: 'MESSAGE_COMPONENT', + id: '980052556908752936', + applicationId: '926551095352901632', + channelId: '980043678720614401', + guildId: '930148608400035860', + user: User { + id: '720349017829015633', + bot: false, + system: false, + flags: UserFlags { bitfield: 0 }, + username: 'ION6060', + discriminator: '4592', + avatar: null, + banner: undefined, + accentColor: undefined + }, + member: GuildMember { + guild: Guild { + id: '930148608400035860', + name: 'RPI Directory', + icon: '76aab371cf5393ee9ae56c7493c656d4', + features: [Array], + commands: [GuildApplicationCommandManager], + members: [GuildMemberManager], + channels: [GuildChannelManager], + bans: [GuildBanManager], + roles: [RoleManager], + presences: PresenceManager {}, + voiceStates: [VoiceStateManager], + stageInstances: [StageInstanceManager], + invites: [GuildInviteManager], + scheduledEvents: [GuildScheduledEventManager], + available: true, + shardId: 0, + splash: null, + banner: null, + description: null, + verificationLevel: 'NONE', + vanityURLCode: null, + nsfwLevel: 'DEFAULT', + discoverySplash: null, + memberCount: 7, + large: false, + premiumProgressBarEnabled: false, + applicationId: null, + afkTimeout: 300, + afkChannelId: null, + systemChannelId: null, + premiumTier: 'NONE', + premiumSubscriptionCount: 0, + explicitContentFilter: 'DISABLED', + mfaLevel: 'NONE', + joinedTimestamp: 1653652465633, + defaultMessageNotifications: 'ALL_MESSAGES', + systemChannelFlags: [SystemChannelFlags], + maximumMembers: 500000, + maximumPresences: null, + approximateMemberCount: null, + approximatePresenceCount: null, + vanityURLUses: null, + rulesChannelId: null, + publicUpdatesChannelId: null, + preferredLocale: 'en-US', + ownerId: '358402930191106049', + emojis: [GuildEmojiManager], + stickers: [GuildStickerManager] + }, + joinedTimestamp: 1653631941538, + premiumSinceTimestamp: null, + nickname: null, + pending: false, + communicationDisabledUntilTimestamp: null, + _roles: [ '946610800418762792' ], + user: User { + id: '720349017829015633', + bot: false, + system: false, + flags: [UserFlags], + username: 'ION6060', + discriminator: '4592', + avatar: null, + banner: undefined, + accentColor: undefined + }, + avatar: null + }, + version: 1, + memberPermissions: Permissions { bitfield: 1071698660929n }, + locale: 'en-US', + guildLocale: 'en-US', + message: Message { + channelId: '980043678720614401', + guildId: '930148608400035860', + id: '980043682298359819', + createdTimestamp: 1653731022191, + type: 'DEFAULT', + system: false, + content: 'Your turn <@720349017829015633>!', + author: ClientUser { + id: '926551095352901632', + bot: true, + system: false, + flags: [UserFlags], + username: 'ION Bot Tester', + discriminator: '3718', + avatar: '98ee8c72c6f7fef859e6815fe1592618', + banner: undefined, + accentColor: undefined, + verified: true, + mfaEnabled: false + }, + pinned: false, + tts: false, + nonce: null, + embeds: [], + components: [ [MessageActionRow] ], + attachments: Collection(0) [Map] {}, + stickers: Collection(0) [Map] {}, + editedTimestamp: null, + reactions: ReactionManager { message: [Circular *1] }, + mentions: MessageMentions { + everyone: false, + users: [Collection [Map]], + roles: Collection(0) [Map] {}, + _members: null, + _channels: null, + crosspostedChannels: Collection(0) [Map] {}, + repliedUser: null + }, + webhookId: null, + groupActivityApplication: null, + applicationId: null, + activity: null, + flags: MessageFlags { bitfield: 0 }, + reference: null, + interaction: null + }, + customId: '1', + componentType: 'BUTTON', + deferred: false, + ephemeral: null, + replied: false, + webhook: InteractionWebhook { id: '926551095352901632' } +} \ No newline at end of file diff --git a/commands/db/battle.js b/commands/db/battle.js index 24580d4..572f145 100644 --- a/commands/db/battle.js +++ b/commands/db/battle.js @@ -1,37 +1,75 @@ //@ts-check +const { STATE } = require('./econ'); + +/** + * Called by "attack" + */ +function attack_special() { + +} -function hpmp(message, command, dbo) { - if (command == 'hp') { - dbo.find({"hp": {$exists: true}}).toArray(function(err, doc) { - return message.reply(`You have ${String(doc[0].hp)} hp left!`); - }); - } else if (command == 'mp') { - dbo.find({"mp": {$exists: true}}).toArray(function(err, doc) { - return message.reply(`You have ${String(doc[0].hp)} mp left!`); - }); - } +function attack(user_dbo, other_dbo, bot, thread, command, mongouri, items) { + + postActionBar(thread, other_dbo); +} + + +/** + * Called by "item" + */ +function heal(user_dbo, bot, thread, command, mongouri, items) { + postActionBar(thread, user_dbo); +} + + +//Gets items by section/name, reacts with them to the message, when pressed, trigger a response +function item() { + throw 'THE "ITEM" COMMAND HAS NOT BEEN SET UP YET!'; +} + + +function cast() { + +} + + +function postActionBar(thread, user_dbo) { + const { MessageActionRow, MessageButton } = require('discord.js'); + const row = new MessageActionRow() + .addComponents( + new MessageButton() + .setCustomId('ATTACK') + .setLabel('ATTACK') + .setStyle('DANGER'), + new MessageButton() + .setCustomId('HEAL') + .setLabel('HEAL') + .setStyle('SUCCESS'), + new MessageButton() + .setCustomId('ITEMS') + .setLabel('ITEMS') + .setStyle('SECONDARY') + ); + + thread.send({ content: `Your turn <@${user_dbo.s.namespace.collection}>!`, components: [row] }); } +function handle(user_dbo, other_dbo, bot, thread, command, mongouri, items) { -//#region Exports -function verifyAndInitiate() { - -} - -function handle(user_dbo, other_dbo, bot, message, args, command, Discord, mongouri, items, xp_collection) { - if (command == 'hp' || command == 'mp') { - hpmp(message, command, user_dbo); - } else if (command == 'initiate') { - + if (command == 'initalize') { + postActionBar(thread, user_dbo); + } else if (command == 'attack') { + attack(user_dbo, other_dbo, bot, thread, command, mongouri, items); + } else if (command == 'items') { + item(); + } else if (command == 'heal') { + heal(); } // initiate(user_dbo, other_dbo, command, message); } -//#endregion - - -module.exports = { handle } \ No newline at end of file +module.exports = { handle } diff --git a/commands/db/econ.js b/commands/db/econ.js index 8f8081b..000f7b2 100644 --- a/commands/db/econ.js +++ b/commands/db/econ.js @@ -14,7 +14,8 @@ const BASE = { const STATE = { IDLE: 0, FIGHTING: 1, - PRONE: 2 + PRONE: 2, + WAITING: 3 } //Note that leveling up to the next level takes 10% more xp than the previous one diff --git a/commands/db/game.js b/commands/db/game.js index 84a3092..bdb9bc9 100644 --- a/commands/db/game.js +++ b/commands/db/game.js @@ -1,3 +1,5 @@ +// @ts-check + const { MongoClient, ServerApiVersion } = require('mongodb'); let ecoimport = require("./econ.js"); let battle = require("./battle.js"); @@ -15,85 +17,126 @@ const allGames = ['battle']; /** Adds the game type tag to the user(s) so the system can tell what game they're playing * @param other_dbo optional, include if the game has two players */ -function Initialize(user_dbo, command, message, other_dbo = null) { - user_dbo.find({"game": {$exists: true}}).toArray(function(err, docs){ - let doc = docs[0]; - if (allGames.indexOf(command) != -1) { - if (other_dbo != null) { - user_dbo.updateOne({ doc}, { $set: { game: command, opponent: other_dbo.s.namespace.collection }}); - other_dbo.updateOne({ game: null, opponent: null}, { $set: { game: command, opponent: user_dbo.s.namespace.collection }}); - } else { - user_dbo.updateOne(doc, { $set: { game: command }}); - } +async function Initialize(bot, user_dbo, command, message, first, second, other_dbo = null) { + return new Promise(async function(resolve, reject) { + user_dbo.find({"game": {$exists: true}}).toArray(function(err, docs){ + let doc = docs[0]; + if (allGames.indexOf(command) != -1) { + if (other_dbo != null) { + user_dbo.updateOne( { "game": {$exists: true} }, { $set: { game: command, opponent: other_dbo.s.namespace.collection, state: STATE.FIGHTING }}); + other_dbo.updateOne({ "game": {$exists: true} }, { $set: { game: command, opponent: user_dbo.s.namespace.collection, state: STATE.FIGHTING }}); + } else { + user_dbo.updateOne({ "game": {$exists: true} }, { $set: { game: command, state: STATE.FIGHTING }}); + } - } else { console.log(`ERROR! ${command} IS NOT A GAME!`); } + } else { message.reply(`ERROR! ${command} IS NOT A GAME!`); } + }); + + //Create a new thread for the game (maybe uneccesary???) - done before initialize + let name_first = await bot.users.cache.get(first); + let name_second = await bot.users.cache.get(second); + + // message.reply(`${first} [${name_first}], ${second} [${name_second}]`); throw 'ERR'; + const threadname = `${name_first.username} VS ${name_second.username} [${command.toUpperCase()}]`; + + const thread = await message.channel.threads.create({ + name: threadname, + // type: 'GUILD_PRIVATE_THREAD', + autoArchiveDuration: 60, + reason: `N/A`, + }); + + //Need lvl 2 boost for this + // thread.add(first); + // thread.add(second); + + message.channel.send(`<@${first}> and <@${second}> have started a game of ***${command.toUpperCase()}!***`); + + resolve(thread); }); - - let mentioned = message.mentions.users.keys(); - let second = mentioned.next().value; - message.reply(`<@${mentioned.next().value}> and <@${second}> have started a game of ***${command.toUpperCase()}!***`); } //#region game lose/win -function loseGame(user_dbo, xp_collection) { +function loseGame(user_dbo, xp_collection, message, bot = null) { + return new Promise(function(resolve, reject) { user_dbo.find({"game": {$exists: true}}).toArray(function(err, docs){ const doc = docs[0]; - - //Update the player's xp - user_dbo.updateOne(doc, { $set: { game: null, opponent: null, state: STATE.IDLE, xp: ecoimport.addxp(message, dbo, Math.ceil((BASE.XP * doc.rank)/2),xp_collection) }}); + if (doc == undefined) { return message.reply("Oops! There's been an error! Please contact support if this problem persists!"); } + if (doc.game == null) { return message.reply("You're not even in a game and you're trying to quit! Sad..."); } - //If remove some money (looting) [maybe implement a "friendly" game setting later with no looting] - let addbal = doc.rank * 2; - let diff = addbal; - if (doc.balance - addbal < 5) { addbal = addbal - doc.balance; } - if (doc.balance > 5) { - user_dbo.updateOne(doc, { $set: { balance: doc.balance - addbal}}); + //If this function was not called from "winGame", return + if (doc.opponent) { + //If remove some money (looting) [maybe implement a "friendly" game setting later with no looting] + var addbal = doc.rank * 2; + if (doc.balance - addbal < 5) { addbal = addbal - doc.balance; } + if (doc.balance > 5) { + user_dbo.updateOne(doc, { $set: { balance: doc.balance - addbal}}); + } } - user_dbo.updateOne(doc, { $set: { game: null, opponent: null, state: STATE.IDLE, xp: BASE.XP * doc.rank }}); - return addbal; + //Update the player's xp + ecoimport.addxp(message, user_dbo, Math.ceil((BASE.XP * doc.rank)/2),xp_collection) + user_dbo.updateOne({"game": {$exists: true}}, { $set: { game: null, opponent: null, state: STATE.IDLE }}); + + resolve(addbal); }); +}); } -function winGame(db, user_dbo, xp_collection) { + +function winGame(client, bot, db, user_dbo, xp_collection, message) { user_dbo.find({"game": {$exists: true}}).toArray(function(err, docs){ const doc = docs[0]; - //Update the player with xp - user_dbo.updateOne(doc, { $set: { game: null, opponent: null, state: STATE.IDLE, xp: doc.xp + (BASE.XP * doc.rank) }}); - //Check for an opponent if (doc.opponent != null) { let other = db.collection(doc.opponent); - let amt_taken = loseGame(other, xp_collection); - user_dbo.updateOne(doc, { $set: { balance: doc.balance + amt_taken}}); + let promise_temp = loseGame(other, xp_collection, message); + + promise_temp.then(function(result) { + var amt_taken = result; + user_dbo.updateOne({'balance': {$exists: true}}, { $set: { balance: doc.balance + amt_taken}}); + }); } + + //Delete the bot's record of the game + client.db('B|S' + bot.user.id).collection(user_dbo.s.namespace.db.substr(0, user_dbo.s.namespace.db.length - 6)).drop(); + + + //Update the player with xp + user_dbo.updateOne({"game": {$exists: true}}, { $set: { game: null, opponent: null, state: STATE.IDLE, xp: doc.xp + (BASE.XP * doc.rank) }}); }); } //#endregion +//replies to the message with current game specifics +function getGame(message, args, db) { + let id; + var temp; + + if (args.length == 1 && String(args[0]).startsWith('<')) { id = args[0].substr(2, args[0].length - 3)} + else { id = message.author.id; } + var user_dbo = db.collection(message.author.id); -function resetPlayer(db, user_dbo, message) { user_dbo.find({"game": {$exists: true}}).toArray(function(err, docs){ const doc = docs[0]; - - if (doc.game == null) { return message.reply("You're not even in a game and you're trying to quit! Sad..."); } - user_dbo.updateOne(doc, { $set: { game: null, opponent: null, state: STATE.IDLE }}); + if (doc.game == null) { + return message.reply(`<@${id}> is not currently playing a game!`); + } - let temp = `${message.author} has quit a game of ${doc.game}!`; + temp = `<@${id}> is currently playing "${doc.game}"`; if (doc.opponent != null) { - let other = db.collection(doc.opponent); - + temp += ` with <@${doc.opponent}>` } + message.reply(temp); }); } - -function acceptIsValid(other_discord, message, msg) { +function acceptIsValid(bot, other_discord, message, msg, tag_len) { if (other_discord == undefined) { message.reply("This is not a valid invite!"); @@ -104,14 +147,16 @@ function acceptIsValid(other_discord, message, msg) { let check0 = msg.author.bot; //Author - let check1 = other_discord.id == message.author.id; + let tag = msg.content.substr(2, tag_len); + let check1 = Number(tag) == Number(message.author.id); //Time (within the last 5 min) let prev = snowflake.convertSnowflakeToDate(msg.id); let now = snowflake.convertSnowflakeToDate(message.id); + // @ts-ignore let diff = now - prev; var minutes = Math.floor((diff/1000)/60); - let check2 = minutes <= 5; + let check2 = minutes <= 5 || bot.inDebugMode; if (!check0) { message.reply("really?"); } else if (!check1 && check2) { message.reply("_INVALID USER_"); } @@ -121,9 +166,42 @@ function acceptIsValid(other_discord, message, msg) { return (check0 && check1 && check2); } + +function hpmp(message, command, dbo) { + if (command == 'hp') { + dbo.find({"hp": {$exists: true}}).toArray(function(err, doc) { + return message.reply(`You have ${String(doc[0].hp)} hp left!`); + }); + } else if (command == 'mp') { + dbo.find({"mp": {$exists: true}}).toArray(function(err, doc) { + return message.reply(`You have ${String(doc[0].hp)} mp left!`); + }); + } +} + //#endregion +//#region GAME SPECIFIC +function in_game_redirector(bot, interaction, threadname, doc, client, mongouri, items) { + + //Maybe fix this later...... + let turn = doc.turn; + const user1 = doc[turn]; + const user2 = doc[Number(!turn)]; + const db = client.db(interaction.guildId + "[ECON]"); + const dbo = db.collection(user1); + const other = db.collection(user2); + const thread = interaction.channel; + + dbo.find({'game': {$exists: true}}).toArray(function (err, docs) { + const game = docs[0].game + switch (game) { + case 'battle': battle.handle(dbo, other, bot, thread, interaction.customId.toLowerCase(), mongouri, items); + } + }); +} + module.exports ={ name: "game", @@ -131,15 +209,21 @@ module.exports ={ async execute(bot, message, args, command, Discord, mongouri, items, xp_collection) { if (!bot.inDebugMode) { return message.reply("This command is currently in development!"); } - + + +//#region Setup const id = message.author.id; const server = message.guild.id; + // @ts-ignore const client = new MongoClient(mongouri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 }); if (client.writeConcern || client.writeConcern) { client.close(); return message.reply("Something went wrong with the database, please try again later and contact support if this problem persists!"); - } + } + + const botdb = client.db('B|S' + bot.user.id); + const serverinbotdb = botdb.collection(server); //Initialize if necessary ecoimport.CreateNewCollection(message, client, server, id); @@ -147,23 +231,28 @@ module.exports ={ //Check for a second person and create a second database entry if neccessary if (message.mentions.users.first() != undefined) { +//#TODO //FIX THIS (NOT THE RIGHT CLIENT 100% OF THE TIME!!!!!!!) ecoimport.CreateNewCollection(message, client, server, message.mentions.users.first().id); } +//#endregion + client.connect(err => { const db = client.db(String(server) + "[ECON]"); const dbo = db.collection(id); if (err) { return console.log(err); } //Check if the client is currently in a game and act accordingly - //#region Check Game +//#region Check Game dbo.find({"game": {$exists: true}}).toArray(async function(err, docs){ - if (err) { return console.log(error); } + if (err) { return console.log(err); } let doc = docs[0]; let game = null; if (doc) { game = doc.game; } - //#endregion +//#endregion +//#region non-game-specific commands + //For TWO+ PLAYER games only!!! if (command == 'accept') { //Handle the messages if (message.reference == null) { return message.reply("Please reply to a valid battle request message!"); } @@ -171,24 +260,72 @@ module.exports ={ let msg = await message.channel.messages.fetch(mid); //Check if the person actually challenged you + //Get the length of any user tag let mentioned = msg.mentions.users.keys(); - const other_discord = mentioned.next().value; - if (!acceptIsValid(other_discord, message, msg)) { return; } + let tag_len = String(mentioned.next().value).length; + + //<@tage_len>, <@ --2+tag_len+2+3 = 7+tag_len + let other_tag = msg.content.substr(7+tag_len, tag_len); + + const other_discord = msg.mentions.users.get(other_tag); + + //Should also check if the player is already playing a game!!! + if (!acceptIsValid(bot, other_discord, message, msg, tag_len)) { return; } //Get the opponent - const other = db.collection(other_discord); + const other = db.collection(other_discord.id); let startPos = msg.content.indexOf('"') + 1; let newCommand = msg.content.substr(startPos, msg.content.lastIndexOf('"') - startPos); + + //#region BOT SECTION + + //Store both IDs in the database (for turns) + let name_first = await bot.users.cache.get(id); + let name_second = await bot.users.cache.get(other_discord.id); + + // message.reply(`${first} [${name_first}], ${second} [${name_second}]`); throw 'ERR'; + const threadname = `${name_first.username} VS ${name_second.username} [${newCommand.toUpperCase()}]`; + var newObj = {0: id, 1: other_discord.id, turn: 0, thread: threadname}; + serverinbotdb.insertOne(newObj); + + //#endregion + + if (newCommand == 'battle') { - Initialize(dbo, newCommand, msg, other); - battle.handle(dbo, other, bot, message, args, 'initiate', Discord, mongouri, items, xp_collection); + const result = Initialize(bot, dbo, newCommand, msg, id, other_discord.id, other); + result.then(function (thread) { + battle.handle(dbo, other, bot, thread, 'initalize', mongouri, items); + }); } - } else { - if (command == 'quit') { - winGame(db, dbo, xp_collection); - } else if (game == 'battle' || command == 'battle') { + } else if (command == 'quit') { + + const channel = bot.channels.cache.get(message.channel.parentId); + //Remove the turn counter from the bot's database + serverinbotdb.deleteOne({0: id} || {1: id}); + if (doc.opponent != null) { + // let other = message.guild.members.cache.get(doc.opponent); + let other = db.collection(doc.opponent); + channel.send(`<@${message.author.id}> has quit a game of "${game}" with <@${doc.opponent}>!`); + winGame(client, bot, db, other, xp_collection, message); + } else { + loseGame(dbo, xp_collection, message, bot); + channel.send(`<@${message.author.id}> has quit a game of "${game}"!`); + } + + message.channel.delete(); + } + else if (command == 'status') { + getGame(message, args, db); + } else if (command == 'hp' || command == 'mp') { + hpmp(message, command, dbo); + } +//#endregion + +//#region game-specific commands + else { + if (game == 'battle' || command == 'battle') { //Handle sending the request and making sure the user exists here let other_discord = message.mentions.users.first(); if (other_discord == undefined) { @@ -204,10 +341,11 @@ module.exports ={ else { message.reply(`'!game ${command}' is not a command!`); } } } +//#endregion }); }); client.close(); - }, allGames + }, allGames, in_game_redirector } \ No newline at end of file diff --git a/commands/turnManager.js b/commands/turnManager.js new file mode 100644 index 0000000..c487410 --- /dev/null +++ b/commands/turnManager.js @@ -0,0 +1,49 @@ +//THESE STRUCTURES SUPPORTS TWO PLAYERS ONLY!!!! + + + +//Determines who's turn it currently is +function getTurn(client, bot, interaction) { + return new Promise(function(resolve, reject) { + + const db = client.db('B|S' + bot.user.id); + const dbo = db.collection(interaction.member.guild.id); + let id = interaction.user.id; + + //Check if you're in the right thread + // dbo.find({thread: {$exists: true}}).toArray(function(err, docs) { + // if (docs[0].thread) {} + // }); + + dbo.find({$or: [ {0: id}, {1: id} ]}).toArray(function(err, docs) { + if (err) { console.log(err); } + + const doc = docs[0]; + const turn = String(doc.turn); + +//#TODO Optimize this somehow......... + let currentuser; + for (const [key, value] of Object.entries(doc)) { + if (key == turn) { currentuser = value; break; } + } + + //Return statement? + // throw "NO"; + resolve([currentuser, doc]); + }); + }); +} + + +function changeTurn(client, bot, interaction) { + const db = client.db('B|S' + bot.user.id); + const dbo = db.collection(interaction.member.guild.id); + dbo.find({turn: {$exists: true}}).toArray(function (err, docs) { + let turn = docs[0].turn; + turn = Number(!turn); + dbo.updateOne(docs[0], {$set: {turn: turn}}); + }); +} + + +module.exports = { getTurn, changeTurn } \ No newline at end of file diff --git a/main.js b/main.js index 009a8e2..3273270 100644 --- a/main.js +++ b/main.js @@ -2,6 +2,7 @@ const { Client, Intents, Permissions } = require('discord.js'); const Discord = require('discord.js'); const { MongoClient, ServerApiVersion } = require('mongodb'); const fs = require('fs'); +const turnManager = require('./commands/turnManager.js'); const { exit } = require('process'); const BASE_LVL_XP = 20; @@ -52,9 +53,9 @@ const { connect } = require('mongoose'); bot.on("guildCreate", guild => { guild.members.fetch guild.roles.create({ name: 'Selmer Bot Mod' }); - + const role = guild.roles.cache.find((role) => role.name === 'Selmer Bot Mod'); // member.roles.cache.has('role-id-here'); - let owner = guild.members.fetch(guild.ownerID); + let owner = guild.members.cache.fetch(guild.ownerID); owner.send('Thank you for adding Selmer Bot to your server!\nPlease give people you want to have access to Selmer Bot\'s restricted commands the <@&' + role + '> role.'); }); @@ -83,6 +84,7 @@ fs.readdirSync('./commands') //Set these two manually because all the seperate games can't be included in the command list (all managed by the 'game' file) let temp_command = require("./commands/db/econ.js"); +const { STATE } = require('./commands/db/econ.js'); bot.commands.set('econ', temp_command); temp_command = require('./commands/db/game.js'); bot.commands.set('game', temp_command); @@ -133,9 +135,40 @@ bot.on('ready', async () => { //Button Section -bot.on('interactionCreate', interaction => { +bot.on('interactionCreate', async interaction => { if (!interaction.isButton()) return; - console.log(interaction); + + const client = new MongoClient(mongouri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 }); + client.connect(err => { + let current_user = turnManager.getTurn(client, bot, interaction); + + current_user.then(function (result) { + const id = result[0]; + const doc = result[1]; + const threadname = doc.thread; + const dbo = client.db(interaction.guildId + '[ECON]').collection(id); + dbo.find({ 'state': {$exists: true} }).toArray(async function (err, docs) { + if (interaction.user.id == id) { + await interaction.deferReply(); + + //Check State + if (docs[0].state == STATE.FIGHTING) { + //Do turn stuff + bot.commands.get('game').in_game_redirector(bot, interaction, threadname, doc, client, mongouri, items); + } + + turnManager.changeTurn(client, bot, interaction); + + //remove the old interation message + interaction.message.delete(); + + interaction.editReply(`<@${interaction.user.id}> used _${interaction.customId.toLowerCase()}_!`); + } else { + console.log("It's not your turn!"); + } + }); + }); + }); }); @@ -156,7 +189,7 @@ bot.on('messageCreate', (message) => { else if(bot.commands.has(command) && command != 'ECON') { //Database access is required, change the inputs if (command == 'game' || command == 'accept') { - bot.commands.get(command).execute(bot, message, args, command, Discord, mongouri, items, xp_collection) + bot.commands.get(command).execute(bot, message, args, command, Discord, mongouri, items, xp_collection); } else { bot.commands.get(command).execute(message, args, Discord, Client, bot); }