aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to '')
-rwxr-xr-xbot.py67
-rwxr-xr-xcogs/admin.py114
-rwxr-xr-xcogs/utils.py36
-rwxr-xr-xmain.py38
4 files changed, 121 insertions, 134 deletions
diff --git a/bot.py b/bot.py
index cace1d1..179ca08 100755
--- a/bot.py
+++ b/bot.py
@@ -7,52 +7,53 @@ import config
import json
extensions = [
- "cogs.utils",
- "cogs.admin"
+ "cogs.utils",
+ "cogs.admin"
]
class BedrockBot(commands.Bot):
- def __init__(self):
- super().__init__(command_prefix='/')
- self.logger = logging.getLogger('discord')
+ def __init__(self):
+ super().__init__(command_prefix='/')
+ self.logger = logging.getLogger('discord')
- with open('custom_commands.json', 'r') as f:
- self.custom_commands = json.load(f)
+ with open('custom_commands.json', 'r') as f:
+ self.custom_commands = json.load(f)
- for extension in extensions:
- self.load_extension(extension)
-
-
+ for extension in extensions:
+ self.load_extension(extension)
+
+
- async def on_ready(self):
- self.uptime = datetime.datetime.utcnow()
+ async def on_ready(self):
+ self.uptime = datetime.datetime.utcnow()
- game = discord.Game("Mining away")
- await self.change_presence(activity=game)
+ game = discord.Game("Mining away")
+ await self.change_presence(activity=game)
- self.logger.warning(f'Online: {self.user} (ID: {self.user.id})')
+ self.logger.warning(f'Online: {self.user} (ID: {self.user.id})')
- async def on_message(self, message):
+ async def on_message(self, message):
- if message.author.bot:
- return
+ if message.author.bot:
+ return
- command = message.content.split()[0]
+ command = message.content.split()[0]
- if command in self.custom_commands:
- await message.channel.send(self.custom_commands[command])
- return
+ if command in self.custom_commands:
+ await message.channel.send(self.custom_commands[command])
+ return
- badWords = ["fair", "f a i r", "ⓕⓐⓘⓡ", "ⓕ ⓐ ⓘ ⓡ"]
- if message.channel.id == 589110766578434078:
- count = 0
- for word in badWords:
- if word in message.content.lower():
- count += 1;
- await message.channel.send('Fair '*count)
+ badWords = ["fair", "f a i r", "ⓕⓐⓘⓡ", "ⓕ ⓐ ⓘ ⓡ"]
+ if message.channel.id == 589110766578434078:
+ count = 0
+ for word in badWords:
+ if word in message.content.lower():
+ count += 1;
+ fair = 'Fair '*count
+ await message.channel.send(fair)
- await self.process_commands(message)
+ await self.process_commands(message)
- def run(self):
- super().run(config.token, reconnect=True)
+ def run(self):
+ super().run(config.token, reconnect=True)
diff --git a/cogs/admin.py b/cogs/admin.py
index 4cf7df7..6cbaf52 100755
--- a/cogs/admin.py
+++ b/cogs/admin.py
@@ -1,70 +1,70 @@
from discord.ext import commands
import discord
-
import subprocess
-
import json
class Admin(commands.Cog):
- def __init__(self, bot):
- self.bot = bot
+ def __init__(self, bot):
+ self.bot = bot
+
+ async def is_mod(ctx):
+ return ctx.author.guild_permissions.manage_channels
- async def is_mod(ctx):
- return ctx.author.guild_permissions.manage_channels
+ async def is_host(ctx):
+ return ctx.author.id == 99457716614885376
- @commands.command(aliases=['addcommand', 'newcommand'])
- @commands.check(is_mod)
- async def setcommand(self, ctx, command, *, message):
- self.bot.custom_commands["/" + command] = message
- with open('custom_commands.json', 'w') as f:
- json.dump(self.bot.custom_commands, f)
+ @commands.command(aliases=['addcommand', 'newcommand'])
+ @commands.check(is_mod)
+ async def setcommand(self, ctx, command, *, message):
+ self.bot.custom_commands["/" + command] = message
+ with open('custom_commands.json', 'w') as f:
+ json.dump(self.bot.custom_commands, f)
- await ctx.send(f"Set message for command {command}")
+ await ctx.send(f"Set message for command {command}")
- @commands.command(aliases=['deletecommand'])
- @commands.check(is_mod)
- async def removecommand(self, ctx, command):
- del self.bot.custom_commands["/" + command]
- with open('custom_commands.json', 'w') as f:
- json.dump(self.bot.custom_commands, f)
+ @commands.command(aliases=['deletecommand'])
+ @commands.check(is_mod)
+ async def removecommand(self, ctx, command):
+ del self.bot.custom_commands["/" + command]
+ with open('custom_commands.json', 'w') as f:
+ json.dump(self.bot.custom_commands, f)
- await ctx.send(f"Removed command {command}")
-
-
- @commands.check(is_mod)
- @commands.command(name='reload', hidden=True, usage='<extension>')
- async def _reload(self, ctx, ext):
- """Reloads an extension"""
- try:
- self.bot.reload_extension(f'cogs.{ext}')
- await ctx.send(f'The extension {ext} was reloaded!')
- except commands.ExtensionNotFound:
- await ctx.send(f'The extension {ext} doesn\'t exist.')
- except commands.ExtensionNotLoaded:
- await ctx.send(f'The extension {ext} is not loaded! (use /load)')
- except commands.NoEntryPointError:
- await ctx.send(f'The extension {ext} doesn\'t have an entry point (try adding the setup function) ')
- except commands.ExtensionFailed:
- await ctx.send(f'Some unknown error happened while trying to reload extension {ext} (check logs)')
- self.bot.logger.exception(f'Failed to reload extension {ext}:')
-
- @commands.check(is_mod)
- @commands.command(name='load', hidden=True, usage='<extension>')
- async def _load(self, ctx, ext):
- """Loads an extension"""
- try:
- self.bot.load_extension(f'cogs.{ext}')
- await ctx.send(f'The extension {ext} was loaded!')
- except commands.ExtensionNotFound:
- await ctx.send(f'The extension {ext} doesn\'t exist!')
- except commands.ExtensionAlreadyLoaded:
- await ctx.send(f'The extension {ext} is already loaded.')
- except commands.NoEntryPointError:
- await ctx.send(f'The extension {ext} doesn\'t have an entry point (try adding the setup function)')
- except commands.ExtensionFailed:
- await ctx.send(f'Some unknown error happened while trying to reload extension {ext} (check logs)')
- self.bot.logger.exception(f'Failed to reload extension {ext}:')
-
+ await ctx.send(f"Removed command {command}")
+
+
+ @commands.check(is_mod)
+ @commands.command(name='reload', hidden=True, usage='<extension>')
+ async def _reload(self, ctx, ext):
+ """Reloads an extension"""
+ try:
+ self.bot.reload_extension(f'cogs.{ext}')
+ await ctx.send(f'The extension {ext} was reloaded!')
+ except commands.ExtensionNotFound:
+ await ctx.send(f'The extension {ext} doesn\'t exist.')
+ except commands.ExtensionNotLoaded:
+ await ctx.send(f'The extension {ext} is not loaded! (use /load)')
+ except commands.NoEntryPointError:
+ await ctx.send(f'The extension {ext} doesn\'t have an entry point (try adding the setup function) ')
+ except commands.ExtensionFailed:
+ await ctx.send(f'Some unknown error happened while trying to reload extension {ext} (check logs)')
+ self.bot.logger.exception(f'Failed to reload extension {ext}:')
+
+ @commands.check(is_mod)
+ @commands.command(name='load', hidden=True, usage='<extension>')
+ async def _load(self, ctx, ext):
+ """Loads an extension"""
+ try:
+ self.bot.load_extension(f'cogs.{ext}')
+ await ctx.send(f'The extension {ext} was loaded!')
+ except commands.ExtensionNotFound:
+ await ctx.send(f'The extension {ext} doesn\'t exist!')
+ except commands.ExtensionAlreadyLoaded:
+ await ctx.send(f'The extension {ext} is already loaded.')
+ except commands.NoEntryPointError:
+ await ctx.send(f'The extension {ext} doesn\'t have an entry point (try adding the setup function)')
+ except commands.ExtensionFailed:
+ await ctx.send(f'Some unknown error happened while trying to reload extension {ext} (check logs)')
+ self.bot.logger.exception(f'Failed to reload extension {ext}:')
def setup(bot):
- bot.add_cog(Admin(bot))
+ bot.add_cog(Admin(bot))
diff --git a/cogs/utils.py b/cogs/utils.py
index 66b9f23..9959fdb 100755
--- a/cogs/utils.py
+++ b/cogs/utils.py
@@ -62,19 +62,13 @@ async def pendingRuns(self, ctx):
"Accept": "application/json",
"User-Agent":"mcbeDiscordBot/1.0"
}
- # mgs = [] #Empty list to put all the messages in the log
- # number = int(number) #Converting the amount of messages to delete to an integer
- # async for x in Client.logs_from(ctx.message.channel, limit = number):
- # mgs.append(x)
- # await Client.delete_messages(mgs)
-
gameID = 'yd4ovvg1' # ID of Minecraft bedrock
gameID2 = 'v1po7r76' # ID of Category extension
runsRequest = requests.get(
- f'https://www.speedrun.com/api/v1/runs?game={gameID}&status=new&max=200', headers=head)
+ f'https://www.speedrun.com/api/v1/runs?game={gameID}&status=new&max=200&embed=category,players', headers=head)
runs = json.loads(runsRequest.text)
runsRequest2 = requests.get(
- f'https://www.speedrun.com/api/v1/runs?game={gameID2}&status=new&max=200', headers=head)
+ f'https://www.speedrun.com/api/v1/runs?game={gameID2}&status=new&max=200&embed=category,players', headers=head)
runs2 = json.loads(runsRequest2.text)
# Use https://www.speedrun.com/api/v1/games?abbreviation=mcbe for ID
@@ -85,22 +79,15 @@ async def pendingRuns(self, ctx):
if key == 'weblink':
link = value
if key == 'category':
- categoryID = value
- categoryRequest = requests.get(
- f"https://www.speedrun.com/api/v1/categories/{categoryID}", headers=head)
- categoryRequest = categoryRequest.json()
- categoryName = categoryRequest['data']['name']
+ categoryName = value["data"]["name"]
if key == 'players':
- if value[0]['rel'] == 'guest':
- player = value[0]['name']
+ if value["data"][0]['rel'] == 'guest':
+ player = value["data"][0]['name']
else:
- nameRequest = requests.get(value[0]['uri'])
- nameRequest = nameRequest.json()
- player = nameRequest['data']['names']['international']
+ player = value["data"][0]["names"]["international"]
if key == 'times':
rta = timedelta(seconds=value['realtime_t'])
except Exception as e:
- #print(e.message + '\n' + e.args)
break
if game == 0:
leaderboard = "Minecraft bedrock"
@@ -127,6 +114,7 @@ class Utils(commands.Cog):
await ctx.send(ctx.message.channel)
@commands.command()
+ @commands.guild_only()
async def pending(self, ctx):
await clear(self)
await pendingRuns(self, ctx)
@@ -149,13 +137,11 @@ class Utils(commands.Cog):
@commands.command()
async def verify(self, ctx, apiKey=None):
- if apiKey is None:
- await ctx.send("Please try this `/verify apiKey` again **in DMs**. If you need the api key you can get it from https://www.speedrun.com/api/auth")
- if ctx.guild is None:
- await verifyRole(self, ctx, apiKey)
- else:
+ if apiKey == None:
+ await ctx.send("Please try again this command by getting an apiKey from https://www.speedrun.com/api/auth then do `/verify <apiKey>` in my DMs or anywhere in this server. \nBe careful who you share this key with. To learn more check out https://github.com/speedruncomorg/api/blob/master/authentication.md")
+ elif ctx.guild != None:
await ctx.message.delete()
- print("Not DMs")
+ await verifyRole(self, ctx, apiKey)
def setup(bot):
bot.add_cog(Utils(bot))
diff --git a/main.py b/main.py
index 56e341b..9f713bf 100755
--- a/main.py
+++ b/main.py
@@ -7,31 +7,31 @@ from bot import BedrockBot
def setup_logging():
- FORMAT = '%(asctime)s - [%(levelname)s]: %(message)s'
- DATE_FORMAT = '%d/%m/%Y (%H:%M:%S)'
+ FORMAT = '%(asctime)s - [%(levelname)s]: %(message)s'
+ DATE_FORMAT = '%d/%m/%Y (%H:%M:%S)'
- logger = logging.getLogger('discord')
- logger.setLevel(logging.INFO)
+ logger = logging.getLogger('discord')
+ logger.setLevel(logging.INFO)
- file_handler = logging.FileHandler(filename='discord.log', mode='a', encoding='utf-8')
- file_handler.setFormatter(logging.Formatter(fmt=FORMAT, datefmt=DATE_FORMAT))
- file_handler.setLevel(logging.INFO)
- logger.addHandler(file_handler)
+ file_handler = logging.FileHandler(filename='discord.log', mode='a', encoding='utf-8')
+ file_handler.setFormatter(logging.Formatter(fmt=FORMAT, datefmt=DATE_FORMAT))
+ file_handler.setLevel(logging.INFO)
+ logger.addHandler(file_handler)
- console_handler = logging.StreamHandler()
- console_handler.setFormatter(logging.Formatter(fmt=FORMAT, datefmt=DATE_FORMAT))
- console_handler.setLevel(logging.WARNING)
- logger.addHandler(console_handler)
+ console_handler = logging.StreamHandler()
+ console_handler.setFormatter(logging.Formatter(fmt=FORMAT, datefmt=DATE_FORMAT))
+ console_handler.setLevel(logging.WARNING)
+ logger.addHandler(console_handler)
def run_bot():
- bot = BedrockBot()
- bot.run()
+ bot = BedrockBot()
+ bot.run()
if __name__ == "__main__":
-
- init_colorama(autoreset=True)
+
+ init_colorama(autoreset=True)
- setup_logging()
-
- run_bot()
+ setup_logging()
+
+ run_bot()