#Basic Pycord Help (Quick Questions Only)
1 messages · Page 48 of 1
already answered
oh
was this it
its the correct import
ine 147, in <module>
@bot.slash_command()
^^^^^^^^^^^^^^^^^
AttributeError: 'SlashCommand' object has no attribute 'slash_command'
it didnt rlly help
ayo, why is on_ready triggering, but the command isn't?
import asyncio
from hypercorn.config import Config
from hypercorn.asyncio import serve
from quart import Quart
import discord
from discord.ext.commands import Bot
import signal
loop = asyncio.new_event_loop()
intends = discord.Intents.default()
token = "token"
bot = Bot(intends=intends, command_prefix="!", loop=loop)
config = Config()
config.bind = ["localhost:8000"]
app = Quart(__name__)
@app.route("/")
async def index():
return "Hello World"
@bot.command()
async def test(_):
print("test")
@bot.event
async def on_ready():
print("Bot ready")
shutdown_event = asyncio.Event()
def _signal_handler():
shutdown_event.set()
# loop.add_signal_handler(signal.SIGTERM, _signal_handler)
try:
bot_task = loop.create_task(bot.start(token))
web_task = loop.create_task(serve(app, config, shutdown_trigger=shutdown_event.wait))
loop.run_until_complete(asyncio.gather(bot_task, web_task))
except KeyboardInterrupt:
loop.run_until_complete(bot.close())
finally:
loop.close()
i would rather suggest using asyncio.run rather than low level asyncio
async def test(_):
and you have a _ inside your cmd
at least name it smth 
we like to call it ctx
it's since I'm not using it
the webapp has to be served too tho
still, a good idea to name it ctx. its a convention. but it doesnt matter
you can use asyncio.create_task
or you can use asyncio.gather
lets continue in #1059472193181991013
yep
part of my code is suddenly throwing an error saying that 'interaction object has no attribute author' when using interaction.author.id, how else can i pull the user's id?
interaction.user
oh ok thanks
don't cross post.
this always returns None how do i fix that, the user object is returning fine but dm_channel attribute always returns None even though the dms exist with the bot
user = bot.get_user(1005734571628838953)
print(user.dm_channel)
.rtfm discord.User.dm_channel
pretty sure it has to be within the cache for it to return it, or else it will be None if its not
you could also use .fetch_user
why would you need dm channel though? just use user.send
You're not showing how you're initializing the view
is pillow compatible with pycord?
Why should it not compatible ?
cause its not working for me
What part is not working for you? it works perfectly for me
Is it possible to send two modals to a single command?
and modals cannot be chained
That basically means my bot depends on message content, it seems. 🤔
modals can have many text inputs
i would hate to be honest but probably not
You can just respond to the modal with a button which opens the next modal lol
Five text fields isn't enough to run through the entire process, and I want it chained in a single command, for the sake of the user.
Thank discord
Its a discord limit
if you could explain your current with message-content system, we can try to help to make it work without message-content
It loops through an array of messages, which it sends and then awaits the input of the user, basically. That was the old thing I wrote.
what type of input does it wait for?
It awaits a message using the bot.wait_for function, and simply tries again if the input isn't right. The input could be an integer or just a string, that depends on where exactly in which process you are.
is it like a google forms?
I think you could compare it to that, I'm not quite familiar with Google forms.
The goal is to guide the user through creating a character, and they need a character to play the game. The things they fill in affect the game mechanics.
and there are more than 5 questions.
Yes.
well, you can ask one question at the time per modal to validate the input
And if I don't want the user to use a command for each next step?
send a message with a button
Could I respond to the initial message with a message with multiple buttons, where each button represents a modal?
yeah
And could I only enable those buttons once the previous modal was filled in correctly? I think that should be possible. 🤔
yeah
what does this mean?
INFO:discord.gateway:Websocket closed with 1000, cannot reconnect.
happens on start then crashes
Any other errors?
async def third_button_callback(self, button, interaction):
if "account" in interaction.data['custom_id']:
if interaction.channel.id == TICKET_CHANNEL:
guild = bot.get_guild(GUILD_ID)
ticket_owner = interaction.user
for ticket in guild.channels:
if str(interaction.user.id) in ticket.name:
embed = discord.Embed(title=f"You can only open one Ticket!", description=f"Here is your opened Ticket --> {ticket.mention}", color=0xff0000)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
open_ticket = bot.get_channel(OPEN_TICKET_LOGS)
embed3 = discord.Embed(title='**Ticket Opened**', description=f"{ticket.mention} Was created!", color=config.EMBED_COLOR)
category = bot.get_channel(CATEGORY_ID4)
ticket_channel = await guild.create_text_channel(f"ticket-eft-accounts-{ticket_owner}", category=category,
topic=f"Ticket from {interaction.user} \nUser-ID: {interaction.user.id}")
await ticket_channel.set_permissions(guild.get_role(TEAM_ROLE1), send_messages=True, read_messages=True, add_reactions=False,
embed_links=True, attach_files=True, read_message_history=True,
external_emojis=True)
await ticket_channel.set_permissions(interaction.user, send_messages=True, read_messages=True, add_reactions=False,
embed_links=True, attach_files=True, read_message_history=True,
external_emojis=True)
await ticket_channel.set_permissions(guild.default_role, send_messages=False, read_messages=False, view_channel=False)
embed = discord.Embed(description=f'Welcome {interaction.user.mention}!\n'
'Hello, How can we help you?',
color=config.EMBED_COLOR)
await ticket_channel.send(embed=embed, view=TicketClose())
embed = discord.Embed(description=f'📬 Ticket was Created!', color=0xe800ff)
await interaction.response.send_message(embed=embed, ephemeral=True) ```
No error was thrown just not creating the ticket. button is shown and everything on the embed as it should be.
:/home/container$ if [[ -d .git ]] && [[ ${AUTO_UPDATE} == "1" ]]; then git pull; fi; if [[ ! -z ${PY_PACKAGES} ]]; then pip install -U --prefix .local ${PY_PACKAGES}; fi; if [[ -f /home/container/${REQUIREMENTS_FILE} ]]; then pip install -U --prefix .local -r ${REQUIREMENTS_FILE}; fi; /usr/local/bin/python /home/container/${BOT_PY_FILE}
Requirement already satisfied: py-cord in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 1)) (2.3.2)
Requirement already satisfied: aiohttp in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 2)) (3.8.3)
Requirement already satisfied: asyncio in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 3)) (3.4.3)
Requirement already satisfied: pymysql in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 4)) (1.0.2)
Requirement already satisfied: requests in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 5)) (2.28.1)
Requirement already satisfied: python-dateutil in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 6)) (2.8.2)
Requirement already satisfied: typing-extensions<5,>=4 in ./.local/lib/python3.10/site-packages (from py-cord->-r requirements.txt (line 1)) (4.4.0)
Requirement already satisfied: charset-normalizer<3.0,>=2.0 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (2.1.1)
Requirement already satisfied: yarl<2.0,>=1.0 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (1.8.2)
Requirement already satisfied: multidict<7.0,>=4.5 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (6.0.4)
Requirement already satisfied: attrs>=17.3.0 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (22.2.0)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (4.0.2)
Requirement already satisfied: frozenlist>=1.1.1 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (1.3.3)
Requirement already satisfied: aiosignal>=1.1.2 in ./.local/lib/python3.10/site-packages (from aiohttp->-r requirements.txt (line 2)) (1.3.1)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in ./.local/lib/python3.10/site-packages (from requests->-r requirements.txt (line 5)) (1.26.13)
Requirement already satisfied: certifi>=2017.4.17 in ./.local/lib/python3.10/site-packages (from requests->-r requirements.txt (line 5)) (2022.12.7)
Requirement already satisfied: idna<4,>=2.5 in ./.local/lib/python3.10/site-packages (from requests->-r requirements.txt (line 5)) (3.4)
Requirement already satisfied: six>=1.5 in ./.local/lib/python3.10/site-packages (from python-dateutil->-r requirements.txt (line 6)) (1.16.0)
- Elevate Manager#1601 has connected to Discord!
- Discord version: 2.3.2
- Python version: 3.10.9 (main, Dec 21 2022, 08:51:48) [GCC 10.2.1 20210110]
- Logged in as: Elevate Manager (1049914370001489981)
- Status Loaded
- Tickets Loaded
- Buttons Loaded
- Elevate Manager | Starlight#5980```
@fervent cradle check if your if statements are correct.
works perfectly fine with select menus
With a ban how do i write a reason
.rtfm Member.ban

Hey guys! How can i fix this error?
code:
embed = discord.Embed(title="Ticket claimed!",
description=f"You will be supportet now by {interaction.user.mention}",
colour=0x2f3136)
await interaction.response.send_message(embed=embed)
button.disabled = True
button.label = "claimed!"
await interaction.response.edit_message(view=self)```
error:
discord.errors.InteractionResponded: This interaction has already been responded to before```
Target not found, try again and make sure to check your spelling.
.rtfm interaction.followup
like that?? await interaction.followup.edit_message(view=self)
No
I see you're trying to edit the original message
So use await interaction.original_response()
That returns the original response
Then you can edit it
and how?
like that: await interaction.original_response.edit_message(view=self)?
message = await interaction.original_response()
await message.edit(view=self)
Can you send multiple modals on one interaction?
no
@discord.slash_command(description="Löscht den aktuellen Channel")
@has_permissions(administrator=True)
async def delchannel(self, ctx):
await ctx.respond("Channel löschen?", ephemeral=True)
if ctx.response == "Y":
await ctx.channel.delete()
Hey guys, i want to reply to the bot's response with "Y" and it should delete the channel. But not with ctx.response == "Y".. do you know a function or way to do this?
.rtfm wait_for
Niceee
personally, I would use buttons.
Can anyone see what's wrong with this code? For some reason, it always says that I am incorrect.
@bot.command(name='scramble')
async def scramble(ctx):
# Generate a random word
original_word = random.choice(['apple', 'banana', 'cherry', 'durian', 'elderberry', 'fig', 'grape'])
# Scramble the chosen word
scrambled_word = ''.join(random.sample(original_word, len(original_word)))
# Send a message to the channel asking the user to guess the original word
await ctx.send(f'Can you guess the original word? The scrambled word is: {scrambled_word}')
# Wait for the user's response
response = await bot.wait_for("message", timeout=30.0)
# Check if the user's response is correct
if response.content.lower() == original_word.lower():
await ctx.respond('Correct!')
else:
await ctx.respond(f'Incorrect. The original word was: {original_word}')
Add checks for wait_for
why?
i did that before and it didn't work
How did you do it?
.rtfm wait_for
See how to do it in docs
I totally didn't get ChatGPT to fix my code because my debugger broke
Also, print original word and response.content. and see what you get
Using Chatgpt would never really work
People really be trying to get spoonfed by an AI nowadays huh
I used it to fix my bugs, because my debugger isn't working
and because I didn't get enough sleep 😔
Maybe you can use it to fix your debugger? 
It's good for asking about coding concepts, but the code won't work. It can't differentiate between dpy and forks, and the data becomes quickly outdated
That's actually worth a shot lmao
How can you break your debugger-
That's what I'm wondering too
And why not try to fix that, instead of blindly writing code?
mobile users wishing they had a debugger
Sterile help channels thanks.
this one's already been contaminated
skill issue
My message looks a bit weird now
embed = discord.Embed(title="Ticket claimed!",
description=f"You will be supportet now by {interaction.user.mention}",
colour=0x2f3136)
await interaction.response.send_message(embed=embed)
button.disabled = True
button.label = "claimed!"
message = await interaction.original_response()
await message.edit(view=self)```
hi everyone, i just want to know what to put in discord.Member.add_roles(...)
the docs say to put in *discord.abc.Snowflake, so i put in a discord.Object(role id here) thing.
it said unknown role. am i doing something wrong, or did i just put in the wrong role iD?
add_roles has to be a list of roles, use add_role instead to add a single role
ok - but the parameter type?
For what
add_role
I checked the docs for it and I can‘t find it anymore I guess they removed it so use member.add_roles([member.guild.get_role(RoleID)])
ah thanks
It’s not the best solution, you can better use this for a cleaner design:
roles = []
roles.append(member.guild.get_role(RoleID))
await member.add_roles(roles)
You‘re welcome
Why does that not work good?
What doesn’t work
The claimed button should change on the message at the top, but it doesn‘t
use interaction.original_message() instead
instead await interaction.original_response()
/Development/Python/TeamMLG/teammlg-discord/views/ticketView.py:135: DeprecationWarning: Interaction.original_message is deprecated since version 2.2, consider using Interaction.original_response instead.
message12 = await interaction.original_message()```
show your pip list
py-cord 2.3.0
File "/home/runner/AK17-EVA/venv/lib/python3.8/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "main.py", line 112, in button_callback
await interaction.user.add_roles(interaction.user.guild.get_role(
File "/home/runner/AK17-EVA/venv/lib/python3.8/site-packages/discord/member.py", line 1007, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
what is going on?
i also reinstalled py-cord but it still doesn't work
2.3 or 2.3.2?
2.3.2
😮
I am a bit new to pycord. Is there anyway I can make the bot wait sending the audio from the mp3 file before sending the next one?
-> I used time.sleep() but that's not the best solution
if you use time.sleep it will block the entire bot
use asyncio.sleep()
?
Does pycord not have the on_raw_member_remove event?
nope
only on_member_remove
This section outlines the different types of events listened by Client. There are two ways to register an event, the first way is through the use of Client.event(). The second way is through subcla...
shit
What should that event do?
Same as on_member_remove except you don't have to cache members for this one to fire.
To put it simple 
Why you don’t want to cache them :d
I don't want to waste resources on caching millions of members.
at a huge amount of users this could be a problme
how long does it take for guild commands to register once you start the bot
10 seconds?
yeah but like where exactly
send code thanks
wait found it
nvm thanks :D
Application Command raised an exception: AttributeError: 'Confirm_view' object has no attribute 'children'
i ama go cry now
code...
class Confirm_view(discord.ui.View):
def __init__(self):
self.value = None
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green, emoji="✅")
async def button_callback(self, button, interaction):
await interaction.response.send_message("Confirming", ephemeral=True)
self.value = True
self.stop()
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger, emoji="❌")
async def button_callback(self, button, interaction):
await interaction.response.send_message("Cancelling", ephemeral=True)
self.value = False
self.stop()
full traceback
You're missing super().init
uh
You're overriding the init method
oh ok
super().__init__
💀
it worked :D
please learn OOP before learning pycord
yes sir
I have an issue with Select Menu. I want to make it so that people can select multiple times one brand they can give a point and one brand they can take the point from. The issue is that the items are kept in select_menu.values even after when nothing is selected anymore. Do you know a way of how to delete selected values from select_menu? Or refresh it? I tried disabling and enabling it, but it didn't help.
send the view when you edit the message and it should reset the selects
Got it, thanks
Guys how can i import a var from a command in a cog?
what is that supposed to mean?
Asking about your attempted solution rather than your actual problem
How can I import a var from (for example) the views.py file. But the var is in a command, the command is in a cog, i can't import the var normally
databases?
is the embed dynamic?
no
There anyway to stop someone executing a command which is already being executed. so if I had a command which sends "Hello World" stop it from being spammed for a duration of time?
My understanding is that you want to get an embed from somewhere to use somewhere else?
yes
Create another file somewhere (I will refer to this as utils.py) and from utils import embed
for both the command in the cog and the somewhere else
ok
names don't have to be the same but I assume you get the idea
You can always restart the bot, but who would stop the command from being executed?
Is it the user, the developer, a moderator, or who?
user
what are you trying to stop
a for-loop, while-loop or something else?
@knotty surge ?
Sorry mate, I am making a bot which sends images back to the user where these textures can be one to 100 for example so quite a few to be completed
So to prevent
./make and then ./make
being used twice
Ah. If you have databases you can add something to indicate that the user's make is in progress and set it back to idle once it is done. Add a check at the beginning of the command to check if it is in progress or idle.
You can also add a cooldown, instead.
how would you add a cooldown?
@knotty surge
Depends on how your code works but there are cooldown command decorators.
You could also make a custom bucket.
Buckets are cool to use as you can reset them once your process is finished.
buckets are very cool
Any documentation going on?
Not sure
@knotty surge this might help:
Simple command decorator:
@commands.cooldown(1, 5, commands.BucketType.user)
I feel like this is what you're looking for though:
cooldown = commands.CooldownMapping.from_cooldown(1, 5, commands.BucketType.member)
bucket = cooldown.get_bucket(whatever)
retry = bucket.update_rate_limit()
if retry_after:
return
bucket.reset()
You might also want to look at the max_concurrency decorator.
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
my presence intent doesnt work
member.activities is always None for some reason
and yes, intents.presences is True
is this in an interaction?
no, normal prefix command
i don't know then
What about member intents?
What's gonna be added in v3?
I pray to God let it be async multiprocessing
I have 4 cores at least, 4 times more requests
is there a way you can get the str of a members presence? (the client's presence specifically)
what is that supposed to mean?
for example: I want to read "Watching 35 servers" and print it to the console
are you talking about any user or just your own bot?
just the client, my own bot
Just a reminder, please do not use any client modifications; they are against Discord ToS.
bot.me.activity
thank you
Using applications such as BetterDiscord, Powercord, or similar is against Discord Terms of Service; it can get you banned.
how is any of that related to the question? Seems super random
thanks for the warning though
bot.me returns your bot as the user
didnt meant to respond to that
bot.me.activity returns the activity
"Using applications such as BetterDiscord, Powercord, or similar is against Discord Terms of Service; it can get you banned."
responding to this ^
this worked great thank you
Just a reminder.
okay, just confused me lol seems super random
pretty sure you dont need them cached to have the event fire
isnt it bot.user?
yeah i just used bot.activity
yeah, I think you're right.
are you even paying attention?
Hello, anyone know how to fix this error?
Fatal error in launcher: Unable to create process using '"c:\users\attle\appdata\local\programs\python\python35\python.exe" "C:\Users\attle\AppData\Local\Programs\Python\Python35\Scripts\pip.exe" install -r requirements.txt': The system cannot find the file specified.
Yes, there's a file that is called requirements.txt and I've got the latest version of pycord.
I can confirm they have the requirements.txt file, I gave them the whole code and it works when I ran it, including installing through requirements.txt.
what is python35
To be honest, I would have no clue. I just installed pycord and it put whatever files it needed I guess.
I do have 3.11
Sure, but you're not using it to run your bot
This indicates that you're running it with 3.5
How would I go by switching it to the 3.11 then?
Because for some reason it keeps defaulting to that version which is clearly the wrong version. I did indeed uninstall all the python things that showed up in my control panel.
i think python3.11 may work?
i know python3.10 works
3.11 does work if you use the latest version of pycord
prob slightly missed the ballmer peak
Seems to be working now anyways. Thanks for the help!
Hey guys, how can I get my bot to work faster? Its average ping is about 450ms
where do you host the bot?
Get a host located in the US, don't use free hosts, make sure your host has good network stats
How do I use my bot to create an emoji? Can I get an example?
I read em and im still confused. can I get an example?
What do you need an example for? It's just one method and the docs explain exactly how to use it
I meant a single line of code
Just read the docs, if you don't understand them you probably don't know Python well enough to be making a bot
Figured it out
💀 The US will get the worst ping for the vast majority of my users
Your users location does not matter at all, it's about your bot's connection to Discord's API server
It's not like your users are connecting directly to your bot 
then you're probably stuck with shit ping
unless you are using music bots or something
For future reference, in your IDE, you solve this by changing the environment in the project settings. If you use Vscode just Google “how to change environment in Vscode” or whatever IDE you use.
Ok thank you
is there any quick example on slash command followup?
No problem
~~This might be what you’re looking for:
https://guide.pycord.dev/interactions/application-commands/slash-commands~~
Guide can be better than docs sometimes
@discord.slash_command(description="Test.")
async def test(
self,
ctx: discord.ApplicationContext,
):
await ctx.defer()
# Do stuff here
...
# send the response
await ctx.respond(...)
# if you want to send another message after the ctx.respond, use channel.send
for slash commands, ctx.respond will respond to the deferral.
if you want to send another message after this, you must use channel.send instead of ctx.respond
You do not need to use defer unless your command takes longer than 3 seconds to execute
ohk thanks!
No problem. Sorry for the confusing response
Is there a quick one-liner for getting all members who have a role?
I'm half awake/a little inexperienced with Pycord so I don't know how well this'll work for larger guilds but you could try something along these lines:
await bot.get_guild(112233445566778899).fetch_members().filter(lambda member: 112233445566778899 in map(lambda role: role.id, member.roles)).flatten()
.rtfm utils.find
appreciate ya both
You really don't need to fetch members. the members property has all the members
Are all guild members cached? For example in a large guild of ~4000 people
(Fetching was just an assumption, I dunno the limitations)
If you have the members and guild intent, it should be
Oh wait actually there is role members too
.rtfm role.members
Oh, that's useful
@north gorge there you go. This is the fastest and most efficient way
I almost forgot I came here with a question of my own lol
What's a way I can allow a webhook to trigger a @bot.command?
Edit: I found this hacky feeling workaround after a bit of googling, but I don't feel comfortable with it as a permanent solution:
@bot.event
async def on_message(message: discord.Message):
ctx = await bot.get_context(message)
if ctx.valid and message.author.bot:
await bot.invoke(ctx)```
that's exactly what I was looking for, tyvm
Webhook in the sense a message sent by a webhook?
Mhmm
Well then only those messages which are sent by a bot will work
The command will work for both users (through the normal @bot.command) and bots (through the on_message handler only) which works for my needs
you are overriding on message. So normal @bot.command will stop working
Eh? It still works for me 
yes you do :)
commands.is_owner().predicate just wanna know whats .predicate in this?
Hello, i'm migrating all my commands to slash commands and i would like to know if anyone could tell me how to solve this issue.
I have a command that takes 2 arguments :
winnerof type discord.Userfoesof type *discord.User because i have one winner but one or more foes/loosers in the game.
If i use in discord.Option and the function tuple[discord.User] i get a unique str with every foes separated by a space, how could i get a list of users with one parameter (or maybe there's a trick to give as many parameters as i want ?
you cant natively get multiple users with a single option. you either have to accept a string and parse it based on ids from the member mentions, or use a string select
Okay, but the string select is to choose an option ?
But it's still limited to one value
oh sorry i meant user select menu
you can allow multiple selections
👍
Ho !
.rtfm user_select
thanks ❤️
🙃
hey guys
how do i use commands.cooldown() for different role for same command
i used this
@commands.cooldown(1, 43200, commands.BucketType.user(lambda u: u.top_role.name == 'Basic'))
but it doesnt works
.rtfm cooldown
discord.ext.commands.Cooldown
discord.ext.commands.Cooldown.copy
discord.ext.commands.Cooldown.get_retry_after
discord.ext.commands.Cooldown.get_tokens
discord.ext.commands.Cooldown.per
discord.ext.commands.Cooldown.rate
discord.ext.commands.Cooldown.reset
discord.ext.commands.Cooldown.update_rate_limit
discord.ext.commands.CommandOnCooldown
discord.ext.commands.CommandOnCooldown.args
discord.ext.commands.CommandOnCooldown.with_traceback
discord.ext.commands.Command.cooldown
discord.ext.commands.Command.get_cooldown_retry_after
discord.ext.commands.Command.is_on_cooldown
discord.ext.commands.Command.reset_cooldown
discord.SlashCommandGroup.cooldown
discord.SlashCommandGroup.get_cooldown_retry_after
discord.SlashCommandGroup.is_on_cooldown
discord.SlashCommandGroup.reset_cooldown
discord.UserCommand.cooldown
Dynamic cooldown
Here's the cooldown example.
hey is there a way to set default command permissions now in pycord? i heard that was released in the discord api a while ago
is it possible to respond to multiple clicks of a button? Ex. it sends 1 then 2 then 3 and so on?
What is 1, 2, and 3
Message responses
So you click the button it sends you 1, then you click it again it sends you 2 and so on
Just have a variable n set it to 1 on the buttons callback increment the value by 1 and send it to the user
I get that but how do I send to the user?
does some1 have a quick minute? https://discord.com/channels/881207955029110855/1060174697544831006
Using interaction.response.send_message() multiple times give me an error
.rtfm interaction
discord.Interaction
discord.Interaction.app_permissions
discord.Interaction.application_id
discord.Interaction.channel
discord.Interaction.channel_id
discord.Interaction.client
discord.Interaction.custom_id
discord.Interaction.data
discord.Interaction.delete_original_message
discord.Interaction.delete_original_response
discord.Interaction.edit_original_message
discord.Interaction.edit_original_response
discord.Interaction.followup
discord.Interaction.guild
discord.Interaction.guild_id
discord.Interaction.guild_locale
discord.Interaction.id
discord.Interaction.is_command
discord.Interaction.is_component
discord.Interaction.locale
interaction gives you anything that you need
Thank you so much
how do i get a webhook message id so i can delete it later on?
wait lemme see if it works
An HTTP exception has occured: 400 HTTPException: Invalid Form Body
In data.components.0.components.0.url: Not a well formed URL.
hey now my cooldown is working but the normal cmds are not :P
@proud mason
can you fix my thing also 😂
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.
@west venture ^
Tried doing this wish jsk and it didn’t add the slash command manually, no errors.
async def f(ctx):
await ctx.respond('foo', ephemeral=True)
a = discord.SlashCommand(name="ad", description="This", func=f)
_bot.add_application_command(a)```
not really a good idea to directly use the SlashCommand class. rather use @_bot.slash_command ?
but anyways you have to sync the commands again
.rtfm bot.sync_commands
I’m creating a custom commands system, in which I fetch custom command data from the database, and I have to add those slash commands when the bot starts up.
Is there some trick to getting an @ role mention to work in an embed? It looks like it renders correctly, yet it doesn't ping the role
<@&roleid>
or
.rtfm role.mention
I dont think a ping works in an embed
role mention in embed wont ping. not in a way ik of
Oh yeah it didn’t ping in an embed
ah ok, that makes sense, thanks people
ah hmm
brb
alr decorator uses the same stuff
yeah it works now, thanks
When does await bot.sync_commands() run when starting up the bot? does it run during on_ready?
on_connect
If you add the custom slash cmds before running the bot, then you don't need to call sync cmds yourself
k
after i use remove_application_command, do I have to re-run bot.sync_commands?
yea. else the command would still be there
k
would i do await bot.sync_commands(command=[thecommandremoved]) or would that re-add the command?
i dont want to have to have it resync all commands since that takes longer
yea i think that would re add the cmd globally
bruh
then i have to resync all commands
thats going to take 4 years
although its quicker than it will take for my dad to come back
eh not exactly
is the custom cmd a guild cmd?
guild
To clarify, is the commands module no longer necessary for slash commands? I read somewhere this was the case.
i think you can manually call bot.register_commands
And the guide seems to follow that concept
the commands ext is not necessary (the one in discord.ext.commands )
not sure
.rtfm bot.register_commands
Sweet. Is there really any purpose to using it anymore other than if you're sticking with prefix?
it has some stuff like command cooldown and some command perms. but i think you can do most stuff without it
with no arguments?
time to rewrite a good portion of my bot! O: thanks
no you would need to pass guild id
or if you are brave then you can manually do stuff
Can ephemeral messages be deleted?
Discord supports it, however does pycord support it?
yes
Hmmm, I'm not able to delete ephemeral messages, it comes with unknown webhook
I tried
interaction.message.delete()
Msg: discord.InteractionMessage = await interaction.original_response()
Msg.delete()
It’s await interaction.delete_original_response()
.rtfm delete_original_response
I did that as well, same error. I'll change some code a bit and see the response
Hello, how can i check if an option was selected or unselected in a select menu?
select.values[0]
but this is only for when a user selects how can i do something on unselect
Get the original select menu object and compares its values to the new one.
ok
Why ctx.user.status always return offline?
Fetch the member or user
and why ctx.user.status return offline too
You don't have presence intents
nope, i have it
Members intents?
because discord doesn't give that information from interactions
and i need to get user and after his status
right?
ok, thank you
.rtfm user.roles
Target not found, try again and make sure to check your spelling.
.rtfm member.roles
What was the thing with ctx.author.avatar.url if the user has just default avatar, wasnt there a way to display both ways?
display_avatar.url ?
yes! thanks
Not sure if this is quick but seems basic, but how would I make it so my bot still listens to interactions from buttons on a message after a restart?
Here's the persistent example.
Thanks, fixed
doing: ```py
avatar = member.avatar
webhook.send(str(message), username=name, avatar_url=avatar)
is there not a way to get the default avatar they have on?
you can try using display_avatar, but that will just be a blank image.
no, I don't think so.
why doesn't the webhook await just move on without an avatar if a None is provided???
this results in my code completely breaking if someone doesn't have an avatar
because that one await errors out, and it doesn't execute the rest of the code in the sequence
you can just handle that error yourself...
avatar.url
this is not discord.py
I know
regardless, both use avatar.url, afaik
still .url
every time I've tried to use the url in place of just the avatar directly it breaks
the way I'm doing it works for everyone besides default avatars
than show your pip list
useful help 👍
so will you be using a try-except to catch users with default avatars, a condition to check if avatar is None, or display_avatar?
or the library could just not be turbo useless and grab the default avatar image when someone with a default avatar is present
like discordjs does
I'm pretty sure that is what display_avatar does, if I am not mistaken
also, feel free to make a pull request on that.
yeah I'm gonna program in python more than I have to 🤢
no one is forcing you.
^
ahahahaha yeah that's why I'm making this in python and not js, because I chose the language to make it in

display_avatar is what I needed
but still doesn't explain why the library simply let a None slip through when requesting the avatar directly
this is one of the most annoying bugs to encounter while programming
I for one don't do testing on accounts with default avatars
because I expect the library to simply function
Well, Discord doesn't actually give information about that.
This is not a discord problem this is a pycord problem
discordjs .avatar works perfectly every time regardless of default
it will remain a pycord problem, unless someone makes a pr
Yeah I'll spend time fixing the bug, then submit a PR just for some maintainer to come in and be like "hub bub hub we actually intended for this bug to exist"
you go spend time doing that
I'll spend my time doing not that.
ok, but they are actually quite friendly
I mean the bug doesnt matter for me I was literally doing it wrong, display avatar correctly grabs guild avatar aswell
But someones code might need to grab the non guild avatar at some point
I had some terrible check for guild_avatar == None
I can't get bot.get_guild to work, it always returns None, despite the same guild ID working in command creation
get_guild only gets from the bots internal cache, which isn't guaranteed to contain your guild at all times. Use https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.fetch_guild
Hello, is there a simple way to reply to a user's slash command within the channel that only they can see?
ephemeral=True
thank you fixed
works perfectly in other instances
You can't just send code and expect people to solve it for you. Describe what's wrong, what errors are you getting, what have you tried? This is completely useless for both you and others.
Could I use this with categories?
for (category, id) in config['ticket-categories'].items():
guild = server_info["guild"]
if not id == "none":
categories[category] = await discord.utils.get_or_fetch(guild, 'category', id, default=None)
print(categories)
This returns the error:
AttributeError: 'Guild' object has no attribute 'get_category'
it literally explains itself its the picturn on the left theres an error on the right theres not
You're not showing what the error is, you're just showing a red underline. That does not "explain itself"
and the code on the left is completely different from the right
Read the error
I understood that, but I don't know what else I would use instead of guild, I couldn't find a category object, I assume this means I can't use this function for categories but I figured I could ask
That's not how you fetch categories, they are channels
question:
for a persistent view, can you have the button sent to multiple places and still work?
What's the right way to separate subcommands of a slashcommandgroup across multiple cogs? I'm guessing it's not whatever = SlashCommandGroup("thing") in every cog
Hello, i'm trying to get a user as parameter in a slash command. Before the migration it was fine with
async def test(ctx, user : discord.User):
But now when i'm doing this with the input_type option as discord.SlashCommandType.user and by entering @aaaa#0000 i get the string representation of the user but not a user anymore.
Is there a way to get a user object instead of a string ?
@commands.slash_command(
description="Get the avatar of someone",
options=[discord.Option(
input_type=discord.SlashCommandOptionType.user,
name="user",
description="Mention of the user you want to get the avatar",
default=None
)]
)
async def avatar(self, ctx : ApplicationContext, user : discord.User):```
Here's the slash options example.
@quasi stratus
I'll check it
I already cheked that, there's no example for users
discord.Member
Still automatically converted to /avatar user: @fickle raft
Eh there is no built in way iirc
But @spiral spruce had made a module for it. I forgot the name
Ask him
hi there
Hey 🙂
it's called pycord-multicog
thanks both of ya, will look it up. I love having everything separated out
you should find an example here ^
makes sense, I'm gonna try it out
@spiral spruce Is it kosher to add the group from the bot.py so I don't have to just pick a cog to add it to initially?
I think it would work
Nice, I'll let you know
just use add_to_group
where can I leave what I guess is a bug fix request for 2.3.2?
Which bug?
in forums, applied_tags doesn't update when tags are changed
there's a help post about it #1049550251012403271
Awesome, I'm all set. Had to put the bot.create_group right after loading cogs in __main__, then the apply_multicog(bot) right before bot.sync_commands() in on_connect
I suspect more dummies like me will run into this, so for CTRL + F posterity, if it won't load you probably accidentally installed pycord the random python module having to do with image processing
You can make a GitHub issue
In fact it's with every type, even with an int i still get a string that i have to manually change
Are you using the option decorator?
I'm using options parameter inside commands.slash_command() Look at my code (in the original text)
Any specific reason of not being able to use the decorator?
Or typehinting it
decorator is preferred over typehinting
Okay i'll try later
why isnt there a fetch_message like there are other fetch methods?
There is
.rtfm fetch_message
discord.abc.Messageable.fetch_message
discord.PartialMessageable.fetch_message
discord.TextChannel.fetch_message
discord.ext.commands.Context.fetch_message
discord.Member.fetch_message
discord.VoiceChannel.fetch_message
discord.ext.bridge.BridgeExtContext.fetch_message
discord.Thread.fetch_message
discord.Webhook.fetch_message
discord.ext.bridge.BridgeApplicationContext.fetch_message
discord.SyncWebhook.fetch_message
discord.ApplicationContext.fetch_message
discord.User.fetch_message
discord.DMChannel.fetch_message
discord.GroupChannel.fetch_message
It's on channel
can check my thing i created the class but no button shows up
Works better yes, don't really understand why tho :/
async def interaction_check(self, interaction) -> bool:
if interaction.user != self.ctx.author:
await interaction.response.send_message("Hey! You cant use that!", ephemeral=True)
print("cant")
return False
else:
print("u can")
return True``` i have this now in a class but there is a error
You never defined a self.ctx
Is it possible to override the int maximum length in a slash command ?
i want to pass an id to a command but it doesn't work because the value is too big.
I could use a string parameter and then convert it but i prefer trying to get a straight int
nope
Just saw that discord limit the integer parameter to 2^53 :/
Welp, let's use a string 🥲
Is there any issue with having the cogs in a separate file like bot.py/cogs/game.py? I get the group created via bot.create_group but the sub-commands with the decorator do not register to it. I'm using the pycord.multicog.Bot method and the decorator.
I might be able to help you if you create a help thread in this channel and share your bot code
How can I get the message properties of the respond message of my bot
so when i await ctx.respond(my message) that i can edit it further in the future
await ctx.interaction.original_response()
Why accent_color always return None
Hello, why does my code not work?
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(title="Missing required argument!",
description="Please pass all required arguments!",
colour=0x2f3136)
embed = add_footer(embed)
await ctx.send(embed=embed)```
.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.
so my code just doesn't react when I have that error, I also doesn't get an error, it's just nothing that hapens, but the error, that would start this script, is still in my console
better?
Print type(error) and see what you get
You also may need to use error.original
nothing, just like it was before the original python error message pops up
Use error.original and compare it to the missing argument error.
you mean i should print error.original
if yes it would be the same
Are you using slash commands or prefixed commands?
for this one here prefixed, but also slash
Bruh
Slash commands are a different error handler
ah
but it doesn't work and i used the prefixed one's
print the error, and send it to me
Ignoring exception in command log:
Traceback (most recent call last):
File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 942, in invoke
await self.prepare(ctx)
File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 872, in prepare
await self._parse_arguments(ctx)
File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 774, in _parse_arguments
transformed = await self.transform(ctx, param)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Development/Python/TeamMLG/main/venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 601, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.```
do you even have the cog loaded where the handler is?
send me your whole cog
where the error handler is
i recconized, that my venv is in the wrong dir in this error
try this
if isinstance(error.original, commands.MissingRequiredArgument):
why 17 ifs and no elif?
that's a good question
i guess i redo my whole project with the venv, that's weird
I will tell you if it works after that
Will make a thread in a few if I still can't figure it out, does "ValueError: list.remove(x): x not in list" from apply_multicog betray any obvious screwups on my part?
That's interesting but I'll need the whole traceback
How can i make a dropdown selector as an argument in a slash command
Here's the slash options example.
@marble obsidian ^
ok ty!
Hey so ctx.author gets the author name but i also want their discrim so it comes out like this: AUTHOR#XXXX
how do I do this?
str(ctx.author)
should do it
Alright thanks
Update: so I'm trying to send the results of str(ctx.author) to a telegram bot to post the results but it only posts the username & not the discrim
What's the reason behind this
then just use string concatenation: ```py
f"{user.name}#{user.discriminator}"
No luck bruh
Idk im gonna do some testing with another method of getting the name#id
also dont use requests, use aiohttp.
and see if it's hiding it]
there is another way to get name#id tho lol
.tag aiohttp
Tag not found.
Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(http://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean)
discord.py uses aiohttp, so it should already be installed. An example of code using aiohttp and discord.py:
async with aiohttp.ClientSession() as cs:
async with cs.get('https://httpbin.org/json%27') as r:
res = await r.json() # returns dict
await ctx.send(res['slideshow']['author'])
For more help, see aiohttp's documentation: <http://aiohttp.readthedocs.io/en/stable/>
wtf happened to tags on that bot
Dont think so let me see
alr
dont think so
Heyall,
The image in this embed is not showing up. Am I doing something wrong here?
According to https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Embed.image it should be like this
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
yeah. You should separate them into different definitions.
like
test_embed = Embed(title='hi')
test_embed.set_image(url='https://static.upland.me/avatars/exclusive/DbCooper.svg')
atm test_embed is a TypeVar
because that is what set_image returns
Chaining methods is encouraged in the docs
and the test_embed.to_dict() is: {'image': {'url': 'https://static.upland.me/avatars/exclusive/DbCooper.svg'}, 'fields': [], 'type': 'rich', 'title': 'hi'}
ok, but it seems like the url doesn't return an image
it kinda does
Nevertheless the chaining is correct in this case. Embed() returns an Embed with its methods
Hmm, I changed it to another png test file and that one works :/
still not very intuitive, but ig it works.
svg test
For me it is ^^ anyway thanks
see svgs work, but not exactly in the way you want to.
Uhm so it should work..
Adding this extra line doesn't fix it
share current code?
Its its:
async def on_ready(self):
img_png = 'https://static.upland.me/legits/nflpa/seasons/3/19/10412/essential/20/thumbnailImage.png'
img_svg = 'https://static.upland.me/avatars/exclusive/DbCooper.svg'
test_embed = Embed(title='hi')
test_embed.set_image(url=img_svg)
ctx = await self.fetch_user(self.OWNER_ID)
await ctx.send(embed=test_embed)
The png does show up but the svg doesnt
this is what an svg looks like
for discord
I don't think it looks like an image
And what to do with the bytes?
Maybe convert to png and then upload it to somewhere..
you can use something like cairosvg to convert svg to png
https://cairosvg.org/
Convert your SVG files to PDF and PNG.
and then use a local file url on the embed
?tag localfile
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)```
Yes! That is so much better than an upload
Lol, that's going to be some extra hours of work ^^
Can you do a slash commands that only appear in specific servers ?
wrap its function calls inside asyncio.to_thread because it is a blocking library
they are called guild slash cmds
pass the guild ids to the decorator
@bot.slash_command(... , guild_ids=[...])
this looks kind of weird: url="attachment://image.png"
pycord knows with attachment that it refers to the discord.File()?
Thank you !
the file name you set in discord.File should be the same as the one you specify in attachment url
also you should use BytesIO instead of actual files for temp files. it is more efficient
Ahh i see
Thanks for the tip, going to check that one out too
If you at the point of needing that performance you should shard your bot anyway so just run multible sharded instances of it wirh multiprocessing
I just red that you can send messages to any user with a bot. The only way to dont get the messages is to block it. But when i try to send a message to a specific user (which obviously disabled DM's from not-friends) it fails. Do you guys know any more?
What do you want do do ?
Catch the exception?
Just send a custom message, with a slash command, to a user, like an answer of their feedback. But through the bot.
like /sendmsg user: text:
Works fine, but not for disabled dms
Yea if the bot can not dm the user because dms are disabled you cant do anything against it.
A has the same priviliges as a normal user.
If the user disabled their dms, you can't dm it
In this reagard
Oh okay, because i just red something in the ticketbot discord that the only way to stop getting dms from it would be to block it. But the case that someone just disabled the dms wasnt covered in their FAQ 😄
Thanks guys
But still makes sense, if you already got dms from it, youll probably didnt turn it off before
If the dm channel is already opened you can send messages i think.
Not 100% sure tho.
For me its okay, i just thought there was a way around it but its not fairly neccessary
Any chance in getting an indent in here: ?
nope
Or is there not really a decent way of formatting these kind of content ^^
daaayum
noticing that there's no cog_load() functionality, is there a better place to put async initialization stuff?
Sane way or f*cky way?
Sane way would be create an async func, decorate it as a task loop with count=1 and start it inside the init
yeah I guess so
stuff like that always makes me feel like I'm doing something wrong but it'll work
.itworks
Lol

Just in case you want to know the fucked up way
import asyncio
class AsyncInit:
async def __new__(cls, *args, **kwds):
obj = super().__new__(cls)
await obj.__init__(*args, **kwds)
return obj
async def __init__(self, a, b):
print(a+b)
async def main():
d = await AsyncInit(1, 2)
asyncio.run(main())
3
0

unless it is a major efficiency upgrade or security patch
or your teacher tells you to
What my science projects look like
My modal dialogs are showing this, but the bot doesn't return an error. 🤔
When submitting.
are you sending a response?
🤔
Not directly after the modal, but last time I tried it returned an error that the interaction had already been responded to. 🤔
but i cant user followup.edit_message
I got that part to work now.
Thanks.
The next problem is using variables to store the modal's input.
Global variables were the only thing I found to work, but when two users use the function simultaneously, it puts both users in the same variable.
how to send a modal after doing interaction.response.defer()
Sending a modal is a response to an interaction, so if you're going to send a modal through that interaction, you don't need to defer it.
So you could simply use interaction.response.send_modal(), I think. 🤔
okay thanks
can anyone tell me why i can't import discord even if i installed it in different ways many times
?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
?tag git
No tag git found.
how do i make a response, if my select menu takes longer than 3sec?
defer doesnt seem to work, atleast i didnt figure out how
Store them on self variables on the modal instance?
CODE:
async def on_message(message: discord.Message):
auctions = bot.get_channel(1060824338057666580)
if message.channel.category == auctions:
if message.content.isdigit():
await message.reply("okay")
else:
await message.delete()```
**ERROR:**
```Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
if message.channel.category == auctions:```
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "c:\workspace\python\Bots\marketplace\main.py", line 207, in on_message
if message.channel.category == auctions:
AttributeError: 'DMChannel' object has no attribute 'category'```
read the error
ye
and even if it does, i wrote into the server
not into the bot DM
can i make a check if the server was sent into the server/guild?
if message.guild or something
message.channel.guild maybe?
message.guild works, problem probably solved :))
async def on_message(message: discord.Message):
auctions = bot.get_channel(1060824338057666580)
marketplace = bot.get_guild(1054406907110113421)
if message.author != bot.user.id:
if message.guild == marketplace:
if message.channel.category == auctions:
if message.content.isdigit():
await message.reply("okay")
else:
await message.delete()
why do the messages of my bot get deleted now?
This is my JSON right now
"auctions": [
{
"Akame": 250
}
]
}```
And this is my python code
with open("auctions.json", "r") as f:
data = json.load(f)
if int(message.content) > data['auctions'][f'{message.channel.name}']:
my question is, how can i access the number in the JSON (the 250)
async def on_timeout(self):
print("test")
self.clear_items()``` is clearing all items right how do i do it only disables the button
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
- MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
- PostgreSQL (Very popular and robust SQL based database management system)
- MySQL (Another popular SQL based system, good start for learning SQL)
i know that
but i dont want to learn how to use databases in python + SQL just to store 1 string and 1 number
at some point i definetly will learn a database system
If you don't want to learn, you're not gonna go very far
learn such a big thing just for storing 2 things
thats not worth it. i can just do it in json if its such a small thing
That's a pretty bad excuse for using a bad practice, but ok
i understand what you mean and i will learn a db system, probably sqlite
but i built my whole bot on json rn and its really just a small piece of data that i wanna store
Your question is also very basic python
so i think i would like to complete it with json for now
yeah i know
indexing in json files
help xD
Read #help-rules
but i dont understand why my code doesnt work + i dont know if i index "Akame" if if then takes the value of Akame
so it takes 250
or if it takes the string "Akame"
auction has a list as the value
so you cant do data['auctions']['Akame']
Is it possible to update a Image or Thumbnail in an Embed a few seconds after it was sent?
Edit the message with an embed containing the same content but a new image or thumbnail
Would I be able to access them from outside the instance? Like call the modal in a variable and return the user's input?
And access variables passed to the functions if I separate it. 🤔
Hey Om, I've it finished for the most part.
How to add a BytesIO file like object for a picture to an embed?
It works when you use a .png file from the disk, as is done in the commented line: # f = discord.File('C:\\Users\\path_to_file\\output.png', filename='output.png').
However, using a BytesIO file like object is giving me some trouble. Giving the png_file.name = 'output.png' is not sufficient enough to load the image into discord. Am I missing something here?
async def on_ready(self):
import io
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
svg_str = ""
svg_bytes = io.StringIO(svg_str)
png_file = io.BytesIO()
renderPM.drawToFile(svg2rlg(svg_bytes), png_file, fmt='PNG')
png_file.name = 'output.png'
# f = discord.File('C:\\Users\\path_to_file\\output.png', filename='output.png')
f = discord.File(png_file, filename='output.png')
e = discord.Embed(title='hi')
e.set_image(url="attachment://output.png")
ctx = await self.fetch_user(self.OWNER_ID)
await ctx.send(file=f, embed=e)
im getting an error which dont makes sense||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||https://ask-your-mom.big-pp.club/🥬🍢🥏🧜
To answer myself, the cursor of the buffer must be set to zero with png_file.seek(0).
What is the use of using the current cursor location in the discord.File? Has it a special usecase? Like, normally you would want to read the whole file from 0
# file.py ln92
if isinstance(fp, io.IOBase):
if not (fp.seekable() and fp.readable()):
raise ValueError(f"File buffer {fp!r} must be seekable and readable")
self.fp = fp
self._original_pos = fp.tell()
self._owner = False
can anyone solve my issue :(
patience
does that mean someone has to answer your question quickly?
How can I get Members (instead of Users) when querying reactions inside message_command? Do I need some permission (Intent)?
Is ctx.author not a member object by default, if the command is used in a server?
A DM channel does not have member objects.
Otherwise you can get members by the ID, but I don't know if that's the most efficient way.
This error suggests that bot is a Command object instead of a Bot instance.
You may need intents to get members.
what can i do to fix it?
Review your code, compare it to other examples. You didn’t post any relevant info, so hard to get any more specific than that
@bot.slash_command(name="bot")
async def bot(ctx):
em = discord.Embed(title="Discord Bot Development", description=":bot_discord18: Need a **custom bot** to enhance your server? we can create a **bot tailored** to your specific needs.\n\n :slayer_SantaGiftBox:1060910216876666970>**WE OFFER**\n\n> :tickets: One-time purchase\n> you'll receive lifetime **free servicing** + **free maintenance**, and **24/7 online** support\n> :discorddv: No **hidden fees or ongoing** costs - just **top-quality** service at an affordable price.\n\n**_STARTING PRICE_**: ||$7||\n\n **__Accepted payment methods:__**\n:Paypal40: :Crypto: :slayer_SantaGiftBox:\nSimply open a `ticket` in the ticket channel to get started. We'll work with you to design and implement the perfect bot for your server.", color=discord.Color.orange())
em.set_footer(text="• Xlereaon Services")
button = Button(label="Create Ticket here", url="https://discord.com/channels/1050739616216518726/1055758151040905227", emoji="https://discord.com/channels/1050739616216518726/1055758151040905227")
view = View()
view.add_item(button)
ctx.channel.send(embed=em, view=view)
bot.run(c.TOKEN)
here
Well first off, you should rename your def bot. You can have the command name bot, as you’ve already defined it. But remove the ambiguation
OOHHH I SEE holy smokes im so dumb. tysm and nvm lol
.send is a coroutine btw
Is it possible to see the dms a bot get? Or do I have it to do like send the content a user send to the bot in a specific channel or also DM to a specific user?
—
In my case I have a auto reply for users dming the bot like: noreply@bot - can’t read it. Which is probably not correct bc I could store/display them somewhere else?
wdym?
You must await it
on_message is called when your bot is dm’d
u can access the content with message.content
I am getting this error file parameter must be File
I am sending a ZIp FIle
Ah I forgot, made each file inside a discord file but not the zip thanks
Getting this now discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not ZipFile
Yes, that was the case - the members one
Can embed thumbnails be gifs?
irrc they can
yes, same for the image
Ok thanks
Hey does anyone know why Discord.File is removing ^ from my file name?
because files cannot have ^
Is there no way to rename them to allow it, I know its an operator or something but does python have a way to null it so its just a normal character?
show your code?
hmm so it works now?
temp = "_" + faction.lower() + "_" + str(change_name).replace(" ", "") + "_" + item
os.makedirs(os.path.join(temp))
# Moves into Folder
shutil.move(filename_start + ".png", os.path.join(temp))
shutil.move(filename_start + ".png" + ".json", os.path.join(temp))
# Rename ytd Path
file_directory_prep = str(r"mp_{gender}_freemode_01-{type}_diff_{value}_{letter}_uni")
os.rename(temp + ".ytd", file_directory_prep.format(gender="m", type=item_base['type'], value=item_base['value'], letter="[A-Z]" + ".ytd"))
# Move Folder and ytd
shutil.move(temp, os.path.join("sent/", temp))
shutil.move(file_directory_prep.format(gender="m", type=item_base['type'], value=item_base['value'], letter="[A-Z]" + ".ytd"),
os.path.join("sent/",
file_directory_prep.format(gender="m", type=item_base['type'], value=item_base['value'], letter="[A-Z]" + ".ytd")))
Or if possible I am wanting to just send a zip file but getting this error: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not ZipFile
.rtfm on_voice_channel
Target not found, try again and make sure to check your spelling.
.rtfm join
discord.on_guild_join
discord.on_member_join
discord.on_thread_join
discord.on_thread_member_join
discord.SystemChannelFlags.join_notification_replies
discord.SystemChannelFlags.join_notifications
discord.Member.joined_at
discord.Thread.join
discord.ThreadMember.joined_at
discord.MemberCacheFlags.joined
.rtfm on_
discord.SlashCommandGroup.is_on_cooldown
discord.Bot.add_application_command
discord.Bot.application_command
discord.Bot.application_commands
discord.Bot.application_flags
discord.Bot.application_id
discord.Bot.application_info
discord.Bot.get_application_command
discord.Bot.get_application_context
discord.Bot.invoke_application_command
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.Bot.pending_application_commands
discord.Bot.process_application_commands
discord.Bot.remove_application_command
discord.Bot.walk_application_commands
discord.AutoShardedClient.application_flags
Move to #883236900171816970 if you're gonna spam commands
nah i am just looking for on_voice_connect or smth
Then use the search feature on the docs, or move to #883236900171816970
any ides?
on how to make it
.rtfm on_voice_state_update
oh thanks
yeah yeah
any ideas on if it's possible to allow a user to chat in a channel, but not allow them to see any chat history, previous or ongoing?
doesnt look possible looking at permissions but just wanted to check
Yes, just enable send messages and disable view history
That will still show any messages sent while looking at the channel
Then it's not possible.
yeah, looks more possible just to use dms for what I want
.rtfm button()
Target not found, try again and make sure to check your spelling.
remove the () and go to #883236900171816970
@discord.ui.button(label="verify", style=discord.ButtonStyle.link, url="https://youtube.com")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: button() got an unexpected keyword argument 'url'
uh i dont understand why i am getting a error
Can you show the pip list?
aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
certifi==2022.12.7
charset-normalizer==2.1.1
discord==2.1.0
discord.py==2.1.0
ffmpeg-python==0.2.0
frozenlist==1.3.3
future==0.18.2
idna==3.4
imageio-ffmpeg==0.4.7
multidict==6.0.4
numpy==1.24.1
peppercorn==0.6
py-cord==2.3.2
requests==2.28.1
sampleproject==3.0.0
urllib3==1.26.13
yarl==1.8.2
uninstall ```py
discord==2.1.0
discord.py==2.1.0
py-cord==2.3.2
and reinstall py-cord
okok
im stil getting the same error
and my new pip list is this:
aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
certifi==2022.12.7
charset-normalizer==2.1.1
ffmpeg-python==0.2.0
frozenlist==1.3.3
future==0.18.2
idna==3.4
imageio-ffmpeg==0.4.7
multidict==6.0.4
numpy==1.24.1
peppercorn==0.6
py-cord==2.3.2
requests==2.28.1
sampleproject==3.0.0
urllib3==1.26.13
yarl==1.8.2
did you restart the IDE?
yea
You cant create url buttons like that
Here's the link example.
tysm
Yes ;D Now I got the threading implemented too
Unfortunately, the cairosvg didnt work for me, but svglib does do the job somewhat
Thnx for the tipx
I'm not sure if this is the right channel for this but I have a question. I would like to edit a message that has been sent by it, but I don't know how I should do that because the only references I found were using ctx(Applicationcontext).send(), but I have to use ctx.respond() otherwise you get a exception that the Bot didn't respond even though it sent a message. (Bearbeitet)
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 ...
await ctx.interaction.original_response() would return the message you responded with
thanks all of you
why is my bot.users empty when the bot is on a server with some users?
you are missing members intent
but why do I need member intent when i want the users
@bot.event
async def on_message(message):
# Check if the auto-check feature is enabled for this server
cursor.execute('''
SELECT enabled FROM auto_check WHERE server_id=?
''', (str(message.guild.id),))
result = cursor.fetchone()
# Use the SentimentIntensityAnalyzer to analyze the sentiment of the message
sid = SentimentIntensityAnalyzer()
sentiment = sid.polarity_scores(message.content)
toxicity = sentiment['compound']
drama = sentiment['neg']
if message.author.id == "1057048030920061048":
return
if result and result[0] == 1:
# Check if the toxicity or drama score is above a certain threshold
if toxicity < -0.4 or drama > 0.4:
await message.channel.send("Detected a potentially toxic or dramatic message. This is your warning. Please stop! Thanks!")
else:
await message.channel.send(f"Neutral {message.content}")
No errors, the bot just reads its messages onlyWHY?
Intents are given in code.
Intents are given in dhasboard
because you can only see users in a guild
@silver moat any idea?
show code for intents
intents = discord.Intents(messages=True, guilds=True)
bot = commands.Bot(commands_prefix="!", intents=intents)
message_content is also an intent you should specify
so i do
intents = discord.Intents(messages=True, guilds=True, message_content=True)
yeah
what do you mean ?
In order to cache a user, you would either need to fetch them or share a guild with them.
and the bot does
right, but for the bot, the guild doesn't have any members
because you don't have members intent
and intents.message=True ;3
the correct intent is messages
same 
how to delete interaction response python
msg = await interaction.response.send_message(view=verify())
well that returns an interaction. You would use interaction and https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.original_response would return the response message.
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 ...
is there an easy way to get the same guilds the bot and a specific user is in?
.rtfm mutual_guild
@dry echo ^
thank you!
is it possible to get the color? because user.color gives me 0 and accent_colour None
i have no banner?
i just mean I have no banner because i dont have nitro...because of that this color shows up. but how can i fetch it?
accent color is what you would use, but interactions give the bare minimum information about the user.
How do you delete an attachment file in an embed?
await ctx.respond(file=file, embed=embed)
I want to keep the embed but delete the file
I assume you’d have to edit the message by passing file as None and passing the embed back in
Just pass file=None
the embed stays?

