Giveaway Create command

mail@pastecode.io avatar
unknown
python
a year ago
5.0 kB
2
Indexable
Never
@client.command()
async def create(ctx):
    user = ctx.author

    # Step 1 - Prize:
    embed = discord.Embed(title='🎉 Giveaway Creation 🎉 | Step 1', description=f'{user.mention}, please enter the prize for the giveaway.', color=discord.Colour.blue(), timestamp=ctx.message.created_at)
    await ctx.send(embed=embed)
    try:
        response = await client.wait_for('message', check=lambda msg: msg.author == user, timeout=30)
        user_responses[user.id] = {"prize": response.content}
    except asyncio.TimeoutError:
        embed = discord.Embed(title='Error', description=f'{user.mention}, you took too long to respond. The giveaway creation has been canceled!', color=discord.Colour.red(), timestamp=ctx.message.created_at)
        return await ctx.send(embed=embed)

    # Step 2 - Amount of winners:
    embed = discord.Embed(title='🎉 Giveaway Creation 🎉 | Step 2', description=f'{user.mention}, how many winners should there be? (1-10)', color=discord.Colour.blue(), timestamp=ctx.message.created_at)
    await ctx.send(embed=embed)
    try:
        response = await client.wait_for('message', check=lambda msg: msg.author == user and msg.content.isdigit() and 1 <= int(msg.content) <= 10, timeout=30)
        user_responses[user.id]["winners"] = int(response.content)
    except asyncio.TimeoutError:
        embed = discord.Embed(title='Error', description=f'{user.mention}, you took too long to respond. The giveaway creation has been canceled!', color=discord.Colour.red(), timestamp=ctx.message.created_at)
        return await ctx.send(embed=embed)

    # Step 3 - Duration
    embed = discord.Embed(title='🎉 Giveaway Creation 🎉 | Step 3', description=f'{user.mention}, how long should the giveaway take? (e.g. 30s, 5m, 12h, 3d)', color=discord.Colour.blue(), timestamp=ctx.message.created_at)
    await ctx.send(embed=embed)
    try:
        response = await client.wait_for('message', check=lambda msg: msg.author == user and is_valid_duration(msg.content), timeout=30)
        user_responses[user.id]["duration"] = response.content
    except asyncio.TimeoutError:
        embed = discord.Embed(title='Error', description=f'{user.mention}, you took too long to respond. The giveaway creation has been canceled!', color=discord.Colour.red(), timestamp=ctx.message.created_at)
        return await ctx.send(embed=embed)

    # Step 4 - Create the giveaway
    user_response = user_responses.get(user.id)
    if user_response:
        prize = user_response.get("prize")
        winners = user_response.get("winners")
        duration = user_response.get("duration")
        end_time = calculate_end_time(duration)

        embed = discord.Embed(title=f'🎉 Giveaway | {prize} 🎉', description=f'Winners: {winners}\nEnds in: {duration}\nHosted by: {user.mention}', color=discord.Colour.blue(), timestamp=ctx.message.created_at)
        giveaway_msg = await ctx.send(embed=embed)
        await giveaway_msg.add_reaction("🎉")

        def reaction_check(reaction, reacting_user):
            return str(reaction.emoji) == "🎉" and reacting_user != client.user

        await asyncio.sleep(duration_to_seconds(duration))

        reactions = await giveaway_msg.reactions[0].users().flatten()
        participants = [user for user in reactions if user != client.user]

        if len(participants) >= winners:
            winners = random.sample(participants, winners)
            winner_names = ", ".join([winner.mention for winner in winners])
            embed = discord.Embed(title='🎉 Congrats! 🎉', description=f'{winner_names} won the giveaway!', color=discord.Colour.blue(), timestamp=ctx.message.created_at)
            await ctx.send(embed=embed)
        else:
            embed = discord.Embed(title='Error', description='Not enough participants to determine the winner(s)!', color=discord.Colour.red(), timestamp=ctx.message.created_at)
            await ctx.send(embed=embed)

        await giveaway_msg.delete()

        del user_responses[user.id]

def is_valid_duration(duration_str):
    pattern = re.compile(r'^(\d+[smhd])$')
    if not pattern.match(duration_str):
        return False

    value = int(duration_str[:-1])
    unit = duration_str[-1]

    if unit == 's':
        return 10 <= value <= 604800
    elif unit == 'm':
        return 10 <= value <= 10080
    elif unit == 'h':
        return 10 <= value <= 168
    elif unit == 'd':
        return 1 <= value <= 7
    return False

def duration_to_seconds(duration_str):
    value = int(duration_str[:-1])
    unit = duration_str[-1]

    if unit == 's':
        return value
    elif unit == 'm':
        return value * 60
    elif unit == 'h':
        return value * 3600
    elif unit == 'd':
        return value * 86400

def calculate_end_time(duration_str):
    seconds = duration_to_seconds(duration_str)
    current_time = datetime.utcnow()
    end_time = current_time + timedelta(seconds=seconds)
    return end_time.strftime("%Y-%m-%d %H:%M:%S UTC")