#discord-bots

1 messages Β· Page 352 of 1

west shuttle
#

Members spamming button

viscid hornet
viscid hornet
#

it's a yes or no quesiton

west shuttle
west shuttle
viscid hornet
west shuttle
viscid hornet
fathom tree
#

any stratus on user installed commands ?
maybe not in the stable branch but some other version (py-cord)

west shuttle
viscid hornet
#

or the person that ran the command

west shuttle
viscid hornet
west shuttle
#

can i do it for certain user?

viscid hornet
#

compare IDs or pass through the view __init__

red stratus
#

I've created a Discord Modals bot that allows Discord users to fill out information in a Modals form. When users click on a designated button, the bot displays the Modals. However, when I don't submit any information and leave it for about 6 minutes, and I or others click the button again, it shows a 'Not Responding' alert. I want it to be always available. Whenever someone clicks on the designated button, the bot should always display the Modals to the user. (Can anyone help me?)

west shuttle
#

OHHH let me try that

viscid hornet
#

(i recommend the view __init__)

viscid hornet
#

why not just run the command again?

red stratus
# viscid hornet why not just run the command again?

I've seen someone do this before, but I have no idea how they did it. They made the bot send an embed message to a text channel with a button at the bottom. No matter how long it's been, even months later, whenever someone clicks the button, the bot always displays the Modals to the user without sending any messages or restarting the bot every 15 minutes. I'm wondering if there's a way to do this

viscid hornet
red stratus
# viscid hornet probably needs a persistent view

I understand that restarting the bot will make the button work (the button that displays modals), but I don't want to do it this way. I want the button to be always ready to work. Please tell me or give me some ideas

pale zenith
viscid hornet
red stratus
hushed galleon
hushed galleon
hushed galleon
#

!d discord.ForumChannel

unkempt canyonBOT
#

class discord.ForumChannel```
Represents a Discord guild forum channel.

New in version 2.0.

x == y Checks if two forums are equal.

x != y Checks if two forums are not equal.

hash(x) Returns the forum’s hash.

str(x) Returns the forum’s name.
viscid hornet
#

πŸ”₯

viscid hornet
#

i want it to say Today at X:XXxx

#

where xx is am or pm and X:XX is a 12h format

hushed galleon
#

it depends on the user's locale, e.g. en-GB would show 24h while en-US shows 12h

#

assuming you're using Embed.timestamp or discord.utils.format_dt()

viscid hornet
#

does .format_dt() even work for this?

hushed galleon
#

oh for the former you can only pass a datetime

#

format_dt() should format correctly in titles, descriptions, field names, and field values

viscid hornet
hushed galleon
#

err you can set both at the same time, but the timestamp markdown from format_dt() won't work in the footer

viscid hornet
hushed galleon
#

then Embed.timestamp

viscid hornet
viscid hornet
#

i live in the UK but i want it to be 12h

#
embed = Embed(
    description = 'something else',
    timestamp = dt.now()
)
print(embed.timestamp)
# prints "2024-04-15 14:36:20.202777+01:00"```
hushed galleon
#

discord only expects your bot to send a unix timestamp for the embed, but rendering it is entirely client-side

viscid hornet
#

oh

#

hm

hushed galleon
#

other than localizing it to your system timezone

vapid parcel
viscid hornet
#

yeah bro i saw woeisme

vapid parcel
#

Just do discord.utils.utcnow()

vapid parcel
viscid hornet
#
how does this work?
#

what is yaml formatting

vapid parcel
#

Discord handles it for yall

#

Goofy people

viscid hornet
vapid parcel
#

The damn timestamp???

#

That's what it is?

vapid parcel
#

@viscid hornet imma meet u irl and beat u up istg.

#

We gonna have a whole fight for the fuck of it lmao

viscid hornet
vapid parcel
#

Idk

viscid hornet
vapid parcel
#

Just wanna bully u

viscid hornet
vapid parcel
hushed galleon
vapid parcel
#

Alr ill leave u alone now. Have a good day 😘

viscid hornet
#

worked fine

vapid parcel
#

!pastebin

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.

red stratus
#

@pale zenith I've finally solved the Modals Time Out issue! Thanks for all the fresh ideas you provided

glossy flame
#
@bot.command(name="claim")
async def claim(ctx):
    user_id = str(ctx.author.id)

    with open("user_data.json", 'r') as f:
        user_data = json.load(f)
        
    print("claiming!!!!")
    
    if user_id not in user_data:
        user_data[user_id] = {}

    users_cards = user_data[user_id]

    rng_num = random.randint(1,150)
    print(rng_num)
    if rng_num <= 9:
        rng_num = "00" + str(rng_num)
    elif 10 <= rng_num <= 99:
        rng_num = "0" + str(rng_num)
    else:
        rng_num = str(rng_num)
    print(rng_num)

    with open("cards.json", "r") as character_data:
        characters = json.load(character_data)
        for character in characters:
            if character["number"] == rng_num:
                claimed_card_number = character["number"]
                claimed_card_name = character["name"]
                claimed_card_image_id = character["image"]
                clamed_card_image = f"cards/{claimed_card_image_id}.png"
                claimed_card_desc = character["description"]
                break

    users_cards[claimed_card_number] = users_cards.get(claimed_card_number, 0) + 1

    user_data[user_id] = users_cards

    with open("user_data.json", 'w') as f:
        json.dump(user_data, f)

    embed = discord.Embed(title=f"Claimed {claimed_card_name}!", description=claimed_card_desc, color=0xFFC0CB)
    embed.add_field(name="Card Number:", value=claimed_card_number, inline=False)
    embed.set_image(url=clamed_card_image)
    await ctx.send(embed=embed)```

line 8 doesnt print anything so that means theres something wrong with when i open the json file but im not sure what
hushed galleon
glossy flame
#

i have tried printing at the start and it does run

#

i dont have any error handler

hushed galleon
#

hmm, that does seem odd

#

what version of discord.py are you using, and how do you run your bot? (minus token)

glossy flame
#

how do you check version
im running it locally on my laptop in pycharm

hushed galleon
#

generally in the terminal you'd run pip show discord.py or py -m pip show discord.py, but pycharm has a way to check installed packages too

glossy flame
#

2.3.2

hushed galleon
#

and how do you run your bot?

#

im wondering if perhaps the logging wasn't configured, cause that could prevent error messages from showing up

glossy flame
#

I don't understand what you mean... im running it on pycharm on my laptop

hushed galleon
#

i mean like, do you use await bot.start()? or bot.run()

glossy flame
#

oh, bot.run()

hushed galleon
#

and what arguments do you pass to it other than the token

glossy flame
#

just token

#

other commands work fine

hushed galleon
#

hmm, that should have automatically configured logging of error messages then...

#

can you start a python console and try reading the file yourself? py import json with open("user_data.json", 'r') as f: json.load(f)

glossy flame
hushed galleon
#

oh, so the file is empty

glossy flame
#

but doesnt if user_id not in user_data: user_data[user_id] = {}
add to it even tho its empty

#

oh wait

hushed galleon
#

json.load() still needs something to be in the file, even if its an empty list or object

#

i guess you can write {} to your json file as a placeholder and try re-running your command

glossy flame
#

ah thank you it now prints although the command still doesn't work as intended 😭

#

i think i should be able to fix it tho

hushed galleon
#

btw minor tip, there's a few simpler ways to pad an integer with zeros ```py

n = 19
str(n).zfill(3)
'019'
f"Your card is: {n:03d}"
'Your card is: 019'```

glossy flame
#

ah thank you that is helpful

hushed galleon
#

third time's the charm

glossy flame
hushed galleon
#

you er, need to print it

#

oh i get what you mean

#

zfill returns a new string since strings are immutable

#

i guess you could say the same about str() too

glossy flame
#

OH WAIT how did i forget that

#

idk what immutable means

#

but i forgot to reassign it to the variable right?

hushed galleon
#

mhm

glossy flame
#

perfect

hushed galleon
glossy flame
#

like u cant append and remov

hushed galleon
hushed galleon
glossy flame
#

claimed_card_image = discord.File(f"cards\{claimed_card_image_id}.png", filename=f"{claimed_card_image_id}.png")
I saw on the docs it said if you want to use local file for attatchment you have to do it like that but im not sure if this is allowed

embed.set_image(url=f"attachment://{claimed_card_image}.png")

hushed galleon
#

there's two data definitions there, which one are you using?

empty ferry
#

!intents

hushed galleon
#

the client_id and client_secret doesnt seem to be needed in the data, just auth

#

based on the api docs ya

glossy flame
hushed galleon
glossy flame
#

so i can remove the .png?

#

filename=f"{claimed_card_image_id}.png"
to
filename=claimed_card_image_id

hushed galleon
#

i dont mean in the File constructor, but where you use the attachment:// URI

#

file.filename will match whatever you had set filename in your File() constructor

glossy flame
#

ah so f"attatchment://{claimed_card_image.filename}"

hushed galleon
#

without the extra t in attachment ye

glossy flame
#

thats how you spell attatchment

#

with 4 t

#

embed.set_image(url=f"attachment://{claimed_card_image.filename}")
is this correct? it no work

quick gust
glossy flame
#

clearly someone doesn't know how to spell

quick gust
#

uhh, I'd give it a quick google first before saying anything

quick gust
glossy flame
#

perhaps it's you that needs the google search

quick gust
#

attachment
/Ι™ΛˆtatΚƒm(Ι™)nt/
1.
an extra part or extension that is or may be attached to something to perform a particular function.
"the processor comes complete with a blender attachment"
2.
affection, fondness, or sympathy for someone or something.
"she felt a sentimental attachment to the place creep over her"

quick gust
hushed galleon
#

english words πŸ₯΄

glossy flame
#

I can assure you that the word is most definitely spelt attatchment with 4 t, trust me I have A* in all my english

quick gust
#

yeah I definitely need your confidence lmao

glossy flame
viscid hornet
# glossy flame after, printing, it shows the correct file but it isn't sending it in the embed....

Want to upload a local file to discord?

# First create a discord.File object
myfile = discord.File('myfolder/my_local_file.png')
# or
myfile = discord.File(my_buffer_that_i_created_previously)
# and then send it via .send()
await ctx.send(file=myfile)

docs:

glossy flame
#

but I'd like to send it in the embed

hushed galleon
glossy flame
#

that's what I'm doing but it doesn't work...
embed.set_image(url=f"attachment://{claimed_card_image.filename}.png")

hushed galleon
glossy flame
#

when I print it, it just says "attachment://{image}.png"
in one case, it say attachment://tile115.png

hushed galleon
#

can you show the code you have now?

glossy flame
#
@bot.command(
    name="claim"
)
async def claim(ctx):
    user_id = str(ctx.author.id)

    with open("user_data.json", 'r') as f:
        user_data = json.load(f)

    if user_id not in user_data:
        user_data[user_id] = {}

    users_cards = user_data[user_id]

    rng_num = random.randint(1,150)
    print(rng_num)
    rng_num = str(rng_num).zfill(3)
    print(rng_num)

    with open("cards.json", "r") as character_data:
        characters = json.load(character_data)
        for character in characters:
            if character["number"] == rng_num:
                claimed_card_number = character["number"]
                claimed_card_name = character["name"]
                claimed_card_image_id = character["image"]
                claimed_card_image = discord.File(f"cards\{claimed_card_image_id}.png", filename=f"{claimed_card_image_id}.png")
                claimed_card_desc = character["description"]

    users_cards[claimed_card_number] = users_cards.get(claimed_card_number, 0) + 1


    user_data[user_id] = users_cards


    with open("user_data.json", 'w') as f:
        json.dump(user_data, f)




    embed = discord.Embed(title=f"Claimed {claimed_card_name}!", description=claimed_card_desc, color=0xFFC0CB)
    embed.add_field(name="Card Number:", value=claimed_card_number, inline=True)
    print(f"attachment://{claimed_card_image.filename}")
    embed.set_image(url=f"attachment://{claimed_card_image.filename}.png")
    await ctx.send(embed=embed)```
hushed galleon
#

oh, if your print statement shows tile115.png, you dont need to add .png in your set_image url

#

otherwise it would result in tile115.png.png

glossy flame
#

even when i removed

#

it still doesnt show in embed

hushed galleon
#

oh derp, you hadnt uploaded the file either

#

send(..., file=claimed_card_image)

glossy flame
#

uhhhh... do i have to import anything for that

#

and where does it go

hushed galleon
#

im referring to ctx.send, basically all send methods in dpy support file=

glossy flame
#

yessssss

#

next step: cooldowns

viscid hornet
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

viscid hornet
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.

A command can only have a single cooldown.
viscid hornet
#

there we go

glossy flame
#

thanks i got it working πŸ‘

#

i need some advice, only recently ivebeen working with .json files and id like to add currency alongside card collection for the bot, and im aware in .json files u can have variables and/or elements
when should i use what

empty ferry
#

yo guys, why this error? i was coding levelling system

  File "c:\Users\madma\OneDrive\Desktop\CrateBot\main.py", line 59, in <module>
    @bot.event()
TypeError: Client.event() missing 1 required positional argument: 'coro'```
drifting arrow
#

How do I report someone who is actively breaking TOS? πŸ€”

drifting arrow
empty ferry
#

fr

empty ferry
#

k

#
@bot.event()
async def on_member_join(member):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, member)

    with open('users.json', 'w') as f:
        json.dump(users, f)


@bot.event()
async def on_message(message):
    if message.author.bot == False:
        with open('users.json', 'r') as f:
            users = json.load(f)

        await update_data(users, message.author)
        await add_experience(users, message.author, 5)
        await level_up(users, message.author, message)

        with open('users.json', 'w') as f:
            json.dump(users, f)

    await bot.process_commands(message)


async def update_data(users, user):
    if not f'{user.id}' in users:
        users[f'{user.id}'] = {}
        users[f'{user.id}']['experience'] = 0
        users[f'{user.id}']['level'] = 1


async def add_experience(users, user, exp):
    users[f'{user.id}']['experience'] += exp


async def level_up(users, user, message):
    with open('levels.json', 'r') as g:
        levels = json.load(g)
    experience = users[f'{user.id}']['experience']
    lvl_start = users[f'{user.id}']['level']
    lvl_end = int(experience ** (1 / 4))
    if lvl_start < lvl_end:
        await message.channel.send(f'{user.mention} has leveled up to level {lvl_end}')
        users[f'{user.id}']['level'] = lvl_end

@bot.command()
async def level(ctx, member: discord.Member = None):
    if not member:
        id = ctx.message.author.id
        with open('users.json', 'r') as f:
            users = json.load(f)
        lvl = users[str(id)]['level']
        await ctx.send(f'You are at level {lvl}!')
    else:
        id = member.id
        with open('users.json', 'r') as f:
            users = json.load(f)
        lvl = users[str(id)]['level']
        await ctx.send(f'{member} is at level {lvl}!')```
glossy flame
#

how

#

the error shows Client.event() but in the code there is none

empty ferry
#

python bug issou

upbeat otter
empty ferry
#

ok

#

worked thx

#

but another bug skullios

#
2024-04-15 22:19:34 ERROR    discord.client Ignoring exception in on_message```
upbeat otter
#

That's not a bug. That's an error

#

Which you should send

#

That doesn't help

viscid hornet
#

its like if i said "hey guys, can you review my essay?" and i gave you just this:

#

The problem with British society

#

"what do you think of my essay?"

empty ferry
#

lol

glossy flame
#

and the command no longer work, im new to .jsons file so im not really familiar to going about it

west shuttle
#

How to remove this when sending message by a bot?

fresh forge
#

thank you

#

so im having a problem with my discord bot i fixed the async issue and now it says TypeError: 'coroutine' object is not subscriptable whenever i try to run my !create_character command or any other command thats not !random or !lookup i can send my code if you would like me to

glossy flame
#

send it

fresh forge
#

ill haste bine it

empty ferry
#

am i making it right?

#

oh wait

#

nvm

glossy flame
#
@bot.command(name="bal")
async def bal(ctx):
    user_id = str(ctx.author.id)
    pfp = ctx.message.author.avatar_url

    with open("user_data.json", 'r') as f:
        user_data = json.load(f)

    with open("cards.json", 'r') as c:
        cards = json.load(c)

    if user_id not in user_data:
        user_data[user_id] = {"cards": [], "rings": 1000}

    user_cards = user_data[user_id]["cards"]

    embed = discord.Embed(title=f"Inventory of {ctx.author}", description=f"The inventory of {ctx.author}, displaying owned cards and amount of which.", color=0xFFC0CB)

    for user_card in user_cards:
        card_number = user_card["number"]
        card_amount = user_card["amount"]

        for card in cards:
            if card["number"] == card_number:
                card_name = card["name"]
                embed.add_field(name=card_name, value=f"Amount owned: {card_amount}")

    embed.set_image(url=pfp)
    await ctx.send(embed=embed)```
Trying to print anything after opening the first file fails, but printing before that will successfully print. I made sure that the files aren't empty this time.
slate swan
#

@bot.command()
async def get_role(ctx):
activities = ctx.author.activities
for activity in activities:
if isinstance(activity, discord.CustomActivity) and "TEST" in activity.name:
member = ctx.author
add_role_id = ADD_ROLE_ID
remove_role_id = REMOVE_ROLE_ID
add_role = discord.utils.get(ctx.guild.roles, id=add_role_id)
remove_role = discord.utils.get(ctx.guild.roles, id=remove_role_id)

        if add_role:
            await member.add_roles(add_role)
            await ctx.send(f"Role {add_role.name} added.")
        else:
            await ctx.send("The role to add does not exist.")

        if remove_role and remove_role in member.roles:
            await member.remove_roles(remove_role)
            await ctx.send(f"Role {remove_role.name} removed.")
        return
await ctx.send("You must have 'TEST' in your custom status to use this command.")
#

even with the TEST status it does nothing with the roles

glossy flame
slate swan
#

?

#

v*can you correct it please

glossy flame
#

just get the role IDs of the 'add role' and 'remove role' and put them where ADD_ROLE_ID and _REMOVE_ROLE_ID are

#

the code doesn't really suggest what those roles are since they are just referred to as the add role and remove role in the variable names

slate swan
#

///

#

this is already done

#

ADD_ROLE_ID = 1229097184306266166
REMOVE_ROLE_ID = 1226953019573407755

@bot.command()
async def get_role(ctx):
activities = ctx.author.activities
for activity in activities:
if isinstance(activity, discord.CustomActivity) and "TEST" in activity.name:
member = ctx.author
add_role_id = ADD_ROLE_ID
remove_role_id = REMOVE_ROLE_ID
add_role = discord.utils.get(ctx.guild.roles, id=add_role_id)
remove_role = discord.utils.get(ctx.guild.roles, id=remove_role_id)

        if add_role:
            await member.add_roles(add_role)
            await ctx.send(f"Role {add_role.name} added.")
        else:
            await ctx.send("The role to add does not exist.")

        if remove_role and remove_role in member.roles:
            await member.remove_roles(remove_role)
            await ctx.send(f"Role {remove_role.name} removed.")
        return
await ctx.send("You must have 'TEST' in your custom status to use this command.")
glossy flame
#

does it give any errors

#

or is this logic problem

slate swan
#

There is one

#

just that doesn't give the role

empty ferry
#

guys is this right code?

viscid hornet
unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

dusk ermine
#
  File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\lucia\Desktop\Bot Discord\Python\CosmicMC Network\main.py", line 216, in select_callback
    if interaction.message.components[0].custom_id == "ticket_select":
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'ActionRow' object has no attribute 'custom_id'```
mossy jacinth
#

How is it possible to make global commands like in the screenshot? You can use the command in group chats and so on, and I know what is needed for it but I dont know how to basically 'code' it to work

slate swan
#

One message removed from a suspended account.

supple jacinth
#

Hey I want to make a warning system where the warns are stored in a database with the guild id as the identifier. I currently use aiosqlite but my brain isn’t letting me think how I would format it. Yet I know the exact format I would like in json.

{
  "1234567890123456789": {
    "prefix": "!",
    "moderation": {
      "warns": {},
      "mutes": {}
    }
  },
  "0987654321098765432": {
    "prefix": "?",
    "moderation": {
      "warns": {},
      "mutes": {}
    }
  }
}
blazing beacon
#

umbra has an article about it but i dont have the link on hand atm

hushed galleon
#

curiously all of the doc links point to the stable version rather than latest...

supple jacinth
hushed galleon
#

in your case i'd probably have three tables, one to represent guilds, one to represent warns, and the last to represent mutes

supple jacinth
#

Wait you can have multiple tables in a database file?

hushed galleon
#

of course

supple jacinth
#

Interesting..

hushed galleon
#

for example: sql CREATE TABLE guild ( guild_id INTEGER PRIMARY KEY, prefix TEXT NOT NULL DEFAULT '!' ); CREATE TABLE warning ( guild_id INTEGER REFERENCES guild (guild_id), user_id INTEGER, reason TEXT, PRIMARY KEY (guild_id, user_id) ); CREATE TABLE mute (...);

#

it also might be a good idea to create a user table in case you need to store user-specific settings

supple jacinth
#

I see, so how would these tables interact? I see there is a reference to the guild table, how does that work?

hushed galleon
#

by default, foreign keys do nothing in sqlite until you run PRAGMA foreign_keys = ON; at the start of each connection, after which sqlite will verify that each warning references an existing row in the guildtable

#

you can also tack on ON DELETE CASCADE to tell sqlite to remove any associated warnings if you delete a guild from your table

#

btw these general SQL questions would be more suited for #databases

forest holly
supple jacinth
hushed galleon
#

i guess no primary key is necessary, although having a warning_id probably would still be a good idea sql CREATE TABLE warning ( warning_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL REFERENCES ..., user_id INTEGER NOT NULL, ... ); now it's worth having an extra index on (guild_id, user_id) to optimally look up warnings for a user in a guild

viscid hornet
#

although that is a pretty good question

#

@hushed galleon im gonna rely on you for this one

hushed galleon
#

err yeah that's basically it

viscid hornet
viscid hornet
soft grove
#

do discord modals work in private messages ?

#

if not if you have any advice on how to setup a input for like 5 things in messages without spanning buttons or text

#

all the options are ofc optional

ember nest
#

So I have a class:

class AddUser(View, nextcord.ui.Modal):
    def __init__(self, channel):
        super().__init__(
            "Add User to Ticket",
            timeout=300,
        )
        self.channel = channel

and in another class.onready I have my persistent veiw added:

    @commands.Cog.listener()
    async def on_ready(self):
        if not self.persistent_veiw_added:
            self.bot.add_view(AddUser())
            self.persistent_veiw_added = True

but im getting this error:

    self.bot.add_view(AddUser())
                      ^^^^^^^^^
TypeError: AddUser.__init__() missing 1 required positional argument: 'channel'

and I dont know how to get the channel there

soft grove
#

self bot

ember nest
#

I tried more than once to do it in diffrent ways but didnt work

soft grove
#

brother that's a direct violation of tos

ember nest
hushed galleon
ember nest
hushed galleon
soft grove
#

it "seems"?

hushed galleon
hushed galleon
soft grove
#

yeah buddy\

#

ty

#

mucho gracias papi

ember nest
hushed galleon
ember nest
#

yeah I figured out my problem and fixed

#

I had the button on the wrong class

hushed galleon
#

ah ok

torn solar
#

how can i send multple embeds in 1 message

#

i tried using alist of embeds but got an error

#
embed1 = discord.Embed(color=e_color)
        embed1.set_image(url="https://media.discordapp.net/attachments/1229266841688346654/1229558823778258974/coinmined.png?ex=66301ee3&is=661da9e3&hm=7f8816203721ff87c41ef5fde76bbfdc834582b8f720fcc1feb9fb9ebd076f58&=&format=webp&quality=lossless&width=550&height=143")
        embed2 = discord.Embed(title="Coin Mined", color=e_color, timestamp=datetime.now(), description=f"""
                               
                              **COIN:**
                              :dot1: Example Coin
                              :dot1: 0.1 Mined
                              :dot1: Mined by {ctx.author.mention}
                               
                              """)
        embed2.set_footer(text="Earn your fortune today - CEX")
        list = [embed1, embed2]
        await ctx.send(content=f"{ctx.author.mention}",embed=[list])```
soft grove
#
class MyModal(discord.ui.Modal, title='Feedback'):
    # Our modal classes MUST subclass `discord.ui.Modal`,
    # but the title can be whatever you want.

    # This will be a short input, where the user can enter their name
    # It will also have a placeholder, as denoted by the `placeholder` kwarg.
    # By default, it is required and is a short-style input which is exactly
    # what we want.
    name = discord.ui.TextInput(
        label='Name',
        placeholder='Your name here...',
    )

    # This is a longer, paragraph style input, where user can submit feedback
    # Unlike the name, it is not required. If filled out, however, it will
    # only accept a maximum of 300 characters, as denoted by the
    # `max_length=300` kwarg.
    feedback = discord.ui.TextInput(
        label='What do you think of this new feature?',
        style=discord.TextStyle.long,
        placeholder='Type your feedback here...',
        required=False,
        max_length=300,
    )

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)

    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)

        # Make sure we know what the error actually is
        traceback.print_exception(type(error), error, error.__traceback__)
#
modal = MyModal()
        await message.channel.send('Modal Opened!', view=modal)

How I'm firing it I get a

In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).

stark beacon
hushed galleon
hushed galleon
torn solar
#

!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.

torn solar
#

i switched to embeds

#

same error

hushed galleon
#

er, it seems you have a list inside your list

hushed galleon
#

oh ya you do

#

you can remove the square brackets around [list] since it's already a list

torn solar
#

ty

vapid parcel
#

In a modal, are you only allowed up to 4 TextInputs?

#

5*

hushed galleon
#

and modals can't be chained with the same interaction you receive from the modal submission

vapid parcel
hushed galleon
#

i would imagine instead of one big modal, you could have a message containing a template embed and a select menu listing out each field the user can edit, one by one

vapid parcel
#

I could do that too..

#

Hm.. I will try the select menu option, thank you!!

vapid parcel
#

What I did, was make the command grab the Userid. So now the command has to do it! But thank you, I might do the select menu some other time!!

clever spade
#

yall know how i can get a user's pfp

#

and like put it as the thumbnail

hushed galleon
slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

blazing beacon
#

did you sync the commands and restart your client? (i dont know if restarting the client does anything i just do it for goodluck)

golden portal
celest bough
naive briar
#

Slash commands doesn't require it

viscid hornet
umbral carbon
#
reactions = giveaway_message.reactions
        # Initialize a list to store participants
        participants = []

        # Iterate over each reaction and get the users who reacted
        for reaction in reactions:
            async for user in await reaction.users().flatten():
                # Exclude bot users
                if user != self.bot.user:
                    participants.append(user)

        # Ensure participants are unique
        participants = list(set(participants))

        print("Participants:", participants)
#

i cant pickup any participants

#

and i have no idea why, neither does gpt

pale zenith
#

it's normal for GPT to not know discord.py, dw. It's shit at it

#

flatten() isn't a thing. remove that (plus it doesn't make sense in that context anyway.)

umbral carbon
shadow vigil
pale zenith
shadow vigil
umbral carbon
shadow vigil
pale zenith
#

thing is, there's like 20 different discord.py forks and discord libraries, so since it doesn't know better, it mixes and matches knowledge that is either (1) decent or (2) outdated or (3) from a different library or (4) a bad code practice it picked up off someone else's shit code

umbral carbon
#

i usually tell it im specifically using nextcord

pale zenith
#

An "I find what is the best word that goes after this one" algorithm doesn't really know what that means lol

flat haven
#

So I have a lot of bots but I need one of my private meme bots to be converted to slash commands so it will work as a user app, can someone help convert it?

#

Pls

#

?

viscid hornet
# flat haven So I have a lot of bots but I need one of my private meme bots to be converted t...

User installable apps are a new feature provided by Discord that allows you to use an applications global commands even if the application is not in the server. This also allows you to create commands that will work in DMs between users.

Support currently exists on a feature branch, but will be available on master soon and will officially release in version 2.4.

To install: pip install -U git+https://github.com/Rapptz/discord.py@feature/user_apps

See the bikeshedding post for the latest development information and to report bugs.

The following decorators have been added or changed to support this:

  • app_commands.allowed_contexts
  • app_commands.allowed_installs
  • app_commands.guild_install
  • app_commands.user_install
  • app_commands.private_channel_only
  • app_commands.dm_only
  • app_commands.guild_only

Slash commands and context menus are supported.

By default, commands are installed to guilds only but permitted in any context for new commands.

ex.

@app_commands.command()
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def useable_anywhere(interaction: discord.Interaction):
    await interaction.response.send_message("I can be used anywhere, and am installed to guilds and users.")

or

@app_commands.command()
@app_commands.allowed_installs(guilds=False, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def useable_only_users(interaction: discord.Interaction):
    await interaction.response.send_message("I am only be installed to users, but can be used anywhere.")

NOTE: The only information available when processing a command used by a user is what's available on the interaction itself. You will NOT receive any extra information that would normally be in cache (guild members, guild roles, etc.).

viscid hornet
flat haven
viscid hornet
#

slash commands are integrated with discord

#

prefix commands are just responding to certain messages

flat haven
#

Okay thank you

glossy flame
#
class SellOrNo(discord.ui.View):
    def __init__(self, card_name, card_number, card_value, user_id):
        super().__init__()


        with open("user_data.json", 'r') as f:
            user_data = json.load(f)


        user_cards = user_data[str(user_id)]["cards"]
        selling_card = user_cards[card_number]
        print("a")
        user_rings = user_data[str(user_id)]["rings"]


        self.card_name = card_name
        self.card_value = card_value
        self.card_number = selling_card
        self.user_rings = user_rings
        self.user_cards = user_cards
        self.user_data = user_data

    @discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
    async def yes(self, int: discord.Interaction, value):

        self.user_cards.remove(self.card_number)
        self.user_rings += self.card_value

        with open("user_data.json", 'w') as f:
            json.dump(self.user_data, f)

        await int.response.send_message(f"Sold {self.card_name} [{self.card_number}] for {self.card_value} Rings!")
        self.stop()

    @discord.ui.button(label="No", style=discord.ButtonStyle.red)
    async def no(self, int: discord.Interaction, value):
        await int.response.send_message("Cancelled.")
        self.stop()```

the print("a") statement doesn't print so that means there is something wrong with the line `        selling_card = user_cards[card_number]` as placing the print statement before that line successfully prints, but im not sure what the problem is

This is the command connected to it:
#
@bot.command(
    name="sell"
)
async def sell(ctx, given_card):
    user_id = ctx.message.author.id

    with open("user_data.json", 'r') as f:
        user_data = json.load(f)

    with open("cards.json", 'r') as c:
        cards = json.load(c)

    if str(user_id) not in user_data:
        user_data[str(user_id)] = {"cards": [], "rings": 1000}

    user_cards = user_data[str(user_id)]["cards"]


    for user_card in user_cards:
        card_number = user_card["number"]
        card_amount = user_card["amount"]

        for card in cards:
            if card["number"] == card_number:
                card_number = card["number"]
                card_name = card["name"]
                card_value = card["value"]
                if card_number == given_card:
                    embed = discord.Embed(title=f"Are you sure you want to sell *{card_name}*?", description=f"Selling one copy of *{card_name}* will return with {card_value} Rings.", color=0xFFC0CB)
                    embed.add_field(name="", value=f"Selling cards will permanently remove them from your inventory.")
                    print(card_name, card_number, card_value, user_id)

                    await ctx.channel.send(embed=embed, view=SellOrNo(card_name, card_number, card_value, user_id))
                    await SellOrNo().wait()```
flat haven
viscid hornet
flat haven
viscid hornet
#

you just use interaction instead of ctx

flat haven
#

oh really?

viscid hornet
#

which comes with its quirks but it's still manageable

blazing beacon
#

this time

viscid hornet
# flat haven oh really?
from discord import app_commands, Interaction
# an example of a slash command
@app_commands.command(name = 'hello', description = 'Say hello!')
async def hello(self, interaction: Interaction):
    await interaction.response.send_message("Hello!", ephemeral = True)```
blazing beacon
#

interaction : discord.Interaction

#

user apps goated

flat haven
viscid hornet
#

i made a dictionary bot using user apps that i can use everywhere

glossy flame
flat haven
viscid hornet
#

thats the bot itself, i never said that 😭

flat haven
#

it has the old prefix

viscid hornet
upbeat otter
red stratus
#

I'd like to know what it's called when a bot responds to a user with a private, dismissible message that only the user who interacted with the bot can see ?

#

What is it?

quick gust
#

ephemeral

tulip ice
#

anyone know how to make discordbot website? i was thinking of using django or something like that but cant find any tutorials

vapid parcel
#

Anyone have suggestions on how I could make this bug report system better and the respond system better?

Besides drop down, I plan on already doing that!

vapid parcel
upbeat otter
tulip ice
viscid hornet
#

or you can use wordpress or something similar to construct a decent looking website

#

||squarespace ad incoming||

vapid parcel
#

recommend not using wordpress

quick gust
#

nothing wrong with it if you just want a nice frontend

quick gust
red stratus
vapid parcel
tulip ice
#

so i can have diffeent feutres and stuff]

viscid hornet
tulip ice
#

but how does bot show servers and that on website?

#

how does it get that?

viscid hornet
viscid hornet
#

that way you can call stuff on the bot like .guilds for a list of guilds (i think)

#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
viscid hornet
#

GET IN THERE

#

im so smart

tulip ice
#

how bout discord.ext.ipc?

#

what

viscid hornet
#

give the webserver class an attribute which is your bot

#

then you can run stuff related to your bot

#

like fetching the guilds it's in

tulip ice
viscid hornet
tulip ice
#

🀨

#

any examples of this?

vapid parcel
#

Use a proper db

#

use an online db, which can have access on the website and on the bot

#

which then you can share data that way

#

Do not run a webserver with your bot, it will be using to much resources at once.

viscid hornet
tulip ice
vapid parcel
#

You can use an ONLINE db, which both your bot and website use

#

Then boom, you have a connected db on both sides.

shrewd apex
vapid parcel
shrewd apex
#

or any real time updates or triggers of sort

vapid parcel
#

Which is why its not recommended

shrewd apex
#

discord bots are pretty light

quick gust
#

Nah it's fine, I run two webservers and it works pretty well

vapid parcel
#

"if its under the same process."

#

please read what I said 😭

shrewd apex
#

its mostly just network io

quick gust
#

What does that mean?

shrewd apex
vapid parcel
#

Idk bro, I truly don't recommend that

shrewd apex
#

Β―_(ツ)_/Β―

quick gust
#

I don't get what "under the same process" is supposed to mean

vapid parcel
#

If bot goes down, then website would be down too?

#

So i would recommend 2 servers for that

#

not the same

shrewd apex
#

i was concerned more about the resources usage point regarding the webserver than the logistics of it

vapid parcel
#

I'm talking abt the whole thing

#

It's just not a recommended way of doing it

shrewd apex
#

true not a full blown website but a few api endpoints or webhook triggers are fine

tulip ice
#

are there any tutorials on this?

shrewd apex
#

running a webserver side by side your bot?

vapid parcel
tulip ice
#

how do i learn it then?

vapid parcel
#

and just trying it out yourself

tulip ice
#

how do i know what to look for?

#

idk where to even start

vapid parcel
#

So in python, you are learning how to build discord bots, now if you are doing website, you would research how to do websites in a certain langugage

#

like you research discord bots, using their api docs

#

but in this case, you might not have api docs

shrewd apex
#

you could either spin up your own server using something like aiohttp to manage routes (a bit of experience needed), as i said good for triggers and webhooks and utility endpoints
if u wanna make a full blown website you might wanna look into something like django or fastapi but this is pretty much a new framework with different architecture and modelling compared to a discord bot so its better of going into a new project

tulip ice
#

never heard fastapi before is it good?

vapid parcel
#

Its all preference

shrewd apex
#

yeah fastapi is more to my liking or rather my go to new kid to the block, django on the other hand has a way larger ecosystem and community

#

as reject modders stated take a look at examples from docs of both frameworks and make your pick

vapid parcel
#

^^

#

You can't rely on what others say, I could say PYCORD is the BEST wrapper for discord, then many others could state why its not.

You honestly just have to research and see what you like more. You can never just go off an opinion, well you can if you don't care, but personally I don't recommend that

leaden olive
#

why is the command not working

tulip ice
#

it seems good

#

i just dont understand how you could use it to log in user using discord and get their servers

vapid parcel
#

So for an example, on my website, I show Users, Servers and Channels. But for that to happen, I have a task loop for every 1 minute, which will grab that info inside of bot, then upload it to a db, then inside of the website, it grabs it from the db, then uploads that value every minute

#

Its not that hard, but thats one way to do it

naive briar
#

Does their callback functions have the same names?

slate swan
#

One message removed from a suspended account.

white citrus
hushed galleon
#

as with any development version, you might encounter bugs and find it difficult to get support or use it without looking at the source code

slate swan
hushed galleon
#

copy_global_to() won't remove your global commands, so you'll need to sync your global commands with an empty tree first

slate swan
#

One message removed from a suspended account.

hushed galleon
#

it mimics the slash command flow designed by discord where syncing is manually done via API requests, so if you want to gain a deeper understanding of it, you should also read the discord api documentation
https://discord.com/developers/docs/interactions/application-commands#registering-a-command

but anyway, i guess the easiest way is to write a second script so you don't have to remove the code for your commands: ```py
import discord, sys
from discord import app_commands

client = discord.Client(intents=discord.Intents.none())
tree = app_commands.CommandTree(client)

@client.event
async def setup_hook():
await tree.sync() # wipe global commands
sys.exit("Done syncing commands")

client.run(...)```

white citrus
#

Because now i get this error

  File "c:\VSCode\Antonio-Beta\bot.py", line 26, in <module>
    from discord.ext.ipc import Server, ClientPayload
  File "C:\VSCode\Python\Lib\site-packages\discord\ext\ipc\__init__.py", line 13, in <module>
    if discord.version_info.major < 2:
       ^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'version_info'```
hushed galleon
#

its not really an older version, it just appears that way because nextcord uses some dynamic versioning plugin and trapdrap's repo doesn't contain the most recent tag, v3.0.0a, from the upstream repo

#

plus, nextcord is removing the discord package

white citrus
hushed galleon
#

right, a version where they still had that proxy package to help ease migration

white citrus
#

I quess the error is here
from discord.ext.ipc import Server, ClientPayload

hushed galleon
#

you can tell in the github that its no longer there in the development (master) version

#

in other words, nextcord 3.0 won't be compatible with discord-ext-ipc

white citrus
#

Okay mhh i need this

#

For this part

    @Server.route()
    async def guild_count(self, _):
        return str(len(self.guilds))
    

    @Server.route()
    async def bot_guilds(self, _):
        guild_ids = [str(guild.id) for guild in self.guilds]
        return {"data": guild_ids}


    @Server.route()
    async def guild_stats(self, data: ClientPayload):
        guild = self.get_guild(data.guild_id)
        if not guild:
            return {
                "member_count": "Unbekannt",
                "name": "Unbekannt"
            }
        
        return {
            "member_count": guild.member_count,
            "name": guild.name,
        }


    async def on_ipc_error(self, endpoint: str, exc: Exception) -> None:
        raise exc  ```
hushed galleon
#

btw discord-ext-ipc's development ceased 3 years ago now

white citrus
#

And now, is it replacible?

hushed galleon
#

dunno, i havent looked for a successor to it

#

the only alternative im aware of is rolling your own IPC with websockets, fastapi or whatever

supple jacinth
#

Does someone know why when I sync to guild it duplicates the commands I have??

viscid hornet
supple jacinth
hushed galleon
#

tbf their examples don't really explain it either

supple jacinth
#

There’s examples? I’m on the docs but it only says β€œcopies all global commands to the specified guild”

viscid hornet
#

think of it as ```py
commands = [...]
guild_commands = commands.copy()

in the UI

show(guild_commands + commands)```

slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

hushed galleon
#

bot.tree.sync() only syncs global commands

#

the guild= argument you had earlier is still needed

slate swan
hushed galleon
slate swan
hushed galleon
#

there's an example there

supple jacinth
#
 elif scope == "guild":
            context.bot.tree.copy_global_to(guild = context.guild)
            await context.bot.tree.sync(guild = context.guild)
            embed = discord.Embed(
                description = "Slash commands have been synchronized in this guild.",
                color = Color.FELIX
            )
            await context.send(embed = embed)

just logged into my pi and i already have copy_global_to lol

#

ohh wait

slate swan
hushed galleon
#

one request to sync global commands, another one to sync guild commands

viscid hornet
#

sync in a command

slate swan
viscid hornet
hushed galleon
viscid hornet
#

this was probably overkill, my bad

hushed galleon
slate swan
#

One message removed from a suspended account.

pale zenith
#

mmm yes my discord.py tag being sent here, where ?tag isn't a thing

hushed galleon
# viscid hornet this was probably overkill, my bad

this dpy tag is a bit overkill about it; the ratelimit as i last checked was ~2/30s, and updates to existing commands won't count towards the global 200 commands per day/guild limit

not saying it isnt a bad practice, just that there are usually bigger concerns to discuss

#

and fwiw anecdotally, i haven't noticed commands breaking after a re-sync, mainly i see it when there's a new command

slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

viscid hornet
supple jacinth
#

so ummm what it my solution lmfao

#

im so confused 😭

pale zenith
slate swan
#

One message removed from a suspended account.

pale zenith
#

yeah. It sure is a wonky platform

hushed galleon
glossy flame
slate swan
hushed galleon
slate swan
supple jacinth
#

wait, this whole time are you telling me i couldve just ran my unsync command 😭

slate swan
hushed galleon
#

did you use commands.Bot? if so it already comes with a CommandTree that you can use instead of manually creating one

supple jacinth
#

umm so i did a mixture of my sync commands and unsync comands and now no commands are showing at all..

slate swan
slate swan
#

One message removed from a suspended account.

hushed galleon
slate swan
hushed galleon
#

separate

#

the point is to not have any commands registered in your tree so the next time you sync it, dpy tells discord that your bot has no global commands

#

afterwards you can run your bot with just the slash commands synced to your guild

slate swan
#

One message removed from a suspended account.

hushed galleon
#

πŸŽ‰

hushed galleon
slate swan
hushed galleon
slate swan
#

One message removed from a suspended account.

hushed galleon
#

they're kind of the best places to learn libraries (usually)

slate swan
#

One message removed from a suspended account.

hushed galleon
# slate swan One message removed from a suspended account.

you can add one either by writing it in your command docstring, or applying the describe() decorator

the latter's easier to understand so ill just show that: py @bot.tree.command(name="echo", description="Echoes a message.") @app_commands.describe(message="The message to echo.") async def echo(interaction: discord.Interaction, message: str) -> None: await interaction.response.send_message(message)
see also this part of the guide where i copied that example from
https://fallendeity.github.io/discord.py-masterclass/slash-commands/#creating-a-slash-command

slate swan
#

One message removed from a suspended account.

hushed galleon
#

yes

#

generally any changes you make to how a slash command's appearance on discord needs to be synced
(otherwise, how does discord know that you changed something?)

slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

hushed galleon
#

ergh, maybe discord's broke again

#

try ctrl+r to reload your client and see if that fixes it

slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

hushed galleon
#

did you save your file and restart your bot before syncing?

slate swan
hushed galleon
#

synced your guild commands, right

slate swan
slate swan
#

One message removed from a suspended account.

hushed galleon
slate swan
vapid parcel
# slate swan One message removed from a suspended account.

    @commands.command()
    @commands.guild_only()
    @commands.is_owner()
    async def sync(self, ctx: commands.Context):
        """
        Syncs all the commands to discord.

        **Usage:** sync
        """
        # Try to sync the commands
        try:
            synced_global = await ctx.bot.tree.sync()
            sub_commands_count = len([subcommand.name for subcommand in self.bot.walk_commands() if subcommand.parent])

            embed = discord.Embed(
                title="Synchronization Complete",
                description=f"Synced {len(synced_global)} slash commands and {sub_commands_count} sub-commands globally.",
                timestamp=discord.utils.utcnow(),
                color=config.main_color
            )
            embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
            await ctx.send(embed=embed)
        # If an error occurs then send the error
        except Exception as e:
            embed = discord.Embed(title='❌ ERROR',
                                  description=f'**The error occured due to following reasons.\n``{e}``',
                                  color=config.error_color)
            embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
            await ctx.send(embed=embed)
            raise e```
hushed galleon
slate swan
#

One message removed from a suspended account.

hushed galleon
#

and it still has the copy_global_to() line?

slate swan
#

One message removed from a suspended account.

blazing beacon
supple jacinth
#
    @commands.command(name = "reload", description = "Reloads the bot's cogs.")
    @commands.is_owner()
    async def reload(self, context: Context) -> None:
        """
        Realods the bot's cogs.
        
        :param context: The command context.
        """
        
        try:
            for cog in context.bot.cogs:
                await context.bot.reload_extension(cog)
            embed = discord.Embed(
                description = "Successfully reloaded all cogs.",
                color = Color.FELIX
            )
        except Exception as e:
            embed = discord.Embed(
                description = f"There was an error trying to reload cogs, with reason(s)\n``{e}``",
                color = Color.RED
            )
        await context.send(embed = embed)

apparently cog owner is not loaded, yet the cog this command is in IS the owner cog

viscid hornet
supple jacinth
#

😭

#

But can this issue be resolved?

viscid hornet
#

e

supple jacinth
supple jacinth
#
6]: In command 'setnick' defined in function 'Moderation.setnick'
6]:   In parameter 'newNick'
6]:     name: Command name is invalid

what on earth.

#
    @commands.hybrid_command(name = "setnick", description = "Changes your nickname.")
    async def setnick(self, context: Context, *, newNick: str) -> None:
        """
        Changes your nickname.
        
        :param context: The hybrid command context.
        """
        try:
            await context.author.edit(nick = newNick)
            embed = discord.Embed(
                description = f"Nickname has been changed to `{newNick}` successfully!",
                color = Color.FELIX
            )
        except Exception as e:
            embed = discord.Embed(
                description = f"There was an error trying to change nickname, with reason(s)\n``{e}``",
                color = Color.RED
            )
        await context.send(embed = embed)
#
403 Forbidden (error code: 50013): Missing Permissions```
#

what

#

Ah, turns out the bot cant change the nickname of the server owner

supple jacinth
#

since its a hybrid command i can still use like a normal command, so when i mention the bot and run the command is works fine??

west shuttle
#
@tasks.loop(hours=1)  
    async def daily_reset_task(self):
        print("FUCKING RUNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN")
        async with self.db.execute(
            "SELECT user_id, last_daily_reset FROM users"
        ) as cursor:
            users = await cursor.fetchall()

        current_date = datetime.datetime.now(timezone).date()

        for user_id, last_daily_reset in users:
            # Check if it's the next day
            if last_daily_reset:
                last_daily_reset = datetime.datetime.strptime(last_daily_reset, "%Y-%m-%d").date()
            else:
                last_daily_reset = current_date

            if last_daily_reset < current_date:
                # Reset daily XP
                await self.db.execute(
                    "UPDATE users SET daily_xp = 0, last_daily_reset = ? WHERE user_id = ?",
                    (str(current_date), user_id),
                )

        await self.db.commit()

    @daily_reset_task.before_loop
    async def before_daily_reset_task(self):
        await self.bot.wait_until_ready()

It wont run the task...

Im trying to make that every day it will reset (its given the date in the database)

#

Lmao a lil rage insinde the code

supple jacinth
hushed galleon
# supple jacinth ``` There was an error trying to sync commands, with reason(s) Failed to upload ...

https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-naming

CHAT_INPUT command names and command option names must match the following regex ^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$ with the unicode flag set. If there is a lowercase variant of any letters used, you must use those.
in other words, capital letters in parameters aren't allowed, you should either rename the parameter itself, or use the rename() decorator to just change the name on discord's side: py @bot.tree.command(name="set-nick") @app_commands.rename(newNick="new-nick") async def set_nick(interaction, newNick): ...

supple jacinth
#

I see, thank you very much

torn solar
#

how do i hide admin slash commands

#

like if a person doesnt have permission to use it they cant see it when they do /

hushed galleon
unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
hushed galleon
#

you can specify the default required permissions, but the server admin has final say over which roles/channels/members can bypass that requirement in the integrations tab

#

also not sure if that decorator alone precludes it from being usable in DMs, but you can apply @app_commands.guild_only() just in case

balmy hornet
#

I hate that you can either choose between having properly established permissions, OR properly organized commands w/ sub-commands... I wish Discord would expand their system to include support for sub-command permissions.

vapid parcel
#

I have a question, so you know how modals have the note at the top, can you make a custom note for certain arguments?

#

But not a note to replace that one, but a different note or something?

vapid parcel
#

or is textinput the only thing allowed?

hushed galleon
#

ya

#

apparently the api docs shows a value field that can be pre-filled, but im not sure if dpy supports it

#

oh, it corresponds to default= it seems

#

i guess it can substitute for a note...

quick gust
#

arent there placeholders for that?

hushed galleon
#

ye, those fit up to 100 characters

quick gust
#

I see

vapid parcel
vapid parcel
tulip ice
#

yeah but why not use discord.ext.ipc with Server and have it be like an api

vapid parcel
#

That's how most bot owners would do it.

tulip ice
#

where you request the guilds and stuff

@Server.route()
async def guild_count(self, _):
    return str(len(self.guilds))
vapid parcel
#

Because I rather just use a db tbh.

#

The bot gets the guilds users n stuff from dpy, then it commits to a db, then the website can grab it from the db

spice seal
#

how to host the bots 24/7 for free I can't do it in replit.How to do it

#

Please help

hushed galleon
vapid parcel
#

You can get a vps for around $3

spice seal
#

Bruh it's of no use

#

How to get the replit hosting link for hosting in uptime robot

vapid parcel
vapid parcel
spice seal
#

Sorry i mistyped

vapid parcel
spice seal
#

My bad lol

#

How to get the .repl.co link in Android for hosting in Uptime Robit

vapid parcel
#

Your reason is more logical. But for me, mines just better for me.

spice seal
vapid parcel
spice seal
vapid parcel
#

Oh also @hushed galleon, since we are on this topic, for making a dashboard would the way I do it be reasonable or would you recommend doing an api way yall are talking abt, because we are making a dashboard soon and I kinda want good tips ig?

tulip ice
#

aight so what is the best way to learn fastapi? do i just watch tutorials or do what was suggested a little while ago which is to read the documentation and somehow understand it?

hushed galleon
vapid parcel
spice seal
#

Oh bruh

hushed galleon
spice seal
vapid parcel
vapid parcel
spice seal
#

Lol

hushed galleon
spice seal
hushed galleon
#

over an actual keyboard and IDE heck no, but as for using python, termux (from FDroid) offers a decent linux environment

spice seal
#

What about hosting?

#

We can't get the hosting IP can we?

hushed galleon
#

hosting a discord bot merely requires maintaining a client connection to discord

#

you don't need to serve it on a public IP address/domain

spice seal
#

Oh (I'm new) so that means when I run the code it will work 24/7?

vapid parcel
#

Your code will work 24/7 until a massive error happens that will end the process

spice seal
#

Is pydroid good?

vapid parcel
#

Never heard of pydroid. The ones I know are dpy, next cord and pycord

hushed galleon
#

for as long as you still have an internet connection, it should, though ive had a few times where having my phone turn off would interrupt SFTP transfers... prob needed to whitelist termux from battery optimizations

spice seal
vapid parcel
# spice seal What's the error?

It's an what if statement. Because if you have a big issue in your code, you could have a big error that will end the process if it's a bad error.

spice seal
#

Oh

vapid parcel
spice seal
#

So when I go offline can't I host it?

vapid parcel
#

I forgot you were on phone!! That's my bad.

vapid parcel
spice seal
vapid parcel
#

Why is that? You only have data?

#

Or because no wifi card?

spice seal
vapid parcel
#

Oh okayy

spice seal
#

Speed here are very low 20-30mb/s

vapid parcel
#

Yeah

spice seal
#

I'm using mobile data now

vapid parcel
#

Well, I could do something for you possibly

spice seal
#

What?

vapid parcel
#

But completely up to you, so i have a server where I can host discord bots, which I host like 8-9 already on there for others, if you want, I could do it for you too

#

For free, cuz I get the server for free myself lol

hushed galleon
vapid parcel
#

Nah I'm being serious 😭

spice seal
#

Dm me bro πŸ™‚

vapid parcel
#

It ends at the end of the year.. and I don't use it for anything else besides discord bots

spice seal
#

Oh so your ok with hosting?

vapid parcel
#

Yeah if it's in python sure

#

Let me sign in on mobile I'll show u

spice seal
#

@vapid parcel dm maybe?

vapid parcel
#

Yeah hold on

zenith yarrow
#

How much to check if a message pinged me or not in discrod py

#

Like how
If ...

naive briar
unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

viscid hornet
viscid hornet
viscid hornet
#

!tb

#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

viscid hornet
#

there

glossy flame
viscid hornet
glossy flame
#

of the console?

#

all it does is print from the print statement at the end of the sell command

robust fulcrum
glossy flame
#

await SellOrNo().wait()
?

robust fulcrum
#

as its a coroutine

glossy flame
#

oh im not worried about that rn but thanks anyways

quick gust
#

try printing out the type() of card_number

#

try printing the rest of the variables too

#

see if they have the data as u expect

glossy flame
#

alright but im confident they are correct

#

huh....

#

print(card_name.type(), card_number.type(), card_value.type(), user_id.type())
is this right?

#

im doing that but nothing is printing

quick gust
#

no

#

u need to do type(card_name)

glossy flame
#

ahh

#

i rarely use that

quick gust
#

I wonder why it still isn't raising an error, do u have an error handler?

glossy flame
#

yes

#

this was the case with another command aswell

quick gust
#

can u send that?

glossy flame
#

wait

quick gust
#

problem perhaps lies there

glossy flame
#

i dont have an error handler

quick gust
#

oh

naive briar
#

Consistency

glossy flame
#

no error handler in this command

quick gust
#

do you have a general error handler?

glossy flame
#

Output: <class 'str'> <class 'str'> <class 'int'> <class 'int'>

#

just as it should be

glossy flame
#

like if i miss a bracket its not like it wont tell me

quick gust
#

I'm pretty sure the error is just being suppressed somewhere because u calling type() shouldve also raised an error

quick gust
glossy flame
#

right

#

what do you mean by its being suppressed? ive never heard of this before

quick gust
#

I'll try to look more if u wanna send the entire code to me in dms

glossy flame
#

the entire thing

#

thers a lot

#

626 in total

quick gust
quick gust
glossy flame
#

626 gb

quick gust
#

what- πŸ’€

glossy flame
#

jk 626 lines but the first half is just extra stuff

quick gust
#

lmao okay then use

#

!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.

quick gust
#

u can add different files here too

glossy flame
#

should i just include the relevant things?

#

like, just the stuff for the cards game

quick gust
#

well you might miss out the important part accidentally

#

Β―_(ツ)_/Β―

glossy flame
#

hmmm alright

quick gust
#

upto you

glossy flame
#

just dont plagiarise my code

quick gust
#

I won't πŸ’€

glossy flame
quick gust
#

as expected

glossy flame
#

what is it

quick gust
#
@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.CommandOnCooldown):
    await ctx.channel.send(f"This command is on cooldown, retry in {error.retry_after:.2f}s")```
#

after this if statement, add

else:
  raise error
glossy flame
#

wow

#

i never would have guessed

#

finally

quick gust
#

what error did it raise?

glossy flame
#

here is the error:
Traceback (most recent call last):
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\iront\PycharmProjects\CBX\main.py", line 603, in sell
await ctx.channel.send(embed=embed, view=SellOrNo(card_name, card_number, card_value, user_id))
File "C:\Users\iront\PycharmProjects\CBX\main.py", line 540, in init
print(user_cards[card_number])
TypeError: list indices must be integers or slices, not str

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\iront\PycharmProjects\CBX\main.py", line 172, in on_command_error
raise error
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str

hushed galleon
glossy flame
quick gust
#

yeah what confirmed it was an error handler was, the error not being rased when he called type() on an integer

quick gust
glossy flame
#

as intended...

quick gust
hushed galleon
# glossy flame sorry

well now you can enjoy debugging your code with error messages and tracebacks instead of guessing what's broken :)

glossy flame
#

but the thing is i dont know how to fix cuz

quick gust
#

same, thats why i asked u to print the types

glossy flame
#
{"675798876858482731": {"cards": [{"number": "077", "amount": 1}, {"number": "021", "amount": 1}, {"number": "096", "amount": 1}, {"number": "066", "amount": 1}, {"number": "113", "amount": 1}, {"number": "112", "amount": 1}], "rings": 1000}```
quick gust
glossy flame
#

well it depends

#

its the given number

quick gust
#

before indexing

glossy flame
#

card number is the 3 digit one

#
        user_cards = user_data[str(user_id)]["cards"]
        print(user_cards[card_number])
        selling_card = user_cards[card_number]
        user_rings = user_data[str(user_id)]["rings"]```

printing user_cards will give the list, but it wont know which like item in the string that the number its looking for is in
#

this hurts my head

hushed galleon
#

remember that lists can only be indexed starting from 0, 1, 2, ... but dictionaries can be indexed by each key it has - if you want to be able to index by card number, the card numbers need to be keys in a dictionary rather than a list

glossy flame
#

ik what ur saying is to do like
user_cards[integer]["card_number"]
but idk how to get that integer unless it makes some loop to run through all the items in user_cards and see if number is equal to the given number and if it is then assign that value to the variable but idk how to do that

glossy flame
hushed galleon
#

yes

glossy flame
#

user_id should have the children cards and rings
and for every card in cards, it should have children number and amount

glossy flame
hushed galleon
#

i guess you can write a little migration script to read the file, replace the lists with dictionaries, and write it back

afterwards make sure your bot is storing dictionaries instead of lists

glossy flame
#

ok first of all how do i change the dictionary to look better cuz rn it all in one line

hushed galleon
glossy flame
#

headache

#

{"675798876858482731": {"cards": {{"number": "077", "amount": 1}, {"number": "021", "amount": 1}, {"number": "096", "amount": 1}, {"number": "066", "amount": 1}, {"number": "113", "amount": 1}, {"number": "112", "amount": 1}}, "rings": 1000}, "590190033495916595": {"cards": {{"number": "044", "amount": 1}, {"number": "071", "amount": 1}, {"number": "085", "amount": 1}, {"number": "014", "amount": 1}, {"number": "125", "amount": 1}, {"number": "092", "amount": 1}}, "rings": 1000}, "696309271524147251": {"cards": {{"number": "034", "amount": 1}, {"number": "057", "amount": 1}, {"number": "012", "amount": 1}, {"number": "123", "amount": 1}, {"number": "038", "amount": 1}, {"number": "106", "amount": 1}, {"number": "130", "amount": 1}}, "rings": 1000}}
i tried to change it myself by changing all the []s to {}s

#

but it didnt work

#
  "675798876858482731": {
    "cards": [
      {
        "number": "077",
        "amount": 1
      },
      {
        "number": "021",
        "amount": 1
      },
      {
        "number": "096",
        "amount": 1
      },
      {
        "number": "066",
        "amount": 1
      },
      {
        "number": "113",
        "amount": 1
      },
      {
        "number": "112",
        "amount": 1
      }
    ],
    "rings": 1000
  },
  "590190033495916595": {
    "cards": [
      {
        "number": "044",
        "amount": 1
      },
      {
        "number": "071",
        "amount": 1
      },
      {
        "number": "085",
        "amount": 1
      },
      {
        "number": "014",
        "amount": 1
      },
      {
        "number": "125",
        "amount": 1
      },
      {
        "number": "092",
        "amount": 1
      }
    ],
    "rings": 1000
  },
  "696309271524147251": {
    "cards": [
      {
        "number": "034",
        "amount": 1
      },
      {
        "number": "057",
        "amount": 1
      },
      {
        "number": "012",
        "amount": 1
      },
      {
        "number": "123",
        "amount": 1
      },
      {
        "number": "038",
        "amount": 1
      },
      {
        "number": "106",
        "amount": 1
      },
      {
        "number": "130",
        "amount": 1
      }
    ],
    "rings": 1000
  }
}```
this the original
viscid hornet
glossy flame
#

an actual database?

#

id rather make all the changes now rather than have to in the future for ease, how do you mean by actual database?

glossy flame
#

uhhhh in cs class yeah but i dont really get it

viscid hornet
#

it's not really that difficult to get the basics and I have a gist on it (self promo ✨)

viscid hornet
#

@hushed galleon which of these is a good idea? py card = cards[cards.index({'number': '007', 'amount': 1}}] py card = [card for card in cards if card['number'] == '007'][0]

hushed galleon
glossy flame
#

i have one more json file which hsa the information for all the cards, do you recommend to change that to sql too?

viscid hornet
glossy flame
#

indeed

glossy flame
viscid hornet
#

the tables look like excel spreadsheets when you look at them

#

so you can have a table for cards, a table for inventory, etc

hushed galleon
viscid hornet
glossy flame
#

wow i wish i heard of this sooner

hushed galleon
#

(ignore the capitalization inconsistencies in the table names)

viscid hornet
viscid hornet
glossy flame
#

is it gonna take long to finish the sqlbolt

#

i am stuck on lesson 2 (this is gonna take ages)

hushed galleon
#

i think sqlbolt lacks exercises for the other side of SQL, which is knowing how to model data with tables

#

you need to practise it on something practical, like storing custom guild prefixes or tracking wins/losses in a minigame

glossy flame
#

so you always put the semicolon at the end of the qury

hushed galleon
#

generally yes, but it becomes optional when you start using python libraries like sqlite3 or aiosqlite or asqlite to run queries

glossy flame
#

which ill have to do if i switch from json to sql anyways

#

i have idea

#

for now, ill use json and in the meantime ill learn sql, then practice on something like tracking wins/losses then when im ready ill switch

#

but i still want to get this sell function to work...

quick gust
#

whats the issue rn?

glossy flame
#

Using the for loop, it sends the embed and it knows the card but after sending the embed it will say this:

Traceback (most recent call last):
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\iront\PycharmProjects\CBX\main.py", line 172, in on_command_error
raise error
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: SellOrNo.init() missing 4 required positional arguments: 'card_name', 'card_number', 'card_value', and 'user_id'

#

it says its missing the 4 arguments, but the arguments were given and it had to have been or else the embed wouldnt have sent containing information OF the given arguments

quick gust
#
Error handling request
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
    messages, upgraded, tail = self._request_parser.feed_data(data)
  File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
  Invalid method encountered:

    b'\x03'
      ^
Error handling request
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
    messages, upgraded, tail = self._request_parser.feed_data(data)
  File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
  Invalid method encountered:

    b'\x16\x03\x01'
      ^
Error handling request
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
    messages, upgraded, tail = self._request_parser.feed_data(data)
  File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
  Invalid method encountered:

    b'\x16\x03\x01'```
#

what are these errors and how do i fix

upbeat otter
quick gust
#

im using disnake (latest ver)

glossy flame
#

who

viscid hornet
viscid hornet
#

i doubt nextcord, pycord, disnake, etc has user app support

#

might be wrong shrug

quick gust
quick gust
hushed galleon
#

the API's in preview after all, it'd be annoying to release it only for discord to make a breaking API change and cause all libraries to bump a major version

upbeat otter
quick gust
#

how are you so sure its from disnake?

glossy flame
# viscid hornet wheres the section of code that raises this error?

im not sure but it has to be in either here:

class SellOrNo(discord.ui.View):
    def __init__(self, card_name, card_number, card_value, user_id):
        super().__init__()


        with open("user_data.json", 'r') as f:
            user_data = json.load(f)


        user_cards = user_data[str(user_id)]["cards"]
        for card in user_cards:
            if card["number"] == card_number:
                selling_card = card
        user_rings = user_data[str(user_id)]["rings"]


        self.card_name = card_name
        self.card_value = card_value
        self.card_number = selling_card
        self.user_rings = user_rings
        self.user_cards = user_cards
        self.user_data = user_data

    @discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
    async def yes(self, interaction: discord.Interaction, value):

        self.user_cards.remove(self.card_number)
        self.user_rings += self.card_value

        with open("user_data.json", 'w') as f:
            json.dump(self.user_data, f)

        await interaction.response.send_message(f"Sold {self.card_name} [{self.card_number}] for {self.card_value} Rings!")
        self.stop()

    @discord.ui.button(label="No", style=discord.ButtonStyle.red)
    async def no(self, interaction: discord.Interaction, value):
        await interaction.response.send_message("Cancelled.")
        self.stop()```

or here:
#
@bot.command(
    name="sell"
)
async def sell(ctx, given_card):
    user_id = ctx.message.author.id

    with open("user_data.json", 'r') as f:
        user_data = json.load(f)

    with open("cards.json", 'r') as c:
        cards = json.load(c)

    if str(user_id) not in user_data:
        user_data[str(user_id)] = {"cards": [], "rings": 1000}

    user_cards = user_data[str(user_id)]["cards"]


    for user_card in user_cards:
        card_number = user_card["number"]
        card_amount = user_card["amount"]

        for card in cards:
            if card["number"] == card_number:
                card_number = card["number"]
                card_name = card["name"]
                card_value = card["value"]
                if card_number == given_card:
                    embed = discord.Embed(title=f"Are you sure you want to sell *{card_name}*?", description=f"Selling one copy of *{card_name}* will return with {card_value} Rings.", color=0xFFC0CB)
                    embed.add_field(name="", value=f"Selling cards will permanently remove them from your inventory.")
                    print(type(card_name), type(card_number), type(card_value), type(user_id))

                    await ctx.channel.send(embed=embed, view=SellOrNo(card_name, card_number, card_value, user_id))
                    await SellOrNo().wait()```
hushed galleon
#

the lower half of that traceback comes from CommandInvokeError, it's not as important as the upper half that should have shown the exact line where the TypeError occurred

#

but regardless the last line there, await SellOrNo().wait(), is probably where it occurred

viscid hornet
#

thats your issue

quick gust
#

the second instance is missing the arguments

hushed galleon
#

it doesnt look like you need to wait on it, but either way, you need the same view instance that you created and passed to send(view=) in order to wait on it

viscid hornet
quick gust
#

yeah

hushed galleon
glossy flame
#

right...

viscid hornet
#

(in a test file)

glossy flame
#

thank you, but i think there is a logic error as the card has been removed but my rings value in the json didnt increase by the same amount of the cards value

#

and there is no error

upbeat otter
viscid hornet
#

try replacing this py class Example: def __init__(self): user_rings = ... self.user_rings = user_rings
with this instead py class Example: def __init__(self): self.user_rings = ...

viscid hornet
glossy flame
#

ohhh right i get it

#

hm... it didnt work

#
    def __init__(self, card_name, card_number, card_value, user_id):
        super().__init__()


        with open("user_data.json", 'r') as f:
            user_data = json.load(f)


        user_cards = user_data[str(user_id)]["cards"]
        for card in user_cards:
            if card["number"] == card_number:
                selling_card = card


        self.card_name = card_name
        self.card_value = card_value
        self.card_number = selling_card
        self.user_rings =  user_data[str(user_id)]["rings"]
        self.user_cards = user_cards
        self.user_data = user_data```
quick gust
slate swan
#
        userid = interaction.user.id
        email = self.inputemail.value

        data = read_json("users")
        for user in data['users']:
            if user['id'] == userid:
                user['email'] = email
                self.email_set_event.set()
                self.stop()
                return
        else:
            await interaction.response.send_message("User not found", ephemeral=True)
            return
        
    async def on_cancel(self, interaction: discord.Interaction):
        await interaction.response.send_message("Cancelled", ephemeral=True)
        return```
#

how do i close out of the modal after self.stop()

viscid hornet
slate swan
#

after i submit it and it does self.stop() it doesnt close out of the modal

#

it keeps it open

slate swan
viscid hornet
#

or submit it

#

afaik just close out of the modal yourself. it'll block your screen and prevent you from using the app so users will instinctively want to click out

slate swan
#

alright thanks

eager drift
#

@viscid hornet yo I got a question, where/ if you do/ do you host like discord bots

#

for free, cuz I am trying to figure out a way to host my bot on some server for free, I found 1 website but my bot doesnt work onit and so I am here asking you for rec

viscid hornet
eager drift
viscid hornet
eager drift
#

what is that

slate swan
#

@viscid hornet is it possible to keep editing messages?

slate swan
#

like let me send u my code because im keep getting like discord.errors.InteractionResponded: This interaction has already been responded to before

#
    inputemail = discord.ui.TextInput(style=discord.TextStyle.short, required=True, label="Email Address", placeholder='Enter your email address', min_length=1, max_length=100)

    email_set_event = asyncio.Event()

    async def on_submit(self, interaction: discord.Interaction):
        userid = interaction.user.id
        email = self.inputemail.value

        data = read_json("users")
        for user in data['users']:
            if user['id'] == userid:
                user['email'] = email
                write_json(data, "users")
                await interaction.response.defer()
                embed = discord.Embed(title="Email Set", description="Email set successfully", color=discord.Color.green())
                await interaction.edit_original_response(embed=embed, view=None)
                self.email_set_event.set()
                self.stop()
        else:
            await interaction.response.send_message("User not found", ephemeral=True)
            return
        
    async def on_cancel(self, interaction: discord.Interaction):
        await interaction.response.send_message("Cancelled", ephemeral=True)
        return

    

    @app_commands.command(name="buy", description="Buy gifting credits")
    async def buy(self, interaction: discord.Interaction):
        class PaymentMethodSelect(discord.ui.Select):
            def __init__(self):
                super().__init__(
                placeholder="Payment Method",
                min_values=1,
                max_values=1,
                options=[
                    discord.SelectOption(label="Test"),
                ],)

            async def callback(self, interaction: discord.Interaction):
                selected_method = self.values[0]
                if selected_method == "Test":

                    if not check_email(interaction.user.id):
                        await interaction.response.send_modal(SetEmail())
                        await SetEmail.email_set_event.wait()

                    embed = discord.Embed(title="Test", description="Click the button below to pay with Test", color=discord.Color.dark_theme())
                    
                    await interaction.response.edit_message(embed=embed, view=None)
                    return

        class PaymentMethodView(discord.ui.View):
            def __init__(self):
                super().__init__(timeout=None)
                self.add_item(PaymentMethodSelect())
        

        embed = discord.Embed(title="Payment Method", description="Select a payment method", color=discord.Color.dark_theme())

        await interaction.response.send_message(embed=embed, view=PaymentMethodView())```
#

@viscid hornet so like when i have a email in the json it shows embed = discord.Embed(title="Test", description="Click the button below to pay with Test", color=discord.Color.dark_theme()) which i want and when i dont have a email in, it shows the modal and when i put it in it returns embed = discord.Embed(title="Email Set", description="Email set successfully", color=discord.Color.green()) and i want it to edit the message also to show the Click the button below to pay with Test but i keep getting discord.errors.InteractionResponded: This interaction has already been responded to before

viscid hornet
slate swan
viscid hornet
slate swan
tulip ice
#

how do u update a deferred message? i want to send file

glad cradle
tulip ice
glad cradle
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
slate swan
#

@viscid hornet i keep getting this discord.errors.InteractionResponded: This interaction has already been responded to before

#

here im send the updated code

#
class SetEmail(discord.ui.Modal, title='Set Email'):
    inputemail = discord.ui.TextInput(style=discord.TextStyle.short, required=True, label="Email Address", placeholder='Enter your email address', min_length=1, max_length=100)

    email_set_event = asyncio.Event()

    async def on_submit(self, interaction: discord.Interaction):
        userid = interaction.user.id
        email = self.inputemail.value

        data = read_json("users")
        for user in data['users']:
            if user['id'] == userid:
                user['email'] = email
                write_json(data, "users")
                await interaction.response.defer()
                embed = discord.Embed(title="Email Set", description="Email set successfully", color=discord.Color.green())
                await interaction.followup.send(embed=embed, ephemeral=True)
                self.email_set_event.set()
                self.stop()
        else:
            await interaction.response.send_message("User not found", ephemeral=True)
            return
        
    async def on_cancel(self, interaction: discord.Interaction):
        await interaction.response.send_message("Cancelled", ephemeral=True)
        return

    @app_commands.command(name="buy", description="Buy gifting credits")
    async def buy(self, interaction: discord.Interaction):
        class PaymentMethodSelect(discord.ui.Select):
            def __init__(self):
                super().__init__(
                placeholder="Payment Method",
                min_values=1,
                max_values=1,
                options=[
                    discord.SelectOption(label="Test")
                ],)

            async def callback(self, interaction: discord.Interaction):
                selected_method = self.values[0]
                if selected_method == "Test":

                    if not check_email(interaction.user.id):
                        await interaction.response.send_modal(SetEmail())
                        await SetEmail.email_set_event.wait()

                    embed = discord.Embed(title="Test Payment", description="Click the button below to pay with Test", color=discord.Color.dark_theme())
                    
                    await interaction.response.defer()
                    await interaction.followup.send(embed=embed, ephemeral=True)
                    return

        class PaymentMethodView(discord.ui.View):
            def __init__(self):
                super().__init__(timeout=None)
                self.add_item(PaymentMethodSelect())
        

        embed = discord.Embed(title="Payment Method", description="Select a payment method", color=discord.Color.dark_theme())

        await interaction.response.send_message(embed=embed, view=PaymentMethodView())
slate swan
# viscid hornet what line

in the callback where it says await interaction.response.defer() await interaction.followup.send(embed=embed, ephemeral=True)

viscid hornet
viscid hornet
slate swan
#

okay

#

okay it worked when there is no email and i set he email it return the embed and it said email set and returned also another embed with Test Payment

#

but when i do the command again and it click it with it email set i get discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

#

@viscid hornet

viscid hornet
#

try just await inter.resp.send()

#

without deferring

slate swan
viscid hornet
slate swan
#

okay

#

okay when it set the email it sent that but it didnt send the test payment and i got a error

slate swan
slate swan
viscid hornet
#

foolproof

slate swan
#

okay let me try it

glad cradle
#

He could solve that refactoring a bit the code

glad cradle
slate swan
midnight oracle
#

Can I use the wait_for() inside of a Cog?? Because this is giving me an error:

import discord
from discord.ext import commands
from discord import app_commands


class Avatar(commands.Cog):
    def __int__(self, bot) -> None:
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, member: discord.Member) -> None:
        await member.send(f"Welcome, write your name")
        name = await self.bot.wait_for('message', check = lambda message: message.author == member and message.channel == member.dm_channel)
        
ERROR      - discord.client  : Ignoring exception in on_member_join
Traceback (most recent call last):
  File "/home/codespace/.python/current/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/workspaces/AdeptusStudio-PyBot/cogs/comunity/avatar.py", line 13, in on_member_join
    name = await self.bot.wait_for('message', check = lambda message: message.author == member and message.channel == member.dm_channel)
AttributeError: 'Avatar' object has no attribute 'bot'
glad marsh
#

anyone recommend any hosting sites

leaden olive
viscid hornet
viscid hornet
#

your reason is also already a string so you don't have to do f"{...}"

viscid hornet
#

is there an update in the database?