Skip to content

Commit 6a72cdb

Browse files
committed
Resolved more TODO's
1 parent 08477f9 commit 6a72cdb

File tree

4 files changed

+39
-37
lines changed

4 files changed

+39
-37
lines changed

bot.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from discord.ext.commands.view import StringView
3131

3232
from os import listdir
33-
from asyncio import sleep, Event
33+
import asyncio
3434
from textwrap import dedent
3535
from datetime import datetime
3636
from types import SimpleNamespace
@@ -62,7 +62,7 @@ def __init__(self):
6262
self._threads = None
6363
self._session = None
6464
self._config = None
65-
self._connected = Event()
65+
self._connected = asyncio.Event()
6666
self._db = None
6767

6868
if self.self_hosted:
@@ -570,7 +570,7 @@ async def data_loop(self):
570570
}
571571

572572
await self.api.post_metadata(data)
573-
await sleep(3600)
573+
await asyncio.sleep(3600)
574574

575575
async def autoupdate_loop(self):
576576
await self.wait_until_ready()
@@ -619,7 +619,7 @@ async def autoupdate_loop(self):
619619
channel = self.log_channel
620620
await channel.send(embed=embed)
621621

622-
await sleep(3600)
622+
await asyncio.sleep(3600)
623623

624624
async def get_latest_updates(self, limit=3):
625625
latest_commits = ''

core/paginator.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ def __init__(self, ctx: commands.Context, *embeds, **options):
4040
'▶': self.next_page,
4141
'⏭': self.last_page,
4242
# '⏹': self.close
43-
# TODO: implement self.close
4443
}
4544

4645
if options.get('edit_footer', True) and len(self.embeds) > 1:

core/thread.py

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
import discord
2-
from discord.ext.commands import UserInputError
2+
from discord.ext.commands import UserInputError, CommandError
33

44
import re
55
import string
66
import asyncio
77
import typing
88
from io import BytesIO
9-
from urllib.parse import urlparse
109
from datetime import datetime, timedelta
1110
from traceback import print_exc
1211

1312
from core.decorators import async_executor
14-
from core.utils import is_image_url, days
13+
from core.utils import is_image_url, days, match_user_id, parse_image_url
1514
from core.objects import Bot, ThreadManagerABC, ThreadABC
1615

1716
from colorthief import ColorThief
@@ -24,10 +23,12 @@ def __init__(self, manager: 'ThreadManager',
2423
recipient: typing.Union[discord.Member, discord.User],
2524
channel: typing.Union[discord.DMChannel,
2625
discord.TextChannel]):
26+
if recipient.bot:
27+
raise CommandError('Recipient cannot be a bot.')
28+
2729
self.manager = manager
2830
self.bot = manager.bot
2931
self._id = recipient.id
30-
# TODO: recipient should not be bot
3132
self._recipient = recipient
3233
self._channel = channel
3334
self._ready_event = asyncio.Event()
@@ -465,21 +466,19 @@ async def _find_from_channel(self, channel):
465466
"""
466467
user_id = None
467468

468-
if channel.topic and 'User ID: ' in channel.topic:
469-
user_id = int(re.findall(r'\d+', channel.topic)[0])
469+
if channel.topic:
470+
user_id = match_user_id(channel.topic)
470471

471472
# BUG: When discord fails to create channel topic.
472473
# search through message history
473474
elif channel.topic is None:
474-
async for message in channel.history(limit=50):
475+
async for message in channel.history(limit=100):
475476
if message.embeds:
476477
embed = message.embeds[0]
477-
# TODO: use re.search instead
478-
matches = re.findall(r'User ID: (\d+)',
479-
str(embed.footer.text))
480-
if matches:
481-
user_id = int(matches[0])
482-
break
478+
if embed.footer.text:
479+
user_id = match_user_id(embed.footer.text)
480+
if user_id is not None:
481+
break
483482

484483
if user_id is not None:
485484
if user_id in self.cache:
@@ -536,7 +535,7 @@ async def create(self, recipient, *, creator=None, category=None):
536535
self.cache[recipient.id] = thread
537536

538537
log_url = await self.bot.api.create_log_entry(recipient, channel,
539-
creator or recipient),
538+
creator or recipient)
540539

541540
log_data = await self.bot.api.get_user_logs(recipient.id)
542541
# await self.get_dominant_color(recipient.avatar_url)
@@ -565,27 +564,17 @@ async def find_or_create(self, recipient):
565564
return await self.find(recipient=recipient) or \
566565
await self.create(recipient)
567566

568-
@staticmethod
569-
def valid_image_url(url):
570-
"""Checks if a url leads to an image."""
571-
types = ['.png', '.jpg', '.gif', '.jpeg', '.webp']
572-
parsed = urlparse(url)
573-
if any(parsed.path.endswith(i) for i in types):
574-
# TODO: Replace this logic with urlsplit/urlunsplit
575-
return url.replace(parsed.query, 'size=128')
576-
return ''
577-
578567
@async_executor()
579568
def _do_get_dc(self, image, quality):
580569
with BytesIO(image) as f:
581570
return ColorThief(f).get_color(quality=quality)
582571

583572
async def get_dominant_color(self, url=None, quality=10):
584573
"""
585-
Returns the dominant color of an image from a url
574+
Returns the dominant color of an image from a URL
586575
(misc)
587576
"""
588-
url = self.valid_image_url(url)
577+
url = parse_image_url(url)
589578

590579
if not url:
591580
raise ValueError('Invalid image url passed.')

core/utils.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from discord import Object
22
from discord.ext import commands
33

4+
import re
45
import typing
5-
from urllib.parse import urlparse
6+
from urllib import parse
67

78

89
class User(commands.IDConverter):
@@ -25,11 +26,18 @@ def truncate(c: str) -> str:
2526
return c[:47].strip() + '...' if len(c) > 50 else c
2627

2728

28-
def is_image_url(u: str, _=None) -> bool:
29-
for x in {'.png', '.jpg', '.gif', '.jpeg', '.webp'}:
30-
if urlparse(u.lower()).path.endswith(x):
31-
return True
32-
return False
29+
def is_image_url(url: str, _=None) -> bool:
30+
return bool(parse_image_url(url))
31+
32+
33+
def parse_image_url(url: str) -> str:
34+
"""Checks if a url leads to an image."""
35+
types = ['.png', '.jpg', '.gif', '.jpeg', '.webp']
36+
url = parse.urlsplit(url)
37+
38+
if any(url.path.lower().endswith(i) for i in types):
39+
return parse.urlunsplit((*url[:3], 'size=128', url[-1]))
40+
return ''
3341

3442

3543
def days(d: typing.Union[str, int]) -> str:
@@ -47,3 +55,9 @@ def cleanup_code(content: str) -> str:
4755

4856
# remove `foo`
4957
return content.strip('` \n')
58+
59+
60+
def match_user_id(s: str) -> typing.Optional[int]:
61+
match = re.match(r'^User ID: (\d+)$', s)
62+
if match is not None:
63+
return int(match.group(1))

0 commit comments

Comments
 (0)