Files
UtilityBot
Code
12 1,672
UtilityBot/bot.py
import os
import sys
import json
import logging
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
f = open("config.json")
config = json.load(f)
f.close()
logging.basicConfig(
level=getattr(logging, config.get("log_level", "INFO")),
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
log = logging.getLogger("bot")
intents = discord.Intents.all()
intents.message_content = True
bot = commands.Bot(
command_prefix=commands.when_mentioned_or(config["prefix"]),
intents=intents,
help_command=commands.DefaultHelpCommand(no_category="Commands"),
)
activity_type_map = {
"playing": discord.ActivityType.playing,
"watching": discord.ActivityType.watching,
"listening": discord.ActivityType.listening,
"streaming": discord.ActivityType.streaming,
}
@bot.event
async def on_ready():
activity_type = activity_type_map.get(config.get("activity_type", "playing"))
activity = discord.Activity(type=activity_type, name=config.get("activity", "with commands"))
await bot.change_presence(activity=activity)
log.info(f"Logged in as {bot.user} (ID: {bot.user.id})")
log.info(f"Loaded cogs: {', '.join(bot.cogs.keys()) or 'none'}")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"❌ You need the **{', '.join(error.missing_permissions)}** permission to use this command.")
return
if isinstance(error, commands.BotMissingPermissions):
await ctx.send(f"❌ I need the **{', '.join(error.missing_permissions)}** permission to do that.")
return
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"❌ Missing argument: `{error.param.name}`\nUsage: `{ctx.prefix}{ctx.command.qualified_name} {ctx.command.signature}`")
return
if isinstance(error, commands.BadArgument):
await ctx.send(f"❌ Invalid argument: {error}")
return
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"⏳ Command on cooldown. Try again in {error.retry_after:.1f}s.")
return
log.error(f"Unhandled error in {ctx.command}: {error}", exc_info=error)
async def load_extensions():
for file in os.listdir("cogs"):
if file.endswith(".py") and not file.startswith("_"):
try:
await bot.load_extension(f"cogs.{file[:-3]}")
log.info(f"Loaded cog: {file[:-3]}")
except Exception as e:
log.error(f"Failed to load cog {file}: {e}")
@bot.command(name="reload", hidden=True)
@commands.is_owner()
async def reload_cogs(ctx):
for file in os.listdir("cogs"):
if file.endswith(".py") and not file.startswith("_"):
try:
await bot.reload_extension(f"cogs.{file[:-3]}")
except Exception:
try:
await bot.load_extension(f"cogs.{file[:-3]}")
except Exception as e:
await ctx.send(f"❌ Failed to reload `{file}`: {e}")
return
await ctx.send("✅ All cogs reloaded.")
async def main():
await load_extensions()
token = os.getenv("DISCORD_TOKEN")
if not token:
log.error("DISCORD_TOKEN not found in .env")
sys.exit(1)
await bot.start(token)
if __name__ == "__main__":
import asyncio
asyncio.run(main())