Skip to content

Commit fb31870

Browse files
committed
Changed the brute forced "obj" converter and moved lambda-ike functions into utils.py
1 parent dfd9afe commit fb31870

File tree

4 files changed

+56
-38
lines changed

4 files changed

+56
-38
lines changed

cogs/modmail.py

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from core.decorators import trigger_typing
1010
from core.paginator import PaginatorSession
1111
from core.time import UserFriendlyTime, human_timedelta
12+
from core.utils import User, truncate
1213

1314

1415
class Modmail:
@@ -17,9 +18,6 @@ class Modmail:
1718
def __init__(self, bot):
1819
self.bot = bot
1920

20-
def obj(arg):
21-
return discord.Object(int(arg))
22-
2321
@commands.command()
2422
@trigger_typing
2523
@commands.has_permissions(administrator=True)
@@ -342,10 +340,8 @@ async def nsfw(self, ctx):
342340
@commands.command(aliases=['threads'])
343341
@commands.has_permissions(manage_messages=True)
344342
@trigger_typing
345-
async def logs(self, ctx, *,
346-
member: Union[discord.Member, discord.User, obj] = None):
343+
async def logs(self, ctx, *, member: User = None):
347344
"""Shows a list of previous Modmail thread logs of a member."""
348-
# TODO: find a better way of that Union ^
349345
if not member:
350346
thread = await self.bot.threads.find(channel=ctx.channel)
351347
if not thread:
@@ -397,10 +393,6 @@ async def logs(self, ctx, *,
397393
else:
398394
log_url = self.bot.config.log_url.strip('/') + f'/logs/{key}'
399395

400-
# TODO: Move all the lambda-like functions to a utils.py
401-
def truncate(c):
402-
return c[:47].strip() + '...' if len(c) > 50 else c
403-
404396
if entry['messages']:
405397
short_desc = truncate(entry['messages'][0]['content'])
406398
if not short_desc:
@@ -545,9 +537,7 @@ async def blocked(self, ctx):
545537
@commands.command()
546538
@trigger_typing
547539
@commands.has_permissions(manage_channels=True)
548-
async def block(self, ctx,
549-
user: Union[discord.Member, discord.User, obj] = None,
550-
*, reason=None):
540+
async def block(self, ctx, user: User = None, *, reason=None):
551541
"""Block a user from using Modmail."""
552542

553543
if user is None:
@@ -580,8 +570,7 @@ async def block(self, ctx,
580570
@commands.command()
581571
@trigger_typing
582572
@commands.has_permissions(manage_channels=True)
583-
async def unblock(self, ctx, *,
584-
user: Union[discord.Member, discord.User, obj] = None):
573+
async def unblock(self, ctx, *, user: User = None):
585574
"""Unblocks a user from using Modmail."""
586575

587576
if user is None:

cogs/utility.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from core.paginator import PaginatorSession
1818
from core.decorators import auth_required, owner_only, trigger_typing
1919
from core.changelog import ChangeLog
20+
from core.utils import cleanup_code
2021

2122

2223
class Utility:
@@ -599,15 +600,6 @@ async def eval_(self, ctx, *, body):
599600

600601
env.update(globals())
601602

602-
def cleanup_code(content):
603-
"""Automatically removes code blocks from the code."""
604-
# remove ```py\n```
605-
if content.startswith('```') and content.endswith('```'):
606-
return '\n'.join(content.split('\n')[1:-1])
607-
608-
# remove `foo`
609-
return content.strip('` \n')
610-
611603
body = cleanup_code(body)
612604
stdout = StringIO()
613605

core/thread.py

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from traceback import print_exc
1111

1212
from core.decorators import async_executor
13+
from core.utils import is_image_url, days
14+
1315
from colorthief import ColorThief
1416

1517

@@ -270,14 +272,6 @@ async def send(self, message, destination=None,
270272
url=message.jump_url
271273
)
272274

273-
image_types = ['.png', '.jpg', '.gif', '.jpeg', '.webp']
274-
275-
def is_image_url(u, _):
276-
for x in image_types:
277-
if urlparse(u.lower()).path.endswith(x):
278-
return True
279-
return False
280-
281275
delete_message = not bool(message.attachments)
282276

283277
attachments = [(a.url, a.filename) for a in message.attachments]
@@ -521,9 +515,10 @@ async def find_or_create(self, recipient):
521515
@staticmethod
522516
def valid_image_url(url):
523517
"""Checks if a url leads to an image."""
524-
types = ['.png', '.jpg', '.gif', '.webp']
518+
types = ['.png', '.jpg', '.gif', '.jpeg', '.webp']
525519
parsed = urlparse(url)
526520
if any(parsed.path.endswith(i) for i in types):
521+
# TODO: Replace this logic with urlsplit/urlunsplit
527522
return url.replace(parsed.query, 'size=128')
528523
return False
529524

@@ -588,11 +583,6 @@ def _format_info_embed(self, user, creator, log_url, log_count, dc):
588583
description=user.mention,
589584
timestamp=time)
590585

591-
def days(d):
592-
if d == '0':
593-
return '**today**'
594-
return f'{d} day ago' if d == '1' else f'{d} days ago'
595-
596586
created = str((time - user.created_at).days)
597587
# if not role_names:
598588
# embed.add_field(name='Mention', value=user.mention)

core/utils.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from discord import Object
2+
from discord.ext import commands
3+
4+
from urllib.parse import urlparse
5+
6+
7+
class User(commands.IDConverter):
8+
async def convert(self, ctx, argument):
9+
try:
10+
return await commands.MemberConverter.convert(self, ctx, argument)
11+
except commands.BadArgument:
12+
pass
13+
try:
14+
return await commands.UserConverter.convert(self, ctx, argument)
15+
except commands.BadArgument:
16+
pass
17+
match = self._get_id_match(argument)
18+
if match is None:
19+
raise commands.BadArgument('User "{}" not found'.format(argument))
20+
return Object(int(match.group(1)))
21+
22+
23+
def truncate(c):
24+
return c[:47].strip() + '...' if len(c) > 50 else c
25+
26+
27+
def is_image_url(u, _):
28+
for x in {'.png', '.jpg', '.gif', '.jpeg', '.webp'}:
29+
if urlparse(u.lower()).path.endswith(x):
30+
return True
31+
return False
32+
33+
34+
def days(d):
35+
if d == '0':
36+
return '**today**'
37+
return f'{d} day ago' if d == '1' else f'{d} days ago'
38+
39+
40+
def cleanup_code(content):
41+
"""Automatically removes code blocks from the code."""
42+
# remove ```py\n```
43+
if content.startswith('```') and content.endswith('```'):
44+
return '\n'.join(content.split('\n')[1:-1])
45+
46+
# remove `foo`
47+
return content.strip('` \n')

0 commit comments

Comments
 (0)