diff --git a/serious_bot/db.py b/serious_bot/db.py index 6c71b5f..282cfe7 100644 --- a/serious_bot/db.py +++ b/serious_bot/db.py @@ -17,18 +17,18 @@ def register(cls): def init(): - print('INITIALIZING DATABASE AND LOADING MODELS...') - database.initialize(PostgresqlExtDatabase( - 'seriousbot_dev', - user='postgres', - port=5432, - autorollback=True)) + print("INITIALIZING DATABASE AND LOADING MODELS...") + database.initialize( + PostgresqlExtDatabase( + "seriousbot_dev", user="postgres", port=5432, autorollback=True + ) + ) for model in MODELS: print(f"Looping {model}") model.create_table(True) - if hasattr(model, 'SQL'): + if hasattr(model, "SQL"): database.execute_sql(model.SQL) diff --git a/serious_bot/models/user.py b/serious_bot/models/user.py index 9eb00d4..7d601f0 100644 --- a/serious_bot/models/user.py +++ b/serious_bot/models/user.py @@ -12,11 +12,9 @@ class User(BaseModel): user_rank = SmallIntegerField(default=0) class Meta: - db_table = 'users' + db_table = "users" - indexes = ( - (('id', 'username', 'discriminator'), True), - ) + indexes = ((("id", "username", "discriminator"), True),) @BaseModel.register @@ -29,8 +27,6 @@ class Trivia(BaseModel): points = SmallIntegerField() # Small should be good.. right? :thonk: class Meta: - db_table = 'trivia' + db_table = "trivia" - indexes = ( - (('guild_id', 'user_id'), False), - ) + indexes = ((("guild_id", "user_id"), False),) diff --git a/serious_bot/plugins/dyk/didyouknow.py b/serious_bot/plugins/dyk/didyouknow.py index cc421d3..a183899 100644 --- a/serious_bot/plugins/dyk/didyouknow.py +++ b/serious_bot/plugins/dyk/didyouknow.py @@ -4,7 +4,11 @@ import random -PARSERS = [dykparser.DYKParser(), djtechparser.DJTechParser(), dedustparser.DEDustParser()] +PARSERS = [ + dykparser.DYKParser(), + djtechparser.DJTechParser(), + dedustparser.DEDustParser(), +] def grab_fact(): @@ -14,6 +18,6 @@ def grab_fact(): fact = parser.get_random() if fact is None: - return ('Failed to grab a fact!', None) + return ("Failed to grab a fact!", None) else: return (fact, parser.name) diff --git a/serious_bot/plugins/dyk/parsers/baseparser.py b/serious_bot/plugins/dyk/parsers/baseparser.py index ae253e2..0d44a10 100644 --- a/serious_bot/plugins/dyk/parsers/baseparser.py +++ b/serious_bot/plugins/dyk/parsers/baseparser.py @@ -1,5 +1,4 @@ class BaseParser: - def __init__(self): self.name = "Unknown" diff --git a/serious_bot/plugins/dyk/parsers/dedustparser.py b/serious_bot/plugins/dyk/parsers/dedustparser.py index b471938..4d39996 100644 --- a/serious_bot/plugins/dyk/parsers/dedustparser.py +++ b/serious_bot/plugins/dyk/parsers/dedustparser.py @@ -3,11 +3,10 @@ class DEDustParser(BaseParser): - def __init__(self): - self.name = 'Penrouk' + self.name = "Penrouk" - loaded_file = open('./serious_bot/plugins/dyk/parsers/de_dust.txt', 'r') + loaded_file = open("./serious_bot/plugins/dyk/parsers/de_dust.txt", "r") self.lines = loaded_file.readlines() loaded_file.close() diff --git a/serious_bot/plugins/dyk/parsers/djtechparser.py b/serious_bot/plugins/dyk/parsers/djtechparser.py index 7db9234..88a4563 100644 --- a/serious_bot/plugins/dyk/parsers/djtechparser.py +++ b/serious_bot/plugins/dyk/parsers/djtechparser.py @@ -5,16 +5,15 @@ class DJTechParser(BaseParser): - def __init__(self): - self.name = 'DJTech' + self.name = "DJTech" def get_random(self): - html = requests.get('http://www.djtech.net/humor/shorty_useless_facts.htm').text + html = requests.get("http://www.djtech.net/humor/shorty_useless_facts.htm").text - parser = BeautifulSoup(html, 'html.parser') + parser = BeautifulSoup(html, "html.parser") - text_list = parser.find_all('font', {'style': 'font-size: 11pt'}) + text_list = parser.find_all("font", {"style": "font-size: 11pt"}) if len(text_list) > 0: return random.choice(text_list).text.replace("\n\t\t", "") diff --git a/serious_bot/plugins/dyk/parsers/dykparser.py b/serious_bot/plugins/dyk/parsers/dykparser.py index b7a09ee..1cd0163 100644 --- a/serious_bot/plugins/dyk/parsers/dykparser.py +++ b/serious_bot/plugins/dyk/parsers/dykparser.py @@ -5,7 +5,6 @@ class DYKParser(BaseParser): - def __init__(self): self.name = "Did-You-Knows" @@ -13,11 +12,11 @@ def get_random(self): page = random.randint(1, 50) html = requests.get(f"http://www.did-you-knows.com/?page={page}").text - parser = BeautifulSoup(html, 'html.parser') + parser = BeautifulSoup(html, "html.parser") - text_list = parser.find_all('span', {'class': 'dykText'}) + text_list = parser.find_all("span", {"class": "dykText"}) if len(text_list) > 0: - return 'Did you know ' + random.choice(text_list).text + return "Did you know " + random.choice(text_list).text else: return None diff --git a/serious_bot/plugins/events.py b/serious_bot/plugins/events.py index 78ab689..1cc4d34 100644 --- a/serious_bot/plugins/events.py +++ b/serious_bot/plugins/events.py @@ -3,26 +3,31 @@ class EventsPlugin(Plugin): - def load(self, ctx): super(EventsPlugin, self).load(ctx) - self._servers = ctx.get('servers', {}) + self._servers = ctx.get("servers", {}) def unload(self, ctx): - ctx['servers'] = self._servers + ctx["servers"] = self._servers super(EventsPlugin, self).unload(ctx) - @Plugin.listen('MessageCreate') + @Plugin.listen("MessageCreate") def on_message_create(self, event): - self.log.info(u'{}: {}'.format(event.author, event.content)) + self.log.info(u"{}: {}".format(event.author, event.content)) for key, attachment in event.attachments.items(): - self.log.info(u'{}, {}, {}'.format(attachment.filename, attachment.url, attachment.proxy_url)) + self.log.info( + u"{}, {}, {}".format( + attachment.filename, attachment.url, attachment.proxy_url + ) + ) - @Plugin.listen('PresenceUpdate') + @Plugin.listen("PresenceUpdate") def on_presence_update(self, event): - self.log.info(u'Update in {} -> {}'.format(event.guild_id, event.presence.user)) + self.log.info(u"Update in {} -> {}".format(event.guild_id, event.presence.user)) - @Plugin.listen('Ready') + @Plugin.listen("Ready") def on_ready(self, event): - self.client.update_presence(Status.online, Game(type=GameType.watching, name='you fail at life.')) + self.client.update_presence( + Status.online, Game(type=GameType.watching, name="you fail at life.") + ) diff --git a/serious_bot/plugins/fun.py b/serious_bot/plugins/fun.py index 75f4310..377fb95 100644 --- a/serious_bot/plugins/fun.py +++ b/serious_bot/plugins/fun.py @@ -12,10 +12,9 @@ class FunPlugin(Plugin): - def load(self, ctx): self.roaster = Roast() - self.reddit = Reddit('dankmemes') + self.reddit = Reddit("dankmemes") # Just scrape them right off the bat and get it over with # TODO: Sync them every now and then? @@ -36,7 +35,7 @@ def on_pre_command(self, command, event, _par, _brack): return event - @Plugin.command('dyk') + @Plugin.command("dyk") def on_dyk(self, event): self.client.api.channels_typing(event.msg.channel_id) @@ -46,18 +45,20 @@ def on_dyk(self, event): embed.description = f"**{fact}**" embed.set_footer(text=name) embed.timestamp = datetime.utcnow().isoformat() - embed.color = '10038562' + embed.color = "10038562" event.msg.reply(embed=embed) - @Plugin.command('urban', '[phrase:str...]') + @Plugin.command("urban", "[phrase:str...]") def on_urban(self, event, phrase=None): self.client.api.channels_typing(event.msg.channel_id) urban_entry = None if phrase is None: - urban_entry = random.choice(ud.random()) # grab some random words | list of urbandef + urban_entry = random.choice( + ud.random() + ) # grab some random words | list of urbandef else: defs = ud.define(phrase) @@ -65,32 +66,35 @@ def on_urban(self, event, phrase=None): urban_entry = defs[0] if urban_entry is None: - event.msg.reply('Failed to find a definition for that!') + event.msg.reply("Failed to find a definition for that!") else: definition = urban_entry.definition # Let's do a little... checking! if len(definition) >= 2000: - definition = definition[:1950] + '...' + definition = definition[:1950] + "..." # Let's construct an embed :) embed = MessageEmbed() embed.title = f"**Defintion of {urban_entry.word}**" embed.description = definition - embed.add_field(name='Example', value=urban_entry.example) - embed.add_field(name='Rating', value=f"{urban_entry.upvotes} 👍 | {urban_entry.downvotes} 👎") + embed.add_field(name="Example", value=urban_entry.example) + embed.add_field( + name="Rating", + value=f"{urban_entry.upvotes} 👍 | {urban_entry.downvotes} 👎", + ) - embed.color = '5824574' + embed.color = "5824574" event.msg.reply(embed=embed) - @Plugin.command('roast') + @Plugin.command("roast") def on_roast(self, event): roast = self.roaster.get_random() event.msg.reply(f"{event.author.mention}, {roast}") - @Plugin.command('meme') + @Plugin.command("meme") def on_reddit(self, event): random_post = self.reddit.random_post(self.memes) diff --git a/serious_bot/plugins/trivia.py b/serious_bot/plugins/trivia.py index 54d81f6..dbb0921 100644 --- a/serious_bot/plugins/trivia.py +++ b/serious_bot/plugins/trivia.py @@ -13,10 +13,16 @@ class OpenTDB: - class Question: - - def __init__(self, category, type, difficulty, question, correct_answer, incorrect_answers): + def __init__( + self, + category, + type, + difficulty, + question, + correct_answer, + incorrect_answers, + ): self.category = category self.kind = type self.difficulty = difficulty @@ -26,7 +32,7 @@ def __init__(self, category, type, difficulty, question, correct_answer, incorre self.caller = None def get_questions(self): - response = requests.get('https://opentdb.com/api.php?amount=10').text + response = requests.get("https://opentdb.com/api.php?amount=10").text data = json.loads(response) @@ -34,7 +40,7 @@ def get_questions(self): return None # Parse each into a `Question` class and store it in a list. - return [OpenTDB.Question(**k) for k in data['results']] + return [OpenTDB.Question(**k) for k in data["results"]] def get_random(self): question_list = self.get_questions() @@ -55,7 +61,7 @@ def get_random(self): class TriviaPluginConfig(Config): - mode = 'command' + mode = "command" lock = False @@ -74,10 +80,10 @@ class TriviaPlugin(Plugin): def load(self, ctx): super(TriviaPlugin, self).load(ctx) self.otd = OpenTDB() - self.active_servers = ctx.get('active_servers', {}) + self.active_servers = ctx.get("active_servers", {}) def unload(self, ctx): - ctx['active_servers'] = self.active_servers + ctx["active_servers"] = self.active_servers super(TriviaPlugin, self).unload(ctx) @Plugin.pre_command() @@ -93,7 +99,7 @@ def on_pre_command(self, command, event, _par, _brack): return event def generate_embed(self, question): - desc = '' + desc = "" count = 1 for answer in question.answers: @@ -102,25 +108,39 @@ def generate_embed(self, question): embed = MessageEmbed() embed.description = desc - embed.set_footer(text=f"Difficulty: {question.difficulty} | {question.category}") - embed.color = 0x9300ff + embed.set_footer( + text=f"Difficulty: {question.difficulty} | {question.category}" + ) + embed.color = 0x9300FF return embed - @Plugin.command('trivia', parser=True) - @Plugin.parser.add_argument('-h', action='store_true', help='Shows help') - @Plugin.parser.add_argument('-m', action='store_true', help='Gets current trivia mode') - @Plugin.parser.add_argument('-l', action='store_true', help='Gets current lock status') - @Plugin.parser.add_argument('--mode', help='Sets the current trivia mode', required=False) - @Plugin.parser.add_argument('--lock', help='User-lock trivia questions', required=False) + @Plugin.command("trivia", parser=True) + @Plugin.parser.add_argument("-h", action="store_true", help="Shows help") + @Plugin.parser.add_argument( + "-m", action="store_true", help="Gets current trivia mode" + ) + @Plugin.parser.add_argument( + "-l", action="store_true", help="Gets current lock status" + ) + @Plugin.parser.add_argument( + "--mode", help="Sets the current trivia mode", required=False + ) + @Plugin.parser.add_argument( + "--lock", help="User-lock trivia questions", required=False + ) def on_trivia(self, event, args): if event.author.id == 117789813427535878: if args.h: return event.msg.reply(event.parser.format_help()) if args.m: - return event.msg.reply(f"The current trivia mode is: **{self.config.mode}**") + return event.msg.reply( + f"The current trivia mode is: **{self.config.mode}**" + ) if args.l: - return event.msg.reply(f"The current lock status is: **{self.config.lock}**") + return event.msg.reply( + f"The current lock status is: **{self.config.lock}**" + ) if args.mode is not None: self.config.mode = args.mode @@ -128,7 +148,7 @@ def on_trivia(self, event, args): if args.lock is not None: isLocked = False - if args.lock == 'True': + if args.lock == "True": isLocked = True self.config.lock = isLocked @@ -137,23 +157,27 @@ def on_trivia(self, event, args): guild_id = event.msg.guild if guild_id is None: - event.msg.reply('Something went wrong') + event.msg.reply("Something went wrong") return guild_id = guild_id.id - question = self.active_servers[guild_id] if guild_id in self.active_servers else self.otd.get_random() + question = ( + self.active_servers[guild_id] + if guild_id in self.active_servers + else self.otd.get_random() + ) if guild_id not in self.active_servers: question.caller = event.author.id self.active_servers[guild_id] = question else: - event.msg.reply('There is already an active question!') + event.msg.reply("There is already an active question!") - self.log.info('Question: %s\nAnswer: %s\n', question.question, question.answer) + self.log.info("Question: %s\nAnswer: %s\n", question.question, question.answer) if question is None: - event.msg.reply('Something went wrong!') + event.msg.reply("Something went wrong!") return embed = self.generate_embed(question) @@ -161,61 +185,88 @@ def on_trivia(self, event, args): event.msg.reply(f"**{question.question}**", embed=embed) # Trivia subcommands - @Plugin.command('leaderboard', group='trivia', parser=True) - @Plugin.parser.add_argument('-g', action='store_true', help='Show global stats', required=False) + @Plugin.command("leaderboard", group="trivia", parser=True) + @Plugin.parser.add_argument( + "-g", action="store_true", help="Show global stats", required=False + ) def on_trivia_leaderboard(self, event, args): try: if args.g: - users = list(Trivia.select( - Trivia.user_id, - Trivia.correct_answers, - Trivia.incorrect_answers, - Trivia.points - ).order_by(SQL('points').desc()).limit(5).tuples()) + users = list( + Trivia.select( + Trivia.user_id, + Trivia.correct_answers, + Trivia.incorrect_answers, + Trivia.points, + ) + .order_by(SQL("points").desc()) + .limit(5) + .tuples() + ) else: - users = list(Trivia.select( - Trivia.user_id, - Trivia.correct_answers, - Trivia.incorrect_answers, - Trivia.points - ).where( - event.guild.id == Trivia.guild_id - ).order_by(SQL('points').desc()).limit(5).tuples()) + users = list( + Trivia.select( + Trivia.user_id, + Trivia.correct_answers, + Trivia.incorrect_answers, + Trivia.points, + ) + .where(event.guild.id == Trivia.guild_id) + .order_by(SQL("points").desc()) + .limit(5) + .tuples() + ) except Exception as e: print(traceback.format_exc()) - return event.msg.reply('Failed to grab leaderboard stats: ```{}```'.format(e)) - - event.msg.reply('**TOP TRIVIA EXPERTS**\n' + (len(users) > 0 and '\n'.join( - '{}. **{}** {}\n <:green_tick:435164337167138826> {} <:red_tick:435164344125489155> {}\n**{}** points'.format( # noqa - i + 1, - (self.state.users.get(row[0]) and self.state.users.get(row[0]).username or 'Invalid User'), - ':crown:' if i == 0 else '', - row[1], - row[2], - row[3] - ) for i, row in enumerate(users)) or '***No trivia stats found for this server***' - )) + return event.msg.reply( + "Failed to grab leaderboard stats: ```{}```".format(e) + ) + + event.msg.reply( + "**TOP TRIVIA EXPERTS**\n" + + ( + len(users) > 0 + and "\n".join( + "{}. **{}** {}\n <:green_tick:435164337167138826> {} <:red_tick:435164344125489155> {}\n**{}** points".format( # noqa + i + 1, + ( + self.state.users.get(row[0]) + and self.state.users.get(row[0]).username + or "Invalid User" + ), + ":crown:" if i == 0 else "", + row[1], + row[2], + row[3], + ) + for i, row in enumerate(users) + ) + or "***No trivia stats found for this server***" + ) + ) # End - @Plugin.command('answer', '') + @Plugin.command("answer", "") def on_answer(self, event, number): - if self.config.mode != 'command': - event.msg.reply('Sorry, command mode is disabled. Please just respond with the number you wish to use.') + if self.config.mode != "command": + event.msg.reply( + "Sorry, command mode is disabled. Please just respond with the number you wish to use." + ) return guild_id = event.msg.guild.id # Make sure there is an active question if guild_id not in self.active_servers: - event.msg.reply('There is not currently an active question!') + event.msg.reply("There is not currently an active question!") return question = self.active_servers[guild_id] # Check if person calling it is the one answering as well for lock - if self.config.lock == 'True' or self.config.lock: + if self.config.lock == "True" or self.config.lock: # Do checks if question.caller != event.author.id: return @@ -230,38 +281,39 @@ def on_answer(self, event, number): # Returns the created/got stats and True/False if it was created or not. trivia_stats, _created = Trivia.get_or_create( - guild_id=guild_id, - user_id=event.author.id, - defaults={ - 'correct_answers': 0, - 'incorrect_answers': 0, - 'points': 0 - } + guild_id=guild_id, + user_id=event.author.id, + defaults={"correct_answers": 0, "incorrect_answers": 0, "points": 0}, ) # Now let's check if it's right or not if question.answers[number - 1] == question.answer: - if question.difficulty == 'hard': + if question.difficulty == "hard": points_gained = 3 - elif question.difficulty == 'medium': + elif question.difficulty == "medium": points_gained = 2 else: points_gained = 1 - event.msg.reply('You got it right! Awesome job!\nYou got **{}** point(s)! You now have **{}**'.format( - points_gained, - trivia_stats.points + points_gained - )) - - Trivia.update({ - Trivia.points: Trivia.points + points_gained, - Trivia.correct_answers: Trivia.correct_answers + 1 - }).where(Trivia.user_id == event.author.id).execute() + event.msg.reply( + "You got it right! Awesome job!\nYou got **{}** point(s)! You now have **{}**".format( + points_gained, trivia_stats.points + points_gained + ) + ) + + Trivia.update( + { + Trivia.points: Trivia.points + points_gained, + Trivia.correct_answers: Trivia.correct_answers + 1, + } + ).where(Trivia.user_id == event.author.id).execute() else: - event.msg.reply(f"Nope, sorry.. The correct answer was **{question.answer}**") + event.msg.reply( + f"Nope, sorry.. The correct answer was **{question.answer}**" + ) - Trivia.update({ - Trivia.incorrect_answers: Trivia.incorrect_answers + 1 - }).where(Trivia.user_id == event.author.id).execute() + Trivia.update( + {Trivia.incorrect_answers: Trivia.incorrect_answers + 1} + ).where(Trivia.user_id == event.author.id).execute() del self.active_servers[guild_id] diff --git a/serious_bot/plugins/utility.py b/serious_bot/plugins/utility.py index b67b991..c70a3e0 100644 --- a/serious_bot/plugins/utility.py +++ b/serious_bot/plugins/utility.py @@ -9,80 +9,97 @@ class UtilityPlugin(Plugin): - def load(self, ctx): self._eval = {} - self._hidden_commands = ['eval', 'update'] + self._hidden_commands = ["eval", "update"] - @Plugin.command('help') + @Plugin.command("help") def on_help(self, event): - command_list = [command for command in self.bot.commands if command.name not in self._hidden_commands] # LIST K o m p r e h e n s i o n # noqa - grouped = {'GENERAL': []} + command_list = [ + command + for command in self.bot.commands + if command.name not in self._hidden_commands + ] # LIST K o m p r e h e n s i o n # noqa + grouped = {"GENERAL": []} for command in command_list: if command.group is None: - grouped['GENERAL'].append(command.name) + grouped["GENERAL"].append(command.name) else: if grouped.get(command.group) is None: grouped[command.group] = [] grouped[command.group].append(command.name) - builder = '' + builder = "" for key, item in grouped.items(): builder += f"**{key.upper()}:**\n{', '.join(item)}\n\n" event.msg.reply(builder) - @Plugin.command('timeleft') + @Plugin.command("timeleft") def on_time_left(self, event): pfriday = tc.get_next_friday() - event.msg.reply('Time left until game night: \n\n{}'.format(pfriday)) + event.msg.reply("Time left until game night: \n\n{}".format(pfriday)) - @Plugin.command('kick', ' ', level=CommandLevels.ADMIN) + @Plugin.command("kick", " ", level=CommandLevels.ADMIN) def on_kick(self, event, user, reason): if user is None: - return event.msg.reply('Invalid User!') + return event.msg.reply("Invalid User!") try: user_dm = user.open_dm() guild_member = event.guild.members.get(user.id) - user_dm.send_message(f"You have been kicked from {event.guild.name} for **{reason}**") + user_dm.send_message( + f"You have been kicked from {event.guild.name} for **{reason}**" + ) guild_member.kick(reason=reason) except APIException as e: print(e) - return event.msg.reply('Sorry, cant do that!') + return event.msg.reply("Sorry, cant do that!") - event.msg.reply(':green_tick:') + event.msg.reply(":green_tick:") - @Plugin.command('ban', ' ', level=CommandLevels.ADMIN) + @Plugin.command("ban", " ", level=CommandLevels.ADMIN) def on_ban(self, event, user, reason): if user is None: - return event.msg.reply('Invalid user!') + return event.msg.reply("Invalid user!") try: user_dm = user.open_dm() guild_member = event.guild.members.get(user.id) - user_dm.send_message(f"You have been **banned** from {event.guild.name} for **{reason}**") + user_dm.send_message( + f"You have been **banned** from {event.guild.name} for **{reason}**" + ) guild_member.ban(0) except APIException as e: print(e) - return event.msg.reply('Sorry, cant do that!') + return event.msg.reply("Sorry, cant do that!") + + event.msg.reply(":green_tick:") + + @Plugin.command( + "hban", " [reason:str...]", level=CommandLevels.ADMIN + ) + def on_hban(self, event, user, reason="No Reason Specified"): + event.guild.create_ban(user, reason=reason) - event.msg.reply(':green_tick:') + event.msg.reply(":ok_hand:") # Level Management - THIS IS TEMPORARY! - @Plugin.command('set', ' ', group='rank', level=CommandLevels.OWNER) + @Plugin.command( + "set", " ", group="rank", level=CommandLevels.OWNER + ) def on_rank_set(self, event, user, rank): # for some reason you need all lower-case to get the enum _rank = CommandLevels.get(rank.lower()) if not _rank: - return event.msg.reply('Invalid rank') + return event.msg.reply("Invalid rank") if not user: return @@ -92,45 +109,54 @@ def on_rank_set(self, event, user, rank): if current_rank and author_rank: if current_rank > author_rank: - return event.msg.reply('Woah there! You can\'t target this person.') + return event.msg.reply("Woah there! You can't target this person.") self.bot.config.levels[user.id] = _rank event.msg.reply(f"{user.username} has been assigned '{rank}'") - @Plugin.command('list', group='rank', level=CommandLevels.OWNER) + @Plugin.command("list", group="rank", level=CommandLevels.OWNER) def on_rank_list(self, event): - event.msg.reply(', '.join([level for level in CommandLevels._attrs.keys()])) + event.msg.reply(", ".join([level for level in CommandLevels._attrs.keys()])) # Plugin reloading (and stuff) - @Plugin.command('update', level=CommandLevels.OWNER) + @Plugin.command("update", level=CommandLevels.OWNER) def on_update(self, event): - proc = subprocess.Popen('git pull origin master', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) + proc = subprocess.Popen( + "git pull origin master", + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + shell=True, + ) out, _ = proc.communicate() event.msg.reply(f"```\n{out.decode().strip()}\n```") - @Plugin.command('list', group='plugin', level=CommandLevels.OWNER) + @Plugin.command("list", group="plugin", level=CommandLevels.OWNER) def on_plugin_list(self, event): - event.msg.reply(', '.join(self.bot.plugins.keys())) + event.msg.reply(", ".join(self.bot.plugins.keys())) - @Plugin.command('reload', '', group='plugin', level=CommandLevels.OWNER) + @Plugin.command( + "reload", "", group="plugin", level=CommandLevels.OWNER + ) def on_plugin_reload(self, event, plugin_name): - if plugin_name == 'all': + if plugin_name == "all": to_reload = self.bot.plugins - del to_reload['UtilityPlugin'] + del to_reload["UtilityPlugin"] [plugin.reload() for plugin in to_reload.values()] - return event.msg.reply(':ok_hand:') + return event.msg.reply(":ok_hand:") plugin = self.bot.plugins.get(plugin_name) - if plugin is None or plugin_name == 'DefaultPlugin': + if plugin is None or plugin_name == "DefaultPlugin": return event.msg.reply(f"{plugin_name} does not exist.") plugin.reload() event.msg.reply(":ok_hand:") - @Plugin.command('unload', '', group='plugin', level=CommandLevels.OWNER) + @Plugin.command( + "unload", "", group="plugin", level=CommandLevels.OWNER + ) def on_plugin_unload(self, event, plugin_name): plugin = self.bot.plugins.get(plugin_name) @@ -140,7 +166,13 @@ def on_plugin_unload(self, event, plugin_name): self.bot.rmv_plugin(plugin.__class__) event.msg.reply(":ok_hand:") - @Plugin.command('load', '', group='plugin', level=CommandLevels.OWNER, disabled=True) + @Plugin.command( + "load", + "", + group="plugin", + level=CommandLevels.OWNER, + disabled=True, + ) def on_plugin_load(self, event, plugin_name): if self.bot.plugins.get(plugin_name) is not None: return event.msg.reply(f"{plugin_name} already exists.") @@ -158,45 +190,48 @@ def on_plugin_load(self, event, plugin_name): event.msg.reply(":ok_hand:") # E V A L - @Plugin.command('eval', '') + @Plugin.command("eval", "") def on_eval(self, event, code): if event.author.id != 117789813427535878: return - if self._eval.get('env') is None: - self._eval['env'] = {} - - self._eval['env'].update({ - 'bot': self.bot, - 'event': event, - 'client': self.bot.client, - 'message': event.msg, - 'channel': event.msg.channel, - 'guild': event.msg.guild, - 'author': event.author, - }) - - code = code.replace('```py\n', '').replace('```', '').replace('`', '') - _code = 'def func(self):\n try:\n{}\n finally:\n self._eval[\'env\'].update(locals())'\ - .format(textwrap.indent(code, ' ')) + if self._eval.get("env") is None: + self._eval["env"] = {} + + self._eval["env"].update( + { + "bot": self.bot, + "event": event, + "client": self.bot.client, + "message": event.msg, + "channel": event.msg.channel, + "guild": event.msg.guild, + "author": event.author, + } + ) + + code = code.replace("```py\n", "").replace("```", "").replace("`", "") + _code = "def func(self):\n try:\n{}\n finally:\n self._eval['env'].update(locals())".format( + textwrap.indent(code, " ") + ) try: - exec(_code, self._eval['env']) + exec(_code, self._eval["env"]) - func = self._eval['env']['func'] + func = self._eval["env"]["func"] output = func(self) if output is not None: output = repr(output) else: - output = 'No output' + output = "No output" except Exception as e: output = str(e) - message = '```\n{}```'.format(output) + message = "```\n{}```".format(output) if len(message) > 2000: - message = message[:1980] + '... (truncated)' + message = message[:1980] + "... (truncated)" event.msg.reply(message) diff --git a/serious_bot/plugins/utils/reddit_scraper.py b/serious_bot/plugins/utils/reddit_scraper.py index 3c1f4e6..5a863e8 100644 --- a/serious_bot/plugins/utils/reddit_scraper.py +++ b/serious_bot/plugins/utils/reddit_scraper.py @@ -4,20 +4,19 @@ class Reddit: - class Post: # TODO: Do something with the author and such... def __init__(self, data): - self.author = data['author'] - self.nsfw = data['over_18'] - self.url = data['url'] + self.author = data["author"] + self.nsfw = data["over_18"] + self.url = data["url"] self.permalink = f"https://www.reddit.com{data['permalink']}" - self.title = data['title'] + self.title = data["title"] def __init__(self, sub, limit=100): self.url = f"https://www.reddit.com/r/{sub}/.json?limit={limit}" self.headers = { # *groan* - 'User-Agent': 'Linux:SeriousBot:v1.0.0 (by /u/ThePixeLatedCoder)' + "User-Agent": "Linux:SeriousBot:v1.0.0 (by /u/ThePixeLatedCoder)" } def scrape_posts(self): @@ -28,10 +27,14 @@ def scrape_posts(self): return [] # what a hacky way to do this... kms - return [Reddit.Post(k['data']) for k in data['data']['children'] if ~k['data']['url'].endswith('/')] + return [ + Reddit.Post(k["data"]) + for k in data["data"]["children"] + if ~k["data"]["url"].endswith("/") + ] def random_post(self, posts): if len(posts) == 0: - return '' + return "" return random.choice(posts) diff --git a/serious_bot/plugins/utils/roast.py b/serious_bot/plugins/utils/roast.py index 83032b1..e3e5ce6 100644 --- a/serious_bot/plugins/utils/roast.py +++ b/serious_bot/plugins/utils/roast.py @@ -4,18 +4,17 @@ class Roast: - def __init__(self): - self.url = 'http://www.gotlines.com/insults/{}' + self.url = "http://www.gotlines.com/insults/{}" self.max_pages = 5 def get_html(self, page=1): return requests.get(self.url.format(page)).text def parse_data(self, html): - parser = BeautifulSoup(html, 'html.parser') + parser = BeautifulSoup(html, "html.parser") - return parser.find_all('span', {'class': 'linetext'}) + return parser.find_all("span", {"class": "linetext"}) def get_random(self): random_page = random.randint(1, self.max_pages) diff --git a/serious_bot/plugins/utils/time_convert.py b/serious_bot/plugins/utils/time_convert.py index fdd82f4..6574e0c 100644 --- a/serious_bot/plugins/utils/time_convert.py +++ b/serious_bot/plugins/utils/time_convert.py @@ -9,34 +9,41 @@ def next_weekday(d, weekday, time): dr = d.replace(hour=time[0], minute=time[1], second=time[2]) delta = dr - d - hours, minutes, seconds = (delta.seconds // 3600, (delta.seconds // 60) % 60, (delta.seconds) % 60) + hours, minutes, seconds = ( + delta.seconds // 3600, + (delta.seconds // 60) % 60, + (delta.seconds) % 60, + ) days_ahead = weekday - d.weekday() - if days_ahead < 0 or (delta.days < 0 or (hours >= time[0] and minutes >= time[1] and seconds >= time[2])): + if days_ahead < 0 or ( + delta.days < 0 + or (hours >= time[0] and minutes >= time[1] and seconds >= time[2]) + ): # It's for sure past the day, let's move on. days_ahead += 6 return { - 'delta': delta, - 'time_data': [days_ahead, hours, minutes, seconds], - 'next_date': (dr + datetime.timedelta(days_ahead)) + "delta": delta, + "time_data": [days_ahead, hours, minutes, seconds], + "next_date": (dr + datetime.timedelta(days_ahead)), } def get_next_friday(): next_data = next_weekday(datetime.datetime.utcnow(), 4, [21, 0, 0]) - time_data = next_data['time_data'] + time_data = next_data["time_data"] if len(time_data) < 4: - return 'Error getting time!' + return "Error getting time!" - return '{} day{}, {} hour{}, {} minute{}, {} second{}'.format( + return "{} day{}, {} hour{}, {} minute{}, {} second{}".format( time_data[0], - 's' if time_data[0] != 1 else '', # THIS + "s" if time_data[0] != 1 else "", # THIS time_data[1], - 's' if time_data[1] != 1 else '', # IS + "s" if time_data[1] != 1 else "", # IS time_data[2], - 's' if time_data[2] != 1 else '', # A + "s" if time_data[2] != 1 else "", # A time_data[3], - 's' if time_data[3] != 1 else '' # MEME + "s" if time_data[3] != 1 else "", # MEME )