From d3fd36fb75d1f38113523e65573fa491b880d141 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 09:53:49 -0500 Subject: [PATCH 01/15] change `embed = embed.add_field()` to `embed.add_field()`. Fixes #106. --- exts/base.py | 8 ++++---- exts/study.py | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/exts/base.py b/exts/base.py index 6d086cb..b629bba 100644 --- a/exts/base.py +++ b/exts/base.py @@ -99,10 +99,10 @@ class BaseCog(commands.Cog): 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) - embed = embed.add_field(name="Version", value=f'v{info.release}') - embed = embed.add_field(name="Contributing", value=info.contributing, inline=False) + embed.add_field(name="Authors", value=", ".join(info.authors)) + embed.add_field(name="License", value=info.license) + embed.add_field(name="Version", value=f'v{info.release}') + embed.add_field(name="Contributing", value=info.contributing, inline=False) embed.set_thumbnail(url=str(self.bot.user.avatar_url)) await ctx.send(embed=embed) diff --git a/exts/study.py b/exts/study.py index 541bf73..124d53d 100644 --- a/exts/study.py +++ b/exts/study.py @@ -69,16 +69,16 @@ class StudyCog(commands.Cog): 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'] + + embed.add_field(name='Question:', value=question['text'], inline=False) + embed.add_field(name='Answers:', value='**A:** ' + question['answers']['A'] + '\n**B:** ' + question['answers']['B'] + '\n**C:** ' + question['answers']['C'] + '\n**D:** ' + question['answers']['D'], inline=False) - embed = embed.add_field(name='Answer:', value='Type _?rqa_ for answer', inline=False) + embed.add_field(name='Answer:', value='Type _?rqa_ for answer', inline=False) if 'image' in question: image_url = f'https://hamstudy.org/_1330011/images/{selected_pool.split("_",1)[1]}/{question["image"]}' - embed = embed.set_image(url=image_url) + embed.set_image(url=image_url) self.lastq[ctx.message.channel.id] = (question['id'], question['answer']) await ctx.send(embed=embed) From a93f6d7a035c1e7af9394f6126f169d9d6b83fb0 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 09:57:05 -0500 Subject: [PATCH 02/15] >:-( PEP8 --- exts/study.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/exts/study.py b/exts/study.py index 124d53d..806089d 100644 --- a/exts/study.py +++ b/exts/study.py @@ -71,10 +71,10 @@ class StudyCog(commands.Cog): embed.colour = cmn.colours.good embed.add_field(name='Question:', value=question['text'], inline=False) embed.add_field(name='Answers:', value='**A:** ' + question['answers']['A'] + - '\n**B:** ' + question['answers']['B'] + - '\n**C:** ' + question['answers']['C'] + - '\n**D:** ' + question['answers']['D'], - inline=False) + '\n**B:** ' + question['answers']['B'] + + '\n**C:** ' + question['answers']['C'] + + '\n**D:** ' + question['answers']['D'], + inline=False) embed.add_field(name='Answer:', value='Type _?rqa_ for answer', inline=False) if 'image' in question: image_url = f'https://hamstudy.org/_1330011/images/{selected_pool.split("_",1)[1]}/{question["image"]}' From ca224cc744de091130ce3cd95f02ff7210e95335 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 10:32:24 -0500 Subject: [PATCH 03/15] fix commands that do not use embeds Fixes #50 --- exts/ae7q.py | 8 ++++++-- exts/morse.py | 11 ++++++----- exts/study.py | 17 ++++++++++++----- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/exts/ae7q.py b/exts/ae7q.py index 1e5f065..b543b13 100644 --- a/exts/ae7q.py +++ b/exts/ae7q.py @@ -37,11 +37,16 @@ class AE7QCog(commands.Cog): callsign = callsign.upper() desc = '' base_url = "http://ae7q.com/query/data/CallHistory.php?CALL=" + embed = cmn.embed_factory(ctx) async with aiohttp.ClientSession() as session: async with session.get(base_url + callsign) as resp: if resp.status != 200: - return await ctx.send('Could not load AE7Q') + embed.title = "Error in AE7Q call command" + embed.description = 'Could not load AE7Q' + embed.colour = cmn.colours.bad + await ctx.send(embed=embed) + return page = await resp.text() soup = BeautifulSoup(page, features="html.parser") @@ -59,7 +64,6 @@ class AE7QCog(commands.Cog): rows = None if rows is None: - embed = cmn.embed_factory(ctx) embed.title = f"AE7Q History for {callsign}" embed.colour = cmn.colours.bad embed.url = f"{base_url}{callsign}" diff --git a/exts/morse.py b/exts/morse.py index de762b6..1d7f952 100644 --- a/exts/morse.py +++ b/exts/morse.py @@ -62,6 +62,7 @@ class MorseCog(commands.Cog): @commands.command(name="cwweight", aliases=["weight", 'cww'], category=cmn.cat.ref) async def _weight(self, ctx: commands.Context, *, msg: str): '''Calculates the CW Weight of a callsign or message.''' + embed = cmn.embed_factory(ctx) with ctx.typing(): msg = msg.upper() weight = 0 @@ -70,13 +71,13 @@ class MorseCog(commands.Cog): cw_char = self.ascii2morse[char].replace('-', '==') weight += len(cw_char) * 2 + 2 except KeyError: - res = f'Unknown character {char} in callsign' - await ctx.send(res) + embed.title = 'Error in calculation of CW weight' + embed.description = f'Unknown character {char} in callsign' + embed.colour = cmn.colours.bad + await ctx.send(embed=embed) return - res = f'The CW weight is **{weight}**' - embed = cmn.embed_factory(ctx) embed.title = f'CW Weight of {msg}' - embed.description = res + embed.description = f'The CW weight is **{weight}**' embed.colour = cmn.colours.good await ctx.send(embed=embed) diff --git a/exts/study.py b/exts/study.py index 541bf73..59c56f4 100644 --- a/exts/study.py +++ b/exts/study.py @@ -30,6 +30,7 @@ class StudyCog(commands.Cog): gen_pool = 'E3_2019' extra_pool = 'E4_2016' + embed = cmn.embed_factory(ctx) with ctx.typing(): selected_pool = None try: @@ -49,15 +50,22 @@ class StudyCog(commands.Cog): if (level is None) or (level == 'all'): # no pool given or user wants all, so pick a random pool selected_pool = random.choice([tech_pool, gen_pool, extra_pool]) if (level is not None) and (selected_pool is None): # unrecognized pool given by user - await ctx.send('The question pool you gave was unrecognized. ' + - 'There are many ways to call up certain question pools - try ?rq t, g, or e. ' + - '(Note that only the US question pools are available).') + embed.title = 'Error in HamStudy command' + embed.description = ('The question pool you gave was unrecognized. ' + 'There are many ways to call up certain question pools - try ?rq t, g, or e. ' + '\n\nNote that currently only the US question pools are available.') + embed.colour = cmn.colours.bad + await ctx.send(embed=embed) return async with aiohttp.ClientSession() as session: async with session.get(f'https://hamstudy.org/pools/{selected_pool}') as resp: if resp.status != 200: - return await ctx.send('Could not load questions...') + embed.title = 'Error in HamStudy command' + embed.description = 'Could not load questions' + embed.colour = cmn.colours.bad + await ctx.send(embed=embed) + return pool = json.loads(await resp.read())['pool'] # Select a question @@ -65,7 +73,6 @@ class StudyCog(commands.Cog): pool_questions = random.choice(pool_section)['questions'] question = random.choice(pool_questions) - embed = cmn.embed_factory(ctx) embed.title = question['id'] embed.description = self.source embed.colour = cmn.colours.good From c48a4069cb7219191e8504f52134afb027d9835e Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 11:32:02 -0500 Subject: [PATCH 04/15] add reactions on keywords functionality Fixes #52 --- main.py | 10 ++++++++++ templates/data/options.py | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/main.py b/main.py index 49ffedb..832d0ac 100644 --- a/main.py +++ b/main.py @@ -115,6 +115,16 @@ async def on_ready(): print("------") +@bot.event +async def on_message(message): + msg = message.content.lower() + for emoji, keywords in opt.msg_reacts.items(): + if any([keyword in msg for keyword in keywords]): + await message.add_reaction(discord.utils.find(lambda x: x.id == emoji, bot.emojis)) + + await bot.process_commands(message) + + # --- Tasks --- @tasks.loop(minutes=5) diff --git a/templates/data/options.py b/templates/data/options.py index a704c07..6fe15b7 100644 --- a/templates/data/options.py +++ b/templates/data/options.py @@ -31,3 +31,7 @@ exts = ['ae7q', 'base', 'fun', 'grid', 'ham', 'image', 'lookup', 'morse', 'qrz', # The text to put in the "playing" status. game = 'with lids on 7.200' + +# Emoji IDs and keywords for emoji reactions +# Use the format {emoji_id (int): ('tuple', 'of', 'lowercase', 'keywords')} +msg_reacts = {} From ae67498e753a09e89b02b7f1fa90612a402caf82 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 11:47:37 -0500 Subject: [PATCH 05/15] qrz: handle addresses that are only whitespace Fixes #124 --- exts/qrz.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/exts/qrz.py b/exts/qrz.py index b180049..3ab6858 100644 --- a/exts/qrz.py +++ b/exts/qrz.py @@ -71,6 +71,7 @@ class QRZCog(commands.Cog): embed.set_thumbnail(url=resp_data['image']) data = qrz_process_info(resp_data) + print(data) for title, val in data.items(): if val is not None: @@ -139,6 +140,9 @@ def qrz_process_info(data: dict): state = '' address = data.get('addr1', '') + '\n' + data.get('addr2', '') + \ state + ' ' + data.get('zip', '') + address = address.strip() + if address == '': + address = None if 'eqsl' in data: eqsl = 'Yes' if data['eqsl'] == 1 else 'No' else: From e9d2274e6402eecf33fcd322961785f0db7104b7 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 11:49:55 -0500 Subject: [PATCH 06/15] remove print statement --- exts/qrz.py | 1 - 1 file changed, 1 deletion(-) diff --git a/exts/qrz.py b/exts/qrz.py index 3ab6858..5846062 100644 --- a/exts/qrz.py +++ b/exts/qrz.py @@ -71,7 +71,6 @@ class QRZCog(commands.Cog): embed.set_thumbnail(url=resp_data['image']) data = qrz_process_info(resp_data) - print(data) for title, val in data.items(): if val is not None: From f649d15890839342169a7e01693a3f04f3227939 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 13:29:04 -0500 Subject: [PATCH 07/15] modify playing status so it changes based on time of day Fixes #57 --- main.py | 23 +++++++++++++++++++++-- requirements.txt | 1 + templates/data/options.py | 12 ++++++++++-- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index 832d0ac..a490d57 100644 --- a/main.py +++ b/main.py @@ -8,12 +8,14 @@ This file is part of discord-qrm2 and is released under the terms of the GNU General Public License, version 2. """ +from datetime import time, datetime + import discord from discord.ext import commands, tasks +import pytz import common as cmn import info - import data.options as opt import data.keys as keys @@ -129,7 +131,24 @@ async def on_message(message): @tasks.loop(minutes=5) async def _ensure_activity(): - await bot.change_presence(activity=discord.Game(name=opt.game)) + status = opt.status_default + + try: + tz = pytz.timezone(opt.status_tz) + except pytz.exceptions.UnknownTimeZoneError: + print(f'[!!] UnknownTimeZoneError: {opt.status_tz}') + await bot.change_presence(activity=discord.Game(name=status)) + return + + now = datetime.now(tz=tz).time() + + for sts in opt.statuses: + start_time = time(hour=sts[1][0], minute=sts[1][1], tzinfo=tz) + end_time = time(hour=sts[2][0], minute=sts[2][1], tzinfo=tz) + if start_time < now <= end_time: + status = sts[0] + + await bot.change_presence(activity=discord.Game(name=status)) @_ensure_activity.before_loop diff --git a/requirements.txt b/requirements.txt index a31e785..21f069a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ discord.py ctyparser beautifulsoup4 lxml +pytz diff --git a/templates/data/options.py b/templates/data/options.py index 6fe15b7..768126c 100644 --- a/templates/data/options.py +++ b/templates/data/options.py @@ -29,8 +29,16 @@ owners_uids = (200102491231092736,) # The extensions to load when running the bot. exts = ['ae7q', 'base', 'fun', 'grid', 'ham', 'image', 'lookup', 'morse', 'qrz', 'study', 'weather'] -# The text to put in the "playing" status. -game = 'with lids on 7.200' +# Timezone for the status (string) +status_tz = 'US/Eastern' +# The text to put in the "playing" status, with start and stop times +statuses = [('with lids on 3.840', (00,00), (6,00)), + ('with lids on 7.200', (6,00), (10,00)), + ('with lids on 14.313', (10,00), (18,00)), + ('with lids on 7.200', (18,00), (20,00)), + ('with lids on 3.840', (20,00), (23,59))] +# The text to put in the "playing" status otherwise +status_default = 'with lids on the air' # Emoji IDs and keywords for emoji reactions # Use the format {emoji_id (int): ('tuple', 'of', 'lowercase', 'keywords')} From 2ccb225a5f271458113ae210af76b6bfb40a641a Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 13:33:19 -0500 Subject: [PATCH 08/15] hhhhhhhh whitespace --- templates/data/options.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/templates/data/options.py b/templates/data/options.py index 768126c..99fa7b8 100644 --- a/templates/data/options.py +++ b/templates/data/options.py @@ -32,11 +32,11 @@ exts = ['ae7q', 'base', 'fun', 'grid', 'ham', 'image', 'lookup', 'morse', 'qrz', # Timezone for the status (string) status_tz = 'US/Eastern' # The text to put in the "playing" status, with start and stop times -statuses = [('with lids on 3.840', (00,00), (6,00)), - ('with lids on 7.200', (6,00), (10,00)), - ('with lids on 14.313', (10,00), (18,00)), - ('with lids on 7.200', (18,00), (20,00)), - ('with lids on 3.840', (20,00), (23,59))] +statuses = [('with lids on 3.840', (00, 00), (6, 00)), + ('with lids on 7.200', (6, 00), (10, 00)), + ('with lids on 14.313', (10, 00), (18, 00)), + ('with lids on 7.200', (18, 00), (20, 00)), + ('with lids on 3.840', (20, 00), (23, 59))] # The text to put in the "playing" status otherwise status_default = 'with lids on the air' From 9e79eececcf4557de1dae5ef65763bf0fc5b8e9c Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 13:34:56 -0500 Subject: [PATCH 09/15] remove print statement --- main.py | 1 - 1 file changed, 1 deletion(-) diff --git a/main.py b/main.py index a490d57..405fe8e 100644 --- a/main.py +++ b/main.py @@ -136,7 +136,6 @@ async def _ensure_activity(): try: tz = pytz.timezone(opt.status_tz) except pytz.exceptions.UnknownTimeZoneError: - print(f'[!!] UnknownTimeZoneError: {opt.status_tz}') await bot.change_presence(activity=discord.Game(name=status)) return From b25b5a95ffd473c75fbaa3fee16c863dd59fed34 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 14:06:42 -0500 Subject: [PATCH 10/15] refactor to allow for fixed, random, or by time statuses --- main.py | 28 ++++++++++++++++++++-------- templates/data/options.py | 18 +++++++++++------- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/main.py b/main.py index 405fe8e..ed8103f 100644 --- a/main.py +++ b/main.py @@ -9,6 +9,7 @@ General Public License, version 2. """ from datetime import time, datetime +import random import discord from discord.ext import commands, tasks @@ -115,6 +116,12 @@ async def _extctl_unload(ctx: commands.Context, extension: str): async def on_ready(): print(f"Logged in as: {bot.user} - {bot.user.id}") print("------") + if opt.status_mode == "time": + _ensure_activity_time.start() + elif opt.status_mode == "random": + _ensure_activity_random.start() + else: + _ensure_activity_fixed.start() @bot.event @@ -130,8 +137,8 @@ async def on_message(message): # --- Tasks --- @tasks.loop(minutes=5) -async def _ensure_activity(): - status = opt.status_default +async def _ensure_activity_time(): + status = opt.statuses[0] try: tz = pytz.timezone(opt.status_tz) @@ -141,7 +148,7 @@ async def _ensure_activity(): now = datetime.now(tz=tz).time() - for sts in opt.statuses: + for sts in opt.time_statuses: start_time = time(hour=sts[1][0], minute=sts[1][1], tzinfo=tz) end_time = time(hour=sts[2][0], minute=sts[2][1], tzinfo=tz) if start_time < now <= end_time: @@ -149,10 +156,17 @@ async def _ensure_activity(): await bot.change_presence(activity=discord.Game(name=status)) +@tasks.loop(minutes=5) +async def _ensure_activity_random(): + status = random.choice(opt.statuses) -@_ensure_activity.before_loop -async def _before_ensure_activity(): - await bot.wait_until_ready() + await bot.change_presence(activity=discord.Game(name=status)) + +@tasks.loop(minutes=5) +async def _ensure_activity_fixed(): + status = opt.statuses[0] + + await bot.change_presence(activity=discord.Game(name=status)) # --- Run --- @@ -160,8 +174,6 @@ async def _before_ensure_activity(): for ext in opt.exts: bot.load_extension(ext_dir + '.' + ext) -_ensure_activity.start() - try: bot.run(keys.discord_token) diff --git a/templates/data/options.py b/templates/data/options.py index 99fa7b8..225f329 100644 --- a/templates/data/options.py +++ b/templates/data/options.py @@ -29,16 +29,20 @@ owners_uids = (200102491231092736,) # The extensions to load when running the bot. exts = ['ae7q', 'base', 'fun', 'grid', 'ham', 'image', 'lookup', 'morse', 'qrz', 'study', 'weather'] +# Either "time", "random", or "fixed" (first item in statuses) +status_mode = "fixed" + +# Random statuses pool +statuses = ["with lids on the air", "with fire"] + # Timezone for the status (string) status_tz = 'US/Eastern' # The text to put in the "playing" status, with start and stop times -statuses = [('with lids on 3.840', (00, 00), (6, 00)), - ('with lids on 7.200', (6, 00), (10, 00)), - ('with lids on 14.313', (10, 00), (18, 00)), - ('with lids on 7.200', (18, 00), (20, 00)), - ('with lids on 3.840', (20, 00), (23, 59))] -# The text to put in the "playing" status otherwise -status_default = 'with lids on the air' +time_statuses = [('with lids on 3.840', (00, 00), (6, 00)), + ('with lids on 7.200', (6, 00), (10, 00)), + ('with lids on 14.313', (10, 00), (18, 00)), + ('with lids on 7.200', (18, 00), (20, 00)), + ('with lids on 3.840', (20, 00), (23, 59))] # Emoji IDs and keywords for emoji reactions # Use the format {emoji_id (int): ('tuple', 'of', 'lowercase', 'keywords')} From 4d763c2fc11927d3b20cb25e5febba36eb6a366b Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 14:08:05 -0500 Subject: [PATCH 11/15] sigh --- main.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/main.py b/main.py index ed8103f..019e21e 100644 --- a/main.py +++ b/main.py @@ -156,12 +156,14 @@ async def _ensure_activity_time(): await bot.change_presence(activity=discord.Game(name=status)) + @tasks.loop(minutes=5) async def _ensure_activity_random(): status = random.choice(opt.statuses) await bot.change_presence(activity=discord.Game(name=status)) + @tasks.loop(minutes=5) async def _ensure_activity_fixed(): status = opt.statuses[0] From 951dc38992d319a9083655a16464fc457b35b27d Mon Sep 17 00:00:00 2001 From: Abigail Gold <5366828+classabbyamp@users.noreply.github.com> Date: Mon, 23 Dec 2019 15:56:25 -0500 Subject: [PATCH 12/15] Update main.py Co-Authored-By: 0x5c <0x5c.dev@gmail.com> --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 019e21e..da19add 100644 --- a/main.py +++ b/main.py @@ -143,7 +143,7 @@ async def _ensure_activity_time(): try: tz = pytz.timezone(opt.status_tz) except pytz.exceptions.UnknownTimeZoneError: - await bot.change_presence(activity=discord.Game(name=status)) + await bot.change_presence(activity=discord.Game(name="with invalid timezones.")) return now = datetime.now(tz=tz).time() From 28eb6d45c1353f0cefbd067e54f52f7b3bac5051 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 15:57:57 -0500 Subject: [PATCH 13/15] updates from review --- main.py | 3 ++- templates/data/options.py | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index da19add..a7e7b7b 100644 --- a/main.py +++ b/main.py @@ -11,9 +11,10 @@ General Public License, version 2. from datetime import time, datetime import random +import pytz + import discord from discord.ext import commands, tasks -import pytz import common as cmn import info diff --git a/templates/data/options.py b/templates/data/options.py index 225f329..194b7ad 100644 --- a/templates/data/options.py +++ b/templates/data/options.py @@ -36,6 +36,7 @@ status_mode = "fixed" statuses = ["with lids on the air", "with fire"] # Timezone for the status (string) +# See https://pythonhosted.org/pytz/ for more info status_tz = 'US/Eastern' # The text to put in the "playing" status, with start and stop times time_statuses = [('with lids on 3.840', (00, 00), (6, 00)), From f1993c85b2ef7ecb6811b3030c73dc705fa8e76e Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 17:54:20 -0500 Subject: [PATCH 14/15] combine all aiohttp operations into a single session Fixes #49 --- common.py | 2 +- exts/ae7q.py | 19 +++++++++---------- exts/image.py | 18 ++++++++---------- exts/qrz.py | 2 +- exts/study.py | 20 +++++++++----------- exts/weather.py | 48 ++++++++++++++++++++++-------------------------- main.py | 7 +++++++ 7 files changed, 57 insertions(+), 59 deletions(-) diff --git a/common.py b/common.py index 494762c..b0f08fa 100644 --- a/common.py +++ b/common.py @@ -24,7 +24,7 @@ import discord.ext.commands as commands import data.options as opt -__all__ = ["colours", "cat", "emojis", "error_embed_factory", "add_react", "check_if_owner"] +__all__ = ["colours", "cat", "emojis", "embed_factory", "error_embed_factory", "add_react", "check_if_owner"] # --- Common values --- diff --git a/exts/ae7q.py b/exts/ae7q.py index b543b13..e27a019 100644 --- a/exts/ae7q.py +++ b/exts/ae7q.py @@ -16,7 +16,6 @@ NA2AAA: unassigned, no records import discord.ext.commands as commands from bs4 import BeautifulSoup -import aiohttp import common as cmn @@ -24,6 +23,7 @@ import common as cmn class AE7QCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot + self.session = bot.qrm.session @commands.group(name="ae7q", aliases=["ae"], category=cmn.cat.lookup) async def _ae7q_lookup(self, ctx: commands.Context): @@ -39,15 +39,14 @@ class AE7QCog(commands.Cog): base_url = "http://ae7q.com/query/data/CallHistory.php?CALL=" embed = cmn.embed_factory(ctx) - async with aiohttp.ClientSession() as session: - async with session.get(base_url + callsign) as resp: - if resp.status != 200: - embed.title = "Error in AE7Q call command" - embed.description = 'Could not load AE7Q' - embed.colour = cmn.colours.bad - await ctx.send(embed=embed) - return - page = await resp.text() + async with self.session.get(base_url + callsign) as resp: + if resp.status != 200: + embed.title = "Error in AE7Q call command" + embed.description = 'Could not load AE7Q' + embed.colour = cmn.colours.bad + await ctx.send(embed=embed) + return + page = await resp.text() soup = BeautifulSoup(page, features="html.parser") tables = soup.select("table.Database") diff --git a/exts/image.py b/exts/image.py index f9ebd8b..5e6e048 100644 --- a/exts/image.py +++ b/exts/image.py @@ -12,14 +12,13 @@ import io import discord import discord.ext.commands as commands -import aiohttp - import common as cmn class ImageCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot + self.session = bot.qrm.session @commands.command(name="bandplan", aliases=['plan', 'bands'], category=cmn.cat.ref) async def _bandplan(self, ctx: commands.Context, region: str = ''): @@ -58,14 +57,13 @@ class ImageCog(commands.Cog): 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: - embed.description = 'Could not download file...' - embed.colour = cmn.colours.bad - else: - data = io.BytesIO(await resp.read()) - embed.set_image(url=f'attachment://greyline.jpg') + async with self.session.get(gl_url) as resp: + if resp.status != 200: + embed.description = 'Could not download file...' + embed.colour = cmn.colours.bad + else: + data = io.BytesIO(await resp.read()) + embed.set_image(url=f'attachment://greyline.jpg') await ctx.send(embed=embed, file=discord.File(data, 'greyline.jpg')) @commands.command(name="map", category=cmn.cat.maps) diff --git a/exts/qrz.py b/exts/qrz.py index 5846062..27831a1 100644 --- a/exts/qrz.py +++ b/exts/qrz.py @@ -21,7 +21,7 @@ import data.keys as keys class QRZCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot - self.session = aiohttp.ClientSession() + self.session = bot.qrm.session self._qrz_session_init.start() @commands.command(name="call", aliases=["qrz"], category=cmn.cat.lookup) diff --git a/exts/study.py b/exts/study.py index 143f9cd..6c98fb4 100644 --- a/exts/study.py +++ b/exts/study.py @@ -12,8 +12,6 @@ import json import discord.ext.commands as commands -import aiohttp - import common as cmn @@ -22,6 +20,7 @@ class StudyCog(commands.Cog): self.bot = bot self.lastq = dict() self.source = 'Data courtesy of [HamStudy.org](https://hamstudy.org/)' + self.session = bot.qrm.session @commands.command(name="hamstudy", aliases=['rq', 'randomquestion', 'randomq'], category=cmn.cat.study) async def _random_question(self, ctx: commands.Context, level: str = None): @@ -58,15 +57,14 @@ class StudyCog(commands.Cog): await ctx.send(embed=embed) return - async with aiohttp.ClientSession() as session: - async with session.get(f'https://hamstudy.org/pools/{selected_pool}') as resp: - if resp.status != 200: - embed.title = 'Error in HamStudy command' - embed.description = 'Could not load questions' - embed.colour = cmn.colours.bad - await ctx.send(embed=embed) - return - pool = json.loads(await resp.read())['pool'] + async with self.session.get(f'https://hamstudy.org/pools/{selected_pool}') as resp: + if resp.status != 200: + embed.title = 'Error in HamStudy command' + embed.description = 'Could not load questions' + embed.colour = cmn.colours.bad + await ctx.send(embed=embed) + return + pool = json.loads(await resp.read())['pool'] # Select a question pool_section = random.choice(pool)['sections'] diff --git a/exts/weather.py b/exts/weather.py index 577e495..ec38443 100644 --- a/exts/weather.py +++ b/exts/weather.py @@ -13,8 +13,6 @@ import re import discord import discord.ext.commands as commands -import aiohttp - import common as cmn @@ -23,6 +21,7 @@ class WeatherCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot + self.session = bot.qrm.session @commands.command(name="bandconditions", aliases=['cond', 'condx', 'conditions'], category=cmn.cat.weather) async def _band_conditions(self, ctx: commands.Context): @@ -31,14 +30,13 @@ class WeatherCog(commands.Cog): 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: - embed.description = 'Could not download file...' - embed.colour = cmn.colours.bad - else: - data = io.BytesIO(await resp.read()) - embed.set_image(url=f'attachment://condx.png') + async with self.session.get('http://www.hamqsl.com/solarsun.php') as resp: + if resp.status != 200: + embed.description = 'Could not download file...' + embed.colour = cmn.colours.bad + else: + data = io.BytesIO(await resp.read()) + embed.set_image(url=f'attachment://condx.png') await ctx.send(embed=embed, file=discord.File(data, 'condx.png')) @commands.group(name="weather", aliases=['wttr'], category=cmn.cat.weather) @@ -81,14 +79,13 @@ See help for weather command for possible location types. Add a `-c` or `-f` to 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: - if resp.status != 200: - embed.description = 'Could not download file...' - embed.colour = cmn.colours.bad - else: - data = io.BytesIO(await resp.read()) - embed.set_image(url=f'attachment://wttr_forecast.png') + async with self.session.get(f'http://wttr.in/{loc}_{units}pnFQ.png') as resp: + if resp.status != 200: + embed.description = 'Could not download file...' + embed.colour = cmn.colours.bad + else: + data = io.BytesIO(await resp.read()) + embed.set_image(url=f'attachment://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) @@ -115,14 +112,13 @@ See help for weather command for possible location types. Add a `-c` or `-f` to 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: - if resp.status != 200: - embed.description = 'Could not download file...' - embed.colour = cmn.colours.bad - else: - data = io.BytesIO(await resp.read()) - embed.set_image(url=f'attachment://wttr_now.png') + async with self.session.get(f'http://wttr.in/{loc}_0{units}pnFQ.png') as resp: + if resp.status != 200: + embed.description = 'Could not download file...' + embed.colour = cmn.colours.bad + else: + data = io.BytesIO(await resp.read()) + embed.set_image(url=f'attachment://wttr_now.png') await ctx.send(embed=embed, file=discord.File(data, 'wttr_now.png')) diff --git a/main.py b/main.py index a7e7b7b..3a110a6 100644 --- a/main.py +++ b/main.py @@ -10,8 +10,10 @@ General Public License, version 2. from datetime import time, datetime import random +from types import SimpleNamespace import pytz +import aiohttp import discord from discord.ext import commands, tasks @@ -37,13 +39,17 @@ bot = commands.Bot(command_prefix=opt.prefix, description=info.description, help_command=commands.MinimalHelpCommand()) +bot.qrm = SimpleNamespace() +bot.qrm.session = aiohttp.ClientSession(headers={'User-Agent': f'discord-qrm2/{info.release}'}) # --- Commands --- + @bot.command(name="restart", hidden=True) @commands.check(cmn.check_if_owner) async def _restart_bot(ctx: commands.Context): """Restarts the bot.""" + await bot.qrm.session.close() global exit_code await cmn.add_react(ctx.message, cmn.emojis.good) print(f"[**] Restarting! Requested by {ctx.author}.") @@ -55,6 +61,7 @@ async def _restart_bot(ctx: commands.Context): @commands.check(cmn.check_if_owner) async def _shutdown_bot(ctx: commands.Context): """Shuts down the bot.""" + await bot.qrm.session.close() global exit_code await cmn.add_react(ctx.message, cmn.emojis.good) print(f"[**] Shutting down! Requested by {ctx.author}.") From f7aaa467b5e87ed70f3183ff7199323bb78813da Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 23 Dec 2019 18:10:36 -0500 Subject: [PATCH 15/15] >_> pep8 --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 3a110a6..f98c869 100644 --- a/main.py +++ b/main.py @@ -42,8 +42,8 @@ bot = commands.Bot(command_prefix=opt.prefix, bot.qrm = SimpleNamespace() bot.qrm.session = aiohttp.ClientSession(headers={'User-Agent': f'discord-qrm2/{info.release}'}) -# --- Commands --- +# --- Commands --- @bot.command(name="restart", hidden=True) @commands.check(cmn.check_if_owner)