From be13d0f686dcbddfd217a9464ed361cd0b2df4d9 Mon Sep 17 00:00:00 2001 From: aikaterna Date: Wed, 8 Aug 2018 21:54:06 -0700 Subject: [PATCH] [V3] Cleanup --- away/away.py | 42 ++++---- away/info.json | 5 +- blurplefy/blurplefy.py | 208 +++++++++++++++++++++++++-------------- blurplefy/info.json | 22 +++++ chatchart/chatchart.py | 91 ++++++++++++----- chatchart/info.json | 8 +- dungeon/dungeon.py | 21 +++- dungeon/info.json | 19 ++++ info.json | 12 +-- inspirobot/info.json | 16 +++ inspirobot/inspirobot.py | 10 +- partycrash/info.json | 15 +++ pingtime/info.json | 13 +++ pingtime/pingtime.py | 3 +- retrosign/info.json | 19 ++++ retrosign/retrosign.py | 2 +- rndstatus/info.json | 12 +++ seen/info.json | 7 +- seen/seen.py | 35 ++++--- wolfram/info.json | 12 +++ wolfram/wolfram.py | 34 +++---- 21 files changed, 431 insertions(+), 175 deletions(-) create mode 100644 blurplefy/info.json create mode 100644 dungeon/info.json create mode 100644 inspirobot/info.json create mode 100644 partycrash/info.json create mode 100644 pingtime/info.json create mode 100644 retrosign/info.json create mode 100644 rndstatus/info.json create mode 100644 wolfram/info.json diff --git a/away/away.py b/away/away.py index 17b77cd..f836061 100644 --- a/away/away.py +++ b/away/away.py @@ -8,12 +8,8 @@ from redbot.core.bot import Red class Away: """Le away cog""" - default_global_settings = { - "ign_servers": [] - } - default_user_settings = { - "MESSAGE": False - } + default_global_settings = {"ign_servers": []} + default_user_settings = {"MESSAGE": False} def __init__(self, bot: Red): self.bot = bot @@ -36,20 +32,30 @@ class Away: test = await self._away.user(author).MESSAGE() if test: try: - avatar = author.avatar_url if author.avatar else author.default_avatar_url + avatar = ( + author.avatar_url if author.avatar else author.default_avatar_url + ) if test: em = discord.Embed(description=test, color=discord.Color.blue()) - em.set_author(name='{} is currently away'.format(author.display_name), icon_url=avatar) + em.set_author( + name="{} is currently away".format(author.display_name), + icon_url=avatar, + ) else: em = discord.Embed(color=discord.Color.blue()) - em.set_author(name='{} is currently away'.format(author.display_name), icon_url=avatar) + em.set_author( + name="{} is currently away".format(author.display_name), + icon_url=avatar, + ) await message.channel.send(embed=em) except: if test: - msg = '{} is currently away and has set the following message: `{}`'.format(author.display_name, test) + msg = "{} is currently away and has set the following message: `{}`".format( + author.display_name, test + ) else: - msg = '{} is currently away'.format(author.display_name) + msg = "{} is currently away".format(author.display_name) await message.channel.send(msg) @commands.command(name="away") @@ -59,14 +65,16 @@ class Away: mess = await self._away.user(author).MESSAGE() if mess: await self._away.user(author).clear() - msg = 'You\'re now back.' + msg = "You're now back." else: length = len(str(message)) if length < 256 and length > 2: - await self._away.user(author).MESSAGE.set(' '.join(ctx.message.clean_content.split()[1:])) + await self._away.user(author).MESSAGE.set( + " ".join(ctx.message.clean_content.split()[1:]) + ) else: - await self._away.user(author).MESSAGE.set(' ') - msg = 'You\'re now set as away.' + await self._away.user(author).MESSAGE.set(" ") + msg = "You're now set as away." await ctx.send(msg) @commands.command(name="toggleaway") @@ -78,10 +86,10 @@ class Away: guilds = await self._away.ign_servers() guilds.remove(guild.id) await self._away.ign_servers.set(guilds) - message = 'Not ignoring this guild anymore.' + message = "Not ignoring this guild anymore." else: guilds = await self._away.ign_servers() guilds.append(guild.id) await self._away.ign_servers.set(guilds) - message = 'Ignoring this guild.' + message = "Ignoring this guild." await ctx.send(message) diff --git a/away/info.json b/away/info.json index 8e5140d..7df0c18 100644 --- a/away/info.json +++ b/away/info.json @@ -1,8 +1,9 @@ { "author": [ - "Axas and aikaterna" + "aikaterna", + "Axas" ], - "description": "Set and unset a user as being away.", + "description": "Set and unset a user as being away. Originally by Paddo.", "short": "Away message toggle for users", "tags": [ "away" diff --git a/blurplefy/blurplefy.py b/blurplefy/blurplefy.py index 41a71c7..0df6e87 100644 --- a/blurplefy/blurplefy.py +++ b/blurplefy/blurplefy.py @@ -27,10 +27,7 @@ class Blurplefy: self.bot = bot self.config = Config.get_conf(self, 2778931480, force_registration=True) - default_guild = { - "role_enabled": False, - "blurple_role": None - } + default_guild = {"role_enabled": False, "blurple_role": None} self.config.register_guild(**default_guild) self.session = aiohttp.ClientSession() @@ -42,27 +39,30 @@ class Blurplefy: """Toggle a role award for having a blurple profile picture.""" blurple_role_id = await self.config.guild(ctx.guild).blurple_role() if blurple_role_id is None: - await ctx.send('Enter the role name to award: it needs to be a valid, already existing role.') + await ctx.send( + "Enter the role name to award: it needs to be a valid, already existing role." + ) def check(m): return m.author == ctx.author try: - blurple_role = await ctx.bot.wait_for('message', timeout=15.0, check=check) + blurple_role = await ctx.bot.wait_for("message", timeout=15.0, check=check) blurple_role_obj = discord.utils.get(ctx.guild.roles, name=blurple_role.content) if blurple_role_obj is None: - return await ctx.send('No role with that name.') - await ctx.invoke(self.blurpleroleset, blurple_role_obj) + return await ctx.send("No role with that name.") + return await ctx.invoke(self.blurpleroleset, role_name=blurple_role_obj) except asyncio.TimeoutError: - return await ctx.send('No role entered, try again later.') + return await ctx.send("No role entered, try again later.") role_enabled = await self.config.guild(ctx.guild).role_enabled() await self.config.guild(ctx.guild).role_enabled.set(not role_enabled) + if not role_enabled: - word = 'enabled' + word = "enabled" else: - word = 'disabled' - await ctx.send('Blurple role awarding {}.'.format(word)) + word = "disabled" + await ctx.send("Blurple role awarding {}.".format(word)) @commands.guild_only() @commands.command() @@ -72,15 +72,15 @@ class Blurplefy: await self.config.guild(ctx.guild).blurple_role.set(role_name.id) blurple_role_id = await self.config.guild(ctx.guild).blurple_role() blurple_role_obj = discord.utils.get(ctx.guild.roles, id=blurple_role_id) - await ctx.send('Blurple award role set to: {}.'.format(blurple_role_obj.name)) + await ctx.send("Blurple award role set to: {}.".format(blurple_role_obj.name)) blurple_role_enabled = await self.config.guild(ctx.guild).role_enabled() if not blurple_role_enabled: await ctx.invoke(self.blurplerole) - async def blurplefy(self, ctx, user: discord.Member=None): + async def blurplefy(self, ctx, user: discord.Member = None): """Blurplefy a user or image.""" picture = None - await ctx.send('{}, starting blurple image analysis.'.format(ctx.message.author.mention)) + await ctx.send("{}, starting blurple image analysis.".format(ctx.message.author.mention)) link = ctx.message.attachments if user is None and not link: picture = ctx.author.avatar_url @@ -92,19 +92,19 @@ class Blurplefy: else: picture = user.avatar_url try: - async with self.session.request('GET', picture) as r: + async with self.session.request("GET", picture) as r: response = await r.read() except ValueError: - await ctx.send('{}, please link a valid image URL.'.format(ctx.author.display_name)) + await ctx.send("{}, please link a valid image URL.".format(ctx.author.display_name)) return @commands.guild_only() @commands.command() @commands.cooldown(rate=1, per=30, type=BucketType.user) - async def blurple(self, ctx, user: discord.Member=None): + async def blurple(self, ctx, user: discord.Member = None): """Check a user or uploaded image for blurple content.""" picture = None - await ctx.send('{}, starting blurple image analysis.'.format(ctx.message.author.mention)) + await ctx.send("{}, starting blurple image analysis.".format(ctx.message.author.mention)) link = ctx.message.attachments if user is None and not link: picture = ctx.author.avatar_url @@ -119,46 +119,68 @@ class Blurplefy: role_check = False try: - async with self.session.request('GET', picture) as r: + async with self.session.request("GET", picture) as r: response = await r.read() except ValueError: - await ctx.send('{}, please link a valid image URL.'.format(ctx.author.display_name)) + await ctx.send("{}, please link a valid image URL.".format(ctx.author.display_name)) return try: im = Image.open(BytesIO(response)) except Exception: - await ctx.send('{}, please link a valid image URL.'.format(ctx.author.display_name)) + await ctx.send("{}, please link a valid image URL.".format(ctx.author.display_name)) return - im = im.convert('RGBA') + im = im.convert("RGBA") imsize = list(im.size) - impixels = imsize[0]*imsize[1] + impixels = imsize[0] * imsize[1] # 1250x1250 = 1562500 maxpixelcount = 1562500 if impixels > maxpixelcount: - downsizefraction = math.sqrt(maxpixelcount/impixels) - im = resizeimage.resize_width(im, (imsize[0]*downsizefraction)) + downsizefraction = math.sqrt(maxpixelcount / impixels) + im = resizeimage.resize_width(im, (imsize[0] * downsizefraction)) imsize = list(im.size) - impixels = imsize[0]*imsize[1] - await ctx.send('{}, image resized smaller for easier processing.'.format(ctx.message.author.display_name)) + impixels = imsize[0] * imsize[1] + await ctx.send( + "{}, image resized smaller for easier processing.".format( + ctx.message.author.display_name + ) + ) image = self.blurple_imager(im, imsize) - image = discord.File(fp=image, filename='image.png') + image = discord.File(fp=image, filename="image.png") - blurplenesspercentage = round(((nooftotalpixels/noofpixels)*100), 2) - percentblurple = round(((noofblurplepixels/noofpixels)*100), 2) - percentdblurple = round(((noofdarkblurplepixels/noofpixels)*100), 2) - percentwhite = round(((noofwhitepixels/noofpixels)*100), 2) + blurplenesspercentage = round(((nooftotalpixels / noofpixels) * 100), 2) + percentblurple = round(((noofblurplepixels / noofpixels) * 100), 2) + percentdblurple = round(((noofdarkblurplepixels / noofpixels) * 100), 2) + percentwhite = round(((noofwhitepixels / noofpixels) * 100), 2) - embed = discord.Embed(title='', colour=0x7289DA) - embed.add_field(name='Total amount of Blurple', value='{}%'.format(blurplenesspercentage), inline=False) - embed.add_field(name='Blurple (rgb(114, 137, 218))', value='{}%'.format(percentblurple), inline=True) - embed.add_field(name='White (rgb(255, 255, 255))', value='{}\%'.format(percentwhite), inline=True) - embed.add_field(name='Dark Blurple (rgb(78, 93, 148))', value='{}\%'.format(percentdblurple), inline=True) - embed.add_field(name='Guide', value='Blurple, White, Dark Blurple = \nBlurple, White, and Dark Blurple (respectively) \nBlack = Not Blurple, White, or Dark Blurple', inline=False) - embed.set_footer(text='Please note: Discord slightly reduces quality of the images, therefore the percentages may be slightly inaccurate. | Content requested by {}'.format(ctx.author)) - embed.set_image(url='attachment://image.png') + embed = discord.Embed(title="", colour=0x7289DA) + embed.add_field( + name="Total amount of Blurple", value="{}%".format(blurplenesspercentage), inline=False + ) + embed.add_field( + name="Blurple (rgb(114, 137, 218))", value="{}%".format(percentblurple), inline=True + ) + embed.add_field( + name="White (rgb(255, 255, 255))", value="{}\%".format(percentwhite), inline=True + ) + embed.add_field( + name="Dark Blurple (rgb(78, 93, 148))", + value="{}\%".format(percentdblurple), + inline=True, + ) + embed.add_field( + name="Guide", + value="Blurple, White, Dark Blurple = \nBlurple, White, and Dark Blurple (respectively) \nBlack = Not Blurple, White, or Dark Blurple", + inline=False, + ) + embed.set_footer( + text="Please note: Discord slightly reduces quality of the images, therefore the percentages may be slightly inaccurate. | Content requested by {}".format( + ctx.author + ) + ) + embed.set_image(url="attachment://image.png") embed.set_thumbnail(url=picture) await ctx.send(embed=embed, file=image) @@ -166,16 +188,29 @@ class Blurplefy: if role_check and blurple_role_enabled: blurple_role_id = await self.config.guild(ctx.guild).blurple_role() blurple_role_obj = discord.utils.get(ctx.guild.roles, id=blurple_role_id) - if blurplenesspercentage > 75 and picture == ctx.author.avatar_url and blurple_role_obj not in ctx.author.roles and percentblurple > 5: - await ctx.send('{}, as your profile pic has enough blurple (over 75% in total and over 5% blurple), you have recieved the role **{}**!'.format(ctx.message.author.display_name, blurple_role_obj.name)) + if ( + blurplenesspercentage > 75 + and picture == ctx.author.avatar_url + and blurple_role_obj not in ctx.author.roles + and percentblurple > 5 + ): + await ctx.send( + "{}, as your profile pic has enough blurple (over 75% in total and over 5% blurple), you have recieved the role **{}**!".format( + ctx.message.author.display_name, blurple_role_obj.name + ) + ) await ctx.author.add_roles(blurple_role_obj) elif picture == ctx.author.avatar_url and blurple_role_obj not in ctx.author.roles: - await ctx.send('{}, your profile pic does not have enough blurple (over 75% in total and over 5% blurple), therefore you are not eligible for the role {}.'.format(ctx.message.author.display_name, blurple_role_obj.name)) + await ctx.send( + "{}, your profile pic does not have enough blurple (over 75% in total and over 5% blurple), therefore you are not eligible for the role {}.".format( + ctx.message.author.display_name, blurple_role_obj.name + ) + ) @commands.guild_only() @commands.command() @commands.cooldown(rate=1, per=30, type=BucketType.user) - async def blurplefy(self, ctx, user: discord.Member=None): + async def blurplefy(self, ctx, user: discord.Member = None): """Blurplefy a user or uploaded image.""" picture = None await ctx.send("{}, starting blurple image analysis.".format(ctx.message.author.mention)) @@ -190,7 +225,7 @@ class Blurplefy: else: picture = user.avatar_url try: - async with self.session.request('GET', picture) as r: + async with self.session.request("GET", picture) as r: response = await r.read() except ValueError: await ctx.send("{}, please link a valid image URL.".format(ctx.author.display_name)) @@ -202,7 +237,7 @@ class Blurplefy: return imsize = list(im.size) - impixels = imsize[0]*imsize[1] + impixels = imsize[0] * imsize[1] # 1250x1250 = 1562500 maxpixelcount = 1562500 @@ -213,14 +248,20 @@ class Blurplefy: except Exception: isgif = False - await ctx.send('{}, image fetched, analyzing image...'.format(ctx.message.author.display_name)) + await ctx.send( + "{}, image fetched, analyzing image...".format(ctx.message.author.display_name) + ) if impixels > maxpixelcount: - downsizefraction = math.sqrt(maxpixelcount/impixels) - im = resizeimage.resize_width(im, (imsize[0]*downsizefraction)) + downsizefraction = math.sqrt(maxpixelcount / impixels) + im = resizeimage.resize_width(im, (imsize[0] * downsizefraction)) imsize = list(im.size) - impixels = imsize[0]*imsize[1] - await ctx.send('{}, image resized smaller for easier processing'.format(ctx.message.author.display_name)) + impixels = imsize[0] * imsize[1] + await ctx.send( + "{}, image resized smaller for easier processing".format( + ctx.message.author.display_name + ) + ) if isgif is False: image = self.imager(im, imsize) @@ -228,9 +269,9 @@ class Blurplefy: image = self.gifimager(im, gifloop, imsize) await ctx.send("{}, image data extracted.".format(ctx.author.display_name)) if isgif is False: - image = discord.File(fp=image, filename='image.png') + image = discord.File(fp=image, filename="image.png") else: - image = discord.File(fp=image, filename='image.gif') + image = discord.File(fp=image, filename="image.gif") try: embed = discord.Embed(title="", colour=0x7289DA) @@ -239,11 +280,19 @@ class Blurplefy: embed.set_image(url="attachment://image.png") else: embed.set_image(url="attachment://image.gif") - embed.set_footer(text="Please note - This blurplefier is automated and therefore may not always give you the best result. | Content requested by {}".format(ctx.author)) + embed.set_footer( + text="Please note - This blurplefier is automated and therefore may not always give you the best result. | Content requested by {}".format( + ctx.author + ) + ) embed.set_thumbnail(url=picture) await ctx.send(embed=embed, file=image) except Exception: - await ctx.send("{}, whoops! It looks like this gif is too big to upload. Try a smaller image (less than 8mb).".format(ctx.author.name)) + await ctx.send( + "{}, whoops! It looks like this gif is too big to upload. Try a smaller image (less than 8mb).".format( + ctx.author.name + ) + ) @staticmethod def blurple_imager(im, imsize): @@ -273,11 +322,13 @@ class Blurplefy: checkwhite = 1 checkdarkblurple = 1 for i in range(3): - if not(blurple[i]+colourbuffer > pixel[i] > blurple[i]-colourbuffer): + if not (blurple[i] + colourbuffer > pixel[i] > blurple[i] - colourbuffer): checkblurple = 0 - if not(darkblurple[i]+colourbuffer > pixel[i] > darkblurple[i]-colourbuffer): + if not ( + darkblurple[i] + colourbuffer > pixel[i] > darkblurple[i] - colourbuffer + ): checkdarkblurple = 0 - if not(white[i]+colourbuffer > pixel[i] > white[i]-colourbuffer): + if not (white[i] + colourbuffer > pixel[i] > white[i] - colourbuffer): checkwhite = 0 if checkblurple == 0 and checkdarkblurple == 0 and checkwhite == 0: check = 0 @@ -294,28 +345,28 @@ class Blurplefy: noofpixels += 1 image_file_object = io.BytesIO() - im.save(image_file_object, format='png') + im.save(image_file_object, format="png") image_file_object.seek(0) return image_file_object @staticmethod def imager(im, imsize): - im = im.convert(mode='L') + im = im.convert(mode="L") im = ImageEnhance.Contrast(im).enhance(1000) - im = im.convert(mode='RGB') + im = im.convert(mode="RGB") img = im.load() - for x in range(imsize[0]-1): + for x in range(imsize[0] - 1): i = 1 - for y in range(imsize[1]-1): + for y in range(imsize[1] - 1): pixel = img[x, y] if pixel != (255, 255, 255): img[x, y] = (114, 137, 218) image_file_object = io.BytesIO() - im.save(image_file_object, format='png') + im.save(image_file_object, format="png") image_file_object.seek(0) return image_file_object @@ -325,9 +376,9 @@ class Blurplefy: newgif = [] for frame in frames: - frame = frame.convert(mode='L') + frame = frame.convert(mode="L") frame = ImageEnhance.Contrast(frame).enhance(1000) - frame = frame.convert(mode='RGB') + frame = frame.convert(mode="RGB") img = frame.load() for x in range(imsize[0]): @@ -340,7 +391,7 @@ class Blurplefy: image_file_object = io.BytesIO() gif = newgif[0] - gif.save(image_file_object, format='gif', save_all=True, append_images=newgif[1:], loop=0) + gif.save(image_file_object, format="gif", save_all=True, append_images=newgif[1:], loop=0) image_file_object.seek(0) return image_file_object @@ -348,12 +399,23 @@ class Blurplefy: async def countdown(self, ctx): """Countdown to Discord's 4th Anniversary.""" embed = discord.Embed(name="", colour=0x7289da) - timeleft = datetime.datetime(2018, 5, 13) + datetime.timedelta(hours=7) - datetime.datetime.utcnow() - embed.set_author(name='Time left until Discord\'s 4th Anniversary') + timeleft = ( + datetime.datetime(2018, 5, 13) + + datetime.timedelta(hours=7) + - datetime.datetime.utcnow() + ) + embed.set_author(name="Time left until Discord's 4th Anniversary") if int(timeleft.total_seconds()) < 0: - timeleft = datetime.datetime(2019, 5, 13) + datetime.timedelta(hours=7) - datetime.datetime.utcnow() - embed.set_author(name='Time left until Discord\'s 4th Anniversary') - embed.add_field(name='Countdown to midnight, May 13, California time (UTC-7):', value=('{}'.format(self._dynamic_time(int(timeleft.total_seconds()))))) + timeleft = ( + datetime.datetime(2019, 5, 13) + + datetime.timedelta(hours=7) + - datetime.datetime.utcnow() + ) + embed.set_author(name="Time left until Discord's 4th Anniversary") + embed.add_field( + name="Countdown to midnight, May 13, California time (UTC-7):", + value=("{}".format(self._dynamic_time(int(timeleft.total_seconds())))), + ) await ctx.send(embed=embed) @staticmethod diff --git a/blurplefy/info.json b/blurplefy/info.json new file mode 100644 index 0000000..4f59f01 --- /dev/null +++ b/blurplefy/info.json @@ -0,0 +1,22 @@ +{ + "author": [ + "aikaterna" + ], + "description": "Blurplefy a user profile picture or image. Admins can configure an awardable role if a user's profile pic has more than a certain percentage of blurple in it.", + "install_msg": "Thanks for installing, have fun.", + "permissions" : [ + "embed_links", + "manage_roles" + ], + "requirements": [ + "pillow", + "python-resize-image" + ], + "short": "Blurplefy a user profile picture or image.", + "tags": [ + "blurple", + "image", + "profile" + ], + "type": "COG" +} \ No newline at end of file diff --git a/chatchart/chatchart.py b/chatchart/chatchart.py index 5855cf8..57b8fb5 100644 --- a/chatchart/chatchart.py +++ b/chatchart/chatchart.py @@ -1,6 +1,6 @@ # Lines 72 through 90 are influenced heavily by cacobot's stats module: # https://github.com/Orangestar12/cacobot/blob/master/cacobot/stats.py -# Big thanks to Redjumpman for changing the beta version from +# Big thanks to Redjumpman for changing the beta version from # Imagemagick/cairosvg to matplotlib. # Thanks to violetnyte for suggesting this cog. import discord @@ -8,9 +8,11 @@ import heapq import os from io import BytesIO import matplotlib -matplotlib.use('agg') + +matplotlib.use("agg") import matplotlib.pyplot as plt -plt.switch_backend('agg') + +plt.switch_backend("agg") from discord.ext import commands @@ -28,34 +30,63 @@ class Chatchart: sizes = sizes + [others] labels = labels + ["Others {:g}%".format(others)] if len(channel.name) >= 19: - channel_name = '{}...'.format(channel.name[:19]) + channel_name = "{}...".format(channel.name[:19]) else: channel_name = channel.name title = plt.title("Stats in #{}".format(channel_name), color="white") title.set_va("top") title.set_ha("center") plt.gca().axis("equal") - colors = ['r', 'darkorange', 'gold', 'y', 'olivedrab', 'green', 'darkcyan', 'mediumblue', 'darkblue', 'blueviolet', 'indigo', 'orchid', 'mediumvioletred', 'crimson', 'chocolate', 'yellow', 'limegreen','forestgreen','dodgerblue','slateblue','gray'] + colors = [ + "r", + "darkorange", + "gold", + "y", + "olivedrab", + "green", + "darkcyan", + "mediumblue", + "darkblue", + "blueviolet", + "indigo", + "orchid", + "mediumvioletred", + "crimson", + "chocolate", + "yellow", + "limegreen", + "forestgreen", + "dodgerblue", + "slateblue", + "gray", + ] pie = plt.pie(sizes, colors=colors, startangle=0) - plt.legend(pie[0], labels, bbox_to_anchor=(0.7, 0.5), loc="center", fontsize=10, - bbox_transform=plt.gcf().transFigure, facecolor='#ffffff') + plt.legend( + pie[0], + labels, + bbox_to_anchor=(0.7, 0.5), + loc="center", + fontsize=10, + bbox_transform=plt.gcf().transFigure, + facecolor="#ffffff", + ) plt.subplots_adjust(left=0.0, bottom=0.1, right=0.45) image_object = BytesIO() - plt.savefig(image_object, format='PNG', facecolor='#36393E') + plt.savefig(image_object, format="PNG", facecolor="#36393E") image_object.seek(0) return image_object @commands.guild_only() @commands.command() @commands.cooldown(1, 10, commands.BucketType.channel) - async def chatchart(self, ctx, channel: discord.TextChannel=None, messages=5000): + async def chatchart(self, ctx, channel: discord.TextChannel = None, messages=5000): """ Generates a pie chart, representing the last 5000 messages in the specified channel. """ e = discord.Embed(description="Loading...", colour=0x00ccff) e.set_thumbnail(url="https://i.imgur.com/vSp4xRk.gif") em = await ctx.send(embed=e) - + if channel is None: channel = ctx.message.channel history = [] @@ -68,33 +99,39 @@ class Chatchart: except discord.errors.Forbidden: await em.delete() return await ctx.send("No permissions to read that channel.") - msg_data = {'total count': 0, 'users': {}} + msg_data = {"total count": 0, "users": {}} for msg in history: if len(msg.author.name) >= 20: - short_name = '{}...'.format(msg.author.name[:20]) + short_name = "{}...".format(msg.author.name[:20]) else: short_name = msg.author.name - whole_name = '{}#{}'.format(short_name, msg.author.discriminator) + whole_name = "{}#{}".format(short_name, msg.author.discriminator) if msg.author.bot: pass - elif whole_name in msg_data['users']: - msg_data['users'][whole_name]['msgcount'] += 1 - msg_data['total count'] += 1 + elif whole_name in msg_data["users"]: + msg_data["users"][whole_name]["msgcount"] += 1 + msg_data["total count"] += 1 else: - msg_data['users'][whole_name] = {} - msg_data['users'][whole_name]['msgcount'] = 1 - msg_data['total count'] += 1 + msg_data["users"][whole_name] = {} + msg_data["users"][whole_name]["msgcount"] = 1 + msg_data["total count"] += 1 - for usr in msg_data['users']: - pd = float(msg_data['users'][usr]['msgcount']) / float(msg_data['total count']) - msg_data['users'][usr]['percent'] = round(pd * 100, 1) + for usr in msg_data["users"]: + pd = float(msg_data["users"][usr]["msgcount"]) / float(msg_data["total count"]) + msg_data["users"][usr]["percent"] = round(pd * 100, 1) - top_ten = heapq.nlargest(20, [(x, msg_data['users'][x][y]) - for x in msg_data['users'] - for y in msg_data['users'][x] - if y == 'percent'], key=lambda x: x[1]) + top_ten = heapq.nlargest( + 20, + [ + (x, msg_data["users"][x][y]) + for x in msg_data["users"] + for y in msg_data["users"][x] + if y == "percent" + ], + key=lambda x: x[1], + ) others = 100 - sum(x[1] for x in top_ten) img = self.create_chart(top_ten, others, channel) await em.delete() - await ctx.message.channel.send(file=discord.File(img, 'chart.png')) + await ctx.message.channel.send(file=discord.File(img, "chart.png")) diff --git a/chatchart/info.json b/chatchart/info.json index 1af67b8..42427fe 100644 --- a/chatchart/info.json +++ b/chatchart/info.json @@ -1,14 +1,18 @@ { "author": [ - "Redjumpman and aikaterna" + "aikaterna", + "Redjumpman" ], "description": "Generate a pie chart from the last 5000 messages in a channel to see who's been talking the most.", + "install_msg": "Thanks for installing, have fun.", "short": "Generate a pie chart from the last 5000 messages", "tags": [ "data", "chart", "activity" ], - "requirements": ["matplotlib"], + "requirements": [ + "matplotlib" + ], "type": "COG" } \ No newline at end of file diff --git a/dungeon/dungeon.py b/dungeon/dungeon.py index f8034dd..1120547 100644 --- a/dungeon/dungeon.py +++ b/dungeon/dungeon.py @@ -66,13 +66,16 @@ class Dungeon: blacklist_msg = ", blacklisted from the bot," else: blacklist_msg = "" - msg = f"{user} has been sent to the dungeon{blacklist_msg} and has had all previous roles stripped." + msg = ( + f"{user} has been sent to the dungeon{blacklist_msg} and has had all previous roles stripped." + ) await ctx.send(msg) @commands.group(autohelp=True) @commands.guild_only() @checks.admin_or_permissions(manage_server=True) async def dungeon(self, ctx): + """Main dungeon commands.""" pass @dungeon.command() @@ -233,7 +236,9 @@ class Dungeon: blacklist_msg = " and the bot blacklist" else: blacklist_msg = "" - msg = f"{user} has been removed from the dungeon{blacklist_msg} and now has the initial user role." + msg = ( + f"{user} has been removed from the dungeon{blacklist_msg} and now has the initial user role." + ) await ctx.send(msg) if dm_toggle: @@ -363,7 +368,9 @@ class Dungeon: blacklist = await self.config.guild(member.guild).auto_blacklist() dungeon_role_id = await self.config.guild(member.guild).dungeon_role() dungeon_role_obj = discord.utils.get(member.guild.roles, id=dungeon_role_id) - perm_msg = f"dungeon.py: Unable to auto-ban user, permissions needed and no announce channel set. Guild: {member.guild.id}" + perm_msg = ( + f"dungeon.py: Unable to auto-ban user, permissions needed and no announce channel set. Guild: {member.guild.id}" + ) if auto_ban: if auto_ban_msg: @@ -392,7 +399,9 @@ class Dungeon: if not mod_log: if announce_channel: - msg = f"Auto-banned new user: \n**{member}** ({member.id})\n{self._dynamic_time(int(since_join.total_seconds()))} old account" + msg = ( + f"Auto-banned new user: \n**{member}** ({member.id})\n{self._dynamic_time(int(since_join.total_seconds()))} old account" + ) return await channel_object.send(msg) else: print(perm_msg) @@ -434,7 +443,9 @@ class Dungeon: print("dungeon.py: I need permissions to manage channels and manage roles.") return - msg = f"Auto-banished new user: \n**{member}** ({member.id})\n{self._dynamic_time(int(since_join.total_seconds()))} old account" + msg = ( + f"Auto-banished new user: \n**{member}** ({member.id})\n{self._dynamic_time(int(since_join.total_seconds()))} old account" + ) if default_avatar: msg += ", no profile picture set" await channel_object.send(msg) diff --git a/dungeon/info.json b/dungeon/info.json new file mode 100644 index 0000000..75dcb9c --- /dev/null +++ b/dungeon/info.json @@ -0,0 +1,19 @@ +{ + "author": [ + "aikaterna" + ], + "description": "Provides additional raid protection for servers utilizing a welcome/rules join channel.", + "install_msg": "Please read the additional instructions at: ", + "min_python_version": [3, 6, 0], + "permissions" : [ + "ban_members", + "manage_channels", + "manage_roles" + ], + "short": "", + "tags": [ + "dungeon", + "autoban" + ], + "type": "COG" +} \ No newline at end of file diff --git a/info.json b/info.json index d80784a..45ef00d 100644 --- a/info.json +++ b/info.json @@ -1,7 +1,7 @@ { - "AUTHOR" : "aikaterna", - "INSTALL_MSG" : "Thanks for installing. Please PR any issues or code changes, I'm sure some cogs of mine will need some work.", - "NAME" : "aikaterna-cogs", - "SHORT" : "Some cogs I've mashed together while learning Python.", - "DESCRIPTION" : "Someday, this repository will have cogs that I actually wrote by myself. Until then, enjoy my learning process of taking code and modifying it." -} + "author" : "aikaterna (aikaterna#1393)", + "install_msg" : "Thanks for installing. Please submit issue reports on my repo if something's broken. You can find me in the Red servers or at the invite on my repo.", + "name" : "aikaterna-cogs", + "short" : "Utility and fun cogs", + "description" : "Cogs requested by others, personal cogs, or orphaned cogs." +} \ No newline at end of file diff --git a/inspirobot/info.json b/inspirobot/info.json new file mode 100644 index 0000000..537a8f7 --- /dev/null +++ b/inspirobot/info.json @@ -0,0 +1,16 @@ +{ + "author": [ + "aikaterna" + ], + "description": "Fetch a random 'inspiring' message from http://inspirobot.me", + "install_msg": "Thanks for installing, have fun.", + "permissions" : [ + "embed_links" + ], + "short": "Fetch 'inspiring' messages.", + "tags": [ + "inspire", + "inspirobot" + ], + "type": "COG" +} \ No newline at end of file diff --git a/inspirobot/inspirobot.py b/inspirobot/inspirobot.py index 9c6ca27..02ec853 100644 --- a/inspirobot/inspirobot.py +++ b/inspirobot/inspirobot.py @@ -2,8 +2,8 @@ import aiohttp import discord from redbot.core import commands -class Inspirobot: +class Inspirobot: def __init__(self, bot): self.bot = bot self.session = aiohttp.ClientSession() @@ -12,13 +12,15 @@ class Inspirobot: async def inspireme(self, ctx): """Fetch a random "inspirational message" from the bot.""" try: - async with self.session.request("GET", "http://inspirobot.me/api?generate=true") as page: - pic = await page.text(encoding='utf-8') + async with self.session.request( + "GET", "http://inspirobot.me/api?generate=true" + ) as page: + pic = await page.text(encoding="utf-8") em = discord.Embed() em.set_image(url=pic) await ctx.send(embed=em) except Exception as e: - await ctx.send(f"Oops, there was a problem: {e}") + await ctx.send(f"Oops, there was a problem: {e}") def __unload(self): self.session.close() diff --git a/partycrash/info.json b/partycrash/info.json new file mode 100644 index 0000000..282d6ba --- /dev/null +++ b/partycrash/info.json @@ -0,0 +1,15 @@ +{ + "author": [ + "aikaterna" + ], + "description": "Posts invites to servers, if the bot is allowed to view them. Does not generate new invites.", + "install_msg": "Thanks for installing, have fun.", + "permissions" : [ + "manage_server" + ], + "short": "Post server invites.", + "tags": [ + "invite" + ], + "type": "COG" +} \ No newline at end of file diff --git a/pingtime/info.json b/pingtime/info.json new file mode 100644 index 0000000..bb04894 --- /dev/null +++ b/pingtime/info.json @@ -0,0 +1,13 @@ +{ + "author": [ + "aikaterna" + ], + "description": "It's ping... with latency. Shows all shards.", + "install_msg": "Thanks for installing, have fun.", + "short": "Ping pong.", + "tags": [ + "pingtime", + "latency" + ], + "type": "COG" +} \ No newline at end of file diff --git a/pingtime/pingtime.py b/pingtime/pingtime.py index 07d4237..77c6c30 100644 --- a/pingtime/pingtime.py +++ b/pingtime/pingtime.py @@ -2,7 +2,6 @@ from discord.ext import commands class Pingtime: - def __init__(self, bot): self.bot = bot @@ -12,5 +11,5 @@ class Pingtime: latencies = self.bot.latencies msg = "Pong!\n" for shard, pingt in latencies: - msg += "Shard {}/{}: {}ms\n".format(shard + 1, len(latencies), round(pingt*1000)) + msg += "Shard {}/{}: {}ms\n".format(shard + 1, len(latencies), round(pingt * 1000)) await ctx.send(msg) diff --git a/retrosign/info.json b/retrosign/info.json new file mode 100644 index 0000000..35bad4c --- /dev/null +++ b/retrosign/info.json @@ -0,0 +1,19 @@ +{ + "author": [ + "aikaterna" + ], + "description": "A port of Anismash's retrosign cog for v2: = 15: return await ctx.send( "\N{CROSS MARK} Your first line is too long (14 character limit)" diff --git a/rndstatus/info.json b/rndstatus/info.json new file mode 100644 index 0000000..afac64f --- /dev/null +++ b/rndstatus/info.json @@ -0,0 +1,12 @@ +{ + "author": [ + "aikaterna" + ], + "description": "Random statuses with an optional bot stats mode. Ported from Twentysix's v2 cog.", + "install_msg": "Thanks for installing, have fun.", + "short": "Random bot statuses", + "tags": [ + "status" + ], + "type": "COG" +} \ No newline at end of file diff --git a/seen/info.json b/seen/info.json index 2fc2e42..a510b66 100644 --- a/seen/info.json +++ b/seen/info.json @@ -1,11 +1,12 @@ { "author": [ - "aikaterna and Paddo" + "aikaterna" ], - "description": "Check when the user was last active on a server.", + "description": "Check when the user was last active on a server. Originally made by Paddo.", "short": "Check when the user was last active on a server.", "tags": [ - "seen", "activity" + "seen", + "activity" ], "type": "COG" } \ No newline at end of file diff --git a/seen/seen.py b/seen/seen.py index f4b55e8..535d547 100644 --- a/seen/seen.py +++ b/seen/seen.py @@ -11,43 +11,43 @@ class Seen: self.bot = bot self.config = Config.get_conf(self, 2784481001, force_registration=True) - default_member = { - "member_seen": [] - } + default_member = {"member_seen": []} self.config.register_member(**default_member) @commands.guild_only() - @commands.command(name='seen') + @commands.command(name="seen") async def _seen(self, ctx, author: discord.Member): - '''Shows last time a user was seen in chat''' + """Shows last time a user was seen in chat""" member_seen = await self.config.member(author).member_seen() now = int(time.time()) try: time_elapsed = int(now - member_seen) except TypeError: - embed = discord.Embed(colour=discord.Color.red(), title='I haven\'t seen that user yet.') + embed = discord.Embed( + colour=discord.Color.red(), title="I haven't seen that user yet." + ) return await ctx.send(embed=embed) output = self._dynamic_time(time_elapsed) if output[2] < 1: - ts = 'just now' + ts = "just now" else: - ts = '' + ts = "" if output[0] == 1: - ts += '{} day, '.format(output[0]) + ts += "{} day, ".format(output[0]) elif output[0] > 1: - ts += '{} days, '.format(output[0]) + ts += "{} days, ".format(output[0]) if output[1] == 1: - ts += '{} hour, '.format(output[1]) + ts += "{} hour, ".format(output[1]) elif output[1] > 1: - ts += '{} hours, '.format(output[1]) + ts += "{} hours, ".format(output[1]) if output[2] == 1: - ts += '{} minute ago'.format(output[2]) + ts += "{} minute ago".format(output[2]) elif output[2] > 1: - ts += '{} minutes ago'.format(output[2]) + ts += "{} minutes ago".format(output[2]) em = discord.Embed(colour=discord.Color.green()) avatar = author.avatar_url if author.avatar else author.default_avatar_url - em.set_author(name='{} was seen {}'.format(author.display_name, ts), icon_url=avatar) + em.set_author(name="{} was seen {}".format(author.display_name, ts), icon_url=avatar) await ctx.send(embed=em) def _dynamic_time(self, time_elapsed): @@ -57,7 +57,10 @@ class Seen: return (d, h, m) async def on_message(self, message): - if not isinstance(message.channel, discord.abc.PrivateChannel) and self.bot.user.id != message.author.id: + if ( + not isinstance(message.channel, discord.abc.PrivateChannel) + and self.bot.user.id != message.author.id + ): prefixes = await self.bot.get_prefix(message) if not any(message.content.startswith(n) for n in prefixes): author = message.author diff --git a/wolfram/info.json b/wolfram/info.json new file mode 100644 index 0000000..23f4b73 --- /dev/null +++ b/wolfram/info.json @@ -0,0 +1,12 @@ +{ + "author": [ + "aikaterna" + ], + "description": "Query Wolfram|Alpha for answers. Requires a free API key. Originally by Paddo.", + "install_msg": "Thanks for installing, have fun.", + "short": "Query Wolfram|Alpha for answers.", + "tags": [ + "wolfram" + ], + "type": "COG" +} \ No newline at end of file diff --git a/wolfram/wolfram.py b/wolfram/wolfram.py index 9aaa23d..9571e30 100644 --- a/wolfram/wolfram.py +++ b/wolfram/wolfram.py @@ -6,28 +6,26 @@ import xml.etree.ElementTree as ET class Wolfram: """Ask Wolfram Alpha a question.""" + def __init__(self, bot): self.bot = bot - - default_global = { - "WOLFRAM_API_KEY": None, - } - + + default_global = {"WOLFRAM_API_KEY": None} + self.config = Config.get_conf(self, 2788801004) self.config.register_guild(**default_global) - - @commands.command(name='wolfram', aliases=['ask']) + @commands.command(name="wolfram", aliases=["ask"]) async def _wolfram(self, ctx, *arguments: str): """ Ask Wolfram Alpha any question. """ api_key = await self.config.WOLFRAM_API_KEY() if api_key: - url = 'http://api.wolframalpha.com/v2/query?' - query = ' '.join(arguments) - payload = {'input': query, 'appid': api_key} - headers = {'user-agent': 'Red-cog/2.0.0'} + url = "http://api.wolframalpha.com/v2/query?" + query = " ".join(arguments) + payload = {"input": query, "appid": api_key} + headers = {"user-agent": "Red-cog/2.0.0"} conn = aiohttp.TCPConnector(verify_ssl=False) session = aiohttp.ClientSession(connector=conn) async with session.get(url, params=payload, headers=headers) as r: @@ -35,18 +33,20 @@ class Wolfram: session.close() root = ET.fromstring(result) a = [] - for pt in root.findall('.//plaintext'): + for pt in root.findall(".//plaintext"): if pt.text: a.append(pt.text.capitalize()) if len(a) < 1: - message = 'There is as yet insufficient data for a meaningful answer.' + message = "There is as yet insufficient data for a meaningful answer." else: - message = '\n'.join(a[0:3]) + message = "\n".join(a[0:3]) else: - message = 'No API key set for Wolfram Alpha. Get one at http://products.wolframalpha.com/api/' - await ctx.send('```{0}```'.format(message)) + message = ( + "No API key set for Wolfram Alpha. Get one at http://products.wolframalpha.com/api/" + ) + await ctx.send("```{0}```".format(message)) - @commands.command(name='setwolframapi', aliases=['setwolfram']) + @commands.command(name="setwolframapi", aliases=["setwolfram"]) @checks.is_owner() async def _setwolframapi(self, ctx, key: str): """