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))