Untitled

 avatar
unknown
plain_text
10 months ago
8.2 kB
7
Indexable
import discord
from discord.ext import commands, tasks
from itertools import cycle
import random
import os
from PIL import Image, ImageDraw  # Import necessary modules for image processing
import requests
from io import BytesIO
import re

from first_bot_token import BOT_TOKEN  # Import your bot token from a separate file

# Function to create a circular image with a specified size
def create_circular_image(image_url, size=(60, 60)):  # Specify the desired size (width, height)
    response = requests.get(image_url)
    img = Image.open(BytesIO(response.content)).convert("RGBA")
    
    # Resize the image to the specified size using LANCZOS resampling filter
    img = img.resize(size, Image.LANCZOS)
    
    bigsize = (img.size[0] * 3, img.size[1] * 3)
    mask = Image.new('L', bigsize, 0)
    draw = ImageDraw.Draw(mask)
    draw.ellipse((0, 0) + bigsize, fill=255)
    mask = mask.resize(img.size, Image.LANCZOS)
    img.putalpha(mask)

    output = BytesIO()
    img.save(output, format="PNG")
    output.seek(0)
    return output


# Define a custom Bot class inheriting from commands.Bot
class MyBot(commands.Bot):
    def __init__(self, command_prefix, intents):
        super().__init__(command_prefix=command_prefix, intents=intents)
        self.bot_status = cycle(["Initialising...", "Executing Commands...", "Administrating...", "01001000 01001001"])

    async def on_ready(self):
        print(f"{self.user.name} has successfully connected to Discord.")
        self.change_status.start()
        await self.load_cogs()
        await self.sync_commands()

    async def load_cogs(self):
        for filename in os.listdir("./cogs"):
            if filename.endswith(".py"):
                try:
                    await self.load_extension(f"cogs.{filename[:-3]}")
                    print(f"{filename[:-3]} has successfully loaded.")
                except Exception as e:
                    print(f"Failed to load {filename[:-3]}: {e}")

    @tasks.loop(seconds=20)
    async def change_status(self):
        await self.change_presence(activity=discord.Game(next(self.bot_status)))

    async def magic_eight_ball(self, ctx, *, question):
        with open("eight_ball_responses.txt", "r") as file:
            random_responses = file.readlines()
            response = random.choice(random_responses)
        await ctx.send(response)

    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            await ctx.send("That command does not exist.")

    @staticmethod
    def get_server_prefix(bot, message):
        return "/"

    async def sync_commands(self):
        await self.tree.sync()
        print("Commands synced successfully.")

bot = MyBot(command_prefix=MyBot.get_server_prefix, intents=discord.Intents.all())

# Define a view for the review embed
class ReviewView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.embed = discord.Embed(color=discord.Color.blue())  # Initialize the embed with a specified color
        self.embed.add_field(name="Rating", value="Not provided", inline=False)
        self.embed.add_field(name="Review", value="Not provided", inline=False)
        self.embed.add_field(name="Date of Review", value="Not provided", inline=False)
        self.embed.title = "Title"
        self.add_item(RatingButton())
        self.add_item(ReviewButton())

    # Function to update the embed with new title, review, and rating
    def update_embed(self, title=None, review=None, rating=None, date=None):
        if title:
            self.embed.title = title
        if review:
            self.embed.set_field_at(1, name="Review", value=review, inline=False)
        if rating:
            self.embed.set_field_at(0, name="Rating", value=rating, inline=False)
        if date:
            self.embed.set_field_at(2, name="Date", value=date, inline=False)

# Define a button for entering rating
class RatingButton(discord.ui.Button):
    def __init__(self):
        super().__init__(label="Enter Rating", style=discord.ButtonStyle.secondary)

    # Callback function to handle button click
    async def callback(self, interaction: discord.Interaction):
        modal = RatingModal(self.view)
        await interaction.response.send_modal(modal)

# Define a modal for entering rating
class RatingModal(discord.ui.Modal):
    def __init__(self, view):
        self.view = view
        super().__init__(title="Enter a Rating")
        self.rating_input = discord.ui.TextInput(label="Rating", placeholder="Enter a rating out of 5...", max_length=1)
        self.add_item(self.rating_input)

    # Handle form submission
    async def on_submit(self, interaction: discord.Interaction):
        rating = self.rating_input.value
        if rating.isdigit() and 1 <= int(rating) <= 5:
            rating = int(rating)
            star_rating = "⭐" * rating
            self.view.update_embed(rating=star_rating)
            await interaction.response.edit_message(embed=self.view.embed, view=self.view)
        else:
            await interaction.response.send_message("Invalid rating! Please enter a number between 1 and 5.", ephemeral=True)


# Define a button for entering review
class ReviewButton(discord.ui.Button):
    def __init__(self):
        super().__init__(label="Enter Review", style=discord.ButtonStyle.primary)

    # Callback function to handle button click
    async def callback(self, interaction: discord.Interaction):
        modal = ReviewModal(self.view)
        await interaction.response.send_modal(modal)

# Define a modal for entering review
class ReviewModal(discord.ui.Modal):
    def __init__(self, view):
        self.view = view
        super().__init__(title="Enter a Review")
        self.title_input = discord.ui.TextInput(label="Title", placeholder="Enter your title here...", required=True, max_length=30)
        self.review_input = discord.ui.TextInput(label="Review", placeholder="Enter your review here...", style=discord.TextStyle.paragraph, required=True, max_length=500)
        self.date_input = discord.ui.TextInput(label="Date", placeholder="Enter the date here (e.g., 05/19/2024)...", required=True, max_length=10)
        self.add_item(self.title_input)
        self.add_item(self.review_input)
        self.add_item(self.date_input)

    # Handle form submission
    async def on_submit(self, interaction: discord.Interaction):
        title = self.title_input.value
        review = self.review_input.value
        date = self.date_input.value

        # Validate date format (MM/DD/YYYY)
        if not re.match(r"\d{2}/\d{2}/\d{4}", date):
            await interaction.response.send_message("Invalid date format! Please enter the date in the format MM/DD/YYYY (e.g., 05/19/2024).", ephemeral=True)
            return

        self.view.update_embed(title=title, review=review, date=date)
        await interaction.response.edit_message(embed=self.view.embed, view=self.view)


# Define a slash command using the discord.app_commands decorator
@bot.tree.command(name="review", description="Write a Review!")
async def slash_command(interaction: discord.Interaction):
    try:
        view = ReviewView()
        circular_image = create_circular_image(interaction.user.avatar.url)  # Create a circular version of the user's avatar
        file = discord.File(circular_image, filename="circular_avatar.png")  # Convert the circular image to a file
        view.embed.set_footer(text=f"Sent by: @{interaction.user.name}")  # Set the footer
        view.embed.set_footer(text=f"Sent by: @{interaction.user.name}")  # Set the footer text
        view.embed.set_thumbnail(url="attachment://circular_avatar.png")  # Set the thumbnail to the circular avatar
        await interaction.response.send_message(embed=view.embed, view=view, file=file)  # Send the message with embed, view, and file
    except Exception as e:
        print(f"An error occurred: {e}")

# Run the bot
bot.run(BOT_TOKEN)
Editor is loading...
Leave a Comment