#discord-bots

1 messages · Page 389 of 1

fast osprey
#

read the warning carefully

formal basin
#

oh

young dagger
#
class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.moderator_roles = (727152007009271822, 710242627089596459, 710241598348329080, 949779453909823488,
                                711210963231178803, 1076838318555267073)

    # Mute command
    @commands.command(name="mute", description="Mutes the user.")
    @commands.guild_only()
    @commands.cooldown(1, 5.0, commands.BucketType.user)
    @commands.has_any_role(self.moderator_roles)

Why can't I use the decorator check for my commands? Unresolved reference 'self'

real rampart
#

Change the check_moderator Instead of a staticmethod, make check_moderator

young dagger
#

Do you have any idea?

fast osprey
#

If this is hardcoded just put it in the decorator

formal basin
fast osprey
#

There isn't an event

#

you pass initial presence into the bot constructor

young dagger
fast osprey
#

Also very generally, people really don't care about how many servers your bot is in. It's just a humblebrag that steals space from something that could actually be useful

fast osprey
#

You could look at things that aren't a publicly broadcast status shrug

real rampart
# young dagger ```py class Moderation(commands.Cog): def __init__(self, bot): self....

`class Moderation(commands.Cog):
def init(self, bot):
self.bot = bot
self.moderator_roles = (727152007009271822, 710242627089596459, 710241598348329080, 949779453909823488,
711210963231178803, 1076838318555267073)

def is_moderator(self, ctx):
    return any(role.id in self.moderator_roles for role in ctx.author.roles)

def check_moderator(self):
    return commands.check(self.is_moderator)

@commands.command(name="mute", description="Mutes the user.")
@commands.guild_only()
@commands.cooldown(1, 5.0, commands.BucketType.user)
@check_moderator() 
async def mute(self, ctx, member: commands.MemberConverter, *, reason=None):
    await ctx.send(f"{member} has been muted for reason: {reason}"

bot.add_cog(Moderation(bot))`

#

try it like this

young dagger
fast osprey
#

These don't need to be an instance attribute

#

you could just set a constant

formal basin
fast osprey
#

yup

#

it has status and activity kwargs

formal basin
fast osprey
#

What do you mean by "see"

fast osprey
# young dagger Any idea?

Just use a constant. Again this doesn't need to be an instance attribute if it's not changing per instance

young dagger
young dagger
fast osprey
#

Exactly

young dagger
# fast osprey Exactly

Than I should use @commands.has_any_role(*moderator_roles) to unpack the tuple into individual arguments?

fast osprey
#

Yeah that should work

young dagger
fast osprey
#

Not that I'm aware of

#

You may really want to consider moving to app commands instead

young dagger
fast osprey
#

The formal name is app commands as that also includes context menus, but yes

pale turtle
#

Hi. I used to code a lot of discord bots using python in the past, but it has been so so long since I last coded one, and I wanna get back at it. Is there some manual that really teaches everything from the beginning, including all of these new features such as slash commands, menus, etc...

stark ingot
pale turtle
fast osprey
#

It's also a bit of a mixed bag. The libraries tend to only officially support api docs which tell you how the individual components work. These deep dive "tutorials" are made by individuals and vary a ton on quality or recency

stark ingot
#

There are a bunch now, py-cord, nextcord, disnake, etc

fast osprey
#

There were loads of forks made while discord.py was on hiatus

pale turtle
#

Which one would you suggest I use?

fast osprey
#

Very subjective question tbh

#

Pretty much all of the popular ones are up to date on the discord api

#

Becomes a question of library design choices and support

stark ingot
pale turtle
#

So the top 4 would be discord.py, py-cord, nextcord and disnake? Or are there more worth checking out

stark ingot
fast osprey
#

Iirc hikari was the only one with novel design and not just a dpy fork

stark ingot
pale turtle
#

Alright. I'll make sure to check them. Just interested, which one do you both use?

stark ingot
#

I use py-cord

fast osprey
#

I am community support for discord.py so take that with a grain of salt lol

pale turtle
#

Alright. Thank you both for the help, much appreciated!

young dagger
fast osprey
#

If you do that, you are persisting a single view object across all of the messages that view type might be on

fast osprey
#

Either use dynamic items, or make as many views as you need

young dagger
young dagger
quick gust
#

Pycharm?

stark ingot
#

That is something you can ignore. Generally you do not make a function that does not use an argument but in this case you have to so that the lib can provide the argument without erroring

young dagger
young dagger
stark ingot
#

Not that I know of, it is just a weak warning that you have to ignore

young dagger
#

Is there any way to supress these warnings in Pycharm by adding a comment?

quick gust
#

Yeah just add a _ before the parameter

late knoll
#

Hi, not sure if this is the right channel to ask this in but I was having some trouble so I figured I'd try, https://github.com/vn-ki/film-raffle-bot I'm attempting to recreate a discord bot that uses python, I think I've got the main elements in the config file down but I'm having trouble with setting up a database for it since I have no experience with that. Any suggestions or recommendations for what to use?

GitHub

Contribute to vn-ki/film-raffle-bot development by creating an account on GitHub.

young dagger
#

It removes the buttons but not the image

dry kelp
# young dagger It removes the buttons but not the image
@staticmethod
def create_answer_callback(user, correct_answer):
    async def answer_callback(interaction: discord.Interaction):
        if interaction.user != user:
            return

        selected_answer = interaction.data["custom_id"].split(":")[1]
        if selected_answer == correct_answer:
            response = "You have been successfully verified."
        else:
            response = "Verification failed. Please try again."

        # Create a new embed or modify the existing one to remove the image
        new_embed = discord.Embed(title="", description=response, color=discord.Color.blue())
        new_embed.set_image(url=None)  # Explicitly clear the image

        # Edit the message to update the content and remove the buttons
        await interaction.response.edit_message(embed=new_embed, view=None)

    return answer_callback
#

Try this ⬆️

young dagger
dry kelp
#

1 moment

dry kelp
# young dagger Captcha image is still there
@staticmethod
def create_answer_callback(user, correct_answer):
    async def answer_callback(interaction: discord.Interaction):
        if interaction.user != user:
            return

        selected_answer = interaction.data["custom_id"].split(":")[1]
        if selected_answer == correct_answer:
            response = "You have been successfully verified."
        else:
            response = "Verification failed. Please try again."

        # Create a new embed or modify the existing one to remove the image
        new_embed = discord.Embed(title="", description=response, color=discord.Color.blue())

        # Edit the message to update the content, remove the buttons, and the image (embed and file)
        await interaction.response.edit_message(content=response, embed=new_embed, attachments=[], view=None)

    return answer_callback

You need to make sure that the one you're editing is the actual message, and i am unsure but i didn't know we can edit ephemeral messages.

#

And i don't think we can edit them, i never tried and never looked into that.

young dagger
#

Thanks spooky

ivory remnant
# dry kelp And i don't think we can edit them, i never tried and never looked into that.

i keep getting the same error.. who can help?

Exception has occurred: Forbidden
403 Forbidden (error code: 50007): Cannot send messages to this user
  File "C:\Users\jeqqy\OneDrive\Desktop\Frostware\frostware.py", line 653, in sendkey
    await user.send(f"Your key is: {key.strip()}")
  File "C:\Users\jeqqy\OneDrive\Desktop\Frostware\frostware.py", line 683, in <module>
    botclient.run(bottoken)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```

```py
        for user in users_to_message:
            try:
                await user.send(f"Your key is: {key.strip()}")
                print(f">> Sent key to {user.name}")
                users_to_message.remove(user)
                break 
            except discord.Forbidden:
                print(f">> Cannot send message to {user.name}, DMs are closed.")
                await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
            except Exception as e:
                print(f">> An unexpected error occurred with {user.name}: {e}")
                await ctx.send(f"An unexpected error occurred with {user.name}: {e}")```
dry kelp
ivory remnant
dry kelp
#

I can't see the full code, But i belive that's why this happens.

ivory remnant
ivory remnant
#
@botclient.command()
async def sendkey(ctx):
    if ctx.author.id != 849652633261834241:
        await ctx.send("You don't have permission to use this command.")
        return

    if not os.path.exists(KEY_FILE):
        await ctx.send("Key file does not exist.")
        return

    with open(KEY_FILE, 'r') as file:
        keys = file.read().strip().split(',')

    guild = botclient.get_guild(GUILD_ID)
    if guild is None:
        await ctx.send("Guild not found.")
        return

    role = guild.get_role(ROLE_ID)
    if role is None:
        await ctx.send("Role not found.")
        return

    users_to_message = [member for member in guild.members if role in member.roles]

    if not users_to_message:
        await ctx.send("No users with the specified role found.")
        return

    for key in keys:
        if not users_to_message:
            break

        for user in users_to_message:
            try:
                await user.send(f"Your key is: {key.strip()}")
                print(f">> Sent key to {user.name}")
                users_to_message.remove(user)
                break 
            except discord.Forbidden:
                print(f">> Cannot send message to {user.name}, DMs are closed.")
                await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
            except Exception as e:
                print(f">> An unexpected error occurred with {user.name}: {e}")
                await ctx.send(f"An unexpected error occurred with {user.name}: {e}")
        
        keys.remove(key)
        with open(KEY_FILE, 'w') as file:
            file.write(','.join(keys))

    await ctx.send("Keys sent and updated.")```
#

see

dry kelp
#

Ah

#

1 moment

#
@botclient.command()
async def sendkey(ctx: commands.Context) -> None:
    bot_owner_id = 849652633261834241  # Replace with actual bot owner's ID
    
    if ctx.author.id != bot_owner_id:
        await ctx.send("You don't have permission to use this command.")
        return

    if not os.path.exists(KEY_FILE):
        await ctx.send("Key file does not exist.")
        return

    with open(KEY_FILE, 'r') as file:
        keys = [key.strip() for key in file.read().split(',')]

    guild = botclient.get_guild(GUILD_ID)
    if guild is None:
        await ctx.send("Guild not found.")
        return

    role = guild.get_role(ROLE_ID)
    if role is None:
        await ctx.send("Role not found.")
        return

    users_to_message = [member for member in guild.members if role in member.roles]

    if not users_to_message:
        await ctx.send("No users with the specified role found.")
        return

    for key in keys[:]:
        if not users_to_message:
            break

        user = users_to_message.pop(0)  # Get and remove the first user in the list
        try:
            await user.send(f"Your key is: {key}")
            print(f">> Sent key to {user.name}")
        except discord.Forbidden:
            print(f">> Cannot send message to {user.name}, DMs are closed.")
            await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
        except Exception as e:
            print(f">> An unexpected error occurred with {user.name}: {e}")
            await ctx.send(f"An unexpected error occurred with {user.name}: {e}")
        else:
            keys.remove(key)  # Remove the key after successful delivery

    # Update the key file
    with open(KEY_FILE, 'w') as file:
        file.write(','.join(keys))

    await ctx.send("Keys sent and updated.")
#

@ivory remnant

ivory remnant
young dagger
#

Is it better to use os or pathlib?

dry kelp
# ivory remnant same error
@botclient.command()
async def sendkey(ctx: commands.Context) -> None:
    bot_owner_id = 849652633261834241  # Replace with the actual bot owner's ID
    
    if ctx.author.id != bot_owner_id:
        await ctx.send("You don't have permission to use this command.")
        return

    if not os.path.exists(KEY_FILE):
        await ctx.send("Key file does not exist.")
        return

    with open(KEY_FILE, 'r') as file:
        keys = [key.strip() for key in file.read().split(',') if key.strip()]

    if not keys:
        await ctx.send("No keys available in the file.")
        return

    guild = botclient.get_guild(GUILD_ID)
    if guild is None:
        await ctx.send("Guild not found.")
        return

    role = guild.get_role(ROLE_ID)
    if role is None:
        await ctx.send("Role not found.")
        return

    users_to_message = [member for member in guild.members if role in member.roles]

    if not users_to_message:
        await ctx.send("No users with the specified role found.")
        return

    keys_sent = 0
    for user, key in zip(users_to_message, keys):
        try:
            await user.send(f"Your key is: {key}")
            print(f">> Sent key to {user.name}")
            keys_sent += 1
        except discord.Forbidden:
            print(f">> Cannot send message to {user.name}, DMs are closed.")
            await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
        except Exception as e:
            print(f">> An unexpected error occurred with {user.name}: {e}")
            await ctx.send(f"An unexpected error occurred with {user.name}: {e}")

    if keys_sent > 0:
        remaining_keys = keys[keys_sent:]  # Slice the keys that haven't been sent
        with open(KEY_FILE, 'w') as file:
            file.write(','.join(remaining_keys))

        await ctx.send(f"Sent {keys_sent} keys and updated the key file.")
    else:
        await ctx.send("No keys were sent.")
dry kelp
young dagger
dry kelp
#
  1. Enhanced Functionality
  2. Cleaner Syntax
  3. Object-Oriented Interface

Examples:

import os

if os.path.exists('file.txt'):
    print('File exists')
from pathlib import Path

if Path('file.txt').exists():
    print('File exists')
#

Joining paths example:

import os

full_path = os.path.join('dir', 'subdir', 'file.txt')
from pathlib import Path

full_path = Path('dir') / 'subdir' / 'file.txt'
young dagger
#

Which one is faster in performance?

dry kelp
urban flume
#

i believe it's the same except pathlib is prefered in newer codebase after python 3.6

dry kelp
ivory remnant
dry kelp
ivory remnant
#
403 Forbidden (error code: 50007): Cannot send messages to this user
  File "C:\Users\jeqqy\OneDrive\Desktop\Frostware\frostware.py", line 656, in sendkey
    await user.send(f"Your key is: {key}")
  File "C:\Users\jeqqy\OneDrive\Desktop\Frostware\frostware.py", line 687, in <module>
    botclient.run(bottoken)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
#

@dry kelp

pale zenith
#

error seems pretty clear?

ivory remnant
#

@slate swan i didnt "blindly" paste someone elses code.. i looke dthru it and ensured anything needed to be changed

ivory remnant
#

thats my issues thats what im trying to fix

#

if the dms is closed, it js skips them

#

thats what i implemented but it doesnt seem to want to skip

pale zenith
#

the error seems different, though. Could you copy the whole file and paste it?

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

wispy gulch
#

whats your problem?

sick birch
#

a lot of os/pathlib functions will be bottlenecked by system IO anyway

ivory remnant
#

the rest is unrelated stuff

pale zenith
#

did you save your file and restart your bot? like this should work

ivory remnant
#
KEY_FILE = "keys.txt"
GUILD_ID = 1223160887871934484
ROLE_ID = 1226546057077456966

@botclient.command()
async def sendkey(ctx: commands.Context) -> None:
    bot_owner_id = 849652633261834241  # Replace with the actual bot owner's ID
    
    if ctx.author.id != bot_owner_id:
        await ctx.send("You don't have permission to use this command.")
        return

    if not os.path.exists(KEY_FILE):
        await ctx.send("Key file does not exist.")
        return

    with open(KEY_FILE, 'r') as file:
        keys = [key.strip() for key in file.read().split(',') if key.strip()]

    if not keys:
        await ctx.send("No keys available in the file.")
        return

    guild = botclient.get_guild(GUILD_ID)
    if guild is None:
        await ctx.send("Guild not found.")
        return

    role = guild.get_role(ROLE_ID)
    if role is None:
        await ctx.send("Role not found.")
        return

    users_to_message = [member for member in guild.members if role in member.roles]

    if not users_to_message:
        await ctx.send("No users with the specified role found.")
        return

    keys_sent = 0
    for user, key in zip(users_to_message, keys):
        try:
            await user.send(f"Your key is: {key}")
            print(f">> Sent key to {user.name}")
            keys_sent += 1
        except discord.Forbidden:
            print(f">> Cannot send message to {user.name}, DMs are closed.")
            await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
        except Exception as e:
            print(f">> An unexpected error occurred with {user.name}: {e}")
            await ctx.send(f"An unexpected error occurred with {user.name}: {e}")

    if keys_sent > 0:
        remaining_keys = keys[keys_sent:]  # Slice the keys that haven't been sent
        with open(KEY_FILE, 'w') as file:
            file.write(','.join(remaining_keys))

        await ctx.send(f"Sent {keys_sent} keys and updated the key file.")
    else:
        await ctx.send("No keys were sent.")```
ivory remnant
pale zenith
#

since this error is referencing bot.run(), this doesn't seem quite related with

#

-oh are you using like the actual debugger? don't

ivory remnant
#

b4 anything else

#

cuz if i try to run a python file and theres a error it js closes

pale zenith
#

could you try without it? just open a console (even the vscode console) and just python YOUR_FILE_NAME.py or python3 or whatever you use

#

ya you don't just rawdog a python file like that, run it via a terminal instead of just double-clicking it

fast osprey
#

Not with that attitude

pale zenith
pale zenith
#

anyway, if running the code in a more conventional way does not fix the issue, send the most recent error here and we'll see

ivory remnant
#

i did it in vsc terminal and it works just fine now

pale zenith
#

yea figures. I don't trust them debuggers- if I had to guess it just "forgot" to notice the file was saved, or something like that

#

yep the vscode terminal works fine like any other! for future reference, avoid using the debugger for discord.py-related code as it usually leads to such errors :)

#

I would go as far as to say not to use it for any code (but I'm just not a fan of it, usually gives me more headaches than it's worth)

#

glad it was fixed tho

ivory remnant
#

wait @pale zenith how do i stop debugging?

pale zenith
young dagger
#

Which python version is recommend to use right now?

zinc gust
#

always download the last one

young dagger
wanton current
#

if only it said somewhere

zinc gust
#

then 12

zinc gust
young dagger
#

Do I always have to fetch the user to see if they are a member of the guild?

wanton current
#

no?

mild token
#

Can I run fastapi and my bot in same script? I want to implement pubsub model

fast osprey
#

You can, you shouldn't

mild token
#

I am checking api continuosly for changes and wanted to implement pubsub model

fast osprey
#

What is the webserver doing?

mild token
#

And just fire it up when there it updates instantly

young dagger
#
# task.py
import discord
from discord.ext import commands
import asyncio

guild_access_lock = asyncio.Lock()```
#
# events.py
import discord
from discord.ext import commands
from task import guild_access_lock

class EventsCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def another_command(self, ctx):
        async with guild_access_lock:
#

Why isn't this working?

midnight oracle
#

Are the files in the same forlder?

fast osprey
young dagger
young dagger
#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: ModuleNotFoundError: No module named 'tasks'

mild token
fast osprey
#

What does this notification function do?

mild token
fast osprey
#

You don't need a bot to do that at all, you can just post to a webhook

mild token
#

I have to track around 30-40 channel

fast osprey
#

webhooks are how you post from some arbitrary program into a discord message

mild token
young dagger
#

with (dot) in the beginning

midnight oracle
young dagger
#

Why is the dot necessary?

fast osprey
#

It's relative to your cwd

midnight oracle
#

You can use more than one dot to refer to the parent(s)

fair herald
#

PS C:\Users\luffy\Downloads\pycord why> python bot.py
Bot is online as invade#9123
C:\Users\luffy\Downloads\pycord why\.venv\Lib\site-packages\discord\cog.py:796: RuntimeWarning: coroutine 'setup' was never awaited
  setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog help.py: object list can't be used in 'await' exp```
#

@young dagger

crude remnant
#

test ignore

fast osprey
#

Code?

fair herald
#
C:\Users\luffy\Downloads\pycord why\.venv\Lib\site-packages\discord\cog.py:796: RuntimeWarning: coroutine 'setup' was never awaited
  setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "C:\Users\luffy\Downloads\pycord why\bot.py", line 19, in <module>
    bot.loop.run_until_complete(load_cogs())
  File "C:\Users\luffy\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 687, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\luffy\Downloads\pycord why\bot.py", line 10, in load_cogs
    await bot.load_extension('cogs.help')  # Ensure the path is correct
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: object list can't be used in 'await' expression
PS C:\Users\luffy\Downloads\pycord why> ```
#

@fast osprey

fast osprey
#

Code?

fair herald
fast osprey
#

both ideally

#

at least the extension

fair herald
merry cliff
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

fair herald
#

alr

#

@fast osprey@merry cliff

merry cliff
#

Is help.py in the same directory as the main file

fair herald
#

no

merry cliff
#

That’s interesting

fast osprey
#

What library and version are you using?

merry cliff
#

Looks like pycord perhaps

#

I think pycord has a load_extensions thing

stark ingot
#

And then do not await load_extension

fair herald
# stark ingot My guess is that you have both py-cord and discord.py installed If you are plann...

it work but i have another problem


PS C:\Users\luffy\Downloads\pycord why> python bot.py
Traceback (most recent call last):
  File "C:\Users\luffy\Downloads\pycord why\bot.py", line 70, in <module>
    @bot.command()
     ^^^^^^^^^^^^^
  File "C:\Users\luffy\Downloads\pycord why\.venv\Lib\site-packages\discord\ext\commands\core.py", line 1430, in decorator
    self.add_command(result)
  File "C:\Users\luffy\Downloads\pycord why\.venv\Lib\site-packages\discord\ext\commands\core.py", line 1283, in add_command
    raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
PS C:\Users\luffy\Downloads\pycord why> ```
#

@stark ingot

meager rock
# fair herald it work but i have another problem ```python PS C:\Users\luffy\Downloads\pycor...

you (can, but) should not be writing a help command this way. override the default help command by subclassing commands.HelpCommand and passing it into your Bot constructor. https://docs.pycord.dev/en/stable/ext/commands/api.html#ext-commands-help-command

charred estuary
#

excuse me sir i get certificate verification error when i run python file on windows server using library nextcord
and I have installed certifi using pip install certifi
how do i solve this problem?
the error like this

charred estuary
cobalt crane
#

also make sure your system clock is correct

charred estuary
cobalt crane
#

you're running it inside a VM right?

charred estuary
cobalt crane
#

have you tried running it locally to see if it works? might be an issue with where it's hosted

charred estuary
cobalt crane
#

do you use ssl in your project?

charred estuary
charred estuary
charred estuary
cobalt crane
#

try adding this to your code

import certifi
import os
from discord.ext import commands
os.environ["SSL_CERT_FILE"] = certifi.where()
charred estuary
cobalt crane
#

in your python file

charred estuary
charred estuary
cobalt crane
#

no worries! glad you got it sorted 😊

charred estuary
#

hah??

slate swan
#

Not sure how sending irrelevant memes is related to this channel

west escarp
#

!charinfo ᲼᲼᲼᲼᲼᲼

#

@dim pond please don't post giant blocks of characters like that, thanks

signal lion
#

anyone here familiar w discord api please dm me

feral timber
#

If you have a question you can ask it here

signal lion
#

okkk

#

so basically ive only been coding for about 2 months and i tried making a discord username changer, you enter your token and the desired name and it changes the username to it, but for some reason i cant get this to work

fast osprey
#

That is against TOS

signal lion
#

how

#

i dont use automation i enter everything manually

fast osprey
#

Writing any automation that asks for or uses user tokens

signal lion
#

oh

#

my bad

#

can i use a bot token to change my username ?

fast osprey
#

No

#

Not your global one. A bot can change server-level nicknames

young dagger
#

Is there any better way to do this?

def contains_repeated_content(message_content):
    normalized_content = re.sub(r'\s+', ' ', message_content).strip()

    pattern = re.compile(r'(.+?)\s+\1{1,}', re.IGNORECASE)
    return bool(pattern.search(normalized_content))
fair herald
fast osprey
#

!hosting

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

young dagger
zinc gust
fast osprey
#

🤨

young dagger
zinc gust
#

im using a known one

#

called pylexnodes

#

100% free

fast osprey
#

And how are they making money to maintain their servers?

young dagger
#

No such thing as a free lunch

quick gust
fast osprey
#

To...whom? The one person who goes on the site once to register and run their shit?

quick gust
#

Yeah apparently on the "free panel" they have

fast osprey
#

Yeeeeah that doesn't remotely add up lol

quick gust
#

Uhuh also probably not enough to sustain the servers they're using

#

I wonder why people start free hosting sites and if it's actually profitable in any ethical way

sullen crest
#

does anyone know how a discord bot can read a previous message?

fast osprey
#

Depends, how are you picking which message you want?

sullen crest
#

Wait can you choose a person’s last message sent?

fast osprey
#

There's not a short way to do that. You can search over a channel's history, and then filter based on that

sullen crest
#

For the former or latter?

fast osprey
#

Both

#

I mean you can't say "what was the last message this person sent ever", because your bot can't see every message a person sends

sullen crest
#

fair enough, is the former doable?

fast osprey
#

yeah

sullen crest
fast osprey
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.

Examples

Usage...
sullen crest
#

ah must've missed it ty!

devout willow
#

Hello, I am here for Pycord API

scarlet tiger
devout willow
#

I might, I am just gauging the server 😊

scarlet tiger
devout willow
scarlet tiger
fast osprey
#

It's been under active development again for years

mint pecan
#

is it possible to get the context inside a FlagConverter's subclass?

merry cliff
#

show code maybe you can pass it in

timber dragon
#

What do you need it for?

zinc lichen
#

Can anyone tell me why is the embed not coming

@bot.command(aliases = ["CF"])
@commands.cooldown(rate=1, per=10, type=commands.BucketType.user)
async def cf(ctx, amt: int):
    await open_account(ctx.author)
    users = await get_bank_data()
    
    possibility = ["head", "tail"]
    user_choice = random.choice(possibility)
    bot_choice = random.choice(possibility)
    
    if amt == None:
        await ctx.send("Enter a amount to bet")
    
    elif amt <= 0:
        await ctx.send("Must be at least one")
    elif amt > users[str(ctx.author.id)]["Wallet"]:
        await ctx.send("You don't have enough money in your Wallet")
    else:    
        users[str(ctx.author.id)]["Wallet"] -= amt
            
        if user_choice == bot_choice:
            amt = amt*2
            users[str(ctx.author.id)]["Wallet"] += amt
                
            em = discord.Embed(
            title=f"Coin Flip",
            description=f"Your choice **{user_choice}**, after filling the coin **{bot_choice}**. You won {amt}",
            color=discord.Color.blue
            )
                
            await ctx.send(embed = em)
            await save_data_bank(users)
        else:
            em = discord.Embed(
            title=f"Coin Flip",
            description=f"Your choice **{user_choice}**, after filling the coin **{bot_choice}**. You lost {amt}.", 
            color=discord.Color.blue
            )
            
            await ctx.send(embed = em)
            await save_data_bank(users)
                
@cf.error
async def cf_error(ctx, error):
    if isinstance(error, commands.errors.BadArgument):
        await ctx.send("Please choose a number")
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f"Command is on cooldown! Try again in {error.retry_after:.0f} seconds.")
fast osprey
#

What does happen?

zinc lichen
#

I don't even get an error

fast osprey
#

And what happens in your error handler if you hit an error that isn't those two specific types?

zinc lichen
#

I get error

fast osprey
#

Nope

zinc lichen
#

😐

fast osprey
#

If you pass through those two if clauses, you do nothing

#

(error handlers should be exhaustive and always have a fallback where you do something)

zinc lichen
#

Ohhhhhhh

#

Got it thanks

fast osprey
#

IMO, completely independently of any user feedback you should always be logging the errors somewhere you can see them

zinc lichen
#

Now a type error came

#

Screw it I got the error

#

Thank btw

fast osprey
#

any time

ivory remnant
#

i have been seeing this for a while now and i dont see much going around explaining how it works? allowing bots to join servers for you, can someone provide a example on how its done?

fast osprey
#

It is an oauth scope your bot can request from users

ivory remnant
mint pecan
hushed galleon
stark ingot
hushed galleon
#

i think hikari can handle the oauth2 flow if you combine their methods with a webserver, citation needed

young dagger
#

Is there any benefit to using match-case instead of elif statements when it comes to performance?

low reef
#

Hey guys, would someone be able to tell me exactly what i need to change to get my welcome image feature to work? For context I'm a beginner coder following this video: https://www.youtube.com/watch?v=Eu7X2SUOpaI&t=1030s&ab_channel=Paradoxial , the code doesnt give me any errors but when people join the server no welcome message is sent. Ive spent wayyy too many hours trying to fix. The developer intents are checked, the system message is on the correct one. And I have other cogs that run just fine so I doubt its the file structure or it not loading properly from the main.py. the code in question: https://paste.pythondiscord.com/HYWA the first section is the main.py the 2nd section is the actual welcome message cog. If someone would be able to tell me exactly what i need to change or maybe hop in a discord call for 2 minutes to get it fixed i would much appreciate 🙏

Hey guys, today we use a specific version of Pillow in Python to create ourselves some unique and professional looking welcome image cards for new members who join the server! Subscribe! :)

MY DISCORD: https://discord.gg/UqdbGp426a

MY GITHUB: https://github.com/Paradoxial8172

MY WEBSITE: http://houseofcode.xyz/index.html

DONATE: https://payp...

▶ Play video
fast osprey
#

Some debugging would be a good first step

#

even as simple as just prints to see if the code you think is problematic is running at all

low reef
#

how would i go about doin that?

fast osprey
#

Writing print statements?

low reef
#

setting up the debugging

fast osprey
#

I can also tell you from watching about 15 seconds of this video that it recommends some pretty horrid practices

#

in general these video "tutorials" are very poor quality

fast osprey
#
@commands.Cog.listener()
async def some_event(...):
  logic1()
  logic2()
  logic3()
  ...

With this code, it is completely indistinguishable between this event never running at all, vs any of these individually silently failing. You're going in blind.

@commands.Cog.listener()
async def some_event(...):
  print("the event fired")
  logic1()
  print("i did logic 1")
  logic2()
  print('i did logic 2")
  ...

This actually gives you some insight into what is happening. It's rudimentary, but you don't necessarily need something fancy for your own purposes that isn't meant for end users

low reef
quaint obsidian
#
import cogs.ext.utils.utils as utils

def isEmbedEph(embed: discord.Embed, eph: str) -> bool:
    return embed is not None and utils.configManager.isActivePlaceholder(eph) and eph in embed.title

error

name 'utils' is not defined
#

like what?

low reef
rose narwhal
#

the button doesn't work after bot restart,
My code:

@app_commands.command(name="ticketmenu", description="Sends ticket menu")
    @app_commands.checks.has_permissions(administrator=True)
    async def ticketmenu(self, interaction, channel: discord.TextChannel):
        ticketbutton = ui.Button(label="Open Ticket",
                                style=discord.ButtonStyle.primary,
                                custom_id="ticketbutton",
                                emoji="📩")
        embed = discord.Embed(title="Tickets",
                            description="**Open a ticket only if you need support!**\n**Opening tickets without a reason can get you __punished__!**\n**Make sure your issue is only related to CoffeeNetwork**\n**Please use correct category for your ticket**",
                            color=discord.Color.green())
        embed.set_thumbnail(url=interaction.guild.icon.url)
        class Pview(ui.View):
            def __init__(self):
                 super().__init__(timeout=None)
            
            @ui.button(label="Open Ticket", style=discord.ButtonStyle.primary, custom_id='pticketbutton')
            async def TicketsButton(self, interaction: discord.Interaction, button: ui.Button):
                 await interaction.response.send_message('test')

        
        view = Pview()
        self.bot.add_view(view)
        view.add_item(ticketbutton)
        # ticketbutton.callback = self.ticket_callback
        await channel.send(embed=embed, view=view)
        
        await interaction.response.send_message(f"**✅ Ticket panel has been sent to {channel.mention}**")```
fast osprey
low reef
#

nope not seein any errors

fast osprey
# rose narwhal the button doesn't work after bot restart, My code: ```py @app_commands.command(...

A few things about this code:

  • You don't need to declare the view class every time this function runs. You can declare it outside at the top level of your module just once.
  • You should probably be using @app_commands.default_permissions rather than a local @app_commands.check
  • If you want things to continue working after restart, check the persistent.py example in the repo (assuming you're using discord.py). It gives you two approaches for doing this
fast osprey
rose narwhal
fast osprey
#

You need to call add_view when the bot restarts

#

not when someone runs the command again

#

Notice in the example how they use it

low reef
rose narwhal
#

hmm, so outside the command declaration right

fast osprey
#

At some point during your startup process most likely

#

Yeah you're disabling logging

fast osprey
low reef
fast osprey
#

Alternatively you could setup logging manually. But a lot of these tutorials go through this asyncio.run setup pointlessly without really realizing why

rose narwhal
#

tysm solstice

fast osprey
#

For one off debugging where attaching debuggers fries your bot, it's fine

mild token
#

i want to send new video publish link when some register streamer release video

#

how can i do that

dry kelp
#
def create_board_embed(
    message: disnake.Message, board_name: str, color: disnake.Color, _: int
) -> tuple[disnake.Embed, list[disnake.ui.Button]]:
    """Create an embed dynamically for the board message based on the message content."""
    embed = disnake.Embed(title=f"{board_name.capitalize()} Message", color=color)
    embed.set_author(name=message.author.display_name, icon_url=message.author.display_avatar.url)

    description = message.content or ""

    if (
        message.reference
        and message.reference.resolved
        and not isinstance(message.reference.resolved, disnake.DeletedReferencedMessage)
    ):
        reply_message = message.reference.resolved
        description = (
            f"**Replying to [{reply_message.author.display_name}]"
            f"({reply_message.jump_url})**\n\n{description}"
        )

    embed.description = description

    if message.attachments:
        attachment = message.attachments[0]
        if attachment.url.endswith((".png", ".jpg", ".jpeg", ".gif")):
            embed.set_image(url=attachment.url)

    buttons = [url_button(label="Jump to Message", url=message.jump_url)]
    return embed, buttons

Why does the attachment issue, not uploading it as embed image

#

nvm found a fix.

topaz lodge
#

Can anyone tell me when I can find some non outdated tutorials im new to discord bot development and need some guidance to get started

stark ingot
topaz lodge
stark ingot
#

Discord and discord.ext are what you import not the library that you pip install

topaz lodge
#

Ye thats what I use

rocky tree
merry cliff
topaz lodge
merry cliff
#

Oh lmao

rocky tree
merry cliff
#

There are also some examples in the discord.py github

topaz lodge
#

I will read through the documentation tomorrow when I can get on my pc

trim moon
#

Hi!
I have just made a Discord bot with python, and got it hosted on my raspberry pi. How do I publish it?

hushed prawn
#

hello I come to you I need help or an explanation I have a bot in py that uses the discord buttons but when the bot restarts the old button no longer works which is a problem for me since it works with the gateway session id the id changes with each restart do you have a solution to save all the buttons automatically in a json or other if possible I would like to know how to do it because I am lost

stark ingot
trim moon
stark ingot
trim moon
rocky tree
rocky tree
hushed prawn
hushed prawn
rocky tree
#

?

hushed prawn
hushed prawn
rocky tree
#

i didnt even

stark ingot
#

It depends on your usecase

rocky tree
#

okee

hushed prawn
# stark ingot It depends on your usecase

well in fact there is an embed we fill it after it sends the information in a room with a button on it in order to react if the bot restarts the button no longer works which blocks my project

#

in the big lines

stark ingot
#

When you press the button what needs to be done?

#

even better can you show your button callback

hushed prawn
#

well once you press the button the bot sends a message in dm if the bot restarts the getwey changes so the button does not follow

stark ingot
stark ingot
trim moon
stark ingot
#

Yeah, this goes more in depth

severe vault
#

Can someone tell me wheres the main chat?

stark ingot
#

for python, help, or off topic discussion?

severe vault
#

About Programing chat?

stark ingot
#

the first one then

hushed prawn
stark ingot
#

If i understand what you mean you should just be able to add custom_id = "The_Custom_ID_For_This_Button" to your button decorator

hushed prawn
#

I don't need to make a json that keeps everything? because it currently works but if the bot restarts then the getwey also changes since a connection an id that's the problem

stark ingot
#

You only need to keep track of the custom_ids whenyou are storing information in the view object that cannot be retrieved from the interaction

#

I have to go for a while and will be unable to help until I am back

hushed prawn
#

@stark ingot

from discord.ext import commands
import json
import os

bot = commands.Bot(command_prefix="!")

# Fichier de stockage pour les boutons
BUTTON_DATA_FILE = "button_data.json"

# Fonction pour charger les données des boutons
def load_button_data():
    if os.path.exists(BUTTON_DATA_FILE):
        with open(BUTTON_DATA_FILE, "r") as f:
            return json.load(f)
    return {}

# Fonction pour sauvegarder les données des boutons
def save_button_data(data):
    with open(BUTTON_DATA_FILE, "w") as f:
        json.dump(data, f)

# Classe pour créer les boutons
class PersistentView(discord.ui.View):
    def __init__(self, message_id):
        super().__init__(timeout=None)
        self.message_id = message_id

    @discord.ui.button(label="Bouton 1", custom_id="static_button_1")
    async def button_1(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("Tu as cliqué sur le Bouton 1")

    @discord.ui.button(label="Bouton 2", custom_id="static_button_2")
    async def button_2(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("Tu as cliqué sur le Bouton 2")

# Commande pour créer des boutons et sauvegarder l'ID du message
@bot.command()
async def create_buttons(ctx):
    view = PersistentView(None)
    message = await ctx.send("Clique sur un bouton :", view=view)
    
    # Sauvegarde l'ID du message et les boutons
    button_data = load_button_data()
    button_data[str(message.id)] = {"message_id": message.id}
    save_button_data(button_data)

# Lorsque le bot démarre, recharge les boutons pour les messages existants
@bot.event
async def on_ready():
    print(f"Bot connecté en tant que {bot.user}")
    
    # Récupère les données des boutons sauvegardés
    button_data = load_button_data()
    
    # Recrée les boutons pour chaque message sauvegardé
    for message_id, data in button_data.items():
        channel = bot.get_channel(123456789012345678)  # Remplace par ton ID de salon
        message = await channel.fetch_message(int(message_id))
        view = PersistentView(message_id)
        await message.edit(view=view)

# Lancer le bot
bot.run("YOUR_TOKEN")
```I asked the question to chat gpt basically should I take inspiration from that?
merry cliff
#

have you tried using dynamic items instead? that way you dn't have t keep track of every button you send

hushed prawn
merry cliff
#

huh

#

look at the dynamic item section

hushed prawn
#

that it is better to store everything or the dynamic because the problem is getwey if the bot restarts that the ids do not follow

merry cliff
#

then you don't need to store it anywhere and just do py bot.add_dynamic_items(you_dynamic_item)

#

the id will follow

#

because dynamic items store their data USING the id

hushed prawn
#

yes but the id with Gateway (Session ID: it does not follow if? if the bot restarts the id will change so the chain will be lost

fast osprey
#

nothing to do with the session id

#

whenever you send any component, that has a custom id on it. dynamic items put data into that custom id. That stays the same forever on the components on that message unless you edit it yourself

hushed prawn
#

I will try I just have to add the list no need for anything else?

merry cliff
#

what list

hushed prawn
#

?

merry cliff
hushed prawn
fast osprey
#

json is not a storage solution

hushed prawn
young dagger
young dagger
dry kelp
young dagger
dry kelp
#

Are you using discord.py? I don't remember if i previously asked you

young dagger
#

Indeed I am

dry kelp
#

ah yes, sorry just seen the code

fast osprey
#

dynamic items are just another way of registering existing components to work. You don't need, or really want, to do both

hushed prawn
#

import discord
from discord.ext import commands

class AskBtn(discord.ui.View):
def init(self, target: discord.User):
super().init(timeout=None)
self.value = None
self.target = target

    # Dynamically add the button when initializing the View
    self.add_dynamic_button()

def add_dynamic_button(self):
    # Modifier dynamiquement les propriétés du bouton
    button_label = f"Envoyer une demande à {self.target.display_name}"
    button_style = discord.ButtonStyle.green if self.target.bot else discord.ButtonStyle.blurple

    # Ajouter dynamiquement un bouton avec label et style personnalisés
    button = discord.ui.Button(label=button_label, style=button_style)

    # Associer l'action à l'événement de clic du bouton
    button.callback = self.ask_callback

    # Ajouter le bouton à la vue
    self.add_item(button)

async def ask_callback(self, interaction: discord.Interaction):
    # Logique lors de l'appui sur le bouton dynamique
    if isBlacklisted(interaction.user.id):
        await interaction.response.send_message(embed=discord.Embed(
            title="", 
            color=discord.Color.red()).add_field(name="", value="Tu ne peux pas intéragir car tu as été banni(e) du système de MATCH"), ephemeral=True)
        return
    
    if isBlacklisted(self.target.id):
        await interaction.response.send_message(embed=discord.Embed(
            title="", 
            color=discord.Color.red()).add_field(name="", value="Cette personne a été banni(e)."), ephemeral=True)
        return
    
    if not isComplete(interaction.user.id):
        await interaction.response.send_message(embed=discord.Embed(
            title="", 
            color=discord.Color.red()).add_field(name="", value="Tu dois avant tout finir de créer ton profil !"), ephemeral=True)
        return
    
    if self.target == interaction.user:
        await interaction.response.send_message(embed=discord.Embed(
            title="", 
            color=discord.Color.red()).add_field(name="", value="Tu ne peux pas t'envoyer une demande à toi-même !"), ephemeral=True)
        return
    
    # Si toutes les conditions sont bonnes, envoie une réponse positive
    await interaction.response.send_message(embed=discord.Embed(
        title="Demande envoyée", 
        color=discord.Color.green()).add_field(name="", value=f"Ta demande a été envoyée à {self.target.display_name} !"), ephemeral=True)

Commande d'envoi avec bouton dynamique

bot = commands.Bot(command_prefix="!")

@bot.command()
async def envoyer(ctx, member: discord.Member):
view = AskBtn(target=member)
await ctx.send(f"Envoyer une demande à {member.display_name}", view=view)
it's good in dynamics finally you think that it solves the problem

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

hushed prawn
#

sorry

#

if you can tell me if it's like that I asked chat gpt for inspiration to be sure to start correctly

fast osprey
#

This isn't a dynamic item at all

#

you should never be creating a generic Button object and stapling callbacks onto it

hushed prawn
#

I don't understand anything

fast osprey
#

It's probably the right play to read the official docs, then ask targeted questions on what you specifically don't understand

frail yew
#

anyone know how to add mutliple languages to discord bot

fast osprey
#

I think there's a misunderstanding here of what "dynamic" means

#

In the context of persisting/making buttons work after restart, this very specifically refers to buttons/selects that subclass DynamicItem and implement the methods mentioned in the example. Your code does not do that

slate swan
#

python bot = https://paste.pythondiscord.com/raw/YMXA
# notice that in line 94 u can change title and embad color

vocal laurel
#

?

devout willow
mint pecan
#

what is the parameter kind in commands.Parameter? what do i set it to?

golden portal
#

!d inspect.Parameter.kind

unkempt canyonBOT
#

Describes how argument values are bound to the parameter. The possible values are accessible via Parameter (like Parameter.KEYWORD_ONLY), and support comparison and ordering, in the following order:

mint pecan
golden portal
#

commands.param for the shorten one

fast osprey
severe sonnet
#

I need someone who have stripe and a confirmable country for me to confirm my bot, my friend country to confirm payout is not available anymore, and my country, Brazil, is also not available to confirm payout. I need help so my bot can be in more than 100 different servers, please can anyone help?

stark ingot
#

You need to find someone who you can trust. Not someone random. You have to transfer ownership of the bot to them so if it is someone random they can steal the bot

#

That person also needs to trust you because I believe the person who verifies is responsible for any legal actions that occurs

severe sonnet
#

i put all my efforts into this bot

#

but discord don't help

stark ingot
#

Yeah, I'm not sure why some regions are banned. But it would be worse if someone deleted your bot.

topaz lodge
#

why do i get an error when im importing dotenv

#

@stark ingot you should know

#

can u help?

sage crown
austere night
topaz lodge
#

ye

sage crown
#

I mean like python virtual environment

topaz lodge
#

how do i check

austere night
#

open env and the /lib

#

and what version

sage crown
#

It should say in the corner, but you cut that off the screenshot

sage crown
#

Looks like you don't have a virtual environment selected

#

Show the full output of the pip command you ran?

topaz lodge
#

i have an interpreter if thats what u mean

topaz lodge
#

its a big message where do u want me to put it

#

should i put it in a file and send it here

sage crown
#

The pypi package dotenv is actually a decoy intented to confuse you. You actually want python-dotenv

topaz lodge
#

??

#

do i put that in the code or cmd

sage crown
topaz lodge
#

ye?

sage crown
#

Nothing that old will work anymore

topaz lodge
#

i already did it in cmd

sage crown
topaz lodge
#

thats the one i used

sage crown
sage crown
topaz lodge
sage crown
topaz lodge
#

It just says this:
pip install python-dotenv
Requirement already satisfied: python-dotenv in c:\users\Admin\appdata\local\programs\python\python311\lib\site-packages (1.0.1)

sage crown
topaz lodge
#

huh?

sage crown
#

You're using 3.12 in your project

#

And you installed it into 3.11

topaz lodge
#

oh?

#

how do i change/fix it

sage crown
#

You need to see what interpreter Vscode is using

#

If you use Ctrl + Shift + P and select interpreter it should show you which one you picked

#

You're better off creating a .venv virtual environment in your workspace folder though

topaz lodge
#

already selected

#

@sage crown

sage crown
#

Yeah so hit + create virtual environment

topaz lodge
#

@sage crown

sage crown
#

Hit show logs

topaz lodge
#

too late its loaded

#

its giving everything errors now -_-

prime dove
#

Maybe you have to pip install them again

sage crown
#

Now you need to install the deps into the created virtual environment

sage crown
#

If you open a terminal in vscode it should activate it for you

topaz lodge
#

ok

#

done nothing happened

prime dove
#

Meaning you still get those errors?

sage crown
#

Show the terminal?

topaz lodge
sage crown
#

@topaz lodge ^

topaz lodge
sage crown
#

What do you get when you run where python?

topaz lodge
sage crown
#

Hmm nothing?

#

What happens if you run the script? It should print the python version to the terminal as well

topaz lodge
#

hold on

#

i still have the imports underlined but it works?

prime dove
#

Could be a problem with the linter since you installed them in a venv, not sure tho

sage crown
#

@topaz lodge ^

silent portal
#

for role.position, do I need to adjust the position for all roles? Cuz I have a "key-role" and I want to create a new one and set it over the "key-role".

I just got like role.edit(position=ey_role.position + 1)

#

and that doesn't quite work, the position is still at the bottom

#

when the role is newly created

#

and the bot role is on top of every role so it's not a permissions-issue

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @last granite until <t:1726598536:f> (9 minutes and 59 seconds) (reason: duplicates spam - sent 4 duplicate messages).

The <@&831776746206265384> have been alerted for review.

pale turtle
viscid hornet
pale turtle
#

Long time ago when I tried discord.py, it didn't have a lot of features that other versions have. Does discord.py do everything that pycord can?

pale turtle
#

Alright. Is there some guide for starting and coding discord.py? Not just the docs

slate swan
#

No

#

Pycord is superior. Discord.py doesn’t let you record audio from voice channels.

#

AI GPT Calling is the future, thus pycord is the future

slate swan
#

Take inspiration from GitHub projects

fast osprey
#

chatgpt will tell you 3 isn't a prime number

#

what are you on about

#

Also audio receive isn't even supported by discord. It's also rife for privacy concerns, I have yet to see someone implement this legally and ethically

glad cradle
#

"legally" and "ethically", how?

it's not even documented so it's not supposed to be implemented at all

#

it's impossible to solve privacy concerns from a library perspective, IMO discord should do something about it: document the feature and enforce a new priviledged Intent or permission, and inform users with a prompt that it's being registered / listened by a Bot

fast osprey
#

In theory a bot could implement that opt in, plus protection of data privacy rights. I have yet to see someone even care about doing that though

#

But either way, weird criterion to pick a library on whether or not they support something the system itself doesn't even support

glad cradle
#

shouldn't a Bot like that be banned if discovered by discord, even though it protects the privacy of the users etc... it's still not supposed to be done

fast osprey
#

Discord refuses to ban things that are far more egregiously against law/tos

glad cradle
#

like? that's surprising

fast osprey
#

Mee6 continues to exist besides literally scamming people, violating gdpr, you name it

glad cradle
#

So in theory, me as a user could make a lawsuit to both mee6 team and discord

fast osprey
#

Yeah sure

#

I have an open gdpr complaint between carlbot and discord

glad cradle
#

not that i have the money kek

glad cradle
fast osprey
#

No, they refused to respond to me so it is with my gdpr officer

glad cradle
#

huh, so did you put real money for that?

#

that's crazy

fast osprey
#

no it's free lol

viscid hornet
fast osprey
#

I too can cherry pick screenshots

#

point being not that it is never wrong, but that it is not always right and very confident about it

stark ingot
#

The guide also has content for 2.x versions.
Note we do have a bug on our docs website that says that the docs are for version 0.1 but it is actually the latest version. Just a bug in the docs code

viscid hornet
fast osprey
#

The example I had was less of a direct question. It gets confused when it has to juggle multiple concepts, and will very confidently assert things that are blatantly wrong

devout willow
#

Could someone show me how to make a slash command option accept attachment upload within Pycord?

    async def new(self, ctx: discord.ApplicationContext, attachment: discord.SlashCommandOptionType.attachment= discord.Option(description="Upload optional attachment", required=False)):
#

I have also tried:

discord.Attachment
#

both end up as string inputs ¯_(ツ)_/¯

devout willow
devout willow
#

an option decorator would be lovely, but that just gets me errors

scarlet tiger
#

I personally use the decorators

#

But you can use the Option object directly in the function parameter

devout willow
#

could you link docs about them?

scarlet tiger
# devout willow could you link docs about them?

https://docs.pycord.dev/en/stable/api/application_commands.html#discord.commands.option

This decorator can take all the parameters of discord.Option() but you have to pass it the name of the function argument as the first argument.

#

As in the example I sent you

devout willow
scarlet tiger
#

You can import from the discord module

from discord import option, ApplicationContext, ...

devout willow
blazing beacon
marble prism
#

I haven't seen you in a while mf

pale turtle
#

Yeah it's been a long long time

marble prism
#

Imagine coming back then immediately trying to make a discord bot again

#

At least learn something new 😭

pale turtle
#

I'm bored honestly

#

I learned way too many things in the time I was gone

dire marlin
#

yo i needed help with a discord bot (sort of)

#

its not exactly a discord bot but a script that automates something within discord and idk where else to ask

need help getting auto captcha working

copper ivy
#

is it worth to make a discord bot in python ?

prime dove
prime dove
prime dove
dire marlin
prime dove
#

Since you said it's not exactly a discord bot

#

Type for you? Send messages through your account without you actually doing it? Yes, that's selfbotting.

dire marlin
#

if so im not using it ;]

prime dove
#

It's not

#

Actually, is that all the code?

dire marlin
prime dove
#

What are you even trying to do? Run slash commands?

dire marlin
#

i just open my discord and run that (allegedly)

dire marlin
#

/fish and you catch a fish and sell it

prime dove
#

Ah, yeah I don't think that counts as selfbotting exactly

dire marlin
#

it works but i need a way to detect the captchas and solve them

prime dove
#

Which captchas are we talking about?

dire marlin
#

never done any complex project before only minor school stuff hence im struggling pretty bad

#

tried a brute force approach and got timed out from fishing for an hour 😭

prime dove
#

Well of course, you'd want to maintain a time gap with each time you run it at least, and with the captcha, you're on your own

dire marlin
prime dove
#

You have to enter it yourself/not brute force it so you don't get the captcha at all, again, I have never used that bot so shrug

dire marlin
#

i worded that badly, the 3 attempts arent timed - you get three tries before a penalty

fast osprey
#

It is against tos to write any automation that utilizes a user token

dire marlin
fast osprey
#

how do you think the discord client communicates with discord

#

there is not a meaningful distinction between automation clicking on the client and automation making calls directly

dire marlin
sick birch
dire marlin
dire marlin
#

okay then how can I detect an image on my screen for an u related project

sick birch
dire marlin
#

tbf didn’t know it wasn’t allowed but mb

stark ingot
#

In general if any sort of game is

  • connected to the internet in any way
  • OR has a leaderboard/point system of some sort.
    It will be breaking a rule from someone. It is also not fun for other people who are playing the game without cheating. Also after you run a script like that there is no fun in the game for you anymore so you will end up quitting anyways.
tired jay
#

guys

#

i have a problem here

#

how to

#

install pyautogui

fast osprey
#

What does that have to do with discord bots

tired jay
#

oh ok ok just nvm

fast osprey
civic blade
#

PS C:\Users\mitro> & C:/Users/mitro/AppData/Local/Microsoft/WindowsApps/python3.11.exe "c:/Users/mitro/Desktop/Novi Bot Novi Pocetak )/main.py"
Traceback (most recent call last):
File "c:\Users\mitro\Desktop\Novi Bot Novi Pocetak )\main.py", line 10, in <module>
from cogs.clear_command import Clear_Command
File "c:\Users\mitro\Desktop\Novi Bot Novi Pocetak )\cogs\clear_command.py", line 5, in <module>
from discord import Option
ImportError: cannot import name 'Option' from 'discord' (C:\Users\mitro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCac he\local-packages\Python311\site-packages\discord_init_.py)

How to fix this

fast osprey
#

What library are you using?

civic blade
stark ingot
#

show your pip list

fast osprey
#

You also installed some discord library at some point

stark ingot
#

Generally you should know tho

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

stark ingot
#

How much code do you have so far?

fast osprey
#

You ultimately will need to pick one discord library, uninstall the rest, and then reinstall that one

stark ingot
#

You have to decided what library you are using or that you want to use because you currently have 5+ installed

#

They break each other if they are installed at the same time

civic blade
#

can I just delete everything and just install python again too my pc and install the discord import

#

so I mean to delete python from pc

fast osprey
#

You could, but you really don't need to

stark ingot
#

Im not sure if deleting python removes packages

fast osprey
#

Throwing the baby out with the bathwater. Just uninstall the packages you don't need

stark ingot
#

It would help if you used a virtual environment like venv so you can sort your packages better.

dry kelp
#

Does anyone know how to remove top.gg color gradient?

zinc lichen
#
@bot.command()
async def buy(ctx, item_id: int, amt: int = 1):
    await open_account(ctx.author)
    users = await get_bank_data()
    user = ctx.author
    
    for item in shop_item:
        id = item["id"]
        name = item["name"]
        price = item["price"]
        id = int(id)
        if item_id == id:
            break
    if item_id > id:
        await ctx.send("There is no item code like that.")
        return
    

    cost = eval("price*amt")
    cost = int(cost)
#
    view = discord.ui.View()
    
    async def Wallet_callback(interaction):
        await interaction.response.defer()
        if users[str(user.id)]["Wallet"] < cost:
            await ctx.send("You don't have that much money.")
        else:
            await ctx.send(f"You have brought {name} {amt}x for ${cost}")
            users[str(interaction.user.id)]["Wallet"] -= cost
            for i, item in enumerate(users(str(interaction.user.id)["Bag"])):
                if item["ID"] == id:
                    users[str(interaction.user.id)]["Bag"][i]["amt"] += amt
                    break
                else:
                    users[str(interaction.user.id)]["Bag"].append({"ID": id, "amt": amt})
                    break
            await save_data_bank(users)
        view.stop()
        
    async def Bank_callback(interaction):
        await interaction.response.defer()
        if users[str(user.id)]["Bank"] < cost:
            await ctx.send("You don't have that much money.")        
        else:
            await ctx.send(f"You have brought {name} {amt}x for ${cost}")
            users[str(interaction.user.id)]["Bank"] -= cost
            for i, item in enumerate(users(str(interaction.user.id)["Bag"])):
                if item["ID"] == id:
                    users[str(interaction.user.id)]["Bag"][i]["amt"] += amt
                    break
                else:
                    users[str(interaction.user.id)]["Bag"].append({"ID": id, "amt": amt})
                    await ctx.send("added")
                    break
            await save_data_bank(users)
        view.stop()
        
    Wallet_button = discord.ui.Button(label='Wallet', style=discord.ButtonStyle.grey)
    Wallet_button.callback = Wallet_callback
    
    Bank_button = discord.ui.Button(label='Bank', style=discord.ButtonStyle.grey)
    Bank_button.callback = Bank_callback
#
view.add_item(Wallet_button)
    view.add_item(Bank_button)
    
    msg = await ctx.send("How would you like to pay?", view=view)
    await view.wait()
    
    await msg.delete()
#

Can anyone tell me what is wrong in this command

dapper cobalt
scarlet tiger
zinc lichen
#

K

zinc lichen
# scarlet tiger Showing only the code does not help, it shows what kind of error or problem you ...

2024-09-19 08:20:15 ERROR discord.ui.view Ignoring exception in view <View timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Bank' emoji=None row=None sku_id=None>
Traceback (most recent call last):
line 430, in _scheduled_task
await item.callback(interaction)
File "<string>", line 335, in Bank_callback
TypeError: string indices must be integers, not 'str'

2024-09-19 08:20:20 ERROR discord.ui.view Ignoring exception in view <View timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Wallet' emoji=None row=None sku_id=None>
Traceback (most recent call last):
line 430, in _scheduled_task
await item.callback(interaction)
File "<string>", line 318, in Wallet_callback
TypeError: string indices must be integers, not 'str'

#

2 error

#

@dapper cobalt ??

dapper cobalt
zinc lichen
dapper cobalt
zinc lichen
#

Oh

dapper cobalt
#

Try printing users[str(user.id)]

zinc lichen
#

{"1229961335287058545": {"Wallet": 10000, "Bank": 9990000, "Bag": []}}

dapper cobalt
zinc lichen
zinc lichen
dapper cobalt
#

In that case, can u screenshot line 335 and 318?

zinc lichen
#

Both are same

dapper cobalt
#

I'm not sure, but you can try replacing it with this:

for item in users(str(interaction.user.id)["Bag"]):
  if item["ID"] == id:
zinc lichen
#

I tried

#

Btw I gotta go

dapper cobalt
#

Hold, i found the problem

#

You replaced [] with ()

#
for item in users[str(interaction.user.id)["Bag"]]:
  if item["ID"] == id:
#

Should work

dapper cobalt
zinc lichen
#

My mistake and I didn't event seen that

#

Btw really really thanks for the help

pale turtle
#

Does anyone have a bot using pycord on github I can take a look at and see how y'all did it? Trying to figure pycord out

vocal laurel
#

These are all examples provided from pycord

pale turtle
#

Yeah but these are single files. I'm trying to see a project that used cogs and stuff

fast osprey
#

Cogs have nothing to do with files

stark ingot
pale turtle
stark ingot
fast osprey
#

IMO these examples that conflate extensions with cogs, and that imply they must be 1:1, are a bit reductive. I strongly suggest reading the docs on these concepts separately and making informed decisions, vs just repeating a pattern

stark ingot
#

I see what you mean but the docs themselves even suggest that they are used one-one most of the time.

#

I also dont know any examples that do not use them one-one, so I cant do much

marble prism
#

Forget about the old news that it got discontinued

#

It's maintained rn

stark ingot
#

Thats not really good advice

marble prism
#

Uh

#

I know Nir is asking about pycord because he's thinking dpy is unmaintained

stark ingot
#

They choose to use pycord there is no point to switching

marble prism
#

I'm not advising a stranger

scarlet tiger
#

I tried both and it's easier to understand (for me)

marble prism
#

There aren't much differences that affect understanding

scarlet tiger
young dagger
#
2024-09-19 11:23:24 ERROR    discord.ui.view Ignoring exception in view <Verific                                                                                                                                                             ationView timeout=None children=1> for item <Button style=<ButtonStyle.secondary                                                                                                                                                             : 2> url=None disabled=False label='Click to Verify' emoji=<PartialEmoji animate                                                                                                                                                             d=False name='check_mark' id=1185706844665159820> row=None sku_id=None>
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/discord/ui/view.py", line 430, i                                                                                                                                                             n _scheduled_task
    await item.callback(interaction)
  File "/cogs/verification.py", line 95, in start_verification
    await interaction.response.send_message(embed=embed, file=file, view=view, e                                                                                                                                                             phemeral=True)
  File "/usr/local/lib/python3.12/site-packages/discord/interactions.py", line 8                                                                                                                                                             55, in send_message
    await adapter.create_interaction_response(
  File "/usr/local/lib/python3.12/site-packages/discord/webhook/async_.py", line                                                                                                                                                              221, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
fast osprey
#

You have to respond within 3 seconds

young dagger
fast osprey
#

Respond within 3 seconds 😂

stark ingot
#

or defer

#

to get up to 15 minutes

fast osprey
#

That itself has to be done within 3 seconds

#

So either there are long running processes before you respond, or your entire bot has something blocking

fast osprey
#

You should not be making generic views and buttons and stapling callbacks onto them

#

Either way this is taking more than 3 seconds and it's on you to debug why

#

(As an aside, static image based captcha is effectively useless. This isn't giving you anything besides pissing off users)

hushed prairie
#

how do i fix this?

stark ingot
#

There is an arrow in the error that is pointing to what is wrong.
: is not a valid character for being in between and object and a method

hushed prairie
#

oh

#

i fixed it

#

showed me another error now

finite salmon
#

Show

hushed prairie
#

nvm i fixed it, thanks anyway Smiley

fast osprey
young dagger
slim bloom
#

skibidi dop dop

fast osprey
#

Beyond the fact that image captchas don't do anything, yes

young dagger
quick gust
#

I think what they mean is, the fact that it's a set of predefined images that will eventually (and commonly) repeat, renders it pretty useless

fast osprey
#

The purpose of captcha is to prevent automatic processes from doing something. Simple static images where you detect a word in it does not accomplish that. These are trivially easy to break

slow hollow
#

My code function in pycharm but not in daki, it’s a database for "mariage"
Why ?

#
    conn = await aiosqlite.connect('database.db')
    try:
        cursor = await conn.cursor()
        # Crée la table proposals avec la colonne timestamp
        await cursor.execute('''
            CREATE TABLE IF NOT EXISTS proposals (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                proposer_id TEXT NOT NULL,
                proposer_name TEXT NOT NULL,
                proposee_id TEXT NOT NULL,
                proposee_name TEXT NOT NULL,
                guild_id TEXT NOT NULL,  -- Ajout du champ guild_id
                status TEXT NOT NULL,
                timestamp DATETIME NOT NULL  -- Ajout de la colonne timestamp
            )
        ''')
        # Crée la table mariage
        await cursor.execute('''
            CREATE TABLE IF NOT EXISTS mariage (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                partner1_id TEXT NOT NULL,
                partner2_id TEXT NOT NULL,
                guild_id TEXT NOT NULL,  -- Ajout du champ guild_id
                date TEXT
            )
        ''')
        await conn.commit()
    finally:
        await conn.close()

# Fonction pour ajouter la colonne timestamp si elle n'existe pas
async def add_timestamp_column():
    conn = await aiosqlite.connect('database.db')
    try:
        cursor = await conn.cursor()
        # Vérifie si la colonne timestamp existe déjà
        await cursor.execute("PRAGMA table_info(proposals);")
        columns = await cursor.fetchall()
        if not any(column[1] == 'timestamp' for column in columns):
            await cursor.execute('ALTER TABLE proposals ADD COLUMN timestamp DATETIME')
            await conn.commit()
    finally:
        await conn.close()```
#
async def recreate_mariage_table():
    conn = await aiosqlite.connect('database.db')
    try:
        cursor = await conn.cursor()
        await cursor.execute('DROP TABLE IF EXISTS mariage')
        await cursor.execute('''
            CREATE TABLE mariage (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                partner1_id TEXT NOT NULL,
                partner2_id TEXT NOT NULL,
                guild_id TEXT NOT NULL,  -- Ajout du champ guild_id
                date TEXT
            )
        ''')
        await conn.commit()
    finally:
        await conn.close()

# Fonction de vérification des tables existantes
async def check_tables():
    conn = await aiosqlite.connect('database.db')
    try:
        cursor = await conn.cursor()
        await cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = await cursor.fetchall()
        print("Tables dans la base de données:", tables)
    finally:
        await conn.close()

# Fonction principale
async def main():
    await create_tables()
    await add_timestamp_column()  # Ajoute la colonne timestamp si nécessaire
    # Si tu veux recréer la table mariage, décommente la ligne suivante
    # await recreate_mariage_table()
    await check_tables()

# Démarrage du script
if __name__ == "__main__":
    asyncio.run(main())```
young dagger
fast osprey
#

You have multiple view types here. You need to be more specific

young dagger
fast osprey
#

What is the exact flow you're following?

young dagger
#

After 60 seconds

fast osprey
#

I mean what do you in discord

#

This "other instance" isn't really well explained

young dagger
#

How are these two connected to the same timeout?

fast osprey
#

What are you doing in discord

#

I still don't know what this "instance" is

young dagger
#

Did you check the code?

fast osprey
#

I did

#

That does not tell me what you're doing in discord

young dagger
#

@discord.ui.button(label="Click to Verify", style=discord.ButtonStyle.secondary, emoji=discord.PartialEmoji(name="check_mark", id=check_mark_emoji_id), custom_id='verification:start')

#

This one sends a message right

fast osprey
#

What are you doing in discord

#

Step by step

young dagger
#

They click on Click to Verify it sends them await interaction.response.send_message(embed=embed, file=file, view=view, ephemeral=True)

#

The view is received from class CaptchaAnswerView

#

There is a timeout super().__init__(timeout=60)

#

On timeout it disabled the buttons
async def on_timeout(self): for item in self.children: if isinstance(item, discord.ui.Button): item.disabled = True

#

When it does, it disable other buttons too

fast osprey
#

Where are these "other buttons"

young dagger
#

You click once and wait 40 seconds, and click again. You are expecting the first one to timeout in 20 seconds, but so does the second one

fast osprey
#

How are they coming to exist

young dagger
fast osprey
#

You're the one saying "other button"

#

You tell me dude

young dagger
fast osprey
#

What actually happens on message 2? Is this all of your code? What you're describing isn't default behavior

#

You can debug this by giving the view instances some kind of uuid if you want and logging that out

young dagger
#

The first one is expected to be time outed (after 60 seconds), not the second one (after 20 seconds)

#

@fast osprey

fast osprey
#

You need to do some debugging here

#

And not just look at the code and guess

#

Is the timeout method being called? Are these the same actual python objects?

young dagger
#

view.message = message

#

Than use it for class CaptchaAnswerView

    async def on_timeout(self):
        for item in self.children:
            item.disabled = True
        if self.message:
            await self.message.edit(view=self)
fast osprey
#

How do you know if that is being called?

young dagger
fast osprey
#

At all

#

This is what debugging is for

zinc gust
#

ou tu l'a deja fait ?

slow hollow
#

J’ai trouver l’erreur, avoir accès aux database sur daki c’est payant

young dagger
fast osprey
#

But it's not actually editing the message

sick birch
fast osprey
#

That would result in an error when they later try to use it, which is probably at least part of the problem

#

if they don't see that error, that's the first thing to fix

sick birch
#

looks like this is the only place it's being used:

        # Edit the original message to disable the buttons
        if self.message:
            await self.message.edit(view=self)
young dagger
sick birch
#

though it is a bit strange that actions taken on one view affects all of them

fast osprey
#

calling .edit on None would cause an error

#

so you're either not calling that, or you're eating the error and you need to fix that

sick birch
#
        # Edit the original message to disable the buttons
        if self.message:
            await self.message.edit(view=self)

i think you need to think about this a bit more. it seems like you slapped it on there because the type checker was complaining at you (and rightfully so) without thinking of why or the consequences

young dagger
sick birch
#

though tbh the way i've always done it is use view.wait() to wait for the view to expire from within the caller rather than handle it in on_timeout

fast osprey
#

And how many timeout methods are firing?

young dagger
fast osprey
#

If they are separate instances, it's not the library

#

and if you've proven that

#

on_timeout fires when that view object times out, which happens x seconds after the last interaction on that object

young dagger
#

The buttons stop working in betweeen

#

For both users

#

When view timeouts for first user, it does that for second user as well

fast osprey
#

Why are there multiple users

#

you were saying you clicked on it

silent portal
#

what is the rate-limit for changing a channel name? I have a loop that runs every minute which changes a channels name and I'm getting rate-limited

fast osprey
#

You should not be doing that

#

discord does not want you rapidly changing channel names

silent portal
#

why not tho

#

it's like showing the stats of the server

fast osprey
#

That's what they decided. Channel names aren't for that

silent portal
#

members, members in VC currently

#

stuff like that

fast osprey
#

they are meant to show the purpose of a channel. Not a placeholder for random data

silent portal
#

damn

#

ok

young dagger
fast osprey
#

None of those prints tell you whether or not it's the same object

sick birch
#

i dont think its officially documented and is subject to change but that's what i've noticed

silent portal
sick birch
#

per channel

silent portal
#

okay

sick birch
#

(i think)

silent portal
#

ty

#

btw keep the grind in satisfactory 🔥

sick birch
#

i see

#

thanks

sick birch
young dagger
#

Sure

fast osprey
#

there is no print, and you just removed the timeout completely?

#

This isn't going to work well if you run code A when you tell us what's happening and then send us code B

young dagger
#

I didn't change the codes behaviour by removing one print

sick birch
#

so let me get this straight:

  • user 1 clicks "Click to verify" button, embed with button gets sent for them (view 1)
  • 20 seconds passes
  • user 2 clicks "Click to verify" button, embed with buttons gets set for them (view 2)
  • 40 seconds passes
  • view 1 times out, causing view 2 to also time out?
fast osprey
#

No, but you remove our ability to check your work

sick birch
fast osprey
#

That just isn't how timeouts work in the library

sick birch
#

something else is going on here

young dagger
#

I have been trying to solve this for 8 hours now FeelsCryMan

sick birch
#

are your interactions still failing when you press the button?

young dagger
sick birch
young dagger
sick birch
#

no, i mean when you click on one of the buttons 1-4, does it work as expected?

young dagger
#

So it's time outing out all instances that are "running"

sick birch
#

and you believe that because your alt account was unable to use the buttons after your main account had allowed it to elapse the timeout?

young dagger
sick birch
#

are you creating them at the same time?

fast osprey
#

Can you put the prints back in, show us that code, and do it with one account

young dagger
sick birch
#

so the 2nd instance pretty much stops responding almost immediately?

young dagger
sick birch
sick birch
sick birch
#

view 1 times out, causing view 2 non responding
5 seconds passes
view 2 times out
how are you making a differentiation between "not responding" and "timing out"?

sick birch
young dagger
#

I know

sick birch
#

so how are you differentiating between not responding and timeout?

#

if the end result is the same?

young dagger
sick birch
#

yes, we asked to show the code with those print statements

fast osprey
#

And we don't know how those prints are behaving. Because you removed them

young dagger
#

Line 87

fast osprey
#

That's not the timeout

young dagger
fast osprey
#

No

#

timing out is not the only way views finish

young dagger
sick birch
#

you need to check that the wait method returned True

young dagger
#

So I assume it's from the timeout

fast osprey
#

You shouldn't assume

#

you should log from the timeout

#

More logs don't cost you anything

sick birch
#

also if you could attach timestamps that would be useful

#

maybe look into actual logging later

young dagger
#

@fast osprey @sick birch Tried to click on one of the four buttons in between red

fast osprey
#

So clearly they aren't timing out at the same time

young dagger
#

No but why does the second instance stops working?

fast osprey
#

Because it timed out?

young dagger
#

Marked in red

fast osprey
#

Views time out if they have not been interacted with for the duration of the timeout

sick birch
#

ok so they are timing out individually

fast osprey
#

nothing else causes that

sick birch
# young dagger

can you do the same thing like this but add a timestamp for when a user presses a button:

class CaptchaAnswerButton(discord.ui.Button):
    ...
    async def callback(self, interaction: discord.Interaction):
        print(f"[{discord.utils.utcnow().strftime("%Y-%m-%d %H:%M:%S")}] User pressed button {self.label}")

fast osprey
#

It's also not entirely clear that this label is unique

young dagger
sick birch
#

really? and the print is the first line?

young dagger
#

You said the exact same thing right? Open 2 instances and wait for the first one to time out

sick birch
#

no, click on it before it times out

young dagger
sick birch
#

if the 2nd one responds fine even if the first one is timed out then your views are working as intended

young dagger
sick birch
#

can you give a step by step of what exactly you did on discord

young dagger
#

After that View 2 timed out as well

#

Same as before

sick birch
#

so the callback is not being called even though the view is not timed out

young dagger
sick birch
#

try removing the custom_id argument in CaptchaAnswerButton's super initializer

sick birch
#

are you using add_view anywhere?

fast osprey
#

It does

young dagger
sick birch
#

comment it out for now

young dagger
sick birch
#

is the button you're trying to click from earlier, before a restart?

sick birch
#

just send a new one

young dagger
young dagger
# sick birch just send a new one

I added time.time() for the custom ID for the CaptchaAnswerButton and it solved the issue

class CaptchaAnswerButton(discord.ui.Button):
def init(self, label: str, correct_answer: str):
super().init(label=label, style=discord.ButtonStyle.secondary, custom_id=f'captcha:{label}:{time.time()}')

sick birch
#

that makes sense

#

it probably wants a unique button ID

#

though i'm not sure why discord.py isn't generating one for you

young dagger
sick birch
#

maybe a UUID

young dagger
young dagger
# sick birch maybe a UUID

Should be enough?

        self.unique_id = str(uuid.uuid4())
        super().__init__(label=label, style=discord.ButtonStyle.secondary, custom_id=f'captcha:{label}:{time.time()}:{self.unique_id}')
young dagger
#

Thanks Robin prayge

hard jay
#

Hello

#

I am trying to make a transcript for my discord ticket bot, so it can record the messages and any info inside the channel

#

But i keep failing

#

Can someone help me?

fast osprey
#

Are the users consenting to having their messages recorded, and are you giving them a mechanism to ask for their data to be deleted?

hard jay
fast osprey
#

Not really the answer of someone who has thought about those things, which is in the TOS

hard jay
#

Also i made the transcript to be saved but when i go to view it, it's with a white background with no colours nor logos

fast osprey
#

Right, and if you take messages that users sent and put them somewhere else, that needs to be communicated in your privacy policy and you need to give them a way to request you to delete it.

Alternatively, leave the messages as-is in an archived discord thread where their privacy rights are maintained

hard jay