Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
37 kB
1
Indexable
Never
import contextlib
import discord
import sqlite3
import random
from discord.ext import commands
import requests
import json
import asyncio
import locale
from typing import Union
import datetime
import matplotlib.pyplot as plt
from datetime import datetime, timedelta, timezone
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

bot = commands.Bot(command_prefix='*', intents=intents)

bot.remove_command('help')

conn = sqlite3.connect('message_db.sqlite')
cursor = conn.cursor()
cursor.execute('''
    CREATE TABLE IF NOT EXISTS messages (
        user_id INTEGER PRIMARY KEY,
        message_count INTEGER
    )
''')
conn.commit()

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game("*help"))
    print(f'Logged on as {bot.user}!')

@bot.event
async def on_command(ctx):
    embed = discord.Embed(
        title=f'Command "{ctx.message.content}" used by {ctx.author.name}',
        description=f'Author ID: {ctx.author.id}\nGuild: {ctx.guild.name} ({ctx.guild.id})',
        color=random.randint(0, 0xFFFFFF)
    )
    channel = bot.get_channel(1080891904616571041) # get the channel by ID
    await channel.send(embed=embed)

@bot.event
async def on_message(message):
    # ignore messages sent by the bot itself or by other bots
    if message.author == bot.user or message.author.bot:
        return

    # add the user to the database if they're not already there
    cursor.execute('''
        INSERT OR IGNORE INTO messages (user_id, message_count)
        VALUES (?, 0)
    ''', (message.author.id,))
    conn.commit()

    # increment the message count for the user and update the database
    cursor.execute('''
        UPDATE messages
        SET message_count = message_count + 1
        WHERE user_id = ?
    ''', (message.author.id,))
    conn.commit()

    if cursor.execute('SELECT message_count FROM messages WHERE user_id = ?', (message.author.id,)).fetchone()[0] == 200:
        role = message.guild.get_role(1084216342305067028)
        await message.author.add_roles(role)
        await message.channel.send(f"Congratulations, {message.author.mention}! You have reached 200 messages and have been assigned the {role.name} role.")

    await bot.process_commands(message)

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        error_msg = await ctx.send("Invalid command.")
    elif isinstance(error, commands.MissingRequiredArgument):
        error_msg = await ctx.send("You are missing a required argument.")
    elif isinstance(error, commands.BadArgument):
        error_msg = await ctx.send("Invalid argument.")
    elif isinstance(error, commands.CommandOnCooldown):
        error_msg = await ctx.send(f"This command is on cooldown. Try again in {round(error.retry_after, 2)} seconds.")
    elif isinstance(error, commands.MissingPermissions):
        error_msg = await ctx.send("You do not have permission to use this command.")
    elif isinstance(error, commands.BotMissingPermissions):
        error_msg = await ctx.send("I do not have permission to perform this command.")
    else:
        error_msg = await ctx.send("An error has occurred while processing your command.")
        print(error)

    await asyncio.sleep(60)
    with contextlib.suppress(discord.errors.NotFound):
        await ctx.message.delete()
        await error_msg.delete()

@bot.command()
async def leaderboard(ctx):
    """Displays the top 10 users by message count."""
    # get the top 10 users by message count
    cursor.execute('''
        SELECT user_id, message_count
        FROM messages
        ORDER BY message_count DESC
        LIMIT 10
    ''')
    rows = cursor.fetchall()

    # create the leaderboard message
    leaderboard = []
    for i, row in enumerate(rows):
        user_id, message_count = row
        member = ctx.guild.get_member(user_id)
        if member is None:
            if not str(user_id).isdigit():
                username = f'user{user_id}'
                user_tag = f'<@{user_id}>'
                leaderboard.append(f'`{i+1})` {username} ({user_tag}): `{message_count}`')

        elif not member.display_name.isdigit():
            username = member.display_name
            user_tag = member.mention
            leaderboard.append(f'`{i+1})` {username} ({user_tag}): `{message_count}`')
    # send the leaderboard as an embed and delete the command message
    color = random.randint(0, 0xFFFFFF)
    embed = discord.Embed(title='Message Leaderboard', description='\n'.join(leaderboard), color=color)
    await ctx.send(embed=embed)

@bot.command()
@commands.has_permissions(administrator=True)
async def cleaderboard(ctx):
    """Clears the message leaderboard."""
    # clear the leaderboard
    cursor.execute('DELETE FROM messages')
    conn.commit()

    # send a confirmation message as an embed and delete the command message
    color = random.randint(0, 0xFFFFFF)
    embed = discord.Embed(title='Message Leaderboard Cleared', color=color)
    embed.add_field(name='Success', value='The message leaderboard has been cleared.')
    await ctx.send(embed=embed)
    await ctx.message.delete()

api_key = 'd820d744-0c5f-46be-a827-7c03c32bef2e'

@bot.command()
async def cprice(ctx, symbol: str=None):
    """Displays the latest price and change in value for a given cryptocurrency symbol."""
    if symbol is None:
        await ctx.send("`Please provide a cryptocurrency symbol. Usage: crypto <symbol>`")
        return

    if not symbol.isalnum() or len(symbol) > 10:
        await ctx.send("`Invalid cryptocurrency symbol. Please enter a valid symbol (alphanumeric and <= 10 characters).`")
        return

    api_url = f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol={symbol}&convert=USD"
    headers = {'X-CMC_PRO_API_KEY': api_key}
    response = requests.get(api_url, headers=headers)

    if response.status_code == 200:
        data = response.json()
        if symbol.upper() not in data['data']:
            await ctx.send(f"`Sorry, could not find price information for {symbol.upper()}.`")
            return
        quote = data['data'][symbol.upper()]['quote']['USD']
        price = quote['price']
        percent_change_1h = quote['percent_change_1h']
        percent_change_24h = quote['percent_change_24h']
        percent_change_7d = quote['percent_change_7d']
        change_1h = round(price * percent_change_1h / 100, 2)
        change_24h = round(price * percent_change_24h / 100, 2)
        change_7d = round(price * percent_change_7d / 100, 2)
        embed = discord.Embed(title=f"```{symbol.upper()}```", description=f"**Current Price:** ```${price:.2f}```\n\n**1 Hour:** ```${change_1h:.2f} ({percent_change_1h:.2f}%)```\n**24 Hours:** ```${change_24h:.2f} ({percent_change_24h:.2f}%)```\n**7 Days:** ```${change_7d:.2f} ({percent_change_7d:.2f}%)```\nPlease note that prices may have changed since this information was last updated.", color=discord.Color(random.randint(0, 0xFFFFFF)))
        await ctx.send(embed=embed)
    elif response.status_code == 400:
        await ctx.send("`Invalid cryptocurrency symbol. Please enter a valid symbol (alphanumeric and <= 10 characters).`")
    else:
        await ctx.send("Sorry, there was an error retrieving the price information.")

@bot.command()
async def news(ctx):
    """Shows the latest crypto news."""
    # Enter your NewsAPI key
    api_key = '52b86c2429704c10a58bfa7141816852'
    url = f'https://newsapi.org/v2/everything?q=cryptocurrency&sortBy=publishedAt&apiKey={api_key}'
    response = requests.get(url)
    news = json.loads(response.text)

    if news['status'] == 'ok':
        articles = news['articles'][:5]  # limit to 5 articles
        color = discord.Color.from_rgb(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))  # generate a random color
        embed = discord.Embed(title="Crypto News", color=color)
        for article in articles:
            title = article['title']
            url = article['url']
            embed.add_field(name=title, value=url, inline=False)
        await ctx.send(embed=embed)
    else:
        await ctx.send("Sorry, something went wrong while fetching the news.")

@bot.command()
async def scam(ctx):
    """Scam detection."""
    await ctx.message.delete()

    # Create the warning embed with a random color
    color = discord.Color.from_rgb(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    embed = discord.Embed(title="Possible Scam Alert!", color=color)
    embed.description = ("Please be cautious of anyone who asks you to leave this server and talk about making money in DMs. "
                          "This could be a possible scam. Remember to report any suspicious activity to our moderators or admins. "
                          "Thank you for helping us keep our community safe!")

    # Send the warning message
    await ctx.send(embed=embed)

class HelpView(discord.ui.View):
    def __init__(self, pages, current_page):
        super().__init__()
        self.pages = pages
        self.current_page = current_page

    async def show_page(self, page):
        self.current_page = page
        embed = self.pages[page]
        await self.message.edit(embed=embed, view=self)

    @discord.ui.button(label="◀️")
    async def prev_page(self, interaction: discord.Interaction, button: discord.ui.Button):
        if self.current_page > 0:
            await self.show_page(self.current_page - 1)
        await interaction.response.edit_message(embed=self.pages[self.current_page])

    @discord.ui.button(label="▶️")
    async def next_page(self, interaction: discord.Interaction, button: discord.ui.Button):
        if self.current_page < len(self.pages) - 1:
            await self.show_page(self.current_page + 1)
        await interaction.response.edit_message(embed=self.pages[self.current_page])  # This line is corrected

    async def error_handler(self, interaction: discord.Interaction, error: Exception):
        # Log the error
        print(f"An error occurred in the HelpView: {error}")

        # Send an error message to the user
        await interaction.response.send_message("An error occurred while processing your request. Please try again later.")
        
@bot.command()
async def help(ctx):
    """Displays this help message."""
    try:
        commands = [command for command in bot.commands if not command.hidden]
        pages = []
        num_commands = len(commands)
        for i in range(0, num_commands, 5):
            command_list = [
                f"{command.help}"
                f"```{command.name}```"
                for command in commands[i:i+5]
            ]
            help_embed = discord.Embed(title="Bot Commands", description="\n".join(command_list), color=random.randint(0, 0xFFFFFF))
            help_embed.set_author(name="Vashly")
            help_embed.set_footer(text=f"Requested by {ctx.author.name}")
            help_embed.description = f"Welcome to the help section! If you need further assistance, please contact the server staff. Here are the available commands:\n\n {help_embed.description}"
            pages.append(help_embed)

        current_page = 0
        view = HelpView(pages, current_page)
        view.message = await ctx.send(embed=pages[current_page], view=view)
    except Exception as e:
        # Log the error
        print(f"An error occurred in the help command: {e}")

        # Send an error message to the user
        await ctx.send("An error occurred while processing your request. Please try again later.")

@bot.event
async def on_member_join(member):
    # Get the welcome channel
    welcome_channel = bot.get_channel(1080155183008448662)

    # Create the welcome embed with a random color
    welcome_embed = discord.Embed(title="Welcome to the world of wealth creation!", color=random.randint(0, 0xFFFFFF))
    welcome_embed.description = (f"Hello, and welcome to our Discord server, {member.mention}! We're excited to have you join our community of like-minded individuals who share a passion for money.\n\n"
                                  "Here in our server, we aim to create a friendly and welcoming environment where you can connect with others, share your thoughts and ideas, and have fun. We encourage respectful and constructive conversations and are always open to new perspectives and diverse opinions.\n\n"
                                  "Whether you're here to learn, socialise, or hang out, we have a variety of channels and features to suit your needs. We've got something for everyone, from discussions and game nights to movie nights and voice channels.\n\n"
                                  "So please take a moment to introduce yourself and familiarise yourself. Our moderators and administrators are always here to help with any questions or concerns.\n\n"
                                  "Once again, welcome to our community! We're thrilled to have you here and look forward to getting to know you.")

    # Check if account age is less than 2 weeks
    if (
        datetime.datetime.now(datetime.timezone.utc) - member.created_at
    ).days < 14:
        # Apply the Muted role to the user
        muted_role = member.guild.get_role(1081654119636410418)
        await member.add_roles(muted_role)

        # Send the muted embed message in the channel
        muted_embed = discord.Embed(title="You have been muted!", color=discord.Color.red())
        muted_embed.description = "We apologize for the inconvenience, but your account is less than 2 weeks old and we suspect you may be a robot. You will be unmuted in 30 minutes."
        await welcome_channel.send(f"{member.mention}:", embed=muted_embed)

        # Wait for 30 minutes and remove the Muted role
        await asyncio.sleep(1800)
        await member.remove_roles(muted_role)

    # Send the welcome message with the mention
    await welcome_channel.send(f"{member.mention}:", embed=welcome_embed)

@bot.command()
async def weeklyjoins(ctx):
    """Shows the servers weekly joins compared to last weeks."""
    current_date = datetime.now(timezone.utc).date()

    # Calculate the start and end dates of the current week
    current_week_start = current_date - timedelta(days=current_date.weekday())
    current_week_end = current_week_start + timedelta(days=6)

    # Calculate the start and end dates of the previous week
    previous_week_start = current_week_start - timedelta(days=7)
    previous_week_end = current_week_start - timedelta(days=1)

    # Get the list of members who joined in the current week
    current_week_joins = [member for member in ctx.guild.members if current_week_start <= member.joined_at.date() <= current_week_end]

    # Get the list of members who joined in the previous week
    previous_week_joins = [member for member in ctx.guild.members if previous_week_start <= member.joined_at.date() <= previous_week_end]

    # Create the graph
    fig, ax = plt.subplots()
    ax.set_xlabel('Week')
    ax.set_ylabel('Number of Joins')

    # Plot the data
    ax.bar('Previous Week', len(previous_week_joins))
    ax.bar('Current Week', len(current_week_joins))

    # Save the graph as a PNG file
    plt.savefig('weekly_joins.png')

    # Create a random color for the embed
    color = random.randint(0, 0xFFFFFF)

    # Create the embed
    embed = discord.Embed(title='Weekly Joins', color=color)
    embed.add_field(name='Previous Week', value=str(len(previous_week_joins)), inline=True)
    embed.add_field(name='Current Week', value=str(len(current_week_joins)), inline=True)

    # Add the graph as an image to the embed
    with open('weekly_joins.png', 'rb') as f:
        file = discord.File(f, filename='weekly_joins.png')
        embed.set_image(url='attachment://weekly_joins.png')
        await ctx.send(embed=embed, file=file)

    # Delete the PNG file
    plt.clf()
    plt.cla()
    plt.close()
    import os
    os.remove("weekly_joins.png")



locale.setlocale(locale.LC_ALL, '') 

@bot.command()
async def profitcal(ctx, symbol: str=None, purchase_price: float=None, quantity: float=None, current_price: float=None):
    """Calculates the profit/loss of a cryptocurrency investment."""
    if symbol is None or purchase_price is None or quantity is None or current_price is None:
        await ctx.send("`Please provide a cryptocurrency symbol, purchase price, quantity, and current price. Usage: crypto_profit <symbol> <purchase_price> <quantity> <current_price>`")
        return

    if not symbol.isalnum() or len(symbol) > 10:
        await ctx.send("`Invalid cryptocurrency symbol. Please enter a valid symbol (alphanumeric and <= 10 characters).`")
        return

    profit = (current_price - purchase_price) * quantity

    # Generate a random color for the embed
    color = random.randint(0, 0xffffff)

    # Create the embed with the results
    embed = discord.Embed(title='Profit Calculator', description='Please note that this calculator provides an estimate of your cryptocurrency investment\'s profit/loss and does not factor in trading fees or tax implications. As such, it should not be used as an exact calculation of your profit/loss.', color=color)
    embed.add_field(name='Symbol', value=f'```{symbol.upper()}```', inline=False)
    embed.add_field(name='Purchase Price', value=f'```${purchase_price:,.2f}```', inline=False)
    embed.add_field(name='Quantity', value=f'```{quantity:,.8f}```', inline=False)
    embed.add_field(name='Current Price', value=f'```${current_price:,.2f}```', inline=False)
    embed.add_field(name='Profit/Loss', value=f'```${profit:,.2f}```', inline=False)

    # Send the embed
    await ctx.send(embed=embed)

@bot.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, member: discord.Member, *, reason: str):
    """Warns a user and stores the warning in a database."""
    # create the database table if it doesn't exist
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS warnings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            moderator_id INTEGER,
            reason TEXT
        )
    ''')
    
    # add the warning to the database
    cursor.execute('''
        INSERT INTO warnings (user_id, moderator_id, reason)
        VALUES (?, ?, ?)
    ''', (member.id, ctx.author.id, reason))
    conn.commit()

    # send a warning message as an embed and delete the command message
    color = random.randint(0, 0xFFFFFF)
    embed = discord.Embed(title='User Warned', description=f'{member.mention} has been warned by - {ctx.author.mention}.', color=color)
    embed.add_field(name='Reason', value=reason)
    await ctx.send(embed=embed)
    await ctx.message.delete()

    # send a DM to the warned user
    dm_embed = discord.Embed(title='You have been warned', description=f'You have been warned by - {ctx.author.mention}.', color=color)
    dm_embed.add_field(name='Reason', value=reason)
    await member.send(embed=dm_embed)

@bot.command()
@commands.has_permissions(administrator=True)
async def cwarnings(ctx, member: discord.Member):
    """Clears all warnings of a user from the database."""
    # delete all warnings of the user from the database
    cursor.execute('''
        DELETE FROM warnings
        WHERE user_id=?
    ''', (member.id,))
    conn.commit()

    # send a message indicating that the warnings have been cleared and delete the command message
    embed = discord.Embed(title='Warnings Cleared', description=f'All warnings of {member.mention} have been cleared.', color=0xFF0000)
    await ctx.send(embed=embed)
    await ctx.message.delete()

@bot.command()
@commands.has_permissions(administrator=True)
async def swarnings(ctx, member: discord.Member):
    """Searches for warnings of a user."""
    # get the user's warnings from the database
    cursor.execute('''
        SELECT id, moderator_id, reason
        FROM warnings
        WHERE user_id = ?
    ''', (member.id,))
    results = cursor.fetchall()

    # create an embed to display the results
    color = random.randint(0, 0xFFFFFF)
    embed = discord.Embed(title='Search Results', color=color)
    embed.set_author(name=f'Warnings for {member.name}', icon_url=member.avatar.url)
    if len(results) > 0:
        for result in results:
            embed.add_field(name=f'Warning #{result[0]}', value=f'Moderator: <@{result[1]}> \nReason: {result[2]}', inline=False)
    else:
        embed.description = 'No warnings found for this user.'
    await ctx.send(embed=embed)

@bot.command()
async def daytrading(ctx):
    """Provides resources and tips for learning day trading."""
    resources = [
    'Investopedia is a great resource for beginners to learn about day trading. They offer a variety of articles, tutorials, and videos to help you get started.',
    'There are several trading simulators available online that allow you to practice trading without risking real money. This is a great way to learn the ropes without putting your finances at risk.',
    'Keeping up with the latest news and trends in the market is essential for day traders. You can follow financial news websites and social media accounts to stay informed.',
    'It is important to develop a strategy that works for you when it comes to day trading. This includes setting goals, determining your risk tolerance, and knowing when to buy and sell stocks.',
    'If you are new to day trading, it may be a good idea to consult with a financial professional. They can help you navigate the risks involved and develop a sound trading strategy.',
    'Stick to stocks with high trading volumes to ensure liquidity and easier buying and selling.',
    'Be disciplined with your trading strategy and avoid making emotional decisions.',
    'Keep a trading journal to track your progress and identify areas for improvement.',
    "Don't chase after hot tips or rumors. Do your own research and analysis before making any trades.",
    'Use stop-loss orders to limit your losses in case a trade doesn\'t go as planned.',
    'Keep your trading plan simple and easy to follow. Avoid overcomplicating things.',
    'Develop a routine to help you stay focused and organized while trading.',
    'Stay patient and avoid getting too caught up in short-term market fluctuations.',
    'Be prepared to adapt your strategy as market conditions change.',
    'Avoid trading based on FOMO (fear of missing out) or other emotional impulses.',
    'Always have an exit strategy in place before entering a trade.',
    'Avoid trading with money you can\'t afford to lose.',
    'Learn from your mistakes and use them to improve your trading strategy.',
    'Avoid trading on margin unless you fully understand the risks involved.',
    'Set realistic goals for your trading and avoid trying to get rich quick.',
    'Keep your trading costs (e.g. commissions, fees) in mind when making trades.',
    'Use technical indicators (e.g. moving averages, RSI) to help you identify trends and potential trading opportunities.',
    'Be aware of potential market-moving events (e.g. earnings reports, economic data releases) and plan accordingly.',
    'Don\'t be afraid to take profits on a winning trade.',
    'Use a trading checklist to help you stay focused and avoid making mistakes.',
    'Avoid trading during periods of high volatility or uncertainty (e.g. major news events).',
    'Use position sizing to limit your risk and avoid overexposure to any one stock.',
    'Use a watchlist to keep track of potential trading opportunities.',
    'Stay up to date on changes to trading regulations and rules.',
    'Don\'t trade just for the sake of trading. Be patient and wait for the right opportunities to present themselves.',
    'Use fundamental analysis (e.g. financial statements, earnings reports) to help you evaluate potential trades.',
    'Don\'t try to predict market movements. Instead, react to what the market is telling you.',
    'Be aware of your own biases and how they may impact your trading decisions.',
    'Stay focused on the long-term goal of consistent profitability, rather than short-term gains.',
    'Always be learning and seeking to improve your trading skills and knowledge.',
    'Investopedia is a great resource for beginners to learn about day trading. They offer a variety of articles, tutorials, and videos to help you get started.',
    'There are several trading simulators available online that allow you to practice trading without risking real money. This is a great way to learn the ropes without putting your finances at risk.',
    'Keeping up with the latest news and trends in the market is essential for day traders. You can follow financial news websites and social media accounts to stay informed.',
    'It is important to develop a strategy that works for you when it comes to day trading. This includes setting goals, determining your risk tolerance, and knowing when to buy and sell stocks.',
    'If you are new to day trading, it may be a good idea to consult with a financial professional. They can help you navigate the risks involved and develop a sound trading strategy.',
    'Stick to stocks with high trading volumes to ensure liquidity and easier buying and selling.',
    'Be disciplined with your trading strategy and avoid making emotional decisions.',
    'Keep a trading journal to track your progress and identify areas for improvement.',
    "Don't chase after hot tips or rumors. Do your own research and analysis before making any trades.",
    'Use stop-loss orders to limit your losses in case a trade doesn\'t go as planned.',
    'Keep your trading plan simple and easy to follow. Avoid overcomplicating things.',
    'Develop a routine to help you stay focused and organized while trading.',
    'Stay patient and avoid getting too caught up in short-term market fluctuations.',
    'Be prepared to adapt your strategy as market conditions change.',
    'Avoid trading based on FOMO (fear of missing out) or other emotional impulses.',
    'Always have an exit strategy in place before entering a trade.',
    'Avoid trading with money you can\'t afford to lose.',
    'Learn from your mistakes and use them to improve your trading strategy.',
    'Avoid trading on margin unless you fully understand the risks involved.',
    'Set realistic goals for your trading and avoid trying to get rich quick.',
    'Keep your trading costs (e.g. commissions, fees) in mind when making trades.',
    'Use technical indicators (e.g. moving averages, RSI) to help you identify trends and potential trading opportunities.',
    'Be aware of potential market-moving events (e.g. earnings reports, economic data releases) and plan accordingly.',
    'Don\'t be afraid to take profits on a winning trade.',
    'Use a trading checklist to help you stay focused and avoid making mistakes.',
    'Avoid trading during periods of high volatility or uncertainty (e.g. major news events).',
    'Use position sizing to limit your risk and avoid overexposure to any one stock.',
    'Use a watchlist to keep track of potential trading opportunities.',
    'Stay up to date on changes to trading regulations and rules.',
    'Don\'t trade just for the sake of trading. Be patient and wait for the right opportunities to present themselves.',
    'Use fundamental analysis (e.g. financial statements, earnings reports) to help you evaluate potential trades.',
    'Don\'t try to predict market movements. Instead, react to what the market is telling you.',
    'Be aware of your own biases and how they may impact your trading decisions.',
    'Stay focused on the long-term goal of consistent profitability, rather than short-term gains.',
    'Always be learning and seeking to improve your trading skills and knowledge.'
]
    page_size = 3
    num_pages = (len(resources) + page_size - 1) // page_size  # ceil(len(resources) / page_size)

    current_page = 1
    start_index = (current_page - 1) * page_size
    end_index = start_index + page_size
    page_resources = resources[start_index:end_index]

    disclaimer = 'Please note that the advice provided here should not be taken as financial advice, and users should speak to a professional before making any investment decisions. Additionally, use the reactions below to navigate pages.'

    embed = discord.Embed(title='Day Trading Resources', description=f'{disclaimer}\n\n`Page {current_page}/{num_pages}`\n\n**Here are some resources and tips to help you learn about day trading:**', color=random.randint(0, 0xFFFFFF))

    for i, resource in enumerate(page_resources, start=start_index + 1):
        embed.add_field(name=f'{i}.', value=resource)

    message = await ctx.send(embed=embed)

    if num_pages > 1:
        await message.add_reaction('⬅️')
        await message.add_reaction('➡️')

        def check(reaction, user):
            return user == ctx.author and reaction.message == message and reaction.emoji in ('⬅️', '➡️')

        while True:
            try:
                reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
            except asyncio.TimeoutError:
                break

            if reaction.emoji == '⬅️' and current_page > 1:
                current_page -= 1
            elif reaction.emoji == '➡️' and current_page < num_pages:
                current_page += 1
            else:
                continue

            start_index = (current_page - 1) * page_size
            end_index = start_index + page_size
            page_resources = resources[start_index:end_index]

            embed.description = f'{disclaimer}\n\n`Page {current_page}/{num_pages}`\n\n**Here are some resources and tips to help you learn about day trading:**'

            for i, resource in enumerate(page_resources, start=start_index + 1):
                embed.set_field_at(i - start_index - 1, name=f'{i}.', value=resource)

            await message.edit(embed=embed)
            await reaction.remove(user)

    await message.clear_reactions()

@bot.command()
@commands.has_permissions(administrator=True)
async def wleaderboard(ctx):

    """Displays the top 10 most warned users."""
    # retrieve warnings from the database and display a leaderboard
    cursor.execute('''
        SELECT user_id, COUNT(*) AS warning_count
        FROM warnings
        GROUP BY user_id
        ORDER BY warning_count DESC
        LIMIT 10
    ''')
    if rows := cursor.fetchall():
        color = random.randint(0, 0xFFFFFF)
        leaderboard = '\n'.join([f'`{idx}.` **{bot.get_user(row[0]).name}** `User ID: ({row[0]})` - `{row[1]} warnings`' for idx, row in enumerate(rows, start=1)])
        embed = discord.Embed(title='Most Warned Users', description=leaderboard, color=color)
        await ctx.send(embed=embed)
    else:
        await ctx.send('No warnings found.')

@bot.command()
async def reactiongame(ctx, member: discord.Member):
    """Starts a reaction game with the specified user."""
    reactions = ['🔴', '🔵', '🟢', '🟡', '🟣', '💴', '👀', '📰']
    correct_reaction = random.choice(reactions)

    # create an embed to display game details
    color = random.randint(0, 0xFFFFFF)
    embed = discord.Embed(title="Reaction Game", color=color)
    embed.set_author(name=f"{ctx.author.display_name} vs {member.display_name}")
    embed.add_field(
        name="Instructions",
        value="React to this message with the correct reaction to win!\n **Please let all reactions to load onto the message before reacting!**",
    )
    embed.set_footer(text="Game ends in 60 seconds.")

    message = await ctx.send(f"{ctx.author.mention} has started a reaction game with {member.mention}!")
    await message.edit(embed=embed)

    for reaction in reactions:
        await message.add_reaction(reaction)

    def check(reaction, user):
        if reaction.message != message or user != member:
            return False
        if str(reaction.emoji) == correct_reaction:
            return True
        else:
            raise ValueError("Selected the wrong reaction")

    try:
        reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
        await message.remove_reaction(reaction, user)

        embed.set_author(name=f"{user.display_name} won the game!")
        embed.set_footer(text="")
        await message.edit(embed=embed)

    except asyncio.TimeoutError:
        embed.set_author(name=f"{member.display_name} didn't react in time.")
        embed.set_footer(text="")
        await message.edit(embed=embed)

    except ValueError:
        embed.set_author(name=f"{member.display_name} selected the wrong reaction.")
        embed.set_footer(text="")
        await message.edit(embed=embed)

@bot.command()
async def coinflip(ctx):
    """Flip a coin and get heads or tails"""
    options = ["Heads", "Tails"]
    result = random.choice(options)
    color = random.randint(0, 0xFFFFFF)
    embed = discord.Embed(title="Coinflip", description=f"The coin landed on **{result}**!", color=color)
    await ctx.send(embed=embed)

@bot.command()
async def droll(ctx, sides: int = 6, rolls: int = 1):
    """Roll one or more dice with a specified number of sides."""
    if sides < 2:
        await ctx.send("The number of sides must be at least 2.")
        return
    if rolls < 1:
        await ctx.send("You must roll the dice at least once.")
        return
    if rolls > 10:
        await ctx.send("You can only roll the dice up to 10 times.")
        return

    results = [random.randint(1, sides) for _ in range(rolls)]
    color = random.randint(0, 0xFFFFFF)
    embed = discord.Embed(title="Dice Roll", description=f"You rolled **{', '.join(str(result) for result in results)}**!", color=color)
    await ctx.send(embed=embed)

@bot.command()
async def joke(ctx):
    """Tells a random joke."""
    url = 'https://official-joke-api.appspot.com/random_joke'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        setup = data['setup']
        punchline = data['punchline']
        color = random.randint(0, 0xFFFFFF)
        embed = discord.Embed(title="Joke", description=f"{setup}\n\n||{punchline}||", color=color)
        await ctx.send(embed=embed)
    else:
        await ctx.send("Failed to get a joke :(")

@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: commands.MemberConverter, *, reason=None):
    """Kicks a member from the server."""
    try:
        await member.kick(reason=reason)

        # Create a random color for the embed
        color = discord.Color.random()

        embed = discord.Embed(title=f"❗️ ❗️ {member.display_name} has been kicked ❗️ ❗️", description=f"**Reason:**\n{reason}", color=color)
        embed.set_footer(text=f"Kicked by {ctx.author.display_name}")

        await ctx.send(embed=embed)
    except Exception as e:
        await ctx.send(f"`❗️ Failed to kick the member. Error: {e}`")

@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: commands.MemberConverter, *, reason=None):
    """Bans a member from the server."""
    try:
        await member.ban(reason=reason)

        # Create a random color for the embed
        color = discord.Color.random()

        embed = discord.Embed(title=f"❗️ ❗️ {member.display_name} has been banned ❗️ ❗️", description=f"**Reason:**\n{reason}", color=color)
        embed.set_footer(text=f"Banned by {ctx.author.display_name}")

        await ctx.send(embed=embed)
    except Exception as e:
        await ctx.send(f"`❗️ Failed to ban the member. Error: {e}`")

@bot.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, member: Union[discord.Member, int], *, reason=None):
    """Unbans a member from the server."""
    if isinstance(member, int):
        user = await bot.fetch_user(member)
        if not user:
            return await ctx.send("❗️ User not found.")
    else:
        user = member

    try:
        await ctx.guild.unban(user, reason=reason)

        # Create a random color for the embed
        color = discord.Color.random()

        embed = discord.Embed(title=f"❗️ ❗️ {user.name} has been unbanned ❗️ ❗️", description=f"**Reason:**\n{reason}", color=color)
        embed.set_footer(text=f"Unbanned by {ctx.author.display_name}")

        await ctx.send(embed=embed)
    except Exception as e:
        await ctx.send(f"`❗️ Failed to unban the user. Error: {e}`")



bot.run('NzMyOTgzOTU2MjQ0NTI5MTcy.GZyKjd.hQfQaP_gE1aAoDptDN9aVlspIiOGfTj6SsZffU')