-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
134 lines (105 loc) · 4.44 KB
/
Copy pathbot.py
File metadata and controls
134 lines (105 loc) · 4.44 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
# Main starting file for Karn
# This file creates the Bot object, loads the cogs, and starts the event loop
import discord
from discord.ext import commands, tasks
from dotenv import load_dotenv
from logging import getLogger, WARNING
from mysql.connector.errors import InterfaceError
from os import getenv, listdir
from random import choice
# env must be loaded before importing ./cogs.py
load_dotenv()
TOKEN = getenv("DISCORD_TOKEN") # API token for the bot
if TOKEN is None:
exit("Environment file missing/corrupted. Halting now!")
# Local dependencies
from src.cogs import add_cogs
from src.activities import activities
from src.Cogs.Terminal import send_line
from src.global_vars import FILE_ROOT_DIR, SEND_LINE_CHAR
from src.help_command import CustomHelpCommand
from src.pipeline import run_pipeline
from src.response_strings import NO_DM_SUPPORT
from src.sql import connect_to_sql_database
from src.utils import make_guild_dir
activity = discord.Activity(type=discord.ActivityType.streaming,
name="",
state="Listening for $help"
)
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='$',
case_insensitive=True,
help_command=CustomHelpCommand(),
intents=intents,
activity=activity)
# Add brief help text for the help command
next(filter(lambda x: x.name == "help", bot.commands)).brief = "Shows this message"
try:
sql_connection = connect_to_sql_database()
except InterfaceError:
exit("Database connection failed.\nPlease ensure your .env file is correct.")
# Runs when bot has successfully logged in
# Note: This can and will be called multiple times during the bot's up-times
@bot.event
async def on_ready():
# Only add cogs if no cogs are currently present on the bot
# This prevents the recurring CommandRegistrationError exception
if not bot.cogs:
await add_cogs(bot, sql_connection)
change_activity.start()
print(f"\n{bot.user} is connected to the following guild(s):\n")
for guild in bot.guilds:
print(f"{guild.name} (ID: {guild.id})\nGuild Members: {len(guild.members)}\n")
await bot.tree.sync()
@tasks.loop(hours=1)
async def change_activity():
activity.name = choice(activities)
await bot.change_presence(activity=activity)
@bot.event
async def on_guild_join(guild):
make_guild_dir(guild.id)
@bot.event
async def on_message(msg):
if msg.author == bot.user or not msg.content:
return
if msg.author.bot:
await bot.get_cog("AI").send_reply(msg)
return
if msg.content[0] == bot.command_prefix:
if "--help" in msg.content:
msg.content = f"$help {msg.content.split()[0][1:]}"
if '|' in msg.content:
ctx = await bot.get_context(msg)
result = await run_pipeline(ctx, msg.content)
return await result.send(ctx)
return await bot.process_commands(msg)
if not await send_line(msg, bot):
if not await bot.get_cog("Games").wordle_listener(msg):
await bot.get_cog("AI").send_reply(msg)
bot.get_cog("Rating").rate_listener(msg)
@bot.event
async def on_command_error(ctx, error):
if hasattr(error, "handled") and error.handled:
return
if isinstance(error, commands.NoPrivateMessage):
return await ctx.send(NO_DM_SUPPORT)
if isinstance(error, commands.CommandNotFound):
if ctx.guild and f"{(cmd := ctx.message.content.lstrip('$').lower())}.txt" in listdir(f"{FILE_ROOT_DIR}/{ctx.guild.id}"):
return await ctx.send(f"Did you mean to use a line-response command? "
f"If you send `{SEND_LINE_CHAR}{cmd}`, I will respond with a random line from *{cmd}*.")
try:
author = f"{ctx.author} (a.k.a. {ctx.author.nick})"
except AttributeError:
author = f"{ctx.author}"
print(f"\nCommand error triggered\n"
f"\t Author: {author}\n"
f"\t Guild: {ctx.guild}\n"
f"\tChannel: {ctx.message.channel}\n"
f"\tMessage: {ctx.message.content}\n"
f"Error:\n{error}")
# Begin the bot's event loop
if __name__ == "__main__":
getLogger("discord.gateway").setLevel(WARNING)
bot.run(TOKEN)