#Basic Pycord Help (Quick Questions Only)
1 messages · Page 85 of 1
just not posting at all
and i've tried debugging already
it has it stored in the DB just fine
but its not posting
please give your tasks actual names
its sending the ephmeral message
but not posting in the channels
at all
how do you cross out something like that
~~My Text~~
If the channel isn't in cache, bot.get_channel(channel_id) is going to return None
You should fetch the channel instead
channel = await utils.get_or_fetch() would be best since it doesn't make API calls if not necessary
.rtfm get_or_fetch
discord.utils.get_or_fetch
discord.ext.bridge.AutoShardedBot.get_or_fetch_user
discord.Client.get_or_fetch_user
discord.ext.commands.Bot.get_or_fetch_user
discord.Bot.get_or_fetch_user
discord.ext.commands.AutoShardedBot.get_or_fetch_user
discord.AutoShardedBot.get_or_fetch_user
discord.AutoShardedClient.get_or_fetch_user
discord.ext.bridge.Bot.get_or_fetch_user
Is there a build-in class/function for the help command in form of a slash command?
Docs says it's recommended to use the build-in solution, but that class is build to be used as a classic/prefixed command, from what I see
Asking in case I can save myself from reinventing the wheel
okay i did change to that, but its still not posting
which is why this is so weird haha
TypeError: get_or_fetch() missing 2 required positional arguments: 'attr' and 'id'
Take a look at the example
.rtfm get_or_fetch
discord.utils.get_or_fetch
discord.ext.bridge.AutoShardedBot.get_or_fetch_user
discord.Client.get_or_fetch_user
discord.ext.commands.Bot.get_or_fetch_user
discord.Bot.get_or_fetch_user
discord.ext.commands.AutoShardedBot.get_or_fetch_user
discord.AutoShardedBot.get_or_fetch_user
discord.AutoShardedClient.get_or_fetch_user
discord.ext.bridge.Bot.get_or_fetch_user
channel = await discord.utils.get_or_fetch(server, 'low-tier-items', LOW_TIER_ID, default=None)
?
channel = await discord.utils.get_or_fetch(server, 'high-tier-items', HIGH_TIER_ID, default=None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/utils.py", line 614, in get_or_fetch
getter = getattr(obj, f"get_{attr}")(id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'get_high-tier-items'
nope
you're trying to get/fetch a channel, not "low-tier-items"
thats the channel name
but pycord doesn't know this (not before getting the channel)
you have to specify the type of object you want to return
in your case, a channel
OH
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/tasks/__init__.py", line 169, in _loop
await self.coro(*args, **kwargs)
File "/Users/jef/Desktop/employee.py", line 712, in lowtask
channel = await discord.utils.get_or_fetch(server, 'channel', LOW_TIER_ID, default=None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/utils.py", line 614, in get_or_fetch
getter = getattr(obj, f"get_{attr}")(id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'get_channel'
i understand very little of this error
basically, what happens is this:
You set serveras the object here:
channel = await discord.utils.get_or_fetch(server, 'channel', LOW_TIER_ID, default=None)
Then, the library does the following:
channel = object.get_channel(channel_id)
if not channel:
channel = await object.fetch_channel(channel_id)
Since server is a list of server_ids (Please name your variables accurately, sth like allowed_server_ids would be more fitting), but this list doesn't have the method get_channel, guilds do
so i need to use a specific guild ID?
What does that mean:
Cant Connect to Discord. Too many Files opened
or a bot object
i dont understand
Do you know what a method is?
I just use discord.utils.get(ctx.guild.text_channels, id=123) the most of the time
not really
No tag lernpython found.
im learning by doing 😭
To be clear:
When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.
We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.
let's just ignore my typo
i've only been programming overall for 3 weeks 😭
where can i learn about OOP (dont know what that is), and Async/Await
It's really hard to help you without you knowing basic OOP
lern is german for learn xd
are you able to let me know what i am doing wrong
so i can fix it and then
go learn python
but that won't help you in the long run
.
?tag oop
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html
There's a difference between a class and an instance. Think of it like this:
- A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
- An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.
Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.
mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.
There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.
What does that mean:
Cant Connect to Discord. Too many Files opened
Google it
When in doubt, Google it.
Hmm okay. Nice help
I mean, Google it more accurate.
That's a google question IMO
Kind of like “ask 3 before me” but “ask the damn machine that does everything before me”
So why does this section exist if you can google anyway? 

If Google isn’t smart enough?
thread_group = discord.SlashCommandGroup(
name="thread",
description="Group of thread commands!",
default_member_permissions=discord.Permissions(administrator=True)
)
thread_directory_group = discord.SlashCommandGroup(
name="directory",
description="Group of thread directory commands!",
parent=thread_group
)
@thread_directory_group.command(name="add", description="Adds the thread to the thread directory!")
async def thread_directory_add(self, ctx: discord.ApplicationContext,
thread: discord.Option(discord.Thread, "Please enter the thread!", required=False)):
Any ideas why /thread shows up but not /thread directory add?
Its even in the help rules Nr. 2 #help-rules
You need to make a subgroup of the main slash command group
thx
.rtfm discord.SlashCommandGroup.create_subgroup
its not the name of the guild is it?
how do i have a guild object without an ID
guild objects do have an id, tho get_or_fetch requires a guild object and not guild.id
@rare ice Is there a way to send async webhooks with pycord. I think that is the problem.
You can’t
Check the guide
.tag guide
i see
what is a guild object
Oh there isn’t a guide on it
Yes
Pycord offers support for creating, editing, and executing webhooks through the Webhook class. Attributes avatar, channel, channel_id, created_at, guild, guild_id, id, name, source_channel, source_...
@clear vault maybe this one is helping?
Thanks
is it possible to respond with an ephemeral message on the "on_message" event?
no because ephemeral messages can only be sent as a response to interactions
thanks
guild = await bot.get_guild(id)
channel = await discord.utils.get_or_fetch(guild, 'channel', HIGH_TIER_ID, default=None)
why get_guild?
dark soul said i needed the guild and not the guild id
should i fetch it instead?
I'm sure get_guild isn't a coro
is Embed.from_dict save? (Do I need some json validation, if I get it from users)
Yeah fetch was the way to go
What’s a coro?
Tias
Coroutine
Asynchronous functions are called coroutines
wdym tias? I ask, is it save to pass json from users?
That’s what I thought, thanks!
"Try it and see"
I know what it means bruh
I ask, is it just safe
How do I need to even try it and see, wait until someone abuses that?
then why did you ask bruh
wdym abuse it wtf
Try it and see
read that
try it
Like SQL injection?
wtf are you talking about
deploy it and see if it breaks
god damn children

^^^^^^^^^^^^^^^
people don't know how to read i swear
usually people under 13 :/
not gonna make out any names

~~pulling my hair out a little bit here.
message = output_character(codename, ch)
try:
await ctx.respond(message)
except discord.errors.HTTPException as e:
with open("message.txt","w") as file:
file.write(message)
await ctx.respond("The message is too long to send. Please view the attached file.",file=discord.File('message.txt'))
os.remove('message.txt')
log("Sent character sheet as file")
this is a snippet of code at the end of a slash command call. output_character assigns the raw string I want to send to the user to message. in this context, message can be quite long, sometimes exceeding 2000 chars. the idea here is for the bot to send the message content as a file instead of a message body if the initial ctx.respond fails.
the kicker is this:
i have 2 versions of my bot: one for testing, and one for actual member-facing use.
- on my testing bot, this works fine. if message content exceeds 2000 chars, it's sent as a file instead, exactly as i want.
- on my main bot (which is verified by discord), HTTPException: "Must be 2000 or fewer in length" is thrown and the command fails unconditionally if
messagehas a length above 2000.~~
i have no idea what the issue is here. even when both bots are running the exact same code they perform differently.
i've also attempted to do this via checking len(message) > 2000 beforehand and got similar results
oh fucking hell. nevermind. git issue. i've been working on the wrong branch this entire time
average git
"i dont need to delete the branch yet it'll be fine"
i would like to travel back in time about 1 hour and strangle that version of myself rq
then that version of yourself will travel forward in time about 1 hour and strangle that version of yourself that tried to strangle that version of yourself


but then the versions of yourself will diverge and you'll have merge conflicts
git reset --hard HEAD
data loss
i need help using pycord with a tkinter gui
What's the best way to warn users with a moderation bot? I mean, if the bot detects a bad word, how do you warn the user about his behaviour? Via private message?
- Ping them in the channel that they were warned in
- DM them
- Log the warn
all three should be done
I said you need a guild or a bot object
git stash and git cherry pick
I have a command and I respond to the command like this:
msg = interaction.respond(embed=embed)
works fine. then I wait for a user Input. That works also fine. Now I want to edit the message. How can I do it?
with msg.edit(embed=emb)
?
read the docs 
.rtfm interaction.edit_original
Thanks
For some reason I get an error: discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction , while trying to send an embed?
@bot.slash_command()
@option("by", description="Search from ISBN, Name, or Author", choices=["ISBN", "Title", "Author"])
@option("value", description="Enter the relevant term for your search")
async def search(
ctx: discord.ApplicationContext, by: str, value: str,):
url: str = f"https://openlibrary.org/search.json?{by}={value}".lower()
response = requests.get(url)
data = response.json()
# Check if there are any documents in the response
if "docs" in data:
# Iterate over the documents
for doc in data["docs"]:
# Check if the document has a language field
if "language" in doc and len(doc["language"]) == 1 and doc["language"][0] == "eng":
# Check if the document has an ISBN
if "isbn" in doc:
# Grab the ISBN and print it
isbn = doc["isbn"][0]
print("ISBN:", isbn)
embed = discord.Embed(title="Located Book", description=f"I found a book with the ISBN: {isbn}")
embed.set_author(name=f"Search by for '{value}'")
await ctx.respond(embed=embed)
break # Exit the loop since we found the desired document
else:
print("No English document found.")
else:
print("No documents found in the response.")
Works fine if there is no embed response, and if it is just printed
Dont use requests
?tag requests
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
is that the reason why this error occurs?? There is no error if I don't use embed.
Yes
sorry. haven't bot programmed in a while
If you use requests, its gonna block yout whole bot
hey Zervyel could you look into my help thread? I have no clue what I'm doing wrong and have been stuck on this for a very long time #1121388195322540102
Yet same issue?
@bot.slash_command()
@option(name="by", description="Search from ISBN, Name, or Author", choices=["ISBN", "Title", "Author"])
@option(name="value", description="Enter the relevant term for your search")
async def search(ctx: discord.ApplicationContext, by: str, value: str):
url = f"https://openlibrary.org/search.json?{by}={value}".lower()
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.json()
if "docs" in data:
for doc in data["docs"]:
if "language" in doc and len(doc["language"]) == 1 and doc["language"][0] == "eng":
if "isbn" in doc:
isbn = doc["isbn"][0]
embed = discord.Embed(title="Located Book", description=f"I found a book with the ISBN: {isbn}")
embed.set_author(name=f"Search by for '{value}'")
await ctx.respond(embed=embed)
else:
print("No English document found.")
else:
print("No documents found in the response.")
defer it
so bot is just slow
bummer... idek how to make this faster.
I am trying to make a book which has a folder of books, and user can pass a param like ISBN, title or author, and get info about the book, if there is an entry for it on my pc, I can even attach it in the message.
sadly, just the remote api takes too long
You have to respond after 3 seconds
yeah so, just querying the api alone takes 3 seconds.
So you already could send a respond after that edit or send a new message
could it be because it has so many entries?
perhaps, is there a way to stop reading after some point, and not have to make a request just to pull all this unessecary data
Essentially I am grabbing the 0th book, so long as it is "eng"
error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Messageable.send() got an unexpected keyword argument 'ephemeral'
Code:
await interaction.channel.send(embed=embed, ephemeral=True)
why?
Response
oh
and when the interaction got responded before it is interaction.followup.respond right?
it worked thanks
yesterday i caused a war on the python server so ill do it here as well, indent using tabs or spaces?
Why should you use spaces?
most ides use fake tabs so it just changes it to spaces
pretty sure spaces also let u do indentation like this ```py
foo(
bar, bar1)
I would like to know how many bots my server has, the only way is as follows?
bots = [member for member in guild.members if member.bot]
Yes
Thanks! I'm not sure about what you mean with the first one. Can you explain it a bit? Do you mean the @ thing?
i think it just means if the bot detects a bad word in the channel, delete the message then in the same channel ping the user and give them a warning
something like @user don't use those types of words here!
Thank you very much
not possible on api
How do I do slash commands ?
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
Thank you :)
Can someone explain this to me:
Traceback (most recent call last):
File "c:\Users\waike\Desktop\Discord Bot\main.py", line 7, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
PS C:\Users\waike\Desktop\Discord Bot>
Show your pip list
Do you know basic Python?
I'm like a above average
Than why did you send a screenshots of what you imported and not the pip list?
Is there any way to get information from the server, whether it is a partner, verified or tier premium?
something similar to this?
guild = ctx.guild
if guild.partnered:
print(guild.partnered)
print(f"{guild.name} is a Discord partner server.")
if guild.verified:
print(guild.verified)
print(f"{guild.name} is a verified Discord server.")
if guild.premium_tier:
print(guild.premium_tier)
print(f"{guild.name} has the level of reinforcement {guild.premium_tier} on Discord.")
Uninstall all 3
ok
also uninstall and only reinstall py-cord 2.4.1
What do you mean?
You also have to install py-cord new
and you have a old version installed
It's working now thanks :)
\o
is this a correct way of using perms in a slash command group?
reaction = discord.SlashCommandGroup(
name="reaction",
description="Commands relating to reaction-roles within the guild",
default_member_permissions=discord.Permissions.manage_guild = True
)
I'm getting the
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
really often, and I don't know how to fix it
Is there anyone that will allow me to share my full code to them in DMs to help me out?
It happens you take longer than 3 seconds to respond the most of the time
Right, so is there a way for me to fix it?
defer it
still fails
which is why i need to show someone my full code i think
Does it also happend to a basic slash command?
@bot.slash_command(server_id = server, name = "ping", description = "returns pong")
async def ping(ctx):
await ctx.respond("pong!")
commands like that don't fail i dont think
Did you test it?
just now i did
and it didn't fail
ill run a more complex command and see if the more complex one fails
And if you just send a respond and a message after that?
all commands are working right now so i can't give you much information in regards to that
but usually if i don't use the bot for a while
the first command i use after that break will fail
and the next will succeed. it's like it has a startup time
How do you host the bot?
it's still in development
do you think that i should open up a seperate help post for this, as to not misuse this post?
well host is the issue here. you either have a bad network, or the OS puts the bot to sleep
i assume its the second one
how do i prevent that?
like you said, the 1st request will "warm-up" the network and process, so the following requests dont fail
it doesnt do that for me 
so do you think that i should just host like the parts that are working fully
try using a process manager. maybe pm2?
what is that?
does it say "This interaction failed, or The application did not respond"?
speaking of pm2, can i use pipenv to run my bot using it and how
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
full error
a process manager. it helps run and manage node/python or other "processes"
https://pm2.keymetrics.io/
I also use PM2 for my Bots
havent used pipenv sry
you think this will be able to hit my mac with a hammer constantly to keep the bot awake?
not really. it doesnt need to do that
as you said it is development, so this probably doesn't matter rn
have u ever used pipenv
i just need the interactions to stop failing

is there any other way to get a channel object other than discord.utils.get
.rtfm get_channel
discord.ext.commands.Bot.get_channel
discord.ext.bridge.AutoShardedBot.get_channel
discord.ext.commands.AutoShardedBot.get_channel
discord.AutoShardedBot.get_channel
discord.AutoShardedClient.get_channel
discord.ext.bridge.Bot.get_channel
discord.Guild.get_channel
discord.Guild.get_channel_or_thread
discord.Client.get_channel
discord.Bot.get_channel
get_channel, fetch_channel
there are a few x3
that method is available on bot and guild objects
so i'm lost on how this will help
if its not keeping the bot awake
it should keep it awake. although it wont hammer the cpu. (not sure about this)
i see
How to make arguments required (Instend of Optional) in slash commands?
required=True
;3
or just dont add it
where do I put this though?
At the Option
Okay
if you are using discord.Option, put it in the constructor, if you are using @option, put it in there
does TextChannel.clone clone the channel in the same category and basically replaces the channel?
it's not a replace, it's a new channel with the same attributes (+renaming), same as "Duplicate Channel" on the UI
it will be in the same category
so if i clone it and then delete it its basically a replace, will it be in the same position as well?
it'll be at the bottom of the category
right, so i still need to move it up
still don't get it
what is your current code?
required is already the default, if it's not then you've done something else wrong
@young bone since u use pm2, how do u check logs? ive done pm2 monit once they were there, then exited and then pm2 monit again and logs are gone?
pm2 logs
I'm fairly new to Py Cord and Python in general so idk
@bot.command(description="Kicks the user from the guild")
@has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
embed = discord.Embed(
title="User Successfully Kicked",
description=f":white_check_mark: {member.mention} has been kicked by {ctx.author.mention}",
color=discord.Color.teal()
)
embed.set_thumbnail(url=ctx.author.avatar.url)
embed.add_field(name="Username", value=f"`{member.name}`", inline=True)
embed.add_field(name="User ID", value=f"`{member.id}`", inline=True)
embed.add_field(name="Punished by", value=f"{ctx.author.mention}", inline=True)
embed.add_field(name="Reason", value=f"{reason}", inline=False)
embed.set_footer(text=f"Executed by: {ctx.author.username}")
await member.kick(reason=reason)
await ctx.respond(embed=embed)
isn't it literally just pm2 logs {process}
^
oh
pm2 -help
well thanks
I'm assuming this is a slash command
I said that...
i am free of tmux
which option is not required rn?
just remove the *,
okay...
Why do you have an * in a slash command?
it use to be normal prefixed commands but I changed over
also, the =None should also be removed if you want it to be required
Now I'm getting this:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Member' object has no attribute 'username'
which py-cord version do you use?
The lastest one (you told me to use)
.
use .name
^^^^^^^^^^^
what?
It doesn't say
then show the code for the command u ran
Okay I didn't really read it...
but it says this...
now I got to remove .username to 20 other commands...... welp ok
can someone help me with the correct way to defer an interaction
.rtfm interaction.defer
Target not found, try again and make sure to check your spelling.
Easily share your source code with other developers.
.rtfm ctx.defer
Target not found, try again and make sure to check your spelling.
bruh
.rtfm defer
discord.ext.bridge.BridgeContext.defer
discord.ext.bridge.BridgeExtContext.defer
discord.InteractionResponse.defer
discord.InteractionResponseType.deferred_channel_message
discord.InteractionResponseType.deferred_message_update
discord.ext.bridge.BridgeApplicationContext.defer
discord.ApplicationContext.defer
oh its interactionresponse
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 ...
can you check this out though
ill look at the docs
yeah my code looks correct based on the docs
yep
you can even swap out ctx.followup.send with ctx.respond as the library takes care of that for you
well honestly what i want is a ping in the same message as the embed
i made this code so long ago i'm sure its possible and i just was stupid at the time
because i want it to ping them
await ctx.respond(content = "ping here", embed = embed)
content = ?
never heard of that, let me try it thank you!
await ctx.respond(content = f"{member.mention}\n", embed = tradeEmbed)
it sends the mention but its not a ping
like a notification, yellow highlighted message type ping
help plz
?
i'll send a screenshot
try using use allowed_mentions
return compile(tree, filename, "exec")
TypeError: arguments field "args" must be a list, not a NoneType
but there is no list argument wtf
okay ill look that up in docs
i am not sure why that's happening
it should be pinging?
hmmm
maybe i move the ping to the bottom of the message
would look ugly though
im not very advanced in pycord, just very basic knowledge 
maybe look for what om suggested
bot = commands.Bot(command_prefix = "!", intents=discord.Intents.all(), help_command=None, AllowedMentions = all)
should that do it?
discord.AllowedMentions
discord.AllowedMentions.all
discord.AllowedMentions.everyone
discord.AllowedMentions.merge
discord.AllowedMentions.none
discord.AllowedMentions.replied_user
discord.AllowedMentions.roles
discord.AllowedMentions.to_dict
discord.AllowedMentions.users
discord.Bot.allowed_mentions
discord.AutoShardedBot.allowed_mentions
discord.ext.bridge.Bot.allowed_mentions
discord.Client.allowed_mentions
discord.ext.commands.AutoShardedBot.allowed_mentions
discord.AutoShardedClient.allowed_mentions
discord.ext.bridge.AutoShardedBot.allowed_mentions
discord.ext.commands.Bot.allowed_mentions
ah damn i was hoping i would finally correctly use the docs
what
- AllowedMentions = ...
+ allowed_mentions = ...
yeah i get an error when i use allowed_mentions
hold on let me send it
bot = commands.Bot(allowed_mentions = discord.AllowedMentions.all, command_prefix = "!", intents=discord.Intents.all(), help_command=None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 124, in init
super().init(**options)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/commands/core.py", line 1225, in init
super().init(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 1132, in init
super().init(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 85, in init
super().init(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/cog.py", line 611, in init
super().init(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 244, in init
self._connection: ConnectionState = self._get_state(**options)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 263, in _get_state
return ConnectionState(
^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/state.py", line 194, in init
raise TypeError("allowed_mentions parameter must be AllowedMentions")
TypeError: allowed_mentions parameter must be AllowedMentions
big boy error
you need to call the method
()
no errors but i'm not getting the mention
is it because of the defer?
Easily share your source code with other developers.
that's my code by the way
so that this is easier for you
try this await ctx.respond..., allowed_mentions= discord.AllowedMentions.all())
i did
unfortunately
no luck
maybe its a discord issue
await ctx.respond(content = f"{member.mention}\n", embed = tradeEmbed, allowed_mentions = discord.AllowedMentions.all())
hmm
Do I have to worry about sharding my bot at the start, when its only in like 10 servers? Or can I easily implement AutoSharding later when the amount of servers increases?
Sharding is only need post 2k servers
and it wont even work before that
so using AutoShardedBot before that will only cause overheads
alright, tysm!
hello!
How do I make checks before a command kicks in?
I want to only restrict users usage to only users that have a certain role.
Is it also possible to hide it for users without that role?
I would've said you could use discord permissions by using @discord.default_permissions which checks if the user has role permissions. But if its a personal bot you might directly just use discord's feature which allows you to select on your server who is allowed to use what commands (Under integrations tab; works for slash commands, see image)
But if those are definitely not the ways you want to go, you need to make a custom checker which for example checks if user is admin or smth like that.
(checks if the author has role xxx)
Perfect, I'll try those options, thanks a lot!
How do I send text files
Just like any other file
how i can get categories without ctx?
categ = discord.utils.get(ctx.guild.categories, id=1103752167095017513)
(is on on_ready)
guild.get_channel works for categories
@bot.slash_command(name = "profile", description = "See a user's Profile.")
async def profile(interaction: discord.Interaction, user: discord.Member = None,):
how do i add a description for the user context menu?
user: discord.Option(discord.Member, "My description", default=None)
@su_group.command(name="db", description="Execute a SQL command (owner only)")
@is_owner()
@option(name="sql", type=str)
async def sql(self, ctx: ApplicationContext, sql: str) -> None:
result = await self.bot.db.run_raw_sql(sql)
result_type = type(result)
embed = await build_embed(
self.bot.theme,
"Database Query",
f"""
**Result**
\`\`\`py
{result}
\`\`\`
**Type**
\`\`\`py
{result_type}
\`\`\`
""",
)
return await ctx.respond(embed=embed)
with this code, i keep getting unknown interactions
here's how im using it
add await ctx.defer() at the start of the callback
it isnt taking 3s
the error does indicate that 3s passed before you could respond
How do I send files i used
await ctx.send(file=discord.File("file path"))
But didn't work
.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.
Wait I'll send the error message
Ok so for some reason, passing deug_guild id into my subclass of discord.Bot does not work... and I have no idea why.
"Does not work" --> It doesn't make my commands private.
- How do I know it doesn't work.
I have a checker which checks if commands are global or private, I even checked it to see if the Guild which's ID I provided has any private commands (and it has none so my bot's commands are global)
import platform
import sys
from datetime import datetime
import colorama
import discord
from core.utils import Log, intents
colorama.init(autoreset=True)
sys.stdout = Log(open('./logs/console.log', 'w'))
class Beanie(discord.Bot):
async def on_ready(self):
base_url = discord.utils.oauth_url(self.user.id)
permissions = discord.Permissions.administrator.flag
link = f"{base_url}&permissions={permissions}"
print(colorama.Fore.GREEN + f"\n ---------")
print(colorama.Fore.GREEN + f"System-OS : {platform.system()}")
print(colorama.Fore.GREEN + f"OS-Version : {platform.version()}")
print(colorama.Fore.GREEN + f"Discord-Tag : {self.user}")
print(colorama.Fore.GREEN + f"Client-ID : {self.user.id}")
print(colorama.Fore.GREEN + f"Conected-Guilds : {len(self.guilds)}")
print(colorama.Fore.GREEN + f"Latency : {round(self.latency * 1000)}ms")
print(colorama.Fore.GREEN + f"Time : {datetime.now().strftime('%d-%m-%Y %H:%M:%S')}")
print(colorama.Fore.GREEN + f"Bot-Invite : {link}")
# Write the list of intents to a file using the Log class
sys.stdout.write_intents(intents)
print(colorama.Fore.GREEN + f" ---------\n")
debug_server = globals().get('debug_server', [])
bot = Beanie(intents=intents, debug_guilds=[1114959767715184730])
Any help is appreciated.
documentation even asks for a list with int's so... I am lost at this point.
And here's my regcheck.py file (which is run seperately) if you're wondering how I checked for them to be global / private
import requests, os
from dotenv import load_dotenv
load_dotenv()
bot_id = 1234567891011121314
# Replace these values with bot's information
BOT_TOKEN = os.getenv('token')
CLIENT_ID = bot_id
headers = {
"Authorization": f"Bot {BOT_TOKEN}"
}
GUILD_ID = 1114959767715184730
response = requests.get(f"https://discord.com/api/v9/applications/{CLIENT_ID}/guilds/{GUILD_ID}/commands", headers=headers)
if response.status_code == 200:
commands = response.json()
if not commands:
print("No commands found.")
else:
for command in commands:
print(f"{command['name']}: {command['id']}")
else:
print(f"An error occurred: {response.text}")
(@solemn idol me if you've got a solution)
I get this discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'File' has no len()
full error please 🙃
Okok
Traceback (most recent call last):
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 184, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\thegi\Desktop\development\chatgpt bot\main.py", line 33, in check
await ctx.send(f"Total detected : {len(list_of_members)}", files=discord.File('log.txt'))
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\abc.py", line 1498, in send
if len(files) > 10:
TypeError: object of type 'File' has no len()
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 344, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 951, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 193, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'File' has no len()
any idea ?
parameter for a single file is file, not files
files is for sending multiple files
it needs a list
hey, does ctx.guild.get_member fetch from cache?
yes get_member will return from cache
thanks
np
so
await ctx.send(files=[discord.File('filepath
')])
.tias
so i can rely on the rule of thumb, being get_ for cache and fetch_ for api call?
Thanks @proud mason it works have a nice day
oh and I also tried making private commands like this;
which does also not make it private for no reason,intents does function like it usually should but adding a debug guild just doesnt.
yep thats right
thanks you're an absolute lifesaver
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions does this mean i have no perms? or the bot?
because me and the bot are 1st and 2nd highest roles respectively, all with admin
and im editing a member who doesnt have admin and is the lowest role
although all other switches are turned off 🤔
that might be it
nope
any ideas? 😄
What are you trying to do on the user
edit their nickname and edit their roles
yeah one second
my code's pretty long
try:
user = await ctx.guild.fetch_member(int(id))
except HTTPException:
raise InvalidId
if not user.get_role(int(role_data[0])):
raise NotVerified
[_, pss_name, __, ___] = await get_user_info_by_name(user.display_name, token)
roles = []
for role_id in role_data:
if not role_id:
raise NotConfigured
role = get(ctx.guild.roles, id=int(role_id))
if not role:
raise NotConfigured
roles.append(role)
await ctx.user.edit(nick=None)
await ctx.user.remove_roles(*roles)
await self.bot.db.insert_data_into_table(
ship_table, {"ships": dumps(ship_data)}
)
return await ctx.respond(embed=success_embed)
traceback:
https://sourceb.in/d6LFEzzkIT
You're trying to edit the author
You're doing ctx.user.edit
how do I check if a message is a response to another message?
as in reply?
yes, like this
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 ...
oh, that's the name. I couldn't find it. Thanks!
Can I make the bot check if someones dm is opened or closed
You could send a message and handle the error in try-except
Or maybe use user.create_dm
.rtfm create_dm
discord.Client.create_dm
discord.Member.create_dm
discord.ext.bridge.Bot.create_dm
discord.ext.commands.AutoShardedBot.create_dm
discord.ext.commands.Bot.create_dm
discord.Bot.create_dm
discord.User.create_dm
discord.AutoShardedBot.create_dm
discord.ext.bridge.AutoShardedBot.create_dm
discord.AutoShardedClient.create_dm
how can I read the content of a referenced message? I have the ID, can i get it by ID?
get_message?
.rtfm get_message
in the on_message_edit even it takes a before and after message and to check if the author is a bot is it as simple as if before.author.bot
.tias
so yes
Want me to send the tag again
no just usually when u say it it means a yes
its literally what it says;
Try it and see
If you try it and it works, then it works and the problem is resolved.
If you try it and it doesn't work then we can further assist you as problem solving is usually just trying something different which would make the most sense and then trying it out to see if it works.
i know, it works
Hello, I've been trying out the discord Guild Settings > Integrations feature, but I can't figure out how do "overrides" work. I mean this thing:
Can anyone help me?
i did and it works idk what problem there is
So there is none and your problem is solved.
In other words : You issue seems to be fixed?
yeah
What exactly do you not understand about overrides?
How does that work? Am I disabling the command for that channel?
Yeah, you look;
You can disable the command either for entire channels or for roles
if you disable it for moderator role they cannot use it
but if you only enable it for them only they should be able to use it (unless your bot's code allows them to use the commands without the permission overrides)
The same for channel overrides.
You can either disable a command completely in a channel so it cannot be used by anyone in that channel or...
You enable it so that command can be used in that channel.
Now you can also make a mix of these permissions as you can make it so that in some channels the command cannot be used at all by anyone not even moderators
While in other channels you only allow it to be used by moderators.
oh, so... if I disable it like that but I am admin... I still can use the command? I think that's my confusion
Oh right, I am not sure if admins can still use the commands but it would probably make sense that they can... so yeah, you can always preview your server from a specific role angle (theres an option in the role menu of your server which allows you to do that) so you can view your server with a specific role's permissions etc. as if you were to be that role.
brb
Ok, I'll wait. Btw, that seems to be really useful, where can I find that option?
can anyone please elaborate on the difference between has_permissions and default_permissions? which one is better for lets say moderation commands, they essentially seem to be the same thing?
default_permissions can be overriden by server admins inside of the server's Integration tab. The permissions check is handled by Discord. has_permissions is an internal check handled by the library.
okay, so if i use has_permissions will the commands still be visible to only those with the permissions
yes
and for my which would be better to use part?
you're choice?
well default permissions is a bit more flexible isnt it? i dont know which one to use whether or not to let moderators of guilds manage it or not
nvm, i think its better to use default_permissions cus it is more flexible, and allows for the admins manage it better if they need to
bottom button
how do i mention a command in a slash command group?
What do you mean "in a slash command group"? Like do you want the command mention?
like this
discord.ext.commands.HelpCommand.MENTION_PATTERN
discord.ext.commands.HelpCommand.MENTION_TRANSFORMS
discord.ext.commands.MinimalHelpCommand.MENTION_PATTERN
discord.ext.commands.MinimalHelpCommand.MENTION_TRANSFORMS
discord.SlashCommand.mention
discord.ext.commands.DefaultHelpCommand.MENTION_PATTERN
discord.ext.commands.DefaultHelpCommand.MENTION_TRANSFORMS
discord.ext.bridge.BridgeSlashCommand.mention
5th one
i'll give it a go, cheers.
My question drowned I guess.
discord.ButtonStyle
discord.ButtonStyle.primary
discord.ButtonStyle.secondary
discord.ButtonStyle.success
discord.ButtonStyle.danger
discord.ButtonStyle.link
discord.ButtonStyle.blurple
discord.ButtonStyle.grey
discord.ButtonStyle.gray
discord.ButtonStyle.green
discord.ButtonStyle.red
discord.ButtonStyle.url
discord.ext.pages.Paginator.add_default_buttons
discord.ext.pages.Paginator.update_buttons
discord.Activity.buttons
i can link it myself
LOVE YOU
is there a way to wait for a button click
and then do something based on that action
you can use the callbacks 👀
I am on 2.4.1 and this works for me. My bots set up is almost identical
What does that mean
I am also on 2.4.1 And I have no idea why it doesnt work for me, I am literally stuck.
Is there a setting on the discord developer portal which messes something up?
I dont think so. Does your bot have the create guild commands permission on that server?
It has admin permissions thus...
but it doesnt make my global commands private either
one trick would be to change a command's description or smth. that would force sync the commands. maybe that could help
I think this is a flag in the invite link, not permission sorry.
I guess it has smth to do with webhooks
Wait hold on...
discord.EmojiNotFound is raised when the input is something like this: 👍
how can i work around it, i preferrably need the bot to recognise custom emojis as well as default ones?
@reaction.command(name='add', description='Add a reaction role to the active message')
@discord.option(type=discord.Emoji, name='emoji', description='Emoji to add to the active message', required=True)
@discord.option(type=discord.Role, name='role', description='Role to add once the reaction role is triggered', required=True)
async def add(
self,
ctx: discord.ApplicationContext,
emoji: discord.Emoji,
role: discord.Role
):
Are you running any code when you get this? full traceback please
Maybe my cog is not made correctly because I am using Beanie instead of the default Discord.Bot class
class developer(discord.Cog, description = 'Bot developer commands.'):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name = "test", description = "Test cmd.", debug_guilds=[1114959767715184730])
async def test(self, ctx):
await ctx.send('Approved!')
print('Approved!')
def setup(bot):
bot.add_cog(developer(bot))
?
Yes i run a code
its a ahiottp error
async with aiohttp.ClientSession() as session:
try:
commanduse = discord.Webhook.from_url```
debug_guilds cannot be set for a command. That would be guild_ids
ah right.
Well that's 1 step closer to the solution as now my command is actually made private, yet I still don't understand why it doesn't function via the Beanie subclass of Discord.Bot
@grizzled sentinel pls
If you remove the guild_ids from the command will it work?
Let's try and see
... what the f- just happened?
why does it work now?
Aaaand now it stays private ;)
reverse problem
I think your command was silently erroring due to the invalid argument or something. Then when you added a debug_guild it was not getting updated idk for sure though.
You mean when you remove debug_guilds it is not public?
Yup
I made it an empty list
completely removed it, still private
That is weird. I can reproduce that on my bot to. I wonder if there are still bugs in command registration
class RoleConfirm(discord.ui.View):
@discord.ui.button(label="Accept", row=0, style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction):
await interaction.response.send_message("Role Creation Successfully created!")
@discord.ui.button(label="Deny", row=1, style=discord.ButtonStyle.red)
async def button_callback(self, button, interaction):
await interaction.response.send_message("Role Creation Successfully denied!")
does anyone know why only the deny button is showing up
noooooooooooooooooooooooooooooooooooooooo
This is like really painful, its going to limit my amount of tests and the speed of tests, but what I find most confusing is why making debug_guilds in the Beanie (subclass) doesn't directly make them private
Pleasee????
Can you show the full error please
as if command registeration was ever bug free 😂
🥹
yeah i just tried making it row 1 and 2
and it did not work
you need to have different function names
i do, they're accept and deny
oh
"method names" to be accurate
I dont have it anymore
Restartet the bot
It says too many files open
Cant connect to discord
yk at this point I dont mind adding debug_guilds but they need to work as this is slowly starting to make me loose my mind... first cog loading / unloading and now the general command registration 🥹
And I still don't know why debug_guilds only works half, it used to work on my old bot using Discord.Bot but I am trying to organize stuff ab it more and this is going to ruin a lot
anyone has some example bot made with async sqlalchemy maybe?
async def button_callback(self, acceptbutton, interaction):
like that?
uh no
button_callback itself
you can do like
async def accept_button(...):
and
async def deny_button(...):

@grizzled sentinel and i dont find anything on google
This is the code I have used in the past. I cannot guerentee it is reliable.
try:
emoji_id = await commands.PartialEmojiConverter().convert(ctx=ctx, argument=emoji)
emoji_id = emoji_id.id
except commands.BadArgument:
emoji_id = emoji
alright, thank you.
So how do you work with it without getting a huge headache because of it?
It might be a pycord issue but, im not sure without the full traceback
Really :/
I dont need to switch commands between private and global much
Bro why pycord have such issues
but when you create a new command and you need to test it, later make it public then isn't this a pain?
Can you show the full function for the code that is erroring
I have a dev bot that is different than my prod bot.
I guess this line @grizzled sentinel
I mean what part of your code. Like on startup or on command. OR just randomly after time
Im having issues with interactions atm, after using an interaction it suddenly no longer shows up
Currently this is the code
@bot.bridge_command(aliases=['tt','travel_time', 'travel'], description="Replies with the shortest route and the travel time in between the regions")
async def traveltime(ctx, start: discord.Option(str, choices=[region for region in TravelTime.regions]), end: discord.Option(str, choices=[region for region in TravelTime.regions])):
if end == None and start == None:
await ctx.reply("Choose two regions!", view=Timeview(timeout=30))
return
await ctx.reply(await get_travel_time(start, end, TravelTime.Timegraph, "days"))```
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
yea yea
high chance you have multiple instances running
Multiple Instances?
yeah. like running the same bot (same token) actively more than once
Only running one instance from Vscode on my laptop while im testing and working on the bot
hmm try resetting the token
Random after some time
Next time you get the erro please ping me with the ENTIRE traceback. I have never seen the issue before and am unsure what would cause it without more info.
Yes i changed the code now
But if it shows again i'll ping you
took a while to find my phone but that seemingly worked?
That almost 100% means that you were accidentally running the bot multiple times. (IE in 2 different terminals on your PC) At least it works now!
Oh now that you mention it, I don't know why I am trying to make em public on my dev bot
hey is there a way to make it so that my slash command has a cooldown, and a different cooldown for 3 different roles
Does anyone have like a way only certain roles can use a slash command i cant find info on it anywhere
Slash permissions are handled via guild settings > Integrations
The old system from the bots side was removed long ago.
You can do custom checks tho.
Read the docs :)
.rtfm dynamic_cooldown
Target not found, try again and make sure to check your spelling.
yes
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...
But like its only for that one command not all of the commands in my server
role_name = "Your Role Name"
role = discord.utils.get(ctx.guild.roles, name=role_name)
if role not in ctx.author.roles:
await ctx.respond("You have to have <your role> to use this command.")
return
@slate arrow
Thanks
sure
thank you man
will you let me tip you a coffee
at some point
I don’t have that type of service set up.
yeah i mean you could set it up or i could just tip you through some app like cashapp
nah I’ll pass
Smh squid
bro could've gotten a tip
😭
you've helped me out so much i would want to show appreciation
If i help people does that count towards my volunteer hours 
if role = role:
@discord.ext.commands.dynamic_cooldown(720, type=discord.Message)
something like that?
no, it should be a function, not 720
you’d like an example?
420 
no i should figure this out myself hmm
give me a minute
oh do i need to put in the like function of my command
no?
@discord.ext.commands.dynamic_cooldown(posttrade, type=discord.Message)
thats what i meant
You did not read the docs at all
Then learn it lmfao
def dynamic_cooldown_function(message: Union[discord.Message, discord.Interaction]) ->
commands.Cooldown:
if (insert condition here):
return commands.Cooldown(1, 10)
else:
return commands.Cooldown(1, 5)
...
@commands.dynamic_cooldown(dynamic_cooldown_function, type = commands.BucketType.member)
...
yeah i mean i am trying to get better at reading them
uhh it's just type-hinting
def posttrade(message: Union[discord.Message, discord.Interaction])
if (insert condition here):
return commands.Cooldown(1, 10)
else:
return commands.Cooldown(1, 5)
...
@commands.dynamic_cooldown(posttrade, type = commands.BucketType.member)
?
what?
is that incorrect usage
like where do i put my command name
and where do i leave it as dynamic cooldown
the decorator goes above the command name. This function is just there
def posttrade(message: Union[discord.Message, discord.Interaction])
if (<ctx.user has role>):
return commands.Cooldown(1, 10)
else:
return commands.Cooldown(1, 5)
@commands.dynamic_cooldown(posttrade, type = commands.BucketType.member)
await interaction.something
this is correct? or am i just completely lost
the bucket type will be role
replace <BucketType> with a role?

@bot.slash_command()
@commands.cooldown(
if role:
1, 5,
elif role:
1, 10,
elif role:
1, 15,
commands.BucketType.user
)
async def posttrade(ctx: discord.ApplicationContext):
await ctx.respond("You can use this command again in 5 seconds.")
so in that case, that is how i would make it work?
role give different cd
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"), debug_guilds=[...], intents=intents
)
def my_cooldown(message):
if message.author.get_role(929080208148017242):
return commands.Cooldown(
3, 10
)
elif message.author.get_role(929080208148017242):
return commands.Cooldown(
2, 5
)
else:
return commands.Cooldown(
1, 10
)
@bot.slash_command()
@commands.dynamic_cooldown(my_cooldown, commands.BucketType.role)
async def dynamic(ctx: discord.ApplicationContext):
await ctx.respond("You can use this command again soon.")
# bot.run("TOKEN")
something like that
dunno if its correct tho, i dont do python
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/snekbox/user_base/lib/python3.11/site-packages/discord/init.py", line 22, in <module>
from ._version import *
File "/snekbox/user_base/lib/python3.11/site-packages/discord/_version.py", line 38, in <module>
from .utils import deprecated
File "/snekbox/user_base/lib/python3.11/site-packages/discord/utils.py", line 28, in <module>
import asyncio
File "/snekbox/user_base/lib/python3.11/site-packages/asyncio/init.py", line 21, in <module>
from .base_events import *
File "/snekbox/user_base/lib/python3.11/site-packages/asyncio/base_events.py", line 296
future = tasks.async(future, loop=self)
^^^^^
SyntaxError: invalid syntax
1
eh
xd
fuck u eval
guess what, its written in c# 
how are you a core developer
@waxen whale Kann man sich irgendwo den Code von dem @rough rose Bot anschauen?
bro is up to something
i have enough jobs at pycord 

mhh if you ask nicely
but

not sure atm, i dont really wanna publish the code
Ich dachte der wäre schon public x3
alright
cooldown is in minutes?
its in seconds
oh boy
how often / seconds
Its saying it even in the example
HEEH
def my_cooldown(message):
if message.author.get_role(1121931624670580908):
return commands.Cooldown(
3, 18000
)
elif message.author.get_role(1121860931861893190):
return commands.Cooldown(
2, 14400
)
elif message.author.get_role(1121860948370673747):
return commands.Cooldown(
2, 10800
)
else:
return commands.Cooldown(
1, 6
)
:wheeze:
aw
yeah like that in theory
idk if it works bcs i dont use python 
is the username system updated for the 2.4.1 version of pycord?
got it to work
its so sexy
it allows me to bypass the discord limitation of slowmode being based ONLY on channels and not at all on roles
when you defer
an interaction
it should look like this right?
@bot.slash_command(guild_id = server, name = "example", description = "this is for the py-cord help channel")
async def example(ctx):
await ctx.defer()
await ctx.respond("This is the example message that was deferred")
Yes
thanks
and that stays true with embeds and allat?
should i use ctx.edit?
because i'm wondering if the way i'm deferring is causing interactions to fail
Ctx.edit is to edit the message
yeah i mean i was looking at #creations and that one bot (the undo one) had a custom defer statement
and then it was edited
so i was wondering if that is the better way to do it
If you want to do that
👋 quick question: if I’m in a cog, can I still use @discord.ui.mentionable_select()? seems like I need to modify it somehow because it’s not working for me (just getting an empty view). can post the 5 lines of code in its own thread if needed, but figured it might be a direct question
actually more generally I’m not quite sure what the different pre-made selects actually do. I may be misunderstanding; my hope is that it gives me a dropdown with a list of members in the channel where my slash command was invoked, but that seems a bit unlikely 😅
turns out I was able to make it work via a view, instantiating the class, and setting the component type. I’ve noticed that I don’t always see the dropdown for some reason, I haven’t quite figured out why that is. I’ve also noticed some lag with slash command registration depending on which device I’m connected to discord with 🤔
how should i update my code to work with the new username system?
if designed correctly, no changes are needed
next release should remove the #0 iirc.
For now you could just check discrim is 0
should come within a few weeks
thanks!
@grizzled sentinel So far I have not had the error but can it be that when I query something from a json I have to close it again?
You need to wrap the code into a code block.
Is it possible to get a stream of individual people’s voice audio?
Here's the audio recording example.
Cool I’ll look into it
Does Anyone Have A Way Of Getting A Voice Cannel And Then Chnaging The Name Of It?
I Cant Find Anything Online For It
Isn’t a voice channel id the same as a text channel?
anyone know what happened to hyperlinks? the hyperlink markdown randomly stopped working about a month or so ago
Nvm, ig hyperlinks don't work anymore if the hyperlink text is a discord link, prob protection for phishing links or something
They didn't add those back

Im not sure. I think requests should be auto closed by most libs unless you are doing something weird.
They should still work in embeds
doesn't seem to for me, only works when the hyperlink text is something other than a discord link
Ahh, ok. THats too bad.
so it'll work if it's like:
but not:
or any other official discord link, not just invites
What if I just have something read out?
Im not sure. I would think it is fine, We will have to wait for the error to see the true problem.
The Error is: Cannot connect to host discord.com:443 ssl:default [Too many files opened]
That is the „main error“
Yeah, I want to see what bit of code it originates from like all the way at the top of the traceback.
Yeah if I get the error again I’ll send it to you. I removed the webhooks temporary so maybe the error is for me fixed now
@grizzled sentinel Hmm yes look at that, now 1 command is both private and public at the same time
Again I Got A Problem Where channel.send('Hi') Is Not Working
This is where it gets it
channel = bot.get_channel(int('1122134576215633930'))
and this is where it sends it: channel.send("Hi")
.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.
Pl Well Im Trying To Send A Command In a Channel After A User Presses A Button IN Their Dms
What's the error exactly?
AttributeError: 'NoneType' object has no attribute 'send'
try fetch_channel
AttributeError: 'coroutine' object has no attribute 'add_reaction'
message = ctx.interaction.original_response()
await message.add_reaction("👍") # type: ignore
await message.add_reaction("👎") # type: ignore
That's because get_channel fetches from the cache, which may or may not have your channel
ok
A method which is guaranteed to return a channel is fetch_channel
I Get This Now: TypeError: can't send non-None value to a just-started coroutine
However, you should only use fetch_channel if get_channel returns none
Have you awaited fetch_channel?
no
Yeh you should do that 💀
File "main.py", line 51
await mod_channel = bot.fetch_channel('898223478136799285')
^^^^^^^^^^^^^^^^^
SyntaxError: cannot assign to await expression here. Maybe you meant '==' instead of '='?
await it
no no no no, look you need to await mod_channel.send(f'...')
as that is the part of your async function.
You cannot await anything outside of an async function
Oh Yeah
I Still Get This: TypeError: can't send non-None value to a just-started coroutine
Wait what exactly did you do now?
just awaited the send
???
await mod_channel.send(f'The User {userforbtn} Said The Service Today Was Good')
did you change get_channel to fetch_channel?
yes
have you awaited fetch_channel?
mod_channel = bot.fetch_channel(int('898223478136799285'))
okay that's where the error is coming from, you need to await both .send and .fetch_channel
Okay
since they're both async and return a coroutine
just... (make it simpler for you)
bot.fetch_channel(898223478136799285)
dont pass in a string to then convert it to a string just pass in the int directly ;_;
File "main.py", line 58
await mod_channel = bot.fetch_channel(int('898223478136799285'))
^^^^^^^^^^^^^^^^^
SyntaxError: cannot assign to await expression here. Maybe you meant '==' instead of '='?
no
You need to await fetch_channel
Its Inside Where Awaits Can Happen
You're awaiting it the wrong way
look;
mod_channel = await bot.fetch_channel(898223478136799285)
og

damn that's some spoon-feeding right there
I've lost hope
To be clear:
When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.
We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.
Yeah I Do
I Just Havent Made A Bot For Ages
ok then do you know why we put the await before bot.fetch_channel?
and not before mod_channel?
exactly, + it then only gets awaited when the variable is called.
Youre welcome Ig but... please (this is somewhat common sense in python 💀 )
also the docs are really helpful
how would i get a message object from this? i need to add reactions to the embed.
channel: discord.TextChannel = ctx.guild.get_channel(channel_id) #type: ignore
await channel.send(embed=suggestion_embed)
You could assign the result of the send method to a variable :P
oh yeah, thats pretty silly of me. thank you.
Nahh you're fine ;)
I am not much smarter than you.
np.
so whats the User.name for then? isnt that basically a replacement for the hashtags? since yesterday everyone has pomelo users
The #0 only appears when using str(User)
Because it would do f"{user.name}#{user.discriminator}"
No, user.name is only the username without discriminator
In the new version, str(User) does something like f"{user.name} ({user.global_name})"
Assuming they migrated
ahh i do that manually right now
it doesnt really matter how u do it anyways essentially same thing
God Im Back Again, I Have 2 Buttons And I Want All Of Them To Be Disabled When One Pressed, I Copied The Docks Of:
self.disable_all_items()
await interaction.response.edit_message(view=self)
But That Doesnt Work Is Anyone Able To Help?
i get this error: AttributeError: 'serviceView' object has no attribute 'disable_all_items'
@tasks.loop(minutes=2)
async def check_live_status():
guild_id = 953632089339727953
guild = bot.get_guild(guild_id)
live_role = guild.get_role(live_role_id)
premium_role = guild.get_role(premium_role_id)
if not premium_role:
return
for member in guild.members:
if member.bot:
return
if member.activity and isinstance(member.activity, discord.Streaming):
if live_role not in member.roles:
await member.add_roles(live_role)
else:
if live_role in member.roles:
await member.remove_roles(live_role)
that should be working right?
i see no reason why it would not be working
and yet its not working
oh yeah i called the task in on ready
check_live_status.start()
aw man i can't use /eval code
elp
does check_live_status.is_running() return True
ill check
also py for member in guild.members: if member.bot: return...this ends the task immediately if it finds a bot
HAH
you're looking for continue
yep
yessah
returns true and changed it to continue
but its still not working
intents?
it exists
also i removed that part of the code and it didn't fix it
all of em
as in
not u
can you show pip list
restart your code editor
what happens when u print len(guild.members)
i've gotten that error before and all i had to do was restart vs
i mean you can just debug this with prints and check where it breaks
because there's several places there the task could fail but we can't tell
@tasks.loop(minutes=2)
async def check_live_status():
guild_id = 953632089339727953
guild = bot.get_guild(guild_id)
live_role = guild.get_role(live_role_id)
premium_role = guild.get_role(premium_role_id)
for member in guild.members:
if member.bot:
continue
if member.activity and isinstance(member.activity, discord.Streaming):
if live_role not in member.roles:
await member.add_roles(live_role)
else:
if live_role in member.roles:
await member.remove_roles(live_role)
current code 
still broken 
delete it
see where it stops printing
||you could rather use events?||
oh yeah that works too
well that would be much better than a task loop
that doesnt have py-cord 
yeah i dont know why i uh yeah

wrong python version ig
which python version do you want to use?
3.11 ?
then do py -3.11 -m pip list
live_role_id = 1122209929659428916
premium_role_id = 1121860722054414397
@bot.listen()
async def on_member_update(before, after):
guild = after.guild
live_role = guild.get_role(live_role_id)
premium_role = guild.get_role(premium_role_id)
if premium_role not in after.roles:
return
if not live_role:
return
if after.activity and isinstance(after.activity, discord.Streaming):
if live_role not in after.roles:
await after.add_roles(live_role)
else:
if live_role in after.roles:
await after.remove_roles(live_role)
thank you for telling me that i am stupid 
that's much better
well, reinstall python and select the py launcher while installing
does anyone know how to fix this? it executes the desired function but still responds with this.
You're not responding
do i need to do ctx.respond or smth?
well i used ctx.send in another code that did the same shit, works with respond now tho, thx
btw can i somehow set that to be viewable by me only?
ephemeral=True
thanks!
async def modal_response(message, interaction: discord.Interaction):
doc = await self.collection.find_one({"guild_id": guild_id})
if doc:
await self.collection.update_one({"guild_id": doc["guild_id"]}, {"$set": {"message": message}})
embed = embeds.success("The welcome message has been successfully changed.")
await ctx.respond(embed=embed)
await interaction.response.send_message("The welcome message has been successfully changed.", ephemeral=True)
return
class Modal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.message_input = discord.ui.InputText(label="Message", style=discord.InputTextStyle.paragraph)
async def callback(self, interaction: discord.Interaction):
message = self.message_input.value
await modal_response(message, interaction)
class MyView(discord.ui.View):
@discord.ui.button(label="Change", style=discord.ButtonStyle.primary)
async def button_callback(self, interaction: discord.Interaction):
await interaction.response.send_modal(Modal(title="Set welcome message"))
await ctx.respond(embed=response_embed, view=MyView())
TypeError: WelcomeModule.message.<locals>.MyView.button_callback() takes 2 positional arguments but 3 were given
discord ui confused me before, but now im even more confused
@grizzled sentinel
(self, button, interaction) are the parameters for adding buttons to a view using the decorator
that did something but now i get the error
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body | In data.components: Must be between 1 and 5 in length.
huh can you show the code wheen you did that
await interaction.response.send_modal(Modal(title="Set welcome message"))
this is the line that errors.
.rtfm modal.add
you need to add the input text using that
can i check in an if statement whether or not the method was called by a command?
Hello guys, im trying to run a discord bot on docker, the bot has to access a database in order to work, but when is running inside the docker container it cannot access the database, any help?
Code: https://paste.gg/p/anonymous/9c5d2686ae29454ebd91b48a1a5cade1
Error: https://paste.gg/p/anonymous/6b5d568a2bd148df8d8330bbd21db143
Requirements.txt:
discord.py==2.3.0
aiohttp==3.8.4
mysql-connector-python==8.0.33
bot token redacted for privacy (?)
also in ur command ur vulnerable to sql injection
how can I fix that?
is there an alternative to ctx.respond when using slash commands? in some cases it throws me 404s even though it works perfect in other methods
use parametrised queries

