forked from MUNComputerScienceSociety/Automata
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBot.py
260 lines (205 loc) · 7.22 KB
/
Bot.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
from dotenv import load_dotenv
load_dotenv()
import os
import logging
import traceback
import contextlib
import sys
from pathlib import Path
from io import StringIO
from jigsaw.PluginLoader import PluginLoader
import nextcord
from nextcord.ext import commands
from prometheus_async.aio.web import start_http_server
from Plugin import AutomataPlugin
from Globals import (
DISABLED_PLUGINS,
ENABLED_PLUGINS,
)
IGNORED_LOGGERS = [
"discord.client",
"discord.gateway",
"discord.state",
"discord.gateway",
"discord.http",
"websockets.protocol",
]
# Configure logger and silence ignored loggers
logging.basicConfig(
format="{%(asctime)s} (%(name)s) [%(levelname)s]: %(message)s",
datefmt="%x, %X",
level=logging.DEBUG,
)
for logger in IGNORED_LOGGERS:
logging.getLogger(logger).setLevel(logging.WARNING)
logger = logging.getLogger("Automata")
AUTOMATA_TOKEN = os.getenv("AUTOMATA_TOKEN", None)
if not AUTOMATA_TOKEN:
logger.error(
"AUTOMATA_TOKEN environment variable not set, have you created a .env file and populated it yet?"
)
exit(1)
intents = nextcord.Intents.default()
intents.members = os.getenv("AUTOMATA_MEMBER_INTENTS_ENABLED", "True") == "True"
bot = commands.Bot(
command_prefix="!",
help_command=None,
intents=intents,
description="A custom, multi-purpose moderation bot for the MUN Computer Science Society Discord server.",
)
@bot.event
async def on_message(message):
# Log messages
if isinstance(message.channel, nextcord.DMChannel):
name = message.author.name
else:
name = message.channel.name
logger.info(f"[{name}] {message.author.name}: {message.content}")
await bot.process_commands(message)
@bot.event
async def on_ready():
# When the bot is ready, start the prometheus client
await start_http_server(port=9000)
if os.getenv("SENTRY_DSN", None):
@bot.event
async def on_error(event, *args, **kwargs):
raise
@bot.event
async def on_command_error(ctx, exception):
raise exception
@contextlib.contextmanager
def stdioreader():
old = (sys.stdout, sys.stderr)
stdout = StringIO()
stderr = StringIO()
sys.stdout = stdout
sys.stderr = stderr
yield stdout, stderr
sys.stdout = old[0]
sys.stderr = old[1]
@bot.command(name="eval")
@commands.is_owner()
async def eval_code(ctx: commands.Context, code: str):
"""Evaluates code for debugging purposes."""
try:
result = f"```\n{eval(code)}\n```"
colour = nextcord.Colour.green()
except:
result = f"```py\n{traceback.format_exc(1)}```"
colour = nextcord.Colour.red()
result.replace("\\", "\\\\")
embed = nextcord.Embed()
embed.add_field(name=code, value=result)
embed.colour = colour
await ctx.send(embed=embed)
@bot.command(name="exec")
@commands.is_owner()
async def exec_code(ctx: commands.Context, code: str):
"""Executes code for debugging purposes."""
with stdioreader() as (out, err):
try:
exec(code)
result = f"```\n{out.getvalue()}\n```"
colour = nextcord.Colour.green()
except:
result = f"```py\n{traceback.format_exc(1)}```"
colour = nextcord.Colour.red()
result.replace("\\", "\\\\")
embed = nextcord.Embed()
embed.add_field(name=code, value=result)
embed.colour = colour
await ctx.send(embed=embed)
@bot.command()
async def plugins(ctx: commands.Context):
"""Lists all enabled plugins."""
embed = nextcord.Embed()
embed.colour = nextcord.Colour.blurple()
for plugin in loader.get_all_plugins():
if plugin["plugin"]:
embed.add_field(
name=plugin["manifest"]["name"],
value="{}\nVersion: {}\nAuthor: {}".format(
plugin["plugin"].__doc__.rstrip(),
plugin["manifest"]["version"],
plugin["manifest"]["author"],
),
)
await ctx.send(embed=embed)
class CustomHelp(commands.DefaultHelpCommand): # ( ͡° ͜ʖ ͡°)
"""Custom help command"""
async def send_bot_help(self, mapping):
"""Shows a list of commands"""
embed = nextcord.Embed(title="Commands Help")
embed.colour = nextcord.Colour.blurple()
for cog, commands in mapping.items():
command_signatures = [self.get_command_signature(c) for c in commands]
if command_signatures:
cog_name = getattr(cog, "qualified_name", "No Category")
embed.add_field(
name=cog_name, value="\n".join(command_signatures), inline=False
)
channel = self.get_destination()
await channel.send(embed=embed)
async def send_command_help(self, command):
"""Shows how to use each command"""
embed_command = nextcord.Embed(
title=self.get_command_signature(command), description=command.help
)
embed_command.colour = nextcord.Colour.green()
channel = self.get_destination()
await channel.send(embed=embed_command)
async def send_group_help(self, group):
"""Shows how to use each group of commands"""
embed_group = nextcord.Embed(
title=self.get_command_signature(group), description=group.short_doc
)
for c in group.walk_commands():
embed_group.add_field(name=c, value=c.short_doc, inline=False)
embed_group.colour = nextcord.Colour.yellow()
channel = self.get_destination()
await channel.send(embed=embed_group)
async def send_cog_help(self, cog):
"""Shows how to use each category"""
embed_cog = nextcord.Embed(
title=cog.qualified_name, description=cog.description
)
comms = cog.get_commands()
for c in comms:
embed_cog.add_field(name=c, value=c.short_doc, inline=False)
embed_cog.colour = nextcord.Colour.green()
channel = self.get_destination()
await channel.send(embed=embed_cog)
async def send_error_message(self, error):
"shows if command does not exist"
embed_error = nextcord.Embed(title="Error", description=error)
embed_error.colour = nextcord.Colour.red()
channel = self.get_destination()
await channel.send(embed=embed_error)
bot.help_command = CustomHelp()
plugins_dir = Path("./plugins")
mounted_plugins_dir = Path("./mounted_plugins")
mounted_plugins_dir.mkdir(exist_ok=True)
loader = PluginLoader(
plugin_paths=(str(plugins_dir), str(mounted_plugins_dir)),
plugin_class=AutomataPlugin,
)
loader.load_manifests()
num_of_disabled = 0
for plugin in loader.get_all_plugins():
manifest = plugin["manifest"]
if len(ENABLED_PLUGINS) > 0:
if manifest["main_class"] in ENABLED_PLUGINS:
loader.load_plugin(manifest, bot)
else:
num_of_disabled += 1
else:
if manifest["main_class"] not in DISABLED_PLUGINS:
loader.load_plugin(manifest, bot)
else:
logger.info(f"{manifest['name']} disabled.")
num_of_disabled += 1
logger.info(f"{num_of_disabled} plugins disabled.")
for plugin in loader.get_all_plugins():
if plugin["plugin"]:
plugin["plugin"].enable()
bot.run(AUTOMATA_TOKEN)