Files
WorldCraft_Discord_Bot/cogs/playerlink.py

71 lines
2.3 KiB
Python

import discord
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
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(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{}\t{}\n".format(discordname, 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
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):
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:
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):
client.add_cog(PlayerLink(client))