Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
9.2 kB
1
Indexable
from datetime import datetime, timedelta
import os
from sys import int_info
import discord
from discord.ext import commands, tasks
from discord.ext.commands import cooldown, BucketType
import youtube_dl
import random
from random import choice
from replit import db
import asyncio
import aiohttp
import time
import urllib3
from requests import get
import json
import emoji
from typing import List
from discord.ui import Button, Select, View
import typing
from discord import app_commands
import datetime


class Dank(commands.Cog):

  def __init__(self, client):
    self.client = client

  '''---------------------------------------------------------------------------'''
  #Givewaway Command

  @commands.hybrid_command(aliases=['gstart'])
  @app_commands.describe(
      time="The time for the giveaway.",
      winners="The number of winners (e.g., 1w, 2w).",
      requirement="The role required to enter the giveaway.",
      bypass="The role that can bypass the requirement.",
      bonus=
      "The role that gets bonus entries and the number of bonus entries (e.g., @role 3).",
      title="The title for the Giveaway")
  async def giveaway(self,
                     ctx,
                     time: str,
                     winners: str,
                     requirement: discord.Role = None,
                     *,
                     title,
                     bypass: discord.Role = None,
                     bonus: str = None):
    duration_units = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
    duration_seconds = int(time[:-1]) * duration_units[time[-1]]
    end_time = datetime.datetime.now() + datetime.timedelta(
        seconds=duration_seconds)

    if not winners.endswith('w'):
      return await ctx.send(
          "Invalid number of winners format. Use '1w', '2w', etc.")

    winners_count = int(winners[:-1])  # Extract the number of winners

    bonus_role = None
    bonus_entries = 0
    if bonus:
      try:
        role_mention, bonus_entries = bonus.split()
        bonus_role = await commands.RoleConverter().convert(ctx, role_mention)
        bonus_entries = int(bonus_entries)
      except ValueError:
        return await ctx.send(
            "Invalid bonus role format. Use '@role 3' (replace 'role' with the actual role name)."
        )

    requirement_text = f"**Requirement:** {requirement.mention}" if requirement else "**Requirement:** none"
    bypass_text = f"**Bypass:** {bypass.mention}" if bypass else ""
    bonus_text = f"**Bonus:** {bonus_role.mention} {bonus_entries}" if bonus_role else ""

    embed = discord.Embed(
        title=f'{title}',
        description=
        f'React below to enter!\n**Hosted By:** {ctx.author.mention}\n**Ends at:** <t:{int(end_time.timestamp())}>\n**Number of Winners:** {winners_count}{"w" if requirement or bonus_role else ""}\n{requirement_text}\n{bypass_text}\n{bonus_text}',
        colour=discord.Colour.blurple())
    embed.set_footer(text=f"Giveaway ID: {ctx.message.id}")

    wembed = discord.Embed(
        description=
        f'Congratulations! You have won the giveaway of **{title}** in _*{ctx.guild.name}*_. [Giveaway Message]({ctx.message.jump_url})',
        colour=discord.Colour.green())

    my_message = await ctx.send(embed=embed)
    await my_message.add_reaction("πŸŽ‰")

    await asyncio.sleep(duration_seconds)

    message = await ctx.channel.fetch_message(my_message.id)
    reaction = next((r for r in message.reactions if str(r.emoji) == "πŸŽ‰"),
                    None)

    if reaction:
      valid_users = []
      invalid_users = []
      async for user in reaction.users():
        if user.bot:
          continue
        elif requirement and requirement not in user.roles and bypass not in user.roles:
          try:
            dm_embed = discord.Embed(
                description=
                f"You don't have the '{requirement.name}' role required to enter this giveaway.",
                colour=discord.Colour.red())
            await user.send(embed=dm_embed)
          except discord.HTTPException:
            pass
          invalid_users.append(user)
        else:
          entries = 1
          if bonus_role in user.roles:
            entries += bonus_entries
          for _ in range(entries):
            valid_users.append(user)

      for user in invalid_users:
        await reaction.remove(user)

      if len(valid_users) < winners_count:
        await ctx.send(
            f"Insufficient participants for {winners_count} winner(s). Giveaway ended."
        )
        return

      chosen_winners = random.sample(valid_users, k=winners_count)

      end_embed = discord.Embed(
          title='This Giveaway Has Ended!',
          description=
          f'**Winner(s):** {", ".join(winner.mention for winner in chosen_winners)}\n**Prize:** {title}\n**Hosted By:** {ctx.author.mention}\n**Requirements:** {requirement}',
          colour=discord.Colour.green())
      await my_message.edit(embed=end_embed
                            )  # Edit the original message with the end_embed

      for winner in chosen_winners:
        await winner.send(embed=wembed)
        winner_mentions = ", ".join(winner.mention for winner in chosen_winners)
        giveaway_link = ctx.message.jump_url
        message = f"Your giveaway for {title} in **{ctx.guild.name}** has ended. The winner(s) is: {winner_mentions}\n[Giveaway Link]({giveaway_link})"
        await ctx.author.send(message)

      #await my_message.edit(embed=end_embed)
      

    else:
      await ctx.send("No participants for the giveaway. Giveaway ended.")

  '''---------------------------------------------------------------------------'''
  #Reroll
  @commands.command(name='reroll')
  async def giveaway_reroll(self, ctx, giveaway_id: int, winners: int, title):

    message = await ctx.channel.fetch_message(giveaway_id)
    reaction = next((r for r in message.reactions if str(r.emoji) == "πŸŽ‰"),
                    None)
    if reaction:
      users = []
      async for user in reaction.users():
        users.append(user)
      if len(users) < winners:
        await ctx.send(
            f"Insufficient participants for {winners} winner(s). Reroll not possible."
        )
        return
      chosen_winner = random.choice(users)
      wembed = discord.Embed(
          description=
          f'Congratulations! You have won the giveaway of {title} in {ctx.guild.name}',
          colour=discord.Colour.green())
      await chosen_winner.send(embed=wembed)
      await ctx.send(
          f'{chosen_winner} has won the rerolled giveaway for {title}!')
    else:
      await ctx.send("No participants for the giveaway. Reroll not possible.")

  '''---------------------------------------------------------------------------'''
  #Rolemebers
  @commands.hybrid_command(aliases=['ri'])
  @app_commands.describe(role="The role about which you want the information")
  async def roleinfo(self, ctx, role: discord.Role):
    count = len(role.members)
    await ctx.send(f"The role {role.name} has {count} members.")

  '''---------------------------------------------------------------------------'''
  #Autopartner
  #@commands.hybrid_command()
  #async def partner(self, ctx, role, reach, schannel, ID, *, message):
  #embed = discord.Embed(
  #title='Partner Request',
  #description=
  #f'''{ctx.author.mention} has requested a partnership with your server.\n**Their server Id:** {ID}\n**The role they offered:** {role}\n**Their role reach:** {reach}\n**Seperate channel:** {schannel}\n**Message from the client:** {message}''',
  #colour=discord.Colour.blue())
  #owner = ctx.guild.owner
  #await owner.send(embed=embed)
  '''---------------------------------------------------------------------------'''
  #Timer⏰
  @commands.hybrid_command()
  async def timer(self, ctx, time: str, *, title):
    if not any(char.isdigit()
               for char in time) or time[-1] not in ['s', 'm', 'h', 'd']:
      await ctx.send(
          'Invalid time format. Please use a format like "5s" or "1m".')
      return
    time_units = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
    time_seconds = int(time[:-1]) * time_units[time[-1]]
    end_time = datetime.datetime.now() + datetime.timedelta(
        seconds=time_seconds)
    tembed = discord.Embed(
        title=title,
        description=f"Ends at: <t:{int(end_time.timestamp())}>",
        colour=discord.Colour.blue())
    msg = await ctx.send(embed=tembed)
    await msg.add_reaction('⏰')
    await asyncio.sleep(time_seconds)
    msg = await ctx.channel.fetch_message(msg.id)
    reactions = msg.reactions
    mentioned_users = []
    for reaction in reactions:
      if reaction.emoji == '⏰':
        async for user in reaction.users():
          mentioned_users.append(user.mention)
    message = await ctx.send("Time's up! Users who reacted: " +
                             ", ".join(mentioned_users))
    await asyncio.sleep(3)
    await message.edit(content=f"The timer for **{title}** has ended.")


'''---------------------------------------------------------------------------'''


async def setup(client: commands.Bot):
  await client.add_cog(Dank(client))
Leave a Comment