97 lines
2.8 KiB
Python
97 lines
2.8 KiB
Python
import os
|
|
import discord
|
|
from discord.ext import commands
|
|
from dotenv import load_dotenv
|
|
import aiosqlite
|
|
import asyncio
|
|
import logging
|
|
from datetime import datetime, timedelta
|
|
import openai
|
|
|
|
# Configure logging
|
|
logging.basicConfig(
|
|
level=logging.DEBUG,
|
|
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
|
|
handlers=[
|
|
logging.StreamHandler(),
|
|
logging.FileHandler('minimal_bot.log', encoding='utf-8')
|
|
]
|
|
)
|
|
logger = logging.getLogger('minimal_bot')
|
|
|
|
# Load environment variables
|
|
load_dotenv()
|
|
|
|
# Initialize Discord bot
|
|
intents = discord.Intents.default()
|
|
intents.message_content = True # Enable message content intent
|
|
bot = commands.Bot(command_prefix='!', intents=intents)
|
|
|
|
DB_PATH = os.getenv("DB_PATH", "conversation_history.db")
|
|
MESSAGE_CLEANUP_DAYS = int(os.getenv("MESSAGE_CLEANUP_DAYS", "30"))
|
|
|
|
# API Configuration
|
|
API_KEY = os.getenv("GLHF_API_KEY")
|
|
BASE_URL = os.getenv("GLHF_BASE_URL", "https://glhf.chat/api/openai/v1")
|
|
|
|
# Initialize OpenAI API client
|
|
api_client = openai.OpenAI(api_key=API_KEY, base_url=BASE_URL)
|
|
|
|
async def init_db():
|
|
async with aiosqlite.connect(DB_PATH) as db:
|
|
await db.execute('''
|
|
CREATE TABLE IF NOT EXISTS messages (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
user_id INTEGER NOT NULL,
|
|
role TEXT NOT NULL,
|
|
content TEXT NOT NULL,
|
|
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
channel_id INTEGER NOT NULL,
|
|
token_count INTEGER NOT NULL,
|
|
message_uuid TEXT NOT NULL
|
|
)
|
|
''')
|
|
await db.commit()
|
|
logger.debug("Database initialized")
|
|
|
|
async def cleanup_old_messages():
|
|
cleanup_date = datetime.now() - timedelta(days=MESSAGE_CLEANUP_DAYS)
|
|
async with aiosqlite.connect(DB_PATH) as db:
|
|
await db.execute(
|
|
'DELETE FROM messages WHERE timestamp < ?',
|
|
(cleanup_date.strftime('%Y-%m-%d %H:%M:%S'),)
|
|
)
|
|
await db.commit()
|
|
logger.debug("Old messages cleaned up")
|
|
|
|
async def periodic_cleanup():
|
|
while True:
|
|
await cleanup_old_messages()
|
|
await asyncio.sleep(24 * 60 * 60) # Run cleanup every 24 hours
|
|
|
|
@bot.event
|
|
async def on_ready():
|
|
print(f'{bot.user} has connected to Discord!')
|
|
await init_db()
|
|
bot.loop.create_task(periodic_cleanup())
|
|
|
|
@bot.command(name='ping')
|
|
async def ping(ctx):
|
|
"""Respond with 'pong' to test command handling."""
|
|
await ctx.send('pong')
|
|
|
|
def main():
|
|
# Verify environment variables
|
|
discord_token = os.getenv("DISCORD_TOKEN")
|
|
if not discord_token:
|
|
print("DISCORD_TOKEN environment variable not set")
|
|
return
|
|
|
|
try:
|
|
bot.run(discord_token)
|
|
except Exception as e:
|
|
print(f"Bot startup failed: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|