-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
542 lines (465 loc) · 26.8 KB
/
Copy pathmain.py
File metadata and controls
542 lines (465 loc) · 26.8 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import asyncio
import logging
import os
import traceback
import sys
from datetime import datetime
import aiohttp
import discord
import bugsnag
from discord import ChannelType
from discord.ext.commands import Bot
from cogs.admin import Admin
from cogs.lookup import Lookup
from cogs.order import order
from cogs.registration import Registration
from cogs.stock import stock
from cogs.subscribe import AlertSubscriptions
from cogs.price import Price
from cogs.watchlist import Watchlist
from cogs.listing import Listing
from cogs.marketplace import Marketplace
from cogs.blueprint import Blueprint
from util.config import Config
from util.result import Result
from util.discord_sqs_consumer import DiscordSQSManager
from util.logging_config import LoggingConfig
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
# Setup logging using centralized configuration
logger = LoggingConfig.setup_logging()
class SCMarket(Bot):
session = None
discord_sqs_manager = None
async def setup_hook(self):
await self.add_cog(Registration(self))
await self.add_cog(Admin(self))
await self.add_cog(Lookup(self))
await self.add_cog(order(self))
await self.add_cog(stock(self))
await self.add_cog(AlertSubscriptions(self))
await self.add_cog(Price(self))
await self.add_cog(Watchlist(self))
await self.add_cog(Listing(self))
await self.add_cog(Marketplace(self))
await self.add_cog(Blueprint(self))
await self.tree.sync()
# Initialize Discord SQS manager if enabled
if Config.ENABLE_SQS:
self.discord_sqs_manager = DiscordSQSManager(self)
if await self.discord_sqs_manager.initialize():
# Start consumer in background to avoid blocking main thread
asyncio.create_task(self.discord_sqs_manager.start_consumer())
logger.debug("Discord SQS consumer started successfully in background")
else:
logger.error("Failed to initialize Discord SQS manager")
# SQS-only mode - no web server needed
logger.debug("Running in SQS-only mode")
# Initialize aiohttp session
try:
self.session = aiohttp.ClientSession()
logger.info("aiohttp session initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize aiohttp session: {e}")
self.session = None
logger.error("Bot initialization failed due to session error")
return
# Ensure the session is properly initialized
if self.session and not self.session.closed:
logger.info("Ready!")
else:
logger.error("Failed to initialize aiohttp session")
logger.error("Bot initialization failed due to session error")
return
async def on_command_error(self, interaction, error):
"""Enhanced error handling for command errors"""
error_type = type(error).__name__
error_msg = str(error)
logger.error(f"Command error in {interaction.command.name if interaction.command else 'unknown'}: {error_type}: {error_msg}")
logger.error(f"User: {interaction.user.id} ({interaction.user.name})")
logger.error(f"Channel: {interaction.channel.id} ({interaction.channel.name if hasattr(interaction.channel, 'name') else 'DM'})")
logger.error(f"Guild: {interaction.guild.id if interaction.guild else 'DM'} ({interaction.guild.name if interaction.guild else 'DM'})")
logger.error(f"Full error: {traceback.format_exc()}")
if Config.BUGSNAG_API_KEY:
bugsnag.notify(
error,
context="on_command_error",
meta_data={
"command": {
"name": interaction.command.name if interaction.command else None,
"user_id": str(interaction.user.id),
}
},
)
# Send user-friendly error message
try:
if interaction.response.is_done():
await interaction.followup.send("An error occurred while processing your command. Please try again or contact support if the issue persists.", ephemeral=True)
else:
await interaction.response.send_message("An error occurred while processing your command. Please try again or contact support if the issue persists.", ephemeral=True)
except Exception as e:
logger.error(f"Failed to send error message to user: {e}")
async def close(self):
"""Clean up resources when the bot shuts down"""
logger.info("Bot shutdown initiated, cleaning up resources...")
try:
if hasattr(self, 'session') and self.session is not None and not self.session.closed:
await self.session.close()
logger.info("aiohttp session closed successfully")
except Exception as e:
logger.error(f"Error closing aiohttp session: {e}")
try:
if hasattr(self, 'discord_sqs_manager'):
await self.discord_sqs_manager.stop_consumer()
logger.debug("Discord SQS manager stopped successfully")
except Exception as e:
logger.error(f"Error stopping Discord SQS manager: {e}")
logger.info("Bot shutdown completed")
def on_error(self, event_method, *args, **kwargs):
"""Enhanced error handling for Discord events"""
logger.error(f"Error in Discord event {event_method}: {traceback.format_exc()}")
logger.error(f"Event args: {args}")
logger.error(f"Event kwargs: {kwargs}")
if Config.BUGSNAG_API_KEY:
err = sys.exc_info()[1]
if err:
bugsnag.notify(
err,
context=f"Discord event {event_method}",
meta_data={
"event": {"args": repr(args), "kwargs": repr(kwargs)},
},
)
async def on_message(self, message):
"""Enhanced message handling with comprehensive logging"""
if isinstance(message.channel, discord.Thread):
if not message.author.bot and message.content:
logger.debug(f"Processing message from {message.author.id} ({message.author.name}) in thread {message.channel.id}")
# Check if session is available
if not hasattr(self, 'session') or self.session is None or self.session.closed:
logger.error("Cannot send message: aiohttp session not available")
logger.error(f"Session state: hasattr={hasattr(self, 'session')}, session={self.session}, closed={getattr(self.session, 'closed', 'N/A') if self.session else 'N/A'}")
return
try:
payload = {
"author_id": str(message.author.id),
"name": message.author.name,
"thread_id": str(message.channel.id),
"content": message.content,
}
logger.debug(f"Sending message to backend: {payload}")
async with self.session.post(
f'{Config.discord_backend_base()}/threads/message',
json=payload
) as resp:
response_data = await resp.read()
logger.debug(f"Backend response status: {resp.status}, response: {response_data}")
if not resp.ok:
logger.warning(f"Backend returned non-OK status: {resp.status} - {response_data}")
except aiohttp.ClientError as e:
logger.error(f"Network error sending message to backend: {e}")
logger.error(f"Message details: author={message.author.id}, thread={message.channel.id}, content_length={len(message.content)}")
except asyncio.TimeoutError as e:
logger.error(f"Timeout error sending message to backend: {e}")
logger.error(f"Message details: author={message.author.id}, thread={message.channel.id}, content_length={len(message.content)}")
except Exception as e:
logger.error(f"Unexpected error sending message to backend: {e}")
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Message details: author={message.author.id}, thread={message.channel.id}, content_length={len(message.content)}")
logger.error(f"Full traceback: {traceback.format_exc()}")
async def order_placed(self, body):
"""Enhanced order placement with comprehensive logging"""
logger.info(f"Processing order_placed request: {body}")
try:
# Ensure session is available
if not hasattr(self, 'session') or self.session is None or self.session.closed:
logger.error("Discord session is not available or closed")
logger.error(f"Session state: hasattr={hasattr(self, 'session')}, session={self.session}, closed={getattr(self.session, 'closed', 'N/A') if self.session else 'N/A'}")
return dict(thread=None, failed=True, message="Discord session unavailable", invite_code=None)
# Convert string IDs to integers and handle data types
try:
server_id = int(body.get('server_id')) if body.get('server_id') else None
channel_id = int(body.get('channel_id')) if body.get('channel_id') else None
members = [int(member) for member in body.get('members', []) if member]
except (ValueError, TypeError) as e:
logger.error(f"Failed to convert IDs to integers: {e}")
logger.error(f"Raw values: server_id={body.get('server_id')}, channel_id={body.get('channel_id')}, members={body.get('members')}")
return dict(thread=None, failed=True, message=f"Invalid ID format: {e}", invite_code=None)
# Use order as offer (they have similar structure)
offer = body.get('order', {})
logger.info(f"Creating thread: server_id={server_id}, channel_id={channel_id}, members={members}")
logger.debug(f"Offer details: {offer}")
result = await self.create_thread(
server_id,
channel_id,
members,
offer,
)
thread = result.value
logger.info(f"Thread creation result: {result}")
# Invite creation is now handled by the backend
# We just return the thread creation result
if not thread:
logger.error(f"Thread creation failed: {result.error}")
logger.error(f"Result object: {result}")
else:
logger.info(f"Thread created successfully: {thread}")
return dict(thread=thread, failed=bool(result.error), message=result.error, invite_code=None)
except Exception as e:
logger.error(f"Unexpected error in order_placed: {e}")
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Request body: {body}")
logger.error(f"Full traceback: {traceback.format_exc()}")
return dict(thread=None, failed=True, message=f"An unexpected error occurred: {e}", invite_code=None)
async def verify_invite(self, customer_id, server_id, channel_id, invite_code):
"""Verify if an existing invite is valid (no creation - handled by backend)"""
logger.info(f"Verifying invite: customer_id={customer_id}, server_id={server_id}, channel_id={channel_id}, invite_code={invite_code}")
# Since invite creation is now handled by the backend, we just return the provided invite code
# The backend will have already created a valid invite
if invite_code:
logger.info(f"Using invite code provided by backend: {invite_code}")
return invite_code
else:
logger.debug("No invite code provided by backend")
return None
async def on_member_join(self, member):
"""Enhanced member join handling with comprehensive logging"""
logger.info(f"Member joined: {member.id} ({member.name}) in guild {member.guild.id} ({member.guild.name})")
try:
async with aiohttp.ClientSession() as session:
logger.debug(f"Fetching threads for user {member.id}")
async with session.get(
f'{Config.discord_backend_base()}/threads/user/{member.id}',
) as resp:
if not resp.ok:
logger.error(f"Failed to fetch threads for user {member.id}: {resp.status} - {resp.reason}")
return
try:
result = await resp.json()
logger.debug(f"Threads response for user {member.id}: {result}")
except Exception as e:
logger.error(f"Failed to decode response for user {member.id}: {e}")
logger.error(f"Response status: {resp.status}, response text: {await resp.text()}")
return
if 'thread_ids' not in result:
logger.warning(f"Unexpected response format for user {member.id}: {result}")
return
thread_ids = result['thread_ids']
logger.info(f"Found {len(thread_ids)} threads for user {member.id}")
guild: discord.Guild = member.guild
failed_threads = []
for thread_id in thread_ids:
try:
logger.debug(f"Adding user {member.id} to thread {thread_id}")
thread = guild.get_thread(int(thread_id))
if thread:
await thread.add_user(member)
logger.info(f"Successfully added user {member.id} to thread {thread_id}")
else:
logger.debug(f"Thread {thread_id} not found in guild {guild.name} - this may be a configuration issue")
failed_threads.append(thread_id)
except discord.Forbidden as e:
logger.debug(f"Bot lacks permission to add user {member.id} to thread {thread_id}: {e} - this is a configuration issue")
failed_threads.append(thread_id)
except discord.NotFound as e:
logger.debug(f"Thread {thread_id} not found: {e} - this may be a configuration issue")
failed_threads.append(thread_id)
except discord.HTTPException as e:
logger.error(f"HTTP error adding user {member.id} to thread {thread_id}: {e}")
failed_threads.append(thread_id)
except Exception as e:
logger.error(f"Unexpected error adding user {member.id} to thread {thread_id}: {e}")
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Full traceback: {traceback.format_exc()}")
failed_threads.append(thread_id)
if failed_threads:
logger.debug(f"Failed to add user {member.id} to {len(failed_threads)} threads: {failed_threads} - these may be configuration issues")
else:
logger.info(f"Successfully processed all threads for user {member.id}")
except aiohttp.ClientError as e:
logger.error(f"Network error in on_member_join for user {member.id}: {e}")
except asyncio.TimeoutError as e:
logger.error(f"Timeout error in on_member_join for user {member.id}: {e}")
except Exception as e:
logger.error(f"Unexpected error in on_member_join for user {member.id}: {e}")
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Full traceback: {traceback.format_exc()}")
async def create_thread(self, server_id: int, channel_id: int, members: list[int], offer: dict):
"""Enhanced thread creation with comprehensive logging"""
logger.info(f"Creating thread: server_id={server_id}, channel_id={channel_id}, members={members}")
logger.debug(f"Offer details: {offer}")
if not server_id or not channel_id or not members:
error_msg = f"Missing required parameters: server_id={server_id}, channel_id={channel_id}, members={members}"
logger.error(error_msg)
return Result(error=error_msg)
try:
guild: discord.Guild = await self.fetch_guild(int(server_id))
if not guild:
error_msg = f"Bot is not in the configured guild: {server_id}"
logger.error(error_msg)
return Result(error=error_msg)
logger.debug(f"Found guild: {guild.name}")
# Fetch channel with error handling
try:
channel = guild.get_channel(int(channel_id))
if not channel:
try:
logger.debug(f"Channel {channel_id} not in cache, fetching from Discord...")
channel: discord.TextChannel = await guild.fetch_channel(int(channel_id))
logger.debug(f"Successfully fetched channel: {channel.name}")
except discord.NotFound:
error_msg = f"The configured thread channel {channel_id} no longer exists in guild {guild.name}"
logger.debug(f"{error_msg} - this is a configuration issue")
return Result(error=error_msg)
except discord.Forbidden:
error_msg = f"The bot does not have permission to view the configured thread channel {channel_id} in guild {guild.name}"
logger.debug(f"{error_msg} - this is a configuration issue")
return Result(error=error_msg)
except discord.InvalidData:
error_msg = f"The bot received invalid data from Discord when attempting to fetch the configured thread channel {channel_id}"
logger.error(error_msg)
return Result(error=error_msg)
except Exception as e:
error_msg = f"Unexpected error fetching channel {channel_id}: {e}"
logger.error(error_msg)
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Full traceback: {traceback.format_exc()}")
return Result(error=error_msg)
if not channel:
error_msg = f"Failed to retrieve channel {channel_id} from guild {guild.name}"
logger.error(error_msg)
return Result(error=error_msg)
except Exception as e:
error_msg = f"Error accessing channel {channel_id}: {e}"
logger.error(error_msg)
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Full traceback: {traceback.format_exc()}")
return Result(error=error_msg)
# Determine thread name
is_order = offer.get("order_id")
thread_name = f"{'order' if is_order else 'offer'}-{offer.get('id', offer.get('order_id'))[:8]}"
logger.debug(f"Creating thread with name: {thread_name}")
# Create thread
try:
thread = await channel.create_thread(
name=thread_name,
type=ChannelType.private_thread
)
logger.info(f"Successfully created thread: {thread.id} with name: {thread.name}")
except discord.Forbidden as e:
error_msg = f"The bot does not have permission to create threads in channel {channel.name}: {e}"
logger.debug(f"{error_msg} - this is a configuration issue")
return Result(error=error_msg)
except discord.HTTPException as e:
error_msg = f"HTTP error creating thread in channel {channel.name}: {e}"
logger.error(error_msg)
return Result(error=error_msg)
except Exception as e:
error_msg = f"Unexpected error creating thread in channel {channel.name}: {e}"
logger.error(error_msg)
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Full traceback: {traceback.format_exc()}")
return Result(error=error_msg)
# Add bot to thread
try:
await thread.add_user(self.user)
logger.debug(f"Added bot to thread {thread.id}")
except Exception as e:
logger.debug(f"Failed to add bot to thread {thread.id}: {e} - this may be a configuration issue")
# Add members to thread
failed_members = []
for member in members:
if not member:
continue
try:
logger.debug(f"Adding member {member} to thread {thread.id}")
await thread.add_user(discord.Object(int(member)))
logger.debug(f"Successfully added member {member} to thread {thread.id}")
except discord.Forbidden as e:
logger.debug(f"Bot lacks permission to add member {member} to thread {thread.id}: {e} - this is a configuration issue")
failed_members.append(member)
except discord.NotFound as e:
logger.debug(f"Member {member} not found: {e} - this may be a configuration issue")
failed_members.append(member)
except discord.HTTPException as e:
logger.error(f"HTTP error adding member {member} to thread {thread.id}: {e}")
failed_members.append(member)
except Exception as e:
logger.error(f"Unexpected error adding member {member} to thread {thread.id}: {e}")
logger.error(f"Error type: {type(e).__name__}")
failed_members.append(member)
# Handle failed member additions
invite = None
if failed_members:
logger.debug(f"Failed to add {len(failed_members)} members to thread {thread.id}: {failed_members} - these may be configuration issues")
try:
logger.info(f"Creating invite for failed members: {failed_members}")
invite = await channel.create_invite(max_uses=len(failed_members))
logger.info(f"Created invite: {invite.code}")
for member in failed_members:
try:
user = await self.fetch_user(int(member))
invite_message = f"You submitted an offer on SC Market. Please join the fulfillment server to communicate directly with the seller: {invite}"
await user.send(invite_message)
logger.info(f"Sent invite message to user {member}")
except discord.Forbidden as e:
logger.debug(f"Cannot send DM to user {member}: {e} - this is a configuration issue")
except discord.NotFound as e:
logger.debug(f"User {member} not found: {e} - this may be a configuration issue")
except Exception as e:
logger.error(f"Failed to send invite message to user {member}: {e}")
logger.error(f"Error type: {type(e).__name__}")
except discord.Forbidden as e:
logger.debug(f"Bot lacks permission to create invite in channel {channel.name}: {e} - this is a configuration issue")
except discord.HTTPException as e:
logger.error(f"HTTP error creating invite in channel {channel.name}: {e}")
except Exception as e:
logger.error(f"Unexpected error creating invite: {e}")
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Full traceback: {traceback.format_exc()}")
result_data = dict(thread_id=str(thread.id), failed=failed_members, invite_code=str(invite.code) if invite else None)
logger.info(f"Thread creation completed successfully: {result_data}")
return Result(value=result_data)
except Exception as e:
error_msg = f"Unexpected error in create_thread: {e}"
logger.error(error_msg)
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Full traceback: {traceback.format_exc()}")
return Result(error=error_msg)
def main():
if Config.BUGSNAG_API_KEY:
bugsnag.configure(
api_key=Config.BUGSNAG_API_KEY,
project_root=os.path.dirname(os.path.abspath(__file__)),
)
logger.info("BugSnag configured from BUGSNAG_API_KEY")
else:
logger.warning("BUGSNAG_API_KEY not set; BugSnag disabled")
# Validate configuration
config_issues = Config.validate()
if config_issues:
logger.error("Configuration validation failed:")
for issue, description in config_issues.items():
logger.error(f" {issue}: {description}")
sys.exit(1)
# Log startup information
LoggingConfig.log_startup_info()
bot = SCMarket(intents=intents, command_prefix="/")
try:
logger.info("Starting bot...")
bot.run(Config.DISCORD_API_KEY)
except KeyboardInterrupt:
logger.info("Received keyboard interrupt, shutting down bot...")
except Exception as e:
logger.error(f"Unexpected error during bot execution: {e}")
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Full traceback: {traceback.format_exc()}")
if Config.BUGSNAG_API_KEY:
bugsnag.notify(e, context="bot main")
finally:
# Log shutdown information
LoggingConfig.log_shutdown_info()
logger.info("Bot shutdown completed")
if __name__ == "__main__":
main()