From aa5392b70be4f9f69ffaf50dfd997f921a519aaa Mon Sep 17 00:00:00 2001 From: victormylle Date: Wed, 30 Sep 2020 13:32:23 +0200 Subject: [PATCH 1/9] Started creating server plugin --- .gitignore | 2 ++ DiscordVerifier/.DS_Store | Bin 0 -> 6148 bytes DiscordVerifier/DiscordVerifier.iml | 12 ++++++++ DiscordVerifier/src/Main.java | 43 ++++++++++++++++++++++++++++ DiscordVerifier/src/plugin.yml | 5 ++++ sockettest.py | 12 ++++++++ 6 files changed, 74 insertions(+) create mode 100644 DiscordVerifier/.DS_Store create mode 100644 DiscordVerifier/DiscordVerifier.iml create mode 100644 DiscordVerifier/src/Main.java create mode 100644 DiscordVerifier/src/plugin.yml create mode 100644 sockettest.py diff --git a/.gitignore b/.gitignore index 1febf6c..b3dd952 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea/ __pycache__ +DiscordVerifier/out +local.db diff --git a/DiscordVerifier/.DS_Store b/DiscordVerifier/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..ba90b33c94741cd328969864440d5c8a7b4f1966 GIT binary patch literal 6148 zcmeHK%}T>S5Z-O8ZYyFBf*$wct%ufMJP4uIgEt|f2Ng|B(Ll^flUlS^@*4U^K7p^} z%k^(2Ut8JPWMXJ)E=@H%aVO&gF$2uNZyCV* zL4zWCgoQ(Ub--X-06_eVv;sEv5}2b2J;K5vtbjM`nN-_{u=pP3u_ycYp5xzb5gF8DIt`iUC>a_?|q<~>dF~njiUIMiOevJm8M_4!n4+wta>2L6 + + + + + + + + + + + \ No newline at end of file diff --git a/DiscordVerifier/src/Main.java b/DiscordVerifier/src/Main.java new file mode 100644 index 0000000..c25a687 --- /dev/null +++ b/DiscordVerifier/src/Main.java @@ -0,0 +1,43 @@ +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; + +public class Main extends JavaPlugin { + + public void onEnable() { + getLogger().info("DiscordVerifier Plugin enabled"); + PluginManager pm = getServer().getPluginManager(); + + try{ + ServerSocket ss = new ServerSocket(3333); + while (true) { + Socket s = ss.accept(); + PrintWriter out = + new PrintWriter(s.getOutputStream(), true); + BufferedReader in = new BufferedReader( + new InputStreamReader(s.getInputStream())); + String inputLine, outputLine; + inputLine = in.readLine(); + if (inputLine != null) { + outputLine = "test succeeded"; + out.println(outputLine); + System.out.println("message: " + inputLine); + } + } + + } catch (Exception e) { + System.out.println("error man"); + System.out.println(e); + } + } + + public void onDisable() { + getLogger().info("Plugin disabled"); + } + + + +} diff --git a/DiscordVerifier/src/plugin.yml b/DiscordVerifier/src/plugin.yml new file mode 100644 index 0000000..7eb3e50 --- /dev/null +++ b/DiscordVerifier/src/plugin.yml @@ -0,0 +1,5 @@ +name: DiscordVerifier +main: Main +version: 0.0.1 +description: Verify Mincraftnames +api-version: 1.13 diff --git a/sockettest.py b/sockettest.py new file mode 100644 index 0000000..75448fa --- /dev/null +++ b/sockettest.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 + +import socket + +HOST = '127.0.0.1' # The server's hostname or IP address +PORT = 3333 # The port used by the server + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.connect((HOST, PORT)) + s.sendall(b'Pieter suckt\n') + data = s.recv(1024) + print('Received', repr(data)) From f7bd9e32319d184c2b104a625840ff40a0e9f5a3 Mon Sep 17 00:00:00 2001 From: victormylle Date: Thu, 1 Oct 2020 00:41:02 +0200 Subject: [PATCH 2/9] Updated the server plugin --- DiscordVerifier/.DS_Store | Bin DiscordVerifier/DiscordVerifier.iml | 0 DiscordVerifier/src/Main.java | 56 ++++++++++++++++++---------- DiscordVerifier/src/plugin.yml | 0 README.md | 0 bot.py | 0 cogs/modcommands.py | 0 cogs/servertatus.py | 0 data/constants.py | 0 files/images/server_icon.png | Bin functions/checks.py | 0 sockettest.py | 0 12 files changed, 36 insertions(+), 20 deletions(-) mode change 100644 => 100755 DiscordVerifier/.DS_Store mode change 100644 => 100755 DiscordVerifier/DiscordVerifier.iml mode change 100644 => 100755 DiscordVerifier/src/Main.java mode change 100644 => 100755 DiscordVerifier/src/plugin.yml mode change 100644 => 100755 README.md mode change 100644 => 100755 bot.py mode change 100644 => 100755 cogs/modcommands.py mode change 100644 => 100755 cogs/servertatus.py mode change 100644 => 100755 data/constants.py mode change 100644 => 100755 files/images/server_icon.png mode change 100644 => 100755 functions/checks.py mode change 100644 => 100755 sockettest.py diff --git a/DiscordVerifier/.DS_Store b/DiscordVerifier/.DS_Store old mode 100644 new mode 100755 diff --git a/DiscordVerifier/DiscordVerifier.iml b/DiscordVerifier/DiscordVerifier.iml old mode 100644 new mode 100755 diff --git a/DiscordVerifier/src/Main.java b/DiscordVerifier/src/Main.java old mode 100644 new mode 100755 index c25a687..fc455c8 --- a/DiscordVerifier/src/Main.java +++ b/DiscordVerifier/src/Main.java @@ -1,3 +1,4 @@ +import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -11,27 +12,42 @@ public class Main extends JavaPlugin { getLogger().info("DiscordVerifier Plugin enabled"); PluginManager pm = getServer().getPluginManager(); - try{ - ServerSocket ss = new ServerSocket(3333); - while (true) { - Socket s = ss.accept(); - PrintWriter out = - new PrintWriter(s.getOutputStream(), true); - BufferedReader in = new BufferedReader( - new InputStreamReader(s.getInputStream())); - String inputLine, outputLine; - inputLine = in.readLine(); - if (inputLine != null) { - outputLine = "test succeeded"; - out.println(outputLine); - System.out.println("message: " + inputLine); - } - } + start_socketserver(); - } catch (Exception e) { - System.out.println("error man"); - System.out.println(e); - } + } + + public void start_socketserver() { + new Thread(() -> { + try{ + ServerSocket ss = new ServerSocket(3333); + while (true) { + Socket s = ss.accept(); + PrintWriter out = + new PrintWriter(s.getOutputStream(), true); + BufferedReader in = new BufferedReader( + new InputStreamReader(s.getInputStream())); + String inputLine, outputLine; + inputLine = in.readLine(); + if (inputLine != null) { + outputLine = "test succeeded"; + out.println(outputLine); + System.out.println("message: " + inputLine); + String[] info = inputLine.split("\t"); + Player player = getServer().getPlayer(info[0]); + String code = info[1]; + + send_chat(player, code); + } + } + + } catch (Exception e) { + System.out.println(e); + } + }).start(); + } + + public void send_chat(Player player, String code){ + player.sendMessage(code); } public void onDisable() { diff --git a/DiscordVerifier/src/plugin.yml b/DiscordVerifier/src/plugin.yml old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/bot.py b/bot.py old mode 100644 new mode 100755 diff --git a/cogs/modcommands.py b/cogs/modcommands.py old mode 100644 new mode 100755 diff --git a/cogs/servertatus.py b/cogs/servertatus.py old mode 100644 new mode 100755 diff --git a/data/constants.py b/data/constants.py old mode 100644 new mode 100755 diff --git a/files/images/server_icon.png b/files/images/server_icon.png old mode 100644 new mode 100755 diff --git a/functions/checks.py b/functions/checks.py old mode 100644 new mode 100755 diff --git a/sockettest.py b/sockettest.py old mode 100644 new mode 100755 From 412fc618102cb9bb644442e3c999b378710b045c Mon Sep 17 00:00:00 2001 From: victormylle Date: Thu, 1 Oct 2020 01:26:02 +0200 Subject: [PATCH 3/9] added some error handling --- DiscordVerifier/src/Main.java | 15 +++++---- cogs/playerlink.py | 60 +++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 6 deletions(-) create mode 100644 cogs/playerlink.py diff --git a/DiscordVerifier/src/Main.java b/DiscordVerifier/src/Main.java index fc455c8..7f17317 100755 --- a/DiscordVerifier/src/Main.java +++ b/DiscordVerifier/src/Main.java @@ -26,17 +26,20 @@ public class Main extends JavaPlugin { new PrintWriter(s.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(s.getInputStream())); - String inputLine, outputLine; + String inputLine; inputLine = in.readLine(); if (inputLine != null) { - outputLine = "test succeeded"; - out.println(outputLine); + System.out.println("message: " + inputLine); String[] info = inputLine.split("\t"); Player player = getServer().getPlayer(info[0]); - String code = info[1]; - - send_chat(player, code); + if (player == null){ + out.println("PlayerError"); + }else { + out.println("success"); + String code = info[1]; + send_chat(player, code); + } } } diff --git a/cogs/playerlink.py b/cogs/playerlink.py new file mode 100644 index 0000000..e6d883a --- /dev/null +++ b/cogs/playerlink.py @@ -0,0 +1,60 @@ +import discord +from discord.ext import commands +import random +import string +import socket + +def get_random_string(length): + # Random string with the combination of lower and upper case + letters = string.ascii_letters + "0123456789" + result_str = ''.join(random.choice(letters) for i in range(length)) + return result_str + +class PlayerError(Exception): + pass + +def send_chat(minecraftname, code): + HOST = '127.0.0.1' # The server's hostname or IP address + PORT = 3333 # The port used by the server + + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.connect((HOST, PORT)) + s.send(bytes("{}\t{}\n".format(minecraftname, code), encoding="ascii")) + data = s.recv(1024) + data_string = data.decode("utf-8").strip('\n') + if data_string == "PlayerError": + raise PlayerError() + return True + +class PlayerLink(commands.Cog): + def __init__(self, client): + self.client = client + + @commands.command(name="Link") + async def link(self, ctx, arg): + + channelid = ctx.channel.id + authorid = ctx.author.id + code = get_random_string(8) + + def check(message: discord.Message): + return message.channel.id == channelid and message.author.id == authorid + + try: + if send_chat(arg, code): + await ctx.send("A code has been sent to your minecraft chat in the WorldCraft server.\nSend it in this channel.") + msg = await self.client.wait_for('message', check=check) + if msg.content == code: + await ctx.send("The link was successfull") + else: + await ctx.send("Wrong code") + + except PlayerError: + await ctx.send("Player '" + arg + "' not found") + except: + await ctx.send("Something went wrong") + + + +def setup(client): + client.add_cog(PlayerLink(client)) From e50f56a7e2ea3f56e61d8fc25cfeddce88015ad1 Mon Sep 17 00:00:00 2001 From: victormylle Date: Thu, 1 Oct 2020 19:10:45 +0200 Subject: [PATCH 4/9] Added linked role and unlink method --- DiscordVerifier/src/Main.java | 20 +++++++++++++------- cogs/playerlink.py | 28 +++++++++++++++++++--------- data/constants.py | 6 ++++++ 3 files changed, 38 insertions(+), 16 deletions(-) diff --git a/DiscordVerifier/src/Main.java b/DiscordVerifier/src/Main.java index 7f17317..228a4e5 100755 --- a/DiscordVerifier/src/Main.java +++ b/DiscordVerifier/src/Main.java @@ -8,6 +8,8 @@ import java.net.Socket; public class Main extends JavaPlugin { + Thread serversocket; + public void onEnable() { getLogger().info("DiscordVerifier Plugin enabled"); PluginManager pm = getServer().getPluginManager(); @@ -17,7 +19,7 @@ public class Main extends JavaPlugin { } public void start_socketserver() { - new Thread(() -> { + serversocket = new Thread(() -> { try{ ServerSocket ss = new ServerSocket(3333); while (true) { @@ -32,13 +34,14 @@ public class Main extends JavaPlugin { System.out.println("message: " + inputLine); String[] info = inputLine.split("\t"); - Player player = getServer().getPlayer(info[0]); + String discordname = info[0]; + Player player = getServer().getPlayer(info[1]); if (player == null){ out.println("PlayerError"); }else { out.println("success"); - String code = info[1]; - send_chat(player, code); + String code = info[2]; + send_chat(discordname, player, code); } } } @@ -46,14 +49,17 @@ public class Main extends JavaPlugin { } catch (Exception e) { System.out.println(e); } - }).start(); + }); + + serversocket.start(); } - public void send_chat(Player player, String code){ - player.sendMessage(code); + public void send_chat(String discordname, Player player, String code){ + player.sendMessage(discordname + " wants to link your account\nEnter this code in discord: " + code); } public void onDisable() { + serversocket.stop(); getLogger().info("Plugin disabled"); } diff --git a/cogs/playerlink.py b/cogs/playerlink.py index e6d883a..0ef7292 100644 --- a/cogs/playerlink.py +++ b/cogs/playerlink.py @@ -3,6 +3,7 @@ from discord.ext import commands import random import string import socket +from data import constants def get_random_string(length): # Random string with the combination of lower and upper case @@ -13,13 +14,13 @@ def get_random_string(length): class PlayerError(Exception): pass -def send_chat(minecraftname, code): +def send_chat(discordname, minecraftname, code): HOST = '127.0.0.1' # The server's hostname or IP address PORT = 3333 # The port used by the server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) - s.send(bytes("{}\t{}\n".format(minecraftname, code), encoding="ascii")) + s.send(bytes("{}\t{}\t{}\n".format(discordname, minecraftname, code), encoding="ascii")) data = s.recv(1024) data_string = data.decode("utf-8").strip('\n') if data_string == "PlayerError": @@ -30,6 +31,10 @@ class PlayerLink(commands.Cog): def __init__(self, client): self.client = client + def get_linked_role(self): + return discord.utils.get(self.client.get_guild(constants.WorldCraft).roles, id=constants.roleLinked) + + @commands.command(name="Link") async def link(self, ctx, arg): @@ -41,19 +46,24 @@ class PlayerLink(commands.Cog): return message.channel.id == channelid and message.author.id == authorid try: - if send_chat(arg, code): - await ctx.send("A code has been sent to your minecraft chat in the WorldCraft server.\nSend it in this channel.") - msg = await self.client.wait_for('message', check=check) - if msg.content == code: - await ctx.send("The link was successfull") - else: - await ctx.send("Wrong code") + send_chat(ctx.author.name, arg, code) + await ctx.send("A code has been sent to your minecraft chat in the WorldCraft server.\nSend it in this channel.") + msg = await self.client.wait_for('message', check=check) + if msg.content == code: + await ctx.author.add_roles(self.get_linked_role()) + await ctx.send("The link was successfull") + else: + await ctx.send("Wrong code") except PlayerError: await ctx.send("Player '" + arg + "' not found") except: await ctx.send("Something went wrong") + @commands.command(name="Unlink") + async def unlink(self, ctx): + await ctx.author.remove_roles(self.get_linked_role()) + await ctx.send("Unlinked your account") def setup(client): diff --git a/data/constants.py b/data/constants.py index b143685..b9e55e9 100755 --- a/data/constants.py +++ b/data/constants.py @@ -9,5 +9,11 @@ roleAdmin = 730709756125249588 roleMod = 688328855605346339 roleOwner = 687996070986383436 +# User roles +roleLinked = 730709907275382904 # given when minecraft account is connected with discord account + +# Guild id +WorldCraft = 683422015394545665 + adminRoles = [roleAdmin, roleOwner] modPlusRoles = [roleAdmin, roleMod, roleOwner] From 8ec382c3d6587faea96c1b9b66aa24f1d9de91ac Mon Sep 17 00:00:00 2001 From: victormylle Date: Fri, 2 Oct 2020 22:33:27 +0200 Subject: [PATCH 5/9] Created embed message and added timer --- cogs/playerlink.py | 65 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/cogs/playerlink.py b/cogs/playerlink.py index 0ef7292..6eb6091 100644 --- a/cogs/playerlink.py +++ b/cogs/playerlink.py @@ -3,6 +3,8 @@ from discord.ext import commands import random import string import socket +import asyncio +import threading from data import constants def get_random_string(length): @@ -13,6 +15,8 @@ def get_random_string(length): class PlayerError(Exception): pass +class WrongCodeError(Exception): + pass def send_chat(discordname, minecraftname, code): HOST = '127.0.0.1' # The server's hostname or IP address @@ -45,26 +49,77 @@ class PlayerLink(commands.Cog): def check(message: discord.Message): return message.channel.id == channelid and message.author.id == authorid + def create_embed(discord_author, minecraftname, timer, error=None, success=False): + embed = discord.Embed(title="WorldCraft Linker") + embed.add_field(name="How to:", value= "A code has been sent to your minecraft chat in the WorldCraft server.\nSend the code in this channel.") + embed.add_field(name="Minecraft Name:", value=f"{minecraftname}", inline=False) + embed.add_field(name="Discord Name:", value=f"{discord_author.mention}", inline=False) + + if isinstance(error, WrongCodeError): + embed.add_field(name="Error", value=f"The code is wrong!", inline=False) + embed.colour = discord.Colour.red() + elif (timer.minutes == 0 and timer.seconds == 0 and timer.ended): + embed.add_field(name="Timer", value=f"The code is expired!", inline=False) + embed.colour = discord.Colour.red() + elif (success == True): + embed.add_field(name="Success", value=f"The link was successfull!", inline=False) + embed.colour = discord.Colour.green() + else: + embed.add_field(name="Timer", value=f"The code will expire in {str(timer.minutes).zfill(2)}:{str(timer.seconds).zfill(2)}", inline=False) + embed.colour = discord.Colour.orange() + return embed + + async def update_timer(timer, message): + while (not timer.ended): + await asyncio.sleep(1) + timer.update() + await message.edit(embed=create_embed(ctx.author, arg, timer)) + try: send_chat(ctx.author.name, arg, code) - await ctx.send("A code has been sent to your minecraft chat in the WorldCraft server.\nSend it in this channel.") + timer = Timer() + message = await ctx.send(embed=create_embed(ctx.author, arg, timer)) + + # Start timer in background + task = asyncio.create_task(update_timer(timer, message)) + msg = await self.client.wait_for('message', check=check) + if msg.content == code: await ctx.author.add_roles(self.get_linked_role()) - await ctx.send("The link was successfull") + timer.ended = True + await message.edit(embed=create_embed(ctx.author, arg, timer, success=True)) else: - await ctx.send("Wrong code") + # this stops the timer loop + task.cancel() + timer.ended = True + await message.edit(embed=create_embed(ctx.author, arg, timer, WrongCodeError())) except PlayerError: await ctx.send("Player '" + arg + "' not found") - except: - await ctx.send("Something went wrong") + #except: + # await ctx.send("Something went wrong") @commands.command(name="Unlink") async def unlink(self, ctx): await ctx.author.remove_roles(self.get_linked_role()) await ctx.send("Unlinked your account") +class Timer(): + def __init__(self): + self.minutes = 2 + self.seconds = 0 + self.ended = False + + def update(self): + if (self.minutes > 0 and self.seconds == 0): + self.minutes -= 1 + self.seconds = 59 + elif (self.seconds > 0): + self.seconds -= 1 + if (self.minutes == 0 and self.seconds == 0): + self.ended = True + def setup(client): client.add_cog(PlayerLink(client)) From eef4a06c93a5eeb970c92d6228fb891906210a1a Mon Sep 17 00:00:00 2001 From: victormylle Date: Fri, 2 Oct 2020 22:38:18 +0200 Subject: [PATCH 6/9] Small changes --- cogs/playerlink.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cogs/playerlink.py b/cogs/playerlink.py index 6eb6091..7372b1a 100644 --- a/cogs/playerlink.py +++ b/cogs/playerlink.py @@ -49,6 +49,7 @@ class PlayerLink(commands.Cog): def check(message: discord.Message): return message.channel.id == channelid and message.author.id == authorid + # creates the embed for the link message def create_embed(discord_author, minecraftname, timer, error=None, success=False): embed = discord.Embed(title="WorldCraft Linker") embed.add_field(name="How to:", value= "A code has been sent to your minecraft chat in the WorldCraft server.\nSend the code in this channel.") @@ -58,7 +59,7 @@ class PlayerLink(commands.Cog): if isinstance(error, WrongCodeError): embed.add_field(name="Error", value=f"The code is wrong!", inline=False) embed.colour = discord.Colour.red() - elif (timer.minutes == 0 and timer.seconds == 0 and timer.ended): + elif (timer.ended): embed.add_field(name="Timer", value=f"The code is expired!", inline=False) embed.colour = discord.Colour.red() elif (success == True): @@ -73,6 +74,8 @@ class PlayerLink(commands.Cog): while (not timer.ended): await asyncio.sleep(1) timer.update() + # maybe create a task from this because this takes some time -> timer not accurate + # asyncio.create_task(message........) await message.edit(embed=create_embed(ctx.author, arg, timer)) try: @@ -83,6 +86,7 @@ class PlayerLink(commands.Cog): # Start timer in background task = asyncio.create_task(update_timer(timer, message)) + # Wait for the code response msg = await self.client.wait_for('message', check=check) if msg.content == code: @@ -90,7 +94,7 @@ class PlayerLink(commands.Cog): timer.ended = True await message.edit(embed=create_embed(ctx.author, arg, timer, success=True)) else: - # this stops the timer loop + # this stops the timer task task.cancel() timer.ended = True await message.edit(embed=create_embed(ctx.author, arg, timer, WrongCodeError())) From 72a54ff4024d5d19445992e4128062ee24f6d4d6 Mon Sep 17 00:00:00 2001 From: victormylle Date: Sat, 10 Oct 2020 15:13:48 +0200 Subject: [PATCH 7/9] some little changes --- cogs/playerlink.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/cogs/playerlink.py b/cogs/playerlink.py index 7372b1a..fc2663e 100644 --- a/cogs/playerlink.py +++ b/cogs/playerlink.py @@ -65,6 +65,12 @@ class PlayerLink(commands.Cog): elif (success == True): embed.add_field(name="Success", value=f"The link was successfull!", inline=False) embed.colour = discord.Colour.green() + elif (timer.minutes == 2): + embed.add_field(name="Timer", value=f"The code will expire in { str(timer.minutes)} minutes", inline=False) + embed.colour = discord.Colour.orange() + elif (timer.minutes < 2): + embed.add_field(name="Timer", value=f"The code will expire in less than { str(timer.minutes + 1)} {'minutes' if timer.minutes + 1 > 1 else 'minute'}", inline=False) + embed.colour = discord.Colour.orange() else: embed.add_field(name="Timer", value=f"The code will expire in {str(timer.minutes).zfill(2)}:{str(timer.seconds).zfill(2)}", inline=False) embed.colour = discord.Colour.orange() @@ -75,11 +81,13 @@ class PlayerLink(commands.Cog): await asyncio.sleep(1) timer.update() # maybe create a task from this because this takes some time -> timer not accurate - # asyncio.create_task(message........) - await message.edit(embed=create_embed(ctx.author, arg, timer)) + if ((timer.minutes < 2 and timer.seconds == 59) or (timer.minutes == 0 and timer.seconds == 0)): + asyncio.create_task(message.edit(embed=create_embed(ctx.author, arg, timer))) + try: send_chat(ctx.author.name, arg, code) + #message_send_time = timer = Timer() message = await ctx.send(embed=create_embed(ctx.author, arg, timer)) From a4d8abf48c9d769d4cbc7b58e254721491807d37 Mon Sep 17 00:00:00 2001 From: victormylle Date: Thu, 22 Oct 2020 22:39:56 +0200 Subject: [PATCH 8/9] Added unlink support --- DiscordVerifier/src/Main.java | 54 ++++++++++++++++++++++++++-- cogs/playerlink.py | 68 ++++++++++++++++++++++++++++------- requirements.txt | 1 + 3 files changed, 109 insertions(+), 14 deletions(-) mode change 100644 => 100755 cogs/playerlink.py diff --git a/DiscordVerifier/src/Main.java b/DiscordVerifier/src/Main.java index 228a4e5..e72bfef 100755 --- a/DiscordVerifier/src/Main.java +++ b/DiscordVerifier/src/Main.java @@ -1,3 +1,6 @@ +// 25216 --> uuid server +// 25224 --> send chat server + import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -5,25 +8,65 @@ import org.bukkit.plugin.java.JavaPlugin; import java.io.*; import java.net.ServerSocket; import java.net.Socket; +import java.util.UUID; public class Main extends JavaPlugin { Thread serversocket; + Thread uuidServerThread; + ServerSocket uuidServerSocket; + ServerSocket chatServerSocket; public void onEnable() { getLogger().info("DiscordVerifier Plugin enabled"); PluginManager pm = getServer().getPluginManager(); start_socketserver(); + start_uuid_server(); } + public void start_uuid_server(){ + uuidServerThread = new Thread(() -> { + try{ + uuidServerSocket = new ServerSocket(25216); + while (true) { + Socket s = uuidServerSocket.accept(); + PrintWriter out = + new PrintWriter(s.getOutputStream(), true); + BufferedReader in = new BufferedReader( + new InputStreamReader(s.getInputStream())); + String inputLine; + inputLine = in.readLine(); + if (inputLine != null) { + System.out.println("minecraftname: " + inputLine); + Player player = getServer().getPlayer(inputLine); + if (player == null){ + out.println("PlayerError"); + }else { + System.out.println(player.getUniqueId().toString()); + UUID uuid = player.getUniqueId(); + out.println(uuid.toString()); + + } + } + } + + } catch (Exception e) { + System.out.println(e); + } + }); + + uuidServerThread.start(); + } + + public void start_socketserver() { serversocket = new Thread(() -> { try{ - ServerSocket ss = new ServerSocket(3333); + chatServerSocket = new ServerSocket(25224); while (true) { - Socket s = ss.accept(); + Socket s = chatServerSocket.accept(); PrintWriter out = new PrintWriter(s.getOutputStream(), true); BufferedReader in = new BufferedReader( @@ -59,6 +102,13 @@ public class Main extends JavaPlugin { } public void onDisable() { + try { + chatServerSocket.close(); + uuidServerSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + uuidServerThread.stop(); serversocket.stop(); getLogger().info("Plugin disabled"); } diff --git a/cogs/playerlink.py b/cogs/playerlink.py old mode 100644 new mode 100755 index fc2663e..2927fae --- a/cogs/playerlink.py +++ b/cogs/playerlink.py @@ -6,6 +6,10 @@ import socket import asyncio import threading from data import constants +from data.DatabaseConnection import * + +# 25216 --> uuid server +# 25224 --> send chat server def get_random_string(length): # Random string with the combination of lower and upper case @@ -18,9 +22,22 @@ class PlayerError(Exception): class WrongCodeError(Exception): pass +def get_player_uuid(minecraftname): + HOST = '192.168.1.214' # The server's hostname or IP address + PORT = 25216 # The port used by the server + + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.connect((HOST, PORT)) + s.send(bytes("{}\n".format(minecraftname), encoding="ascii")) + data = s.recv(1024) + data_string = data.decode("utf-8").strip('\n') + if data_string == "PlayerError": + raise PlayerError() + return data_string + def send_chat(discordname, minecraftname, code): - HOST = '127.0.0.1' # The server's hostname or IP address - PORT = 3333 # The port used by the server + HOST = '192.168.1.214' # The server's hostname or IP address + PORT = 25224 # The port used by the server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) @@ -29,7 +46,7 @@ def send_chat(discordname, minecraftname, code): data_string = data.decode("utf-8").strip('\n') if data_string == "PlayerError": raise PlayerError() - return True + return data_string class PlayerLink(commands.Cog): def __init__(self, client): @@ -46,6 +63,7 @@ class PlayerLink(commands.Cog): authorid = ctx.author.id code = get_random_string(8) + def check(message: discord.Message): return message.channel.id == channelid and message.author.id == authorid @@ -56,15 +74,18 @@ class PlayerLink(commands.Cog): embed.add_field(name="Minecraft Name:", value=f"{minecraftname}", inline=False) embed.add_field(name="Discord Name:", value=f"{discord_author.mention}", inline=False) + + # use dictionary and set color string before the message: example => r(ed):message + if isinstance(error, WrongCodeError): embed.add_field(name="Error", value=f"The code is wrong!", inline=False) embed.colour = discord.Colour.red() - elif (timer.ended): - embed.add_field(name="Timer", value=f"The code is expired!", inline=False) - embed.colour = discord.Colour.red() elif (success == True): embed.add_field(name="Success", value=f"The link was successfull!", inline=False) embed.colour = discord.Colour.green() + elif (timer.ended): + embed.add_field(name="Timer", value=f"The code is expired!", inline=False) + embed.colour = discord.Colour.red() elif (timer.minutes == 2): embed.add_field(name="Timer", value=f"The code will expire in { str(timer.minutes)} minutes", inline=False) embed.colour = discord.Colour.orange() @@ -86,6 +107,8 @@ class PlayerLink(commands.Cog): try: + + uuid = get_player_uuid(arg) send_chat(ctx.author.name, arg, code) #message_send_time = timer = Timer() @@ -98,9 +121,17 @@ class PlayerLink(commands.Cog): msg = await self.client.wait_for('message', check=check) if msg.content == code: - await ctx.author.add_roles(self.get_linked_role()) - timer.ended = True - await message.edit(embed=create_embed(ctx.author, arg, timer, success=True)) + + dbLinker = PlayerDBLinker() + try: + dbLinker.linkPlayer(uuid, authorid) + await ctx.author.add_roles(self.get_linked_role()) + timer.ended = True + await message.edit(embed=create_embed(ctx.author, arg, timer, success=True)) + except SQLInsertError: + await message.edit(embed=create_embed(ctx.author, arg, timer)) + finally: + dbLinker.closeconnections() else: # this stops the timer task task.cancel() @@ -113,9 +144,22 @@ class PlayerLink(commands.Cog): # await ctx.send("Something went wrong") @commands.command(name="Unlink") - async def unlink(self, ctx): - await ctx.author.remove_roles(self.get_linked_role()) - await ctx.send("Unlinked your account") + async def unlink(self, ctx, arg): + authorid = ctx.author.id + dbLinker = PlayerDBLinker() + try: + dbLinker.unlinkPlayer(arg, authorid) + await ctx.author.remove_roles(self.get_linked_role()) + await ctx.send("Unlinked your account") + except UnLinkError: + await ctx.send("The unlink was unsuccessfull") + except WrongMinecraftName: + await ctx.send("Wrong minecraft name!") + except PlayerNotLinked: + await ctx.send("Player not linked!") + finally: + dbLinker.closeconnections() + class Timer(): def __init__(self): diff --git a/requirements.txt b/requirements.txt index 8532548..a0ea04f 100755 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ discord.py==1.5.0 mcstatus==4.0.0 +mysql-connector-python==8.0.21 From 65a0a4c368422f97ae09b81deb529d83dde90364 Mon Sep 17 00:00:00 2001 From: victormylle Date: Fri, 6 Nov 2020 23:24:25 +0100 Subject: [PATCH 9/9] Some changes --- data/DatabaseConnection.py | 100 +++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100755 data/DatabaseConnection.py diff --git a/data/DatabaseConnection.py b/data/DatabaseConnection.py new file mode 100755 index 0000000..72ee79c --- /dev/null +++ b/data/DatabaseConnection.py @@ -0,0 +1,100 @@ +import mysql.connector + +class WrongMinecraftName(Exception): + pass +class SQLInsertError(Exception): + pass +class UnLinkError(Exception): + pass +class PlayerNotLinked(Exception): + pass + +class DatabaseConnection: + # databases -> worldcraft and worldcraft_discord + def __init__(self, database="worldcraft_discord"): + if database == "worldcraft_discord": + self.mydb = mysql.connector.connect( + host="192.168.1.251", + user="worldcraft_discord", + password="aquev5vcwhLwTdRt", + database=database + ) + elif database == "s13_worldcraft": + self.mydb = mysql.connector.connect( + host="192.168.1.251", + user="u13_f2zpWZpIKY", + password="@fZQ6Uu3+U^WH1i2JNemgTC7", + database=database + ) + + self.cursor = self.mydb.cursor() + + def get_db(self): + return self.mydb + + def get_cursor(self): + return self.cursor + + def close(self): + self.mydb.close() + +# this will save the uuid of the player and discord id +class PlayerDBLinker: + def __init__(self): + self.tablename = "playerlinks" + self.discorddbconn = DatabaseConnection(database="worldcraft_discord") + self.serverdbconn = DatabaseConnection(database="s13_worldcraft") + # check if table exists + cursor = self.discorddbconn.get_cursor() + cursor.execute("create table IF NOT EXISTS {} (id int NOT NULL PRIMARY KEY AUTO_INCREMENT, minecraftUUID varchar(36) NOT NULL, discordid TINYTEXT NOT NULL)".format(self.tablename)) + + def checkPlayerLink(self, minecraftUUID, discordid): + cursor = self.discorddbconn.get_cursor() + cursor.execute("select count(*) from {} where minecraftUUID='{}' AND discordid='{}'".format(self.tablename, minecraftUUID, discordid)) + res = cursor.fetchone() + return res[0] == 1 + + def minecraftUUIDused(self, minecraftUUID): + cursor = self.discorddbconn.get_cursor() + cursor.execute("select count(*) from {} where minecraftUUID='{}'".format(self.tablename, minecraftUUID)) + res = cursor.fetchone() + return res[0] >= 1 + + def discordidused(self, discordid): + cursor = self.discorddbconn.get_cursor() + cursor.execute("select count(*) from {} where discordid='{}'".format(self.tablename, discordid)) + res = cursor.fetchone() + return res[0] >= 1 + + def linkPlayer(self, minecraftUUID, discordid): + cursor = self.discorddbconn.get_cursor() + sql = "insert into {} (minecraftUUID, discordid) VALUES (%s, %s)".format(self.tablename) + val = (minecraftUUID, discordid) + + 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() + discorddb_cursor = self.discorddbconn.get_cursor() + sql = "SELECT playerUUID FROM playerprofiles WHERE playerName = '{}' LIMIT 1".format(minecraftname) + serverdb_cursor.execute(sql) + res = serverdb_cursor.fetchone() + if res == None: + raise WrongMinecraftName() + playeruuid = res[0] + if self.checkPlayerLink(playeruuid, discordid): + sql2 = f"DELETE FROM {self.tablename} WHERE minecraftUUID = '{playeruuid}' AND discordid = '{discordid}'" + discorddb_cursor.execute(sql2) + res2 = self.discorddbconn.get_db().commit() + else: + raise PlayerNotLinked() + + def closeconnections(self): + self.discorddbconn.close() + self.serverdbconn.close()