-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
66 lines (53 loc) · 1.89 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
import datetime
import discord
import asyncio
import logging
from discord.ext import commands
import os
import sys
from dotenv import load_dotenv
# Set up logging to file
logging.basicConfig(
filename="bot_errors.log", # Log to a file named "bot_errors.log"
level=logging.ERROR, # Log error level and above (ERROR, CRITICAL)
format="%(asctime)s - %(levelname)s - %(message)s", # Log message format
)
# # StreamHandler for console output
# console_handler = logging.StreamHandler()
# console_handler.setLevel(logging.ERROR)
# console_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
# logging.getLogger().addHandler(console_handler)
# Define a custom exception hook to log uncaught exceptions
def log_uncaught_exception(exc_type, exc_value, exc_tb):
if exc_type == KeyboardInterrupt:
# Ignore keyboard interrupts (e.g. when the bot is shut down)
pass
else:
logging.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
# Set the custom exception hook
sys.excepthook = log_uncaught_exception
# Load environment variables
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
# Bot setup
intents = discord.Intents.default()
bot = commands.Bot(command_prefix=["!", "?", "&"], intents=intents)
# Event: Bot is ready
@bot.event
async def on_ready():
await bot.tree.sync() # Sync slash commands globally
# Function to dynamically load cogs
async def load_cogs():
for filename in os.listdir("./cogs"):
if filename.endswith(".py") and filename != "__init__.py":
try:
await bot.load_extension(f"cogs.{filename[:-3]}")
print(f"Loaded cog: {filename}")
except Exception as e:
print(f"Failed to load cog {filename}: {e}")
# Run the bot
async def main():
async with bot:
await load_cogs()
await bot.start(TOKEN)
asyncio.run(main())