-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
244 lines (194 loc) Β· 8.53 KB
/
main.py
File metadata and controls
244 lines (194 loc) Β· 8.53 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/env python3
"""
Main entry point for the Discord Prediction Market Bot.
This script initializes the complete architecture including:
- Dependency injection container
- Logging system with correlation IDs
- Error handling and recovery
- Configuration validation
- Security middleware
- Rate limiting
- Database connections
"""
import asyncio
import logging
import os
import sys
from pathlib import Path
import discord
from discord.ext import commands
# Add project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from config import validate_configuration, print_configuration_summary, ConfigurationError
from core.container import DIContainer, get_container, set_container
from core.logging_manager import get_logging_manager, get_logger, set_correlation_id
from core.error_handler import ErrorHandler, get_error_handler, set_error_handler
from core.rate_limiter import RateLimiter
from core.security import SecurityManager
from database.supabase_client import SupabaseClient
from helpers.SimplePointsManager import PointsManagerSingleton
class PredictionMarketBot(commands.Bot):
"""Enhanced Discord bot with full architecture integration."""
def __init__(self, settings, container: DIContainer):
# Configure intents
intents = discord.Intents.default()
intents.message_content = True # Required for message commands
super().__init__(
command_prefix=settings.discord.command_prefix,
intents=intents,
help_command=None # We'll create a custom help command
)
self.settings = settings
self.container = container
self.logger = get_logger("PredictionMarketBot")
self._ready = False
# Set up error handling
self.error_handler = get_error_handler()
self.error_handler.bot = self
async def setup_hook(self) -> None:
"""Initialize bot services and load cogs."""
self.logger.info("π Starting bot setup...")
# Set correlation ID for startup
startup_id = set_correlation_id("STARTUP")
self.logger.info(f"Bot startup correlation ID: {startup_id}")
try:
# Initialize all singleton services
await self.container.initialize_all_singletons()
self.logger.info("β
All services initialized")
# Load cogs
await self._load_cogs()
self.logger.info("β
All cogs loaded")
# Sync commands if enabled
if self.settings.discord.sync_commands:
await self.tree.sync()
self.logger.info("β
Slash commands synced")
self.logger.info("π Bot setup completed successfully!")
except Exception as e:
self.logger.critical(f"β Failed to setup bot: {e}", exc_info=True)
raise
async def on_ready(self) -> None:
"""Called when bot is ready."""
if not self._ready:
self.logger.info(f"π€ {self.user.name} is ready!")
self.logger.info(f"π Connected to {len(self.guilds)} guilds")
self.logger.info(f"π₯ Serving {sum(guild.member_count for guild in self.guilds)} users")
self._ready = True
else:
self.logger.info("π Bot reconnected")
async def on_command_error(self, ctx: commands.Context, error: Exception) -> None:
"""Handle command errors."""
await self.error_handler.handle_command_error(ctx, error)
async def on_application_command_error(
self,
interaction: discord.Interaction,
error: Exception
) -> None:
"""Handle slash command errors."""
await self.error_handler.handle_discord_error(interaction, error)
async def _load_cogs(self) -> None:
"""Load all cogs from the cogs directory."""
cogs_dir = project_root / "cogs"
# Load cogs from subdirectories
for cog_file in cogs_dir.rglob("*.py"):
if cog_file.name.startswith("_"):
continue
# Convert file path to module path
relative_path = cog_file.relative_to(project_root)
module_path = str(relative_path.with_suffix("")).replace(os.sep, ".")
try:
await self.load_extension(module_path)
self.logger.info(f"β
Loaded cog: {module_path}")
except Exception as e:
self.logger.error(f"β Failed to load cog {module_path}: {e}")
async def close(self) -> None:
"""Clean shutdown of bot and services."""
self.logger.info("π Shutting down bot...")
try:
# Dispose of container and all services
await self.container.dispose_async()
self.logger.info("β
Services disposed")
except Exception as e:
self.logger.error(f"β Error during shutdown: {e}")
await super().close()
self.logger.info("π Bot shutdown complete")
async def setup_services(settings, container: DIContainer) -> None:
"""Set up all application services in the DI container."""
logger = get_logger("ServiceSetup")
logger.info("π§ Setting up services...")
# Register logging manager
logging_manager = get_logging_manager(settings.logging)
container.register_instance(type(logging_manager), logging_manager)
# Register error handler
error_handler = ErrorHandler()
set_error_handler(error_handler)
container.register_instance(ErrorHandler, error_handler)
# Register rate limiter
rate_limiter = RateLimiter(
default_requests_per_minute=settings.rate_limit.user_requests_per_minute,
cleanup_interval=settings.rate_limit.cleanup_interval
)
container.register_instance(RateLimiter, rate_limiter)
# Register security manager
security_manager = SecurityManager()
container.register_instance(SecurityManager, security_manager)
# Register database client
db_client = SupabaseClient(
url=settings.database.supabase_url,
key=settings.database.supabase_publishable_key,
secret_key=settings.database.supabase_secret_key
)
container.register_instance(SupabaseClient, db_client)
# Register points manager (existing system)
points_manager = PointsManagerSingleton(
base_url=settings.drip_api.base_url,
api_key=settings.drip_api.api_key,
realm_id=settings.drip_api.realm_id
)
container.register_instance(PointsManagerSingleton, points_manager)
logger.info("β
All services registered")
async def main() -> None:
"""Main application entry point."""
print("π― Discord Prediction Market Bot")
print("=" * 50)
try:
# Load and validate configuration
print("π Loading configuration...")
settings = validate_configuration()
print_configuration_summary(settings)
# Initialize logging
print("π Initializing logging system...")
logging_manager = get_logging_manager(settings.logging)
logger = get_logger("Main")
# Set startup correlation ID
startup_id = set_correlation_id("MAIN_STARTUP")
logger.info(f"π Starting application with correlation ID: {startup_id}")
# Create and configure DI container
logger.info("ποΈ Setting up dependency injection container...")
container = DIContainer()
set_container(container)
# Register all services
await setup_services(settings, container)
# Create and run bot
logger.info("π€ Creating bot instance...")
bot = PredictionMarketBot(settings, container)
# Register bot in container for other services to use
container.register_instance(PredictionMarketBot, bot)
logger.info("π Starting bot...")
await bot.start(settings.discord.token)
except ConfigurationError as e:
print(f"β Configuration Error: {e}")
sys.exit(1)
except KeyboardInterrupt:
print("\nπ Received interrupt signal, shutting down...")
except Exception as e:
print(f"π₯ Fatal error: {e}")
if 'logger' in locals():
logger.critical(f"Fatal error during startup: {e}", exc_info=True)
sys.exit(1)
if __name__ == "__main__":
# Run the bot
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\nπ Goodbye!")