From 4ca13061d25a6ebf013fed1a70b9d828fd740636 Mon Sep 17 00:00:00 2001 From: Joseph Montanaro Date: Fri, 8 May 2020 21:39:28 -0700 Subject: [PATCH] initial commit --- .gitignore | 1 + bot.py | 39 +++++++++++++++++++++++++++++++++++++++ heavynode.py | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 .gitignore create mode 100644 bot.py create mode 100644 heavynode.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f2d4b96 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__* \ No newline at end of file diff --git a/bot.py b/bot.py new file mode 100644 index 0000000..643ae70 --- /dev/null +++ b/bot.py @@ -0,0 +1,39 @@ +import logging +import os + +from discord.ext import commands + +import heavynode + + +logging.basicConfig() +hn = heavynode.Client(os.environ['heavynode_token']) +bot = commands.Bot(command_prefix='!') + + +@bot.command() +@commands.has_role('Server admin') +async def add(ctx, player): + """Add a player to the server whitelist.Must use exact Minecraft name.""" + await hn.send_command('d030737c', f'whitelist add {player}') + await ctx.send(f'"{player}" added to whitelist.') + + +@bot.command() +@commands.has_role('Server admin') +async def remove(ctx, player): + """Remove a player from the server whitelist. Must use exact Minecraft name.""" + await hn.send_command('d030737c', f'whitelist remove {player}') + await ctx.send(f'"{player}" removed from whitelist.') + + +@add.error +@remove.error +async def whitelist_error(ctx, error): + if isinstance(error, commands.CheckFailure): + await ctx.send('You must be a server admin to use this command.') + else: + raise error + + +bot.run(os.environ['discord_token'], reconnect=True) \ No newline at end of file diff --git a/heavynode.py b/heavynode.py new file mode 100644 index 0000000..f2340a9 --- /dev/null +++ b/heavynode.py @@ -0,0 +1,36 @@ +import urllib.parse + +import aiohttp + + +class HttpError(Exception): + def __init__(self, msg, response): + self.response = response + super().__init__(msg) + + +class Client: + def __init__(self, token): + self.token = token + self.session = aiohttp.ClientSession() + self.baseurl = 'https://control.heavynode.com/api' + + async def make_request(self, method, path, *args, **kwargs): + h = {'Authorization': f'Bearer {self.token}'} + if 'headers' in kwargs: + kwargs['headers'].update(h) + else: + kwargs['headers'] = h + + if path[0] != '/': + path = '/' + path + url = self.baseurl + path + + r = await self.session.request(method, url, *args, **kwargs) + if r.status >= 400: + raise HttpError(f'Request failed with status code {r.status}', r) + return r + + async def send_command(self, serverid, cmd): + payload = {'command': cmd} + return await self.make_request('POST', f'/client/servers/{serverid}/command', json=payload)