diff options
author | AnInternetTroll <lucafulger@gmail.com> | 2020-05-06 10:00:46 +0000 |
---|---|---|
committer | AnInternetTroll <lucafulger@gmail.com> | 2020-05-06 10:00:46 +0000 |
commit | 14fd81118a30dea394eca940cefb6dda86b66933 (patch) | |
tree | 5105b1cf1d0ef86dd651e17564c49f58c384b3ed | |
download | steve-bot-14fd81118a30dea394eca940cefb6dda86b66933.tar steve-bot-14fd81118a30dea394eca940cefb6dda86b66933.tar.gz steve-bot-14fd81118a30dea394eca940cefb6dda86b66933.tar.bz2 steve-bot-14fd81118a30dea394eca940cefb6dda86b66933.tar.lz steve-bot-14fd81118a30dea394eca940cefb6dda86b66933.tar.xz steve-bot-14fd81118a30dea394eca940cefb6dda86b66933.tar.zst steve-bot-14fd81118a30dea394eca940cefb6dda86b66933.zip |
First commit :partying_face:
-rwxr-xr-x | .gitignore | 4 | ||||
-rwxr-xr-x | .vscode/settings.json | 3 | ||||
-rwxr-xr-x | bot.py | 56 | ||||
-rwxr-xr-x | cogs/admin.py | 70 | ||||
-rwxr-xr-x | cogs/utils.py | 161 | ||||
-rwxr-xr-x | custom_commands.json | 8 | ||||
-rwxr-xr-x | main.py | 37 | ||||
-rw-r--r-- | readme.md | 8 |
8 files changed, 347 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..3339ce1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__ +config.py +discord.log +.vscode/ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100755 index 0000000..4a172e5 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.pythonPath": "C:\\Users\\matei\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe" +}
\ No newline at end of file @@ -0,0 +1,56 @@ +from discord.ext import commands +import discord +import logging + +import datetime +import config +import json + +extensions = [ + "cogs.utils", + "cogs.admin" +] + +class CelesteBot(commands.Bot): + + 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) + + for extension in extensions: + self.load_extension(extension) + + + + async def on_ready(self): + self.uptime = datetime.datetime.utcnow() + + game = discord.Game("Mining away") + await self.change_presence(activity=game) + + self.logger.warning(f'Online: {self.user} (ID: {self.user.id})') + + async def on_message(self, message): + + if message.author.bot: + return + + command = message.content.split()[0] + + 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: + for word in badWords: + if word in message.content.lower(): + await message.channel.send('Fair') + + await self.process_commands(message) + + def run(self): + super().run(config.token, reconnect=True) diff --git a/cogs/admin.py b/cogs/admin.py new file mode 100755 index 0000000..4cf7df7 --- /dev/null +++ b/cogs/admin.py @@ -0,0 +1,70 @@ +from discord.ext import commands +import discord + +import subprocess + +import json + +class Admin(commands.Cog): + def __init__(self, bot): + self.bot = bot + + async def is_mod(ctx): + return ctx.author.guild_permissions.manage_channels + + @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}") + + @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}:') + + +def setup(bot): + bot.add_cog(Admin(bot)) diff --git a/cogs/utils.py b/cogs/utils.py new file mode 100755 index 0000000..66b9f23 --- /dev/null +++ b/cogs/utils.py @@ -0,0 +1,161 @@ +from discord.ext import commands +from discord.ext import tasks +from discord.utils import get +import discord +import requests +import json +import asyncio +from datetime import timedelta +from google.cloud import translate_v2 as translate +translate_client = translate.Client() + +async def translateMsg(text, target="en"): + # Text can also be a sequence of strings, in which case this method + # will return a sequence of results for each text. + result = translate_client.translate( + text, target_language=target) + print(u'Text: {}'.format(result['input'])) + print(u'Translation: {}'.format(result['translatedText'])) + print(u'Detected source language: {}'.format( + result['detectedSourceLanguage'])) + return result; + + +async def verifyRole(self, ctx, apiKey): + server = self.bot.get_guild(574267523869179904) + RunneRole = server.get_role(574268937454223361) + WrRole = server.get_role(583622436378116107) + head = { + "X-API-Key":apiKey, + "Accept": "application/json", + "User-Agent":"mcbeDiscordBot/1.0" + } + r = requests.get('https://www.speedrun.com/api/v1/profile', headers=head) + + #print(profile.text) + profile = json.loads(r.text) + pbs = requests.get(profile["data"]["links"][3]["uri"]) + pbs = json.loads(pbs.text) + + for i in pbs["data"]: + if i["place"] == 1: + if i["run"]["game"] == "yd4ovvg1" or i["run"]["game"] == "v1po7r76": + await ctx.send("WR boi") + await server.get_member(ctx.message.author.id).add_roles(WrRole) + print("WR boi") + if i["run"]["game"] == "yd4ovvg1" or i["run"]["game"] == "v1po7r76": + #print(i) + await ctx.send("Runner") + await server.get_member(ctx.message.author.id).add_roles(RunneRole) + #print("minecraft") + + print(r.status_code) + #print(json.dumps(pbs,sort_keys=True, indent=4)) + +async def clear(self): + async for msg in self.bot.get_channel(699713639866957905).history(): + await msg.delete() + + +async def pendingRuns(self, ctx): + head = { + "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) + runs = json.loads(runsRequest.text) + runsRequest2 = requests.get( + f'https://www.speedrun.com/api/v1/runs?game={gameID2}&status=new&max=200', headers=head) + runs2 = json.loads(runsRequest2.text) + # Use https://www.speedrun.com/api/v1/games?abbreviation=mcbe for ID + + for game in range(2): + for i in range(200): + try: + for key, value in runs['data'][i].items(): + 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'] + if key == 'players': + if value[0]['rel'] == 'guest': + player = value[0]['name'] + else: + nameRequest = requests.get(value[0]['uri']) + nameRequest = nameRequest.json() + player = nameRequest['data']['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" + elif game == 1: + leaderboard = "Minecraft Bedrock category extensions" + embed = discord.Embed( + title=leaderboard, url=link, description=f"{categoryName} in `{str(rta).replace('000','')}` by **{player}**", color=16711680+i*60) + await self.bot.get_channel(699713639866957905).send(embed=embed) + runs = runs2 + gameID = gameID2 + +class Utils(commands.Cog): + + def __init__(self, bot): + self.bot = bot + + @commands.command() + async def ping(self, ctx): + # """Shows the Client Latency.""" + await ctx.send(f'Pong! {round(self.bot.latency*1000)}ms') + + @commands.command() + async def test(self, ctx): + await ctx.send(ctx.message.channel) + + @commands.command() + async def pending(self, ctx): + await clear(self) + await pendingRuns(self, ctx) + + @commands.command() + async def translate(self, ctx, *, message): + response = await translateMsg(message) + embed=discord.Embed(title="Translation",description=f"{ctx.message.author.mention} says:", timestamp=ctx.message.created_at, color=0x4d9aff) + embed.add_field(name=f"[{response['detectedSourceLanguage']}] Source:" , value=response['input'], inline=False) + embed.add_field(name="Translation", value=response['translatedText'], inline=True) + await ctx.send(embed=embed) + + @commands.command() + async def trans(self, ctx, lan, *, message): + response = await translateMsg(message, lan) + embed=discord.Embed(title="Translation",description=f"{ctx.message.author.mention} says:", timestamp=ctx.message.created_at, color=0x4d9aff) + embed.add_field(name=f"[{response['detectedSourceLanguage']}] Source:" , value=response['input'], inline=False) + embed.add_field(name="Translation", value=response['translatedText'], inline=True) + await ctx.send(embed=embed) + + @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: + await ctx.message.delete() + print("Not DMs") + +def setup(bot): + bot.add_cog(Utils(bot)) diff --git a/custom_commands.json b/custom_commands.json new file mode 100755 index 0000000..e9d18d7 --- /dev/null +++ b/custom_commands.json @@ -0,0 +1,8 @@ +{ + "/src": "https://www.speedrun.com/mcbe", + "/launcher": "https://github.com/MCMrARM/mc-w10-version-launcher/releases/tag/0.1.0", + "/locate": "head north", + "/boards": "https://www.speedrun.com/mcbe", + "/leaderboards": "https://www.speedrun.com/mcbe", + "/ban": "shut up" +}
\ No newline at end of file @@ -0,0 +1,37 @@ +import asyncio +import logging + +from colorama import init as init_colorama + +from bot import CelesteBot + + +def setup_logging(): + FORMAT = '%(asctime)s - [%(levelname)s]: %(message)s' + DATE_FORMAT = '%d/%m/%Y (%H:%M:%S)' + + 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) + + 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 = CelesteBot() + bot.run() + +if __name__ == "__main__": + + init_colorama(autoreset=True) + + setup_logging() + + run_bot() diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..f85b95e --- /dev/null +++ b/readme.md @@ -0,0 +1,8 @@ +# Minecraft Bedrock Discord Bot + +## How to +Make a file called `config.py` and add a `token="DiscordToken"` variable in there. +Launch the bot with `python3 main.py` and you're ready to go. Unless dependencies. Dependencies are google cloud and discord. + +This bot was built as a fork of [celesteBot](https://github.com/CelesteClassic/celestebot), so a lot of code is recycled. +Feel free to make a pull request or use the code here. |