Skip to content

Commit af50efd

Browse files
committed
try again
1 parent 800ac92 commit af50efd

File tree

1 file changed

+24
-60
lines changed

1 file changed

+24
-60
lines changed

start_bot.py

Lines changed: 24 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
1-
import asyncio
21
from discord.ext import commands
32
import discord
43
from os import environ, makedirs, path
54
from dotenv import load_dotenv
65
import logging
76

87
# Ensure logs directory exists
9-
log_dir = '/app/logs'
10-
makedirs(log_dir, exist_ok=True)
11-
logging_file_path = path.join(log_dir, 'discord.log')
8+
makedirs('/app/logs', exist_ok=True)
9+
logging_file_path = '/app/logs/discord.log'
1210

1311
# Setup logging
1412
logging.basicConfig(level=logging.INFO)
1513
logger = logging.getLogger('discord')
16-
logger.setLevel(logging.DEBUG)
14+
logger.setLevel(logging.WARNING)
1715
handler = logging.FileHandler(filename=logging_file_path, encoding='utf-8', mode='w')
1816
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
1917
logger.addHandler(handler)
@@ -24,64 +22,30 @@
2422
intents = discord.Intents.default()
2523
intents.message_content = True
2624

27-
class DraftReviewBot(commands.Bot):
28-
def __init__(self):
29-
super().__init__(
30-
command_prefix='~',
31-
help_command=None,
32-
intents=intents
33-
)
34-
# Add reconnect settings
35-
self.reconnect_attempts = 0
36-
self.max_reconnect_attempts = 5
37-
self.reconnect_delay = 5 # Start with 5 second delay
38-
39-
async def setup_hook(self):
40-
"""Setup hook that runs when the bot starts."""
41-
print('waiting...') # Add the waiting message back
42-
await self.load_extension("draft_review")
43-
await self.load_extension("draft_vote")
44-
logger.info("Bot extensions loaded")
25+
# Create bot
26+
bot = commands.Bot(command_prefix='~', help_command=None, intents=intents)
4527

46-
async def on_ready(self):
47-
"""Event that runs when the bot is ready."""
48-
logger.info(f"Logged in as {self.user} (ID: {self.user.id})")
49-
self.reconnect_attempts = 0 # Reset reconnect attempts on successful connection
28+
@bot.event
29+
async def on_ready():
30+
"""Log when bot is ready"""
31+
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
32+
logger.info(f'Bot ready - logged in as {bot.user} (ID: {bot.user.id})')
5033

51-
async def on_error(self, event_method: str, *args, **kwargs):
52-
"""Handle any uncaught exceptions."""
53-
logger.error(f"Error in {event_method}", exc_info=True)
54-
55-
if "connect" in event_method and self.reconnect_attempts < self.max_reconnect_attempts:
56-
self.reconnect_attempts += 1
57-
delay = self.reconnect_delay * (2 ** (self.reconnect_attempts - 1)) # Exponential backoff
58-
logger.info(f"Attempting reconnect {self.reconnect_attempts} in {delay} seconds...")
59-
await asyncio.sleep(delay)
60-
try:
61-
await self.start(environ['BotToken'])
62-
except Exception as e:
63-
logger.error(f"Reconnect attempt failed: {str(e)}")
64-
else:
65-
logger.error("Max reconnect attempts reached or non-connection error occurred")
66-
67-
async def main():
68-
print('waiting...') # Add waiting message at startup
69-
bot = DraftReviewBot()
70-
try:
71-
async with bot:
72-
await bot.start(environ['BotToken'])
73-
except KeyboardInterrupt:
74-
logger.info("Bot shutdown by user")
75-
except Exception as e:
76-
logger.error(f"Bot crashed: {str(e)}", exc_info=True)
77-
finally:
78-
if not bot.is_closed():
79-
await bot.close()
34+
# Load extensions
35+
try:
36+
bot.load_extension("draft_review")
37+
bot.load_extension("draft_vote")
38+
print('Extensions loaded')
39+
except Exception as e:
40+
logger.error(f'Failed to load extensions: {str(e)}')
41+
raise
8042

81-
# Run the bot
43+
# Run bot
8244
try:
83-
asyncio.run(main())
45+
print('Starting bot...')
46+
bot.run(environ['BotToken'])
8447
except KeyboardInterrupt:
85-
logger.info("Bot shutdown by user")
48+
print('Bot shutdown by user')
8649
except Exception as e:
87-
logger.error(f"Bot crashed: {str(e)}", exc_info=True)
50+
logger.error(f'Bot failed to start: {str(e)}')
51+
raise

0 commit comments

Comments
 (0)