#Basic Pycord Help (Quick Questions Only)

1 messages · Page 36 of 1

young bone
#

check if the bot can see the channel

silver moat
#

it takes an integer, not a string

#

not quite. the first two tries to get it from it's internal cache while the other fetches from the API

solid gull
#

i tried both of those

meager heron
#

Use an int for the channel ID, not a string

solid gull
#

i already tried that

#

regardless its the same error

meager heron
#

Then if fetch isn’t working, you probably have the wrong ID, or the bot isn’t in the server

solid gull
#

i think it may be because im initializing that before the bot activates

#

let me try putting it after the on_ready

#

so the issue is essentially the loop is running

#

before the on_ready runs

#

so any suggestions

limber urchin
#

Don't start the loop before the bot is ready

solid gull
#

how can i do that

young bone
#

your bot cannot see the channels because no intents at your client

solid gull
#

oh

silver moat
#

but those intents are not passed anywhere

solid gull
#

im dumb

#
#                                                                           #
# ToonHQ                                                                    #
# https://github.com/NoraHanegan/ToonHQ-Discord-Bot                         #
# Copyright (C) 2021 Nora Hanegan. All rights reserved.                     #
#                                                                           #
# License:                                                                  #
# MIT License https://www.mit.edu/~amini/LICENSE.md                         #
#                                                                           #
#***************************************************************************#
import discord
import os
import platform
import requests

from discord.ext import tasks


#Intents
intents = discord.Intents.all()

#Define Client
client = discord.Client(intents=intents)


@client.event
async def on_ready():
  print("Running as: " + client.user.name + "#" + client.user.discriminator)
  print(f'With Client ID: {client.user.id}')
  print("\nBuilt With:")
  print("Python " + platform.python_version())
  print("Py-Cord " + discord.__version__)

@tasks.loop(seconds=5, count=None)
async def myloop():
  channel = client.get_channel(1043694560657817680)
  await channel.send("hi")

#Run Bot
TOKEN = os.environ.get("TOKEN")
client.run(TOKEN)
#

no errors now, but its not running thr loop

silver moat
#

you need to start the loop with myloop.start()

solid gull
#

forgot about that part

#

and now were back to the nonetype error

#
#***************************************************************************#
#                                                                           #
# ToonHQ                                                                    #
# https://github.com/NoraHanegan/ToonHQ-Discord-Bot                         #
# Copyright (C) 2021 Nora Hanegan. All rights reserved.                     #
#                                                                           #
# License:                                                                  #
# MIT License https://www.mit.edu/~amini/LICENSE.md                         #
#                                                                           #
#***************************************************************************#
import discord
import os
import platform
import requests

from discord.ext import tasks


#Intents
intents = discord.Intents.all()

#Define Client
client = discord.Client(intents=intents)


@client.event
async def on_ready():
  print("Running as: " + client.user.name + "#" + client.user.discriminator)
  print(f'With Client ID: {client.user.id}')
  print("\nBuilt With:")
  print("Python " + platform.python_version())
  print("Py-Cord " + discord.__version__)

@tasks.loop(seconds=5, count=None)
async def myloop():
  channel = client.get_channel(1043694560657817680)
  await channel.send("hi")
myloop.start()

#Run Bot
TOKEN = os.environ.get("TOKEN")
client.run(TOKEN)
silver moat
#

put the start in on_ready

solid gull
#

yay

#

now my 2nd question how do i delete that post before it reposts it

#

essentially im fetching an uptime api and i want it to "refresh" every 5 minutes

silver moat
solid gull
#

so the post that the script above is posting every 5 seconds instead of spamming it

#

delete the old hi and say hi again

limber urchin
#

Keep the message in a global variable and delete it before re-posting

solid gull
#

how?

limber urchin
#

Or just edit it

solid gull
#

editing it wont work

limber urchin
#

send returns the message

#

store that in a global variable

#

and if it has a value, delete it before sending a new one in your loop

solid gull
#

how do i delete a post

#

again

limber urchin
silver moat
#

are you looking for a message, not a post?

solid gull
#

yes

solid gull
#

that doesnt seem to be working

#

can u just write out the line

limber urchin
#

What did you try? And what isn't working?

#

And no, I am not writing code for you

solid gull
#

thats not what im asking

#

im asking can you just tell me is it channel.delete

limber urchin
#

Try it and see NPCMechanicShrug

solid gull
#

i cant access that url

fervent cradle
#

You can use ‘.send’ but make sure your slash command is also responded too with ‘.respond’, it’s not impossible

fallow hawk
#

can these option types have values?

#

like would a dict work?

warm grotto
#

Is discord.ext.commands.Greedy supported in slash_commands?

fierce elm
#

Trying to get a list of datetime.time that are every 15mins but the closest I can get without getting every minute, would be to use something like

start = datetime(2022, 11, 20, 00, 00)
end = datetime(2022, 11, 20, 23, 45)
[r.datetime.time for r in arrow.Arrow.span_range('hour', start, end)]

warm grotto
#

How do you mention a slash command?

meager heron
#

</name:id>

#

Or SlashCommand.mention

warm grotto
warm grotto
meager heron
#

No, the slash command's ID

warm grotto
meager heron
#

Bot.walk_application_commands()

#

Also Cog.get_commands()

warm grotto
#

Great! Thanks

cobalt tangle
warm grotto
cobalt tangle
#

command.options

cobalt tangle
#

You cant mention it with options but u can show the options via this (pretty sure u cant)

warm grotto
#

I see, yeah I was rooting if I could mention with options already filled out

#

Okay. Thanks again!

cobalt tangle
#

lol

still helm
#

is there a way to use aliases in a bridge_command?

steel fjord
#

how to install pycord master branch?

full basin
obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

foggy mortar
#
Traceback (most recent call last):
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 775, in _load_from_module_spec
    setup(self)
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\cogs\newscog.py", line 101, in setup
    bot.add_cog(newscog(bot))
                ^^^^^^^^^^^^
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\cogs\newscog.py", line 27, in __init__
    self.timednews.start()
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\tasks\__init__.py", line 333, in start
    self.loop = asyncio.get_event_loop()
                ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\asyncio\events.py", line 677, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'MainThread'.
#

what

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

Traceback (most recent call last):
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 13, in <module>
    bot.load_extension('cogs.newscog')
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 899, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 780, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.newscog' raised an error: RuntimeError: There is no current event loop in thread 'MainThread'.
Task was destroyed but it is pending!
task: <Task pending name='Task-1' coro=<Loop._loop() running at C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\tasks\__init__.py:152>>
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
full basin
foggy mortar
#

um but i dont

full basin
#

Do pip freeze

foggy mortar
#

lemme have a look i have another bot library but not dpy

#

like you dont import it like import discord

#

or imma just uninstall it

#

still like that

#

@full basin

#

it somehow worked now

#

and it somehow not working now

#

i edited the discord.ext.tasks.__init__.py to make it work

peak chasm
#

I want it to wait 5 seconds for the channel to be deleted, what can I do?

limber urchin
#

Use asyncio's sleep function

peak chasm
limber urchin
#

it's a coroutine

peak chasm
#

if he told me the error haha zdxdxd

limber urchin
#

what?

peak chasm
#

It already works <3

#

<3 <3

peak chasm
#

How can I get a role to mention later?

peak chasm
#

I am using this but it does not notify

fervent cradle
#

how send "missing premission message"

full basin
#

Error handlers.

fervent cradle
#

ok

#

@full basin like this
@bot.command()
async def on_command_error(ctx, error):
if isinstance(error , commands.MissingPermissions):
await ctx.reply("error message")

full basin
#

bot.command?

fervent cradle
#

oh dump me

full basin
fervent cradle
#

how make command whitc can run only in certain channel

young bone
fervent cradle
#

ok can you send pycord docs or smothing tutorial for that

#

@young bone can you (sorry ping)

limber urchin
#

You won't find a tutorial for everything, it's very simple. Just add a check in your command for the channel ID you want to allow your command in

fervent cradle
#

ok

fervent cradle
limber urchin
fervent cradle
#

what i think'

limber urchin
#

what

fervent cradle
#

i think i need to do this i need to get chennel id where the command send in and store it in variadle then do

limber urchin
#

why?

#

Just check if the channel id is the same as the channel you want to allow the command in

fervent cradle
#

yeah that is what i am doing i just dont know how get the channel id of the chennel where the command is sentted(sorry bad english)

limber urchin
#

You have access to the context parameter in the command send, just get the channel attribute from that

fervent cradle
#

oh thanks

fervent cradle
limber urchin
#

no

#

you need the id of the channel, not the channel object

fervent cradle
#

oops

peak chasm
#

the bot has permissions and everything but it doesn't mention

limber urchin
#

That has nothing to do with pycord. You either messed up the permissions or the role isn't mentionable

fervent cradle
#

@limber urchin (sory ping) is this smothing like it discord.ext.commands.channel

limber urchin
#

what?

fervent cradle
#

the chennnel limiter thinggy

limber urchin
#

what about it?

fervent cradle
#

is this the channel id taker discord.ext.commands.channel

limber urchin
#

no?

#

just get the id attribute of the channel you already had on your ctx

fervent cradle
#

ok i gonna test

fervent cradle
limber urchin
#

huh?

fervent cradle
#

is this the variable whitc stores the channel id where the command is send ctx."somthing"???????

young bone
#

@fervent cradle do you know the basic of python?

fervent cradle
#

yes i kown

limber urchin
#

you already have the channel object from ctx.channel

fervent cradle
limber urchin
#

What part of it are you not getting?

#

I told you, you can get the id from the id attribute of your channel object that you already have

#

I don't know what else to tell you

fervent cradle
#

ok

#

😑 (my brains is burn)

meager heron
#

Get the ID of the channel you want from Discord itself (right-click -> copy ID). In your code, if ctx.channel.id == <THAT_ID_YOU_COPIED>:

peak chasm
#

Rare

meager heron
#

response, not respond

fervent cradle
young bone
mortal junco
#

Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1088, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 374, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.

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.

#

wtd do i do

limber urchin
#

Wait for the rate limit to pass, and stop spamming the API

mortal junco
#

so do i wait?

limber urchin
#

Doesn't matter if you are using it

mortal junco
limber urchin
#

Your code is spamming the API and causing a rate limit

mortal junco
#

How long is rate limit?

limber urchin
#

🤷‍♂️ no way to tell unless you check the headers of the request response

#

could be a few minutes, could be hours

mortal junco
#

i dont even use http..

#

how would i get rate limited

limber urchin
#

you're using pycord right?

mortal junco
#
  File "/home/container/LightStore.py", line 113, in <module>
    client.run(json.loads(open("config.json", "r").read())["token"])
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 717, in run
    return future.result()
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 696, in runner
    await self.start(*args, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 659, in start
    await self.login(token)
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 514, in login
    data = await self.http.static_login(token.strip())
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 406, in static_login
    data = await self.request(Route("GET", "/users/@me"))
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 318, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.```
mortal junco
limber urchin
#

And pycord makes http requests

limber urchin
#

so yes you are using htt

#

p

#

so you need to check your code for API calls and reduce them anywhere you're spamming them

mortal junco
#

ok

young bone
limber urchin
#

or if you're using some shitty free host, that is also a reason for being rate limited

mortal junco
mortal junco
#

sparkedhosting

limber urchin
#

never heard of it

young bone
mortal junco
#

yh

young bone
#

get a Raspberry Pi

#

its greate to host the bot

limber urchin
#

Eh, the hosting service seems fine

#

just look for anything can spam the API in your code and fix it

mortal junco
#

thank u ❤️ hope its not down for too long

spice oyster
#

What's the best way to intentionally trigger an error while responding to a Slash Command?
I want to send an error message that's in my error handler without copy-pasting it. rooThink

limber urchin
#

Create your own custom error class, raise that error class and catch it in your error handler

spice oyster
fervent cradle
#

need help
uninstalled all packages and reinstalled py-cord still same error

fervent cradle
#

still same error

silver moat
#

pip list and send output

fervent cradle
silver moat
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

silver moat
#

2b

fervent cradle
#

oh i think i need to update py

silver moat
#

py-cord supports python 3.8+

fervent cradle
#

ye i using

#

3.7.9

#
  File "C:\Users\timpi\Documents\GitHub\marius-sperlich-discord\minimal-bot\docker\bot.py", line 5, in <module>
    from discord.ext import commands
  File "C:\Users\timpi\Documents\GitHub\marius-sperlich-discord\minimal-bot\docker\venv\Lib\site-packages\discord\ext\commands\__init__.py", line 18, in <module>
    from .flags import *
  File "C:\Users\timpi\Documents\GitHub\marius-sperlich-discord\minimal-bot\docker\venv\Lib\site-packages\discord\ext\commands\flags.py", line 57, in <module>
    @dataclass
     ^^^^^^^^^
  File "C:\Users\timpi\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1221, in dataclass
    return wrap(cls)
           ^^^^^^^^^
  File "C:\Users\timpi\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1211, in wrap
    return _process_class(cls, init, repr, eq, order, unsafe_hash,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\timpi\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 959, in _process_class
    cls_fields.append(_get_field(cls, name, type, kw_only))
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\timpi\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 816, in _get_field
    raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory

I don't even know what to google here???

silver moat
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

fervent cradle
#

thank you

meager mica
#

Hey so I noticed when I set commands with required permissions @discord.default permissions it hides commands but when I do it to sub commands it don't hide them can I hide sub commands just like default permissions does

twilit valley
#

How do I make the bot send a message in a specific channel once every week at a specified time (automatically)?

civic jayBOT
meager mica
#

Bruh

#

Not that

#

Just have it loop every 5 seconds it something then get current hour and day with datetime module and see if it's right time then fetch and send message

twilit valley
#

alr I can try that

peak chasm
#

how can i make the channel i am creating to be made in a category

#
channel = await interaction.guild.create_text_channel(name=f"test-{interaction.user.name}".lower(),overwrites=overwrites,reason="Test")
simple canopy
#

you need to get a category first

#

with guild.get_channel(id)

#

and then call an create function on category's object

peak chasm
#

<3

young bone
#

guild_only()

full basin
#

It's a decorator

young bone
#

what?

#

this one?

errant craneBOT
#

Here's the slash options example.

rigid sable
#

Can I have the slash command roles example

near hollow
near hollow
#

np

#
@bot.message_command(name="Add Quote")  # Creates a global message command
async def add_quote(ctx, message: discord.Message):  # Message commands give a message param
    x = collection.find_one({'GuildID' : ctx.guild.id}, {"Server Quotes":1, "Settings":1, "Premium":1, "_id": False})
    if message.embeds != []:
        await ctx.respond("You can't quote an embed!", ephemeral=True)
    else:
        if x['Settings']['ApprovalChannel'] == None:
            await ctx.respond("Please have an admin set a approval channel with ``/set approvalchannel``", ephemeral=True)
            return```

So the last part keeps duplicating and sending twice not sure why. No I am not running two processes I have checked multiple times. Not sure what the issue is and I am very confused
fringe pier
#

how can i enumerate the element inside an array of an array?
say a = [[1,2,3],[4,5,6],[7,8,9]]
if i enumerate i get 0, 1,2 for each array
but i want to enumerate the 1,2,3

fringe pier
copper dew
#

also just wondering if you know basic python, bc a problem like this should be pretty easy to figure out

fringe pier
#

i am beginner

#

thank you so much

copper dew
#

ok that makes more sense

fringe pier
#

oh wait my bad

#

it worked thank you !

copper dew
#

np

snow swan
#

is the time needed to create application commands extraordinarily long now?
I have confirmed its registered in bot.pending_application_commands but its been a day now and nothing really happens

proud mason
snow swan
#

huh... what is wrong with mine then
I used discord.ext.commands.slash_command to create it in cog and enabled application command in invite
its also registered in bot.pending_application_command so there should be no problem with the code right?

proud mason
#

discord.ext.commands.slash_command

the decorator right?

proud mason
#

its also registered in bot.pending_application_command so there should be no problem with the code right?

yeah should be fine

proud mason
snow swan
#

in on_connect I just do print("bot connected")

#

should I do something there?

proud mason
snow swan
#

i used cog listener

proud mason
#

if you use bot.event for the on_connect event then bot.sync_commands wont get called

snow swan
#

oh I also used client event to do prefix command

#

is it that

proud mason
#

like which event?

snow swan
#

bot. event

#

on_message

proud mason
#

oh that shouldnt be a problem either

#

idk what your bot exactly does, but if nothing works, call bot.sync_commands in the on_connect listener. its not good practice cuz the library does it for you, but it works

#

or send your code and we'll help to figure out whats wrong

snow swan
#

I'll try sync commands first then

#

should it be instant even when the command is global?

proud mason
#

not sure

snow swan
#

just to be safe I will add guild ids

proud mason
#

aight

snow swan
proud mason
#

oh lol 👍

snow swan
#

the global one hasn't created tho, so not that instant

proud mason
#

btw thats not a perfect solution and can break after a while depending on the code

snow swan
#

so maybe I shouldn't define on_connect?

proud mason
snow swan
#

async def on_connect(self): await self.sync_commands() print("bot connected") /

full basin
#

If you override on_connect you must register the commands

snow swan
#

just that sync_commands right?

full basin
#

Yes

snow swan
proud mason
#

oh wait

#

thats not a cog listener

#

thats the bot class

#

cuz you are doing self.sync_commands

#

@snow swan is that the bot class?

snow swan
#

yes it is

#

ohh

proud mason
# snow swan ohh

yeaa so you are overriding the on_connect it wont cuz issues if you sync command there

#

dont put the cog listener decorator on it btw

snow swan
#

I only put the cog listener in the cog file so its fine

proud mason
snow swan
#

thank you very much, this issue had me bamboozled for quite some time without any leads 👍

#

I even made a command to monitor the pending command lul

gleaming falcon
#

So uh, under what conditions causes command autocomplete to just randomly fail, and then fail forever?

Task exception was never retrieved
future: <Task finished name='Task-285946' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at /[python]/discord/bot.py:827> exception=AttributeError("'NoneType' object has no attribute 'invoke_autocomplete_callback'")>

Traceback (most recent call last):
  File "/[python]/discord/bot.py", line 830, in callback
    return await command.invoke_autocomplete_callback(ctx)
  File "/[python]/discord/commands/core.py", line 1300, in invoke_autocomplete_callback
    await command.invoke_autocomplete_callback(ctx)
AttributeError: 'NoneType' object has no attribute 'invoke_autocomplete_callback'

And what error handler can I use to prevent this error from keeping the command broken until I restart it?

gleaming falcon
full basin
#

I've never seen an autocomplete fail.

#

Could you show code?

proud mason
#

me neither. tf is up with my keyboard

#

seems like command is being None

gleaming falcon
#

I hadn't touched anything, it had been running for days with no other hiccups. I'm assuming Discord decided to break, but I'm hoping that if I can properly handle the error, it would recover. I had to restart the bot to get the autocomplete to work again.

proud mason
#

discord probably sent a wrong command name?

rare ice
#

Try updating your client or refreshing.

proud mason
gleaming falcon
rare ice
#

So it’s either Discord but most likely your code.

proud mason
gleaming falcon
#

The other parts of the bot were working, it's just the autocomplete part of the command failed and never restored.

It would be nice if there was some error handler I could at least capture the task exception so it didn't permanently break until restart.

rare ice
#

Send your autocomplete code

gleaming falcon
#
    async def chain_list(self, ctx: discord.AutocompleteContext):
        chains = list(self.safes.keys())

        return [
            OptionChoice(name=info.get('name', chain), value=chain)
            for chain, info in self.bot.networks.items() if chain in chains and ctx.value.upper() in chain.upper()
        ]

Pretty simplistic; it's just returning a list of key names for selection. self.safes is static. self.bot.networks can change with an intentional reset (e.g. live reloading), but again I hadn't touched the bot in days.

rare ice
#

Shouldn’t you be returning strings?

proud mason
# rare ice So it’s either Discord but most likely your code.

well as you said, it might a discord issue. but refreshing your discord client wont fix it.
the command seems to be None from the traceback. I can only infer that the command name discord sent didnt match with that of your commands. this can be due to a non-refreshed client like you said. but there might some user like this. and if he uses the command, then the autocomplete fails as we saw.

rare ice
#

For autocomplete

gleaming falcon
#

No, OptionChoice is valid for when name and value differ

rare ice
#

alr

proud mason
#

"valid" or "works" 😂

gleaming falcon
#

It works just fine normally. My complaint is that it randomly started failing

#

To be clear, this isn't "help me with my code that isn't working", it's more of "the library did this unexpectedly, what causes this to happen (and how can I capture it so it doesn't permanently break)"

proud mason
gleaming falcon
#

Will give it a try, thanks for the suggestion.
Open to any others, of course 🙂

atomic wolf
#

So i have a question, I have a command that removes all the users roles. But it says it cant remove the role "@ everyone". How do i make it so he ignores it.

the code:

roles = interaction.user.roles
        for i in roles:
            try:
                await author.remove_roles(i)
            except:
                print(f"Can't remove the role {i}")

full basin
atomic wolf
#

ty

mortal junco
#

bro my bot keeps rate limiting

#

i fixed the issue i thought and still have the issue

#

idk what else to doo

errant craneBOT
#

Here's the context menus example.

rare ice
#

How would I go about getting a channel ID and a message ID from a message link string? should I use an id snowflake regex and use the last 2 items

full basin
#

Regex is the best option.

full basin
#

I've got one if you want it

atomic wolf
#

Do you have to stop a View if I already have cleared the items?

silver moat
mortal junco
silver moat
mortal junco
silver moat
#

well, your host is ratelimited.

#

contact your host to see if they have alternative IP addresses.

mortal junco
#

ok

#

is it the bots fault or the hosting fault?

silver moat
#

the host's

mortal junco
#

this host support is so ass

silver moat
#

there are free hosts that are recommended

#

you also can get paid ones if your bot using a lot of processing power.

#

I recommend using railway.app

full basin
#

Railway isn't good anymore.

proud mason
#

there are a few that require a credit card for verification

#

like i recently found out oracle free vps

proud mason
#

you can then use match.group("channel_id) to get the channel id

rare ice
#

ive already got a working code, but thanks

proud mason
#

or use match.groups() to get a tuple of it

#

lag

proud mason
mortal junco
#

@silver moat

#

which ones are reccomenend

obtuse juncoBOT
#

Oracle Cloud Always Free Tier

☑️ 2 virtual machine with 1/8 OCPU and 1 GB RAM each
☑️ 2 Block Volumes, 100 GB total. 10 GB Archive Storage
☑️ Outbound Data Transfer: 10 TB per month

For more info check: https://www.oracle.com/cloud/free/#always-free

mortal junco
#

@silver moat

#

there is likely an abuser as there is only 50 bots on this IP.

#

Is what they said

limber urchin
#

50 bots on the same IP? Jesus

meager heron
#

"Only" sounds like a lot

meager heron
#

(Been using for 3 months)

limber urchin
#

I've been using GalaxyGate for over 2 years and never had an issue, but Vultr and DigitalOcean are also good options for paid VPSs

meager heron
#

Out of curiosity, what kind of latency do you get there? The lowest I've seen is at GCP. (I'm aware it's not a particularly important metric)

fallow hawk
#

anyone know why this would happen?

#

it responds with this

meager heron
#

You probably did ctx.respond(embed) vs ctx.respond(embed=embed)

fallow hawk
#

oh thank you

quartz thunder
#

Hi, Is it possible to make a slash_command with a multiselect dropdown (with choices or autocomplete) ?

full basin
#

Yes

quartz thunder
#

How ? ahah cannot find the option

rare ice
#

You can’t do a select menu while invoking a slash command no

limber urchin
quartz thunder
quartz thunder
limber urchin
#

pretty sure you can't, unless you just add a bunch of optional parameters with the same options

quartz thunder
#

Thanks for the advices 😉

meager heron
limber urchin
#

It's very dependant on where the server is located though. Pretty sure mine is in NYC

meager heron
#

For sure

limber urchin
#

Upgrade your pip with
python3 -m pip install --upgrade pip

fringe socket
#

How can I make a command appear just by pinging the bot and nothing else?

limber urchin
#

Check for the bot's mention in your on_message event

versed fern
#
message = SlashCommandGroup(name="message", description="Send/edit message commands!")

    @message.command(description="Sends a message in the channel specified!")
    @has_permissions(administrator=True)
    async def send(self, ctx,
                   content: Option(str, "Please enter the content of your message!", required=True),
                   channel: Option(discord.TextChannel, "Please enter the channel!", required=False)):
        if channel is None:
            channel = ctx.channel
        await channel.send(content)
        await ctx.respond(f"Successfully send the message in <#{channel.id}>!", ephemeral=True)

    @message.command(description="Edits the message specified!")
    @has_permissions(administrator=True)
    async def edit(self, ctx,
                   msg: Option(discord.Message, "Please enter the message link or ID!", required=True),
                   content: Option(str, "Please enter the new content of your message!", required=True)):
        if msg.author != self.client.user:
            await ctx.respond("Can't edit this message!")
            return
        await msg.edit(content)
        await ctx.respond("Successfully edited the message!", ephemeral=True)

Currently trying to prevent users without admin perms to use these commands. While it works (kinda, throws an error, but that should be catchable), it actually prefer those commands to not be shown at all. Does anybody know of a way of doing this?

proud pagoda
#

Strangely enough one of my bots users is able to run commands in his server he is the owner of in a channel with no errors, but when another person runs the exact same commands in the same channel, the bot throws a 403 forbidden

#

Are the permissions for the bot when the command is run based on the users permissions as well?

sly oak
#

Tell me why the error output on cooldown is ignored

young bone
sly oak
versed fern
#

looks good, I'll give it a try, thx

obsidian ginkgo
#

can someone help me

#

im trying to make a welcome bot for my server but nothing works

obtuse juncoBOT
#

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

obsidian ginkgo
#

The code was good but it did nothing

fervent cradle
#

Without showing your code or at least explaining it we can do nothing since we have no knowledge of what you're trying to do.

fervent cradle
#

so i need help with this code

#

So what im trying to do is make a command return however many roles a user has with "💍" in it.

#

I already have some code done i can send it if needed

#

any help

quartz thunder
#

Hey all 🙂 hope you are fine
Is there a way to enable/disable a command by a boolean flag ?

proud mason
fervent cradle
#

bro your mad goofy

#

thats useless

obsidian ginkgo
#

this is the code

#

nothing wrong but i dont work

#

dont judge me i just started with python

fervent cradle
#

💀 🤣

#

im dead

proud mason
#

also what is client.send_message(member). thats not a thing

#

?tag lp

obtuse juncoBOT
#
proud mason
#

discord bots shouldnt be in your early states of python learning. it will confuse you

grizzled sentinel
grizzled sentinel
somber remnant
#

Hey ! I have a little problem with the menu prayadge

I made a multiple choice menu, and when u choose an anwser, it edit the message and show another menu instead of the back one. But, the 'interaction failed' show, and i want to remove it
How i can do that ? I know that is something like interaction.followup or something similar but i'm stuck
If you need code ask me !

versed fern
# grizzled sentinel https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/s...
    message_group = SlashCommandGroup(name="message", description="Group of send/edit message commands!")

    @message_group.command(description="Sends a message in the channel specified!")
    @default_permissions(administrator=True)
    async def send(self, ctx,
                   content: Option(str, "Please enter the content of your message!", required=True),
                   channel: Option(discord.TextChannel, "Please enter the channel!", required=False)):
        if channel is None:
            channel = ctx.channel
        await channel.send(content)
        await ctx.respond(f"Successfully send the message in <#{channel.id}>!", ephemeral=True)

Changed it to @default_permissions(), but now it allows non admins to use the command. Took a look at the command perms and they said that </message:0> was fine to be used by everyone (as shown in the pic below), which kinda max sense, since it's the subcommands with permission restrictions, not the command group. That's why I think I gotta make the entire group perm restricted, but I just don't know how (since using the @default_permissions() above message_group = SlashCommandGroup(name="message", description="Group of send/edit message commands!") obviously won't do the trick. Any ideas?

fiery tiger
full basin
#

Your token is wrong

echo copper
#
@slash_command(name='feijaopuro', description='Montagem do meme feijão puro')
    async def wanted(self, inter : discord.Interaction):
        await inter.response.defer()
        feijaopuro = VideoFileClip('./videos/feijaopuro.mp4').subclip(0,10)

        await inter.respond(file=discord.File(feijaopuro))```
#

estou tentando enviar um vídeo, mas não estou conseguindo, vai em português msm 😄

grizzled sentinel
grizzled sentinel
meager heron
#

I think the answer is no, but is it possible to subclass Interaction? (And thus always get that subclass rather than discord.Interaction)

meager heron
#

Oh? Documentation link? I didn't find anything

young bone
#

you find anything there

meager heron
#

I wasn't asking for a link to the general documentation. I was saying I didn't find anything in the documentation

meager heron
meager heron
# young bone

And this continues to be unhelpful, as I already noted

meager heron
#

Please stop pinging me, dude

young bone
#

k

meager heron
# silver moat basically, yes

Would the instantiation be something like ...

class MyInteraction(discord.Interaction):
    # Custom behaviors here
    pass

# `base` is a standard discord.Interaction object
my_interaction = MyInteraction(**base.to_dict())

Or is there a better way?

young bone
#

is there a way to deactive something like that?

silver moat
old mesa
#

My Bot needs to handle command and also run other code in a loop, can the bot do both at the same time in 1 script? Or does it need multiple Python scripts

silver moat
old mesa
#

Alr

meager heron
# silver moat seems correct

Hm, I'm getting TypeError: Interaction.__init__() got an unexpected keyword argument 'id'. Any suggestions? I know how I could just add the function to the object, but that seems like bad form. Or I could make a wrapper that implements __getattr__, but that also seems like an ugly solution

clever lark
#

Hi, I'm trying to declare a view using PyCord 2.0.1 and I'm getting the following error:

TypeError: __init__() got an unexpected keyword argument 'disable_on_timeout'```
According to the docs, 'disable_on_timeout' should be a valid argument, so I'm unsure why it's throwing an error.

The documentation I'm using for reference: https://docs.pycord.dev/en/stable/api.html?highlight=on_timeout#discord.ui.View.disable_on_timeout
copper dew
clever lark
rare ice
#

.docs discord.ui.View

winter condorBOT
rare ice
clever lark
rare ice
#

So that way you can actually set it

#

Since rn you are setting something that doesn’t exist hm

full basin
#

Shouldn't you be able to just do disable_on_timeout=True

clever lark
# rare ice You have to define it in your `__init__` if you subclass

i do not subclass, sorry for the confusion. my code for defining the view and adding items and callbacks is as follows :

view.on_timeout = on_timeout``` according to what i've been told by the docs and you, this should create a view with a timeout of 5 seconds, that disables the components when it times out. then set the timeout behaviour for the view. i'm not sure why the disable_on_timeout seems to have no effect, but the buttons are still enabled and clickable after 5 seconds.

as for what dark#8901 said, you would think, but again, that doesnt seem to work.
silver moat
#

you should update the view yourself

clever lark
hallow blaze
# clever lark i do not subclass, sorry for the confusion. my code for defining the view and ad...
    async def on_timeout(self) -> None:
        """|coro|

        A callback that is called when a view's timeout elapses without being explicitly stopped.
        """
        if self.disable_on_timeout:
            if self._message:
                self.disable_all_items()
                await self._message.edit(view=self)

This is the behavior of the on_timeout method (for discord.ui.View), it seems like you made your own on_timeout behavior, so it basically just overwrote what happens I believe.

fallow hawk
#
                Page(
                    embeds=[
                        discord.Embed(
                            title="TITLE",
                            description="DESCRIPTIOn"
                        )
                    ],
                ),
            ]``` how would i add a field to this type of embed? i've only used the ``embed.add_field`` type
#

nvm

somber remnant
fervent cradle
#

hey guys, are the new permissions changes in py-cord?

cold hamlet
#

What permission is required to create threads in a forum channel? send_messages or create_public_threads?

#

Nevermind its literally in the docs description that I completely missed

versed fern
# grizzled sentinel You can pass it right to SlashCommandGroup with https://docs.pycord.dev/en/mast...

Did it like this:

message_group = SlashCommandGroup(
        name="message",
        description="Group of send/edit message commands!",
        default_member_permissions=discord.Permissions.administrator
    )

    @message_group.command(name="send", description="Sends a message in the channel specified!")
    @has_permissions(administrator=True)
    async def message_send(self, ctx,
                           content: Option(str, "Please enter the content of your message!", required=True),
                           channel: Option(discord.TextChannel, "Please enter the channel!", required=False)):
        if channel is None:
            channel = ctx.channel
        await channel.send(content)
        await ctx.respond(f"Successfully send the message in <#{channel.id}>!", ephemeral=True)

But I get the follwoing error every time I run the code:

Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\AIM_Bot\venv\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\User\PycharmProjects\AIM_Bot\venv\lib\site-packages\discord\bot.py", line 1138, in on_connect
    await self.sync_commands()
  File "C:\Users\User\PycharmProjects\AIM_Bot\venv\lib\site-packages\discord\bot.py", line 692, in sync_commands
    registered_commands = await self.register_commands(
  File "C:\Users\User\PycharmProjects\AIM_Bot\venv\lib\site-packages\discord\bot.py", line 570, in register_commands
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
  File "C:\Users\User\PycharmProjects\AIM_Bot\venv\lib\site-packages\discord\bot.py", line 570, in <listcomp>
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
  File "C:\Users\User\PycharmProjects\AIM_Bot\venv\lib\site-packages\discord\commands\core.py", line 1168, in to_dict
    ] = self.default_member_permissions.value
AttributeError: 'flag_value' object has no attribute 'value'
plush meadow
#

I'm having a bit of difficulty understanding where to put the timeout for a view

#
class AirDropView(discord.ui.View):
     def __init__(self):
          super().__init__()

I am declaring a view like so, and it doesn't seem like I've put the timeout in the right spot yet

#

and I've put it in several places

plush meadow
#

that seems loopy

plush meadow
#
        class AirDropView(discord.ui.View):
            def __init__(self):
                super().__init__(timeout=None)
#

so like this

young bone
#

yes

plush meadow
#

okay wonderful, thank you so much

#

i would've never tried that

young bone
#

this should help you

plush meadow
#

I was here, but I wasn't able to find anything pertaining to timeouts

#

although I did see that there was a keyword argument for timeout for discord.ui.View, I just didn't know where to put it

#

maybe I just can't read

plush meadow
#

what where

#

are we on the same page

round rivet
young bone
#

Interactions>UI Components

plush meadow
#

ohh it's under buttons

#

my fault, I should've looked better

winged zephyr
#

an example of a mute command in pycord

#

can anybody send me mute command code

#

i wanna make a command for muting someone in the server for 2hours or some time

white scarab
#

Does defer(invisible=True) work?

await ctx.defer(invisible=True)

I am trying to use it but the message that says:

Bot is thinking ...

is seen in the chat even if I put invisible=True.

#

Using:

py-cord 2.1.3
stark nebula
winged zephyr
#

like mod bots do

stark nebula
#

ehhh one sek

#

so you could time out the user with

await Member.timeout_for()

https://docs.pycord.dev/en/stable/api.html#discord.Member.timeout_for
but that stops the user from doing anything except viewing messages

or you could give the Member a custom role that stops them from typing in the channel

await Member.add_roles()

https://docs.pycord.dev/en/stable/api.html#discord.Member.add_roles

and then remove it once your done

await Member.remove_roles()

https://docs.pycord.dev/en/stable/api.html#discord.Member.remove_roles

winged zephyr
stark nebula
#

let me check

winged zephyr
winged zephyr
stark nebula
#

I would assume so because it stops interaction but you might want to check

winged zephyr
#

oki thnx

white scarab
#

If I do that.

#

The message is still displayed, but only to the user.

#

I want it not to be shown.

#

Because actually I send the message with channel.send() to avoid Discord not allowing me to edit the message after 15min (because the interaction is no longer valid).

round rivet
copper knot
#

quick question: can you do something like```py
members = await ctx.guild.fetch_members()
users = bot.users
if users[0] in members:

#

i dont know if you can use an in function but i know you can compare members and users

round rivet
spring hull
#

hello @proud mason

#

continue here?

#

pycord is installing on 3.10 rn

proud mason
proud mason
spring hull
#

oh i think it just worked wot

proud mason
#

lmao nice 👍

spring hull
#

maybe a reboot?

proud mason
#

show pip list

spring hull
proud mason
#

your environment is probably fucked . python 3.8 3.10 and 3.11 at the same time

proud mason
spring hull
#

.....

#

soooo what do i do

#

can;t remove 3.10, removed 3.8

proud mason
#

hmm

spring hull
#

can remove 3.9 (ms store that i don't use)

#

but it worked on 3.9

#

so i think that has pycord

proud mason
#

wait

#

you installed wrong library

spring hull
#

HEH

proud mason
#

its py-cord

#

uninstall the other one

spring hull
#

🤦

proud mason
#

ikr 💀

spring hull
#

what's the diff

proud mason
#

well pycord is a wrapper for ffmpeg or smth

spring hull
#

ffs

proud mason
#

barely any users but owner of that lib is not ready to switch

spring hull
#

no error!!!

#

now what?? (added a guild to test guilds)

#

(still logged in tho)

copper knot
#

or you are registering them twice

silver moat
#

upgrade to master branch for 3.11 support

#

?tag github

obtuse juncoBOT
#

dynoError No tag github found.

silver moat
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

spring hull
#

why do python break everything in "bugfixes"

silver moat
#

?

spring hull
#

3.11 is labelled as a "bugfix" but it still breaks loads of things

proud mason
#

3.11 isnt a bug fix

#

its a full blown release with additional features too

spring hull
#

not what they call it but sure ¯_(ツ)_/¯

#

bruuuuuuhhH!

#

Probs me being dumb

proud mason
#

where do they call it a bugfix 💀

proud mason
spring hull
#

when you click the play button on the cog not main.py lmao

proud mason
#

lmao

spring hull
#

still no

proud mason
spring hull
#

I did

proud mason
#

that shouldnt make a difference tbh

spring hull
#

i get this when starting the bot, but it still goes onlin

silver moat
#

why is self there

proud mason
silver moat
#

if it’s in a cog the command itself should also be indented

spring hull
#

(i copied off a tutorial to get the cog code working then changed things for slash commands, maybe some things i did aren't necessary anymore?? IDK!)

spring hull
silver moat
#

send full error and code

proud mason
silver moat
#

and I gtg

proud mason
#

oh wait

silver moat
proud mason
#

you are using discord.Cog

proud mason
spring hull
silver moat
#

what you are doing it correct

spring hull
#

heh

proud mason
spring hull
#

idk!! slash comnads????

proud mason
#

discord.Bot or commands.Bot?

#

show how you initialize your bot

#

bot = ...

silver moat
spring hull
#

bot = discord.Bot

proud mason
proud mason
silver moat
proud mason
#

ouu

spring hull
#

but i want slash commands and probably only slash commands

#

(pycord has changed a lot since i last used it AHHH)

#

(and i wasn't using cogs back then lmao)

#

what do i do then??

spring hull
fiery tiger
spring hull
#

click the link

fiery tiger
#

I did that lol

proud mason
#

so enable virtualization from bios

spring hull
spring hull
# silver moat send full error and code

Error:

Microsoft Windows [Version 10.0.22621.819]
(c) Microsoft Corporation. All rights reserved.

I:\JARD Bot\JARD-Bot>"C:/Program Files/Python310/python.exe" "i:/JARD Bot/JARD-Bot/main.py"
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\bot.py", line 1138, in on_connect
    await self.sync_commands()
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\bot.py", line 711, in sync_commands
    app_cmds = await self.register_commands(
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\bot.py", line 581, in register_commands
    registered = await register("bulk", data, _log=False)
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\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
In 1: Application command names must be unique
Logged in as JARD Bot#1232!
Ignoring exception in command ping:
Traceback (most recent call last):
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\commands\core.py", line 970, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "i:\JARD Bot\JARD-Bot\cogs\demo.py", line 12, in ping
    await ctx.respond(
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\commands\context.py", line 282, in respond
    return await self.interaction.response.send_message(
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 825, in send_message
    await self._locked_response(
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 1090, in _locked_response
    await coro
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\webhook\async_.py", line 215, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

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

Traceback (most recent call last):
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\bot.py", line 1088, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\commands\core.py", line 374, in invoke
    await injected(ctx)
  File "C:\Users\boxer\AppData\Roaming\Python\Python310\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

Code: https://github.com/Boxersteavee/JARD-Bot

proud mason
#

why is it that the simplest of all bots have the most errors 😩

spring hull
#

idk Cry

#

All i want is 1 cog (atm) with 1 simple command!!!

proud mason
#

why do you import commands ext but never use it 🤔

#

yk what

spring hull
#

heh

proud mason
#

try using commands.bot

#

and commands.cog

spring hull
#

still got the command name must be unique error. give a sec for other thing

#

FUCK SAKE

#

still doesn;t work. same errosr

proud mason
#

and @commands.slash_command

spring hull
#

o

spring hull
#

yeah still didn't

proud mason
#

show updated code

spring hull
#

pushed to git

proud mason
#

use a different bot's token

#

this one might be cursed

spring hull
#

heh

proud mason
#

i honestly have no idea whats wrong

spring hull
#

LMAO FIGURED IT!!!

#

it's because /ping

proud mason
#

hows that to do with anything

spring hull
#

IDK BUT IT WORKED

proud mason
#

lmao

#

👍

spring hull
#

why can't my command be named ping

#

if i do that, i get the "Application commands must be unique"

proud mason
spring hull
#

nope

#

nothing else has this token

proud mason
#

or maybe lots of bots with ping command in your server?

spring hull
#

also no

proud mason
#

hmm

#

discord doesnt like your bot naming its command ping then

spring hull
#

no clue why tho

#

so how can i remove the old /ping from discord then?

#

Cuz my bot still has a /ping thing registered when i press /

#

but it doesn't work

proud mason
#

i forgor 💀

#

but it was by running bot.sync_commands(force=True) from what i recall

spring hull
#

?

proud mason
#

do that once and then remove from your code

spring hull
#

where do i put it

proud mason
grizzled sentinel
versed fern
#

I think I’m just not able to read the docs properly

versed fern
grizzled sentinel
#

You almost always want to pass an object of the class.
It is a bit difficult you just get used to how the docs are written after a while. I actually dont know if there is anything that gives it away besides a bit of logic if you understand what is going on (which will come with time)

spring hull
#

fixed it..... i had a template cog and forgot to a) change file extension and b) hash the code

#

it works now

white scarab
round rivet
#

no

white scarab
#

Ok, thanks.

void abyss
#

Extension 'cogs.ping' raised an error: TypeError: module() takes at most 2 arguments (3 given)

#

how can i fix this?

#
from discord.ext import commands

class Ping(commands.cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self, client):
        print(f'{client.user.tag} is ready')

    @discord.slash_command()
    async def ping(self, ctx):
        await ctx.respond("pong")

    def setup(client):
       client.add_cog(Ping(client))```
limber urchin
#

Your setup function should not be in the class

void abyss
#

i still got the error

limber urchin
#

How are you loading the cog?

void abyss
#
from discord.ext import commands
import json
import os
import asyncio

y = open('config.json')
data = json.load(y)

intents = discord.Intents.default()

client = discord.Bot(intents=intents)


async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'cogs.{filename[:-3]}')

async def main():
    await load()
    client.run(data['token'])



asyncio.run(main())
limber urchin
#

load_extension is not a coroutine

#

so no need to use asyncio

meager heron
glossy tusk
#

how can ı delete respond message

#

and where did docs gone

limber urchin
#

?

#

The docs are in the same place they've always been

glossy tusk
#

When ı search, ı can't see anything.

limber urchin
glossy tusk
#

*Search in site

mild osprey
#

Where do i find documentation?

mild osprey
glossy tusk
mild osprey
#

yeah with ctrl + f

silver moat
#

There is a search button

mild osprey
#

anyone know whats wrong with? typing !test <anything> does nothing. ```import discord

class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')

client = MyClient(intents = discord.Intents.default())
client.run('token')

from discord.ext import commands

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

@bot.command()
async def test(ctx, arg, author):
ctx.reply('hello {author} ! thanks for making me say {arg} .')
pass
bot.add_command(test)
```

silver moat
#

?tag message-content

obtuse juncoBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

mild osprey
#

thanks

full basin
#

Why the hell you're running two instances

mild osprey
mild osprey
#

im new to both python and pycord, your gonna need to be more specific lol

young bone
young bone
full basin
#

You're subclassing discord.Client, then running then creating a commands.Bot instance and creating a command.

young bone
limber urchin
#

Read rule 1 in #help-rules

mild osprey
mild osprey
glossy tusk
mild osprey
#

ok bye

young bone
#

ok?

limber urchin
#

Good luck 👋

glossy tusk
silver moat
#

wdym

glossy tusk
#

Go docs site and try

#

search something

full basin
#

Works well.

glossy tusk
limber urchin
#

Do a hard reload then

mild osprey
#

anyone know why it says discord doesn't have an attribute named "Bot"?

bot = discord.Bot()```
full basin
#

Because probably you're using an outdated version.

mild osprey
#

is their an updated version on replit?

full basin
#

?tag replit

obtuse juncoBOT
mild osprey
#

thanks.

mild osprey
fringe socket
#

Is there a way you can check what badges a user has?

#

or a member?

silver moat
fringe socket
#

ah

warm grotto
#

Ok. This one is tricky to explain, but:

My situation is that I have two bots. One is my main bot, and another is a premium manager. Premium manager has the command /redeem with code and guild as a parameter. The guild parameter is a discord.Option containing discord.AutocompleteContext, and in result returns a str. The guild parameter supposedly searches for guilds that my main bot is in either by it's ID or name, since the premium manager bot does not have that guild information. discord.AutocompleteContext can return a list of strings, but can it return a list of discord.OptionChoice so that the guild parameter can return it's ID via discord.OptionChoice.value

#

The reason I can not put discord.Guild as a type parameter for discord.Option is because the bot can only search for server's it is in, not where my main bot is in

#
class Redeem(commands.Cog):
  def __init__(self, client):
    self.client = client
  @slash_command(description="Redeem a premium code")
  async def redeem(self, ctx,
      code:Option(str, "Enter the premium code to redeem"),
      guild:Option(str, "Enter the server name or ID to apply premium to", autocomplete=get_guild)):```

```py
async def get_guild(ctx: discord.AutocompleteContext):
  searchterms = []
  GlobalData = Load("Global", "Variables")
  for bot in GlobalData:
    if bot != "_id":
      for i in range(len(GlobalData[bot]["Guilds"])):
        for ID in GlobalData[bot]["Guilds"][i]:
          if ctx.value in decrypt(ID) or ctx.value in GlobalData[bot]["Guilds"][i][ID]["Name"]: #if ctx.value matches a discord guild's ID or name
            searchterms.append(discord.OptionChoice(
              name = GlobalData[bot]["Guilds"][i][ID]["Name"],
              value = decrypt(ID)
            ))
  return searchterms```
#

Output:

mortal cairn
#

Is python 3.11 supported in version 2.3?

silver moat
mortal cairn
#

I might upgrade but test first also because a few libraries are broken with 3.11

north gorge
#
async with self.image_getter.get(sub.url) as resp:
    buffer = BytesIO(await resp.read())
    file = discord.File(fp=buffer, filename='attachment.png')

Any idea why that might give me "400 Bad Request (Error Code: 50008): Cannot send messages in a non-text channel" when I send that file as the file= attachment in .create_thread()?

#

I've got the luck of having an error message with only 3 appearances in google

quartz thunder
#

Hey all 🙂
Do you know if it is possible to make a command that self-reboot the bot completely?

fringe socket
#

no

#

because if you turn off the bot it can't run any more processes

limber sorrel
#

Hello, if I work on application command event, what should I need to do next?
Like process what?

#

Pls help me, thanks

fringe socket
#

what's your current code

#

also if you have an issue, first thing. read the docs and guide

limber sorrel
#

I can't find the answer in docs and guide

#

On application command
Does it need await self.bot.process_application_command(ctx.interaction)?

fringe socket
#

I've never really used cogs so...

limber sorrel
#

But

#

It like not in the cog...

fringe socket
#

then why did you use @commands.Cog.listener()

limber sorrel
#

You can see that as @bot.event

copper dew
#

yes if u want to register an event in a cog, you'll need the commands.Cog.listener decorator

cobalt tangle
#

can you use bridge.has_permissions with commands.Bot?

cobalt tangle
white scarab
glossy tusk
#

How do I know if the bot is disconnected from the voice channel? (Force disconnect like ban)

grizzled sentinel
mild osprey
glossy tusk
tiny hearth
#

im getting this error after updating to pycord 2.3.0, it was running good on2.2.2 any ideas?

#

weird, switching from python 3.11 to 3.10.7 seems to have fixed it

mild osprey
#

why does it automatically stop running ```import discord

bot = discord.Bot()

@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")

@bot.slash_command(guild_ids=[1044049692989870150])
async def sayisuck(ctx):
await ctx.respond("test")

bot.run('token')```

cobalt tangle
#

It's wrong

mild osprey
#

where

cobalt tangle
#

Bot.run should not be indented into the cmd

#

It should be on its own

mild osprey
#

ok

#

ty

cobalt tangle
#

np

#

By its own, I mean no indentation

mild osprey
#

ok

#

im stupid, how do i make the bot.run on its own and not in the cmd?

cobalt tangle
#

um

#

Don't indent it

mild osprey
#

how lol

cobalt tangle
#

Um

#

How tf do I explain this

mild osprey
#

try sending an ss and telling me what to change

cobalt tangle
#

there should be no spaces on the left side of the bot.run keyword

mild osprey
#

still doesnt work ```import discord

bot = discord.Bot()

@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")

@bot.slash_command(guild_ids=[your, guild_ids, here])
async def hello(ctx):
await ctx.respond("Hello!")

bot.run("token")```

cobalt tangle
#

Yes

#

Now try

mild osprey
#

i did

cobalt tangle
#

Hm

#

Maybe pass intents?

mild osprey
#

oh it worked

cobalt tangle
#

What did you do?

mild osprey
#

dunno why i did nothing

#

well tysm for the help

cobalt tangle
#

np

winged zephyr
#

whats the diff between slash_command user_command and normal bot.command(()?

raw gust
#

slash command, is a command you invoke with "/".
User command can only be invoked by clicking on a user and select "Apps" then the command.

winged zephyr
#

and bot.command can be invoke with the prefix i give ?

#

and do bot.command come in a list like the slash command

glossy tusk
#

and bridge_command all of them

north gorge
#

Anyone have a working snippet for taking a URL to an image and attaching it as a discord.File(), spent a while trying to figure it out and kept getting illegible errors, wanted to avoid temporarily saving it

#

idk if it's something specific to forum.create_thread() but I couldn't get it to work for the life of me

fervent cradle
#

How can i find when someone has clicked a hyperlink in a embed? so it will send another emphermal embed once clicked

silver moat
#

you can't

fervent cradle
#

f

hallow blaze
north gorge
#

I spent hours last night trying to figure it out pepehands

hallow blaze
#

@north gorge I found a workaround... but it's through editing the thread message itself.
Use Thread.starting_message and edit it with the file perhaps?
What results when I do that with my profile as a file for example is this.

ERRATA: edit Thread.last_message, perhaps that is more of a reliable workaround for now compared to the former.

north gorge
#

ooo I'll try that, thanks 🙂

#

I wonder what the issue is

hallow blaze
#

If that doesnt work use last_message

#

When testing starting_message it brought a None, so probably last_message will be more reliable as the workaround

hallow blaze
silver moat
#

yes

loud holly
#

what exactly are the new Guild features?

silver moat
#

##1788

errant craneBOT
stark nebula
#

Does anybody know how to remove the timeout on a View

like i am making a view like this

class supportView(discord.ui.View):
    @discord.ui.button(label="CoolButton", style=discord.ButtonStyle.primary, custom_id="buttonOne")
    async def first_button_callback(self, button, interaction):
        #do some stuff

What code would i need to add to make it not disable

#

like I know it is disable_on_timeout but where would i implement this

round rivet
#

add an __init__ and pass timeout=None to remove the timeout

stark nebula
#

thanks

stark nebula
rare ice
stark nebula
indigo badger
#

Ahhhh How do I fix this it keeps coming on my host logs?

silver moat
indigo badger
silver moat
#

because if they are 40+ seconds behind, then they aren't a good host

indigo badger
#

Or somewhere in US.

stray phoenix
#

How can I make my bot get user id?

silver moat
stray phoenix
silver moat
#

where is the ID you want to check for stored?

stray phoenix
#

it checks if the user id matches on "if" line.

silver moat
#

so the ID is static?

stray phoenix
#

yes

silver moat
woeful spindle
silver moat
rare ice
#

it did what you wanted it to

#

Because you set it as a thumbnail

#

.docs discord.Embed.set_image

silver moat
#

.tag embeds

silver moat
#

we knew that

#

I am too

indigo badger
silver moat
#

Do you use the requests library?

indigo badger
glossy tusk
#

What is data?

full basin
glossy tusk
#

If bot disconnected(force) from voice channel how can I wavelink player disconnet from track

#

I can't use .disconnect because player not exist but when I call bot back this song still playing

#

@silver moat Sorry for ping, any idea?

quartz thunder
#

Hello 🙂
I'm in a COG and I want to set dynamically an autocomplete Option, do you know a way to do that ?

fringe socket
#

What the cog doin'?

quartz thunder
#

Slash commands, events, private methods

#

Hmmm I can't because it's not a static data source to fil the autocomplete

quartz thunder
#

I'm inside a cog, I want to fill a slash command option with autocomplete (array of string)
This autocomplete data comes from database (dynamic), I have to call a method to get it, but here I can't :

full basin
#

Create the function outside your class

quartz thunder
#

Thats what StackOverflow told me ahah

#

I just wanted to know if is there an other way

#

I dont want to call my db outside 😦

full basin
humble ice
#

Is there a way to separate bots from an option? For example...

async def trade(ctx: discord.ApplicationContext, var1, user_b: discord.User, var3):
user_b: discord.User

Shows all members including bots
besides just writing a custom user list, is there a way to remove bots as an option in the autocomplete list?
I've already written something to replace it but, I like that when you use discord.User you can see their avatar and presence

silver moat
#

You can use autocomplete and populate your own member list

humble ice
#

thanks...

north gorge
#

How do you actually register a slash command group defined in a cog? I figured adding the cog would do it but it doesn't seem to

limber urchin
#

Please share your code

north gorge
#
class BanBets(commands.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot

    banbets = SlashCommandGroup("banbets", "Wager your Reddit account on price action!", guild_ids=[1037784194476163223])

    #banbets_admin = SlashCommandGroup(
    #    "banbets admin",
    #    "BanBets Admin",
    #    checks=[
    #        commands.is_owner().predicate
    #    ],  # Ensures the owner_id user can access this group, and no one else
    #)

    @banbets.command()
    async def stats(self, ctx: discord.ApplicationContext, guild_ids=[1037784194476163223], cooldown=commands.CooldownMapping.from_cooldown(1, 180, commands.BucketType.user)):
        user_to_check = (await session.execute(select(Redditor).filter(Redditor.discord_id == ctx.author.id))).first()
        if users_to_auth:
            wins = (await session.execute(select(BanBet).filter(BanBet.redditor_id == users_to_auth[0].id).filter(BanBet.expired == True).filter(BanBet.won == True))).count()
            losses = (await session.execute(select(BanBet).filter(BanBet.redditor_id == users_to_auth[0].id).filter(BanBet.expired == True).filter(BanBet.won == False))).count()
            new_embed = discord.Embed()
            new_embed.add_field(name="Wins", value=f"{wins}", inline=True)
            new_embed.add_field(name="Losses", value=f"{losses}", inline=True)
            new_embed.add_field(name="Total", value=f"{wins + losses}", inline=True)
            await ctx.respond(embed=new_embed)
        else:
            ctx.respond("You're not even authed. How'd you get in here?", ephemeral=True)

    #@banbets_admin.command()
    #async def stop(self, ctx: discord.ApplicationContext, member: discord.Member):
    #    await ctx.respond(f"{member.mention} secret handshakes you")

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx: discord.ApplicationContext, error: discord.DiscordException):
        if isinstance(error, commands.NotOwner):
            await ctx.respond("You can't use that command!")
        else:
            raise error  # Raise other errors so they aren't ignored
#

Then I'm registering the cog like I do all the others in on_ready with "bot.add_cog(BanBets(bot))"

#

slash command just doesn't show up

copper dew
north gorge
#

I did not. I put it in bot.event def on_ready() with the other cogs I register

#

that the issue?

copper dew
north gorge
#

happy thank you, I'll try it out

copper dew
#

bot.add_cog() registers the class you pass in as a cog, and bot.load_extension() actually loads the cog file

long torrent
#

is it possible to add a normal button next to paginator buttons, i want to have a button next to my paginator buttons that opens a webpage on click, ik its possible with normal buttons but i cant seem to do it next to paginator buttons

proud mason
#

Or custom buttons or smth

#

Put the row id as 2 so it will be displayed below the paginator controls

quartz thunder
tender seal
#

hi

#

how would I send a message to every server my bot is in

fringe socket
tender seal
#

yeah

#

I was just making a guess

#

how would I do it

fringe socket
tender seal
#

it'll just send a message once

#

in general
without pinging anyone

long torrent
fringe socket
#

Yeah just set the variables to the labels to be page number minus one and page number plus one.

tender seal
#

I'll add a toggle in the settings

#

if the owner wants to turn the messages off

#

the channel will be picked during setup too

fringe socket
simple bay
#

among us

tender seal
#

can you use cogs with bridge commands?

#

wait nv

cobalt tangle
#

can u use @bridge.has_permissions with commands.Bot with slash commands

young bone
#

you have to use bridge.Bot

merry briar
#

How can I use jishaku?

Errors: discord.errors.ExtensionFailed: Extension 'jishaku' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'

main

import discord

from dotenv import load_dotenv
import os
import asyncio

load_dotenv()

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

bot = discord.Bot(intents=intents)

bot.load_extension('jishaku')
bot.run(os.getenv("TOKEN"))

proud mason
#

and from discord.ext import commands in your imports

young bone
tiny hearth
#

any ideas why it doing this, it works fine with python 3.10.7, but not with 3.11.0

py-cord version 2.3.0

worked before updating to 2.3.0

cyan quail
proud mason
cyan quail
#

im aware

#

they have an old version on 3.11 though

#

which predates bridge commands

tiny hearth
proud mason
#

ohh ic

tiny hearth
#

my default python is 3.11

#

weird

proud mason
#

use pip3.11 ...

cyan quail
#

that doesn't mean pip matches it

tiny hearth
#

my bad

proud mason
#

happens blobpain

merry briar
# proud mason jishaku uses prefix commands. that needs you to use `commands.Bot` instead of `d...

It seems to have done everything, but also at ! or / commands are not used

main

import discord
from discord.ext import commands

from dotenv import load_dotenv
import os
import asyncio

load_dotenv()

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

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

bot.remove_command("help")

bot.load_extension('jishaku')


bot.run(os.getenv("TOKEN"))
tiny hearth
#

well im still getting the same problem

young bone
#

uninstall it and try the git version

tiny hearth
#

good idea

young bone
tiny hearth
#

still not

#

well honestly i have no idea

#

what is the problem

merry briar
merry briar
proud mason
merry briar
proud mason