-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
242 lines (201 loc) · 8.07 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
import asyncio
import os
import platform
import random
import sys
import re
import logging
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from noncommands import haikudetector
from noncommands import musicdetector
from noncommands import paywallDetector
from noncommands import imchecker
from noncommands import reminderLoop
from noncommands import birthdayLoop
from noncommands import scooby
from noncommands import chat
import nextcord
import yaml
from nextcord import Interaction
from nextcord.ext import commands, tasks
from nextcord.ext.commands import Bot, Context
with open("config.yaml") as file:
config = yaml.load(file, Loader=yaml.FullLoader)
class DadBot(commands.Bot):
def __init__(self, loggingFormatter, botConfig) -> None:
super().__init__(
command_prefix=commands.when_mentioned_or(botConfig["bot_prefix"]),
intents=intents,
help_command=None,
)
self.logger: logging.Logger = loggingFormatter
self.config: dict = botConfig
self.super = super()
intents = nextcord.Intents.default().all()
class LoggingFormatter(logging.Formatter):
black: str = "\x1b[30m"
red: str = "\x1b[31m"
green: str = "\x1b[32m"
yellow: str = "\x1b[33m"
blue: str = "\x1b[34m"
gray: str = "\x1b[38m"
reset: str = "\x1b[0m"
bold: str = "\x1b[1m"
COLORS: dict[int, str] = {
logging.DEBUG: gray + bold,
logging.INFO: blue + bold,
logging.WARNING: yellow + bold,
logging.ERROR: red,
logging.CRITICAL: red + bold,
}
def format(self, record) -> str:
log_color: str = self.COLORS[record.levelno]
format = "(black){asctime}(reset) (levelcolor){levelname:<8}(reset) (green){name}(reset) {message}"
format: str = format.replace("(black)", self.black + self.bold)
format = format.replace("(reset)", self.reset)
format = format.replace("(levelcolor)", log_color)
format = format.replace("(green)", self.green + self.bold)
formatter = logging.Formatter(format, "%Y-%m-%d %H:%M:%S", style="{")
return formatter.format(record)
logger: logging.Logger = logging.getLogger(name="DadBot")
logger.setLevel(level=logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setFormatter(LoggingFormatter())
file_handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
file_handler_formatter = logging.Formatter(
"[{asctime}] [{levelname:<8}] {name}: {message}", "%Y-%m-%d %H:%M:%S", style="{"
)
file_handler.setFormatter(file_handler_formatter)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
bot = DadBot(loggingFormatter=logger, botConfig=config)
imChecker = imchecker.ImChecker()
reminderChecker = reminderLoop.ReminderLoop()
birthdayChecker = birthdayLoop.BirthdayLoop(bot)
haikuDetector = haikudetector.HaikuDetector()
musicDetector = musicdetector.MusicDetector()
paywallDetector = paywallDetector.PaywallDetector()
scooby = scooby.Scooby(bot)
chat = chat.Chat(bot)
@bot.event
async def on_ready() -> None:
if bot.user is None:
sys.exit("Bot has no user!")
bot.logger.info(f"Logged in as {bot.user.name}")
bot.logger.info(f"nextcord.py API version: {nextcord.__version__}")
bot.logger.info(f"Python version: {platform.python_version()}")
bot.logger.info(f"Running on: {platform.system()} {platform.release()} ({os.name})")
bot.logger.info(f"Servers: {len(bot.guilds)}")
for i in bot.guilds:
bot.logger.info(f" - {i.name}")
bot.logger.info(f"Users: {len(bot.users)}")
bot.logger.info("-------------------")
status_task.start()
# Setup the game status task of the bot
@tasks.loop(minutes=1.0)
async def status_task():
statuses = ["with your mom"]
await bot.change_presence(activity=nextcord.Game(random.choice(statuses)))
@bot.event
async def on_message(message: nextcord.Message) -> None:
if message.author == bot.user or message.author.bot:
return
if not re.search("(\|\|[\S\s]*\|\|)", message.content):
# So that dad doesn't respond in a thread with im or haiku
if not isinstance(message.channel, nextcord.Thread):
await imChecker.checkIm(message)
await haikuDetector.checkForHaiku(message)
await musicDetector.detectMusic(message)
await paywallDetector.detectPaywall(message)
await chat.respond(message)
await bot.process_commands(message)
@bot.event
async def on_command_completion(context: Context) -> None:
if context.command is None:
bot.logger.warning(f"Command is None: {context}")
return
full_command_name: str = context.command.qualified_name
split: list[str] = full_command_name.split(" ")
executed_command = str(split[0])
if context.guild is not None:
bot.logger.info(
f"Executed {executed_command} command in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})"
)
else:
bot.logger.info(
f"Executed {executed_command} command by {context.author} (ID: {context.author.id}) in DMs"
)
@bot.event
async def on_command_error(context: Context, error) -> None:
if isinstance(error, commands.CommandOnCooldown):
minutes, seconds = divmod(error.retry_after, 60)
hours, minutes = divmod(minutes, 60)
hours = hours % 24
embed = nextcord.Embed(
description=f"**Please slow down** - You can use this command again in {f'{round(hours)} hours' if round(hours) > 0 else ''} {f'{round(minutes)} minutes' if round(minutes) > 0 else ''} {f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.",
color=0xE02B2B,
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingPermissions):
embed = nextcord.Embed(
description="You are missing the permission(s) `"
+ ", ".join(error.missing_permissions)
+ "` to execute this command!",
color=0xE02B2B,
)
await context.send(embed=embed)
elif isinstance(error, commands.BotMissingPermissions):
embed = nextcord.Embed(
description="I am missing the permission(s) `"
+ ", ".join(error.missing_permissions)
+ "` to fully perform this command!",
color=0xE02B2B,
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingRequiredArgument):
embed = nextcord.Embed(
title="Error!",
# We need to capitalize because the command arguments have no capital letter in the code.
description=str(error).capitalize(),
color=0xE02B2B,
)
await context.send(embed=embed)
else:
raise error
@tasks.loop(seconds=5)
async def checkTimes():
await reminderChecker.checkReminders(bot)
await reminderChecker.updateOldReminders(bot)
if __name__ == "__main__":
for file in os.listdir(f"{os.path.realpath(os.path.dirname(__file__))}/cogs"):
if file.endswith(".py") and file != "template.py":
extension = file[:-3]
try:
bot.load_extension(f"cogs.{extension}")
bot.logger.info(f"Loaded extension '{extension}'")
except Exception as e:
exception = f"{type(e).__name__}: {e}"
bot.logger.error(f"Failed to load extension {extension}\n{exception}")
checkTimes.start()
scheduler = AsyncIOScheduler()
scheduler.add_job(
scooby.apod, CronTrigger(hour="9", minute="0", second="0", timezone="EST")
)
# scheduler.add_job(
# scooby.log_steps, CronTrigger(hour="7", minute="0", second="0", timezone="EST")
# )
scheduler.add_job(
birthdayChecker.checkBirthdays,
CronTrigger(hour="8", minute="0", second="0", timezone="EST"),
)
scheduler.add_job(
scooby.praiseFireGator,
CronTrigger(day_of_week="THU", hour="0", minute="0", second="0", timezone="EST"),
)
# scheduler.add_job(
# scooby.advent_of_code,
# CronTrigger(hour="9", minute="0", second="0", timezone="EST"),
# )
scheduler.start()
bot.run(config["token"])