modified: bot.py

This commit is contained in:
SimolZimol
2025-10-09 12:47:59 +02:00
parent 9d1b502609
commit 6cd187b950

225
bot.py
View File

@@ -787,10 +787,13 @@ async def handle_expired_giveaway(process_uuid, data):
# Use process_uuid as giveaway_id since that's our new system
giveaway_id = str(process_uuid)
logger.info(f"Processing expired giveaway with ID: {giveaway_id[:8]}...")
# Try to get giveaway from memory first, then from database
giveaway = None
if giveaway_id in giveaways:
giveaway = giveaways[giveaway_id]
logger.info(f"Found giveaway {giveaway_id[:8]} in memory")
else:
# Recreate giveaway object from database data
try:
@@ -862,7 +865,7 @@ async def handle_expired_giveaway(process_uuid, data):
# List winners
winner_list = []
for i, winner in enumerate(winners, 1):
winner_list.append(f"<EFBFBD> **#{i}** {winner.mention}")
winner_list.append(f"🏆 **#{i}** {winner.mention}")
winner_embed.add_field(name="🎊 Winners", value="\n".join(winner_list), inline=False)
@@ -1763,6 +1766,226 @@ async def startgiveaway(ctx, platform: str, prize: str, num_winners: int, title:
if not process_manager.is_running():
process_manager.start()
@client.hybrid_command()
async def editgiveaway(ctx, giveaway_id: str, field: str, *, new_value: str):
"""Edit an active giveaway (Only available for admins)
Parameters:
- giveaway_id: The giveaway ID (first 8 characters of UUID are enough)
- field: What to edit (sponsor, title, subtitle, prize, duration)
- new_value: The new value for the field
"""
guild_id = ctx.guild.id
user_data = load_user_data_sync(ctx.author.id, guild_id)
if user_data["permission"] < 5:
await ctx.send("You don't have permission to edit giveaways.")
return
# Find giveaway by partial ID
matching_giveaway = None
matching_id = None
for giv_id, giveaway in giveaways.items():
if giv_id.startswith(giveaway_id) or giveaway_id in giv_id:
matching_giveaway = giveaway
matching_id = giv_id
break
if not matching_giveaway:
await ctx.send(f"❌ No active giveaway found with ID starting with `{giveaway_id}`")
return
# Validate field
valid_fields = ["sponsor", "title", "subtitle", "prize", "duration"]
if field.lower() not in valid_fields:
await ctx.send(f"❌ Invalid field. Valid fields: {', '.join(valid_fields)}")
return
# Store old value for comparison
old_value = getattr(matching_giveaway, field.lower(), "Not set")
try:
# Edit the field
if field.lower() == "sponsor":
matching_giveaway.sponsor = new_value
# Process sponsor mention for display
matching_giveaway.sponsor_display = await process_sponsor_mention(ctx, new_value)
elif field.lower() == "title":
matching_giveaway.title = new_value
elif field.lower() == "subtitle":
matching_giveaway.subtitle = new_value
elif field.lower() == "prize":
matching_giveaway.prize = new_value
elif field.lower() == "duration":
# Parse new duration and update end_time
if new_value.endswith("m"):
minutes = int(new_value[:-1])
new_end_time = datetime.now() + timedelta(minutes=minutes)
elif new_value.endswith("h"):
hours = int(new_value[:-1])
new_end_time = datetime.now() + timedelta(hours=hours)
elif new_value.endswith("d"):
days = int(new_value[:-1])
new_end_time = datetime.now() + timedelta(days=days)
else:
await ctx.send("❌ Invalid duration format. Use 'm' for minutes, 'h' for hours, or 'd' for days.")
return
matching_giveaway.duration = new_value
matching_giveaway.end_time = new_end_time
# Update the process end_time in database
try:
# Use existing update_process_status function to update end_time
connection = connect_to_database()
cursor = connection.cursor()
update_query = "UPDATE active_processes SET end_time = %s WHERE uuid = %s"
cursor.execute(update_query, (new_end_time, str(matching_giveaway.process_uuid)))
connection.commit()
cursor.close()
close_database_connection(connection)
logger.info(f"Updated process end_time for giveaway {matching_giveaway.process_uuid}")
except Exception as e:
logger.error(f"Error updating process end_time: {e}")
# Update process data in database
try:
giveaway_data = {
"guild_id": matching_giveaway.guild_id,
"channel_id": matching_giveaway.ctx.channel.id,
"platform": matching_giveaway.platform,
"prize": matching_giveaway.prize,
"num_winners": matching_giveaway.num_winners,
"title": matching_giveaway.title,
"subtitle": matching_giveaway.subtitle,
"sponsor": matching_giveaway.sponsor,
"sponsor_display": matching_giveaway.sponsor_display,
"game_url": matching_giveaway.game_url,
"game_info": matching_giveaway.game_info,
"winner_uuids": [str(uuid) for uuid in matching_giveaway.winner_uuids],
"prize_uuid": str(matching_giveaway.prize_uuid),
"game_key": matching_giveaway.game_key,
"participants": []
}
update_process_status(matching_giveaway.process_uuid, "active", data=giveaway_data)
except Exception as e:
logger.error(f"Error updating process data: {e}")
# Success message
embed = discord.Embed(
title="✅ Giveaway Updated",
description=f"Successfully updated the giveaway!",
color=0x00ff00,
timestamp=datetime.now()
)
embed.add_field(name="🆔 Giveaway ID", value=f"`{matching_id[:8]}...`", inline=True)
embed.add_field(name="📝 Field Updated", value=f"**{field.title()}**", inline=True)
embed.add_field(name="👤 Updated by", value=ctx.author.mention, inline=True)
embed.add_field(name="🔄 Changes", value=f"**Old:** {old_value}\n**New:** {new_value}", inline=False)
if field.lower() == "duration":
embed.add_field(name="⏰ New End Time",
value=f"<t:{int(matching_giveaway.end_time.timestamp())}:F>\n<t:{int(matching_giveaway.end_time.timestamp())}:R>",
inline=False)
embed.set_footer(text="Changes are immediately effective")
await ctx.send(embed=embed)
logger.info(f"Giveaway {matching_id[:8]} edited by {ctx.author.id}: {field} = {new_value}")
except Exception as e:
logger.error(f"Error editing giveaway: {e}")
await ctx.send(f"❌ Error editing giveaway: {str(e)}")
@client.hybrid_command()
async def listgiveaways(ctx):
"""List all active giveaways in this server (Only available for admins)"""
guild_id = ctx.guild.id
user_data = load_user_data_sync(ctx.author.id, guild_id)
if user_data["permission"] < 5:
await ctx.send("You don't have permission to list giveaways.")
return
# Filter giveaways for this guild
server_giveaways = []
for giv_id, giveaway in giveaways.items():
if giveaway.guild_id == guild_id and not giveaway.is_finished():
server_giveaways.append((giv_id, giveaway))
if not server_giveaways:
embed = discord.Embed(
title="📋 No Active Giveaways",
description="There are currently no active giveaways in this server.",
color=0x3498db
)
await ctx.send(embed=embed)
return
# Create list embed
embed = discord.Embed(
title="🎉 Active Giveaways",
description=f"Found **{len(server_giveaways)}** active giveaway(s) in this server:",
color=0xFFD700,
timestamp=datetime.now()
)
for giv_id, giveaway in server_giveaways[:10]: # Limit to 10 for readability
# Calculate remaining time
remaining = giveaway.end_time - datetime.now()
if remaining.total_seconds() > 0:
days = remaining.days
hours, remainder = divmod(remaining.seconds, 3600)
minutes, _ = divmod(remainder, 60)
if days > 0:
time_left = f"{days}d {hours}h {minutes}m"
elif hours > 0:
time_left = f"{hours}h {minutes}m"
else:
time_left = f"{minutes}m"
else:
time_left = "Expired (processing...)"
# Giveaway info
prize_text = giveaway.prize
if hasattr(giveaway, 'game_info') and giveaway.game_info and giveaway.game_info.get('name'):
prize_text = giveaway.game_info['name']
giveaway_info = f"**Prize:** {prize_text}\n"
giveaway_info += f"**Platform:** {giveaway.platform}\n"
giveaway_info += f"**Winners:** {giveaway.num_winners}\n"
giveaway_info += f"**Participants:** {len(giveaway.participants)}\n"
giveaway_info += f"**Time Left:** {time_left}\n"
if hasattr(giveaway, 'sponsor_display') and giveaway.sponsor_display:
giveaway_info += f"**Sponsor:** {giveaway.sponsor_display}\n"
giveaway_info += f"**ID:** `{giv_id[:8]}...`"
embed.add_field(
name=f"🎁 {giveaway.title}",
value=giveaway_info,
inline=True
)
if len(server_giveaways) > 10:
embed.add_field(
name=" Note",
value=f"Showing first 10 of {len(server_giveaways)} giveaways.",
inline=False
)
embed.set_footer(text="Use /editgiveaway <id> <field> <value> to edit a giveaway")
await ctx.send(embed=embed)
# -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
live_chats = {}