First layout
This commit is contained in:
117
bot.py
Normal file
117
bot.py
Normal file
@@ -0,0 +1,117 @@
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from database import Database
|
||||
import logging
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Bot setup
|
||||
intents = discord.Intents.default()
|
||||
intents.message_content = True
|
||||
intents.members = True
|
||||
|
||||
bot = commands.Bot(command_prefix=',', intents=intents)
|
||||
|
||||
# Database instance
|
||||
db = None
|
||||
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
global db
|
||||
logger.info(f'{bot.user} has connected to Discord!')
|
||||
if db is None:
|
||||
db = Database()
|
||||
await db.connect()
|
||||
await load_cogs()
|
||||
|
||||
async def load_cogs():
|
||||
"""Load all command cogs"""
|
||||
cogs_dir = 'cogs'
|
||||
for filename in os.listdir(cogs_dir):
|
||||
if filename.endswith('.py') and not filename.startswith('_'):
|
||||
try:
|
||||
await bot.load_extension(f'cogs.{filename[:-3]}')
|
||||
logger.info(f'Loaded cog: {filename}')
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to load cog {filename}: {e}')
|
||||
|
||||
@bot.event
|
||||
async def on_message(message):
|
||||
"""Handle character trigger messages"""
|
||||
# Ignore bot messages
|
||||
if message.author.bot:
|
||||
return
|
||||
|
||||
# Check if message starts with prefix
|
||||
if message.content.startswith(','):
|
||||
# Extract trigger and content
|
||||
parts = message.content.split(' ', 1)
|
||||
trigger = parts[0][1:] # Remove the comma
|
||||
msg_content = parts[1] if len(parts) > 1 else ''
|
||||
|
||||
# Check if this is a registered command
|
||||
if trigger in ['oc', 'help', 'ping', 'stats', 'invite', 'support', 'about', 'reload', 'debug', 'admin', 'config']:
|
||||
await bot.process_commands(message)
|
||||
return
|
||||
|
||||
# Try to find a character with this trigger
|
||||
if db:
|
||||
character = await db.get_character_by_trigger(message.author.id, trigger)
|
||||
if character:
|
||||
# Delete original message
|
||||
try:
|
||||
await message.delete()
|
||||
except:
|
||||
pass
|
||||
|
||||
# Create webhook and send message
|
||||
await send_character_message(message.channel, character, msg_content)
|
||||
return
|
||||
|
||||
# Process other commands
|
||||
await bot.process_commands(message)
|
||||
|
||||
async def send_character_message(channel, character, content):
|
||||
"""Send a message through webhook as a character"""
|
||||
try:
|
||||
# Get existing webhooks
|
||||
webhooks = await channel.webhooks()
|
||||
webhook = None
|
||||
|
||||
# Look for existing bot webhook
|
||||
for wh in webhooks:
|
||||
if wh.user.id == bot.user.id:
|
||||
webhook = wh
|
||||
break
|
||||
|
||||
# Create webhook if doesn't exist
|
||||
if not webhook:
|
||||
webhook = await channel.create_webhook(name='OC-Bot')
|
||||
|
||||
# Send message through webhook
|
||||
await webhook.send(
|
||||
content=content,
|
||||
username=character['name'],
|
||||
avatar_url=character['avatar_url']
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to send character message: {e}')
|
||||
|
||||
@bot.event
|
||||
async def on_command_error(ctx, error):
|
||||
"""Error handling for commands"""
|
||||
logger.error(f'Command error: {error}')
|
||||
|
||||
# Run bot
|
||||
if __name__ == '__main__':
|
||||
TOKEN = os.getenv('DISCORD_TOKEN')
|
||||
if not TOKEN:
|
||||
raise ValueError('DISCORD_TOKEN not found in .env file')
|
||||
bot.run(TOKEN)
|
||||
Reference in New Issue
Block a user