-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
178 lines (147 loc) · 5.71 KB
/
main.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
import json
import logging
import os
import platform
import sys
import traceback
import discord
from discord.ext import commands
from discord.ext.commands import Context
from dotenv import load_dotenv
if not os.path.isfile(f"{os.path.realpath(os.path.dirname(__file__))}/config.json"):
sys.exit("'config.json' not found! Please add it and try again.")
else:
with open(f"{os.path.realpath(os.path.dirname(__file__))}/config.json") as file:
config = json.load(file)
intents = discord.Intents.all()
class LoggingFormatter(logging.Formatter):
# Colors
black = "\x1b[30m"
red = "\x1b[31m"
green = "\x1b[32m"
yellow = "\x1b[33m"
blue = "\x1b[34m"
gray = "\x1b[38m"
# Styles
reset = "\x1b[0m"
bold = "\x1b[1m"
COLORS = {
logging.DEBUG: gray + bold,
logging.INFO: blue + bold,
logging.WARNING: yellow + bold,
logging.ERROR: red,
logging.CRITICAL: red + bold,
}
def format(self, record):
log_color = self.COLORS[record.levelno]
format = "(black){asctime}(reset) (levelcolor){levelname:<8}(reset) (green){name}(reset) {message}"
format = 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.getLogger("gemini_bot")
logger.setLevel(logging.INFO)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(LoggingFormatter())
# File handler
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)
# Add the handlers
logger.addHandler(console_handler)
logger.addHandler(file_handler)
class GeminiBot(commands.Bot):
def __init__(
self, cogs: list[str] = ["cogs.chat", "cogs.help", "cogs.events"]
) -> None:
super().__init__(
command_prefix=commands.when_mentioned_or(config["prefix"]),
intents=intents,
help_command=None,
)
self.logger = logger
self.config = config
self.cogs_to_load = cogs
self.owner_ids = config.get("developers", [])
self.error_channel = None
self.log_channel = None
async def setup_hook(self) -> None:
"""
Executed after the bot is once ready.
"""
self.logger.info(f"Logged in as {self.user.name}")
self.logger.info(f"discord.py API version: {discord.__version__}")
self.logger.info(f"Python version: {platform.python_version()}")
self.logger.info(
f"Running on: {platform.system()} {platform.release()} ({os.name})"
)
self.logger.info("-------------------")
await self.load_cogs()
async def on_command_completion(self, context: Context) -> None:
full_command_name = context.command.qualified_name
split = full_command_name.split(" ")
executed_command = str(split[0])
if context.guild is not None:
self.logger.info(
f"Executed {executed_command} command in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})"
)
else:
self.logger.info(
f"Executed {executed_command} command by {context.author} (ID: {context.author.id}) in DMs"
)
async def on_command_error(self, context: Context, exception) -> None:
if isinstance(exception, commands.CommandNotFound) or isinstance(
exception, commands.CheckFailure
):
pass
else:
await context.reply(f"An error occurred: {exception}")
if self.error_channel:
await self.error_channel.send(
f"An error occurred in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})\n```{exception}```"
)
async def load_cogs(self):
for cog in self.cogs_to_load:
try:
await self.load_extension(cog)
except Exception as e:
self.logger.error(f"Failed to load cog {cog}: {e}")
traceback.print_exc()
async def on_ready(self) -> None:
await self.change_presence(activity=discord.Game(name="@GeminiBot help"))
try:
self.log_channel = await self.fetch_channel(
self.config.get("log_channel", 0)
)
except:
self.logger.error(f"Failed to fetch log channel.")
try:
self.error_channel = await self.fetch_channel(
self.config.get("error_channel", 0)
)
except:
self.logger.error(f"Failed to fetch error channel.")
print(f"{self.user.name} is ready.")
load_dotenv()
bot = GeminiBot()
def assert_config():
assert "prefix" in config, "No prefix specified in config.json"
assert "owner" in config, "No owner specified in config.json"
assert "blacklist" in config, "No blacklist specified in config.json"
assert "initial_prompt" in config, "Initial prompt missing in config.json"
def assert_env():
assert "BOT_TOKEN" in os.environ, "No BOT_TOKEN specified in environment variables"
assert (
"GEMINI_API_KEY" in os.environ
), "No GEMINI_API_KEY specified in environment variables"
def main():
assert_config()
assert_env()
bot.run(os.environ["BOT_TOKEN"])
if __name__ == "__main__":
main()