captcha

 avatar
unknown
python
2 years ago
6.1 kB
7
Indexable
import contextlib
import json
import logging
import os
import platform
import random
import string
import time
import traceback
from typing import Union

import discord
from captcha.image import ImageCaptcha
from colorama import Back, Fore, Style
from discord.ext import commands
from discord import ui

import settings

logger = settings.logging.getLogger("bot")

config = None
verify_channel = None
verify_role = None
verify_guild = None
length = 6


def run():
    class PersistentViewBot(commands.Bot):
        def __init__(self):
            intents = discord.Intents().all()
            super().__init__(command_prefix="-", intents=intents)

        async def setup_hook(self) -> None:
            self.add_view(VerifyButton())

    bot = PersistentViewBot()

    @bot.event
    async def on_ready():
        global config
        global verify_channel
        global verify_role
        global verify_guild
        prfx = (
            Fore.BLUE
            + time.strftime("%H:%M:%S PST", time.localtime())
            + Back.RESET
            + Fore.WHITE
            + Style.BRIGHT
        )
        print(f"{prfx} Loading config... {Fore.CYAN}")
        try:
            config = json.loads(open("config.json", "r").read())
        except Exception:
            print(f"{prfx} No config found! Run -setup in your server!")
        else:
            verify_guild = bot.get_guild(config["guild"])
            verify_channel = bot.get_channel(config["channel"])
            verify_role = verify_guild.get_role(config["role"])
        synced = await bot.tree.sync()
        print(f"{prfx} Slash CMDs Synced " + str(len(synced)) + " Commands")
        logger.info(f"User: {bot.user} (ID: {bot.user.id})")

    class VerifyButton(discord.ui.View):
        def __init__(self):
            super().__init__(timeout=None)

        @discord.ui.button(label="verify", custom_id="verify_button")
        async def verify(
            self, interaction: discord.Interaction, Button: discord.ui.Button
        ):
            global config
            global verify_channel
            global verify_role
            global verify_guild
            text = "".join(
                random.choice(
                    string.ascii_uppercase + string.digits + string.ascii_lowercase
                )
                for _ in range(length)
            )
            file_name = "".join(
                random.choice(
                    string.ascii_uppercase + string.digits + string.ascii_lowercase
                )
                for _ in range(20)
            )
            image = ImageCaptcha(width=280, height=90)
            captcha = image.generate(text)
            # ? WORKING TO HERE
            print(text)
            image.write(text, f"captchas\\{file_name}.png")
            file = discord.File(
                f"captchas//{file_name}.png", filename=f"{file_name}.png"
            )
            embed = discord.Embed(
                title="Verification",
                description="This server is using Captcha Verification\n to protect their server.\n\nPlease type out the letters you see in\nthe captcha below.\n\n**Note:** The captcha is **case-sensitive.**",
                color=0x000001,
            )
            embed.set_footer(text="Captcha Verification by /bran#6666")
            embed.set_image(url=f"attachment://{file_name}.png")
            await interaction.response.send_message(
                embed=embed,
                file=file,
                ephemeral=True,
                view=MyView2(),
            )

    class MyView2(discord.ui.View):
        def __init__(self):
            super().__init__(timeout=None)

        @discord.ui.button(
            label="Input Code",
            row=0,
            style=discord.ButtonStyle.secondary,
            custom_id="InputCode",
        )
        async def button_callback(self, interaction, button):
            await interaction.response.send_modal(MyModal())

            print("Modal has been sent successfully")

    class MyModal(ui.Modal, title="Verification"):
        code = ui.TextInput(
            label="Captcha",
            placeholder="Input Captcha Code",
            style=discord.TextStyle.short,
        )

        async def on_submit(self, interaction: discord.Interaction):
            for x in range(3):
                try:
                    code = await interaction.on_submit(
                        "checkcaptcha", check=interaction.on_submit, timeout=30
                    )
                except:
                    try:
                        await interaction.user.kick(
                            reason="Verification Timeout.", ephemeral=True
                        )
                    except:
                        pass
                    break
                else:
                    if code == text:
                        await interaction.user.add_roles(verify_role)
                        return
                    if x != 2:
                        code = await verify_channel.interaction.response.send_message(
                            f"{interaction.user.mention} Invalid, you have {2 - x} attempts left.",
                            ephemeral=True,
                        )
            try:
                interaction.user.kick(reason="Too many attempts.", ephemeral=True)
            except:
                pass

    @bot.tree.command(name="verify")
    async def verify(interaction: discord.Interaction):
        buttembed = discord.Embed(
            title="This is a test embed",
            description="I hate Discord bots.",
            color=0x000001,
        )
        buttembed.set_footer(text="Captcha Verification by /bran#6666")
        await interaction.channel.send(
            content="",
            embed=buttembed,
            view=VerifyButton(),
        )

    bot.run(settings.DISCORD_TOKEN, root_logger=True)


if __name__ == "__main__":
    run()
Editor is loading...