/
moderation.py
203 lines (187 loc) · 8.24 KB
/
moderation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""
This cog is the moderation toolkit this is for tasks such as
kicking/banning users.
"""
import discord
from discord.ext import commands
from discord.utils import find
from .utils import helpers, checks
from .utils.enums import Action
class MemberID(commands.Converter):
async def convert(self, ctx, argument):
try:
m = await commands.MemberConverter().convert(ctx, argument)
except commands.BadArgument:
try:
return int(argument, base=10)
except ValueError:
raise commands.BadArgument(f"{argument} is not a valid'\
'member or member ID.") from None
else:
can_execute = ctx.author.id == ctx.bot.owner_id or \
ctx.author == ctx.guild.owner or \
ctx.author.top_role > m.top_role
if not can_execute:
raise commands.BadArgument('You cannot do this action on this'
' user due to role hierarchy.')
return m.id
class BannedMember(commands.Converter):
async def convert(self, ctx, argument):
ban_list = await ctx.guild.bans()
try:
member_id = int(argument, base=10)
entity = discord.utils.find(
lambda u: u.user.id == member_id, ban_list)
except ValueError:
entity = discord.utils.find(
lambda u: str(u.user) == argument, ban_list)
if entity is None:
raise commands.BadArgument("Not a valid previously-banned member.")
return entity
class ActionReason(commands.Converter):
async def convert(self, ctx, argument):
ret = argument
if len(ret) > 512:
reason_max = 512 - len(ret) - len(argument)
raise commands.BadArgument(
f'reason is too long ({len(argument)}/{reason_max})')
return ret
class Moderation:
"""
Main cog class
"""
def __init__(self, bot):
super().__init__()
self.bot = bot
@commands.command()
@checks.has_permissions(manage_messages=True)
async def purge(self, ctx, *args, mentions=None):
deleted = []
try:
count = int(next(iter(args or []), 'fugg'))
except ValueError:
count = 100
mentions = ctx.message.mentions
await ctx.message.delete()
if mentions:
for user in mentions:
try:
deleted += await ctx.channel.purge(
limit=count,
check=lambda x: x.author == user
)
except discord.Forbidden as e:
return await ctx.send(
'I do not have sufficient permissions to purge.')
except Exception as e:
self.bot.logger.warning(f'Error purging messages: {e}')
else:
try:
deleted += await ctx.channel.purge(limit=count)
except discord.Forbidden as e:
return await ctx.send(
'I do not have sufficient permissions to purge.')
except Exception as e:
self.bot.logger.warning(f'Error purging messages: {e}')
@commands.command()
@checks.has_permissions(manage_roles=True)
async def timeout(self, ctx, member: discord.Member):
guild_roles = ctx.guild.roles
timeout_role = ctx.guild.get_role(self.bot.timeout_id)
confirm = await helpers.confirm(ctx, member, '')
removed_from_channels = []
if confirm:
try:
await member.add_roles(timeout_role)
all_channels = await self.bot.postgres_controller.get_all_channels()
for row in all_channels:
channel = self.bot.get_channel(row['host_channel'])
if not channel:
continue
try:
message = await channel.get_message(row['message_id'])
except:
continue
if not message:
continue
for reaction in message.reactions:
coubt = 0
async for user in reaction.users():
coubt += 1
if user.id == member.id:
self.bot.logger.info(f'{row}')
try:
target_channel = self.bot.get_channel(
row['target_channel'])
await self.remove_perms(member, target_channel)
removed_from_channels.append(target_channel.name)
except Exception as e:
self.bot.logger.warning(f'Error removing user from channel!: {row["target_channel"]}{e}') # noqa
self.bot.logger.warning(f'{row["target_channel"]} - {coubt}') # noqa
except Exception as e:
self.bot.logger.warning(f'Error timing out user!: {e}')
await ctx.send('❌', delete_after=3)
return
# send output to log channel
mod_info = self.bot.get_channel(self.bot.mod_info)
time = self.bot.timestamp()
ret = ', '.join(removed_from_channels)
await mod_info.send(f'**{time} | User: {member.name}#{member.discriminator}: **Successfully TO\'ed and removed from channels: ```{ret}```') # noqa
else:
await ctx.send("Cancelled timeout", delete_after=3)
@commands.command()
@checks.has_permissions(manage_roles=True)
async def untimeout(self, ctx, member: discord.Member):
guild_roles = ctx.guild.roles
timeout_role = ctx.guild.get_role(self.bot.timeout_id)
confirm = await helpers.confirm(ctx, member, '')
removed_from_channels = []
if confirm:
try:
await member.remove_roles(timeout_role)
all_channels = await self.bot.postgres_controller.get_all_channels()
for row in all_channels:
channel = self.bot.get_channel(row['host_channel'])
if not channel:
continue
try:
message = await channel.get_message(row['message_id'])
except:
continue
if not message:
continue
reacted_users = await message.reactions[0].users().flatten()
if member in reacted_users:
try:
target_channel = self.bot.get_channel(row['target_channel'])
await self.add_perms(member, target_channel)
removed_from_channels.append(target_channel.name)
except Exception as e:
self.bot.logger.warning(f'Error removing user from channel!: {row["target_channel"]}{e}')
except Exception as e:
self.bot.logger.warning(f'Error untiming out user!: {e}')
await ctx.send('❌', delete_after=3)
return
# send output to log channel
mod_info = self.bot.get_channel(self.bot.mod_info)
time = self.bot.timestamp()
ret = ', '.join(removed_from_channels)
await mod_info.send(f'**{time} | User: {member.name}#{member.discriminator}: **Successfully un-TO\'ed and re-added to channels: ```{ret}```') # noqa
else:
await ctx.send("Cancelled timeout", delete_after=3)
async def add_perms(self, user, channel):
"""
Adds a user to channels perms
"""
try:
await channel.set_permissions(user, read_messages=True)
except Exception as e:
self.bot.logger.warning(f'{e}')
async def remove_perms(self, user, channel):
"""
removes a users perms on a channel
"""
try:
await channel.set_permissions(user, read_messages=False)
except Exception as e:
self.bot.logger.warning(f'{e}')