From 7a9d64465eba1feec967f60f96ac421c9ea2bfea Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 16 Dec 2019 03:49:34 -0500 Subject: [PATCH 1/2] convert all embed creation to embed_factory --- common.py | 15 +++++--- exts/ae7q.py | 21 +++++------ exts/base.py | 72 +++++++++++++------------------------- exts/grid.py | 72 +++++++++++++++----------------------- exts/ham.py | 70 ++++++++++++++---------------------- exts/image.py | 44 ++++++++--------------- exts/lookup.py | 6 ++-- exts/morse.py | 30 +++++++--------- exts/qrz.py | 20 +++++------ exts/study.py | 35 ++++++++---------- exts/weather.py | 30 +++++++--------- main.py | 5 ++- resources/callsign_info.py | 2 +- 13 files changed, 164 insertions(+), 258 deletions(-) diff --git a/common.py b/common.py index bb0e052..494762c 100644 --- a/common.py +++ b/common.py @@ -46,18 +46,23 @@ emojis = SimpleNamespace(good='✅', # --- Helper functions --- +def embed_factory(ctx: commands.Context) -> discord.Embed: + """Creates an embed with neutral colour and standard footer.""" + embed = discord.Embed(timestamp=datetime.utcnow(), colour=colours.neutral) + embed.set_footer(text=ctx.author, icon_url=str(ctx.author.avatar_url)) + return embed + + def error_embed_factory(ctx: commands.Context, exception: Exception, debug_mode: bool) -> discord.Embed: """Creates an Error embed.""" if debug_mode: fmtd_ex = traceback.format_exception(exception.__class__, exception, exception.__traceback__) else: fmtd_ex = traceback.format_exception_only(exception.__class__, exception) - embed = discord.Embed(title="Error", - timestamp=datetime.utcnow(), - colour=colours.bad) - embed.set_footer(text=ctx.author, - icon_url=str(ctx.author.avatar_url)) + embed = embed_factory(ctx) + embed.title = "Error" embed.description = "```\n" + '\n'.join(fmtd_ex) + "```" + embed.colour = colours.bad return embed diff --git a/exts/ae7q.py b/exts/ae7q.py index 0cb9457..8e2a44c 100644 --- a/exts/ae7q.py +++ b/exts/ae7q.py @@ -62,12 +62,10 @@ class AE7QCog(commands.Cog): rows = None if rows is None: - embed = discord.Embed(title=f"AE7Q History for {callsign}", - colour=cmn.colours.bad, - url=f"{base_url}{callsign}", - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f"AE7Q History for {callsign}" + embed.colour = cmn.colours.bad + embed.url = f"{base_url}{callsign}" embed.description = desc embed.description += f'\nNo records found for `{callsign}`' await ctx.send(embed=embed) @@ -92,13 +90,10 @@ class AE7QCog(commands.Cog): if len(row_cells) > 1: table_contents += [row_cells] - embed = discord.Embed(title=f"AE7Q Records for {callsign}", - colour=cmn.colours.good, - url=f"{base_url}{callsign}", - timestamp=datetime.utcnow()) - - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f"AE7Q Records for {callsign}" + embed.colour = cmn.colours.good + embed.url = f"{base_url}{callsign}" for row in table_contents[0:3]: header = f'**{row[0]}** ({row[1]})' diff --git a/exts/base.py b/exts/base.py index 4dd27e4..700153f 100644 --- a/exts/base.py +++ b/exts/base.py @@ -50,24 +50,17 @@ class QrmHelpCommand(commands.HelpCommand): return f'{opt.prefix}{alias} {command.signature}' async def send_error_message(self, error): - embed = discord.Embed(title='qrm Help Error', - description=error, - colour=cmn.colours.bad, - timestamp=datetime.utcnow() - ) - embed.set_footer(text=self.context.author.name, - icon_url=str(self.context.author.avatar_url)) + embed = cmn.embed_factory(self.context) + embed.title = 'qrm Help Error' + embed.description = error + embed.colour = cmn.colours.bad await self.context.send(embed=embed) async def send_bot_help(self, mapping): - embed = discord.Embed(title='qrm Help', - description=(f'For command-specific help and usage, use `{opt.prefix}help [command name]`' - '. Many commands have shorter aliases.'), - colour=cmn.colours.neutral, - timestamp=datetime.utcnow() - ) - embed.set_footer(text=self.context.author.name, - icon_url=str(self.context.author.avatar_url)) + embed = cmn.embed_factory(self.context) + embed.title = 'qrm Help' + embed.description = (f'For command-specific help and usage, use `{opt.prefix}help [command name]`' + '. Many commands have shorter aliases.') for cat, cmds in mapping.items(): cmds = list(filter(lambda x: not x.hidden, cmds)) @@ -81,23 +74,15 @@ class QrmHelpCommand(commands.HelpCommand): await self.context.send(embed=embed) async def send_command_help(self, command): - embed = discord.Embed(title=self.get_command_signature(command), - description=command.help, - colour=cmn.colours.neutral, - timestamp=datetime.utcnow() - ) - embed.set_footer(text=self.context.author.name, - icon_url=str(self.context.author.avatar_url)) + embed = cmn.embed_factory(self.context) + embed.title = self.get_command_signature(command) + embed.description = command.help await self.context.send(embed=embed) async def send_group_help(self, group): - embed = discord.Embed(title=self.get_command_signature(group), - description=group.help, - colour=cmn.colours.neutral, - timestamp=datetime.utcnow() - ) - embed.set_footer(text=self.context.author.name, - icon_url=str(self.context.author.avatar_url)) + embed = cmn.embed_factory(self.context) + embed.title = self.get_command_signature(group) + embed.description = group.help for cmd in group.commands: embed.add_field(name=self.get_command_signature(cmd), value=cmd.help, inline=False) await self.context.send(embed=embed) @@ -111,12 +96,9 @@ class BaseCog(commands.Cog): @commands.command(name="info", aliases=["about"]) async def _info(self, ctx: commands.Context): """Shows info about qrm.""" - embed = discord.Embed(title="About qrm", - description=info.description, - colour=cmn.colours.neutral, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = "About qrm" + embed.description = info.description embed = embed.add_field(name="Authors", value=", ".join(info.authors)) embed = embed.add_field(name="License", value=info.license) @@ -129,24 +111,18 @@ class BaseCog(commands.Cog): async def _ping(self, ctx: commands.Context): """Show the current latency to the discord endpoint.""" content = ctx.message.author.mention if random.random() < 0.05 else '' - embed = discord.Embed(title="**Pong!**", - description=f'Current ping is {self.bot.latency*1000:.1f} ms', - colour=cmn.colours.neutral, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = "**Pong!**" + embed.description = f'Current ping is {self.bot.latency*1000:.1f} ms' await ctx.send(content=content, embed=embed) @commands.command(name="changelog", aliases=["clog"]) async def _changelog(self, ctx: commands.Context): """Show what has changed in the most recent bot version.""" - embed = discord.Embed(title="qrm Changelog", - description=("For a full listing, visit [Github](https://" - "github.com/classabbyamp/discord-qrm2/blob/master/CHANGELOG.md)."), - colour=cmn.colours.neutral, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = "qrm Changelog" + embed.description = ("For a full listing, visit [Github](https://" + "github.com/classabbyamp/discord-qrm2/blob/master/CHANGELOG.md).") changelog = self.changelog vers = 0 diff --git a/exts/grid.py b/exts/grid.py index 76f4d8e..f4252ee 100644 --- a/exts/grid.py +++ b/exts/grid.py @@ -37,21 +37,17 @@ with negative being latitude South and longitude West.''' grid += chr(ord('a') + int((lonf - (int(lonf/2)*2)) / (5/60))) grid += chr(ord('a') + int((latf - (int(latf/1)*1)) / (2.5/60))) grid += "**" - embed = discord.Embed(title=f'Maidenhead Grid Locator for {float(lat):.6f}, {float(lon):.6f}', - description=grid, - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'Maidenhead Grid Locator for {float(lat):.6f}, {float(lon):.6f}' + embed.description = grid + embed.colour = cmn.colours.good else: raise ValueError('Out of range.') except ValueError as err: - msg = f'Error generating grid square for {lat}, {lon}.' - embed = discord.Embed(title=msg, description=str(err), - colour=cmn.colours.bad, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'Error generating grid square for {lat}, {lon}.' + embed.description = str(err) + embed.colour = cmn.colours.bad await ctx.send(embed=embed) @commands.command(name="ungrid", aliases=['loc'], category=cmn.cat.maps) @@ -64,28 +60,21 @@ If two grid squares are given, the distance and azimuth between them is calculat grid = grid.upper() loc = get_coords(grid) - if len(grid) >= 6: - embed = discord.Embed(title=f'Latitude and Longitude for {grid}', - description=f'**{loc[0]:.5f}, {loc[1]:.5f}**', - colour=cmn.colours.good, - url=f'https://www.openstreetmap.org/#map=13/{loc[0]:.5f}/{loc[1]:.5f}', - timestamp=datetime.utcnow()) + embed = cmn.embed_factory(ctx) + embed.title = f'Latitude and Longitude for {grid}' + embed.colour = cmn.colours.good + if len(grid) >= 6: + embed.description = f'**{loc[0]:.5f}, {loc[1]:.5f}**' + embed.url = f'https://www.openstreetmap.org/#map=13/{loc[0]:.5f}/{loc[1]:.5f}' else: - embed = discord.Embed(title=f'Latitude and Longitude for {grid}', - description=f'**{loc[0]:.1f}, {loc[1]:.1f}**', - colour=cmn.colours.good, - url=f'https://www.openstreetmap.org/#map=10/{loc[0]:.1f}/{loc[1]:.1f}', - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed.description = f'**{loc[0]:.1f}, {loc[1]:.1f}**' + embed.url = f'https://www.openstreetmap.org/#map=10/{loc[0]:.1f}/{loc[1]:.1f}' except Exception as e: - msg = f'Error generating latitude and longitude for grid {grid}.' - embed = discord.Embed(title=msg, description=str(e), - colour=cmn.colours.bad, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'Error generating latitude and longitude for grid {grid}.' + embed.description = str(e) + embed.colour = cmn.colours.bad else: radius = 6371 try: @@ -110,20 +99,15 @@ If two grid squares are given, the distance and azimuth between them is calculat math.cos(math.radians(loc2[1] - loc[1])) bearing = (math.degrees(math.atan2(y_dist, x_dist)) + 360) % 360 - des = f'**Distance:** {d:.1f} km ({d_mi:.1f} mi)\n**Bearing:** {bearing:.1f}°' - embed = discord.Embed(title=f'Great Circle Distance and Bearing from {grid} to {grid2}', - description=des, - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'Great Circle Distance and Bearing from {grid} to {grid2}' + embed.description = f'**Distance:** {d:.1f} km ({d_mi:.1f} mi)\n**Bearing:** {bearing:.1f}°' + embed.colour = cmn.colours.good except Exception as e: - msg = f'Error generating great circle distance and bearing from {grid} and {grid2}.' - embed = discord.Embed(title=msg, description=str(e), - colour=cmn.colours.bad, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'Error generating great circle distance and bearing from {grid} and {grid2}.' + embed.description = str(e) + embed.colour = cmn.colours.bad await ctx.send(embed=embed) diff --git a/exts/ham.py b/exts/ham.py index 3b09861..ce7b1fe 100644 --- a/exts/ham.py +++ b/exts/ham.py @@ -30,16 +30,14 @@ class HamCog(commands.Cog): '''Look up a Q Code.''' with ctx.typing(): qcode = qcode.upper() + embed = cmn.embed_factory(ctx) if qcode in self.qcodes: - embed = discord.Embed(title=qcode, description=self.qcodes[qcode], - colour=cmn.colours.good, - timestamp=datetime.utcnow()) + embed.title = qcode + embed.description = self.qcodes[qcode] + embed.colour = cmn.colours.good else: - embed = discord.Embed(title=f'Q Code {qcode} not found', - colour=cmn.colours.bad, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed.title = f'Q Code {qcode} not found' + embed.colour = cmn.colours.bad await ctx.send(embed=embed) @commands.command(name="phonetics", aliases=['ph', 'phoneticize', 'phoneticise', 'phone'], category=cmn.cat.fun) @@ -53,12 +51,10 @@ class HamCog(commands.Cog): else: result += char result += ' ' - embed = discord.Embed(title=f'Phonetics for {msg}', - description=result.title(), - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'Phonetics for {msg}' + embed.description = result.title() + embed.colour = cmn.colours.good await ctx.send(embed=embed) @commands.command(name="utc", aliases=['z'], category=cmn.cat.ref) @@ -67,12 +63,10 @@ class HamCog(commands.Cog): with ctx.typing(): now = datetime.utcnow() result = '**' + now.strftime('%Y-%m-%d %H:%M') + 'Z**' - embed = discord.Embed(title='The current time is:', - description=result, - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = 'The current time is:' + embed.description = result + embed.colour = cmn.colours.good await ctx.send(embed=embed) @commands.command(name="prefixes", aliases=["vanity", "pfx", "vanities", "prefix"]) @@ -81,37 +75,27 @@ class HamCog(commands.Cog): if country is None: await ctx.send_help(ctx.command) return + embed = cmn.embed_factory(ctx) if country.lower() not in callsign_info.options: - embed = discord.Embed(title=f'{country} not found!', - description=f'Valid countries: {", ".join(callsign_info.options.keys())}', - colour=cmn.colours.bad, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) - await ctx.send(embed=embed) - return - embed = discord.Embed(title=callsign_info.options[country.lower()][0], - description=callsign_info.options[country.lower()][1], - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) - - for name, val in callsign_info.options[country.lower()][2].items(): - embed.add_field(name=name, value=val, inline=False) + embed.title = f'{country} not found!', + embed.description = f'Valid countries: {", ".join(callsign_info.options.keys())}', + embed.colour = cmn.colours.bad + else: + embed.title = callsign_info.options[country.lower()][0] + embed.description = callsign_info.options[country.lower()][1] + embed.colour = cmn.colours.good + for name, val in callsign_info.options[country.lower()][2].items(): + embed.add_field(name=name, value=val, inline=False) await ctx.send(embed=embed) @commands.command(name="contests", aliases=["cc", "tests"], category=cmn.cat.ref) async def _contests(self, ctx: commands.Context): - embed = discord.Embed(title="Contest Calendar", - timestamp=datetime.utcnow(), - colour=cmn.colours.good) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) - + embed = cmn.embed_factory(ctx) + embed.title = "Contest Calendar" embed.description = ("*We are currently rewriting the old, Chrome-based `contests` command. In the meantime, " "use [the website](https://www.contestcalendar.com/weeklycont.php).*") + embed.colour = cmn.colours.good await ctx.send(embed=embed) diff --git a/exts/image.py b/exts/image.py index e1014b5..efec067 100644 --- a/exts/image.py +++ b/exts/image.py @@ -33,27 +33,21 @@ class ImageCog(commands.Cog): arg = region.lower() with ctx.typing(): + embed = cmn.embed_factory(ctx) if arg not in name: desc = 'Possible arguments are:\n' for abbrev, title in name.items(): desc += f'`{abbrev}`: {title}\n' - embed = discord.Embed(title=f'Bandplan Not Found!', - description=desc, - colour=cmn.colours.bad, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed.title = f'Bandplan Not Found!' + embed.description = desc + embed.colour = cmn.colours.bad await ctx.send(embed=embed) else: img = discord.File(f"resources/images/bandchart/{arg}bandchart.png", filename=f'{arg}bandchart.png') - embed = discord.Embed(title=f'{name[arg]} Amateur Radio Bands', - colour=cmn.colours.good, - timestamp=datetime.utcnow()) + embed.title = f'{name[arg]} Amateur Radio Bands' + embed.colour = cmn.colours.good embed.set_image(url=f'attachment://{arg}bandchart.png') - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) - await ctx.send(embed=embed, file=img) @commands.command(name="grayline", aliases=['greyline', 'grey', 'gray', 'gl'], category=cmn.cat.maps) @@ -62,9 +56,9 @@ class ImageCog(commands.Cog): gl_url = ('http://www.fourmilab.ch/cgi-bin/uncgi/Earth?img=NOAAtopo.evif' '&imgsize=320&dynimg=y&opt=-p&lat=&lon=&alt=&tle=&date=0&utc=&jd=') with ctx.typing(): - embed = discord.Embed(title='Current Greyline Conditions', - colour=cmn.colours.good, - timestamp=datetime.utcnow()) + embed = cmn.embed_factory(ctx) + embed.title = 'Current Greyline Conditions' + embed.colour = cmn.colours.good async with aiohttp.ClientSession() as session: async with session.get(gl_url) as resp: if resp.status != 200: @@ -73,8 +67,6 @@ class ImageCog(commands.Cog): else: data = io.BytesIO(await resp.read()) embed.set_image(url=f'attachment://greyline.jpg') - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) await ctx.send(embed=embed, file=discord.File(data, 'greyline.jpg')) @commands.command(name="map", category=cmn.cat.maps) @@ -89,27 +81,21 @@ class ImageCog(commands.Cog): arg = map_id.lower() with ctx.typing(): + embed = cmn.embed_factory(ctx) if arg not in map_titles: desc = 'Possible arguments are:\n' for abbrev, title in map_titles.items(): desc += f'`{abbrev}`: {title}\n' - embed = discord.Embed(title=f'Map Not Found!', - description=desc, - colour=cmn.colours.bad, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed.title = 'Map Not Found!' + embed.description = desc + embed.colour = cmn.colours.bad await ctx.send(embed=embed) else: img = discord.File(f"resources/images/map/{arg}map.png", filename=f'{arg}map.png') - embed = discord.Embed(title=f'{map_titles[arg]} Map', - colour=cmn.colours.good, - timestamp=datetime.utcnow()) + embed.title = f'{map_titles[arg]}' + embed.colour = cmn.colours.good embed.set_image(url=f'attachment://{arg}map.png') - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) - await ctx.send(embed=embed, file=img) diff --git a/exts/lookup.py b/exts/lookup.py index 50d1c1d..3cdf7cd 100644 --- a/exts/lookup.py +++ b/exts/lookup.py @@ -43,10 +43,8 @@ class LookupCog(commands.Cog): with ctx.typing(): query = query.upper() full_query = query - embed = discord.Embed(title=f'DXCC Info for ', - timestamp=datetime.utcnow()) - embed.set_footer(text=f'{ctx.author.name}', - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'DXCC Info for ' embed.description = f'*Last Updated: {self.cty.formatted_version}*' embed.colour = cmn.colours.bad while query: diff --git a/exts/morse.py b/exts/morse.py index 8222518..1e4fbbc 100644 --- a/exts/morse.py +++ b/exts/morse.py @@ -34,12 +34,10 @@ class MorseCog(commands.Cog): except KeyError: result += '' result += ' ' - embed = discord.Embed(title=f'Morse Code for {msg}', - description=result, - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'Morse Code for {msg}' + embed.description = result + embed.colour = cmn.colours.good await ctx.send(embed=embed) @commands.command(name="unmorse", aliases=['demorse', 'uncw', 'decw'], category=cmn.cat.ref) @@ -57,12 +55,10 @@ class MorseCog(commands.Cog): except KeyError: result += '' result += ' ' - embed = discord.Embed(title=f'ASCII for {msg0}', - description=result, - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'ASCII for {msg0}' + embed.description = result + embed.colour = cmn.colours.good await ctx.send(embed=embed) @commands.command(name="cwweight", aliases=["weight", 'cww'], category=cmn.cat.ref) @@ -80,12 +76,10 @@ class MorseCog(commands.Cog): await ctx.send(res) return res = f'The CW weight is **{weight}**' - embed = discord.Embed(title=f'CW Weight of {msg}', - description=res, - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f'CW Weight of {msg}' + embed.description = res + embed.colour = cmn.colours.good await ctx.send(embed=embed) diff --git a/exts/qrz.py b/exts/qrz.py index c09d863..c1a5841 100644 --- a/exts/qrz.py +++ b/exts/qrz.py @@ -53,12 +53,10 @@ class QRZCog(commands.Cog): await self._qrz_lookup(ctx, callsign) return if 'Not found' in resp_session['Error']: - embed = discord.Embed(title=f"QRZ Data for {callsign.upper()}", - colour=cmn.colours.bad, - description='No data found!', - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f"QRZ Data for {callsign.upper()}" + embed.colour = cmn.colours.bad + embed.description = 'No data found!' await ctx.send(embed=embed) return raise ValueError(resp_session['Error']) @@ -67,12 +65,10 @@ class QRZCog(commands.Cog): namespaces={'x': 'http://xmldata.qrz.com'}) resp_data = {el.tag.split('}')[1]: el.text for el in resp_xml_data[0].getiterator()} - embed = discord.Embed(title=f"QRZ Data for {resp_data['call']}", - colour=cmn.colours.good, - url=f'http://www.qrz.com/db/{resp_data["call"]}', - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = f"QRZ Data for {resp_data['call']}" + embed.colour = cmn.colours.good + embed.url = f'http://www.qrz.com/db/{resp_data["call"]}' if 'image' in resp_data: embed.set_thumbnail(url=resp_data['image']) diff --git a/exts/study.py b/exts/study.py index 8b85eaa..35f1a9c 100644 --- a/exts/study.py +++ b/exts/study.py @@ -67,12 +67,10 @@ class StudyCog(commands.Cog): pool_questions = random.choice(pool_section)['questions'] question = random.choice(pool_questions) - embed = discord.Embed(title=question['id'], - description=self.source, - colour=cmn.colours.good, - timestamp=datetime.utcnow()) - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed = cmn.embed_factory(ctx) + embed.title = question['id'] + embed.description = self.source + embed.colour = cmn.colours.good embed = embed.add_field(name='Question:', value=question['text'], inline=False) embed = embed.add_field(name='Answers:', value='**A:** ' + question['answers']['A'] + '\n**B:** ' + question['answers']['B'] + @@ -93,29 +91,24 @@ class StudyCog(commands.Cog): with ctx.typing(): correct_ans = self.lastq[ctx.message.channel.id][1] q_num = self.lastq[ctx.message.channel.id][0] + embed = cmn.embed_factory(ctx) if answer is not None: answer = answer.upper() if answer == correct_ans: result = f'Correct! The answer to {q_num} was **{correct_ans}**.' - embed = discord.Embed(title=f'{q_num} Answer', - description=f'{self.source}\n\n{result}', - colour=cmn.colours.good, - timestamp=datetime.utcnow()) + embed.title = f'{q_num} Answer' + embed.description = f'{self.source}\n\n{result}' + embed.colour = cmn.colours.good else: result = f'Incorrect. The answer to {q_num} was **{correct_ans}**, not **{answer}**.' - embed = discord.Embed(title=f'{q_num} Answer', - description=f'{self.source}\n\n{result}', - colour=cmn.colours.bad, - timestamp=datetime.utcnow()) + embed.title = f'{q_num} Answer' + embed.description = f'{self.source}\n\n{result}' + embed.colour = cmn.colours.bad else: result = f'The correct answer to {q_num} was **{correct_ans}**.' - embed = discord.Embed(title=f'{q_num} Answer', - description=f'{self.source}\n\n{result}', - colour=cmn.colours.neutral, - timestamp=datetime.utcnow()) - - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) + embed.title = f'{q_num} Answer' + embed.description = f'{self.source}\n\n{result}' + embed.colour = cmn.colours.neutral await ctx.send(embed=embed) diff --git a/exts/weather.py b/exts/weather.py index f7aed05..f697bd8 100644 --- a/exts/weather.py +++ b/exts/weather.py @@ -29,9 +29,9 @@ class WeatherCog(commands.Cog): async def _band_conditions(self, ctx: commands.Context): '''Posts an image of HF Band Conditions.''' with ctx.typing(): - embed = discord.Embed(title='Current Solar Conditions', - colour=cmn.colours.good, - timestamp=datetime.utcnow()) + embed = cmn.embed_factory(ctx) + embed.title = 'Current Solar Conditions' + embed.colour = cmn.colours.good async with aiohttp.ClientSession() as session: async with session.get('http://www.hamqsl.com/solarsun.php') as resp: if resp.status != 200: @@ -40,8 +40,6 @@ class WeatherCog(commands.Cog): else: data = io.BytesIO(await resp.read()) embed.set_image(url=f'attachment://condx.png') - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) await ctx.send(embed=embed, file=discord.File(data, 'condx.png')) @commands.group(name="weather", aliases=['wttr'], category=cmn.cat.weather) @@ -78,10 +76,11 @@ See help for weather command for possible location types. Add a `-c` or `-f` to loc = self.wttr_units_regex.sub('', location).strip() - embed = discord.Embed(title=f'Weather Forecast for {loc}', - description='Data from [wttr.in](http://wttr.in/).', - colour=cmn.colours.good, - timestamp=datetime.utcnow()) + embed = cmn.embed_factory(ctx) + embed.title = f'Weather Forecast for {loc}' + embed.description = 'Data from [wttr.in](http://wttr.in/).' + embed.colour = cmn.colours.good + loc = loc.replace(' ', '+') async with aiohttp.ClientSession() as session: async with session.get(f'http://wttr.in/{loc}_{units}pnFQ.png') as resp: @@ -91,8 +90,6 @@ See help for weather command for possible location types. Add a `-c` or `-f` to else: data = io.BytesIO(await resp.read()) embed.set_image(url=f'attachment://wttr_forecast.png') - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) await ctx.send(embed=embed, file=discord.File(data, f'wttr_forecast.png')) @_weather_conditions.command(name='now', aliases=['n'], category=cmn.cat.weather) @@ -113,10 +110,11 @@ See help for weather command for possible location types. Add a `-c` or `-f` to loc = self.wttr_units_regex.sub('', location).strip() - embed = discord.Embed(title=f'Current Weather for {loc}', - description='Data from [wttr.in](http://wttr.in/).', - colour=cmn.colours.good, - timestamp=datetime.utcnow()) + embed = cmn.embed_factory(ctx) + embed.title = f'Current Weather for {loc}' + embed.description = 'Data from [wttr.in](http://wttr.in/).' + embed.colour = cmn.colours.good + loc = loc.replace(' ', '+') async with aiohttp.ClientSession() as session: async with session.get(f'http://wttr.in/{loc}_0{units}pnFQ.png') as resp: @@ -126,8 +124,6 @@ See help for weather command for possible location types. Add a `-c` or `-f` to else: data = io.BytesIO(await resp.read()) embed.set_image(url=f'attachment://wttr_now.png') - embed.set_footer(text=ctx.author.name, - icon_url=str(ctx.author.avatar_url)) await ctx.send(embed=embed, file=discord.File(data, 'wttr_now.png')) diff --git a/main.py b/main.py index 05a7b08..03094d1 100644 --- a/main.py +++ b/main.py @@ -74,9 +74,8 @@ async def _extctl(ctx: commands.Context): @_extctl.command(name="list") async def _extctl_list(ctx: commands.Context): """Lists Extensions.""" - embed = discord.Embed(title="Loaded Extensions", - colour=cmn.colours.neutral, - timestamp=datetime.utcnow()) + embed = cmn.embed_factory(ctx) + embed.title = "Loaded Extensions" embed.description = "\n".join(["‣ " + x.split(".")[1] for x in bot.extensions.keys()]) await ctx.send(embed=embed) diff --git a/resources/callsign_info.py b/resources/callsign_info.py index 0366421..c8f4945 100644 --- a/resources/callsign_info.py +++ b/resources/callsign_info.py @@ -11,7 +11,7 @@ from collections import OrderedDict us_calls_title = "Valid US Vanity Callsigns" -us_calls_desc = ('#x# is the number of letters in the prefix and suffix of a callsign.' +us_calls_desc = ('#x# is the number of letters in the prefix and suffix of a callsign. ' 'E.g., WY4RC would be a 2x2 callsign, with prefix WY and suffix RC.') us_calls = OrderedDict([('**Group A** (Extra Only)', ('**Any:** K, N, W (1x2)\n' ' AA-AL, KA-KZ, NA-NZ, WA-WZ (2x1)\n' From 51cd182c57f54f41d9414ece1d15dfa87bbbadee Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 16 Dec 2019 03:59:14 -0500 Subject: [PATCH 2/2] PEP8, my nemesis, we meet again! (removed unused imports) --- exts/ae7q.py | 3 --- exts/base.py | 1 - exts/grid.py | 2 -- exts/ham.py | 1 - exts/image.py | 1 - exts/lookup.py | 2 -- exts/morse.py | 2 -- exts/qrz.py | 2 -- exts/study.py | 2 -- exts/weather.py | 1 - main.py | 3 --- 11 files changed, 20 deletions(-) diff --git a/exts/ae7q.py b/exts/ae7q.py index 8e2a44c..1e5f065 100644 --- a/exts/ae7q.py +++ b/exts/ae7q.py @@ -13,9 +13,6 @@ KE8FGB: assigned once, no restrictions NA2AAA: unassigned, no records """ -from datetime import datetime - -import discord import discord.ext.commands as commands from bs4 import BeautifulSoup diff --git a/exts/base.py b/exts/base.py index 700153f..3e8e82c 100644 --- a/exts/base.py +++ b/exts/base.py @@ -7,7 +7,6 @@ This file is part of discord-qrm2 and is released under the terms of the GNU General Public License, version 2. """ -from datetime import datetime import re from collections import OrderedDict import random diff --git a/exts/grid.py b/exts/grid.py index f4252ee..570b2e9 100644 --- a/exts/grid.py +++ b/exts/grid.py @@ -8,9 +8,7 @@ General Public License, version 2. """ import math -from datetime import datetime -import discord import discord.ext.commands as commands import common as cmn diff --git a/exts/ham.py b/exts/ham.py index ce7b1fe..c082916 100644 --- a/exts/ham.py +++ b/exts/ham.py @@ -10,7 +10,6 @@ import json import random from datetime import datetime -import discord import discord.ext.commands as commands import common as cmn diff --git a/exts/image.py b/exts/image.py index efec067..f9ebd8b 100644 --- a/exts/image.py +++ b/exts/image.py @@ -8,7 +8,6 @@ General Public License, version 2. """ import io -from datetime import datetime import discord import discord.ext.commands as commands diff --git a/exts/lookup.py b/exts/lookup.py index 3cdf7cd..6e88f71 100644 --- a/exts/lookup.py +++ b/exts/lookup.py @@ -7,10 +7,8 @@ This file is part of discord-qrm2 and is released under the terms of the GNU General Public License, version 2. """ -from datetime import datetime import threading -import discord from discord.ext import commands, tasks from ctyparser import BigCty diff --git a/exts/morse.py b/exts/morse.py index 1e4fbbc..de762b6 100644 --- a/exts/morse.py +++ b/exts/morse.py @@ -8,9 +8,7 @@ General Public License, version 2. """ import json -from datetime import datetime -import discord import discord.ext.commands as commands import common as cmn diff --git a/exts/qrz.py b/exts/qrz.py index c1a5841..b180049 100644 --- a/exts/qrz.py +++ b/exts/qrz.py @@ -7,10 +7,8 @@ This file is part of discord-qrm2 and is released under the terms of the GNU General Public License, version 2. """ from collections import OrderedDict -from datetime import datetime from io import BytesIO -import discord from discord.ext import commands, tasks import aiohttp diff --git a/exts/study.py b/exts/study.py index 35f1a9c..541bf73 100644 --- a/exts/study.py +++ b/exts/study.py @@ -9,9 +9,7 @@ General Public License, version 2. import random import json -from datetime import datetime -import discord import discord.ext.commands as commands import aiohttp diff --git a/exts/weather.py b/exts/weather.py index f697bd8..577e495 100644 --- a/exts/weather.py +++ b/exts/weather.py @@ -8,7 +8,6 @@ General Public License, version 2. """ import io -from datetime import datetime import re import discord diff --git a/main.py b/main.py index 03094d1..49ffedb 100644 --- a/main.py +++ b/main.py @@ -8,9 +8,6 @@ This file is part of discord-qrm2 and is released under the terms of the GNU General Public License, version 2. """ - -from datetime import datetime - import discord from discord.ext import commands, tasks