-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
189 lines (146 loc) · 5.42 KB
/
main.py
File metadata and controls
189 lines (146 loc) · 5.42 KB
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
from collections import defaultdict
from discord import app_commands
import asyncio
import discord
import dotenv
import os
import re
dotenv.load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
GUILD_ID = int(os.getenv("GUILD_ID"))
COUNTING_CHANNEL_ID = int(os.getenv("COUNTING_CHANNEL_ID"))
LOG_CHANNEL_ID = int(os.getenv("LOG_CHANNEL_ID"))
intents = discord.Intents().all()
bot = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(bot)
bot_deletions = []
def sanitize(msg):
prefix = ""
if "`" in msg:
prefix = " (contained backticks, stripped below)"
prefix += ":\n```"
msg = msg.replace("`", "")
if len(msg) > 100:
msg = msg[:100] + "... [TRUNCATED]"
return f"{prefix}\n{msg}\n```"
async def aenumerate(asequence):
n = 0
async for elem in asequence:
yield n, elem
n += 1
async def get_invalid():
counting_channel = bot.get_channel(COUNTING_CHANNEL_ID)
messages = counting_channel.history(limit=None, oldest_first=True)
current = 0
invalid = []
async for i, msg in aenumerate(messages):
if len(invalid) > 0:
invalid.append(msg)
continue
if int(msg.content) == current + 1:
current += 1
else:
invalid.append(msg)
return invalid
async def purge(invalid):
# Delete latest first
for msg in invalid[::-1]:
bot_deletions.append(msg.id)
await msg.delete()
@tree.command(name="counters", description="Counting statistics", guild=discord.Object(id=GUILD_ID))
async def stats(interaction: discord.Interaction):
if interaction.channel.id == COUNTING_CHANNEL_ID:
return
# Respond immediately and send stats as normal message later
# (Discord has 3 second response limit)
await interaction.response.send_message("Collecting stats...")
counting_channel = bot.get_channel(COUNTING_CHANNEL_ID)
messages = counting_channel.history(limit=None, oldest_first=True)
counts = defaultdict(int)
async for i, msg in aenumerate(messages):
# Skip rules message
if i == 0:
continue
counts[msg.author] += 1
response = "```\n"
response += "=" * 20 + "\n STATISTICS\n" + "=" * 20 + "\n"
for author, count in sorted(counts.items(), key=lambda x: x[1], reverse=True):
response += f"{author.display_name}: {count}\n"
response += "```"
await interaction.channel.send(response)
@tree.command(name="validate", description="Validate order and purge mistakes", guild=discord.Object(id=GUILD_ID))
@app_commands.checks.has_permissions(administrator=True)
async def validate(interaction: discord.Interaction):
if interaction.channel.id == COUNTING_CHANNEL_ID:
return
await interaction.response.send_message("Validating...")
invalid = await get_invalid()
if len(invalid) == 0:
await interaction.channel.send("No errors found in sequence")
return
await interaction.channel.send(f"Error(s) found, purging {len(invalid)} messages...")
await purge(invalid)
await interaction.channel.send(f"Invalid messages purged, sequence restored!")
@bot.event
async def on_message(message: discord.Message):
if message.author == bot.user or message.channel.id != COUNTING_CHANNEL_ID:
return
previous = [msg async for msg in message.channel.history(limit=2)][1]
has_error = False
if len(message.attachments) > 0:
error = "a message with an attachment (not re-posted here)"
has_error = True
elif re.fullmatch(r"\d+", message.content, flags=re.ASCII) is None:
error = "a non-decimal message"
has_error = True
elif int(message.content) != int(previous.content) + 1:
error = "the wrong next number"
has_error = True
elif message.author == previous.author:
error = "two messages in a row"
has_error = True
if has_error:
msg = sanitize(message.content)
try:
await bot.get_channel(LOG_CHANNEL_ID).send(
f""":bell: SHAME, SHAME, SHAME :bell:
[<#{COUNTING_CHANNEL_ID}>] <@{message.author.id}> posted {error}{msg}
"""
)
except:
await bot.get_channel(LOG_CHANNEL_ID).send(
"I don't know what you just did, but you caused an exception :("
)
finally:
bot_deletions.append(message.id)
await message.delete()
return
@bot.event
async def on_message_edit(before: discord.Message, after: discord.Message):
if before.channel.id != COUNTING_CHANNEL_ID:
return
if len(await get_invalid()) == 0:
return
message = sanitize(f"{before.content} -> {after.content}")
await bot.get_channel(LOG_CHANNEL_ID).send(
f""":bell: SHAME, SHAME, SHAME :bell:
[<#{COUNTING_CHANNEL_ID}>] <@{before.author.id}> edited their message{message}
Please edit your post back
"""
)
@bot.event
async def on_message_delete(message: discord.Message):
if message.channel.id != COUNTING_CHANNEL_ID or message.id in bot_deletions:
return
await bot.get_channel(LOG_CHANNEL_ID).send(
f""":bell: SHAME, SHAME, SHAME :bell:
[<#{COUNTING_CHANNEL_ID}>] A message by <@{message.author.id}> was deleted{sanitize(message.content)}
Purging all subsequent posts..."""
)
invalid = await get_invalid()
await purge(invalid)
@bot.event
async def on_ready():
await tree.sync(guild=discord.Object(id=GUILD_ID))
print("Ready!")
bot.run(TOKEN)