#Basic Pycord Help (Quick Questions Only)
1 messages · Page 36 of 1
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
i tried both of those
Use an int for the channel ID, not a string
Then if fetch isn’t working, you probably have the wrong ID, or the bot isn’t in the server
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
Don't start the loop before the bot is ready
your bot cannot see the channels because no intents at your client
but those intents are not passed anywhere
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
you need to start the loop with myloop.start()
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)
put the start in on_ready
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
Can you be more specific?
so the post that the script above is posting every 5 seconds instead of spamming it
delete the old hi and say hi again
Keep the message in a global variable and delete it before re-posting
how?
Or just edit it
editing it wont work
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

are you looking for a message, not a post?
yes
Try it and see 
i cant access that url
You can use ‘.send’ but make sure your slash command is also responded too with ‘.respond’, it’s not impossible
Is discord.ext.commands.Greedy supported in slash_commands?
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)]
How do you mention a slash command?
And how do I obtain the SlashCommand class?
And would the ID be the application ID (a.k.a., the bot's user ID)?
No, the slash command's ID
How do I get that?
Great! Thanks
it doesn't get slash command groups so I would recommend walk_commands()
Alright, can mentioning commands also come with autofill values?
command.options
^
You cant mention it with options but u can show the options via this (pretty sure u cant)
I see, yeah I was rooting if I could mention with options already filled out
Okay. Thanks again!
Suggest this to Discord
lol
is there a way to use aliases in a bridge_command?
how to install pycord master branch?
?tag install
- 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
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
Looks like you have a conflicting discord.py
um but i dont
Do pip freeze
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
I want it to wait 5 seconds for the channel to be deleted, what can I do?
Use asyncio's sleep function
it's a coroutine
if he told me the error haha zdxdxd
what?
How can I get a role to mention later?
I am using this but it does not notify
how send "missing premission message"
Error handlers.
ok
@full basin like this
@bot.command()
async def on_command_error(ctx, error):
if isinstance(error , commands.MissingPermissions):
await ctx.reply("error message")
bot.command?
that is a event, not a command
oh dump me
All about handling errors.
how make command whitc can run only in certain channel
check for the channel name/id
ok can you send pycord docs or smothing tutorial for that
@young bone can you (sorry ping)
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
ok
i cant find check for channel id
Just do an if statement? No need for some advanced check
what do you mean i need to check the channel id where the command send in then do if the channel id on se channel id where you can send messages
what i think'
what
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
why?
Just check if the channel id is the same as the channel you want to allow the command in
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)
You have access to the context parameter in the command send, just get the channel attribute from that
oh thanks
is smothing like this the if thing
´´´py
if ctx.channel == the channel id
´´´
oops
the bot has permissions and everything but it doesn't mention
That has nothing to do with pycord. You either messed up the permissions or the role isn't mentionable
@limber urchin (sory ping) is this smothing like it discord.ext.commands.channel
what?
the chennnel limiter thinggy
what about it?
is this the channel id taker discord.ext.commands.channel
ok i gonna test
is this the channel id taker ctx.somthing???
huh?
is this the variable whitc stores the channel id where the command is send ctx."somthing"???????
@fervent cradle do you know the basic of python?
yes i kown
Dude just read the docs instead of trying to guess your way to the answer
you already have the channel object from ctx.channel
yeah i read it i just cant make it I do not get it
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
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>:
The error was the command "interaction.respond.send_message()"
I changed it to "interaction.channel.send()" and it worked for the bot
Rare
response, not respond
bruh that is too eysy i am erly dumpm righ now THANK YOU
interaction.response not respond
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.
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
Wait for the rate limit to pass, and stop spamming the API
im not using the bot i sell it to customers.
so do i wait?
Doesn't matter if you are using it
i dont even use http
Your code is spamming the API and causing a rate limit
How long is rate limit?
🤷♂️ no way to tell unless you check the headers of the request response
could be a few minutes, could be hours
you're using pycord right?
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.```
mhm
And pycord makes http requests
http.
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
ok
do you have something with a tasks loop?
or if you're using some shitty free host, that is also a reason for being rate limited
yes
Its a 1 dollar host xD
sparkedhosting
never heard of it
do you have a good internet connection?
yh
Eh, the hosting service seems fine
just look for anything can spam the API in your code and fix it
Ight,
thank u ❤️ hope its not down for too long
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. 
Create your own custom error class, raise that error class and catch it in your error handler
Thank you! That's exactly what I was looking for. 
need help
uninstalled all packages and reinstalled py-cord still same error
restart terminal/ide
pip list and send output
?tag install
- 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
2b
oh i think i need to update py
py-cord supports python 3.8+
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???
use the master branch for 3.11
?tag install
- 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
thank you
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
How do I make the bot send a message in a specific channel once every week at a specified time (automatically)?
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
alr I can try that
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")
you need to get a category first
with guild.get_channel(id)
and then call an create function on category's object
<3
guild_only()
It's a decorator
Here's the slash options example.
Can I have the slash command roles example
async def role(self, ctx, role: Option(discord.Role, "Select a role!")):```
Like this?
Yes, thank you
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
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
nested loops
would you mind showing it to me please 🥹
a = [[1,2,3],[4,5,6],[7,8,9]]
for item in a:
for subItem in item:
print(subItem)
also just wondering if you know basic python, bc a problem like this should be pretty easy to figure out
np
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
actually its the opposite. people are saying the time to register commands is almost instant now since the recent command perms v2 were launched
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?
are you overriding the on_connect event?
discord.ext.commands.slash_command
the decorator right?
its also registered in bot.pending_application_command so there should be no problem with the code right?
yeah should be fine
@snow swan what about this?
and are you using bot.event or bot.listener() or commands.Cog.listener() ?
i used cog listener
oh that should not be an issue then
if you use bot.event for the on_connect event then bot.sync_commands wont get called
uhh which one?
like which event?
yeah but which event? on_message ?
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
I'll try sync commands first then
should it be instant even when the command is global?
thats what i have heard
not sure
just to be safe I will add guild ids
aight
thanks it worked
oh lol 👍
the global one hasn't created tho, so not that instant
btw thats not a perfect solution and can break after a while depending on the code
so maybe I shouldn't define on_connect?
can you show how you do you on_connect ?
async def on_connect(self): await self.sync_commands() print("bot connected") /
If you override on_connect you must register the commands
just that sync_commands right?
Yes
right thanks
Im a bit concerned about this tho
yeah but thats a listener cuz cogs
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?
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
I only put the cog listener in the cog file so its fine
yep no issues then
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
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?
full traceback?
Added
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.
discord probably sent a wrong command name?
Try updating your client or refreshing.
yeah but someone out there using his bot might not have his client refreshed and that could break his bot
I mean.. The command failed, I restarted the bot and used the command just fine all with the same client.
Someone running a slash command wouldn’t break the bot
So it’s either Discord but most likely your code.
i believe no error handler handles this
try if on_error does but not sure
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.
Send your autocomplete code
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.
Shouldn’t you be returning strings?
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.
For autocomplete
No, OptionChoice is valid for when name and value differ
alr
"valid" or "works" 😂
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)"
@gleaming falcon idk but the on_error event might pick up that one
Will give it a try, thanks for the suggestion.
Open to any others, of course 🙂
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}")
interaction.user.roles returns a list. The first item is the everyone role.
ty
bro my bot keeps rate limiting
i fixed the issue i thought and still have the issue
idk what else to doo
Here's the context menus example.
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
Regex is the best option.
that would work
I've got one if you want it
Do you have to stop a View if I already have cleared the items?
no, but it is good practice
please help me fix the rate limit
what are you using to host your bot?
SparkedHosting
well, your host is ratelimited.
contact your host to see if they have alternative IP addresses.
the host's
is there just another host i can buy?
this host support is so ass
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
Railway isn't good anymore.
nothing else which is as good is free anymore
there are a few that require a credit card for verification
like i recently found out oracle free vps
rather than using an id snowflake regex, use a message link regex?
i built this in 5 mins https://regex101.com/r/9hMHsa/1
you can then use match.group("channel_id) to get the channel id
ive already got a working code, but thanks
lol aight. good for me anyways
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
@silver moat
there is likely an abuser as there is only 50 bots on this IP.
Is what they said
50 bots on the same IP? Jesus
"Only" sounds like a lot
I've been liking Railway, but I just got rate-limited the other day >_>
(Been using for 3 months)
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
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)
You probably did ctx.respond(embed) vs ctx.respond(embed=embed)
oh thank you
Hi, Is it possible to make a slash_command with a multiselect dropdown (with choices or autocomplete) ?
Yes
How ? ahah cannot find the option
You can’t do a select menu while invoking a slash command no
With galaxygate I get around 20-30ms
It's about that option list
Yes thanks, I based my development on this example! But if I understand correctly, it is impossible to do multiselect with this
pretty sure you can't, unless you just add a bunch of optional parameters with the same options
Thanks for the advices 😉
That’s pretty good. I think I get 80 on Railway
It's very dependant on where the server is located though. Pretty sure mine is in NYC
For sure
Upgrade your pip with
python3 -m pip install --upgrade pip
How can I make a command appear just by pinging the bot and nothing else?
Check for the bot's mention in your on_message event
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?
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?
Tell me why the error output on cooldown is ignored
on_slash_command? And what do you use
Slash commands
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_perms.py
I assume this works for subcommands
looks good, I'll give it a try, thx
can someone help me
im trying to make a welcome bot for my server but nothing works
?tag idw
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.
The code was good but it did nothing
That answer doesn't help either, you are not showing your code, you're not explaining in detail what's wrong.
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.
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
Hey all 🙂 hope you are fine
Is there a way to enable/disable a command by a boolean flag ?
set a counter variable to 0
iterate through user.roles and search if the emoji is in the name
add 1 to the counter for each such role
this is the code
nothing wrong but i dont work
dont judge me i just started with python
first of all. its on_member_join
also what is client.send_message(member). thats not a thing
?tag lp
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
discord bots shouldnt be in your early states of python learning. it will confuse you
👀
Be nice to people who help. You showed no code.
Take a look at this
https://docs.pycord.dev/en/master/api/application_commands.html#discord.ApplicationCommand.before_invoke
You can make your own check with it.
Or just and if statement at the beginning of each command.
Thanks mate !
Hey ! I have a little problem with the menu 
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 !
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?
Your token is wrong
@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 😄
You can pass it right to SlashCommandGroup with
https://docs.pycord.dev/en/master/api/application_commands.html#discord.SlashCommandGroup.default_member_permissions
You can send, edit, delete and more with interaction.response.xxx
https://docs.pycord.dev/en/master/api/models.html?highlight=InteractionResponse#discord.InteractionResponse
I think the answer is no, but is it possible to subclass Interaction? (And thus always get that subclass rather than discord.Interaction)
yes
Oh? Documentation link? I didn't find anything
#faq
you find anything there
I wasn't asking for a link to the general documentation. I was saying I didn't find anything in the documentation
I'm assuming I can work some magic via the mechanism in here: https://github.com/Pycord-Development/pycord/blob/master/examples/custom_context.py
Basically, make a custom context that creates a custom interaction?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/custom_context.py at master · Pycord-Development/pycord
basically, yes
Thank you
And this continues to be unhelpful, as I already noted
Please stop pinging me, dude
k
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?
seems correct
is there a way to deactive something like that?
Please only contribute meaningful and helpful ideas here. Thanks.
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
you can look at threading.
Alr
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
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
try upgrading your pycord version to 2.2.2, and then retrying it
It's no longer throwing an error, but now it just continues, and doesn't disable the components. Can the on_timeout() callback and disable_on_timeout parameter coexist?
disable_on_timeout is a parameter of View
.docs discord.ui.View
correct, which is why i'm confused that it doesn't seem to apply to my "view" variable (which is using the view class)
You have to define it in your __init__ if you subclass
So that way you can actually set it
Since rn you are setting something that doesn’t exist 
Shouldn't you be able to just do disable_on_timeout=True
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.
it disables them but doesn't update the view
you should update the view yourself
Oh what the heck? What's the purpose then? Either way, thank you so much for the clarification!
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.
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
Yea, that's what i was looking for
Thx for your answer !
hey guys, are the new permissions changes in py-cord?
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
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'
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
init__(timeout)
class AirDropView(discord.ui.View):
def __init__(self, timeout=None):
like this?
that seems loopy
the other one
class AirDropView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
so like this
yes
In December 2020, Discord released their first Interaction: the
this should help you
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
^^
You need to initialize discord.Permissions instead of accessing an attr (discord.Permissions(administrator=True))
Interactions>UI Components
Amazing, thank you
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
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
what do you mean like muting somebody in vc or in like chat?
chat
like mod bots do
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
?that stops user from pressing buttons too?
the timeout i think does?
let me check
i did the roles thing but somehow user was able to somehow send messages mybe because of everyone role has sending messages enabled
ye if it does then i will change it for that thnx
I would assume so because it stops interaction but you might want to check
oki thnx
ephemeral
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).
read the docs:
This parameter does not apply to interactions of type
InteractionType.application_command.
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
hi
cool
oh i think it just worked wot
lmao nice 👍
show pip list
your environment is probably fucked . python 3.8 3.10 and 3.11 at the same time
hmm
hmm
can remove 3.9 (ms store that i don't use)
but it worked on 3.9
so i think that has pycord
HEH
🤦
ikr 💀
what's the diff
well pycord is a wrapper for ffmpeg or smth
ffs
barely any users but owner of that lib is not ready to switch
AYYYY
no error!!!
now what?? (added a guild to test guilds)
(still logged in tho)
you have functions with the same name
or you are registering them twice
No tag github found.
?tag install
- 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
why do python break everything in "bugfixes"
?
3.11 is labelled as a "bugfix" but it still breaks loads of things
where do they call it a bugfix 💀
embed=embed
lmao
still no
^
unindent the insides of that function by 1 level
that shouldnt make a difference tbh
i get this when starting the bot, but it still goes onlin
why is self there
pretty much the 2nd last line
if it’s in a cog the command itself should also be indented
?
(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!)
except there's only one command
send full error and code
commands.slash_command
and I gtg
oh wait
no, it’s discord
you are using discord.Cog
yeah
yeah i forgot about that, what should it be??
what you are doing it correct
heh
well which type of bot are you using?
idk!! slash comnads????
.
bot = discord.Bot
does discord.Cog work for commands.Bot?
ah
yes
ouu
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??
oki
click the link
I did that lol
so enable virtualization from bios
so virtualization is enabled in the bios??
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
why is it that the simplest of all bots have the most errors 😩
heh
still got the command name must be unique error. give a sec for other thing
FUCK SAKE
still doesn;t work. same errosr
and @commands.slash_command
💀
o
show updated code
pushed to git
hmm
use a different bot's token
this one might be cursed
heh
i honestly have no idea whats wrong
IDK BUT IT WORKED
why can't my command be named ping
if i do that, i get the "Application commands must be unique"
do you have another instance of the same bot running with a command named ping?
or maybe lots of bots with ping command in your server?
also no
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
?
do that once and then remove from your code
where do i put it
in an on_ready event
You need to create a permissions object like this
discord.Permissions(administrator=True)
I think I’m just not able to read the docs properly
Is this stated anywhere in the docs and I just missed it or should I be able to know how to do it myself
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)
fixed it..... i had a template cog and forgot to a) change file extension and b) hash the code
it works now
Thank you, I hadn't seen it.
Is there any way to not respond to a slash command interaction?
In my case I need to send the message with channel.send() so that it can be edited after the token expires.
no
Ok, thanks.
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))```
Your setup function should not be in the class
i still got the error
How are you loading the cog?
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())
I usually do an ephemeral with delete_after=5 or something like that
When ı search, ı can't see anything.
Where do i find documentation?
oh ty lol
Can you search in the documentation?
yeah with ctrl + f
There is a search button
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)
```
?tag message-content
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
thanks
Why the hell you're running two instances
where
here
im new to both python and pycord, your gonna need to be more specific lol
at your code
learn python basic first
You're subclassing discord.Client, then running then creating a commands.Bot instance and creating a command.
you will have many problems if you dont know the basic´s of python
Read rule 1 in #help-rules
im a fast learner
oh bruh
clear :d
ok bye
ok?
Good luck 👋
Is it currently working?
wdym
Works well.
It works in incognito tab. I think my chrome account broken
Do a hard reload then
anyone know why it says discord doesn't have an attribute named "Bot"?
bot = discord.Bot()```
Because probably you're using an outdated version.
is their an updated version on replit?
?tag replit
Read this to find out how you can install Pycord in Replit
Old instructions: https://web.archive.org/web/20211128084858/https://namantech.me/pycord/installation/#replit
New instructions: #998272089343668364 message
thanks.
no im getting this
flags
then use py-cord 2.2.2
ah
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:
Is python 3.11 supported in version 2.3?
yes
I might upgrade but test first also because a few libraries are broken with 3.11
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
Hey all 🙂
Do you know if it is possible to make a command that self-reboot the bot completely?
Hello, if I work on application command event, what should I need to do next?
Like process what?
Pls help me, thanks
what's your current code
also if you have an issue, first thing. read the docs and guide
I can't find the answer in docs and guide
On application command
Does it need await self.bot.process_application_command(ctx.interaction)?
I've never really used cogs so...
then why did you use @commands.Cog.listener()
You can see that as @bot.event
from what i can tell, you've probably subclassed discord.ext.commands.Cog and made your own class from it (as a default template). You'll need to get the base class, which would be commands.Cog. Then from there, get the listener decorator
yes if u want to register an event in a cog, you'll need the commands.Cog.listener decorator
can you use bridge.has_permissions with commands.Bot?
Because I do want to add both checks at once as sometimes discord.default_permissions do not work
That could be a solution.
In the end I opted to send an empty message (\u200b) and delete it right after.
And I send the message with channel.send().
The problem is that with this I increase the requests that the bot makes each time it executes the command, but it is the most transparent way for the user that I could think of.
How do I know if the bot is disconnected from the voice channel? (Force disconnect like ban)
Check out this event.
https://docs.pycord.dev/en/stable/api/voice.html#discord.VoiceProtocol.on_voice_state_update
You will have to check if it is your bot and if the channel is None I think.
Otherwise you could check with
https://docs.pycord.dev/en/stable/api/voice.html#discord.VoiceClient.is_connected
i cant find it anywhere
Okey, I have a music bot.
I use play command, bot is playin song a.
When i disconnect bot (force) and use join command, bot still playing song a.
I can't check in the Join command because the player shows as NoneObj.
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
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')```
help
The indentation
It's wrong
where
how lol
try sending an ss and telling me what to change
there should be no spaces on the left side of the bot.run keyword
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")```
i did
oh it worked
What did you do?
np
whats the diff between slash_command user_command and normal bot.command(()?
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.
and bot.command can be invoke with the prefix i give ?
and do bot.command come in a list like the slash command
and bridge_command all of them
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
How can i find when someone has clicked a hyperlink in a embed? so it will send another emphermal embed once clicked
you can't
f
🤔 I'm getting the same issue as you. I've tried it out on my end and it results in the same 50008 response. It may be an underlying issue, could be wrong about that though.
I spent hours last night trying to figure it out 
@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.
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
If it is the case that it is concerning the library, perhaps opening an issue if it already isn't present is a way to go. Though I hope the workaround can assist you in the meantime.
yes
what exactly are the new Guild features?
##1788
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
add an __init__ and pass timeout=None to remove the timeout
thanks
something like this?
Use super().__init__
oh yea
Ahhhh How do I fix this it keeps coming on my host logs?
use a different host
Why?
because if they are 40+ seconds behind, then they aren't a good host
Strange as the host is servers are in New York.
Or somewhere in US.
How can I make my bot get user id?
user id from... what?
a user that used one of my commands. I know already how I can verify if the user id matches but have no idea how to make the bot fetch it.
where is the ID you want to check for stored?
it checks if the user id matches on "if" line.
so the ID is static?
yes
what happened to blocking code? couldn’t that be the issue?
good point. @indigo badger?
it did what you wanted it to
Because you set it as a thumbnail
.docs discord.Embed.set_image
.tag embeds
What do you mean by that could you take a pic of the kind of code you mean?
Do you use the requests library?
No I don’t think I do.
What is data?
Literally says it there
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?
Hello 🙂
I'm in a COG and I want to set dynamically an autocomplete Option, do you know a way to do that ?
What the cog doin'?
Slash commands, events, private methods
Hmmm I can't because it's not a static data source to fil the autocomplete
explain what you're wanting to do
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 :
Create the function outside your class
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 😦
help pls 
Get the player before disconnecting and then just stop it and clear the queue
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
You can use autocomplete and populate your own member list
thanks...
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
I'm using this snippet as a base, and included the bit about registering the cog, and even specified a guild to avoid the slash command registration timer, but no dice
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_cog_groups.py
Please share your code
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
did u move the bot.add_cog to the setup func at the end of the cog ?
I did not. I put it in bot.event def on_ready() with the other cogs I register
that the issue?
i may be incorrect, but i suspect that's the case
thank you, I'll try it out
np
bot.add_cog() registers the class you pass in as a cog, and bot.load_extension() actually loads the cog file
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
I think you can pass a custom view to each page
Or custom buttons or smth
Put the row id as 2 so it will be displayed below the paginator controls
Hey 🙂 Is there another way (don’t want to cal my DB outside of my class if possible 😌)
You haven't defined "channel".
Also if you were to send it to every server, they would hate you. Instead, make it post in an announcment channel in your support server, and code the bot to automatically publish the message. Anyone who wants the messages can follow the channel.
it won't ping @everyone so I don't think they'll care
it'll just send a message once
in general
without pinging anyone
can i not put it next to say the page number
buttons=[
PaginatorButton("prev", label="", style=discord.ButtonStyle.green, emoji="◀️"),
PaginatorButton("page_indicator", style=discord.ButtonStyle.gray, emoji="📄", disabled=True),
PaginatorButton("next", label="", style=discord.ButtonStyle.green, emoji="▶️")
]```
Yeah just set the variables to the labels to be page number minus one and page number plus one.
so how do I do it
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
among us
can u use @bridge.has_permissions with commands.Bot with slash commands
you have to use bridge.Bot
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"))
jishaku uses prefix commands. that needs you to use commands.Bot instead of discord.Bot
and from discord.ext import commands in your imports
did you installed it and which version?
thanks
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
you need to update pycord on 3.11
pycord 2.3 supports python 3.11
ohh ic
use pip3.11 ...
that doesn't mean pip matches it
happens 
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"))
uninstall it and try the git version
good idea
pip install -U git+https://github.com/Pycord-Development/pycord
any errors in the console?
clear
try discord.Intents.all()
not working(
hmm what jishaku version?
jishaku==2.5.1
how are you running the file?

