#Basic Pycord Help (Quick Questions Only)

1 messages · Page 43 of 1

green hinge
#

No nothing

young bone
#

no def init?

green hinge
limber urchin
#

You don't have an init method in your class, and you never call init on the superclass

vapid pumice
#

can client.run and bot.run be executed in the same script?

young bone
vapid pumice
limber urchin
#

Why do you have both client and bot?

#

anything you can do with client you can also do with bot, there is no reason to have both, and it will obviously break your entire code

green hinge
#

If I have a list l=[]
And this list is sometimes filled l=[[P]] and sometimes so l=[[]].
How can I check in an if query if the list has a content or not?

limber urchin
#

just check the length?

green hinge
#

What am I doing wrong?

async def get_qmark(user):
    user = user.lower()
    qmark = []
    async with aiosqlite.connect(DB) as db:
        async with db.execute(
                f"SELECT qmark FROM qmark WHERE user = ? ", (user,)
        ) as cursor:
            async for row in cursor:
                qmark.append(row[0])
            if len(qmark) == 0:
                qmark = ""
            else:
                qmark = qmark[0]

    return qmark```
limber urchin
#

are you getting any errors?

green hinge
#

TypeError: object of type 'type' has no len()

limber urchin
#

type 'type'?

green hinge
#

I do not know that is in the console

limber urchin
#

and what is row[0]?

green hinge
#

So I select from the DB actually always only one thing and it is always only in a letter such as P, L, B, etc..
I think you can solve the whole thing maybe somehow better than how I did it?

As return I would like at the end only the letter or a -.

limber urchin
#

Well I am not going to write code for you

green hinge
#

If I fechtone() the cursor how can I take the content out of there or check if there is content in there?

limber urchin
#

You can check if the result is an instance of sqlite3.Row

green hinge
#

I don't know 😄

limber urchin
#

?

viscid rapids
#

can multiple @ options be defined?

limber urchin
#

yes

viscid rapids
#

OOPS

#

didn't mean to ping someone, sorry.

viscid rapids
# limber urchin yes
@discord.slash_command(guild_ids=config['main_guilds'], description="Mass deletes messages")
    @commands.has_permissions(manage_messages=True)
    @option("messages", description="Amount of messages to delete.")
    @option("member", description="Specific member to delete from.")

so this is valid right

limber urchin
#

yes

viscid rapids
#

great then, I must have an issue.

errant craneBOT
#

Here's the slash options example.

viscid rapids
#

this issue must be longer than I imagined, because that's what I've done yet it doesn't work.

limber urchin
#

Read rule 6 in #help-rules

viscid rapids
#

sorry.

#

I asked here because I thought it was a smaller issue, like not being able to do two options. But it seems bigger so I moved to a forum.

young bone
#

Also pls stay in one channel

viscid rapids
#

gotcha.

#

Bad etiquette sorry.

tired goblet
#

Hey, I'd like to make a bot that gives people points for chatting. So basically the more they chat, the more points they earn

proud cargo
#

How can I have my list of guild ids for a slash command be updated by another command? Can I just write it to an sql table then access that from a subroutine, and have guild_ids=subroutine()?

tired goblet
silver moat
young bone
limber urchin
proud cargo
tired goblet
#

And increment their points based on that?

tired goblet
#

Okay

limber urchin
#

You don't want to query a database on every message, so cache that data and write to the database on an interval or something

silver moat
proud cargo
#

Was about to say that yea

#

alright thanks

silver moat
#

because you can get rate-limited if you do register too many commands (200) in a day.

proud cargo
#

Yea I had that concern in mind, thats why i asked

tired goblet
#

Also i was thinking of something similar with voice chats too, so like the more time someone spends voice chatting the more points they earn. But i was concerned about people idling in the voice chat. If they just join a voice channel and go afk, i dont want them to earn points for that duration. Only active chat time.

silver moat
tired goblet
#

Oh

#

Oh

#

So at a time, one bot can only track people in one voice channel?

limber urchin
#

Just like a user can only be in one voice channel at a time

tired goblet
#

Oh i see

#

That makes sense

#

Thanks for the help guys, i think i can now draw a flow chart and start writing some code

silver moat
#

gl hf

limber urchin
silver moat
#

Well, one vc/guild/bot.

west vault
silver moat
west vault
silver moat
#

ah ok

west vault
#

would be fun tho if you could call with a bot kek

potent tendon
#

how do i check if a user has a certain role?

silver moat
potent tendon
#

i figured it out, but now im getting a response invalid interaction application command from the bot

#

nvm fixed it just somehow had two instances of the bot running

tiny wagon
#

:kekw:

rare ice
#

Right now I’m trying to come up with an idea of a reaction roles system using buttons with each button giving a customizable role from the database. I was thinking of using on_interaction for this since I can handle all callbacks for a reaction role message (from a check) in one. Is there another way of doing this that’s more efficient? Since I don’t want to have to create persistent views over and over again every time the bot starts up.

viscid rapids
#

is the max length allowed in ctx.respond shorter than ctx.send?

#

I noticed that certain messages don't send with ctx.respond that do with ctx.send

rare ice
#

If you mean character limit, it’s the exact same as they’re both classed as discord.Message

viscid rapids
rare ice
#

then #998272089343668364 message ?ref

winter condorBOT
viscid rapids
#

yes ik, i typed it before u said that, i have shit wifi

rare ice
#

All good :)

viscid rapids
#

well I'm having an issue, a certain message isn't being sent through respond that is thru ctx.send

rare ice
#

Could you please send your code and any errors you may have?

#

.paste

winter condorBOT
viscid rapids
#

thing is it's openai, so the responses are GPT, so it's not always going to be the same length.

#

hm wait yeah i can use a constant 1 sec.

rare ice
#

You could make a custom function to trim down the text to the character limit of a message (4029 iirc)

viscid rapids
rare ice
#

Could you please use pastebin? I don’t like clicking on sites that I don’t recognize for my safety.

winter condorBOT
viscid rapids
#

see here, im using a constant message to print out the alphabet 10 times? (26 x 10 = msg length). If I'm using ctx.send it obviously doesn't respond but prints the output.

viscid rapids
errant craneBOT
rare ice
#

For embeds, the character limit is 1024, so you’d need to meet that limit

viscid rapids
#

but if u see, when I use respond, there is actually no response, instead there is no response.

rare ice
#

I recommend using a custom function for trimming text for your use case as I mentioned #998272089343668364 message ?ref

winter condorBOT
viscid rapids
#

No dude, you don't understand. The embed is the same right? but if I use ctx.send() it sends, but not with ctx.respond

rare ice
#

Send your error like I said

viscid rapids
rare ice
#

Both functions are the same, but .respond completes the interaction

#

Send your code with the ctx.respond

viscid rapids
#

well it's exactly the same except im using await ctx.respond(embed=e)

#

do I seriosly need to send u the whole code for that?

rare ice
#

How long is the duration between you executing the command and you responding to it

viscid rapids
#

Ohhh right, respond times out after 3 seconds?

rare ice
#

Since you need to respond to an interaction within 4 seconds without deferring it

#

Yeah

viscid rapids
#

smart man smart man

rare ice
#

So use await ctx.defer()

#

.rtfm InteractionResponse.defer

winter condorBOT
viscid rapids
#

oh? I figured I could send "processing" and then edit it to reflect changes. that way the person doesn't think it's broken?

#

ctx.respond(processing) and then edit

rare ice
#

I recommend deffering

viscid rapids
#

alright.

rare ice
#

So it shows the 'Bot is thinking…' state

viscid rapids
#

ohh true

#

smart man

proud mason
#

You need to send the view along with some message content. Also bot.command is a Slash command if you are using discord.Bot .
You also don't respond to both the Slash cmd and the select menu interaction

viscid rapids
#

@rare ice no error this time but this.

rare ice
#

From what it looks like, you’re using an api such as openai, perhaps there is an error there?

#

Oh that’s not how you do it

proud mason
#

Defer the first thing in the call back

rare ice
#

You need to defer at the first line of your callback

viscid rapids
#

ohhhhh

#

sorry dude, that makes sense lol

rare ice
#

Such as ```py
await ctx.defer()

response

#

All good

viscid rapids
rare ice
#

I might be wrong

#

Oh yeah it is 4096 mb

viscid rapids
#

wait wait mb as in "my bad" or "mega bytes"?

#

just need to clarify.

rare ice
viscid rapids
rare ice
#

You’re good

meager heron
#

Is it possible to run a bot from an IPv6-only network?

viscid rapids
#

is there like an event to check if a member ran a slash command? specifically one of it's own slash commands

viscid rapids
silver moat
#

no, I'm afraid not.

viscid rapids
#

like discord.on_application_command()

#

is this specifically the bots application, or any bots?

silver moat
#

.rtfm on_application_command

silver moat
viscid rapids
#

k ty

viscid rapids
# silver moat just for your bot

wait so, I'm trying to check if a user id matches something, and then stop them from using all commands. I can give an ouput, but the command still works. Is there a way to cancel the command?

viscid rapids
#

it still goes through with the cmd

proud mason
viscid rapids
proud mason
viscid rapids
proud mason
#

And cog checks

#

Try looking for them in the docs

viscid rapids
#

oh ok ty

vapid pumice
sinful pivot
#

I hve a command that I respond to using ctx.respond I want to know how I can edit the responded message since the following code doesn't work: py msg = await ctx.respond(embed=em) await msg.edit(embed=em2)

#

Also if someone responds please ping me

steep bloom
#

Hello RedPanda does anyone know any good Python ML API , just something where it can take some text and based on some preference it can determine how much I'd approve or disapprove of this text ?

proud mason
#

Use edit_original_response

#

.rtfm edit_original_response

winter condorBOT
limber urchin
#

what?

#

I don't know? You sent half of the stacktrace with no code or explanation

wind jay
#

hi this is my code:

people = []

if len(people) != 0:
  peoplestr = "\n".join(people)

people is a list with member objects. and i want to build a str with all the member.names but i cant do "\n".join(people.name)

how can i do it?

limber urchin
proud mason
#

.embed limits

winter condorBOT
#

field amount = 25, title/field name = 256, value = 1024, description = 4096, footer text = 2048
Note that the sum of all characters in the embed should be less than or equal to 6000.

proud mason
#

@chrome skiff ^

#

\n is just 1 character (a newline character)

#

So 4096/8

#

About 512 lines ig

limber urchin
#

32 characters

proud mason
#

Holy shit I just sent an embed with 2048 lines of "E" and it just went on forever lmao

#

4096/32

#

Ah

#

No \n is just 1 character

proud mason
#

Mhm

#

You can use a paginator

#

There is pages ext in pycord

#

.rtfm ext.pages

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

proud mason
#

Pff it's on the docs

#

Why tho

#

Yeah

#

It's a cool ext

#

Hmm

#

Have you tried "reading the error"

#

Error and code?

#

Also fix this first

#

Send full traceback

#

Also the code seems to be different from the error you sent

#

I can't see ctx.respond in the code you sent

#

Also don't use requests

#

.aiohttp

#

?tag aiohttp

obtuse juncoBOT
#

Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(http://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean)

discord.py uses aiohttp, so it should already be installed. An example of code using aiohttp and discord.py:

async with aiohttp.ClientSession() as cs:
    async with cs.get('https://httpbin.org/json%27') as r:
        res = await r.json()  # returns dict
        await ctx.send(res['slideshow']['author']) 

For more help, see aiohttp's documentation: <http://aiohttp.readthedocs.io/en/stable/>

proud mason
#

requests is fine for non asynchronous projects. But it will block the event loop for async ones

errant craneBOT
limber urchin
#

The error explains it all

#

id is positional only, and you're passing it as a keyword arg

fervent cradle
#
            if interaction.channel.id == TICKET_CHANNEL:
                guild = bot.get_guild(GUILD_ID)
                for ticket in guild.channels:
                    if str(interaction.user.id) in ticket.name:
                        embed = discord.Embed(title=f"You can only open one Ticket!", description=f"Here is your opened Ticket --> {ticket.mention}", color=0xff0000)
                        await interaction.response.send_message(embed=embed, ephemeral=True)
                        return

                category = bot.get_channel(CATEGORY_ID1)
                ticket_channel = await guild.create_text_channel(f"ticket-{interaction.user.id}", category=category,
                                                                topic=f"Ticket from {interaction.user} \nUser-ID: {interaction.user.id}")

                await ticket_channel.set_permissions(guild.get_role(TEAM_ROLE1), send_messages=True, read_messages=True, add_reactions=False,
                                                    embed_links=True, attach_files=True, read_message_history=True,
                                                    external_emojis=True)
                await ticket_channel.set_permissions(interaction.user, send_messages=True, read_messages=True, add_reactions=False,
                                                    embed_links=True, attach_files=True, read_message_history=True,
                                                    external_emojis=True)
                await ticket_channel.set_permissions(guild.default_role, send_messages=False, read_messages=False, view_channel=False)
                embed = discord.Embed(description=f'Welcome {interaction.user.mention}!\n'
                                                   'Hello, How can we help you?',
                                                color=0xe800ff)
                await ticket_channel.send(embed=embed)


                embed = discord.Embed(description=f'📬 Ticket was Created! Look here --> {ticket_channel.mention}',
                                        color=0xe800ff)

                await interaction.response.send_message(embed=embed, ephemeral=True)
                return```

How can i make this a certain role use only?
#

by that i mean, i only want verified people to be able to use it but not the unverified people.

limber urchin
fervent cradle
#

where i can learn coding

solemn idol
#

So I am making a log function in my bot, I managed to log messages etc. but would it be possible to log images / files and if, how would I do that?

serene spindle
#

How do you use discord.Interaction.followup? The docs say to use this when wanting to send more than 1 messages, which I want to do, but I can't figure out how to use it.

serene spindle
full basin
#

Then just interaction.followup.send

#

.rtfm interaction.followup

winter condorBOT
proud mason
winter condorBOT
# fervent cradle where i can learn coding
proud mason
#

You can get them from over there

solemn idol
#

Oh, thanks.

silver moat
#

show code

#

.slashnoshow

winter condorBOT
#

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

silver moat
#

confirm this checklist

#

?tag application.commands

obtuse juncoBOT
#

dynoError No tag application.commands found.

silver moat
#

?tag missing-access

obtuse juncoBOT
#

dynoError No tag missing-access found.

silver moat
#

?tag missing_access

obtuse juncoBOT
silver moat
#

or in short, re-invite your bot

#

also show code.

serene spindle
silver moat
#

@fervent cradle ?

#

also show code.

#
debug_guilds=[1052587155471474798, 1034903696271753266]

Is the bot in both of these servers?

lost lodge
#

Hello, does anyone have an idea, how i could check if someone got an uprank or an downrank

limber urchin
#

What is an "uprank" and "downrank"?

fervent cradle
#

hello guys

#

how can i do this slash command

#

async def deneme(ctx, ad="", soyad=""):
response = requests.get(f"api/ad={ad}&soyad={soyad}")
file = open(ad + ".txt", "w", encoding="utf-8")
file.write(str(json.dumps(response.json(), indent=2)).replace("/", "/").encode().decode('unicode_escape'))
file.close()
await ctx.send(file=discord.File(rf'{ad}.txt'))
os.remove(ad + ".txt")

lost lodge
#

an uprank is when a user get's a role that is higher ranked than the one he had before, a downrank is the opposite

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
fervent cradle
#
async def deneme(ctx, ad="", soyad=""):
    response = requests.get(f"api/ad={ad}&soyad={soyad}")
    file = open(ad + ".txt", "w", encoding="utf-8")
    file.write(str(json.dumps(response.json(), indent=2)).replace("\/", "/").encode().decode('unicode_escape'))
    file.close()
    await ctx.send(file=discord.File(rf'{ad}.txt'))
    os.remove(ad + ".txt")
limber urchin
fervent cradle
#

how can i do this slash command

limber urchin
#

Look at the docs and examples

fervent cradle
#

please help me

limber urchin
#

I'm not going to write code for you

fervent cradle
#

I'm not dealing with

limber urchin
#

?

fervent cradle
limber urchin
fervent cradle
limber urchin
fervent cradle
#

help me

limber urchin
#

How am I supposed to help you if you don't tell me what's wrong?

fervent cradle
limber urchin
#

And what is "secret message mode"?

fervent cradle
limber urchin
#

Then I can't help you

fervent cradle
#

what should i add

limber urchin
limber urchin
wind jay
#
@tasks.loop(minutes=10) 
async def sortchannels():
    await bot.wait_until_ready()

    zugeteilt1 = bot.get_channel(categoryid)
    

    channels1 = zugeteilt1.channels
    sorted_channels = sorted(channels1, key=lambda c: c.name)

    print(channels1)
    print(sorted_channels)

    if channels1 == sorted_channels:
        print("pass channels1")
        pass
    else:
        for i, channel in enumerate(channels1):
            print(i, channel.position)
            if channel.position != i:
                print(channel.position, i)
                await asyncio.sleep(1)
                await channel.edit(position=i)

can anyone help me? this isnt working and i am getting no error. it doesent do print(channel.position, i) but it isnt sorted correctly?

solemn idol
#

So is there any way to prevent the "RuntimeError: Event loop is closed" error when using client.close() ?

fervent cradle
limber urchin
fervent cradle
limber urchin
wind jay
limber urchin
fervent cradle
#

is this?

wind jay
#

we dont know your guild id

limber urchin
#

I don't know? Try it and see

fervent cradle
#

how do i get away from this

limber urchin
#

Get away from what?

fervent cradle
wind jay
limber urchin
fervent cradle
#

we don't know what guild id is

limber urchin
#

??????

fervent cradle
#

yes

#

help me

limber urchin
#

If you can't ask a proper question, leave

#

nothing you're saying is making sense

fervent cradle
limber urchin
wind jay
fervent cradle
limber urchin
limber urchin
solemn idol
limber urchin
#

try except?

wind jay
limber urchin
wind jay
#

spaxter can you help me?

limber urchin
#

Have you tried printing the index of the loop to see if your if check is true? Or checked if the sorting works as you think?

wind jay
limber urchin
#

Yeah? So your if statement is never true because all of those are equal

fervent cradle
#

payload = await super().send(content, **kwargs)
TypeError: _Context.send() got an unexpected keyword argument 'file'

#
@bot.command(
    name="deneme",
    description="This is the first command I made!",
    scope=1049907644892188753,
)
async def deneme(ctx, ad="", soyad=""):
    response = requests.get(f"https://api/AdSoyad.php?Name={ad}&Surname={soyad}")
    file = open(ad + ".txt", "w", encoding="utf-8")
    file.write(str(json.dumps(response.json(), indent=2)).replace("\/", "/").encode().decode('unicode_escape'))
    file.close()
    await ctx.send(file=discord.File(rf'{ad}.txt'))
    os.remove(ad + ".txt")
#

error code:

#

Task exception was never retrieved
future: <Task finished name='Task-17' coro=<deneme() done, defined at C:\Users\api\Desktop\ArexOyunda\arexbot.py:26> exception=TypeError("_Context.send() got an unexpected keyword argument 'file'")>
Traceback (most recent call last):
File "C:\Users\api\Desktop\ArexOyunda\arexbot.py", line 36, in deneme
await ctx.send(file=discord.File(rf'{ad}.txt'))
File "C:\Users\api\Desktop\ArexOyunda\venv\lib\site-packages\interactions\client\context.py", line 445, in send
payload = await super().send(content, **kwargs)
TypeError: _Context.send() got an unexpected keyword argument 'file'

rare ice
solemn idol
astral mist
#

can i make it so the bot makes a webhook not me making a link and adding to code

silver moat
#

.rtfm create_webhook

astral mist
jaunty raft
#

Hey guys what am I doing here wrong?

#
Ignoring exception in view <View timeout=180.0 children=5> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='0HcZv1' emoji=None row=None>:
Traceback (most recent call last):
  File "/Users/BiBi/Library/Python/3.11/lib/python/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/Volumes/Exharddrive/discordprojects/booleanTest/main.py", line 168, in yes_callback
    await inner_interaction.message.edit(embeds=[embed], view=None, files=[])
  File "/Users/BiBi/Library/Python/3.11/lib/python/site-packages/discord/message.py", line 1455, in edit
    data = await self._state.http.edit_files(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/BiBi/Library/Python/3.11/lib/python/site-packages/discord/http.py", line 362, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
#
            view = discord.ui.View()
            verify = discord.ui.Button(label="Verify", style=discord.ButtonStyle.green)
            view.add_item(verify)
            async def verify_callback(interaction: discord.Interaction) -> None:
                if role in interaction.user.roles:
                    await interaction.response.send_message("You are already verified", ephemeral=True)
                else: # start
                    member = interaction.user
                    WELCOME_EMBED = discord.Embed(title="Challenge")
                
                    WELCOME_EMBED.add_field(
                        name="How to verify", value="Click one of the 5 buttons here under, check which one is the correct one that u see in the image.", inline=False)
                    words = []  # len must be 5
                    for _ in range(0, 5):
                        gen = await bot.generate()
                        words.append(gen)
                    verify_view = discord.ui.View()
                    
                    random_choice = random.choice(words)
                    generated_img = ImageCaptcha()
                    generated_img.write(random_choice, random_choice + ".png")
                    for word in words:
                        btn = discord.ui.Button(label=word, style=discord.ButtonStyle.grey)
                        if word == random_choice:
                            async def yes_callback(inner_interaction: discord.Interaction) -> None:
                                if inner_interaction.user != member:
                                    await interaction.response.send_message("This is not yours", ephemeral=True)
                                else:
                                    verify_view.stop()
                                    embed  =discord.Embed(title="all done", description="Successfully did the verification.", color=discord.Color.green())
                                    await inner_interaction.response.send_message("Test")
                                    await inner_interaction.message.edit(embeds=[embed], view=None, files=[])
                                    await member.add_roles(role, reason="Verification")
                            btn.callback = yes_callback
                        else:
                            async def no_callback(inner_interaction: discord.Interaction) -> None:
                                if inner_interaction.user != member:
                                    await interaction.response.send_message("This is not yours", ephemeral=True)
                                else:
                                    verify_view.stop()
                                    await inner_interaction.message.edit("INVALID.", view=None)

                            btn.callback = no_callback
                        verify_view.add_item(btn)
                    WELCOME_EMBED.set_image(url="attachment://{}.png".format(random_choice))
                    await interaction.response.send_message(embed=WELCOME_EMBED, view=verify_view, file=discord.File(f"./{random_choice}.png", f"{random_choice}.png"), ephemeral=True)
            verify.callback = verify_callback
            embed = discord.Embed(title="Verification", description="Welcome, please click the **Verify** button to verify.")
            await channel.send(embed=embed, view=view)
fervent cradle
#

anyway i can make a cooldown for a slash commands?

silver moat
errant craneBOT
#

Here's the cooldown example.

fervent cradle
#

nvm ty for link

solemn idol
#

what is the difference between client.run client.start and client.login ?

#

oh and client.connect

limber urchin
#

If you read the docs you will find out

solemn idol
fossil canopy
#
@discord.app_commands.command(name="addrole")
async def add(self, interaction : discord.Interaction): #target_user : discord.Member ,wanted_role : discord.Role):
    perms = False```
#

Raises : Extension 'cogs.role_manage' raised an error: TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>

limber urchin
#

It's not discord.Interaction, it's discord.ApplicationContext

silver moat
limber urchin
fossil canopy
#

I found out

#

sorry

#

pycord icon just looks better xD

royal pulsar
#

My "ctx" variable suddenly stopped working. No functions are being called from it:

Traceback (most recent call last):
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'respond'

#

And whenever I start up my bot, this error occurs:


Traceback (most recent call last):
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 534, in register_commands
    desynced = await self.get_desynced_commands(
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 360, in get_desynced_commands
    elif _check_command(cmd, match):
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 275, in _check_command
    as_dict = cmd.to_dict()
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 844, in to_dict
    "options": [o.to_dict() for o in self.options],
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 844, in <listcomp>
    "options": [o.to_dict() for o in self.options],
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\options.py", line 318, in to_dict
    "type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'
royal pulsar
#

Problem started when i configured a help command, and the error now wouldn't stop even after removing it

rare ice
#

@royal pulsar Please run pip freeze and send the output

royal pulsar
#

aiohttp==3.8.3
aiosignal==1.3.1
altgraph==0.17.3
async-generator==1.10
async-timeout==4.0.2
attrs==22.1.0
certifi==2022.9.24
cffi==1.15.1
charset-normalizer==2.1.1
cycler==0.11.0
exceptiongroup==1.0.0rc9
fonttools==4.34.4
frozenlist==1.3.3
future==0.18.2
h11==0.14.0
idna==3.4
joblib==1.1.0
kiwisolver==1.4.4
matplotlib==3.5.2
mpmath==1.2.1
multidict==6.0.3
numpy==1.23.1
outcome==1.2.0
packaging==21.3
pandas==1.4.3
pefile==2022.5.30
Pillow==9.2.0
psutil==5.9.2
py-cord==2.3.2
pyad==0.6.0
pycparser==2.21
pygame==2.1.2
pyinstaller==5.4.1
pyinstaller-hooks-contrib==2022.10
pyparsing==3.0.9
PySocks==1.7.1
python-dateutil==2.8.2
python-dotenv==0.21.0
pytz==2022.1
pywin32==305
pywin32-ctypes==0.2.0
scikit-learn==1.1.1
scipy==1.8.1
selenium==4.5.0
six==1.16.0
sniffio==1.3.0
sortedcontainers==2.4.0
sympy==1.10.1
threadpoolctl==3.1.0
trio==0.22.0
trio-websocket==0.9.2
typing_extensions==4.4.0
urllib3==1.26.12
wsproto==1.2.0
yarl==1.8.2

rare ice
rare ice
#

Try downgrading to 2.3.0 and see if it was an issue in that release

#

I use 2.3.0 and know it’s a stable release

silver moat
rare ice
#

Yeah

royal pulsar
#

2.3.0 results to the same error

Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1147, in on_connect
    await self.sync_commands()
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 629, in sync_commands
    registered_commands = await self.register_commands(global_commands, method=method, force=force,
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 529, in register_commands
    registered = await register("bulk", data, _log=False)
  File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 359, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body

Got this error when I downgraded to 2.0.0b7, a version I was using before

silver moat
#

the earliest release with the new permissions system was rc1

royal pulsar
#

It's the same error as 2.0.0b7

#

Update: I removed commands and it works fine

#

so the commands are causing something to happen

midnight torrent
#

Is there a way to update the choices of a slash command in runtime?

errant craneBOT
#

Here's the slash autocomplete example.

midnight torrent
#

oh i thought that was just for choices that already existed

eternal wing
#

This is probably stupid, but when a user interacts with my view i update the embed in the message, yet even then discord says the interaction failed, how do i stop that from happening

#

tried interaction.response.pong() but that didn't do the trick

winter condorBOT
rare ice
#

Send code

eternal wing
#
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Accept order", custom_id="Accept-order-button", style=discord.ButtonStyle.primary)
    async def button_callback(self, button, interaction):
        message = interaction.message

        embedL = message.embeds[0].copy()

        embed = discord.Embed(colour=discord.Colour.orange())

        embed.add_field(name=f"{embedL.fields[0].name}", value=f"{embedL.fields[0].value}")
        embed.add_field(name="Has been accepted by:", value=f"{interaction.user.mention}")
        embed.set_footer(text=f"{embedL.footer.text}")

        view = OrderFinishView()
        
        await interaction.response.pong()
        await message.edit(embed=embed, view=view)```
rare ice
#

Why are you ponging the response

#

Try deferring at the start of your code

eternal wing
#

It changes the embed and view on that message. Just don't know how to make discord think the interaction was ok

rare ice
eternal wing
#

on it

#

Ok that doesn't bring up any errors anywhere, thanks a lot!

royal pulsar
#

it also says In 3: Application command names must be unique

limber urchin
#

That means you're trying to register multiple commands with the same name

royal pulsar
#

problem is, none of my commands have the same name

#

im guessing there's another instance of my bot running somewhere

limber urchin
#

Resetting your token will close any running instances, but if you have an instance somewhere without knowing it you probably have bigger problems to deal with

royal pulsar
#

reset the token, the problem still exists

solemn idol
#

so for some reason which I do not understand, this part of my code:

@client.event
async def on_connect():
    print(colorama.Fore.YELLOW + f"\n     ---------\nStarting {client.user}\n     ---------\n")

@client.event
async def on_disconnect():
    print(colorama.Fore.RED + f"     ---------\nStopped {client.user}\n     ---------\n")
    try:
        os._exit(0)
    except:
        sys.exit(0)

Is disabling my help command or atleast, it is making it a "NoneType"...

Error:

line 33, in help
    cmd_help = client.get_application_command('help').mention
AttributeError: 'NoneType' object has no attribute 'mention'
#

if I remove the 2 event's it works fine.

limber urchin
#

Read the docs and you'll find out why

royal pulsar
limber urchin
#

Yes

royal pulsar
#

ok, so that's normal

#

and running any slash command results in the same error

#

I reduced it to one command, still doesn't work

In 1: Application command names must be unique

#

I've done some debugging:

I have 4 commands (including help command) but only 2 is found in the bot

#

fixed it:

changed @bot.slash_command to @commands.slash_command

#

I'd just like to know why it's like that

limber urchin
#

That's how they're decorated in cogs

royal pulsar
#

ok cool

#

also how do i make the help command activatable by slash commands?

solemn idol
royal pulsar
#

might as well make my own

gleaming falcon
#

Anyone know how to properly justify (ljust, etc) emoji? Seems it will add more spaces (I guess since it resolves as a single character sometimes but then the number of utf8 characters when printed)

These columns should all be aligned.

gleaming falcon
fervent cradle
#

How can i access my SQL database from a phpMyAdmin server?

undone mulch
#

I need some help I don't know my issue. I spammed prints but it isn't helping me. Basically when someone loses on the "green" or "blue" or "red" button it executes both if self.win_type == 1: and elif self.win_type == 0: in the async def update_embed(self): function.

#

It's running async def update_embed(self): twice somehow. And it's running the win / loss but I don't get it.

#

I am so confused.

fringe socket
#

How do I make a command that just uses numbers in the name?

fervent cradle
# rare ice Could you run `pip freeze` and send the output here?
aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.1.0
certifi==2022.12.7
charset-normalizer==2.1.1
discord-py-interactions==4.3.4
discord-py-slash-command==4.2.1
frozenlist==1.3.3
idna==3.4
multidict==6.0.3
mysql==0.0.3
mysql-connector-python==8.0.31
mysqlclient==2.1.1
protobuf==3.20.1
py-cord==2.3.2
requests==2.28.1
typing_extensions==4.4.0
urllib3==1.26.13
yarl==1.8.2
undone mulch
#

What happened to my question?

#

Did someone delete it...

fringe socket
#

No people just chat in here

blissful spear
#

am I blind or is it not possible to add users as interested to a scheduled event?

proud mason
#

Show code

#

And pip list

#

Uhm you might be rate limited

blissful spear
proud mason
#

Is it a shared host?

#

Or you might have hit the limit for maximum Slash cmd updates per day

#

Does your host have multiple discord bots with a single ip address?

#

Or do you have your own vps with you own ip address

#

They why are you using a pterodactyl panel?

fringe socket
proud mason
#

#883236900171816970

proud cargo
#

if someone has youtube linked to their discord account, is it possible to get heir youtube id

fringe socket
#

I don't think so

dusty linden
#

OAuth2 should get you enough data to get their ID.

fringe socket
#

Well yes, but that's a pain

#

But if you really want it you'll have to

real frost
#

If i will make a lot of persistence buttons, will this buttons influence performance of the bot?

obtuse juncoBOT
#

dynoError No tag PyNaCl found.

solemn idol
#

How would I be able to make a mute command (not timeout) which keeps track of when someone should be unmuted? For instance if I mute someone for 10 days, and my bot restarts within that time the timer would stop (obviously).

undone mulch
fervent cradle
#

.

undone mulch
#

Why not log the time the mute has started and log the duration of the mute. Then every so often checks if the time has run up and then executes off of that. So log the time the command was run, if the bot restarts have the bot check for all previously logged timers and start it up again. Furthermore when you're dealing with timers you probably shouldn't be actively restarting your bot.

#

Or just have something else keep track of the timer like an API or something.

fringe socket
#

Who just ghost pinged me

solemn idol
undone mulch
#

But it'll work.

fervent cradle
#

hey i asked this a while ago and still struggling any help?

undone mulch
#

It's best to use the timeout feature. It's easy, it's designed for what you want, etc.

fringe socket
#

I got a ping in here

#

But someone deleted it

#

Or edited it out

solemn idol
undone mulch
#

And why not in your case?

#

Timeout is a better option.

#

They can't rejoin your server and bypass it either.

#

Because now you gotta make a on_leave and on_join tracking with role persist. Just more work.

fringe socket
#

Is anyone going to admit to ghost pinging me

solemn idol
# undone mulch And why not in your case?

You see, the bot adds a role to a specific user on discord but I have a minecraft server which then links to people ingame making them muted too. and if ingame mutes then in discord it mutes too

undone mulch
#

Then just do the hard way ig 😄

#

Use database.

solemn idol
#

(I have no idea where to get started)

undone mulch
#

Then use json.

#

And don't even say json sucks because I've used it to store millions of text.

fervent cradle
#

.

undone mulch
#

It's not the best. But it works.

undone mulch
#

I've been waiting to for my question.

solemn idol
#

thx

undone mulch
fervent cradle
#

I doubt i can help but ill try

fervent cradle
undone mulch
#

So you wanna know how to add reactions or check the length of something?

undone mulch
fervent cradle
#

so len would work?

undone mulch
#

So you wanna detect if they reacted to two reactions?

fervent cradle
#

No ill show with a screenshot

undone mulch
#

Play doesn't exist

#

What lib you using

#

Or your own

fervent cradle
undone mulch
fervent cradle
#

If two options react with tick AND x

undone mulch
#

Did you make the options optional?

fervent cradle
#

Yeah

undone mulch
#

Hmmm

#

Just test for if choice2 was used.

#

Then void option 3, 4, 5, 6, 7, etc if option 1 or 2 weren't used.

#

I'm sure there is a better way but I don't really know a lot about slash commands.

fervent cradle
#

alright

undone mulch
#

To my knowledge can't you set the options to "None"

#

Then use an if statement to see if they have content

fervent cradle
undone mulch
#

.-. I've never used your music thingy before.

undone mulch
#

But then you will have a lot of if statements

fervent cradle
#

Yeah

undone mulch
#

Just make a for loop. Then iterate through them.

fervent cradle
undone mulch
#

Well make a for loop. Then a counter to see how many entries were entered.

#

If the counter >= 2 then do something.

#

I'm not sure what a better method would be tbh.

#

I'm not well knowledged in Slash Command options.

fervent cradle
#

I saw something on google with *options: str then checks if options > 10 then it wont work and all that stuff

#

not tried that tho

undone mulch
#

Well in the decorator you could put *, options: str

#

Then detect the arguments within options.

fervent cradle
undone mulch
#
@command.command
async def(self, ctx, *, options: str)
  if options > 2:
fervent cradle
#

Oh thank you, is *, having all options or smth

undone mulch
#

It's either *, options: str or options: str, *

#

But I think it's the first one.

#

And yeah the * is saying infinite arguments.

fervent cradle
#

whats the comma doing tho?

#

I get the *

undone mulch
#

But like I said I'm not sure if slash commands work the same way. In a normal command, it'd work. So maybe it auto-makes options in the slash command?

undone mulch
fervent cradle
#

alr

#

Ill give it a go

undone mulch
#

And yeah it's *, options: str

#

Should work but slash commands are different

fervent cradle
#

alr

fervent cradle
proud mason
#

Have you checked the example?

errant craneBOT
#

Here's the basic voice example.

grizzled sentinel
#

The PyNaCl library needs to be installed\

limber urchin
#

?tag nojson

obtuse juncoBOT
#

Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.

Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable

Popular database management systems:

  • SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
  • MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
  • PostgreSQL (Very popular and robust SQL based database management system)
  • MySQL (Another popular SQL based system, good start for learning SQL)
limber urchin
#

How are you installing pynacl?

#

python3 -m pip install -U py-cord[voice]

fervent cradle
#
from discord.ext import commands
from discord.commands import SlashCommandGroup
from discord import option

class pollCog(commands.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
    Poll = SlashCommandGroup("poll", "Different Poll Groups")
    PollOptions = Poll.create_subgroup(
        "pollcreate", "help", "anonymous")
    @Poll.command(name="poll")
    async def poll(self, ctx, message):
        await ctx.respond(message, "Yes And No")
        
def setup(bot):
    bot.add_cog(pollCog(bot))``` Why isnt it respnding?
#

responding*

young bone
fervent cradle
#

commands

young bone
#

?tag replit

obtuse juncoBOT
fervent cradle
#

Changed it to discord.Bot, no error no work

young bone
fervent cradle
young bone
#

?tag clients

obtuse juncoBOT
#

dynoError No tag clients found.

young bone
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
fervent cradle
#

so should i just remove commands.cog or should it be discord.cog

young bone
#

if you use discord.Bot use discord.Cog for commands.Bot use commands.Cog

fervent cradle
#

Thank you

#

Still no response..

#

Its the same as every command i've made?

obtuse juncoBOT
#

dynoError No tag ffmpeg found.

young bone
cold hamlet
#

My bot is not getting message content in on_message despite having the message intent enabled at both runtime and in the portal

#

Message content is still there if its from an on_reaction_add event though

#

any ideas?

#

re-fetching the message in the on_message event gives me the content

young bone
cold hamlet
#

There's two?

#

Is it not just discord.intents.messages?

young bone
#

intents.messages and intents.message_content?

cold hamlet
#

I didn't know the latter existed

#

Thank you 🙏

young bone
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

fervent cradle
#
from discord.ext import commands
from discord.commands import SlashCommandGroup
from discord import option

class pollCog(discord.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
    Poll = SlashCommandGroup("poll", "Different Poll Groups")
    PollOptions = Poll.create_subgroup(
        "pollcreate", "help", "anonymous")
    @Poll.command(name="poll")
    async def poll(self, ctx, message):
        await ctx.respond(message, "Yes And No")
        
def setup(bot):
    bot.add_cog(pollCog(bot))```
#

fixed

young bone
#

I cannot see the slash commands again....

fervent cradle
#

How can i access my SQL database from a phpMyAdmin server?

#
        await ctx.respond(embed=PollEmbed)
        PollEmbed.add.reaction("1️⃣")``` why no reaction?
young bone
fervent cradle
#

How can I track invites??

young bone
fervent cradle
fervent cradle
solemn idol
#

How do I globally sync my bot again?
Just remove the debug_guilds = Guild_ID ?

#

nvm its empty string

fervent cradle
#
        emoji = ":one:1054045453005627482"
        msg = await PollEmbed.add_reaction(emoji)``` updated
young bone
fervent cradle
#

thanks

green hinge
#

Hello
Why do I get when I type /menu my menu but also a message with "application not responding"?
Where is my error?

import discord
from discord.ext import commands

bot = discord.Bot()


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


    @discord.ui.user_select(placeholder='Wähle einen User')
    async def select_callback(self, select, interaction):
        await interaction.response.send_message("Hallo")
        print(select.values)

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


    @bot.command()
    async def menu(self, ctx):
        await ctx.send("Hallo hier!", view=MySelect())

def setup(bot):
    bot.add_cog(SelectMenu(bot))```
glossy tusk
green hinge
fervent cradle
green hinge
royal pulsar
#

does ctx.author return User or Member, if it's User, how do I change it to Member?

young bone
full basin
#

The same way you do it normally

full basin
full basin
fervent cradle
#

I sorta have it

#

await edit_orginal_response(content=PollEmbed)

full basin
#

You want to edit the message?

#

Didn't you want to add reactions?

woeful spindle
#

how do i respond to a interaction after deferring it?

full basin
#

In a view?

#

interaction.followup.send

woeful spindle
#

just normal command

#
@commands.command()
async def …(self, ctx):
    await ctx.defer()
    # do a lot of things
    # now how do I respond
full basin
#

Just respond

#

The library handles it

woeful spindle
#

using ctx.respond()?

#

my bot was stuck on thinking forever

proud mason
woeful spindle
fervent cradle
#

I thought i was meant to edit the message then react or smth?

#

Or do i just get orginal message then add

solemn idol
full basin
meager mica
#

i dont understand it but i think its so you can setup roles through other websites like sub on twitch role and stuff

full basin
#

Not yet

green hinge
#

You can't move a user to a voice channel if they are not already in a voice channel before, can you?

green hinge
# young bone How should that be possible?

I am in the process of creating a Select User Menu and then I want all selected users to be moved to a Voicechannel.
But this only works if the users are already in a voicechannel or not?

young bone
#

they have to be connected to a vc at the server

green hinge
#

Yes exactly what I thought

limber urchin
#

Imagine if you could force someone into a vc out of nowhere doggokek

green hinge
#

Hmm 😂

limber urchin
#

Exactly

fervent cradle
limber urchin
#

get.original.message??

full basin
#

💀

young bone
fervent cradle
#

I don't know that's why I'm asking kek

full basin
limber urchin
#

You should read the docs and look at examples instead of just blindly guessing

full basin
#

He just doesn't know OOP, just tries to invent attributes and methods

limber urchin
#

I believe he's been told to learn python on multiple occasions, but I guess #help-rules is non-existent to some people

fervent cradle
limber urchin
#

But seriously, if you don't know OOP in Python, learn it before asking questions here.

fervent cradle
#

👍

proud cargo
#

can you check if someone is on a free trial of a premium plan?

undone falcon
#

I was wandering if it is better to have a single database connection for my bot, or open a new connection each time I have a request (Sqlite)

limber urchin
rare ice
real frost
#

If i will make a lot of persistence buttons, will this buttons influence performance of the bot?

limber urchin
#

Depends on what the buttons do, but if you're talking about just having the buttons, not really unless you have an unreasonable amount of them.

silver moat
#

...with mediocre traffic.

green hinge
#

Hello,

can someone tell me why my voice channel is not deleted when I leave it?
The bot event is not executed at all

import discord
from discord.ext import commands

bot = discord.Bot()

@bot.event
async def on_voice_state_update(member, before, after):
    print("HIIIIER")
    # Wenn der Benutzer den Voicekanal verlässt, entfernen wir ihn aus der Liste
    if before.channel and not after.channel:
        channel_name = before.channel.name
        users_in_channel[channel_name] = [user_info for user_info in users_in_channel[channel_name] if user_info[0] != member.id]

            # Wenn keine Benutzer mehr im Voicekanal sind, löschen wir den Voicekanal
        if not users_in_channel[channel_name]:
            del users_in_channel[channel_name]
            await before.channel.delete()

def setup(bot):
    bot.add_cog(SelectMenu(bot))```
harsh canyon
#

as someone who understands the basic concepts of classes from reading code but have never used them in my own code because i just never saw a major advantage to doing so. should i learn how to use and start using cogs? had someone tell me that my code is "unusable" because i dont use them

north gorge
#

how do I get those four buttons to not show up at all? use_default_buttons = False just seems to disable them

silver moat
#

while using cogs isn't mandatory, it is certainly a good practice

limber urchin
#

And you still kinda need to get comfortable with using classes (and other OOP concepts) if you want to develop using pycord

#

so you might as well

silver moat
harsh canyon
#

mmk

#

thx

jaunty raft
#

Hey guys what does this mean?

#

did I scare averyone

full basin
#

You do it after initializing the bot instance

jaunty raft
#

Let me guess its also not a corrupting?

#

Corountine

full basin
#

And it's not a courtoutine either lol yes

tall oak
#

Can I get a command's description using the bot instance?

silver moat
#

.rtfm walk_application_commands

silver moat
#

.rtfm applicationcommand.description

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

silver moat
#

.rtfm .description

tall oak
#

How I can go through the commands is clear to me but how to get the description of it is what I don't get. The class ApplicationCommand doesn't seem to have any attribute that fits

silver moat
#

which inherits from App.Commands

muted pulsar
#

Has anything changed with the context menu lately ? I'm restarting my old bot i haven't used for 2 months and they don't appear in the right click
E: works on my private server

grizzled sentinel
spring kite
#

So I understand that await ctx.defer() can take an ephemeral boolean argument, which should match the later response.

Is there a way to account for a deferred interaction response that is normally visible, but might have something like an error/reminder message? I'd prefer error messages be ephemeral but successful response to be permanent.

rare ice
spring kite
# rare ice Could you please explain what you’re looking to do?

I have this design issue in a few places, but a basic equivalent example would just be, say, a command that can only be used between 10 and 12 GMT. Silly scenario, but it works for this purpose.

If the user tried to use the command at 14:00 GMT, I'd want to reply with an ephemeral message reminding them of the restriction. If there are no issues, then I'd want to reply with a permanent response after it's deferred.

#

It sounds like this may not be possible with how deferring responses works

#

But I thought I'd ask

#

Maybe I can defer after the error checking and just handle an "already responded" exception?

#

But ideally the error reminders should also be deferred

winter dagger
#

Does anyone know of an easy way to add/remove buttons with callbacks from views based on the interaction conditions?

The only way I can think of doing this atm is adding a separate discord button function to the class if a condition is met.

@discord.ui.button()
async def mybutton():
  pass

If logical_test == True:
  my_view.mybutton = mybutton

I haven't tested to see if this will work yet. It seems like there should be a simpler way built into the library.

silver moat
#

.rtfm add_item

winter condorBOT
silver moat
#

.rtfm remove_item

winter condorBOT
silver moat
#

@winter dagger ^

winter dagger
silver moat
#

cache the value of the vanity invite uses.
then check if it is different from

await member.guild.vanity_invite()
grizzled sentinel
spring kite
# grizzled sentinel Why do you need to defer?

There's some database consulting and permission checking that occasionally takes longer than discord likes.

The commands in question work just fine, it'd just be tidier if their replies didn't time out sometimes

grizzled sentinel
#

Would it be possible for you to check the time before deferring? Or do you need to know data from the database to decide to error or not?

proud cargo
#

Is it possible to check using a bot whether someone is on a premium role free trial, or the real thing?

full basin
#

You can't access nitro's information

proud cargo
novel jay
#

Is it possible to remove certain global slash command(s) from a guild without needing to reboot the bot? and vice versa?

full basin
#

You need a role object

#

Not just an id

#

Or at least a Discord object

#

Here you typed role = discord.Role

#

Doesn't look like type hinting chief

novel jay
#

What db type is that?

#

Mongo?

silver moat
#

I also don't think you can add a discord.Role object into a database

novel jay
#

You have to use a collection in mongo

silver moat
#

It probably converted it to a string

#

and that's the role's ID.

novel jay
#

also i recommend you use an async lib for mongo, a non-async (sync) lib will make your bot have stutters if it's making a lot of requests

silver moat
#

?tag blocking

obtuse juncoBOT
#

dynoError No tag blocking found.

silver moat
#

?tags

obtuse juncoBOT
#
Tags (95)

youtube, wavelink, virtualembed, usercmd, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, solved, snowflake, slashcommandmention, rie, restartcmd, requests, replit-install, replit, removeall, pythonserver, python, paste, oracle, option, oop, official, objects, notpycord, norepl, nojson, nohelp, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, localfile, learnpython, json, intents, install_slash, install_git, install, inline-fields, importerror, idw, ide, how2sql, guide, getalpha, get_x, get-help, funny, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, closing, client, buttons2, buttonlimit, bridge, breaking-changes, bitwise, asset, applicationcommands-registration-delay, aoclbcode, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel, CVE-2022-36024

novel jay
#

i meant stutters

silver moat
#

.rtfm fetch_role

winter condorBOT
full basin
#

Isn't a Discord.Object enough

silver moat
#

or

errant craneBOT
#

Here's the fetch role example.

silver moat
#

.rtfm get_role

winter condorBOT
novel jay
errant craneBOT
#

Here's the get role example.

full basin
#

Because they're not examples in the repo

#

They don't exist

#

Squid provided you the documentation

silver moat
#

I'm sorry.
what tf is this

await get_role[]
full basin
#

The hell is get_role[]

#

and role = find["role_id"] doesn't return a list. Don't know why you're type hinting a list

silver moat
#

also python type-hinting doesn't actually do anything

#

except help you/the IDE

full basin
#

But doing it wrong confuses you

novel jay
#

adding await to something only applies if the function itself is async

undone mulch
#

#998272089343668364 message

#

Can anyone help me out with this question I asked earlier? I am really confused.

novel jay
warm grotto
#

I have a bot that backs up and restores guild data from one guild to another. The problem I'm facing is that when I create emojis, it creates the first 50 emojis, but stops the code at await ctx.guild.create_custom_emoji for the rest of the emojis.
Looking at https://discord.com/developers/docs/resources/emoji, it seems it may be a rate-limit error, but I don't think Pycord has implement a rate-limiting handler for ctx.guild.create_custom_emoji...

limber urchin
#

A server without boosts can only have 50 custom emojis tho

warm grotto
limber urchin
#

Then implement your own limit for the creation

fervent cradle
#
    def __init__(self):
        super().__init__(timeout=None) 
        
    @discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.red)
    async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction:
    if "ticket-" in ctx.channel.name:
        channel = bot.get_channel(LOG_CHANNEL)
        closed = ctx.channel.name

        fileName = f"{ctx.channel.name}.txt"
        with open(fileName, "w") as file:
            async for msg in ctx.channel.history(limit=None, oldest_first=True):
                file.write(f"{msg.author.display_name}: {msg.clean_content}\n")

        embed = discord.Embed(
                description=f'Ticket closes automatically in 5 seconds!',
                color=0xe800ff)
        embed2 = discord.Embed(title="Ticket Closed!", description=f"Ticket-Name: {closed}\n Closed-From: {ctx.author.display_name}\n Transcript: ", color=discord.colour.Color.orange())
        file = discord.File(fileName)
        await channel.send(embed=embed2)
        await asyncio.sleep(1)
        await channel.send(file=file)       
        await ctx.send(embed=embed)
        await asyncio.sleep(5)
        await ctx.channel.delete()```

How would i make this work?
full basin
#

What's not working

novel jay
fervent cradle
#
    if "ticket-" in ctx.channel.name:
    ^
IndentationError: expected an indented block after function definition on line 96```
novel jay
#

Read the error...

#

it needs an indent after async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction:

warm grotto
#

I was looking at discord developer documentation and:

Routes for controlling emojis do not follow the normal rate limit conventions. These routes are specifically limited on a per-guild basis to prevent abuse. This means that the quota returned by our APIs may be inaccurate, and you may encounter 429s.

fervent cradle
novel jay
#

NameError: name 'ctx' is not defined

#

Please read your errors 🙂

fervent cradle
#

wtf am i meant to put

novel jay
#

you can define ctx by adding it to self inside the __init__ function and passing it in when calling it

fervent cradle
#

so use self?

novel jay
#

self.ctx after you defined it in __init__, yes

fervent cradle
#

so self.channel.name:

novel jay
fervent cradle
#

ok

silver moat
fervent cradle
# novel jay no, self.ctx.channel.name
    def __init__(self):
        super().__init__(timeout=None) 
        
    @discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.red)
    async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
        if "ticket-" in self.ctx.channel.name:
            channel = bot.get_channel(LOG_CHANNEL)
            closed = self.ctx.channel.name

            fileName = f"{ctx.channel.name}.txt"
            with open(fileName, "w") as file:
                async for msg in ctx.channel.history(limit=None, oldest_first=True):
                    file.write(f"{msg.author.display_name}: {msg.clean_content}\n")

            embed = discord.Embed(
                    description=f'Ticket closes automatically in 5 seconds!',
                    color=0xe800ff)
            embed2 = discord.Embed(title="Ticket Closed!", description=f"Ticket-Name: {closed}\n Closed-From: {ctx.author.display_name}\n Transcript: ", color=discord.colour.Color.orange())
            file = discord.File(fileName)
            await channel.send(embed=embed2)
            await asyncio.sleep(1)
            await channel.send(file=file)       
            await self.ctx.send(embed=embed)
            await asyncio.sleep(5)
            await self.ctx.channel.delete()``` 

Like this?
novel jay
#

you haven't defined ctx in the __init__ function

full basin
#

You domt even need to pass ctx to the view init

full basin
#

Interaction is your "context"

novel jay
#

my bad i just thought they were using ctx for other things

#

im playing BTD6 atm

fervent cradle
full basin
#

✨ Try it and see ✨

novel jay
#

make sure you adjust the other things in there too

fervent cradle
# full basin ✨ Try it and see ✨
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/main.py", line 114, in button_callback
    await interaction.send(embed=embed)
AttributeError: 'Interaction' object has no attribute 'send'```
novel jay
#

its interaction.response.send_message

fervent cradle
#

thx

novel jay
#

always happy to help 🙂

#

also, i could be wrong but i think you can send multiple embeds instead of sending them separately with
await interaction.response.send_message(embeds=[embed, embed2])

#

also, making sure your bot has the correct permissions is always good so you don't get flooded with errors about being forbidden
example:

try:
    await interaction.channel.delete()
except discord.errors.Forbidden:
    errorhandling
#Also has the benefit of if a different error happens, you'll know
fervent cradle
#

which is why are they different

novel jay
#

ah

warm grotto
#

What are some things I need to check in order to properly add a role?

fervent cradle
#

how can i use to different view sends on 1 embed?

warm grotto
#

Because even though my bot has administrator permissions, it's still not adding the role

#

Role must not be higher than the bot, I know that

#

Other than that, not sure

fervent cradle
#
    def __init__(self):
        super().__init__(timeout=None) 
        
    @discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.red)
    async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
        if "ticket-" in interaction.channel.name:
            channel = bot.get_channel(LOG_CHANNEL)
            closed = interaction.channel.name

            fileName = f"{interaction.channel.name}.txt"
            with open(fileName, "w") as file:
                async for msg in interaction.channel.history(limit=None, oldest_first=True):
                    file.write(f"{msg.author.display_name}: {msg.clean_content}\n")

            embed = discord.Embed(
                    description=f'Ticket closes automatically in 5 seconds!',
                    color=0xe800ff)
            embed2 = discord.Embed(title="Ticket Closed!", description=f"Ticket-Name: {closed}\n Closed-From: {interaction.user.display_name}\n Transcript: ", color=discord.colour.Color.orange())
            file = discord.File(fileName)
            await interaction.channel.send(embed=embed2)
            await asyncio.sleep(1)
            await interaction.channel.send(file=file)       
            await interaction.response.send_message(embed=embed)
            await asyncio.sleep(5)
            await interaction.channel.delete()```

This view and another view ill send both need to be sent onto the same embed
fervent cradle
# fervent cradle how can i use to different view sends on 1 embed?
    def __init__(self):
        super().__init__(timeout=None) 
        
    @discord.ui.button(label="Staff Application", style=discord.ButtonStyle.primary)
    async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
            modal = MyModal(title="Staff Application")
            await interaction.response.send_modal(modal)```
royal pulsar
#

I have an async function that is meant to run in parallel with the bot. How do I make it so that it runs parallel and doesn't interfere?

limber urchin
limber urchin
#

You can't send multiple views on one embed

fervent cradle
limber urchin
#

Create an instance of each view, iterate over the items and add them to a new view

fervent cradle
#

any examples?

limber urchin
#

nope

#

It's pretty simple

fervent cradle
#

" iterate over the items and add them to a new view" how would i do this part?

limber urchin
#

Loop over each view's children and add them to your new view

north gorge
#

How do you do an AThere mention, I tried searching and it's just a bunch of people saying "here" LOL

fringe socket
#

Just type @here

vale heath
#

how to use reactions in bridge commands thenking

vale heath
#

Error

Bot is online
Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
  File "C:\Users\Zalama\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Zalama\OneDrive\Documents\GitHub\Grinder_Co\data\cogs\reaction_role.py", line 85, in on_raw_reaction_remove
    member=guild.get_member(payload.user_id)
AttributeError: 'NoneType' object has no attribute 'get_member'

Code

@commands.Cog.listener()
    async def on_raw_reaction_remove(self,payload:discord.RawReactionActionEvent):
        guild = self.bot.get_guild(guildID)#server_ID
        member=guild.get_member(payload.user_id)
        if member.bot != True:
            try:
                with open(configFile) as fp:
                    ID = json.load(fp)
                ID1 = ID["rrID"]["RRID"] 
fringe socket
#

Create a thread @vale heath and show us your code and error there

vale heath
#

ok

woven harbor
#

hi! Does anyone know how to send an embed with no name in the field like mirai does

#

theres some stackoverflow threads that say to use \u200b but that doesn't work for me

#

ayy figured it out just need to use embed.description

fringe socket
#

Anybody know how I can grab a command argument from another file?

#

nvm

spare haven
#

Hi! I'm looking for a recommendation, how should I test my discord bot which is composed only by commands? Is it possible to use pytest for this?

young bone
young bone
spare haven
#

I was thinking about something like this but for that I need to make a class out of my Discord bot that currently it's a script (how can I make my bot a class? If I try to get all the code into a class my @bot.command does not work)

import pytest
import pytest_asyncio

@pytest.mark.asyncio
async def test_command(bot, message):
    # Set up the message object with the appropriate content and author
    message.content = "!command arg1 arg2"
    message.author = bot.user

    # Send the message and wait for a response
    await bot.process_commands(message)
    response = bot.last_response
    
    # Assert that the bot responded with the expected message
    assert response == "expected response"
young bone
#

I dont use pytest so...

spare haven
# young bone I dont use pytest so...

never mind I can figure that out myself, my real question is -> How can I create a class out of my discord bot script? I had everything in a raw python file and now I want to make a class out of it, do you know if there is documentation about this?

earnest lily
#

sup, does anyone know how to make the slash command send a response that only you see?

short talon
#

Anyway to either get a message by content without fetching all messages?
Or is there a way to use the discord search?

serene spindle
proud mason
#

That's the only thing tbh

full basin
#

Best approach is using history

#

Oh I'm late lmao

cobalt tangle
sand siren
#

is there a way to have 2 bots communicating with each other when they are on the same computer?

limber urchin
#

Set up a web server on both and use http requests between them

sand siren
#

how?

limber urchin
#

Set up a web server on both of them

#

and then make http requests

#

that's how

sand siren
#

i mean how do i set up the web server

limber urchin
#

You can use something like aiohttp to set up a web app that listens for requests

sand siren
#

thx

rare ice
#

I have this view class which is a role select, I'm wanting to have an __init__ argument which would be the max_values of the role select. however you cant access self when defining a select menu decorator. is there any way around this?

class RoleSelect(discord.ui.View):
  def __init__(self, max_values:int=5):
    self.selected_roles = None
    self.interaction = None
    self.max_values = max_values
    super().__init__(timeout=300)
  @discord.ui.role_select(placeholder="Select roles...", min_values=0, max_values=self.max_values)
  async def role_select_callback(self, select, interaction):
    self.selected_roles = select.values
    self.interaction = interaction
    self.stop()```
limber urchin
#

I think you can do something with global variables, not sure if there's a better approach

global max_values

class RoleSelect():
    def __init__(self, max_vals):
        global max_values
        max_values = max_vals
proud mason
earnest lily
rare ice
# limber urchin I think you can do something with global variables, not sure if there's a better...
global max_values
class RoleSelect(discord.ui.View):
  def __init__(self, max_selections:int=5):
    self.selected_roles = None
    self.interaction = None
    global max_values
    max_values = max_selections
    super().__init__(timeout=300)
  @discord.ui.role_select(placeholder="Select roles...", min_values=0, max_values=max_values)
  async def role_select_callback(self, select, interaction):
    self.selected_roles = select.values
    self.interaction = interaction
    self.stop()```
said `max_values` is not defined in the decorator
grizzled sentinel
spring kite
grizzled sentinel
spring kite
midnight torrent
#

Once Option() has choices set for a slash command, is it possible to update the choice list?

#

without a restart

grizzled sentinel
ionic hull
#

is it possible to detect when my bot is added to a server?

grizzled sentinel
spring kite
midnight torrent
#

yikes, i see, i can make a work around using autocomplete its just i was hoping for 2 values

ionic hull
midnight torrent
#

my api server is intergrated into my bot and i run a websocket in it, i was hoping to be able to list the names of the connected client and then select them for it to supply the websocket connection ID

grizzled sentinel
#

I think you would have to remove the original command
Manually create a new command with different args. Sync commands.
I dont think discord intends for this behavior so it might be buggy to

midnight torrent
#

oh god

spring kite
midnight torrent
#

but i guess i can just make it find the websocket ID via the name

#

just keep updating the autocomplete

#

in a loop

#

well update a bot variable

sand siren
#

how do make a option in a dropdown menu give you a role when selected but when unselected removes it?

spring kite
midnight torrent
#

i guess it could be

#

i just havent messed with drop down menus

grizzled sentinel
midnight torrent
#

@grizzled sentinel thanks, autocomplete will work just fine

#

was easy enough

rare ice
#

.nohelp

winter condorBOT
#

Nobody helps you? See #help-rules #4, then you know why.

rare ice
#

read the error

#

you also provided different code compared to your error, so i can't help you shruganimated

#

you havent defined a discord.Role object as role

#

what the hell is find :=

fervent cradle
#

Hello :) How do i make a Slash Command that is available on all servers that the bot will join?

rare ice
#

ive never seen that before

#

find isnt defined as well

winter condorBOT
fervent cradle
#

Okay if thats it Thank You :)

rare ice
#

ok then

#

.tias

winter condorBOT
fervent cradle
# rare ice dont set `guild_ids`
@bot.slash_command(description="Sets the channel as the AI Harald Channel", name="setchannel") 
@default_permissions(administrator = True)
async def setchannel(ctx)
#

Is that right?

rare ice
#

you need an actual callback but yes

#

.tias

winter condorBOT
rare ice
#

this code you had was fine

fervent cradle
#

damn it only works one time and after that the command isnt available anymore

vale heath
#

.rtfm guild.get_member

winter condorBOT
vale heath
#

Why it's giving me NoneType error 😑

limber urchin
#

Because you don't have member intents enabled

fervent cradle
#

how to write a PM to a user through a bot, having only an id?

vale heath
limber urchin
limber urchin
#

Keep in mind that you can't DM someone unless they share a server with your bot, and their DMs needs to be enabled

fervent cradle
limber urchin
#

It's a method of your bot instance

vale heath
quartz thunder
#

Hey all, hope your are fine, I need to edit a ephemeral message sent like that (see capture below, can I do it with the returned Interaction id ?

limber urchin
limber urchin
vale heath
limber urchin
limber urchin
vale heath
limber urchin
fervent cradle
limber urchin
#

You can't DM someone unless you have a shared server

vale heath
fervent cradle
limber urchin
#

Imagine if bots could DM you out of nowhere, scammers would abuse that to no end

fervent cradle
limber urchin
#

What?

fervent cradle
# limber urchin What?

As I understand it, a person can write to a random person, but a bot can't write to a person without shared servers?

limber urchin
#

A person can't write to a random person either. You need to share a server, or have them added as a friend

full basin
limber urchin
#

Since when?

fervent cradle
limber urchin
fervent cradle
fervent cradle
atomic wolf
#

Is there an way to create a role that is seperated from others with the bot?

limber urchin
#

what do you mean by "separated from others"?

atomic wolf
#

you know the option you can tik when creating or editing a role that it displays users with the role seperated from others. is there a way to do that with creating a role with the bot?

limber urchin
#

Did you read the docs? bruh

atomic wolf
#

i tried

limber urchin
#

So what do you think this is?

atomic wolf
limber urchin
#

I'm guessing you didn't actually read the docs

limber urchin
#

Is it a coroutine?

#

???

#

Read rule 1 in #help-rules

#

it isn't

#

Learn Python before making a bot

verbal marten
#

Spiderman doesn't know python sad_cat_2

limber urchin
#

Once again, read rule 1 in #help-rules

brittle cove
#

Does anyone know how to pass info through extentions / cogs to other ones

#

I have a cog managing something for my server that another cog needs to access a list from

#
class Cog1:
    def __init__(self, bot):
      self.bot = bot
      self.some_list = []

class Cog2:
    def __init__(self, bot):
      self.bot = bot
      self.some_list_copy = Cog1.some_list # <---- idk where to get this from cross file
somber frost
#

This code creates the channel but it doesnt go into the shops category

#

why?