From 714093fd3479204edfc97b4afcdf2683ab199000 Mon Sep 17 00:00:00 2001 From: victormylle Date: Tue, 10 Nov 2020 00:11:52 +0100 Subject: [PATCH] Cleaned up some code + added redeem --- DiscordVerifier/src/Main.java | 10 ++++ .../src/RedeemCommandListeners.java | 51 +++++++++++++++++++ DiscordVerifier/src/plugin.yml | 6 ++- cogs/quiz.py | 37 ++++++++++---- data/DatabaseConnection.py | 45 +++++++++++----- 5 files changed, 125 insertions(+), 24 deletions(-) create mode 100644 DiscordVerifier/src/RedeemCommandListeners.java diff --git a/DiscordVerifier/src/Main.java b/DiscordVerifier/src/Main.java index e72bfef..f3c92e6 100755 --- a/DiscordVerifier/src/Main.java +++ b/DiscordVerifier/src/Main.java @@ -14,9 +14,12 @@ public class Main extends JavaPlugin { Thread serversocket; Thread uuidServerThread; + ServerSocket uuidServerSocket; ServerSocket chatServerSocket; + DatabaseConnection dbConn; + public void onEnable() { getLogger().info("DiscordVerifier Plugin enabled"); PluginManager pm = getServer().getPluginManager(); @@ -24,6 +27,13 @@ public class Main extends JavaPlugin { start_socketserver(); start_uuid_server(); + this.dbConn = new DatabaseConnection(); + + + RedeemCommandListeners redeemcommands = new RedeemCommandListeners(dbConn); + getCommand(redeemcommands.cmd1).setExecutor(redeemcommands); + + } public void start_uuid_server(){ diff --git a/DiscordVerifier/src/RedeemCommandListeners.java b/DiscordVerifier/src/RedeemCommandListeners.java new file mode 100644 index 0000000..50fda0d --- /dev/null +++ b/DiscordVerifier/src/RedeemCommandListeners.java @@ -0,0 +1,51 @@ +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; + +public class RedeemCommandListeners implements Listener, CommandExecutor { + + public String cmd1 = "redeem"; + private DatabaseConnection dbConn; + + public RedeemCommandListeners(DatabaseConnection dbConn){ + this.dbConn = dbConn; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ + + if(sender instanceof Player){ + if(cmd.getName().equalsIgnoreCase(cmd1)){ + Player p = ((Player)sender); + + String discordid = dbConn.get_discord_id(p); + if (discordid != null){ + int rewards = dbConn.get_reward(discordid); + if (rewards != -1){ + + dbConn.remove_toclaim(discordid); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "eco give " + p.getName() + rewards); + p.sendMessage("You received " + rewards + " dollars!"); + return true; + + }else{ + p.sendMessage("You have no money to claim!"); + } + }else{ + p.sendMessage("Your account is not linked with discord"); + } + + return true; + } + }else{ + sender.sendMessage("Only players can use this command!"); + return true; + } + + return false; + } + +} diff --git a/DiscordVerifier/src/plugin.yml b/DiscordVerifier/src/plugin.yml index 7eb3e50..ad77808 100755 --- a/DiscordVerifier/src/plugin.yml +++ b/DiscordVerifier/src/plugin.yml @@ -1,5 +1,9 @@ name: DiscordVerifier main: Main -version: 0.0.1 +version: 0.0.2 description: Verify Mincraftnames api-version: 1.13 +commands: + redeem: + usage: / + description: Redeems the money won in discord diff --git a/cogs/quiz.py b/cogs/quiz.py index 5086796..f87d668 100644 --- a/cogs/quiz.py +++ b/cogs/quiz.py @@ -18,6 +18,8 @@ class QuizQuestions(commands.Cog): if (f == "add"): if (len(args) == 2): await self.add_question(ctx, args[0], args[1]) + elif (len(args) == 3): + await self.add_question(ctx, args[0], args[1], args[2]) else: await ctx.send("Wrong amount of arguments") elif (f == "rm"): @@ -31,13 +33,13 @@ class QuizQuestions(commands.Cog): else: await ctx.send("Wrong amount of arguments") - async def add_question(self, ctx, q, a): + async def add_question(self, ctx, q, a, reward=50): try: quizdb = QuizDB() - q_id = quizdb.add_question(q, a) + q_id = quizdb.add_question(q, a, reward) await ctx.send("question id: " + str(q_id)) - except: - await ctx.send("Something went wrong") + # except: + # await ctx.send("Something went wrong") finally: quizdb.close() @@ -62,7 +64,7 @@ class QuizQuestions(commands.Cog): else: message = "" for q in questions: - message += f"id: {q[0]}, question: '{q[1]}', answer: '{q[2]}', used: {q[3]}\n" + message += f"id: {q[0]}, question: '{q[1]}', answer: '{q[2]}', reward: {q[3]}, used: {q[4]}\n" await ctx.send(message) except: await ctx.send("Something went wrong") @@ -123,18 +125,33 @@ class Quiz(commands.Cog): if message.content.lower() == self.question[2].lower(): self.in_progress = False - quiz_players_db = QuizPlayersDB() - quiz_players_db.player_won(message.author.id, 1) - - await message.channel.send(f"{message.author.mention} Won 🎉🎉") + userlinked = self.give_reward(message.author.id, self.question[3]) + if userlinked: + await message.channel.send(f"{message.author.mention} Won 🎉🎉") + else: + await message.channel.send(f"{message.author.mention} Won 🎉🎉! To claim? Link your minecraft account") def increment_asked_count(self, q_id): quizdb = QuizDB() quizdb.question_asked_increment(q_id) + quizdb.close() def get_random_question(self): quizdb = QuizDB() - return quizdb.get_random_question() + q = quizdb.get_random_question() + quizdb.close() + return q + + def give_reward(self, discordid, reward): + quiz_players_db = QuizPlayersDB() + quiz_players_db.player_won(discordid, reward) + quiz_players_db.close() + + + + + + diff --git a/data/DatabaseConnection.py b/data/DatabaseConnection.py index 3e8b88e..2aafd58 100755 --- a/data/DatabaseConnection.py +++ b/data/DatabaseConnection.py @@ -10,6 +10,8 @@ class PlayerNotLinked(Exception): pass class QuestionNotFound(Exception): pass +class PlayerNotFound(Exception): + pass class DatabaseConnection: # databases -> worldcraft and worldcraft_discord @@ -28,6 +30,13 @@ class DatabaseConnection: password="@fZQ6Uu3+U^WH1i2JNemgTC7", database=database ) + elif database == "s13_ecobridge": + self.mydb = mysql.connector.connect( + host="192.168.1.251", + user="u13_H9QOWK3I5x", + password="^K2HjsLeTtPTl9+Ek.Y21p7S", + database=database + ) self.cursor = self.mydb.cursor() @@ -41,9 +50,12 @@ class DatabaseConnection: self.mydb.close() class QuizPlayersDB: - def __init__(self): + def __init__(self, conn=None): self.tablename = "quizplayers" - self.discorddbconn = DatabaseConnection(database="worldcraft_discord") + if (conn is not None): + self.discorddbconn = conn + else: + self.discorddbconn = DatabaseConnection(database="worldcraft_discord") cursor = self.discorddbconn.get_cursor() cursor.execute("create table IF NOT EXISTS {} (discordid tinytext NOT NULL, wins int DEFAULT 0, rewards int DEFAULT 0, toclaim int DEFAULT 0)".format(self.tablename)) @@ -54,29 +66,32 @@ class QuizPlayersDB: res = cursor.fetchone() return res[0] == 1 + def player_won(self, discordid, reward): cursor = self.discorddbconn.get_cursor() if self.player_exists(discordid): - sql = f"UPDATE {self.tablename} SET wins = wins + 1, rewards = rewards + {str(reward)}, toclaim = toclaim + {str(reward)} WHERE id = {str(q_id)}" + sql = f"UPDATE {self.tablename} SET wins = wins + 1, rewards = rewards + {str(reward)}, toclaim = toclaim + {str(reward)} WHERE discordid = {str(discordid)}" cursor.execute(sql) else: - sql = f"INSERT INTO {self.tablename} (discordid, wins, rewards, toclaim) VALUES ({discordid}, 1, {reward}, {reward})" + sql = f"INSERT INTO {self.tablename} (discordid, wins, rewards, toclaim) VALUES ({str(discordid)}, 1, {reward}, {reward})" cursor.execute(sql) - self.discorddbconn.get_db().commit() + self.discorddbconn.get_db().commit() + + def close(self): + self.discorddbconn.close() class QuizDB: def __init__(self): self.tablename = "questions" self.discorddbconn = DatabaseConnection(database="worldcraft_discord") cursor = self.discorddbconn.get_cursor() - cursor.execute("create table IF NOT EXISTS {} (id int NOT NULL PRIMARY KEY AUTO_INCREMENT, question text NOT NULL, answer text NOT NULL, asked int DEFAULT 0)".format(self.tablename)) + cursor.execute("create table IF NOT EXISTS {} (id int NOT NULL PRIMARY KEY AUTO_INCREMENT, question text NOT NULL, answer text NOT NULL, reward int NOT NULL, asked int DEFAULT 0)".format(self.tablename)) - def add_question(self, question, answer): + def add_question(self, question, answer, reward): cursor = self.discorddbconn.get_cursor() - sql = "insert into {} (question, answer) VALUES (%s, %s)".format(self.tablename) - val = (question, answer) + sql = f"insert into {self.tablename} (question, answer, reward) VALUES ('{question}', '{answer}', {str(reward)})" try: - cursor.execute(sql, val) + cursor.execute(sql) self.discorddbconn.get_db().commit() return cursor.lastrowid except: @@ -124,8 +139,6 @@ class QuizDB: def close(self): self.discorddbconn.close() - - # this will save the uuid of the player and discord id class PlayerDBLinker: def __init__(self): @@ -154,6 +167,12 @@ class PlayerDBLinker: res = cursor.fetchone() return res[0] >= 1 + def get_minecraftUUID(self, discordid): + cursor = self.discorddbconn.get_cursor() + cursor.execute("select minecraftUUID from {} where discordid='{}'".format(self.tablename, discordid)) + res = cursor.fetchone() + return res[0] + def linkPlayer(self, minecraftUUID, discordid): cursor = self.discorddbconn.get_cursor() sql = "insert into {} (minecraftUUID, discordid) VALUES (%s, %s)".format(self.tablename) @@ -162,10 +181,10 @@ class PlayerDBLinker: try: cursor.execute(sql, val) self.discorddbconn.get_db().commit() + except: raise SQLInsertError() - def unlinkPlayer(self, minecraftname, discordid): # get uuid from server database -> check if in linkerdatabase serverdb_cursor = self.serverdbconn.get_cursor()