Merge pull request #118 from classabbyamp/embed-factory

convert all embed creation to embed_factory
This commit is contained in:
Abigail Gold 2019-12-18 10:35:15 -05:00 committed by GitHub
commit e84ba201bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 164 additions and 278 deletions

View File

@ -46,18 +46,23 @@ emojis = SimpleNamespace(good='✅',
# --- Helper functions --- # --- 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: def error_embed_factory(ctx: commands.Context, exception: Exception, debug_mode: bool) -> discord.Embed:
"""Creates an Error embed.""" """Creates an Error embed."""
if debug_mode: if debug_mode:
fmtd_ex = traceback.format_exception(exception.__class__, exception, exception.__traceback__) fmtd_ex = traceback.format_exception(exception.__class__, exception, exception.__traceback__)
else: else:
fmtd_ex = traceback.format_exception_only(exception.__class__, exception) fmtd_ex = traceback.format_exception_only(exception.__class__, exception)
embed = discord.Embed(title="Error", embed = embed_factory(ctx)
timestamp=datetime.utcnow(), embed.title = "Error"
colour=colours.bad)
embed.set_footer(text=ctx.author,
icon_url=str(ctx.author.avatar_url))
embed.description = "```\n" + '\n'.join(fmtd_ex) + "```" embed.description = "```\n" + '\n'.join(fmtd_ex) + "```"
embed.colour = colours.bad
return embed return embed

View File

@ -13,9 +13,6 @@ KE8FGB: assigned once, no restrictions
NA2AAA: unassigned, no records NA2AAA: unassigned, no records
""" """
from datetime import datetime
import discord
import discord.ext.commands as commands import discord.ext.commands as commands
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
@ -62,12 +59,10 @@ class AE7QCog(commands.Cog):
rows = None rows = None
if rows is None: if rows is None:
embed = discord.Embed(title=f"AE7Q History for {callsign}", embed = cmn.embed_factory(ctx)
colour=cmn.colours.bad, embed.title = f"AE7Q History for {callsign}"
url=f"{base_url}{callsign}", embed.colour = cmn.colours.bad
timestamp=datetime.utcnow()) embed.url = f"{base_url}{callsign}"
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
embed.description = desc embed.description = desc
embed.description += f'\nNo records found for `{callsign}`' embed.description += f'\nNo records found for `{callsign}`'
await ctx.send(embed=embed) await ctx.send(embed=embed)
@ -92,13 +87,10 @@ class AE7QCog(commands.Cog):
if len(row_cells) > 1: if len(row_cells) > 1:
table_contents += [row_cells] table_contents += [row_cells]
embed = discord.Embed(title=f"AE7Q Records for {callsign}", embed = cmn.embed_factory(ctx)
colour=cmn.colours.good, embed.title = f"AE7Q Records for {callsign}"
url=f"{base_url}{callsign}", embed.colour = cmn.colours.good
timestamp=datetime.utcnow()) embed.url = f"{base_url}{callsign}"
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
for row in table_contents[0:3]: for row in table_contents[0:3]:
header = f'**{row[0]}** ({row[1]})' header = f'**{row[0]}** ({row[1]})'

View File

@ -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. General Public License, version 2.
""" """
from datetime import datetime
import re import re
from collections import OrderedDict from collections import OrderedDict
import random import random
@ -50,24 +49,17 @@ class QrmHelpCommand(commands.HelpCommand):
return f'{opt.prefix}{alias} {command.signature}' return f'{opt.prefix}{alias} {command.signature}'
async def send_error_message(self, error): async def send_error_message(self, error):
embed = discord.Embed(title='qrm Help Error', embed = cmn.embed_factory(self.context)
description=error, embed.title = 'qrm Help Error'
colour=cmn.colours.bad, embed.description = error
timestamp=datetime.utcnow() embed.colour = cmn.colours.bad
)
embed.set_footer(text=self.context.author.name,
icon_url=str(self.context.author.avatar_url))
await self.context.send(embed=embed) await self.context.send(embed=embed)
async def send_bot_help(self, mapping): async def send_bot_help(self, mapping):
embed = discord.Embed(title='qrm Help', embed = cmn.embed_factory(self.context)
description=(f'For command-specific help and usage, use `{opt.prefix}help [command name]`' embed.title = 'qrm Help'
'. Many commands have shorter aliases.'), embed.description = (f'For command-specific help and usage, use `{opt.prefix}help [command name]`'
colour=cmn.colours.neutral, '. Many commands have shorter aliases.')
timestamp=datetime.utcnow()
)
embed.set_footer(text=self.context.author.name,
icon_url=str(self.context.author.avatar_url))
for cat, cmds in mapping.items(): for cat, cmds in mapping.items():
cmds = list(filter(lambda x: not x.hidden, cmds)) cmds = list(filter(lambda x: not x.hidden, cmds))
@ -81,23 +73,15 @@ class QrmHelpCommand(commands.HelpCommand):
await self.context.send(embed=embed) await self.context.send(embed=embed)
async def send_command_help(self, command): async def send_command_help(self, command):
embed = discord.Embed(title=self.get_command_signature(command), embed = cmn.embed_factory(self.context)
description=command.help, embed.title = self.get_command_signature(command)
colour=cmn.colours.neutral, embed.description = command.help
timestamp=datetime.utcnow()
)
embed.set_footer(text=self.context.author.name,
icon_url=str(self.context.author.avatar_url))
await self.context.send(embed=embed) await self.context.send(embed=embed)
async def send_group_help(self, group): async def send_group_help(self, group):
embed = discord.Embed(title=self.get_command_signature(group), embed = cmn.embed_factory(self.context)
description=group.help, embed.title = self.get_command_signature(group)
colour=cmn.colours.neutral, embed.description = group.help
timestamp=datetime.utcnow()
)
embed.set_footer(text=self.context.author.name,
icon_url=str(self.context.author.avatar_url))
for cmd in group.commands: for cmd in group.commands:
embed.add_field(name=self.get_command_signature(cmd), value=cmd.help, inline=False) embed.add_field(name=self.get_command_signature(cmd), value=cmd.help, inline=False)
await self.context.send(embed=embed) await self.context.send(embed=embed)
@ -111,12 +95,9 @@ class BaseCog(commands.Cog):
@commands.command(name="info", aliases=["about"]) @commands.command(name="info", aliases=["about"])
async def _info(self, ctx: commands.Context): async def _info(self, ctx: commands.Context):
"""Shows info about qrm.""" """Shows info about qrm."""
embed = discord.Embed(title="About qrm", embed = cmn.embed_factory(ctx)
description=info.description, embed.title = "About qrm"
colour=cmn.colours.neutral, embed.description = info.description
timestamp=datetime.utcnow())
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
embed = embed.add_field(name="Authors", value=", ".join(info.authors)) embed = embed.add_field(name="Authors", value=", ".join(info.authors))
embed = embed.add_field(name="License", value=info.license) embed = embed.add_field(name="License", value=info.license)
@ -129,24 +110,18 @@ class BaseCog(commands.Cog):
async def _ping(self, ctx: commands.Context): async def _ping(self, ctx: commands.Context):
"""Show the current latency to the discord endpoint.""" """Show the current latency to the discord endpoint."""
content = ctx.message.author.mention if random.random() < 0.05 else '' content = ctx.message.author.mention if random.random() < 0.05 else ''
embed = discord.Embed(title="**Pong!**", embed = cmn.embed_factory(ctx)
description=f'Current ping is {self.bot.latency*1000:.1f} ms', embed.title = "**Pong!**"
colour=cmn.colours.neutral, embed.description = f'Current ping is {self.bot.latency*1000:.1f} ms'
timestamp=datetime.utcnow())
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(content=content, embed=embed) await ctx.send(content=content, embed=embed)
@commands.command(name="changelog", aliases=["clog"]) @commands.command(name="changelog", aliases=["clog"])
async def _changelog(self, ctx: commands.Context): async def _changelog(self, ctx: commands.Context):
"""Show what has changed in the most recent bot version.""" """Show what has changed in the most recent bot version."""
embed = discord.Embed(title="qrm Changelog", embed = cmn.embed_factory(ctx)
description=("For a full listing, visit [Github](https://" embed.title = "qrm Changelog"
"github.com/classabbyamp/discord-qrm2/blob/master/CHANGELOG.md)."), embed.description = ("For a full listing, visit [Github](https://"
colour=cmn.colours.neutral, "github.com/classabbyamp/discord-qrm2/blob/master/CHANGELOG.md).")
timestamp=datetime.utcnow())
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
changelog = self.changelog changelog = self.changelog
vers = 0 vers = 0

View File

@ -8,9 +8,7 @@ General Public License, version 2.
""" """
import math import math
from datetime import datetime
import discord
import discord.ext.commands as commands import discord.ext.commands as commands
import common as cmn import common as cmn
@ -37,21 +35,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((lonf - (int(lonf/2)*2)) / (5/60)))
grid += chr(ord('a') + int((latf - (int(latf/1)*1)) / (2.5/60))) grid += chr(ord('a') + int((latf - (int(latf/1)*1)) / (2.5/60)))
grid += "**" grid += "**"
embed = discord.Embed(title=f'Maidenhead Grid Locator for {float(lat):.6f}, {float(lon):.6f}', embed = cmn.embed_factory(ctx)
description=grid, embed.title = f'Maidenhead Grid Locator for {float(lat):.6f}, {float(lon):.6f}'
colour=cmn.colours.good, embed.description = grid
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
else: else:
raise ValueError('Out of range.') raise ValueError('Out of range.')
except ValueError as err: except ValueError as err:
msg = f'Error generating grid square for {lat}, {lon}.' embed = cmn.embed_factory(ctx)
embed = discord.Embed(title=msg, description=str(err), embed.title = f'Error generating grid square for {lat}, {lon}.'
colour=cmn.colours.bad, embed.description = str(err)
timestamp=datetime.utcnow()) embed.colour = cmn.colours.bad
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)
@commands.command(name="ungrid", aliases=['loc'], category=cmn.cat.maps) @commands.command(name="ungrid", aliases=['loc'], category=cmn.cat.maps)
@ -64,28 +58,21 @@ If two grid squares are given, the distance and azimuth between them is calculat
grid = grid.upper() grid = grid.upper()
loc = get_coords(grid) loc = get_coords(grid)
if len(grid) >= 6: embed = cmn.embed_factory(ctx)
embed = discord.Embed(title=f'Latitude and Longitude for {grid}', embed.title = f'Latitude and Longitude for {grid}'
description=f'**{loc[0]:.5f}, {loc[1]:.5f}**', embed.colour = cmn.colours.good
colour=cmn.colours.good,
url=f'https://www.openstreetmap.org/#map=13/{loc[0]:.5f}/{loc[1]:.5f}',
timestamp=datetime.utcnow())
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: else:
embed = discord.Embed(title=f'Latitude and Longitude for {grid}', embed.description = f'**{loc[0]:.1f}, {loc[1]:.1f}**'
description=f'**{loc[0]:.1f}, {loc[1]:.1f}**', embed.url = f'https://www.openstreetmap.org/#map=10/{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))
except Exception as e: except Exception as e:
msg = f'Error generating latitude and longitude for grid {grid}.' embed = cmn.embed_factory(ctx)
embed = discord.Embed(title=msg, description=str(e), embed.title = f'Error generating latitude and longitude for grid {grid}.'
colour=cmn.colours.bad, embed.description = str(e)
timestamp=datetime.utcnow()) embed.colour = cmn.colours.bad
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
else: else:
radius = 6371 radius = 6371
try: try:
@ -110,20 +97,15 @@ If two grid squares are given, the distance and azimuth between them is calculat
math.cos(math.radians(loc2[1] - loc[1])) math.cos(math.radians(loc2[1] - loc[1]))
bearing = (math.degrees(math.atan2(y_dist, x_dist)) + 360) % 360 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 = cmn.embed_factory(ctx)
embed = discord.Embed(title=f'Great Circle Distance and Bearing from {grid} to {grid2}', embed.title = f'Great Circle Distance and Bearing from {grid} to {grid2}'
description=des, embed.description = f'**Distance:** {d:.1f} km ({d_mi:.1f} mi)\n**Bearing:** {bearing:.1f}°'
colour=cmn.colours.good, embed.colour = cmn.colours.good
timestamp=datetime.utcnow())
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
except Exception as e: except Exception as e:
msg = f'Error generating great circle distance and bearing from {grid} and {grid2}.' embed = cmn.embed_factory(ctx)
embed = discord.Embed(title=msg, description=str(e), embed.title = f'Error generating great circle distance and bearing from {grid} and {grid2}.'
colour=cmn.colours.bad, embed.description = str(e)
timestamp=datetime.utcnow()) embed.colour = cmn.colours.bad
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)

View File

@ -10,7 +10,6 @@ import json
import random import random
from datetime import datetime from datetime import datetime
import discord
import discord.ext.commands as commands import discord.ext.commands as commands
import common as cmn import common as cmn
@ -30,16 +29,14 @@ class HamCog(commands.Cog):
'''Look up a Q Code.''' '''Look up a Q Code.'''
with ctx.typing(): with ctx.typing():
qcode = qcode.upper() qcode = qcode.upper()
embed = cmn.embed_factory(ctx)
if qcode in self.qcodes: if qcode in self.qcodes:
embed = discord.Embed(title=qcode, description=self.qcodes[qcode], embed.title = qcode
colour=cmn.colours.good, embed.description = self.qcodes[qcode]
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
else: else:
embed = discord.Embed(title=f'Q Code {qcode} not found', embed.title = f'Q Code {qcode} not found'
colour=cmn.colours.bad, embed.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) await ctx.send(embed=embed)
@commands.command(name="phonetics", aliases=['ph', 'phoneticize', 'phoneticise', 'phone'], category=cmn.cat.fun) @commands.command(name="phonetics", aliases=['ph', 'phoneticize', 'phoneticise', 'phone'], category=cmn.cat.fun)
@ -53,12 +50,10 @@ class HamCog(commands.Cog):
else: else:
result += char result += char
result += ' ' result += ' '
embed = discord.Embed(title=f'Phonetics for {msg}', embed = cmn.embed_factory(ctx)
description=result.title(), embed.title = f'Phonetics for {msg}'
colour=cmn.colours.good, embed.description = result.title()
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)
@commands.command(name="utc", aliases=['z'], category=cmn.cat.ref) @commands.command(name="utc", aliases=['z'], category=cmn.cat.ref)
@ -67,12 +62,10 @@ class HamCog(commands.Cog):
with ctx.typing(): with ctx.typing():
now = datetime.utcnow() now = datetime.utcnow()
result = '**' + now.strftime('%Y-%m-%d %H:%M') + 'Z**' result = '**' + now.strftime('%Y-%m-%d %H:%M') + 'Z**'
embed = discord.Embed(title='The current time is:', embed = cmn.embed_factory(ctx)
description=result, embed.title = 'The current time is:'
colour=cmn.colours.good, embed.description = result
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)
@commands.command(name="prefixes", aliases=["vanity", "pfx", "vanities", "prefix"]) @commands.command(name="prefixes", aliases=["vanity", "pfx", "vanities", "prefix"])
@ -81,37 +74,27 @@ class HamCog(commands.Cog):
if country is None: if country is None:
await ctx.send_help(ctx.command) await ctx.send_help(ctx.command)
return return
embed = cmn.embed_factory(ctx)
if country.lower() not in callsign_info.options: if country.lower() not in callsign_info.options:
embed = discord.Embed(title=f'{country} not found!', embed.title = f'{country} not found!',
description=f'Valid countries: {", ".join(callsign_info.options.keys())}', embed.description = f'Valid countries: {", ".join(callsign_info.options.keys())}',
colour=cmn.colours.bad, embed.colour = cmn.colours.bad
timestamp=datetime.utcnow()) else:
embed.set_footer(text=ctx.author.name, embed.title = callsign_info.options[country.lower()][0]
icon_url=str(ctx.author.avatar_url)) embed.description = callsign_info.options[country.lower()][1]
await ctx.send(embed=embed) embed.colour = cmn.colours.good
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(): for name, val in callsign_info.options[country.lower()][2].items():
embed.add_field(name=name, value=val, inline=False) embed.add_field(name=name, value=val, inline=False)
await ctx.send(embed=embed) await ctx.send(embed=embed)
@commands.command(name="contests", aliases=["cc", "tests"], category=cmn.cat.ref) @commands.command(name="contests", aliases=["cc", "tests"], category=cmn.cat.ref)
async def _contests(self, ctx: commands.Context): async def _contests(self, ctx: commands.Context):
embed = discord.Embed(title="Contest Calendar", embed = cmn.embed_factory(ctx)
timestamp=datetime.utcnow(), embed.title = "Contest Calendar"
colour=cmn.colours.good)
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
embed.description = ("*We are currently rewriting the old, Chrome-based `contests` command. In the meantime, " embed.description = ("*We are currently rewriting the old, Chrome-based `contests` command. In the meantime, "
"use [the website](https://www.contestcalendar.com/weeklycont.php).*") "use [the website](https://www.contestcalendar.com/weeklycont.php).*")
embed.colour = cmn.colours.good
await ctx.send(embed=embed) await ctx.send(embed=embed)

View File

@ -8,7 +8,6 @@ General Public License, version 2.
""" """
import io import io
from datetime import datetime
import discord import discord
import discord.ext.commands as commands import discord.ext.commands as commands
@ -33,27 +32,21 @@ class ImageCog(commands.Cog):
arg = region.lower() arg = region.lower()
with ctx.typing(): with ctx.typing():
embed = cmn.embed_factory(ctx)
if arg not in name: if arg not in name:
desc = 'Possible arguments are:\n' desc = 'Possible arguments are:\n'
for abbrev, title in name.items(): for abbrev, title in name.items():
desc += f'`{abbrev}`: {title}\n' desc += f'`{abbrev}`: {title}\n'
embed = discord.Embed(title=f'Bandplan Not Found!', embed.title = f'Bandplan Not Found!'
description=desc, embed.description = desc
colour=cmn.colours.bad, embed.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) await ctx.send(embed=embed)
else: else:
img = discord.File(f"resources/images/bandchart/{arg}bandchart.png", img = discord.File(f"resources/images/bandchart/{arg}bandchart.png",
filename=f'{arg}bandchart.png') filename=f'{arg}bandchart.png')
embed = discord.Embed(title=f'{name[arg]} Amateur Radio Bands', embed.title = f'{name[arg]} Amateur Radio Bands'
colour=cmn.colours.good, embed.colour = cmn.colours.good
timestamp=datetime.utcnow())
embed.set_image(url=f'attachment://{arg}bandchart.png') 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) await ctx.send(embed=embed, file=img)
@commands.command(name="grayline", aliases=['greyline', 'grey', 'gray', 'gl'], category=cmn.cat.maps) @commands.command(name="grayline", aliases=['greyline', 'grey', 'gray', 'gl'], category=cmn.cat.maps)
@ -62,9 +55,9 @@ class ImageCog(commands.Cog):
gl_url = ('http://www.fourmilab.ch/cgi-bin/uncgi/Earth?img=NOAAtopo.evif' 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=') '&imgsize=320&dynimg=y&opt=-p&lat=&lon=&alt=&tle=&date=0&utc=&jd=')
with ctx.typing(): with ctx.typing():
embed = discord.Embed(title='Current Greyline Conditions', embed = cmn.embed_factory(ctx)
colour=cmn.colours.good, embed.title = 'Current Greyline Conditions'
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get(gl_url) as resp: async with session.get(gl_url) as resp:
if resp.status != 200: if resp.status != 200:
@ -73,8 +66,6 @@ class ImageCog(commands.Cog):
else: else:
data = io.BytesIO(await resp.read()) data = io.BytesIO(await resp.read())
embed.set_image(url=f'attachment://greyline.jpg') 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')) await ctx.send(embed=embed, file=discord.File(data, 'greyline.jpg'))
@commands.command(name="map", category=cmn.cat.maps) @commands.command(name="map", category=cmn.cat.maps)
@ -89,27 +80,21 @@ class ImageCog(commands.Cog):
arg = map_id.lower() arg = map_id.lower()
with ctx.typing(): with ctx.typing():
embed = cmn.embed_factory(ctx)
if arg not in map_titles: if arg not in map_titles:
desc = 'Possible arguments are:\n' desc = 'Possible arguments are:\n'
for abbrev, title in map_titles.items(): for abbrev, title in map_titles.items():
desc += f'`{abbrev}`: {title}\n' desc += f'`{abbrev}`: {title}\n'
embed = discord.Embed(title=f'Map Not Found!', embed.title = 'Map Not Found!'
description=desc, embed.description = desc
colour=cmn.colours.bad, embed.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) await ctx.send(embed=embed)
else: else:
img = discord.File(f"resources/images/map/{arg}map.png", img = discord.File(f"resources/images/map/{arg}map.png",
filename=f'{arg}map.png') filename=f'{arg}map.png')
embed = discord.Embed(title=f'{map_titles[arg]} Map', embed.title = f'{map_titles[arg]}'
colour=cmn.colours.good, embed.colour = cmn.colours.good
timestamp=datetime.utcnow())
embed.set_image(url=f'attachment://{arg}map.png') 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) await ctx.send(embed=embed, file=img)

View File

@ -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. General Public License, version 2.
""" """
from datetime import datetime
import threading import threading
import discord
from discord.ext import commands, tasks from discord.ext import commands, tasks
from ctyparser import BigCty from ctyparser import BigCty
@ -43,10 +41,8 @@ class LookupCog(commands.Cog):
with ctx.typing(): with ctx.typing():
query = query.upper() query = query.upper()
full_query = query full_query = query
embed = discord.Embed(title=f'DXCC Info for ', embed = cmn.embed_factory(ctx)
timestamp=datetime.utcnow()) embed.title = f'DXCC Info for '
embed.set_footer(text=f'{ctx.author.name}',
icon_url=str(ctx.author.avatar_url))
embed.description = f'*Last Updated: {self.cty.formatted_version}*' embed.description = f'*Last Updated: {self.cty.formatted_version}*'
embed.colour = cmn.colours.bad embed.colour = cmn.colours.bad
while query: while query:

View File

@ -8,9 +8,7 @@ General Public License, version 2.
""" """
import json import json
from datetime import datetime
import discord
import discord.ext.commands as commands import discord.ext.commands as commands
import common as cmn import common as cmn
@ -34,12 +32,10 @@ class MorseCog(commands.Cog):
except KeyError: except KeyError:
result += '<?>' result += '<?>'
result += ' ' result += ' '
embed = discord.Embed(title=f'Morse Code for {msg}', embed = cmn.embed_factory(ctx)
description=result, embed.title = f'Morse Code for {msg}'
colour=cmn.colours.good, embed.description = result
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)
@commands.command(name="unmorse", aliases=['demorse', 'uncw', 'decw'], category=cmn.cat.ref) @commands.command(name="unmorse", aliases=['demorse', 'uncw', 'decw'], category=cmn.cat.ref)
@ -57,12 +53,10 @@ class MorseCog(commands.Cog):
except KeyError: except KeyError:
result += '<?>' result += '<?>'
result += ' ' result += ' '
embed = discord.Embed(title=f'ASCII for {msg0}', embed = cmn.embed_factory(ctx)
description=result, embed.title = f'ASCII for {msg0}'
colour=cmn.colours.good, embed.description = result
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)
@commands.command(name="cwweight", aliases=["weight", 'cww'], category=cmn.cat.ref) @commands.command(name="cwweight", aliases=["weight", 'cww'], category=cmn.cat.ref)
@ -80,12 +74,10 @@ class MorseCog(commands.Cog):
await ctx.send(res) await ctx.send(res)
return return
res = f'The CW weight is **{weight}**' res = f'The CW weight is **{weight}**'
embed = discord.Embed(title=f'CW Weight of {msg}', embed = cmn.embed_factory(ctx)
description=res, embed.title = f'CW Weight of {msg}'
colour=cmn.colours.good, embed.description = res
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)

View File

@ -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. General Public License, version 2.
""" """
from collections import OrderedDict from collections import OrderedDict
from datetime import datetime
from io import BytesIO from io import BytesIO
import discord
from discord.ext import commands, tasks from discord.ext import commands, tasks
import aiohttp import aiohttp
@ -53,12 +51,10 @@ class QRZCog(commands.Cog):
await self._qrz_lookup(ctx, callsign) await self._qrz_lookup(ctx, callsign)
return return
if 'Not found' in resp_session['Error']: if 'Not found' in resp_session['Error']:
embed = discord.Embed(title=f"QRZ Data for {callsign.upper()}", embed = cmn.embed_factory(ctx)
colour=cmn.colours.bad, embed.title = f"QRZ Data for {callsign.upper()}"
description='No data found!', embed.colour = cmn.colours.bad
timestamp=datetime.utcnow()) embed.description = 'No data found!'
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)
return return
raise ValueError(resp_session['Error']) raise ValueError(resp_session['Error'])
@ -67,12 +63,10 @@ class QRZCog(commands.Cog):
namespaces={'x': 'http://xmldata.qrz.com'}) namespaces={'x': 'http://xmldata.qrz.com'})
resp_data = {el.tag.split('}')[1]: el.text for el in resp_xml_data[0].getiterator()} 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']}", embed = cmn.embed_factory(ctx)
colour=cmn.colours.good, embed.title = f"QRZ Data for {resp_data['call']}"
url=f'http://www.qrz.com/db/{resp_data["call"]}', embed.colour = cmn.colours.good
timestamp=datetime.utcnow()) embed.url = f'http://www.qrz.com/db/{resp_data["call"]}'
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
if 'image' in resp_data: if 'image' in resp_data:
embed.set_thumbnail(url=resp_data['image']) embed.set_thumbnail(url=resp_data['image'])

View File

@ -9,9 +9,7 @@ General Public License, version 2.
import random import random
import json import json
from datetime import datetime
import discord
import discord.ext.commands as commands import discord.ext.commands as commands
import aiohttp import aiohttp
@ -67,12 +65,10 @@ class StudyCog(commands.Cog):
pool_questions = random.choice(pool_section)['questions'] pool_questions = random.choice(pool_section)['questions']
question = random.choice(pool_questions) question = random.choice(pool_questions)
embed = discord.Embed(title=question['id'], embed = cmn.embed_factory(ctx)
description=self.source, embed.title = question['id']
colour=cmn.colours.good, embed.description = self.source
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
embed = embed.add_field(name='Question:', value=question['text'], inline=False) embed = embed.add_field(name='Question:', value=question['text'], inline=False)
embed = embed.add_field(name='Answers:', value='**A:** ' + question['answers']['A'] + embed = embed.add_field(name='Answers:', value='**A:** ' + question['answers']['A'] +
'\n**B:** ' + question['answers']['B'] + '\n**B:** ' + question['answers']['B'] +
@ -93,29 +89,24 @@ class StudyCog(commands.Cog):
with ctx.typing(): with ctx.typing():
correct_ans = self.lastq[ctx.message.channel.id][1] correct_ans = self.lastq[ctx.message.channel.id][1]
q_num = self.lastq[ctx.message.channel.id][0] q_num = self.lastq[ctx.message.channel.id][0]
embed = cmn.embed_factory(ctx)
if answer is not None: if answer is not None:
answer = answer.upper() answer = answer.upper()
if answer == correct_ans: if answer == correct_ans:
result = f'Correct! The answer to {q_num} was **{correct_ans}**.' result = f'Correct! The answer to {q_num} was **{correct_ans}**.'
embed = discord.Embed(title=f'{q_num} Answer', embed.title = f'{q_num} Answer'
description=f'{self.source}\n\n{result}', embed.description = f'{self.source}\n\n{result}'
colour=cmn.colours.good, embed.colour = cmn.colours.good
timestamp=datetime.utcnow())
else: else:
result = f'Incorrect. The answer to {q_num} was **{correct_ans}**, not **{answer}**.' result = f'Incorrect. The answer to {q_num} was **{correct_ans}**, not **{answer}**.'
embed = discord.Embed(title=f'{q_num} Answer', embed.title = f'{q_num} Answer'
description=f'{self.source}\n\n{result}', embed.description = f'{self.source}\n\n{result}'
colour=cmn.colours.bad, embed.colour = cmn.colours.bad
timestamp=datetime.utcnow())
else: else:
result = f'The correct answer to {q_num} was **{correct_ans}**.' result = f'The correct answer to {q_num} was **{correct_ans}**.'
embed = discord.Embed(title=f'{q_num} Answer', embed.title = f'{q_num} Answer'
description=f'{self.source}\n\n{result}', embed.description = f'{self.source}\n\n{result}'
colour=cmn.colours.neutral, embed.colour = cmn.colours.neutral
timestamp=datetime.utcnow())
embed.set_footer(text=ctx.author.name,
icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed) await ctx.send(embed=embed)

View File

@ -8,7 +8,6 @@ General Public License, version 2.
""" """
import io import io
from datetime import datetime
import re import re
import discord import discord
@ -29,9 +28,9 @@ class WeatherCog(commands.Cog):
async def _band_conditions(self, ctx: commands.Context): async def _band_conditions(self, ctx: commands.Context):
'''Posts an image of HF Band Conditions.''' '''Posts an image of HF Band Conditions.'''
with ctx.typing(): with ctx.typing():
embed = discord.Embed(title='Current Solar Conditions', embed = cmn.embed_factory(ctx)
colour=cmn.colours.good, embed.title = 'Current Solar Conditions'
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get('http://www.hamqsl.com/solarsun.php') as resp: async with session.get('http://www.hamqsl.com/solarsun.php') as resp:
if resp.status != 200: if resp.status != 200:
@ -40,8 +39,6 @@ class WeatherCog(commands.Cog):
else: else:
data = io.BytesIO(await resp.read()) data = io.BytesIO(await resp.read())
embed.set_image(url=f'attachment://condx.png') 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')) await ctx.send(embed=embed, file=discord.File(data, 'condx.png'))
@commands.group(name="weather", aliases=['wttr'], category=cmn.cat.weather) @commands.group(name="weather", aliases=['wttr'], category=cmn.cat.weather)
@ -78,10 +75,11 @@ See help for weather command for possible location types. Add a `-c` or `-f` to
loc = self.wttr_units_regex.sub('', location).strip() loc = self.wttr_units_regex.sub('', location).strip()
embed = discord.Embed(title=f'Weather Forecast for {loc}', embed = cmn.embed_factory(ctx)
description='Data from [wttr.in](http://wttr.in/).', embed.title = f'Weather Forecast for {loc}'
colour=cmn.colours.good, embed.description = 'Data from [wttr.in](http://wttr.in/).'
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
loc = loc.replace(' ', '+') loc = loc.replace(' ', '+')
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get(f'http://wttr.in/{loc}_{units}pnFQ.png') as resp: async with session.get(f'http://wttr.in/{loc}_{units}pnFQ.png') as resp:
@ -91,8 +89,6 @@ See help for weather command for possible location types. Add a `-c` or `-f` to
else: else:
data = io.BytesIO(await resp.read()) data = io.BytesIO(await resp.read())
embed.set_image(url=f'attachment://wttr_forecast.png') 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')) await ctx.send(embed=embed, file=discord.File(data, f'wttr_forecast.png'))
@_weather_conditions.command(name='now', aliases=['n'], category=cmn.cat.weather) @_weather_conditions.command(name='now', aliases=['n'], category=cmn.cat.weather)
@ -113,10 +109,11 @@ See help for weather command for possible location types. Add a `-c` or `-f` to
loc = self.wttr_units_regex.sub('', location).strip() loc = self.wttr_units_regex.sub('', location).strip()
embed = discord.Embed(title=f'Current Weather for {loc}', embed = cmn.embed_factory(ctx)
description='Data from [wttr.in](http://wttr.in/).', embed.title = f'Current Weather for {loc}'
colour=cmn.colours.good, embed.description = 'Data from [wttr.in](http://wttr.in/).'
timestamp=datetime.utcnow()) embed.colour = cmn.colours.good
loc = loc.replace(' ', '+') loc = loc.replace(' ', '+')
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get(f'http://wttr.in/{loc}_0{units}pnFQ.png') as resp: async with session.get(f'http://wttr.in/{loc}_0{units}pnFQ.png') as resp:
@ -126,8 +123,6 @@ See help for weather command for possible location types. Add a `-c` or `-f` to
else: else:
data = io.BytesIO(await resp.read()) data = io.BytesIO(await resp.read())
embed.set_image(url=f'attachment://wttr_now.png') 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')) await ctx.send(embed=embed, file=discord.File(data, 'wttr_now.png'))

View File

@ -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. General Public License, version 2.
""" """
from datetime import datetime
import discord import discord
from discord.ext import commands, tasks from discord.ext import commands, tasks
@ -74,9 +71,8 @@ async def _extctl(ctx: commands.Context):
@_extctl.command(name="list") @_extctl.command(name="list")
async def _extctl_list(ctx: commands.Context): async def _extctl_list(ctx: commands.Context):
"""Lists Extensions.""" """Lists Extensions."""
embed = discord.Embed(title="Loaded Extensions", embed = cmn.embed_factory(ctx)
colour=cmn.colours.neutral, embed.title = "Loaded Extensions"
timestamp=datetime.utcnow())
embed.description = "\n".join(["" + x.split(".")[1] for x in bot.extensions.keys()]) embed.description = "\n".join(["" + x.split(".")[1] for x in bot.extensions.keys()])
await ctx.send(embed=embed) await ctx.send(embed=embed)