Skip to content

Commit fb67e54

Browse files
authored
Merge pull request #109 from kyb3r/v2.0.8-dev
Improvements in block command and new config options available. (v2.0.8)
2 parents ea8a845 + 9165e57 commit fb67e54

File tree

5 files changed

+73
-48
lines changed

5 files changed

+73
-48
lines changed

CHANGELOG.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,22 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
55
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

7+
8+
# v2.0.8
9+
10+
Improvements in commands and new config options available.
11+
12+
### Added
13+
- Added the ability to use your own log channel
14+
- You can do this via the `config set log_channel_id <id>` command.
15+
- Added the ability to use your own main inbox category.
16+
- You can do this via the `config set main_category_id <id>` command.
17+
18+
### Changed
19+
- You now have the ability to supply a reason when blocking a user.
20+
- Blocked users are now stored in the database instead of in the channel topic.
21+
- This means you can delete the top channel in the modmail category now. (Migrate first though.)
22+
723
# v2.0.7
824

925
New command and improvements in bot update message interfaces.

bot.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
SOFTWARE.
2323
"""
2424

25-
__version__ = '2.0.7'
25+
__version__ = '2.0.8'
2626

2727
import asyncio
2828
import textwrap
@@ -91,6 +91,14 @@ def run(self):
9191
super().run(self.token)
9292
finally:
9393
print(Fore.RED + ' - Shutting down bot' + Style.RESET_ALL)
94+
95+
@property
96+
def log_channel(self):
97+
channel_id = self.config.get('log_channel_id')
98+
if channel_id is not None:
99+
return self.get_channel(int(channel_id))
100+
else:
101+
return self.main_category.channels[0]
94102

95103
@property
96104
def snippets(self):
@@ -128,14 +136,15 @@ def using_multiple_server_setup(self):
128136

129137
@property
130138
def main_category(self):
139+
category_id = self.config.get('main_category_id')
140+
if category_id is not None:
141+
return discord.utils.get(self.modmail_guild.categories, id=int(category_id))
131142
if self.modmail_guild:
132143
return discord.utils.get(self.modmail_guild.categories, name='Mod Mail')
133144

134145
@property
135146
def blocked_users(self):
136-
if self.modmail_guild:
137-
top_chan = self.main_category.channels[0]
138-
return [int(i) for i in re.findall(r'\d+', top_chan.topic)]
147+
return self.config.get('blocked', {})
139148

140149
@property
141150
def prefix(self):
@@ -167,7 +176,7 @@ async def on_ready(self):
167176
{Fore.CYAN}Guild ID: {self.guild.id if self.guild else 0}
168177
{line}
169178
""").strip())
170-
179+
171180
if not self.guild:
172181
print(Fore.RED + Style.BRIGHT + 'WARNING - The GUILD_ID provided does not exist!' + Style.RESET_ALL)
173182
else:
@@ -292,7 +301,7 @@ async def on_guild_channel_delete(self, channel):
292301
desc = f"[`{log_data['key']}`]({log_url}) {mod.mention} closed a thread with {user}"
293302
em = discord.Embed(description=desc, color=em.color)
294303
em.set_author(name='Thread closed', url=log_url)
295-
await self.main_category.channels[0].send(embed=em)
304+
await self.log_channel.send(embed=em)
296305

297306
async def on_message_delete(self, message):
298307
"""Support for deleting linked messages"""
@@ -414,7 +423,7 @@ async def autoupdate_loop(self):
414423
short_sha = commit_data['sha'][:6]
415424
em.add_field(name='Merge Commit', value=f"[`{short_sha}`]({html_url}) {message} - {user['username']}")
416425
print('Updating bot.')
417-
channel = self.main_category.channels[0]
426+
channel = self.log_channel
418427
await channel.send(embed=em)
419428

420429
await asyncio.sleep(3600)

cogs/modmail.py

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ async def setup(self, ctx):
3030
await categ.edit(position=0)
3131

3232
c = await self.bot.modmail_guild.create_text_channel(name='bot-logs', category=categ)
33-
await c.edit(topic='Manually add user id\'s to block users.\n\n'
34-
'Blocked\n-------\n\n')
33+
await c.edit(topic='You can delete this channel if you set up your own log channel.')
34+
await c.send('Use the `config set log_channel_id` command to set up a custom log channel.')
3535

3636
await ctx.send('Successfully set up server.')
3737

@@ -87,9 +87,6 @@ async def _add(self, ctx, name: str.lower, *, value):
8787
async def __del(self, ctx, *, name: str.lower):
8888
"""Removes a snippet from bot config."""
8989

90-
if 'snippets' not in self.bot.config.cache:
91-
self.bot.config['snippets'] = {}
92-
9390
em = discord.Embed(
9491
title='Removed snippet',
9592
color=discord.Color.green(),
@@ -101,7 +98,7 @@ async def __del(self, ctx, *, name: str.lower):
10198
em.color = discord.Color.red()
10299
em.description = f'Snippet `{name}` does not exist.'
103100
else:
104-
self.bot.config['snippets'][name] = None
101+
del self.bot.config['snippets'][name]
105102
await self.bot.config.update()
106103

107104
await ctx.send(embed=em)
@@ -138,8 +135,7 @@ async def _close(self, ctx):
138135
pass
139136

140137
# Logging
141-
categ = self.bot.main_category
142-
log_channel = categ.channels[0]
138+
log_channel = self.bot.log_channel
143139

144140
log_data = await self.bot.modmail_api.post_log(ctx.channel.id, {
145141
'open': False, 'closed_at': str(datetime.datetime.utcnow()), 'closer': {
@@ -151,6 +147,9 @@ async def _close(self, ctx):
151147
}
152148
})
153149

150+
if isinstance(log_data, str):
151+
print(log_data) # error
152+
154153
log_url = f"https://logs.modmail.tk/{log_data['user_id']}/{log_data['key']}"
155154

156155
user = thread.recipient.mention if thread.recipient else f'`{thread.id}`'
@@ -300,19 +299,19 @@ async def blocked(self, ctx):
300299
users = []
301300
not_reachable = []
302301

303-
for id in self.bot.blocked_users:
304-
user = self.bot.get_user(id)
302+
for id, reason in self.bot.blocked_users.items():
303+
user = self.bot.get_user(int(id))
305304
if user:
306-
users.append(user)
305+
users.append((user, reason))
307306
else:
308-
not_reachable.append(id)
307+
not_reachable.append((id, reason))
309308

310309
em.description = 'Here is a list of blocked users.'
311310

312311
if users:
313-
em.add_field(name='Currently Known', value=' '.join(u.mention for u in users))
312+
em.add_field(name='Currently Known', value='\n'.join(u.mention + (f' - `{r}`' if r else '') for u, r in users))
314313
if not_reachable:
315-
em.add_field(name='Unknown', value='\n'.join(f'`{i}`' for i in not_reachable), inline=False)
314+
em.add_field(name='Unknown', value='\n'.join(f'`{i}`' + (f' - `{r}`' if r else '') for i, r in not_reachable), inline=False)
316315

317316
if not users and not not_reachable:
318317
em.description = 'Currently there are no blocked users'
@@ -322,7 +321,7 @@ async def blocked(self, ctx):
322321
@commands.command()
323322
@trigger_typing
324323
@commands.has_permissions(manage_channels=True)
325-
async def block(self, ctx, *, user: Union[discord.Member, discord.User, obj]=None):
324+
async def block(self, ctx, user: Union[discord.Member, discord.User, obj]=None, *, reason=None):
326325
"""Block a user from using modmail."""
327326

328327
if user is None:
@@ -332,21 +331,18 @@ async def block(self, ctx, *, user: Union[discord.Member, discord.User, obj]=Non
332331
else:
333332
raise commands.UserInputError
334333

335-
categ = self.bot.main_category
336-
top_chan = categ.channels[0] # bot-info
337-
topic = str(top_chan.topic)
338-
topic += '\n' + str(user.id)
339-
334+
340335
mention = user.mention if hasattr(user, 'mention') else f'`{user.id}`'
341336

342337
em = discord.Embed()
343338
em.color = discord.Color.green()
344339

345-
if str(user.id) not in top_chan.topic:
346-
await top_chan.edit(topic=topic)
340+
if str(user.id) not in self.bot.blocked_users:
341+
self.bot.config.blocked[str(user.id)] = reason
342+
await self.bot.config.update()
347343

348344
em.title = 'Success'
349-
em.description = f'{mention} is now blocked'
345+
em.description = f'{mention} is now blocked ' + f'for `{reason}`' if reason else ''
350346

351347
await ctx.send(embed=em)
352348
else:
@@ -369,18 +365,14 @@ async def unblock(self, ctx, *, user: Union[discord.Member, discord.User, obj]=N
369365
else:
370366
raise commands.UserInputError
371367

372-
categ = self.bot.main_category
373-
top_chan = categ.channels[0] # thread-logs
374-
topic = str(top_chan.topic)
375-
topic = topic.replace('\n' + str(user.id), '')
376-
377368
mention = user.mention if hasattr(user, 'mention') else f'`{user.id}`'
378369

379370
em = discord.Embed()
380371
em.color = discord.Color.green()
381372

382-
if str(user.id) in top_chan.topic:
383-
await top_chan.edit(topic=topic)
373+
if str(user.id) in self.bot.blocked_users:
374+
del self.bot.config.blocked[str(user.id)]
375+
await self.bot.config.update()
384376

385377
em.title = 'Success'
386378
em.description = f'{mention} is no longer blocked'

cogs/utility.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ async def _del(self, ctx, key: str.lower):
392392
valid_keys = [f'`{k}`' for k in self.bot.config.allowed_to_change_in_command]
393393
em.add_field(name='Valid keys', value=', '.join(valid_keys))
394394
else:
395-
self.bot.config.cache[key] = None
395+
del self.bot.config.cache[key]
396396
await self.bot.config.update()
397397

398398
await ctx.send(embed=em)
@@ -498,7 +498,7 @@ async def __del(self, ctx, *, name: str.lower):
498498
em.color = discord.Color.red()
499499
em.description = f'Alias `{name}` does not exist.'
500500
else:
501-
self.bot.config['aliases'][name] = None
501+
del self.bot.config['aliases'][name]
502502
await self.bot.config.update()
503503

504504
await ctx.send(embed=em)

core/config.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,17 @@
66
class ConfigManager:
77
"""Class that manages a cached configuration"""
88

9-
valid_keys = {
10-
'prefix', 'status', 'guild_id',
11-
'mention', 'disable_autoupdates',
12-
'modmail_guild_id', 'token', 'snippets',
13-
'aliases', 'owners', 'modmail_api_token'
14-
}
9+
allowed_to_change_in_command = {
10+
'status', 'log_channel_id', 'mention', 'disable_autoupdates', 'prefix',
11+
'main_category_id'
12+
}
13+
14+
internal_keys = {
15+
'token', 'snippets', 'aliases', 'owners', 'modmail_api_token',
16+
'guild_id', 'modmail_guild_id', 'blocked'
17+
}
1518

16-
allowed_to_change_in_command = valid_keys - {'token', 'snippets', 'aliases', 'owners', 'modmail_api_token'}
19+
valid_keys = allowed_to_change_in_command.union(internal_keys)
1720

1821
def __init__(self, bot):
1922
self.bot = bot
@@ -26,10 +29,15 @@ def api(self):
2629
return self.bot.modmail_api
2730

2831
def populate_cache(self):
32+
data = {
33+
'snippets': {},
34+
'aliases': {},
35+
'blocked': {}
36+
}
2937
try:
30-
data = json.load(open('config.json'))
38+
data.update(json.load(open('config.json')))
3139
except FileNotFoundError:
32-
data = {}
40+
pass
3341
finally:
3442
data.update(os.environ)
3543
data = {k.lower(): v for k, v in data.items() if k.lower() in self.valid_keys}

0 commit comments

Comments
 (0)