Skip to content

Commit d838269

Browse files
committed
Added dynamic alias configuration resolves #86
1 parent 47f72e7 commit d838269

File tree

3 files changed

+150
-26
lines changed

3 files changed

+150
-26
lines changed

cogs/utility.py

+149-23
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import discord
22
from discord.ext import commands
3+
import datetime
34
import traceback
45
import inspect
56
import json
@@ -11,8 +12,6 @@
1112
from core.paginator import PaginatorSession
1213
from core.decorators import auth_required, owner_only, trigger_typing
1314

14-
from prettytable import PrettyTable
15-
1615
class Utility:
1716
'''General commands that provide utility'''
1817

@@ -22,7 +21,7 @@ def __init__(self, bot):
2221
def format_cog_help(self, ctx, cog):
2322
"""Formats the text for a cog help"""
2423
sigs = []
25-
prefix = self.bot.config.get('prefix', 'm.')
24+
prefix = self.bot.prefix
2625

2726
for cmd in self.bot.commands:
2827
if cmd.hidden:
@@ -50,8 +49,11 @@ def format_cog_help(self, ctx, cog):
5049
fmt[index] += f'`{prefix+cmd.qualified_name:<{maxlen}}` - '
5150
fmt[index] += f'{cmd.short_doc:<{maxlen}}\n'
5251
if hasattr(cmd, 'commands'):
53-
for c in cmd.commands:
54-
branch = '\u200b └─ ' + c.name
52+
for i, c in enumerate(cmd.commands):
53+
if len(cmd.commands) == i + 1: # last
54+
branch = '\u200b └─ ' + c.name
55+
else:
56+
branch = '\u200b ├─ ' + c.name
5557
if len(fmt[index] + f"`{branch:<{maxlen+1}}` - " + f"{c.short_doc:<{maxlen}}\n") > 1024:
5658
index += 1
5759
fmt.append('')
@@ -75,7 +77,7 @@ def format_cog_help(self, ctx, cog):
7577

7678
def format_command_help(self, ctx, cmd):
7779
'''Formats command help.'''
78-
prefix = self.bot.config.get('prefix', 'm.')
80+
prefix = self.bot.prefix
7981
em = discord.Embed(
8082
color=discord.Color.green(),
8183
description=cmd.help
@@ -141,7 +143,7 @@ async def help(self, ctx, *, command: str=None):
141143

142144
pages = []
143145

144-
prefix = self.bot.config.get('prefix', 'm.')
146+
prefix = self.bot.prefix
145147

146148
for _, cog in sorted(self.bot.cogs.items()):
147149
em = self.format_cog_help(ctx, cog)
@@ -177,15 +179,15 @@ async def about(self, ctx):
177179
em.add_field(name='Latency', value=f'{self.bot.latency*1000:.2f} ms')
178180

179181

180-
em.add_field(name='Version', value=f'[`{__version__}`](https://github.com/kyb3r/modmail/blob/master/bot.py#L25)')
182+
em.add_field(name='Version', value=f'[`{self.bot.version}`](https://github.com/kyb3r/modmail/blob/master/bot.py#L25)')
181183
em.add_field(name='Author', value='[`kyb3r`](https://github.com/kyb3r)')
182184

183185
em.add_field(name='Latest Updates', value=await self.bot.get_latest_updates())
184186

185187
footer = f'Bot ID: {self.bot.user.id}'
186188

187189
if meta:
188-
if __version__ != meta['latest_version']:
190+
if self.bot.version != meta['latest_version']:
189191
footer = f"A newer version is available v{meta['latest_version']}"
190192
else:
191193
footer = 'You are up to date with the latest version.'
@@ -208,7 +210,7 @@ async def github(self, ctx):
208210
data = await self.bot.modmail_api.get_user_info()
209211
print(data)
210212

211-
prefix = self.bot.config.get('prefix', 'm.')
213+
prefix = self.bot.prefix
212214

213215
em = discord.Embed(title='Github')
214216

@@ -230,11 +232,11 @@ async def update(self, ctx):
230232

231233
em = discord.Embed(
232234
title='Already up to date',
233-
description=f'The latest version is [`{__version__}`](https://github.com/kyb3r/modmail/blob/master/bot.py#L25)',
235+
description=f'The latest version is [`{self.bot.version}`](https://github.com/kyb3r/modmail/blob/master/bot.py#L25)',
234236
color=discord.Color.green()
235237
)
236238

237-
if metadata['latest_version'] == __version__:
239+
if metadata['latest_version'] == self.bot.version:
238240
data = await self.bot.modmail_api.get_user_info()
239241
if not data['error']:
240242
user = data['user']
@@ -246,7 +248,7 @@ async def update(self, ctx):
246248
user = data['user']
247249
em.title = 'Success'
248250
em.set_author(name=user['username'], icon_url=user['avatar_url'], url=user['url'])
249-
em.set_footer(text=f"Updating modmail v{__version__} -> v{metadata['latest_version']}")
251+
em.set_footer(text=f"Updating modmail v{self.bot.version} -> v{metadata['latest_version']}")
250252

251253
if commit_data:
252254
em.description = 'Bot successfully updated, the bot will restart momentarily'
@@ -264,14 +266,24 @@ async def update(self, ctx):
264266
@commands.command(name="status", aliases=['customstatus', 'presence'])
265267
@commands.has_permissions(administrator=True)
266268
async def _status(self, ctx, *, message):
267-
'''Set a custom playing status for the bot.'''
269+
'''Set a custom playing status for the bot.
270+
271+
Set the message to `clear` if you want to remove the playing status.
272+
'''
273+
268274
if message == 'clear':
275+
self.bot.config['status'] = None
276+
await self.bot.config.update()
269277
return await self.bot.change_presence(activity=None)
278+
279+
270280
await self.bot.change_presence(activity=discord.Game(message))
281+
self.bot.config['status'] = message
282+
await self.bot.config.update()
283+
271284
em = discord.Embed(title='Status Changed')
272285
em.description = message
273286
em.color = discord.Color.green()
274-
em.set_footer(text='Note: this change is temporary.')
275287
await ctx.send(embed=em)
276288

277289
@commands.command()
@@ -285,17 +297,66 @@ async def ping(self, ctx):
285297
em.color = 0x00FF00
286298
await ctx.send(embed=em)
287299

300+
@commands.command()
301+
@commands.has_permissions(administrator=True)
302+
async def mention(self, ctx, *, mention=None):
303+
'''Changes what the bot mentions at the start of each thread.'''
304+
current = self.bot.config.get("mention", "@here")
305+
em = discord.Embed(
306+
title='Current text',
307+
color=discord.Color.green(),
308+
description=f'{current}'
309+
)
310+
311+
if mention is None:
312+
await ctx.send(embed=em)
313+
else:
314+
em.title = 'Changed mention!'
315+
em.description = f'On thread creation the bot now says: {mention}'
316+
self.bot.config['mention'] = mention
317+
await self.bot.config.update()
318+
await ctx.send(embed=em)
319+
320+
@commands.command()
321+
@commands.has_permissions(administrator=True)
322+
async def prefix(self, ctx, *, prefix=None):
323+
'''Changes the prefix for the bot.'''
324+
325+
current = self.bot.config.get("prefix", "m.")
326+
em = discord.Embed(
327+
title='Current prefix',
328+
color=discord.Color.green(),
329+
description=f'{current}'
330+
)
331+
332+
if prefix is None:
333+
await ctx.send(embed=em)
334+
else:
335+
em.title = 'Changed prefix!'
336+
em.description = f'Set prefix to `{prefix}`'
337+
self.bot.config['prefix'] = prefix
338+
339+
await self.bot.config.update()
340+
await ctx.send(embed=em)
341+
342+
288343
@commands.group()
289344
@owner_only()
290345
async def config(self, ctx):
291-
'''Change configuration for the bot.'''
346+
'''Change configuration for the bot.
347+
348+
You shouldn't have to use these commands as other commands such
349+
as `prefix` and `status` should change config vars for you.
350+
'''
292351
if ctx.invoked_subcommand is None:
293352
cmd = self.bot.get_command('help')
294353
await ctx.invoke(cmd, command='config')
295354

296355
@config.command(name='set')
297356
async def _set(self, ctx, key: str.lower, *, value):
298-
'''Sets a configuration variable and its value'''
357+
'''
358+
Sets a configuration variable and its value
359+
'''
299360

300361
em = discord.Embed(
301362
title='Success',
@@ -364,7 +425,76 @@ async def get(self, ctx, key=None):
364425
await ctx.send(embed=em)
365426

366427

428+
@commands.group(name='alias', aliases=['aliases'])
429+
@commands.has_permissions(manage_messages=True)
430+
async def aliases(self, ctx):
431+
'''Returns a list of aliases that are currently set.'''
432+
if ctx.invoked_subcommand is not None:
433+
return
367434

435+
embeds = []
436+
437+
em = discord.Embed(color=discord.Color.green())
438+
em.set_author(name='Command aliases', icon_url=ctx.guild.icon_url)
439+
440+
embeds.append(em)
441+
442+
em.description = 'Here is a list of aliases that are currently configured.'
443+
444+
if not self.bot.aliases:
445+
em.color = discord.Color.red()
446+
em.description = f'You dont have any aliases at the moment.'
447+
em.set_footer(text=f'Do {self.bot.prefix}help aliases for more commands.')
448+
449+
for name, value in self.bot.aliases.items():
450+
if len(em.fields) == 5:
451+
em = discord.Embed(color=discord.Color.green(), description=em.description)
452+
em.set_author(name='Command aliases', icon_url=ctx.guild.icon_url)
453+
embeds.append(em)
454+
em.add_field(name=name, value=value, inline=False)
455+
456+
session = PaginatorSession(ctx, *embeds)
457+
await session.run()
458+
459+
@aliases.command(name='add')
460+
async def _add(self, ctx, name: str.lower, *, value):
461+
'''Add an alias to the bot config.'''
462+
if 'aliases' not in self.bot.config.cache:
463+
self.bot.config['aliases'] = {}
464+
465+
self.bot.config.aliases[name] = value
466+
await self.bot.config.update()
467+
468+
em = discord.Embed(
469+
title='Added alias',
470+
color=discord.Color.green(),
471+
description=f'`{name}` points to: {value}'
472+
)
473+
474+
await ctx.send(embed=em)
475+
476+
@aliases.command(name='del')
477+
async def __del(self, ctx, *, name: str.lower):
478+
'''Removes a alias from bot config.'''
479+
480+
if 'aliases' not in self.bot.config.cache:
481+
self.bot.config['aliases'] = {}
482+
483+
em = discord.Embed(
484+
title='Removed alias',
485+
color=discord.Color.green(),
486+
description=f'`{name}` no longer exists.'
487+
)
488+
489+
if not self.bot.config.aliases.get(name):
490+
em.title = 'Error'
491+
em.color = discord.Color.red()
492+
em.description = f'Alias `{name}` does not exist.'
493+
else:
494+
self.bot.config['aliases'][name] = None
495+
await self.bot.config.update()
496+
497+
await ctx.send(embed=em)
368498

369499
@commands.command(hidden=True, name='eval')
370500
@owner_only()
@@ -447,12 +577,8 @@ def paginate(text: str):
447577
break
448578
await ctx.send(f'```py\n{page}\n```')
449579

450-
if out:
451-
await ctx.message.add_reaction('\u2705') # tick
452-
elif err:
453-
await ctx.message.add_reaction('\u2049') # x
454-
else:
455-
await ctx.message.add_reaction('\u2705')
580+
if err:
581+
await ctx.message.add_reaction('\u2049')
456582

457583

458584
def setup(bot):

core/api.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,7 @@ def get_config(self):
5959
return self.request(self.config)
6060

6161
def update_config(self, data):
62-
valid_keys = ['prefix', 'status', 'owners', 'guild_id', 'mention', 'snippets']
63-
62+
valid_keys = ['prefix', 'status', 'guild_id', 'mention', 'snippets', 'aliases']
6463
data = {k: v for k, v in data.items() if k in valid_keys}
6564
return self.request(self.config, method='PATCH', payload=data)
6665

core/decorators.py

-1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,5 @@ async def wrapper(self, ctx, *args, **kwargs):
2525
def owner_only():
2626
async def predicate(ctx):
2727
allowed = [int(x) for x in str(ctx.bot.config.get('owners', '0')).split(',')]
28-
print(allowed)
2928
return ctx.author.id in allowed
3029
return commands.check(predicate)

0 commit comments

Comments
 (0)