Skip to content

Commit

Permalink
Partial rework of kurisu.py and stuff that depends on it (nh-server#1000
Browse files Browse the repository at this point in the history
)

* Rework kurisu.py and update cogs dependent on it

* Use printf-style for formatting log messages
  • Loading branch information
FrozenChen authored Sep 4, 2021
1 parent f19444e commit 35d4bbb
Show file tree
Hide file tree
Showing 7 changed files with 233 additions and 220 deletions.
11 changes: 7 additions & 4 deletions cogs/assistance.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import aiohttp
import discord
import qrcode
import logging

from discord.ext import commands, tasks
from io import BytesIO
Expand All @@ -10,6 +10,9 @@
from utils.checks import check_if_user_can_sr


logger = logging.getLogger(__name__)


class Assistance(commands.Cog, command_attrs=dict(cooldown=commands.Cooldown(1, 30.0, commands.BucketType.channel))):
"""
Commands that will mostly be used in the help channels.
Expand All @@ -28,14 +31,14 @@ def __init__(self, bot):

@tasks.loop(hours=2)
async def apps_update(self):
async with aiohttp.ClientSession() as session:
r = await session.get('https://raw.githubusercontent.com/Universal-Team/db/master/docs/data/full.json')
async with self.bot.session.get("https://raw.githubusercontent.com/Universal-Team/db/master/docs/data/full.json", timeout=45) as r:
if r.status == 200:
# Content type is text/plain instead of application/json
self.unidb = await r.json(content_type=None)
logger.info("Downloaded Universal Team Database")
else:
self.unidb = {}
print("Failed to fetch unidb.")
logger.warning("Failed to fetch Universal Team Database.")

def unisearch(self, query: str) -> dict:
query = query.lower()
Expand Down
18 changes: 8 additions & 10 deletions cogs/imgconvert.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import aiohttp
import concurrent.futures
import functools

Expand Down Expand Up @@ -28,15 +27,14 @@ async def on_message(self, message):
# BMP conversion
for f in message.attachments:
if f.filename.lower().endswith('.bmp') and f.size <= 600000: # 600kb
async with aiohttp.ClientSession() as session:
async with session.get(f.url, timeout=45) as img_request:
img_content = await img_request.read()
with concurrent.futures.ProcessPoolExecutor() as pool:
img_out = await self.bot.loop.run_in_executor(pool, functools.partial(self.img_convert, img_content))
out_message = f"{f.filename} from {message.author.mention}"
new_filename = f.filename[:-3] + "png"
img = File(img_out, filename=new_filename)
await message.channel.send(file=img, content=out_message)
async with self.bot.session.get(f.url, timeout=45) as img_request:
img_content = await img_request.read()
with concurrent.futures.ProcessPoolExecutor() as pool:
img_out = await self.bot.loop.run_in_executor(pool, functools.partial(self.img_convert, img_content))
out_message = f"{f.filename} from {message.author.mention}"
new_filename = f.filename[:-3] + "png"
img = File(img_out, filename=new_filename)
await message.channel.send(file=img, content=out_message)


def setup(bot):
Expand Down
20 changes: 9 additions & 11 deletions cogs/loop.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import aiohttp
import asyncio
import discord
import pytz
import sys
import traceback
import logging

from datetime import datetime, timedelta
from discord.ext import commands
from utils import crud
from utils.utils import send_dm_message


logger = logging.getLogger(__name__)


class Loop(commands.Cog):
"""
Loop events.
Expand Down Expand Up @@ -42,13 +43,12 @@ def netinfo_parse_time(self, timestr):
return datetime.strptime(' '.join(timestr.split()), '%A, %B %d, %Y %I :%M %p').replace(tzinfo=self.tz)

async def update_netinfo(self):
async with aiohttp.ClientSession() as session:
r = await session.get('https://www.nintendo.co.jp/netinfo/en_US/status.json?callback=getJSON')
async with self.bot.session.get('https://www.nintendo.co.jp/netinfo/en_US/status.json?callback=getJSON', timeout=45) as r:
if r.status == 200:
j = await r.json()
else:
# No logging setup :/
print(f"Netinfo: {r.status} while trying to update netinfo.")
# logging setup :)
logger.warning("Status %s while trying to update netinfo.", r.status)
return

now = datetime.now(self.tz)
Expand Down Expand Up @@ -228,10 +228,8 @@ async def start_update_loop(self):

if current_timestamp.minute % 30 == 0 and current_timestamp.second == 0:
self.bot.loop.create_task(self.update_netinfo())
except Exception as e:
print('Ignoring exception in start_update_loop', file=sys.stderr)
traceback.print_tb(e.__traceback__)
print(f'{e.__class__.__name__}: {e}', file=sys.stderr)
except Exception:
logger.error("Ignoring exception in start_update_loop", exc_info=True)
finally:
await asyncio.sleep(1)

Expand Down
Loading

0 comments on commit 35d4bbb

Please sign in to comment.