#General Help
1 messages · Page 9 of 1
uhh can you elaborate
so yk?
well
if you have the role ID, you can do <@&roleid>
if you have a role object, you can do role.mention
Ahhh so the bot needs to return the allowed mentions in the response object. And the bot can only mention the roles that are present in the returned list.
Thank you for the hint @south ermine
set
allowed_mentions=AllowedMentions.all() # to allow everything.
i tried overriding it but it wouldn't work
lmao
ah okay and this interaction.data["values"] can i make it look like the picture?
no it doesnt
what? I was talking to Mihito
data["values"] is a list of values selected from the dropdown, it's up to you to parse that list
but it only works when this is enabled.
Because the webhook permissions dont care about the permissions the bot have and only take @everyone
thanks
all good
so you can mention the role with allowed_mentions and that setting in ctx.respond?
so and how i can remove the ['sak, askas, asjaks'] that you only sak, askas, asjaks have?
it's a list
just iterate through it
or if you want them all as one string, use .join
interaction.join['values']?
no or?
no string joining
you get the character you want to join all the items together with
e.g. if you want to join everything with a /, you'd do "/".join(list)
so i create a list or a string well there it is list and in list come my string ?
so let's say you have a list a = ["b", "c", "d"] and you want to make that list a into a single string "b, c, d"
you would print ", ".join(a)
so?
a = interaction.data['values']
await interaction.response.send_message(f"{', '.join(a)}")
yeah you got it
yayy thank you 
How can I get role by name?
try discord.utils.get
https://docs.pycord.dev/en/master/api.html#discord.utils.get
what is the difference between discord.Role and discord.role.Role ?
they're essentially the same
also you can stop tagging @ here
it doesn't work
discord.role refers to the role.py file
Oh- 😅
while discord.role.Role is the Role class inside that file
which is then shortened to discord.Role
guild = ctx.guild role = discord.utils.get(guild.roles,name=role)
in a certain function this is working, and returns None in the other.
are you using the exact same name? it's case sensitive
can you show the relevant code around it
DM?
it can be here
Okay.
I'll tag you.
any ideas why this wont work?
...read your error?
yeah. i also have the file open so how it doesnt exist idk
Is there a way to prevent slash commands from running until my bot is fully ready? I have some final prep code that completes after on_ready
maybe use the full path instead
make the path a variable then use that everywhere
okie'
having an issue where i can't detect attachments after trying to move this to a cog, is there anything visibly wrong?
@commands.Cog.listener()
async def on_message(self, message):
if message.attachments:
await message.channel.send("attachment")
everything else about the cog does work as intended, just this bit is weird
and yes it does detect the message, just the attachments is funky
guys help
i want the bot to give me a random link
for now its ok
because i have all of them
but
do you have message content intents enabled?
i want to the result of random.choice shows up the name and the image of the link
instead to open the link
but if i do random.choice for the links, name and photos
it will mix everything
help
yep
all intents enabled, this bot’s staying on like 2-3 servers ever
Can you clarify
sorry
but i think i cant explain more clear
idk
will give an example with code
def mctextures():
test1 = ["link", "name", "image file"]
test2 = ["link", "name", "image file"]
random.choice(mctextures)
result = ["??????", "??????", "??????"]
await ctx.respond(f"New texture for minecraft generated!\n\n{result[0]}\n{result[1]}", file=result[2])
see
what do i put in result
i want to make random.choice give me 3 answers per randomization
the link, name and image file
help
This definitely makes no sense
Rule 1
So you want to create a random "texture"
This means a random name, link and file from a list
So do u want help with random or pycord
yes
Then create a list for names, one for links and another one for the files.
Then choice.random each one to get the result
i cant think
i tried it but its totally randomized
Or if the link name and textures gotta go together then maybe nested lists?
for example name1, link1, img1
That's supposed to be random
Use nested lists
The texture itself? So basically you just give out a random set texture
the result will be totally randomized
YES
i want the name have its properly link and img
oh ok
my brain
Yeah that
OH
it is that simple?
wait can i make a list inside a list
and give it a name?
bruh ty
You work with indexes
k
If thing same thing is inside the same thing
It's called nested _____
Ok discord doesn't let underscores apparently
lol
Been testing the waters with localisation, and running into some frustration. From my understanding, there is currently no localisation for slash command groups, but I can still define localisations for the command name.
I've tested this with my discord set to Italian, and my friend in Italy is getting the same issue. It simply does not work. The best we can get is a "detection" as seen in the screenshot.
This is my command definition, and I know for a fact that I'm getting valid dictionaries for the arguments. I have also tried passing in dictionaries directly with no luck.
I've even tried this with a straightforward @slash_command(name=view) and still no dice as seen in the second screenshot.
Any idea what is wrong here?
@profile.command(name="view",
name_localizations=loc.command_names("profile", "view"),
description_localizations=loc.command_descriptions("profile", "view"))
@option("player", discord.Member,
description="The user who plays this character",
name_localizations=loc.option_names("profile", "view", "player"),
description_localizations=loc.option_descriptions("profile", "view", "player"))
@option("name", str,
description="Character's display name (usually given name)",
name_localizations=loc.option_names("profile", "view", "name"),
description_localizations=loc.option_descriptions("profile", "view", "name"))
@option("visible", bool, default=False,
description="Set to 'True' for a permanent, visible response.",
name_localizations=loc.common("visible-name"),
description_localizations=loc.common("visible-desc"))
async def profile_view(self, ctx, player, name, visible):
"""View a character's profile"""
try with this enabled please
omg yes it works perfectly now thank you
np
Any idea if there are plans to allow command group localisation?
not the slightest clue tbh
You could ask here
touching up on the examples in the repository right now, can bridge commands not have their own error handlers? or is there a different way to do it than the standard command_name.error?
I'm trying to send an embed to channel like this: await channel.interaction.response.send_modal(modal) The error is : AttributeError: 'TextChannel' object has no attribute 'interaction'
Slash command
So I just remove the interaction.response?
yeah, text channels dont have an interaction attribute, try using the context you're given in a slash command
If I use ctx how would I send it to a channel?
Wouldn't I have to use channel.send()?
nope, the context object already knows what channel to direct it to
are you wanting to send to a different channel?
yes
I've tried just using a regular command but then the modal doesn't work.
@client.command()
wait sending a modal in a different channel? im not sure i understand
No
if you're wanting to send a message in a different channel then just use textchannel.send()
Sending an embed to a different channel.
same thing, TextChannel.send() has an embed parameter
If I do that it returns random text and not the embed.
<main.RequestModal object at 0x00000280D79BA850>
yeah, thats the object, what are you trying to access?
hey so i was wondering how you get the guild that the event on_voice_state_update happned in im really confused i tried before.guild but it says its a voiceState
member.guild should work
o ok
Ex: You use the slash command /request
A modal opens you enter things then click submit/ok and the info goes into an embed and gets sent to a different channel
assuming you only have one InputText in the Modal:
await text_channel_object.send(embed=discord.Embed(content=modal_object.children[0].value))
I have 4
the children attribute is zero-indexed, so if you want the value of the fourth InputText then do modal.children[3].value
The embed is in the modals callback
then use self instead of modal or modal_object
whatever references the modal works
async def callback(self, member: discord.Member, interaction: discord.Interaction):
embed discord.Embed(title="e")
await interaction.response.send_message(embed=embed)
that would work (assuming you put an = between embed and discord.Embed) for sending it to the same channel.
do you have the channel object?
channel = client.get_channel(randomnumber)?
assuming client is available in the callback's scope yes
The modal is in a class and the slash cmd is not
you can try that, if it doesn't work then you can definitely access client via interaction.client
This is my current code.
The second await in the slash cmd is what I want to send to a different channel
await channel.send(embed=embed) should work then, try?
also, ctx.interaction.response.modal won't work as far as I'm concerned, replace modal with send_modal
did you try it?
Since the embed variable is declared inside the Modal class/callback function
is there any particular reason you aren't sending the embed from inside the modal callback?
It is sending from inside the modal callback technically, wouldn't I need the command to send the embed?
embed not defined.
The embed is inside the callback?
move all of your embeds and all of your sending functionality to the callback
in the screenshot you sent, embed2 is defined within the slash command, something the modal can't access outright
you're trying to send embed2 to a separate channel, correct?
the one in the modal callback
yes
I need that embed sent to a different channel.
And the second embed to be sent to the channel the message was called.
channel = interaction.client.get_channel(id_here)
await channel.send(embed=embed)
^ inside of the callback
I can't tell if it worked or not, since now the modal is getting an error "Something is wrong. Please try again."
TypeError: MyModal.callback() missing 1 required positional argument: 'interaction'
according to your screenshot, remove the member argument from your modal callback
the callback only takes self and interaction
Hi guys, I would like to run a command every time someone says something in a server. I believe this would be a @bot.event. What's the syntax for this?
use on_message
Ah okay, thank you!
Would the decorator be @client.event or @bot.event? the documentation is a bit weird
it'll be the name of your bot variable
Ah okay, thank you!
Sorry once again, I typed this
@bot.event
async def on_message(message):
print(message)
and got this error
AttributeError: 'TextChannel' object has no attribute 'news'
what version/github commit are you on?
I am on py-cord 2.0.0rc1
What's weirder is that I changed print(message) to print(message.content) and this time it didnt crash but it just posted empty lines in the console lololxd
pretty sure this showed up with rc1 for some reason, its fixed in the latest github commit afaik
Oh okok
It works, but the form doesn't go away after submitted and I get an error discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: InteractionResponded: This interaction has already been responded to before
That should be okay, I just need the on_message thing to get the user id. Thank you once again for everything!
np
The embed goes to the channel, but the form doesn't get removed, and gets errored.
send your code please
Can I send via dms?
sure
Can I check how many subcommands can we have in a slash command group?
gifsem = "**bruh**\n**bye**\n**cry**\n**killgif**\n**laugh**\n**hug**\n**slap**\n**pat**\n**punch**"
view = View()
view.add_item(select)
if infotext.strip() == "":
overem.set_footer(icon_url=ctx.author.avatar,text=f"Version: {ver} || View this in DMs by typing: <help dm>")
embed = await ctx.send(embed=overem,view=view)
if infotext.lower().strip() == "dm":
try:
overem.set_footer(icon_url=ctx.author.avatar,text=f"StraDot commands || Version: {ver}")
embed = await ctx.author.send(embed=overem,view=view)
await ctx.message.add_reaction(':white_check_mark:')
except Exception as e:
await ctx.reply(f":negative_squared_cross_mark: An Error occurred!\n{e}")
await ctx.message.add_reaction(':negative_squared_cross_mark:')
async def callback(interaction):
if str(interaction.user) == str(ctx.author):
if select.values[0] == "Overview":
await embed.edit(embed=overem)
if select.values[0] == "Utilities":
await embed.edit(embed=utilityem)
if select.values[0] == "Fun":
await embed.edit(embed=funem)
if select.values[0] == "Gifs":
await embed.edit(embed=gifsem)
if select.values[0] == "Economy":
await embed.edit(embed=economyem)
if select.values[0] == "All Commands":
await embed.edit(embed=allcommandsem)
else:
await interaction.response.send_message("This help command isn't for you.", ephemeral=True)
select.callback = callback
I'm trying to make a dropdown help menu command. while all other menus work except for -
if select.values[0] == "Gifs":
await embed.edit(embed=gifsem)
And i get this weird error
pls help
I tried a quick google search but whats the max characters for a role?
I only found that you can only have 250 roles in a server
It does, but doesn't for me so I just used this method and it works
Yeah but you shouldn't need to do that, can you open a ticket
gt?
how can i get the user object | ID from username#discrim
can MemberConverter be used? and how?
how can i prevent on_message to run if the message is a slash command
I was trying to add cooldowns to my slash command. I was working fine till a few hours ago. Now, when I'm checking the errors (using cogs) from the following code, It didn't do anything.
@commands.Cog.listener()
async def on_application_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(error)
So just to check, I did print(type(error)), and it printed this <class discord.errors.ApplicationCommandInvokeError>. Shouldn't it be an instance of commands.CommandOnCooldown?
its also an instance of ApplicationCommandInvokeError
you may need to grab the original error via the original attribute
error.original?
yep
ok thanks
I am looking for guidance about using HTTPServer with a bot. Anyone have experience with that?
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 1069, in get_gateway
data = await self.request(Route('GET', '/gateway'))
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 275, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being rate limited.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 569, in connect
self.ws = await asyncio.wait_for(coro, timeout=60.0)
File "/usr/lib/python3.8/asyncio/tasks.py", line 494, in wait_for
return fut.result()
File "/usr/local/lib/python3.8/dist-packages/discord/gateway.py", line 305, in from_client
gateway = gateway or await client.http.get_gateway()
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 1071, in get_gateway
raise GatewayNotFound() from exc
discord.errors.GatewayNotFound: The gateway to connect to discord was not found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/fatherbot/FatherBot.py", line 134, in <module>
bot.run(TOKEN)
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 729, in run
return future.result()
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 708, in runner
await self.start(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 672, in start
await self.connect(reconnect=reconnect)
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 618, in connect
ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id)
AttributeError: 'NoneType' object has no attribute 'sequence'
hi, today my bot is shutdown and I can't start it anymore because of this error
Your bot seems to be ratelimited
What features does your bot have?
Seems you have some features causing many api requests
this problem appeared today, before that my bot was working fine. I didn't change anything in the code or do anything that would cause an increase in API requests. At first I thought that maybe the problem is in pycord, but now I noticed that from my pc my bot starts normally, but from the virtual machine I get this error. I don't understand what it's about
Hmm then the IP may got ratelimited or sth, you are using a normal vps provider to host your bot on a vps or is it sth like heroku/replit?
I use normal vps provider to host my bot on a vps. I have already waited about 10 min, but I still get this error
I believe some rate limits can last 24 hours :/
Is it possible to check if the author of a command is able to see a specific other slash command?
The can_run function returns true even if the author does not have the @default_permission permission.
for command in extension.walk_commands():
if await command.can_run(ctx) is True:
embed.add_field(name=command.qualified_name, value="None", inline=False)
await ctx.respond(embed=embed)
Is it possible to invoke a slash command group name
Prefix commands you can invoke the group on its own without any subcommands
discord limitation, you may not
mad
Is there a better way of getting the timestamp of the last message a guild member sent than searching channel history?
Hey yall, For some reason, the options in slash commands that are inside a cog are not getting registered
The slash command is registered but the options are not working
class Youtube(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(
name="download",
guild_ids=guildIDs,
description="Download a YT video")
async def download(
ctx: discord.ApplicationContext,
link: discord.Option(str, "The video you want to download!") # WHY WONT YOU WORK BRUH
):
await interaction.response.send_message("this is a test")
def setup(bot):
bot.add_cog(Youtube(bot))```
Could someone please guide me on how to fix this error
class MyModal(Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(InputText(label="Short Input", placeholder="Placeholder Test"))
self.add_item(
InputText(
label="Longer Input",
value="Longer Value\nSuper Long Value",
style=discord.InputTextStyle.long,
)
)``` how do i make it so `Short Input` can only be less than 150 characters
nvm got it
how'd you do it?
ah xD
yeah
Hi! Can I somehow detect when a user cancels the Modal Dialog interaction?
nope, there's no event for this
Aww, that's sad. Thanks for the quick response!
can_run is only for @commands.check decorators, it doesn't operate with default_member_permissions or the permissions set in the integrations tab
Well what’s the error, I already see what’s wrong but you need to find the error in your console.
So I have Option(discord.TextChannel) in one of my slash commands and I can’t select announcement channels, how do I select announcement channels or have them appear in the options?
Announcement channels are not channels at all iirc.
Hello, because I get this error:
discord\voice_client.py", line 905, in send_audio_packet
encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME)
AttributeError: '_MissingSentinel' object has no attribute 'encode'
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: '_MissingSentinel' object has no attribute 'encode'
I add ctx.voice_client.encoder = discord.opus.Encoder() but then I get:
ctx.voice_client.encoder = discord.opus.Encoder()
AttributeError: 'NoneType' object has no attribute 'encoder'
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'encoder'
Thanks for reading if you did. I know its so long... I may create a post here maybe?
Hello!
Does anyone know how I add the privileged members gateway intent to discord.Intents.default() without adding the other privileged intents? (aka not using discord.Intents.all())?
Thanks in advance!
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(..., intents=intents)
Awesome, thank you!
it's really not that complicated though... Could be one google search.
I was passing them as kwargs
but they're just attributes
Yeah my bad, Thanks for the help though!
np 🙂
mhmMm..
Ignoring exception in command perms:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 122, in wrapped
ret = await coro(arg)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 825, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\[Teststation].py", line 28, in perms
if ctx.me.permissions_in(939551193145950258).send_messages:
AttributeError: 'Member' object has no attribute 'permissions_in'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\bot.py", line 1098, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 331, in invoke
await injected(ctx)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 128, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Member' object has no attribute 'permissions_in'
@slash_command()
async def perms(self, ctx):
if ctx.me.permissions_in(939551193145950258).send_messages:
await ctx.respond(f"Mir fehlen die rechte: send_messages")
else:
await ctx.respond(f"Erfolgreich!")
Read the error, it doesn’t have an attribute to that.
yeah i know but how i can fix that?
Try using ctx.guild.permissions_for(ctx.me).send_messages
okay
no..
Ignoring exception in command perms:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 122, in wrapped
ret = await coro(arg)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 825, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\[Teststation].py", line 27, in perms
if ctx.guild.permissions_for(ctx.me).send_messages:
AttributeError: 'Guild' object has no attribute 'permissions_for'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\bot.py", line 1098, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 331, in invoke
await injected(ctx)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 128, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Guild' object has no attribute 'permissions_for'
@slash_command()
async def perms(self, ctx):
if ctx.guild.permissions_for(ctx.me).send_messages:
await ctx.respond(f"Mir fehlen die rechte: send_messages")
else:
await ctx.respond(f"Erfolgreich!")
Huh
Try ctx.me.guild_permissions.send_messages
That should work
yeah no error but the bot say he has not permissions but he has administrator?
or did I mix up the messages?
In my code an ARRAY consists 2 arrays say array 1 and array 2
Array contais array1 and array 2
So its reads ARRAY and checks if...else condition statement on array1 and then it checks the conditions on array2 this results in an error because both array satisfy atleast one of the conditions and it results in me getting output for 2 satisfied conditions
So can i do it like it reads both the arrays and then check the condition?
show us the statusfunction please
Try doing ctx.channel.permissions_for(ctx.me).send_messages
Yeah but he send ,,Erfolgreich" in englisch it says it works but dont working. so look my code:
@slash_command()
async def perms(self, ctx, member: discord.Member):
if ctx.channel.permissions_for(ctx.me).ban_members:
await ctx.respond(f"Mir fehlen die rechte: send_messages", ephemeral=True)
else:
await ctx.respond(f"Erfolgreich!")
await member.ban(reason="Test")
and the error when the member ban:
Ignoring exception in command perms:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 122, in wrapped
ret = await coro(arg)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 825, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\[Teststation].py", line 31, in perms
await member.ban(reason="Test")
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\member.py", line 665, in ban
await self.guild.ban(self, reason=reason, delete_message_days=delete_message_days)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\guild.py", line 2768, in ban
await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\bot.py", line 1098, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 331, in invoke
await injected(ctx)
File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\commands\core.py", line 128, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
when you dont know what i mean say it 🙂
@cog_ext.cog_slash(name=status_name, description=status_description)
async def status(ctx):
guild = ctx.guild.id
results = collection.find_one({"_id": guild})
if results == None:
await ctx.send("Primeiro sete um ip em /setarip!")
else:
ip = results["ip"]
port = results["port"]
ip = str(ip)
port = int(port)
r = requests.get('https://mtasa.com/api/', stream=True)
r = r.json()
for i in r:
if i['ip'] == ip and i['port'] == port:
name = i['name']
Ip = i['ip']
Players = i['players']
Maxplayers = i["maxplayers"]
Version = i['version']
Port = str(i['port'])
ipfinal = "mtasa://" + Ip + ":" + Port
#embed
await ctx.send(embed=embed)
here
is this function inside a class?
yes
then you need to add self as the first argument
ok
so it would be def status(self, ctx)
ok thanks
..
can someone help me with this error pls:
ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
have you ensured that youve done both?
youve still gotta provide it
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(bouton_rules())
self.add_view(bouton_jeu())
self.add_view(bouton_salon())
self.add_view(bouton_esgi())
self.add_view(bouton_dev())
self.add_view(bouton_alt_ou_init())
self.add_view(menu_annee())
self.add_view(menu_spe())
self.persistent_views_added = True
on my on ready
and
why do you have a view for each button? thats the most ridiculous thing to do
class menu_annee(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
unless you actually need to do such a thing
ah, makes sense then
i do not
😦
and wucik wuestion
quick
why there is error on ishe2 and popout2?
ok this was stupid
but still need help on my thread 😦
if someone can help me
i copied the help message commands from the docs
but the help command only shows up as a prefix command
not a slash command
how do i make it show up as a slash command
How can I create a loop that always executes at midnight german time even if the time changes (twice in a year)?
can you show me your command pls?
works best if the machine running your bot uses german time (e.g. is located in germany)
if not, you have to change the used timezone. Google will help you with that 😉
I thought using the @loop annotation but I´ll look into it
yes, the @tasks.loop decorator
I have a slash command like this
async def delete(
self,
ctx: discord.ApplicationContext,
channel: discord.TextChannel,
message_id: int,
):
message = await channel.fetch_message(message_id)
await message.delete()
but when I want to specify the message_id it says that I must specify a valid integer.
discord.Option(int, "description") didn't work either. So how can I specify a channel/user/message/etc. id?
afaik the message shouldnt be possible. I only used channel as option so far and the user should work (I dont know if in Pycord but in other Discord Bots it does)
so it just doesn't work with messages? That would be so dumb...
There has to be a way to specify an integer as long as a channel id.
well you have to tell the user to give you the message id.
yes... and? That's what I'm doing...
but when I want to specify the message_id it says that I must specify a valid integer.
rly?
beacause its too long for an int in discords eye
discord only allows a string to be x long and its too short
should be 2 billion and a bit
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
2.14...? Is an INT.
but the strange thing is that I can actually specify more that those 2.14 billion but just not enough for the whole id...
yes. Its a limit on discord site. If you tell Discord to use an integer it will take the javascript integer length and thats too short for the snowflake format Discord is using
wdym with "blocking it"? You could just replace it with nothing.
like `string.replace("INV CHAR", "")
.strip()
wow that seems so dumb xD But maybe I just don't get the bigger picture xD
does it also strip invisible characters or only space?
invisible 
yeah I would love to have the snowflake type in an option
it would make a lot of work for me much more simple
Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!
its the one linked just under this
exact same cause i wanted to see how it looks
but noticed the help command doesnt show up as a slash command whereas carl bot's does
did u put a guild_id in the command?
where
you dont specify guild_id here?
its the global help command class im inheriting
yeah just for testing. If you want to use it global it may take an hour or so to register the command
no youre not understanding me
Quick question, what is the event for a user's status changing?
me neither 😄
on_presence_update
if you're looking for an event and can't think of the right name just look in the event list.
https://docs.pycord.dev/en/master/api.html#discord-api-events
@slash_command(guild_ids=[801646969676234782])
@option(name="tests", type=str, description="This commands is testing this exact thing", default="a")
async def test(self, ctx: discord.ApplicationContext, tests: str):
await ctx.respond(f"{tests} hm")```
so i have this command that should make the bot send what the user puts but there is no where to put the `tests` value
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
isnt @option just the decorator version of discord.Option?
option being import from discord
async def predict(ctx, project : str , prediction : float):
await ctx.respond(f"{project} {prediction}")```
I want to have a list of string that the user can choose from in the project. And it shouldn't accept any other values. Any method to do that? I know it has been answered just above but any way to prevent users from putting in new values.
nope still cant input the value
same problem as before with discord not showing the input field
@slow dome any idea how do I ?
examples/app_commands/slash_options.py lines 14 to 33
@bot.slash_command(guild_ids=[...])
@option("name", description="Enter your name")
@option("gender", description="Choose your gender", choices=["Male", "Female", "Other"])
@option(
"age",
description="Enter your age",
min_value=1,
max_value=99,
default=18,
# passing the default value makes an argument optional
# you also can create optional argument using:
# age: Option(int, "Enter your age") = 18
)
async def hello(
ctx: discord.ApplicationContext,
name: str,
gender: str,
age: str,
):
await ctx.respond(f"Hello {name}! Your gender is {gender} and you are {age} years old.")```
have you tried USING the command?
yes
and?
it just returns this
responds*
also its in a cog
if that changes anything
idk
my other slash commands that use @option work fine
one is outside a cog
the other one is in the same cog
could you try using debug_guilds in bot constructor instead of guild_ids
ok
it worked when i changed guild_ids in @slash_command to debug_guilds
did that just register it as a global commands or something?
or is it the same as guild_ids
uh, you were supposed to remove guild_ids. but ig now it's a global command
debug_guilds should be passed into the bot
i tried that
and it didnt work
when i changed it back to that
it seems to work fine
tho why wasnt i able to specify tests field and the command was made?
what could be the reason for not being able to see my commands in dms
slash commands
it was the debug guilds
How can I get the content of a message as escaped string?
E.g. [Hi ||this is|| me] becomes [*Hi* ||this is|| _me_]
got it, using discord.utils.escape_markdown
how can i tell if a message or channel is in a dm
what could be causing that error while removing a role. Yes the bot has manager role permission, and yes the role of the bot is higher than the one to remove (I verified and otherwise it will give Missing permission error and not Missing Access like I get)
here are my bot permission
and the bot permission in the server
and here is the code :
what's the bots role hierarchy?
if it's not high enough discord won't allow it
like if role x is below role y, role x cannot add a role to role y
The role of the bot is higher than the role i am trying to remove
The bot even check for it when running commands
And like I said it would give Missing permission exception
I get Missing access( the only thing i could found on this is when their is not application.command, but in my case it does not apply, because the bot have it)
how can i get the user object | ID from username#discrim
can MemberConverter be used? and how?
Hi, how to have the id of someone that get mention on a command pls?
message.mentions[0].id
where do I have to place it pls?
@bot.command()
async def ratio(ctx, message, raison=""):
mention = message.mentions[0].id
if raison == "":
await ctx.send(f"EH {mention}! **RATIO**! ")
elif raison != "":
await ctx.send(f"EH {mention}! **RATIO** parce que {raison}!")
idk why it's not working
can someone help me work on a hp system? dm me for the code so far
What doesn't work?
Traceback (most recent call last):
File "C:\Users\celia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\celia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\celia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'mentions'
It needs to be ctx.message
b!rtfm pyc discord.Member
hm
First one ^ shows all the attributes
ty mazte!
how can i get the user object | ID from username#discrim
can MemberConverter be used? and how?
@south ermine how do i pass ctx in listener
message is a Message object and i cant figure out the Context object out this
you can get the user with message.author
also Context is only used for prefixed commands
nvm found it, ctx = await bot.get_context(message) worked
nah memberconverter asked for context object only
what does it do anyway?
this
brrr
dont need author
they are different
ok youre talking non-sense (to me) and will now cease to help further
lmao what non sense?
now let em explain you
i want for embed[0].author.name
not author of message
but you can easily just access display_name and discriminator of author though?
yes
but i want id
message.author.id????
nah not working
how so?
that is a string
this thing is added in author of embed
BRUH I DONT WANT THAT, see both are different
||ok youre talking non-sense (to me)||
ok fuck this im not helping you on this
this is just a waste of time for both of us
the pblm was alr solved, you are rather wasting time
dont ping me regarding this again
Error handling in bridge commands?
I tried the normal way it isn't working with bridge commands
AttributeError: 'BridgeCommand' object has no attribute 'error'
just discussed in #discussion and it's a missing feature, I'll be opening an issue sometime today
any tips to edit an embed with buttons? Only want to change 1 value, but cant seem to figure out how
Well in the button callback, get the message, get the embed from it, edit the embed, edit the message to the new embed...
is there any easy way to "get the embed"
i saw you could get elements, but it wouldnt work if there was an icon iirc
why do i get discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix="e!", intents=discord.Intents.all(
), debug_guilds=[819224446727487518, 707278018405466253])
lst = [f for f in os.listdir(
"cogs/") if os.path.isfile(os.path.join("cogs/", f))]
no_py = [s.replace('.py', '') for s in lst]
startup_extensions = ["cogs." + no_py for no_py in no_py]
try:
for cogs in startup_extensions:
client.load_extension(cogs) # Startup all cogs
print(f"Loaded {cogs}")
except Exception as getgood:
print(getgood)
client.run("TOKEN")```
this is my code
If you have the message object that contains the embed you can just do embed = message.embeds[0] or so
hmm will try, thanks
You replaced the "TOKEN" with an actual token?
isnt the 405 error just something with old version
i get it too, but doesnt do anything - still runs fine
Just a short question
I have a command up that has a ctx.defer() in it. There is also an error handling function because I am working with another server and the bot interacting with it. When it fails I only want to abort the ctx.defer() and display the usual "The application did not respond in time" discord error. is there a way to do this?
yeah 405 is an old error caused by perms v2, it's fixed in the newest release rc1
ofc
Show us your code pls
is there a max for the delete_after arg?
I dont think so, because that is stored within your bot. The more you have the slower your bot would be.
quick question, what type of Context is the ctx in a slash command?
async def(self, ctx)```
discord.ApplicationContext
discord.ApplicationContext.bot
discord.ApplicationContext.cog
discord.ApplicationContext.command
discord.ApplicationContext.delete
discord.ApplicationContext.interaction
discord.ApplicationContext.invoke
discord.ApplicationContext.respond
discord.ApplicationContext.selected_options
discord.ApplicationContext.send_modal
danke.
how do I take in input an indefinite number of arguments in my slash command ?
i want the user to pass a list of roles at the size he want
put *args as argument.
args will then be a list holding the roles
But I'm sure there is a more elegant way of doing what you want.
i tried but it don't seem to work on the discord client
it only ask for one role
then show your code pls
@admin.command(name="définir_rôle",description="Défini le rôle à donner")
async def admin_define_role(ctx, *role: discord.Role):
client-side only allow one role
i also tried ctx, * , role
How do I turn Message attachments into Webhook attachments?
there is absolutely no need to ask your question in 2 different threads...
My question's thread contains more info and tracebacks, I just asked one simplified question here that would help me answer my own questions
Ok, so I can't find a solution either. Please ping me, if you found a solution, I'm also interested in the solution.
no problem !
but i start to think that it's not possible :/
Just a quick idea, not 100% certain if this works but you could get the user to type the roles as str and then get them that way
yeah but that's nasty
yep :/
i want to make the most user-friendly interface possible
because this way there is no autocompletion
well, most user friendly would probably be a reaction role...
Can Modals only contain text fields?
How do I respond to an interaction, without actually sending a message? (If at all possible)
you can use the ephemeral option to make the message only visible for the user
or send it with the delete_after=0 argument
Yeah I know, but I don't want the interaction itself to send a message, not even a blink of one.
Something else than the interaction is sending the message, which has no access to that interaction.
I found yesterday a little workaround for this.
try:
await ctx.respond("")
except:
pass
but that's probably not the best practise...
@vagrant mortar
but there will alway be a little blink when invoking the command...
and that's what I want to avoid
I don't think that's possible
I have a command that sends an modal and a ephemeral response. In the modal callback I want to edit the response message, how would I do that?
how can i define a list of choices with current data
for exemple a list of server roles
it seem that can oly be defined before the bot connect to the api
there’s autocomplete and discord.Role as an option
Autocomplete is a list that can be generated dynamically
wait how do i tag a user on embeds again?
i did ctx.author.mention its just showing the <@. . .> thingy
i believe tags dont work in titles
didnt work on embeds author either
probably only works in descriptions...
bump
can i ask when reload_extension the outsite class will also reload?
how to rearrange button order
i basically want 3 buttons of mine to be in the last row and not in the upper row
rearrange them in the view? idk
how is that done
I mean in the code
i need the green ones to start on a new line
oh ok. I actually don't know but I think that's not possible...
you could just add 2 spaceholder buttons...
how do dank memer do it then
there got to be a way
good question xD
maybe sending multiple messages with only 3 buttons?
As I said I can only speculate xD
its a single message my guy
ok then sorry for stealing your time xD
I'm out of suggestions.
no problem its ok someone else can help 😃 appreciate ur efforts
use the row argument
Represents a UI button.
.. versionadded:: 2.0
Parameters
------------
style: :class:`discord.ButtonStyle`
The style of the button.
custom_id: Optional[:class:`str`]
The ID of the button that gets received during an interaction.
If this button is for a URL, it does not have a custom ID.
url: Optional[:class:`str`]
The URL this button sends you to.
disabled: :class:`bool`
Whether the button is disabled or not.
label: Optional[:class:`str`]
The label of the button, if any.
emoji: Optional[Union[:class:`.PartialEmoji`, :class:`.Emoji`, :class:`str`]]
The emoji of the button, if available.
row: Optional[:class:`int`]
The relative row this button belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd
like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed).```
or use ActionRow objects
I'm trying to make my bot press reactions for every new message in thread. Am I getting something wrong?
@client.event
async def on_thread_message(message):
if message.channel.id == 978369141801119795:
await message.add_reaction("\N{skull}")
await message.add_reaction("\N{eye}")
do you get any errors?
the \N{skull} and \N{eye} don't seem like valid reactions...
So here's a thing
import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.channel.id == 639119822525038603:
await message.add_reaction("\N{skull}")
await message.add_reaction("\N{eye}")
@client.event
async def on_thread_message(message):
if message.channel.id == 978369141801119795:
await message.add_reaction("\N{skull}")
await message.add_reaction("\N{eye}")
channel with id 639119822525038603 is a regular channel
and it's working here
but when i'm trying to do same thing on thread
(978369141801119795)
it just not reacting
and so if I trying to send any message
oh so if i use row 4, when there are just like 4 buttons before the 3 buttons, will it still work
wait actually i need to tias
i don't think on_thread_message is an event
try handling that same channel id in the regular on_message
works as expected tysm
Still nothing
even after removing first on_message
send your new code please
import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.channel.id == 978369141801119795:
await message.add_reaction("\N{skull}")
await message.add_reaction("\N{eye}")
client.run('token')
Hi guys, I have overwritten cog_check method but, still i can use that Cog from my server. Do you have any idea? what is wrong?
I probably need to add my bot to a thread somehow, I did it manually but I thinks it aint working like that
Hey guys how do i install pycord alpha on a vps
i tried
pip3 install git+https://github.com/Pycord-Development/pycord
It said this:
My View's interaction_check isn't getting called. This is the correct function signature, right?
async def interaction_check(self, interaction: discord.Interaction) -> bool:
is ext.bridge available on the beta version?
help
Hello - what is the pip command line prompt for importing Pycord libraries?
!install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
this ⬆️
Thank you 😄
That command is out of date. You want 2.0.0rc1
what're the new features?
#library-updates message
rc is alpha?
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.9) or chardet (4.0.0) doesn't match a supported version!
warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
help
RC means release candidate. Very late beta
oh
How do i error handle bridge commands?
@change_prefix.error
async def change_prefix_error(self, ctx:commands.Context, error):
if isinstance(error, commands.MissingPermissions):
await ctx.reply('`Only Adminstrators can run this command`')
if isinstance(error, commands.MissingRequiredArgument):
await ctx.reply('`Error: Missing Required Arguments (new_prefix)`')
Gives me the error -
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\cog.py", line 711, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "e:\Python\Evelynn Workspace\Evelynn5.0\cogs\guildSetup_cog.py", line 5, in <module>
from main import mongo_db
File "e:\Python\Evelynn Workspace\Evelynn5.0\main.py", line 28, in <module>
client.load_extension(f'cogs.{filename[:-3]}')
File "C:\Python\lib\site-packages\discord\cog.py", line 783, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Python\lib\site-packages\discord\cog.py", line 714, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.guildSetup_cog' raised an error: AttributeError: 'BridgeCommand' object has no attribute 'error'```
##1388
just opened an issue regarding it a little bit ago
for now just handle the errors in the regular on_command_error and on_application_command_error events
Can I get the message id, of the message that was sent through ApplicationContext.respond()?
ight thanks
For bridge errors, I just made a bridge between them that is called by both on_command_error and on_application_command_error
I figured out how, but jesus, it's convoluted...
You would think interaction.message would work, but it does not >.<
interaction = await ctx.respond(f"I want this message")
message_id = (await interaction.original_message()).id
message = await interaction.channel.fetch_message(message_id)
heyo any idea why get_guild returns none for my guild? guild = bot.get_guild(my_guild)
because get_guild only returns guilds that are in their cache, so your guild somehow isn't in the cache.
You can do a fetch_guild (coroutine) to grab it.
oh ok neat
cool I can see my guild now
now to figure out how to get a list of the members in it
hmm it's returning none
got it, intents was the issue 😄
im creating a modal, but i want to send the contents to a specific channel. so, i use the code:
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Short Input"))
self.add_item(discord.ui.InputText(label="Long Input", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction, ctx):
embed = discord.Embed(title="Modal Results")
embed.add_field(name="Short Input", value=self.children[0].value)
embed.add_field(name="Long Input", value=self.children[1].value)
channel = bot.get_channel(959130583471112255)
await channel.send_message(embeds=[embed])
@bot.slash_command()
async def modal_slash(ctx: discord.ApplicationContext):
"""Shows an example of a modal dialog being invoked from a slash command."""
modal = MyModal(title="Modal via Slash Command")
await ctx.send_modal(modal)
however, i get the error:
Ignoring exception in modal <__main__.MyModal object at 0x0000021BFD753B80>:
Traceback (most recent call last):
File "C:\Users\alexj\Desktop\EpicGiant Bot\venv\lib\site-packages\discord\ui\modal.py", line 260, in dispatch
await value.callback(interaction)
TypeError: callback() missing 1 required positional argument: 'ctx'
how do i correctly go about sending the embed to a specific channel?
remove the ctx
in this line
async def callback(self, interaction: discord.Interaction, ctx):
omg
tysm
im a bit blind
or lazy
AttributeError: 'TextChannel' object has no attribute 'send_message'
am i using the modern way to send to a specific channel in pycord?
send not send_message
its just channel.send()
lmao all good
back again
right so here is my updated code:
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Short Input"))
self.add_item(discord.ui.InputText(label="Long Input", style=discord.InputTextStyle.long))
async def callback(self):
embed = discord.Embed(title="Modal Results")
embed.add_field(name="Short Input", value=self.children[0].value)
embed.add_field(name="Long Input", value=self.children[1].value)
channel = bot.get_channel(959130583471112255)
await channel.send(embeds=[embed])
@bot.slash_command()
async def modal_slash(ctx: discord.ApplicationContext):
"""Shows an example of a modal dialog being invoked from a slash command."""
modal = MyModal(title="Modal via Slash Command")
await ctx.send_modal(modal)
when i submit the modal, i get this (image attatched), and there is no error message in the console.
I have a big issue here: just updated my verified bot with global slash commands, but it won't register. It seems to only register when it's re-added to the server with applications.commands permission. Is that true? Does every server my bot is on has to do it?
global commands take up to 1 hour to be cached
does anyone have an idea why ctx.interaction.message.author.name doesn't work in a slash command
interaction.message only exists for message components
some do, some don't. idk why discord is inconsistent
i'm pretty sure this is mentioned on the docs(?)
What do you mean?
Isn't a slash command a message component
ohh mb
slash commands don't really have a message affiliated with them as such until you respond
Is there anyway I can get the author?
there's interaction.user
thanks alot it worked
heya buds,
do someone have an example for a websocket via pycord?
ik discord.py got on in their docs, but i do not found it in the pycord docs
or will the same code work too?
yeah nevermind, ill use the discord rest to doin this
can someone help me?
Hi, when I use my command I want a normal string / sentence as output like "Increases most stats by 10%" not with the §a10%§7.
I want my output to be "Increases most stats by 10%"
show code
seems to be formatting residue from whatever api youre interfacing with
yea but is there a way to change it after I requested it from the api
by sanitizing it
one simple example i can think of on the spot is to iterate through the string in a for loop, check if the current element is equal to "§" and remove the next element in the string
How do I use the invisible param when defering an interaction response? Im on the newest version and its an unexpected argument, yet the docs say it exists
guys help
randompack2 = [["Grounded 16x Winter", "cool url", discord.File("grounded.png", filename="grounded.png")], ["Grounded 16x Summer", "another cool url", discord.File("groundedsummer.png", filename="groundedsummer.png")]]
@bot.slash_command(guild_ids=[...])
async def test(ctx):
await ctx.respond(randompack2[0[1]])
its a list nest
i want to pick just one especific item of the nest
because i want to sort it in a embed
the await ctx.respond(randompack2[0[1]] does not work
i think that i cant select it like its on the nest
Will my Bot automatically use the changed time if it changes from winter to summer time?
Instead of using the typing event, can I manually check if a user is typing?
something like user.typing_in(channel), or channel.is_typing(user)?
I don´t know if you can use it like that but you can try using a formatted string with f"" and the var in the {} brackets
yes but this does not solve the problem
Could someone point me in to a resource on how to set up a channel like this? Really love the format for a help channel but can't find anything about how to set it up.
Forum layouts like this are gated by discord partnership, you gotta know someone p much
Ah. Makes sense. Thanks
ty will check
I need some help if anyone can help me with it.
i need to get last message from a user sent in a channel
any help?
is there an event for someone dming the bot
you can use the on_message function and check if channel_type == 'dm'
how do i recieve an interaction callback without subclassing discord.ui.Select
you can use the decorator syntax
original_message = interaction.message
response = interaction.followup
chosen_config = self.values[0]
sent = await response.send(
f"You have chosen {chosen_config}, enter the channel you want to use for this setting.",
)```
File "C:\Users\<user>\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "E:\Docs\discord bot\cogs\settings.py", line 59, in callback
sent = await response.send(
File "C:\Users\<user>\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 1546, in send
data = await adapter.execute_webhook(
File "C:\Users\<user>\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 211, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
im getting notfound when i use followup and then try send a messafge
anyone got any ideas
first respond, then followup
traceback?
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 122, in wrapped
ret = await coro(arg)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 810, in _invoke
arg = obj_type(state=ctx.interaction._state, data=_data, **kw)
TypeError: 'tuple' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1098, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 331, in invoke
await injected(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 128, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'tuple' object is not callable
when using discord.TextChannel in Option
looks like you're on a different version than rc1, that arg = obj_type line is on 826 in rc1
sure you're on the right venv?
im not in any venv
try uninstalling and reinstalling py-cord entirely
try cloning the github repo and installing that
was that while trying to install the github repo?
lmao
sorry :p
all good
@gilded widget btw we can use permissions.has_any_role anymore for guild specific commands?
i used this earlier
but i dont see a way to do it with new perms
not sure if it works but it appears discord.ext.commands.has_any_role is still in the docs
try using @commands.has_any_role?
File "E:\kirkabot\cogs\staff.py", line 389, in Staff
@commands.has_any_role(868890524843638812, 868890524843638806)
AttributeError: 'SlashCommand' object has no attribute 'has_any_role'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:\kirkabot\main.py", line 44, in <module>
bot.load_extension(i)
File "E:\kirkabot\venv\lib\site-packages\discord\cog.py", line 787, in load_extension
self._load_from_module_spec(spec, name)
File "E:\kirkabot\venv\lib\site-packages\discord\cog.py", line 718, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.staff' raised an error: AttributeError: 'SlashCommand' object has no attribute 'has_any_role'
gives me that
i think we cant rip, evolving backwards
is commands defined somewhere
outside of being imported ofc
because that error doesn't really line up
nope
do you have a function with the name commands?
@commands.has_any_role works fine for me so yeah, commands must be defined somewhere
just checked, no
change it and use the name kwarg to set it to the exact name
yeah
like it disables commands for users who dont have that role
not entirely sure if it disables usage but it raises an error
ah ok
it doesnt disable the command per se in terms of ui but it prevents the commands from being invoked with an error
ty
how do i get all news channel as well in discord.TextChannel typehint?
will this work?
cuz there is no discord.NewsChannel
kk this worked, tty
@slash_command(name = 'change_prefix', description = 'Change the Bot Prefix for your server')
async def change_prefix(self, ctx:commands.Context, new_prefix:str):
mongo_db.guild_profiles.update_one({'_id' : ctx.message.guild.id}, {'$set' : {'prefix' : new_prefix}})
embed = discord.Embed(
title = f'Prefix for {ctx.message.guild.name} updated to {new_prefix}',
timestamp = ctx.message.created_at,
color = discord.Color.blue()
)
embed.set_footer(text = ctx.message.author.display_name, icon_url = ctx.message.author.display_avatar)
await ctx.reply(embed = embed)
What might the error be? Nothing displayed in console. This is the only slash command on the Bot, in a cog
await ctx.respond()
hmmm
how to make a embed field description become href?
embed = discord.add_field(name=f"Download", value=f"[Click this link to continue](url)", inline=False)```?
that should do it
h
uh
even the url said it doesnt accessed?
or i should put the url on the ()?
"url" is not accessedPylance
youre using an f string
yes
({url})?
yes
What's a good place to learn sqlachademy for SQLITE3
I am trying to host my bot on a VPS, i dopython3 main.py for executing the code, it doesn't do anything but then after a few mins I get this error:
this is a discord.ext.pages question,
Can you use PaginatorMenu to navigate between Page instances?
what i'm doing isn't navigating between page groups, but only pages
also another question 😅 (about python) how do i get self.data as shown in the picture?
No internet connection
Something
🙂 im stupid. Thanks
async def roles(ctx, role1 : discord.Option()):```
Trying to make role1 an option role parameter, any help with discord.Option()
i want to my bot copy the link of a message can someone help me pls
Guys, quick question. Im trying to get a button(when pressed) to send message to a specific channel.
class Err(discord.ui.View):
def __init__(self):
super().__init__(timeout=120)
async def on_timeout(self):
for child in self.children:
child.disabled = True
@discord.ui.button(
label="Do you think this is an error?",
style=discord.ButtonStyle.danger,
emoji=":grey_question:")
async def button_callback(self, button, interaction):
channel = discord.bot.get_channel(id=972198985441902646)
await channel.send(content="test")```
member.status always returns Status.offline, but intents = discord.Intents.all(). How can this be fixed? I want to get all the information about the user.
but each time i end up with AttributeError: module 'discord.bot' has no attribute 'get_channel'
lol i made a fix
but still cant get past this
Im trying to send this message to a different channel from where the command was used
Sorry, I didn't notice at first
There is no fix yet
And what could this be related to? With the library or with the server?
The libary
Thanks, I will wait for corrections. My bot is too big to be transferred to another library.
np
you can try fetching member
i dont know if its exactly the same problem, but with presence I had to do something like
...
member = member.guild.get_member(member.id)
...
you need to use channel = await guild.get_channel(id=...) Its something along those lines, i dont remember properly check the docs
and if you have no guild to work with
then its
guild = await self.client.get_guild(id=...)
again, idk the exact syntax
docs are your friend
Still gives out Status.offline. I also noticed that there is such a problem with the banner (always None) and the color.
UPD: I'm sorry, it worked! I used to use fetch instead of get out of habit.
np! 🤠
How would i get the time at which a slash_command was used??
@slash_command(name = 'change_prefix', description = 'Change the prefix for your server')
@commands.has_permissions(administrator = True)
async def change_prefix(self, ctx:commands.Context, new_prefix: discord.Option(str, description='The new prefix that activates commands')):
mongo_db.guild_profiles.update_one({'_id' : ctx.guild.id}, {'$set' : {'prefix' : new_prefix}})
embed = discord.Embed(
title = f'Prefix for {ctx.guild.name} updated to {new_prefix}',
timestamp = ctx.message.created_at,
color = discord.Color.blue()
)
embed.set_footer(text = ctx.message.author.display_name, icon_url = ctx.message.author.display_avatar)
await ctx.respond(embed = embed)
Nvm you can just do
from datetime import datetime
timestamp = datetime.now()
autocomplete not working when used with other variables/ keyword args, worked when its was solely used
so
you have to make your own bot instance
and then use the get channel
u gotta know the difference between class instance and class
[mp3 @ 0x5565ada0a880] Failed to read frame size: Could not seek to 1026.
./LegacyRP/files/warteraum.mp3: Invalid argument
how can i fix this??
code:
global player
playerchannel = self.bot.get_channel(978406673326669824)
player = await playerchannel.connect()
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio("./LegacyRP/files/warteraum.mp3"))
player.play(source, after=lambda e: print(f"Player error: {e}") if e else None)
Hi, how to fix that?
https://prnt.sc/WiJrk9vVuKVN
Error: ```
'Context' object has no attribute 'respond'
It's .send not .respond I think
So I noticed that ext.pages makes the paginator message updated with a select menu that doesn’t have a preselected option when using it, how do I do that normally? Because right now, when I edit a select menu, it keeps the selected option selected for my client view, which is kind of annoying. How do I have it not do that like ext.pages does?
But this Bridge
Can anyone help me?
2.0.0rc1
Hmm idk sorry
Ok

Oh what’s that?!
i think that's a typo
i think you wrote tuple instead of turple
Dude
send the code or sth
One message removed from a suspended account.
reply
One message removed from a suspended account.
One message removed from a suspended account.
Look at the quick start mongodbfor python
Also
How are you querying mongodb
Using motor or pymongo
One message removed from a suspended account.
One message removed from a suspended account.
how do i check if a member is above another member in hierarchy
Use motor for mongodb
It's asynchronous
Shouldn't block
One message removed from a suspended account.
Looks aight
Is _id the auto generated mongo one or one you inserted
Also
There's no need to check if blocked_id ==sid
One message removed from a suspended account.
Since you're querying the dB for the sid as _id anyway
If you get a result back
That means they're blocked
Also
results2 can be null
One message removed from a suspended account.
cause the query might not have found anything?
One message removed from a suspended account.
One message removed from a suspended account.
It is wrong
Cause it doesn't raise an error
Also
don't do except:
That catches all types of errors
Even ones you're not meant to be catching
Hello, I need help with this code:
@discord.ui.button(label="Open a ticket", emoji="📩", style=discord.ButtonStyle.green, custom_id="new_ticket")
async def new_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
cursor = self.client.db.cursor()
cursor.execute(f"SELECT role_id FROM Tickets WHERE guild_id = {interaction.guild.id}")
result = cursor.fetchone()
if result is None:
await interaction.response.send_message(
f"This server has not yet configured the role for tickets. Contact a server "
"admin to solve this issue.", ephemeral=True
)
else:
ticket_role = interaction.guild.get_role(result[0])
cursor.execute(f"SELECT category_id FROM Tickets WHERE guild_id = {interaction.guild.id}")
result = cursor.fetchone()
if result is None:
category = None
else:
category = self.client.get_channel(result[0])
channel = await interaction.guild.create_text_channel(f"{interaction.user.name}-ticket", category=category)
await channel.set_permissions(interaction.user, send_messages=True, view_channel=True)
await channel.set_permissions(interaction.guild.default_role, view_channel=False)
await channel.set_permissions(ticket_role, send_messages=True, view_channel=True)
await channel.edit(topic=f"User ID: {interaction.user.id}")
embed = discord.Embed(
title="Thanks for opening a ticket!",
description=f"{interaction.user.mention}, while a staff member arrives at you, "
"describe your problem or tell us what you need.",
color=embed_color
)
await interaction.response.send_message(f"Ticket opened! {channel.mention}", ephemeral=True)
message = await channel.send(content=f"{interaction.user.mention} {ticket_role.mention}", embed=embed,
view=NewTicketButtons(self.client))
await message.pin()
cursor.execute(f"SELECT logs_id FROM Tickets WHERE guild_id = {interaction.guild.id}")
channel_id = cursor.fetchone()
if channel_id is None:
return
else:
logs_channel = self.client.get_channel(channel_id[0])
log_embed = discord.Embed(
title="Ticket opened",
description=f"{interaction.user.mention} opened the ticket {channel.mention}.",
color=embed_color
)
log_embed.timestamp = datetime.datetime.utcnow()
await logs_channel.send(embed=log_embed)
error:
Ignoring exception in view <NewTicket timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Open a ticket' emoji=<PartialEmoji animated=False name='📩' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\Administrator\PycharmProjects\Volt\venv\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Administrator\PycharmProjects\Volt\cogs\ticket.py", line 143, in new_ticket
await channel.set_permissions(ticket_role, send_messages=True, view_channel=True)
File "C:\Users\Administrator\PycharmProjects\Volt\venv\lib\site-packages\discord\abc.py", line 875, in set_permissions
raise InvalidArgument("target parameter must be either Member or Role")
discord.errors.InvalidArgument: target parameter must be either Member or Role
here is my code, im trying to send modal results to a specific channel:
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Short Input"))
self.add_item(discord.ui.InputText(label="Long Input", style=discord.InputTextStyle.long))
async def callback(self):
embed = discord.Embed(title="Modal Results")
embed.add_field(name="Short Input", value=self.children[0].value)
embed.add_field(name="Long Input", value=self.children[1].value)
channel = bot.get_channel(959130583471112255)
await channel.send(embeds=[embed])
@bot.slash_command()
async def modal_slash(ctx: discord.ApplicationContext):
"""Shows an example of a modal dialog being invoked from a slash command."""
modal = MyModal(title="Modal via Slash Command")
await ctx.send_modal(modal)
but when i submit the form, i get this error message (attached in image) and no error message displays in the console.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
dont work
role exists (892080637031383057) and The Volt (my bot) role is above all others
One message removed from a suspended account.
with the code:
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, user: discord.Member, *, reason):
await ctx.guild.ban(user, reason=reason)
i get the error:
Ignoring exception in command ban:
Traceback (most recent call last):
File "C:\Users\alexj\Desktop\EpicGiant Bot\venv\lib\site-packages\discord\commands\core.py", line 126, in wrapped
ret = await coro(arg)
File "C:\Users\alexj\Desktop\EpicGiant Bot\venv\lib\site-packages\discord\commands\core.py", line 853, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "C:\Users\alexj\Desktop\EpicGiant Bot\cogs\moderation.py", line 11, in ban
await ctx.guild.ban(user, reason=reason) # Bans the user.
File "C:\Users\alexj\Desktop\EpicGiant Bot\venv\lib\site-packages\discord\guild.py", line 2907, in ban
await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
File "C:\Users\alexj\Desktop\EpicGiant Bot\venv\lib\site-packages\discord\http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\alexj\Desktop\EpicGiant Bot\venv\lib\site-packages\discord\bot.py", line 993, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\alexj\Desktop\EpicGiant Bot\venv\lib\site-packages\discord\commands\core.py", line 357, in invoke
await injected(ctx)
File "C:\Users\alexj\Desktop\EpicGiant Bot\venv\lib\site-packages\discord\commands\core.py", line 134, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
my bot has ban permissions, what does it mean by missing permissions?
So I noticed that ext.pages makes the paginator message updated with a select menu that doesn’t have a preselected option when using it, how do I do that normally? Because right now, when I edit a select menu, it keeps the selected option selected for my client view, which is kind of annoying. How do I have it not do that like ext.pages does?
create a new select menu in your callback
i've done pip install py-cord and when trying to run my bot it returns the following error
File "f:/stuff/Codes/PY/Bots/eulogy-bot-2/Eulogy-bot-main/main.py", line 2, in <module>
from discord.ext import bridge
ImportError: cannot import name 'bridge' from 'discord.ext' (unknown location)
pip install py-cord will install v1.7.3
?tag install
- Uninstall
discord.pyor any other forks of discord.py you might have with the namespacediscord.
python -m pip uninstall discord.py discord -y
- Install
py-cord
python -m pip install py-cord
Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.
Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
Updating to beta:
pip install py-cord==2.0.0b7
is that what i want?
Bridge isn't part of 1.7.3, you'll probably want the beta
pip install py-cord==2.0.0b7
I'm getting Expected <class 'NoneType'> for min_value, got "int" with this bunch of code, not sure why it's doing this
yeah, I've mentioned it in #974904449044742225
there's a few different problems with options right now, I'd try and fix them but idk enough about how they work
might open an issue on the repo later tonight with all the bugs I know of currently
idk if i'm doing sth wrong but i'm struggling placing a thumbnail taking it from discord.Member.avatar.url and a few variables
e.thumbnail(url=user.avatar.url)
TypeError: 'EmbedProxy' object is not callable ```this is the error
@bot.slash_command(name="userinfo", description="Muestra la información del usuario")
async def info(ctx, user: discord.Member = None):
user = user or ctx.author # if no user is provided it'll use the the author of the message
e = discord.Embed(timestamp=datetime.datetime.now(tz=madrid))
e.set_author(name=user.name)
e.thumbnail(url=user.avatar.url)
e.add_field(name="ID", value=user.id, inline=False) # user ID
e.add_field(
name="Se unió en:",
value=discord.utils.format_dt(user.joined_at, "F"),
inline=False,
) # When the user joined the server
e.set_footer(text="Solicitado por: {}".format(user.name), icon_url=ctx.author.avatar)
e.add_field(
name="Creado en",
value=discord.utils.format_dt(user.created_at, "F"),
inline=False,
) # When the user's account was created
colour = user.colour
if colour.value: # if user has a role with a color
e.colour = colour
if isinstance(user, discord.User): # checks if the user in the server
e.set_footer(text="Este miembro no está en este servidor.")
await ctx.respond(embed=e) # sends the embed
``` this is the whole code for the embed
i just added the thumbnail and the footer
