#Basic Pycord Help
1 messages ¡ Page 22 of 1
How to upload an animated avatar for your bot
To use and upload an animated avatar you can run the following snippet as standalone script:
import discord
import asyncio
# Intents to enable certain events
intents = discord.Intents.all()
# Create a Discord client instance with intents
client = discord.Client(intents=intents)
# Event to handle bot's initialization
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
# Upload animated avatar
try:
with open('yourpicture.gif', 'rb') as avatar:
await client.user.edit(avatar=avatar.read())
print('Animated avatar uploaded successfully!')
except Exception as e:
print('Failed to upload animated avatar:', e)
# Run the bot
client.run("YOUR_TOKEN")
That should be all, have fun!
Why is asyncio imported?
bc is the only way to do it
no reason
Is there a way to check if a member is timeouted?
got it thanks
What is the max time to timeout a member?
1 month? But Im not sure about it
It's not used in the script?
28d
Ok
why this and not dev portal
Dev portal did not support it for at least a little bit
What's the max. amount of characters one can hand over to ctx.respond?
4000 as raw content iirc
That's awsome! Less adjustments needed in my project đ
Thank you Great Squid
just tested it, 4k failed, 2k went through, 2001 failed
It's just my opinion but user experience wise I don't want 4000 characters, especially if I am on mobile.
There any way to check a user for a certain tag such as Moderator to allow them to use certain commands? E.g.
Moderator tries to use a / command which allows them to use it
Random Discord Member tries to use / command (I want to either not show up to them or check their roles to see if they are a Moderator then send an await back to them with a message)
This should be done in integration settings most of the time
I'm not following, can you explain a little further?
In server setting an admin can allow and disallow roles and users to use commands. Q
Ah I see, but is there anyway to check roles on a user out of my own interest
Server settings, integrations, your bot, your command
Ta
I've got a new issue with a pinging a role
admin_role_id = 1212135665811193906 # Replace with the ID of your admin role
admin_role = interaction.guild.get_role(admin_role_id)
if admin_role:
try:
await interaction.followup.send(f"<@&{admin_role.id}>, please check this ticket!")
except discord.errors.HTTPException:
await interaction.followup.send(
"Failed to ping the admin role. Make sure the bot has the necessary permissions.")
else:
await interaction.followup.send("Admin role not found!")
For some reason, its not pinging my admin_role, any assistance would be grand
@commands.Cog.listener()
async def on_member_update(self, before, after):
print('1')```
Shouldnt it print 1 if i update my presence to spotify
Why are you getting the role by ID to then get the ID again for the mention?. Plus try passing allowed_mentions=
.rtfm allowedMentions
Itll print 1 for any presence change...
I know but it doesnât do it
You need intents.presences and intents.members for it to work.
Youre using on_member_update
That event doesnt trigger presences or status changes
on_presence_update does
Read. The. Docs.
zamn
guys i forgot the library i have to install in order to make discord.commands work, when i run the code i get this error:
Traceback (most recent call last):
File "d:\Users\Davi\Desktop\programas\codes\python\pycord\accionar bot\main.py", line 3, in <module>
from discord.commands import Option, OptionChoice
ModuleNotFoundError: No module named 'discord.commands'
its discord.ext.commands
ahh ty
how have you made it this far?
itâs honestly impressive
Prompt engineer 
guys what is wrong with my code
import discord
from discord.ext import commands
from discord.ext.commands import Bot, Context
from discord.ui import View
from discord.ui.button import Button
from discord.ui.select import Select
from discord.ui.modal import Modal
intents = discord.Intents.default()
intents.members = True
class PersistentViewBot(commands.Bot):
def __init__(self):
super().__init__()
self.persistent_views_added = False
async def on_ready(self):
await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name=f"Pycord 2.4.1"))
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
bot = PersistentViewBot()
# ------------------------------------------------------
@bot.slash_command()
async def test(ctx):
await ctx.respond("Hello world")
# ------------------------------------------------------
bot.run("")
it gives me this error
Traceback (most recent call last):
File "d:\Users\Davi\Desktop\programas\codes\python\pycord\accionar bot\main.py", line 23, in <module>
bot = PersistentViewBot()
^^^^^^^^^^^^^^^^^^^
File "d:\Users\Davi\Desktop\programas\codes\python\pycord\accionar bot\main.py", line 15, in __init__
super().__init__()
TypeError: BotBase.__init__() missing 1 required positional argument: 'command_prefix'
i dont want to have a prefix
i want my bot to be 100% operated by slash commands
then use discord.Bot
use discord.Bot instead of commands.Bot
oh ok
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
now it says discord has no attribute Bot đ
python version?
3.12.1
are you using discord.py or pycord
pycord
are you sure?
pip list (or equivalent on your machine) and show output
that would be an issue
i uninstalled discord.py then the terminal is saying that there is no module named discord
restart vsc
nothing changed
is the correct version of python selected?
ye
can you do pip list (or equivalent on your machine) and show output
py-cord not pycord
i cant download a specific version for some reason
i tried it too
when i download py-cord it gives me this error
?tag install
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
use the master branch
what isn't working
at 2a
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
that was the only thing I wanted you to do
Do this master is broken atm
pip install -U git+https://github.com/Pycord-Development/pycord@fc7b1042c4a9a942b9996dfe96f56aac059e179c
ERROR: Error [WinError 2] O sistema nĂŁo pode encontrar o arquivo especificado while executing command git version
ERROR: Cannot find command 'git' - do you have 'git' installed and in your PATH?
what's the issue exactly. Is there an error you are getting?
i just put it on path tho
Ain't no way they broke it again
hmm I don't use windows
back then it worked just fine
does it have something to do with the fact i got a new pc?
yeah, only master works with python3.12 right now and the current master is broken unless you go back a few commits, which requires git
ahhhh
potentially
tf is broken on master
im downgrading rn
He do be a problem solver
we should still support it
that should be mentioned on the issue
done
for some reason ephemeral does nothing, idk why
another thing, .defer(invisible=True) also doesnt work for me
You have to use ephermeral at the defer and interaction
No tag ephermeral found.
?tag ephemeral
An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.
To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)
This is the equivalent of hidden=True if you're coming from interactions.py
e.g.
await ctx.respond("Imagine a message!", ephemeral = True)
await interaction.response.send_message("Imagine a message!", ephemeral = True)
Guys, I can't make up my mind. I have 3 versions for a simple check. All 3 do the same and work. Which one would you pick and why?
if isinstance(ctx.channel, discord.channel.DMChannel):
return await ctx.respond(f"{await get_dm_text()}")
if not ctx.guild:
return await ctx.respond(f"{await get_dm_text()}")
if ctx.guild is None:
return await ctx.respond(f"{await get_dm_text()}")
What do you mean
I would pick the second one. It's less of a check and easier to read
I would say the first as this will guarantee that the channel is a DM. For example if discord adds something like a global event channel that does not corespond with a guild but is not a DM channel.
Essentially what I am saying is the first is more future proof.
i fixed it ty
pycord does not currently support setting the status of a voice channel does it?
What is the purpose of a stage instance? Can't I just use the channel?
no
thx, do you know how I can make the bot able to speak in a stage channel?
do stage channels even have an attached textchat
oh, yea
well, the 2.4 release doesnt support it
but the latest github version does
no not write, speak
oh
Hi guys,how can i make my command is called once and works everytime,in my code it sends from 'chat.json' just when i type !chat again
what are you even trying to do and what is the issue
im trying to send a data to my discord channel from chat.json when i type !chat
also i dont get where you are expecting an httpexception other than .send(), and then you are just sending again
.json changes everytime,sometimes its empty
then fix the part of your code that edits the json
i fixed it already
do you know how to use a json?
i just want to make my command called once and works everytime
yea, well, you are overwriting the json every time like that
when i send !chat to channel it works just once and i need to type !chat again
message is a string and not a dict or list
i literally have no idea waht you want
of course the code only runs when you type !chat
its not
let him cook
So you're asking in a library you don't use support server for help with other library?
Which isn't even related to the library itself
its related
damnnnn
does your bot use py-cord?
Writing json files isn't related to a library
oh, yea
what a smart thing to do
that too lol
I wonder if you are new at coding or new at creating a discord bot
prolly just new at life in general
also just a tip
if you get an httpexception while sending a message, usually, trying to send a different message again wont fix that
You're not using py-cord...
hey my js bot isnât working can you help me pls?
nuh uh
.js.py?
nu
xd
js.js
@bot.on("messagestr") isn't pycord
rs.js
next time try to help
bro
its from another file
not from main
it could be pycord, they just rly donât know what theyâre doing
Lmfao
you are a funny guy aren't you ?
i mean
yis
you say you use pycord
while saying that the non-pycord code comes from another file
so logic predicts that your main.py uses py-cord and your other files, for some reason, use discord.py
you dont need to try understanding what im doing
i just asked
a simple thing
i-
about pycord
ion even think you understand what youâre doing
literally this isnt about understanding my guy
if you dont use pycord this is not for you
The simple thing is: you're not using pycord
then youâre doing it very wrong
but why do you have code that isn't pycord
the ss i sended is from another file
if u look the first one
u will see
you already said that
so how does using discord.py in one file and pycord in another file work?
many times
hint, it does not
bot.on is from d.py?
dude i dont know, but it aint from pycord is it
It aint
maybe thatâs the problem
.rtfm Bot.on
discord.Bot.on_application_command_auto_complete
discord.Bot.on_application_command_error
discord.Bot.on_connect
discord.Bot.on_error
discord.Bot.on_interaction
discord.ext.bridge.Bot.on_application_command_auto_complete
discord.ext.bridge.Bot.on_application_command_error
discord.ext.bridge.Bot.on_command_error
discord.ext.bridge.Bot.on_connect
discord.ext.bridge.Bot.on_error
discord.ext.bridge.Bot.on_interaction
discord.ext.bridge.Bot.on_message
discord.ext.bridge.AutoShardedBot.on_application_command_auto_complete
discord.ext.bridge.AutoShardedBot.on_application_command_error
discord.ext.bridge.AutoShardedBot.on_command_error
discord.ext.bridge.AutoShardedBot.on_connect
discord.ext.bridge.AutoShardedBot.on_error
discord.ext.bridge.AutoShardedBot.on_interaction
discord.ext.bridge.AutoShardedBot.on_message
discord.AutoShardedBot.on_application_command_auto_complete
maybe thatâs why itâs not working
when why tf did you send it here

yes i am
what would refer to with bot if not a discord bot
And that's not how pycord handles events
but not using discord libraries
sure
whats wrong with channel.history, or a persistent array
if you donât want to explain your code why do you think anyone here would be able to help you?
if u look what i sent
sender
u can understand
sended
what i want to know
you want to know how to use json
nah, iâd rather be mean
yeah
this is not a help channel for sure
i mean okay realistically, you wanna know how to store data across command / event invocations
learn to use json then
is json pycord now?
if thatâs the case, why do you even show up that irrelevant code?
do you go to ford workshops to repair your ferrari?
its not about json
i-
then what is it about?
iâm pinging lala
I love how he contradicts himself
@unkempt cipher
as i said
help please
You have the discord-facing part of your code figured out
Now figure the storage part out
That is neither pycord nor discord related
if you want it quick and dirty declare a global list and use that
happy?
json is painful
yeah-
its not helpful for my thing but its an answer
list >>> json
thanks
how is the literal solution not helpful
i literally said its a crude but quick way of doing it
but your entire code looks to be exactly that
Bot variables exist
now that thatâs sorted out, my laptops not working can you guys help?
this is a help channel for everything right?
damn-
what
global list >
?tag botvar
Need to keep track of a variable between functions? No problem!
â ď¸ Careful what you name it though, else you might overwrite something â ď¸
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
right
but global is funny because my IDE says its wrong so i am rebellious by using it
i love that XD
i mean
thats really a sql question and not pycord specific
but really, you dont need to close it
ohh
sorry, i will delete it

I want to begin sharding but currently use a SQLite database mounted to a docker compose container where the bot runs and I'm assuming I would run into file locking issues if I were to run two instances of the bot connected to the same database. My plan is to migrate to MariaDB that way I can have multiple DB connections without issues.
My question is: how are commands/events handled with auto sharding? If I have two instances of commands.AutoShardedBot running the same code, what happens when a command is executed? Do both instances pick it up or does only one instance pick it up and run with it? Same question with events - if one is triggered and the listener for the event is on both shards running the same code, do they both get triggered or only one?
hey im trying to download pycord for windows but im getting an error, i found a stack overflow page that matches my error: https://stackoverflow.com/questions/74550830/error-could-not-build-wheels-for-aiohttp-which-is-required-to-install-pyprojec but this is from over a year ago is aiohttp support still in beta and how do i go about changing my aiohttp version as said in the top comment
What python version you have?
3.12.0
only the maste version (aka github version) supports 3.12
you either downgrade or install the master branch
which, afaik, it is broken rn
how can i use slash commands in cog file
Here's the slash cog example.
is the interaction still working with slash command?
What?
interaction: discord.Interaction?
Slash commands never receive an interaction object
They receive a discord.ApplicationContext object
ah okey thx
Anyone who is working on the audio features of pycord, please take a look at this thread: #1212491741018456134
guys i cant download py-cord for nothing in this world help me
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for aiohttp
Failed to build aiohttp
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
i get this error every time
help pls my boss want me to use pycord
are you using python 3.12?
If you are, please use the master branch or wait a few days until we get a release
You can install the master branch from
?tag install
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
the last paragraph
Is this not a quick question? I can make a form post
Why would you run two instances
I was looking for a way to troubleshoot submitting my botâs server count to an API without taking down the bot which lead me to learn about sharding. I read in the guide it says eventually if a bot gets large enough it will have to be. My bot is at 1,900 servers so I want to start looking into how I can implement it for when I eventually have to
commands.AutoShardedBot should handle everything related to the sharding
I don't have specific experience with sharding, but I'm sure it's just changing that and letting the library handle the stuff
Not sure if there's a guide
All about Sharding Discord Bots.
Yup, this is what I learned from. I might just try it out and see what happens. I just want to make sure there wonât be two instances handling the same command leading to double everything⌠lol
Does anyone know why the on_timeout isnt working for me
the application just doesnt work
only the discord.ui.View class â not discord.ui.Select â has an on_timeout method.
Itâs not firing?
The default timeout is 180 seconds (3 minutes). So it was set to that timeout.
What is the best way to store user config?
It's a newbie question but I want my bot to be organised
I would use a database for it
you can use a SQL database or a NOSQL database
I use MongoDB which is using some json format
Ah I see, thanks
Task was destroyed but it is pending!
task: <Task pending name='pycord: on_message' coro=<Client._run_event() running at /usr/local/lib/python3.10/site-packages/discord/client.py:378> wait_for=<Future pending cb=[Task.task_wakeup()]>>```
i get this error almost on every restart. What i have to do
discord will only send events to a single shard so you will only receive one event
code wise, an autoshardedbot acts as a single client
Perfect, thanks
What if separate shards have different code? For example, if I have an event listener on one of the two shards but not on the second shard, will it know to only trigger the event on the shard that has the listener for it?
can you even have different code for different shards
Is there a decorator for listeners in a bot subclass?
bot.listen()?
Cog.listener()
in the class. Like:
class MyBot(discord.Bot):
@listen...
async def bla(self):
...
Yeah maybe, will try that.
but why do you want to have it at the bot class and not in a cog?
it makes a bit more sense there and its' not really big enough to get it's own cog xD
actually...
yeah a cog makes sense lol đ

Is there any error that specifies kwargs in an on_error event? only seen args so far...
is there a way to ad clickable links to embeds?
Just paste the link?
The bot will also need to have embed links permission
sorry should have worded it better
but not in the title? thats where im trying to do it
The title has its own attribute for that.
url=
Embed(title="My Link", url="https://google.com")
alr thanks :3
can I set the image of an embed to a Pillow image?
I have tried this
file = discord.File(fp=image_to_byte_array(image), filename="image.png")
embed.set_image(url="attachment://image.png")
await message.edit(embed=embed, file=file)
Does it throw any error?
ValueError: unknown file extension: from file = discord.File(fp=image_to_byte_array(image), filename="image.png")
k ty
There was a problem with my image_to_byte_array function now I get this error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
wtf is attachment://image.png
I don't know I found it in stackoverflow
https://stackoverflow.com/a/74275578
.tag localfile
Tag not found.
Did you mean...
local-file
.tag local-file
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
Not sure if that helps, I think you were already doing that
so I have to save the image then use it?
No fp takes bytes too
but I can't convert a pillow image to bytes I tried byteIO, tobytes and getdata
To me it looks like you are doing things right, I can't help further sorry.
If a user has more than one activity is there a way to get them all?
why do I get discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message error when I try to use channel.fetch_message? I have checked the channel_id and message_id
The bot cant get the message
why?
message intent activated?
what is message intent?
?tag intents
Pycord Docs - Intents
Discord API Docs - Gateway Intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
I should put this in my code and enable it in discord developer portal?
Right
ok
Member.activities?...
Read the docs.
I still get the same error also pycharm tells me 'Intents' object attribute 'members' is read-only
Send code
Thanks
what part of my code?
The part where you define your intents?...
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True
intents = discord.Intents.default()
intents.members = True
intents.presences = True
intents.message_content = True
intents = discord.Intents.all()
bot = discord.Bot(intents=intents)
...
async def process_queue():
await asyncio.sleep(5)
while True:
# Get the oldest entry from the database using the Database method
entry = db.get_oldest_request()
if entry:
request_id, channel_id, message_id, user_id, prompt, _ = entry
file = discord.File("image.png", filename="image.png")
channel = bot.get_channel(channel_id)
message = await channel.fetch_message(message_id)
await message.edit(content=f"**{prompt}**", file=file)
await asyncio.sleep(5) # Check queue every 5 seconds
# Start the queue processing task
bot.loop.create_task(process_queue())
bot.run("My Token")
You just need the message content intent
And why are you defining your intents three times?...
sorry I will change intents to just be discord.Intents.all()
what do you mean?
inside discord developer portal?
yes
ok
I still get discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
its from message = await channel.fetch_message(message_id)
then you are most likely fetching a message that doesnt exist
also, why would it not be cached?
I tried bot.get_message but it didn't work
same error?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
oh no sorry wrong error
and the right message ID
last time I checked the message ID was correct but now its not
well get the right one then lol
sorry
get_message gives me this error TypeError: object NoneType can't be used in 'await' expression
hm
also I'm using message = await ctx.respond() and message.id to get the message ID so I can change it later but its different from the value I get when I copy it from discord
uh yea thats not how it works
respond returns an interaction
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
so you need to do (ideally)
interaction = await ctx.respond()
message = interaction.message
I'm sure this is been asked before but can't find anythign definitive
I have a Message Command. Is there a way to acknowledge that interaction without writing an actual message about it?
Not really
You could call ctx.delete
That just removes the interaction
why does interaction.message return None?
there is no Dismiss message button on the message
hm
hi im kinda losing my mind rn because the solution is probably really simple but, I have a bot set up to join voice chat, listen and transcribe audio, then if it hears its name spoken get a response from an AI and send back the response. then the response goes through edge tts and outputs an mp3. HOW can I get the bot to immediately play the mp3 file into discord voice, im completely failing on all the solutions ive seen around
Objects: Attributes average_latency, channel, endpoint, guild, latency, loop, session_id, source, token, user. Methods async disconnect, def is_connected, def is_paused, def is_playing, async move_...
yeah this is what i tried but it keeps telling me it doesnt have is_connected
Could you show the traceback?
ok justa sec
just paste it in a code block?
Traceback (most recent call last):
File "M:\miniconda\envs\yui\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\nani\AppData\Roaming\Python\Python38\site-packages\discord\opus.py", line 556, in run
self.client.recv_decoded_audio(data)
File "C:\Users\nani\AppData\Roaming\Python\Python38\site-packages\discord\voice_client.py", line 841, in recv_decoded_audio
self.sink.write(data.decoded_data, self.ws.ssrc_map[data.ssrc]["user_id"])
File "m:/Desktop/YuiAI/Yui2Voice.py", line 186, in write
global_stream_buffer.write(data=data, user=user,wtime=time.time())
File "m:/Desktop/YuiAI/Yui2Voice.py", line 116, in write
asyncio.run(ys)
File "M:\miniconda\envs\yui\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "M:\miniconda\envs\yui\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "m:/Desktop/YuiAI/Yui2Voice.py", line 148, in yuispeak
await yuiaudio()
File "m:/Desktop/YuiAI/Yui2Voice.py", line 168, in yuiaudio
discord.VoiceClient.play(source, source, after=None)
File "C:\Users\nani\AppData\Roaming\Python\Python38\site-packages\discord\voice_client.py", line 657, in play
if not self.is_connected():
AttributeError: 'str' object has no attribute 'is_connected'
this whole project is hacked together so i have no idea just how broken this really is (its more impressive that it works at all in my opinion đ )
see thats why im confused cause i dont know why its calling that either
using the voiceclient.play is calling for is_connected and idk if im just not using it in the wrong place or what
discord.VoiceClient.play(source, source, after=None)``` according to the traceback?
i mean you have to know that, dont ask me lmfao
but yea i wont be much help tbh, i have never touched voice
yeah idk why its bringing up a connected issue either 
You can ignore pycharm about intents, something is wrong in the formatting but the code will work fine
you dot accidently override discord.VoiceClient anywhere?
the only instance in my code is the line that errors at, should i be calling something else to play audio?
try using original_response instead of .message
Sorry, im have never worked with voice. Im not entirly sure. Might be worth making a post and sending your code
Ok maybe one of you can help me this way, I have a command that can play the output audio when you do >r
is it possible to call / execute it from somewhere else in code instead of sending >r as a message in a channel
@bot.command()
async def r(ctx):
voice = discord.utils.get(bot.voice_clients,guild=ctx.guild)
audio = FFmpegPCMAudio('testshift.mp3')
voice.play(audio)
this 'just works' as a command, can i call / execute this from somewhere in code instead of using a discord message or is it required to be from a discord message
You cant call it from something other than the message as it depends on ctx and you dont have ctx when you dont have a command. What you should do is make a function that takes guild as and argument and have both the r command and the other code call the new function instead.
i get nothing but errors if any of the commands code is outside of a command im starting to think its either not possible or above me 
Then show the errors smh
i did?????????????
Do you use pycharm and know how to set breakpoints and debug? That would solve this pretty quick
Is there a good way to store the current View's children (to preserve state - labels, disabled status, etc), modify those children, and then restore everything back to that? Directly modifying the View's self.children causes it to error out when it tries to update the message with the new View state
Context: I want to modify a button and disable all other controls when someone presses a 'Submit' button on a View (as it's deferred, which doesn't give the greatest UI feedback), and if there's a problem, restore it all (and I'd do separate stuff to indicate error, etc etc)
Thank you
Has this question been answered? Asking myself the same question but could not find anything.
.rtfm customactivity
what kind of errors?
Is there a way for pycord to not automatically sync slash commands
No
Yes there is a way to do it
3.12 fails with asyncio
How did you tried to install it?
with pip install py-cord?
nice, how would I do that
If you overwrite the on_connect Event
That would be after a restart of the bot ;3
Wait
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
Guess I dont need to overwrite it

You can
yes
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
honestly don't use 3.12 until you really have to lol
I try to tell Pycharm to use 3.11.x, but its all "invalid"
Also
just uninstall 3.12?
I can try that
thatâs not how you install packages in pycharm lol
you can use the terminal or the package manager at PyCharm
that assumes they're using a venv
Not at my desk, but something about the len() of self.children which I thought was weird since I was directly setting it with data that came from self.children.copy()
with python? I donât think so
yes
which is the default
that doesnât work on unix
I was using it with the terminal and PyCharm was installing it at the env
I havent tested it on unix
Lemme try it at the VM
absolutely not
on the bottom right corner you can see Python 3.12 (or similar). You can change it to a different version.
if it doesnât exist click Add we interpreter
When I do that, I press 3.11, and it yells at me. I uninstalled 3.12, and made a new project, and it is using 3.11
Let me update packages firrt
without any configurations, that is the case
aiohttp fails to install on 3.12
you didnt read
yeah the only thing I saw was someone trying to install using 3.11 in a 3.12 environment
no, not you
Okay, re-asking this question now that I'm not being completely dumb - -
Is there a good way to store the current View's children (to preserve state - labels, disabled status, etc), modify those children, and then restore everything back to that?
Context: I want to modify a button and disable all other controls when someone presses a 'Submit' button on a View (as it's deferred, which doesn't give the greatest UI feedback), and if there's a problem, restore it all (and I'd do separate stuff to indicate error, etc etc)
def save_state(self):
self.child_state = self.children.copy()
@discord.ui.button(row=2, label='Submit', style=discord.ButtonStyle.green)
async def submit(self, button: discord.ui.Button, interaction: discord.Interaction):
self.save_state()
button.emoji = self.spinner # discord.Emoji instance
button.disabled = True
button.label = 'Submitting...'
await interaction.edit(view=self)
await asyncio.sleep(2)
self.children = self.child_state
await interaction.edit(content='Complete?', view=self)
I get the 'Complete?' text, so everything is "working", but the View does not get restored. Stepping through it, it looks like my child_state is a reference instead of the .copy() I'm clearly performing.
So I guess the question is ... wtf?
Can you check the IDs of the items in the saved state and the original. I wonder if they are not being updated?
Well they're the same, because the contents themselves are the same. If .children gets changed (through my direct button.label et al changes), it's changing my .child_state[] array, but I don't understand why since I'm copying.
Unless I guess the members are by reference. This is where I get a little shaky on Python variable access.
Yeah, it must be. I still have my debugger paused, if I do
blah = self.children.copy()
self.children[1].label = 'asdf'
blah
I can clearly see that blah[1] is now 'asdf', where I would have expected it to be the pre-changed state. My head hurts.
I will.. But barring that, what about self.to_components()? I guess I would have to figure out how best to pull them back into the View on restore (maybe a combination of .clear_items() and recreating the component walking from .from_message()?)
copy.deepcopy(self.children)
TypeError: cannot pickle 'TaskStepMethWrapper' object
Hm. Running into issues with Pycord/dpy's own hydrator.
.to_components() returns a list of dicts that represent the data of each component. Then there's an internal function _component_to_item that seems like it's supposed to take that data and convert it to an Item.
Strangely, this seems to expect a class, whereas to_components returns a dict
I'm not sure what use that method has (which calls each Item's .to_dict()), since it doesn't seem to be used anywhere.
While my bot is up I have jobs that are scheduled to execute at a certain time using AsyncIOScheduler. When I restart the bot, however, all these jobs need to be rescheduled and this is turning into decent amount of processing to do after the bot is ready. Does anyone have any suggestions on how I can optimize this process at all?
you can do with a member object or with ctx/guild
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
I see
Thanks both of i
you*
I use ctx.guild.ban()
but at the end they both do the same
guys im having trouble, i want to log chat messages on console but message.content is not showing up nothing. Here is the bot event:
@bot.event
async def on_message(message):
print(f"{message.created_at} | {message.author.name}: {message.content}")
You havent enabled the message content intent if message.content is None
how do i fix that?
?tag intents
Pycord Docs - Intents
Discord API Docs - Gateway Intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
ty
ok
woah look at you being nice
impressive
bottoms don't talk
why not?
can't say it publicly.
?tag cxt
No tag cxt found.
?tag context
No tag context found.
?tag ctx
No tag ctx found.
Someone can help I want to know how to store views like button and select menu to keep working even bot restarts??
Here's the persistent example.
@dense prawn ^
Thx
Does anyone know how I can use ctx to ban,kick, timeout a member(s)
If there is a specific guide on that it will be much appreciated thanks in advance
Okay
Traceback (most recent call last):
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Dell\onedrive\desktop\demo\main.py", line 319, in button_callback1
await interaction.response.edit_message(content=f'Are you sure you want to unlink this account? \nUsername: {self.username} \nGovernor ID: {self.govid}',view=MyView4(self.username,self.govid, self.author, 'main')) # Send a message when the button is clicked
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 979, in edit_message
state.store_view(view, message_id)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\state.py", line 386, in store_view
self._view_store.add_view(view, message_id)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 581, in add_view
view._start_listening_from_store(self)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 425, in _start_listening_from_store
self.__timeout_expiry = time.monotonic() + self.timeout
TypeError: unsupported operand type(s) for +: 'float' and 'str'
what does this mean
where did i did that i dont understand
if you wanna actually do addition, well, self.timeout appears to be a string
did you use chatgpt to make that
nope
copilot? :)
nope made it myself sorry beginner
nah just wondering because of the indescriptive class name and the comment lol dw
previous versions worked
2.5.0 broke it?
let me check which pycord version i have
didnt update but the same code hosted on the real server works. i was testing new things not changed anything in this but it broke
also you are on python 3.9
I suggest updating to 3.11 if you dont have a reason not to
i think 3.12 might work now too since the pycord update
is there a huge advntage in doing hat?
Generally, if you don't have a reason NOT to, it's always a good reason to update
Because if you don't, eventually you will be a trillion versions behind and that might cause other issues
I'll actually try 3.12 now too because i've been wanting to update for a long time but 2.4.1 didnt allow for that
okay will sure do
done understand yet why its taking self.timeout as a string
shouldnt be the cause of your issue though
and the server has the same package versions as you? and you are trying the exact same thing in the same server etc?
i had made some changes to the file but not to this view locally
well restarting my pc did work
lol
3.12 does work with py-cord 2.5 now btw
nice whats the major update in py-cord 2.5
#library-updates
its a minor update though ;)
3.x would be a major update
Now i need help myself lmao
I updated to 3.12 and now jishaku says its sad, what can i do
jishaku just needed a patch version bump
even tho jishaku says it only supports up to python 3.10
Im using it with 3.11 ^^
yea i know
and it works with 3.12 too on the very latest version
i was just using the penultimate one
The main changes are keeping up with discord. We added the username changes, voice channel status, and more that discord added from 2.4
Morning!
@client.slash_command()
@discord.default_permissions(administrator=True)
async def news(ctx: discord.ApplicationContext, order: Option(str, 'News Snippet', choices=['1'])):
"Post news"
How can I make commands exclusive to certain Role IDs
so they can only see them or for just a check for it?
So, it's only visible to people with Role IDs = [4982523857284, 2349327493247]
that is something that each individual server managers will do.
Server Settings -> Integrations -> Your Bot -> Your Command
Disallow everyone, add role to allow
Bots can do that themselves, though
they cant hide the command though.
If you want to be extra sure that nothing gets messed up you can use ext.commands.has_role. This will make the command error out if they dont have the role but it will not make it hidden
Bots can only hide commands by permission, not by role
I meant bots cant set the allowed roles for a command. They can set a default permission only
^ Only staff with manage integrations can add role/channel overrides
Okay that makes sense, I'll have it altered from the Integrations tab and implement ext.commands.has_role as well.
Thank you!
i am 99% sure dyno can properly sync what you set in their web dashboard to discord
like if you set a command to a specific role in dynos dashboard it can sync that to your server
just tried, yep
that's because larger dashboard bots such as mee6 and dyno bypass this limitation via oauth
the reason we generally say it isn't possible is because the average user doesn't have such a setup
Can someone please tell me what the attribute for the Send Voice Messages permission is?
Because with send_voice_messages I get the error "Invalid permissions given to keyword arguments"
you are probably on an old version. Please update to pycord 2.5
Now it works thanks
is there way to use partial_messageable to send dm to user without other unnecessary API calls e.g. for getting user.dm_channel?
if you have the user or member you can just use .send
nah, plain id thats why im asking
also i dont use cache
so i have to call fetch/send or just partial.send if possible
but to use partial i prolly have to use dm_channel.id instead of user.id
.get_partial_messageable(
dm_channel_id, type=discord.ChannelType.private
)
yea I never did stuff with partial, no idea
if there isnât a DM Channel, it wouldnât work.The bot would have to create one each time it interacts with a new user
although if you already have an User object why not just user.send
;p
and what ID is that
id = int
but im not using User model as it is kind of DB task thing
I mean how did you get the ID. Is the ID of an user or what
yep
but ill probably stick to:
if task.guild_id:
channel = self.client.get_channel(task.channel_id)
else:
channel = self.client.get_user(
task.user_id
) or await self.client.fetch_user(task.user_id)
then
well, the dm channel id is different from the user id
yep
đ
thats the sad thing
so ill have to do 2 api calls anyway
in cases theres no user in cache
so you have to make some API request
just wondering, why do you not use cache?
RAM is there to be used
probably privileged intents
yep but not for bots that will use too much
i mean like XX milions of members
lol
man owns mee6
mee6 has billions
milions of users = not guilds
looks fine to me
guys why message.content doesnt work at all
do you have message content intent?
yes
in the dev portal and used in your code?
nah
then you don't have message content intent
oh
can you show your botâs definition
wdym definition
where you define your bot variable
I don't think there is a better option because just calling user.create_dm() will come down to the same thing (or worse altogether) ;p
define= definition
class PersistentViewBot(discord.Bot):
def __init__(self):
super().__init__()
self.persistent_views_added = False
async def on_ready(self):
await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name=f"Pycord 2.5.0"))
print(f"Logged in as {self.user} (ID: {self.user.id}) at {round(bot.latency * 1000)} ms")
print("------")
bot = PersistentViewBot()
intents = discord.Intents.default()
intents.message_content = True
super().__init__(intents=intents)
intents = discord.Intents.default()
intents.message_content=True
super().__init__(
intents=intents
)
lol
message_content not messages
ah fine just for content yeah
messages only makes you receive message events and is included with default
do i put this inside the class?
yes
k
as long as the super is, the rest doesnât have to be
im getting a error
show it
Traceback (most recent call last):
File "d:\Users\Davi\Desktop\programas\codes\python\pycord\accionar bot\accionarBotV1.py", line 57, in <module>
bot.run("TOKEN")
File "C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 766, in run
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 745, in runner
await self.start(*args, **kwargs)
File "C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 709, in start
await self.connect(reconnect=reconnect)
File "C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 646, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
you tell us
it asks me for a redirect url
you need to be more specific than that
what scopes did you check
cant you just limit cache size?
uncheck everything except bot
bot, messages.read and aplication.commands
.
when i uncheck messages.read the link is generated
messages.read does something else entirely
ahh
(You should keep applications.commands if you want slash commands)
bot includes the other
there are way too many scopes btw
which one do i check then
but i need to fix this error bro
we would love to explain every oauth scope, but it really doesnât matter
then do it?
how
itâs under the bot tab
read?
which one do i check
message content
scroll down until you see message content intent
cant find it
screenshot
not there 
dude
the bot tab
oh ok
:)
after a little refactoring I don't use it very often so it would only apply in this case (since with interactions I have the required stuff anyway)
so I think that there is no need for this altogether
oh ok
reading is hard
i think i found it
itâs a switch
yes
ty
I concluded that I would simply use this in this case:
if task.channel_id:
channel = self.client.get_partial_messageable(
task.channel_id, type=discord.ChannelType.private
)
else:
channel = self.client.get_user(
task.user_id
) or await self.client.fetch_user(task.user_id)
so there was better option lol
Is there a way to make an empty message with only an embed actually ping someone?
a reply?
yeah thereâs the invis messages thing so ânoâ content, but I wouldnât do that because itâs like exploiting
yea I was hoping there was some way to either make embed pings ping, or mention people via an argument ig
Ping and immediately edit content=None
it sounds like he wants the message background to be highlighted
that too if possible
Is there a list of breaking changes for v2.5?
it's a minor version
hey
it has no breaking changes
@bot.slash_command(name='leave', description='leaves a server')
async def leave(ctx, guild_id):
try:
if ctx.author.id == 1097367679028953199:
guild = bot.get_guild(guild_id)
if guild is not None:
await guild.leave()
print(f'Left guild {guild.name} upon command from {ctx.author}')
await ctx.send(f'Left guild {guild.name}')
else:
await ctx.send("Guild not found.")
else:
embed = discord.Embed(color=colorfail, description="You are unauthorized to use this command")
await ctx.respond(embed=embed, ephemeral=True)
except:
embed = discord.Embed(color=colorfail, description="Unable to leave that server")
await ctx.respond(embed=embed, ephemeral=True) ```
Is there a documentation on how to make a guild leaver
cause I don't think this is right
Goated
basically i'd love if there was a mentions= keyword for .send() that just highlgihts and pings but doesnt have the text
i mean, thats how semantic versionining works
just ping them
Oh idk what that means lol
time to educate yourself on something mildly important in online software
i want an empty message because i do the text in the embed
Iâm currently in the bathroom at a dentist office, but yes I will đ
whats wrong with this?
Guild not found error
so
I put a guild id the bot is in
and then it returns guild not found
yea you can't get a guild you aren't in
so use get_or_fetch from discord.utils
i think that supports guilds
but i think you can just fetch if you dont use it a billion times a minute
I'm trying to fetch all the members with a specific role:
guild = client.get_guild(814824676240654376)
role = guild.get_role(9897619211291233)
print(role.members)
Result:
[<Member id=814555443812368404 name='iampacificator' global_name='PACIFICATOR đŽ' bot=False nick=None guild=<Guild id=814824676240654376 name='MiServidor' shard_id=0 chunked=False member_count=38>>]
But it only manages to fetch me, despite 7-8 other members having the same role. Bot has administrator perm
I would like it to fetch all members with the role, what am I missing?
have the bot print guild.members
then show me what it says
guild.members đ
[<Member id=999202880345079929 name='Elon Test Bot' discriminator='9914' bot=True nick=None guild=<Guild id=814824676240654376 name='MiServidor' shard_id=0 chunked=False member_count=38>>, <Member id=814555443812368404 name='iampacificator' global_name='PACIFICATOR đŽ' bot=False nick=None guild=<Guild id=814824676240654376 name='MiServidor' shard_id=0 chunked=False member_count=38>>]
It's unable to print all the members, only the user (myself) and the bot itself (Elon Test Bot)
do you have member intents enabled?
guild is not chunked and that say you dont have all members in cache
so i guess you have to enable it in bot init or manually fetch members / chunk guild
(i was wrong)
ref: A chunked guild means that member_count is equal to the number of members stored in the internal members cache.
the guild isn't cached/chunked
thats why members aren't showing up
Is there a way to set a image in a streaming activity
?tag animated avatar
No tag animated found.
?tag animated_avatar
No tag animated_avatar found.
?tag avatar
No tag avatar found.
?tags
yt-tutorials, youtube, xy, wavelink, virtualembed, usernames, usercmd, update, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, this, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, sqli, solved, snowflake, slashcommandmention, slashblog, rie, restartcmd, requests, replit-install, replit, removeall, pythonversion, pythonserver, python, practices, pp, pomelo, persistant_view, paste, partial_objects, oracle, option, oop, om, official, objects, notpycord, norepl, nojson, nohelp, nohello, no_status, name-conventions, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, logging, localfile, learnpython, json, intents, install_git, install, inline-fields, importerror, idw, ide, how2sql, helpgist, guide, git, gif_avatar, getalpha, get_x, get-help, gather, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, cmd-limits, closing, client, chatgpt, buttons2, buttonlimit, bridge, breaking-changes, botvar, bitwise, asset, applicationcommands-registration-delay, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel, 429
?tag search avatar
?tag gif_avatar
How to upload an animated avatar for your bot
To use and upload an animated avatar you can run the following snippet as standalone script:
import discord
# Create a Discord client instance
client = discord.Client(intents=intents)
# Event to handle bot's initialization
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
# Upload animated avatar
try:
with open('yourpicture.gif', 'rb') as avatar:
await client.user.edit(avatar=avatar.read())
print('Animated avatar uploaded successfully!')
except Exception as e:
print('Failed to upload animated avatar:', e)
# Run the bot
client.run("YOUR_TOKEN")
That should be all, have fun!
With autocomplete, can I also transfer a second value in the background to the transferred value with which I can continue to work?
matching_users = [user.email for user in user_datas if user.email.lower().startswith(ctx.value.lower())]
return matching_users
@slash_command(name="update_user", description="Update Userdata")
@option(
"email",
description="E-Mail",
autocomplete=user_data_email_autocomplete,
required=False,
)
async def update_user_data(self, ctx: discord.ApplicationContext):
#Here I would like to continue working with the ID from the e-mail database
So I could, for example, also transfer an ID for each e-mail from a user, which I can then use in the callback?
There should be name and value... Don't know if pycord actually lets you use both.
it does
instead of a list of strings, you should return a list of discord.OptionChoice with name and value
name is purely visual, while value is the string recieved in the command
And that also works with autocomplete?
Like that ?
matching_users = [OptionChoice(name=user.email, value=str(user.id)) for user in user_datas if user.email.lower().startswith(ctx.value.lower())]
return matching_users
yeah perfect
What do you mean exactly?
unlike choices which you are forced to choose from, autocomplete results are optional; users can enter any value
so for example, in your command callback you should verify that the userid you recieve actually exists
aren't autocomplete just dynamic choices?
almost, but again they aren't enforced
This means that the user could theoretically be suggested e-mails:
[email protected] value=1
[email protected] value=2
[email protected] value=3
Or simply enter [email protected]?
yes
Then I could simply check in my function whether a value is specified or not?
Because then the user can't specify it manually?
yes, you have to enforce it within your command
using optionchoice you only recieve value as a str, so in your case just check if the user id exists
How can I access the value in the function?
email.value?
Ah okay so the email is displayed for selection and in my variable email the value value is then passed into my function?
mhm
matching_users = [user.email for user in user_datas if user.email.lower().startswith(ctx.value.lower())]
return matching_users
@slash_command(name="update_user", description="Update Userdata")
@option(
"email",
description="E-Mail",
autocomplete=user_data_email_autocomplete,
required=False,
)
async def update_user_data(self, ctx: discord.ApplicationContext, email: str):
email_value = email #This is the user id ?
that's right but you don't really need to do that
Yes, I can work directly with email, but I did it this way for clarification đ
Thank you very much!
Is there a quick way to determine whether a user is new (would have that little leaf icon)?
Member.joined_at?
Wouldn't that just show when they joined the server, not Discord?
Was just hoping there was a fetchable flag
itâs not documented
The leaf icon is for new server members
Not new discord users
Hi, any recommendation to run a Selenium function evading the rest of the bot functions to stop?
Basically fills forms and scraps data
asyncio.run could be the answer tho
Let me give it a try
member.intents fixed it, thank you! đŤĄ
cached and working, thanks! đŤĄ
Hello, can someone please try and test on_stage_instance_delete on their end and see if it triggers when ending the stage? I'm on pycord 2.5.0 and it seems that it is not working. on_stage_instance_create works just fine btw. I just want to know if it is an issue on my end or library's end.
Can someone tell me how I can fill a dropdown menu with all server members
you could use a user_select for it
you create a view class and a select menu at the class with ```py
@discord.ui.user_select()
guys help me pls: i've noticed that Option and OptionChoice doesnt work anymore, can someone help me using an alternative method?
@bot.slash_command()
async def test(ctx, member : Option(discord.Member, description="Select a member", required=True)):
# ...
what isn't working?
you get an error?
yes
Traceback (most recent call last):
File "d:\Users\Davi\Desktop\programas\codes\python\pycord\botteste\main.py", line 10, in <module>
from discord.ext.commands import Option, OptionChoice
ImportError: cannot import name 'Option' from 'discord.ext.commands' (C:\Users\Fontanini\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\__init__.py)
i think something changed due to updates
use discord or discord.commands and not from ext.commands
How can I supress all warnings for an aiomysql INSERT IGNORE statement?
Just use normal insert in the SQL and catch the error using try except in python
Or you could look at this https://github.com/aio-libs/aiomysql/issues/103#issuecomment-634741540
nvm i fixed it alr
Worked like a charm
Thank you so much for helping out. This drove me crazy for half an hour..
.. you earned your cape today! : D
hey guys any way of havng a ctx command in pycord, that also works if the bot is pinged?
heard there is an argument to pass when you are creatnig the bot instance, but dont remember what it was
commands.when_mentioned_or("!")
thank you: that was it
Is this also possible in a command not a class
you can use views without classes, it just gets really messy py view = View() select = Select(type=...) async def callback(interaction): ... select.callback = callback view.add_item(select)this in itself doesn't look *that* bad, but it looks horrible if your code is any longer and need to do extensive stuff
i'd recommend the subclassing route for better overall code, but the above works if you're a maniac basically
(i say this as someone who extensively used this method years ago and now shys away from touching the related cog)
hello so basically i made a ticket bot that creates a transcript in my bot directory, but when i try to send it
file_path = f'./{interaction.channel.name}.txt'
await interaction.user.send(file=discord.File(file_path))```
it sends a blank txt file
If you open the file that is created, is that empty? Or just when its sent?
show directory structure?
my other command can read through the json file so it should work with sending the txt
are they both in the same file?
alright, thanks. And what about the code that writes to the file?
class CloseTicket(discord.ui.View):
@discord.ui.button(label="Close Ticket!",style=discord.ButtonStyle.primary, emoji="â")
async def button_callback(self, button, interaction):
filename = f"{interaction.channel.name}.txt"
with open(filename, "w") as file:
async for to_be_transcripted in interaction.channel.history(limit=None):
file.write(f"{to_be_transcripted.created_at} - {to_be_transcripted.author.display_name}: {to_be_transcripted.clean_content}\n")
file_path = f'./{interaction.channel.name}.txt'
await interaction.user.send(file=discord.File(file_path))
await interaction.channel.delete()```
thats the entire closing ticket/creating transcript code
try removing the ./ from file_path
It looks like you're sending the file in your for loop. So, every message that's processed would send a new file to the user. Try it with two messages. You'll get two files
file_path = f'{interaction.channel.name}.txt'```
nan kb
Make sure you send the file to the user outside of the with block
that makes sure the file is written to and closed
Also, you may want to open the file in a mode instead; every time you call write when it's openend in w mode, i believe it overwrites all of the file contents
it worked
thanks alot
i like it more
i tried fixing it for the past 1h or so
no problem, glad I could help
For some reason, it's making it so that every time I switch to another option inside the select menu, it goes back to the default as the selected option which is general. I don't remember this ever happening before but I also can't remember how to fix it
hey, quick question as i keep having errors with interactions
i am trying to delete an interaction, and i have this error
return await self.interaction.delete_original_response(delay=delay)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 552, in delete_original_response
await func
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 222, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 381, in invoke
await injected(ctx)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
when doing await interaction.delete()
is there like a delay or something?
i didnt really seem to find anything on this error code, if someone has some documentation about it please send it to me đ
why are you deleting an interaction?
i want to make it stop working for the user
actually found this message, i think this is the problem
this error only happens when the interaction is after 15 minutes
is there any way to "renew" it?
in views?
yes, because i have a "panel", and when the user clicks on something sometimes it sends ephemeral messages, seems that when its on a view for more than 15 minutes, it also gets this error
50027
set a longer timeout
i set it to None
hm


