|
|
@@ -1,16 +1,221 @@
|
|
1
|
|
-from discord import Guild, Message, PartialEmoji, RawReactionActionEvent, TextChannel
|
|
|
1
|
+from discord import Guild, Member, Message, PartialEmoji, RawReactionActionEvent, TextChannel
|
|
2
|
2
|
from discord.ext import commands
|
|
3
|
|
-from datetime import timedelta
|
|
|
3
|
+from datetime import datetime, timedelta
|
|
4
|
4
|
|
|
5
|
5
|
from config import CONFIG
|
|
6
|
6
|
from rscollections import AgeBoundDict
|
|
7
|
7
|
from storage import ConfigKey, Storage
|
|
8
|
8
|
import json
|
|
9
|
9
|
|
|
|
10
|
+class BotMessageReaction:
|
|
|
11
|
+ """
|
|
|
12
|
+ A possible reaction to a bot message that will trigger an action. The list
|
|
|
13
|
+ of available reactions will be listed at the end of a BotMessage. When a
|
|
|
14
|
+ mod reacts to the message with the emote, something can happen.
|
|
|
15
|
+
|
|
|
16
|
+ If the reaction is disabled, reactions will not register. The description
|
|
|
17
|
+ will still show up in the message, but no emoji is shown. This can be used
|
|
|
18
|
+ to explain why an action is no longer available.
|
|
|
19
|
+ """
|
|
|
20
|
+ def __init__(self, emoji: str, is_enabled: bool, description: str):
|
|
|
21
|
+ self.emoji = emoji
|
|
|
22
|
+ self.is_enabled = is_enabled
|
|
|
23
|
+ self.description = description
|
|
|
24
|
+
|
|
|
25
|
+ def __eq__(self, other):
|
|
|
26
|
+ return other is not None and \
|
|
|
27
|
+ other.emoji == self.emoji and \
|
|
|
28
|
+ other.is_enabled == self.is_enabled and \
|
|
|
29
|
+ other.description == self.description
|
|
|
30
|
+
|
|
|
31
|
+class BotMessage:
|
|
|
32
|
+ """
|
|
|
33
|
+ Holds state for a bot-generated message. A message is composed, sent via
|
|
|
34
|
+ `BaseCog.post_message()`, and can later be updated.
|
|
|
35
|
+
|
|
|
36
|
+ A message consists of a type (e.g. info, warning), text, optional quoted
|
|
|
37
|
+ text (such as the content of a flagged message), and an optional list of
|
|
|
38
|
+ actions that can be taken via a mod reacting to the message.
|
|
|
39
|
+ """
|
|
|
40
|
+
|
|
|
41
|
+ TYPE_DEFAULT = 0
|
|
|
42
|
+ TYPE_INFO = 1
|
|
|
43
|
+ TYPE_MOD_WARNING = 2
|
|
|
44
|
+ TYPE_SUCCESS = 3
|
|
|
45
|
+ TYPE_FAILURE = 4
|
|
|
46
|
+
|
|
|
47
|
+ def __init__(self,
|
|
|
48
|
+ guild: Guild,
|
|
|
49
|
+ text: str,
|
|
|
50
|
+ type: int = 0, # TYPE_DEFAULT
|
|
|
51
|
+ context = None,
|
|
|
52
|
+ reply_to: Message = None):
|
|
|
53
|
+ self.guild = guild
|
|
|
54
|
+ self.text = text
|
|
|
55
|
+ self.type = type
|
|
|
56
|
+ self.context = context
|
|
|
57
|
+ self.quote = None
|
|
|
58
|
+ self.__posted_text = None # last text posted, to test for changes
|
|
|
59
|
+ self.__posted_emoji = set()
|
|
|
60
|
+ self.__message = None # Message
|
|
|
61
|
+ self.__reply_to = reply_to
|
|
|
62
|
+ self.__reactions = [] # BotMessageReaction[]
|
|
|
63
|
+
|
|
|
64
|
+ def is_sent(self) -> bool:
|
|
|
65
|
+ """
|
|
|
66
|
+ Returns whether this message has been sent to the guild. This may
|
|
|
67
|
+ continue returning False even after calling BaseCog.post_message if
|
|
|
68
|
+ the guild has no configured warning channel.
|
|
|
69
|
+ """
|
|
|
70
|
+ return self.__message is not None
|
|
|
71
|
+
|
|
|
72
|
+ def message_id(self):
|
|
|
73
|
+ return self.__message.id if self.__message else None
|
|
|
74
|
+
|
|
|
75
|
+ def message_sent_at(self):
|
|
|
76
|
+ return self.__message.created_at if self.__message else None
|
|
|
77
|
+
|
|
|
78
|
+ async def set_text(self, new_text: str) -> None:
|
|
|
79
|
+ """
|
|
|
80
|
+ Replaces the text of this message. If the message has been sent, it will
|
|
|
81
|
+ be updated.
|
|
|
82
|
+ """
|
|
|
83
|
+ self.text = new_text
|
|
|
84
|
+ await self.__update_if_sent()
|
|
|
85
|
+
|
|
|
86
|
+ async def set_reactions(self, reactions: list) -> None:
|
|
|
87
|
+ """
|
|
|
88
|
+ Replaces all BotMessageReactions with a new list. If the message has
|
|
|
89
|
+ been sent, it will be updated.
|
|
|
90
|
+ """
|
|
|
91
|
+ if reactions == self.__reactions:
|
|
|
92
|
+ # No change
|
|
|
93
|
+ return
|
|
|
94
|
+ self.__reactions = reactions.copy() if reactions is not None else []
|
|
|
95
|
+ await self.__update_if_sent()
|
|
|
96
|
+
|
|
|
97
|
+ async def add_reaction(self, reaction: BotMessageReaction) -> None:
|
|
|
98
|
+ """
|
|
|
99
|
+ Adds one BotMessageReaction to this message. If a reaction already
|
|
|
100
|
+ exists for the given emoji it is replaced with the new one. If the
|
|
|
101
|
+ message has been sent, it will be updated.
|
|
|
102
|
+ """
|
|
|
103
|
+ # Alias for update. Makes for clearer intent.
|
|
|
104
|
+ await self.update_reaction(reaction)
|
|
|
105
|
+
|
|
|
106
|
+ async def update_reaction(self, reaction: BotMessageReaction) -> None:
|
|
|
107
|
+ """
|
|
|
108
|
+ Updates or adds a BotMessageReaction. If the message has been sent, it
|
|
|
109
|
+ will be updated.
|
|
|
110
|
+ """
|
|
|
111
|
+ found = False
|
|
|
112
|
+ for i in range(len(self.__reactions)):
|
|
|
113
|
+ existing = self.__reactions[i]
|
|
|
114
|
+ if existing.emoji == reaction.emoji:
|
|
|
115
|
+ if reaction == self.__reactions[i]:
|
|
|
116
|
+ # No change
|
|
|
117
|
+ return
|
|
|
118
|
+ self.__reactions[i] = reaction
|
|
|
119
|
+ found = True
|
|
|
120
|
+ break
|
|
|
121
|
+ if not found:
|
|
|
122
|
+ self.__reactions.append(reaction)
|
|
|
123
|
+ await self.__update_if_sent()
|
|
|
124
|
+
|
|
|
125
|
+ async def remove_reaction(self, reaction_or_emoji) -> None:
|
|
|
126
|
+ """
|
|
|
127
|
+ Removes a reaction. Can pass either a BotMessageReaction or just the
|
|
|
128
|
+ emoji string. If the message has been sent, it will be updated.
|
|
|
129
|
+ """
|
|
|
130
|
+ for i in range(len(self.__reactions)):
|
|
|
131
|
+ existing = self.__reactions[i]
|
|
|
132
|
+ if (isinstance(reaction_or_emoji, str) and existing.emoji == reaction_or_emoji) or \
|
|
|
133
|
+ (isinstance(reaction_or_emoji, BotMessageReaction) and existing.emoji == reaction_or_emoji.emoji):
|
|
|
134
|
+ self.__reactions.pop(i)
|
|
|
135
|
+ await self.__update_if_sent()
|
|
|
136
|
+ return
|
|
|
137
|
+
|
|
|
138
|
+ def reaction_for_emoji(self, emoji) -> BotMessageReaction:
|
|
|
139
|
+ for reaction in self.__reactions:
|
|
|
140
|
+ if isinstance(emoji, PartialEmoji) and reaction.emoji == emoji.name:
|
|
|
141
|
+ return reaction
|
|
|
142
|
+ elif isinstance(emoji, str) and reaction.emoji == emoji:
|
|
|
143
|
+ return reaction
|
|
|
144
|
+ return None
|
|
|
145
|
+
|
|
|
146
|
+ async def __update_if_sent(self) -> None:
|
|
|
147
|
+ if self.__message:
|
|
|
148
|
+ await self._update()
|
|
|
149
|
+
|
|
|
150
|
+ async def _update(self) -> None:
|
|
|
151
|
+ content: str = self.__formatted_message()
|
|
|
152
|
+ if self.__message:
|
|
|
153
|
+ if content != self.__posted_text:
|
|
|
154
|
+ await self.__message.edit(content=content)
|
|
|
155
|
+ self.__posted_text = content
|
|
|
156
|
+ else:
|
|
|
157
|
+ if self.__reply_to:
|
|
|
158
|
+ self.__message = await self.__reply_to.reply(content=content, mention_author=False)
|
|
|
159
|
+ self.__posted_text = content
|
|
|
160
|
+ else:
|
|
|
161
|
+ channel_id = Storage.get_config_value(self.guild, ConfigKey.WARNING_CHANNEL_ID)
|
|
|
162
|
+ if channel_id is None:
|
|
|
163
|
+ BaseCog.guild_trace(self.guild, 'No warning channel set! No warning issued.')
|
|
|
164
|
+ return
|
|
|
165
|
+ channel: TextChannel = self.guild.get_channel(channel_id)
|
|
|
166
|
+ if channel is None:
|
|
|
167
|
+ BaseCog.guild_trace(self.guild, 'Configured warning channel does not exist!')
|
|
|
168
|
+ return
|
|
|
169
|
+ self.__message = await channel.send(content=content)
|
|
|
170
|
+ self.__posted_text = content
|
|
|
171
|
+ emoji_to_remove = self.__posted_emoji.copy()
|
|
|
172
|
+ for reaction in self.__reactions:
|
|
|
173
|
+ if reaction.is_enabled:
|
|
|
174
|
+ if reaction.emoji not in self.__posted_emoji:
|
|
|
175
|
+ await self.__message.add_reaction(reaction.emoji)
|
|
|
176
|
+ self.__posted_emoji.add(reaction.emoji)
|
|
|
177
|
+ if reaction.emoji in emoji_to_remove:
|
|
|
178
|
+ emoji_to_remove.remove(reaction.emoji)
|
|
|
179
|
+ for emoji in emoji_to_remove:
|
|
|
180
|
+ await self.__message.clear_reaction(emoji)
|
|
|
181
|
+ if emoji in self.__posted_emoji:
|
|
|
182
|
+ self.__posted_emoji.remove(emoji)
|
|
|
183
|
+
|
|
|
184
|
+ def __formatted_message(self) -> str:
|
|
|
185
|
+ s: str = ''
|
|
|
186
|
+
|
|
|
187
|
+ if self.type == self.TYPE_INFO:
|
|
|
188
|
+ s += CONFIG['info_emoji'] + ' '
|
|
|
189
|
+ elif self.type == self.TYPE_MOD_WARNING:
|
|
|
190
|
+ mention: str = Storage.get_config_value(self.guild, ConfigKey.WARNING_MENTION)
|
|
|
191
|
+ if mention:
|
|
|
192
|
+ s += mention + ' '
|
|
|
193
|
+ s += CONFIG['warning_emoji'] + ' '
|
|
|
194
|
+ elif self.type == self.TYPE_SUCCESS:
|
|
|
195
|
+ s += CONFIG['success_emoji'] + ' '
|
|
|
196
|
+ elif self.type == self.TYPE_FAILURE:
|
|
|
197
|
+ s += CONFIG['failure_emoji'] + ' '
|
|
|
198
|
+
|
|
|
199
|
+ s += self.text
|
|
|
200
|
+
|
|
|
201
|
+ if self.quote:
|
|
|
202
|
+ s += f'\n\n> {self.quote}'
|
|
|
203
|
+
|
|
|
204
|
+ if len(self.__reactions) > 0:
|
|
|
205
|
+ s += '\n\nAvailable actions:'
|
|
|
206
|
+ for reaction in self.__reactions:
|
|
|
207
|
+ if reaction.is_enabled:
|
|
|
208
|
+ s += f'\n {reaction.emoji} {reaction.description}'
|
|
|
209
|
+ else:
|
|
|
210
|
+ s += f'\n {reaction.description}'
|
|
|
211
|
+
|
|
|
212
|
+ return s
|
|
|
213
|
+
|
|
10
|
214
|
class BaseCog(commands.Cog):
|
|
11
|
215
|
def __init__(self, bot):
|
|
12
|
216
|
self.bot = bot
|
|
13
|
|
- self.listened_mod_react_message_ids = AgeBoundDict(timedelta(minutes=5), lambda message_id, tpl : tpl[0])
|
|
|
217
|
+
|
|
|
218
|
+ # Config
|
|
14
|
219
|
|
|
15
|
220
|
@classmethod
|
|
16
|
221
|
def get_cog_default(cls, key: str):
|
|
|
@@ -24,14 +229,26 @@ class BaseCog(commands.Cog):
|
|
24
|
229
|
return None
|
|
25
|
230
|
return cog.get(key)
|
|
26
|
231
|
|
|
27
|
|
- def listen_for_reactions_to(self, message: Message, context = None) -> None:
|
|
28
|
|
- """
|
|
29
|
|
- Registers a warning message as something a mod may react to to enact
|
|
30
|
|
- some action. `context` will be passed back in `on_mod_react` and can be
|
|
31
|
|
- any value that helps give the cog context about the action being
|
|
32
|
|
- performed.
|
|
33
|
|
- """
|
|
34
|
|
- self.listened_mod_react_message_ids[message.id] = (message.created_at, context)
|
|
|
232
|
+ # Bot message handling
|
|
|
233
|
+
|
|
|
234
|
+ @classmethod
|
|
|
235
|
+ def __bot_messages(cls, guild: Guild) -> AgeBoundDict:
|
|
|
236
|
+ bm = Storage.get_state_value(guild, 'bot_messages')
|
|
|
237
|
+ if bm is None:
|
|
|
238
|
+ far_future = datetime.utcnow() + timedelta(days=1000)
|
|
|
239
|
+ bm = AgeBoundDict(timedelta(seconds=600),
|
|
|
240
|
+ lambda k, v : v.message_sent_at() or far_future)
|
|
|
241
|
+ Storage.set_state_value(guild, 'bot_messages', bm)
|
|
|
242
|
+ return bm
|
|
|
243
|
+
|
|
|
244
|
+ @classmethod
|
|
|
245
|
+ async def post_message(cls, message: BotMessage) -> bool:
|
|
|
246
|
+ await message._update()
|
|
|
247
|
+ guild_messages = cls.__bot_messages(message.guild)
|
|
|
248
|
+ if message.is_sent():
|
|
|
249
|
+ guild_messages[message.message_id()] = message
|
|
|
250
|
+ return True
|
|
|
251
|
+ return False
|
|
35
|
252
|
|
|
36
|
253
|
@commands.Cog.listener()
|
|
37
|
254
|
async def on_raw_reaction_add(self, payload: RawReactionActionEvent):
|
|
|
@@ -57,27 +274,32 @@ class BaseCog(commands.Cog):
|
|
57
|
274
|
if message.author.id != self.bot.user.id:
|
|
58
|
275
|
# Bot didn't author this
|
|
59
|
276
|
return
|
|
60
|
|
- if not member.permissions_in(channel).ban_members:
|
|
61
|
|
- # Not a mod
|
|
|
277
|
+ guild_messages = self.__bot_messages(guild)
|
|
|
278
|
+ bot_message = guild_messages.get(message.id)
|
|
|
279
|
+ if bot_message is None:
|
|
|
280
|
+ # Unknown message (expired or was never tracked)
|
|
62
|
281
|
return
|
|
63
|
|
- tpl = self.listened_mod_react_message_ids.get(message.id)
|
|
64
|
|
- if tpl is None:
|
|
65
|
|
- # Not a message we're listening for
|
|
|
282
|
+ reaction = bot_message.reaction_for_emoji(payload.emoji)
|
|
|
283
|
+ if reaction is None or not reaction.is_enabled:
|
|
|
284
|
+ # Can't use this reaction with this message
|
|
66
|
285
|
return
|
|
67
|
|
- context = tpl[1]
|
|
68
|
|
- await self.on_mod_react(message, payload.emoji, context)
|
|
|
286
|
+ if not member.permissions_in(channel).ban_members:
|
|
|
287
|
+ # Not a mod (could make permissions configurable per BotMessageReaction some day)
|
|
|
288
|
+ return
|
|
|
289
|
+ await self.on_mod_react(bot_message, reaction, member)
|
|
69
|
290
|
|
|
70
|
|
- async def on_mod_react(self, message: Message, emoji: PartialEmoji, context) -> None:
|
|
|
291
|
+ async def on_mod_react(self,
|
|
|
292
|
+ bot_message: BotMessage,
|
|
|
293
|
+ reaction: BotMessageReaction,
|
|
|
294
|
+ reacted_by: Member) -> None:
|
|
71
|
295
|
"""
|
|
72
|
|
- Override point for getting a mod's emote on a bot message. Used to take
|
|
73
|
|
- action on a warning, such as banning an offending user. This event is
|
|
74
|
|
- only triggered for registered bot messages and reactions by members
|
|
75
|
|
- with the proper permissions. The given `context` value is whatever was
|
|
76
|
|
- passed in `listen_to_reactions_to()`.
|
|
|
296
|
+ Subclass override point for receiving mod reactions to bot messages sent
|
|
|
297
|
+ via `post_message()`.
|
|
77
|
298
|
"""
|
|
78
|
299
|
pass
|
|
79
|
300
|
|
|
80
|
|
- async def validate_param(self, context: commands.Context, param_name: str, value,
|
|
|
301
|
+ @classmethod
|
|
|
302
|
+ async def validate_param(cls, context: commands.Context, param_name: str, value,
|
|
81
|
303
|
allowed_types: tuple = None,
|
|
82
|
304
|
min_value = None,
|
|
83
|
305
|
max_value = None) -> bool:
|
|
|
@@ -87,6 +309,7 @@ class BaseCog(commands.Cog):
|
|
87
|
309
|
to the original message and a False will be returned. If all checks
|
|
88
|
310
|
succeed, True will be returned.
|
|
89
|
311
|
"""
|
|
|
312
|
+ # TODO: Rework this to use BotMessage
|
|
90
|
313
|
if allowed_types is not None and not isinstance(value, allowed_types):
|
|
91
|
314
|
if len(allowed_types) == 1:
|
|
92
|
315
|
await context.message.reply(f'⚠️ `{param_name}` must be of type ' +
|