#Basic Pycord Help (Quick Questions Only)
1 messages Β· Page 90 of 1
async def interaction_check(self, interaction: discord.Interaction):
mods_role = discord.utils.get(interaction.guild.roles, name="Mods")
is_mod = mods_role in interaction.user.roles
if not is_mod:
await interaction.response.send_message(f"Only mods can do thi!", ephemeral=True)
return False
else:
return True
Would have to include that in myview class or appart from it
Sorry, Im a bit dumb on buttons
it's part of the view class
ok great
then I should do this
But in the interaction_check
and return True or false
yes
but I would need to add the button to the interaction_check args right?
async def interaction_check(self, interaction: discord.Interaction, button):
or how
no
the interaction check is for all buttons in the view
you can get the button's custom_id with interaction.data['custom_id']
Do I have to define that custom_id
Im a bit lost tbh
send your view class
1s
well its a bit long lmao
will just send the important part
because there is a whole txid checking logic
sure, you can leave out the method bodies
class MyView(discord.ui.View):
def __init__(self, bot_instance, crypto, price, addy, user_id, author_id):
super().__init__()
self.ncrypto = NCrypto()
self.bot = bot_instance
self.crypto = crypto
self.txid = ''
self.price = price
self.addy = addy
self.userid = user_id
self.author_id = author_id
async def interaction_check(self, interaction: discord.Interaction):
if self.userid != interaction.user.id:
button.disabled = True
button.label = f'You are not <@{self.userid}>'
button.emoji = 'β'
button.style = discord.ButtonStyle.red
return False
else:
return True
@discord.ui.button(label="Sent!", style=discord.ButtonStyle.success, emoji="β
")
async def button_callback(self, button, interaction):
if self.userid != interaction.user.id:
button.disabled = True
button.label = f'You are not <@{self.userid}>'
button.emoji = 'β'
button.style = discord.ButtonStyle.red
return
button.disabled = True
await interaction.response.edit_message(view=self)
await interaction.channel.send('Please send the txid!')```
I didnt remove some parts because Im testing tho
you just do @discord.ui.button(label="Sent!", style=discord.ButtonStyle.success, emoji=":white_check_mark:", custom_id="foo")
and then in interaction_check you just say if interaction.data['custom_id'] == 'foo' or whatever
does that make sense?
ye
and then what should I do to edit the button
like disable it, change the label and shi
if its not the user Id I need
if you disable the button it disables for everyone
if you return False, the callback won't run for that user
oh
interaction_check runs before the callback
I see what you're asking
but its not possible right
now I need to figure out how my code works π
I have a view where if I push a button I remove the buttons and add another button
ah right
view.clear_items()
reopen_button = Button(label="Reopen", style=discord.ButtonStyle.grey, custom_id='work_order_view:reopen')
reopen_button.callback = reopen
view.add_item(reopen_button)```
that's in a static method in the view, which takes in the view as an argument
which I realize is a little confusing
in the callback I do await interaction.message.edit(embed=await WorkOrderView.get_work_order_embed(self.bot, self.work_order_id, interaction.message.guild, view=self), view=self)
WorkOrderView.get_work_order_embed is the static method
so let me take a step back and ask what you want to happen
ok so
I want only one user to have the button enabled
an user id
but disabling it makes it disabled for everyone
So how could I make it send a message that only the user that tried to press the button sees that says "You are not <@user.id> and you cant press this button"
lmao
Just check the id in interaction_check and return false if it's not the right id
so when i have this exact code, the options dont show at all
@bot.slash_command(name="yeah")
@option("Option", description="Choose your gender", choices=["Embed", "Raw", "Other"])
async def hello(
ctx: discord.ApplicationContext,
options: str,
):
if options == 'Embed':
await ctx.respond("wha")
elif options == 'Raw':
await ctx.respond("kys")
else:
await ctx.send("Invalid option!")```
The parameter name and option name should match
There is a kwarg in the decorator if they are different
Pass the parameter name to it
issue is i dont know
right
i did what you did
thanks for the quick response btw
is multiple cooldowns possible?
@ext_commands.cooldown(1, 15, ext_commands.BucketType.user)
this is the cooldown for normal users ^^^ (15 sec cooldown)
but i want it so that premium users only has 10sec cooldown
Check out dynamic cooldown
ty
Here's the cooldown example.
There should be an example at the end
thx a lot β€οΈ
np!
Do bots see pronouns?
Probably not
why i when set respond i having error
Ignoring exception in command kiss:
Traceback (most recent call last):
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\misha\Desktop\34\test.py", line 28, in kiss
await ctx.respond(image_url)
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\context.py", line 282, in respond
return await self.interaction.response.send_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 825, in send_message
await self._locked_response(
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 1090, in _locked_response
await coro
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\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
@bot.slash_command(name="waifu")
async def waifu(ctx):
response = requests.get('https://waifu.pics/api/sfw/waifu')
data = response.json()
image_url = data['url']
await ctx.respond(image_url)
@bot.slash_command(name="kiss")
async def kiss(ctx):
response = requests.get('https://waifu.pics/api/sfw/kiss')
data = response.json()
image_url = data['url']
await ctx.respond(image_url)
?tag aiohttp
Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(https://docs.pycord.dev/en/stable/faq.html#what-does-blocking-mean)
Py-cord uses aiohttp, so it should already be installed. An example of code using aiohttp and Py-cord:
async with aiohttp.ClientSession() as cs:
async with cs.get('https://httpbin.org/json%27') as r:
res = await r.json() # returns dict
await ctx.send(res['slideshow']['author'])β
For more help, see aiohttp's documentation: https://docs.aiohttp.org/en/stable/
This is a list of Frequently Asked Questions regarding using Pycord and its extension modules. Feel free to suggest a new question or submit one via pull requests. Coroutines: Questions regarding c...
since you are making a web request, it might take more than 3 seconds to respond. you should add await ctx.defer() at the start of any such commands
oh thanks
hello need help trying respond that channel not nsfw chat use chat with nsfw tag.
code
@bot.slash_command(name="love")
@commands.is_nsfw() # Decorator to ensure the command is used in an NSFW channel
async def love(ctx):
try:
async with aiohttp.ClientSession() as session:
async with session.get('https://waifu.pics/api/nsfw/waifu') as response:
response.raise_for_status() # Raise an exception if the request was not successful
data = await response.json()
image_url = data['url']
await ctx.respond(image_url)
except commands.NSFWChannelRequired:
# Send a message in the text channel
await ctx.channel.send("This command can only be used in NSFW channels.")
but when i use
Ignoring exception in command love:
Traceback (most recent call last):
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 372, in invoke
await self.prepare(ctx)
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 292, in prepare
if not await self.can_run(ctx):
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 400, in can_run
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\utils.py", line 699, in async_all
for elem in gen:
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 400, in <genexpr>
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 2309, in pred
raise NSFWChannelRequired(ch) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
discord.ext.commands.errors.NSFWChannelRequired: Channel 'general' needs to be NSFW for this command to work.
If your command is nsfw, you can only use that command in nsfw channel
I can if channel isn't I can inform user?
All about handling errors.
yup
Thanks
i tested and didnt know what paste xD here
@love.error
async def on_application_command_error(ctx: discord.ApplicationContext, error: discord.DiscordException):
if isinstance(error, commands.notnsfw):
await ctx.respond("This command can only be used in NSFW channels.")
else:
raise error # Here we raise other errors to ensure they aren't ignored
if isinstance(error, commands.notnsfw):
?)
if isinstance(error, NSFWChannelRequired):
How do I get the actual display name for a member? Like with the new discord username system? discord.member.display_name returns their normal username.
Have you tried doing something like member.user.display_name?
the acutal discord api uses global_name, but thats not anywhere in the pycord docs, and I saw display_name was just something internal to get their username or something
ill try that now tho
Ah
you cant get the user object from a member objects with member.user
is there even a way to get their display name with pycord yet?
With the master branch
^ I don't think the newest version has global name
how do you force update to the master branch on github
i mean like
use the version thats on github master branch
of pycord
oh uhh that branch has unreleased stuff
pip install -U git+https://github.com/Pycord-Development/pycord
thats the point
do you know the usage?
what?
were you not talking to me?
It does sorry by newest I thought master
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
@worn void on master branch ^
still not working
@commands.slash_command(name="test")
async def test(self, ctx):
await ctx.respond(ctx.author.global_name)
on master
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Member' object has no attribute 'global_name'
Send pip list please.
you want the entire list or just the py-cord version
Entire
mk
aiohttp 3.8.4
aiosignal 1.3.1
async-timeout 4.0.2
attrs 23.1.0
blinker 1.6.2
charset-normalizer 3.1.0
chat-exporter 2.5.3
click 8.1.4
colorama 0.4.6
EasyProcess 1.1
emoji 2.2.0
entrypoint2 1.1
Flask 2.3.2
frozenlist 1.3.3
grapheme 0.6.0
humanfriendly 10.0
idna 3.4
itsdangerous 2.1.2
Jinja2 3.1.2
keyboard 0.13.5
mariadb 1.1.6
MarkupSafe 2.1.3
mss 9.0.1
multidict 6.0.4
mysql-connector-python 8.0.33
packaging 23.1
Pillow 9.5.0
pip 23.1.2
protobuf 3.20.3
py-cord 2.4.1.dev145+gcada37a4
pygame 2.4.0
PyGetWindow 0.0.9
PyMsgBox 1.0.9
pynput 1.7.6
pyperclip 1.8.2
pyreadline3 3.4.1
PyRect 0.2.0
python-dotenv 1.0.0
pytweening 1.0.7
pytz 2023.3
setuptools 65.5.0
simple-pid 2.0.0
six 1.16.0
urllib3 1.26.15
vgamepad 0.0.8
Werkzeug 2.3.6
yarl 1.9.2
Hmm weird
How about author.user instead of author
author.user doesnt exist i think
.rtfm member.user
Target not found, try again and make sure to check your spelling.
Huh
.rtfm author.user
Target not found, try again and make sure to check your spelling.
.rtfm ctx.author.user
Target not found, try again and make sure to check your spelling.
Author would return a member object
discord.TeamMember.public_flags
discord.TeamMember.system
discord.TeamMember.team
discord.Member
discord.Member.accent_color
discord.Member.accent_colour
discord.Member.activities
discord.Member.activity
discord.Member.add_roles
discord.Member.avatar
discord.Member.ban
discord.Member.banner
discord.Member.bot
discord.Member.can_send
discord.Member.color
discord.Member.colour
discord.Member.communication_disabled_until
discord.Member.create_dm
discord.Member.created_at
discord.Member.default_avatar
member.global_name is correct.
i dont get why its saying member has no attribute global_name
.rtfm send
discord.Thread.can_send
discord.Thread.send
discord.on_socket_raw_send
discord.Permissions.send_messages
discord.Permissions.send_messages_in_threads
discord.Permissions.send_tts_messages
discord.TextChannel.can_send
discord.TextChannel.send
discord.VoiceClient.send_audio_packet
discord.User.can_send
discord.User.send
discord.VoiceChannel.can_send
discord.VoiceChannel.send
discord.ext.commands.Context.can_send
discord.ext.commands.Context.send
discord.ext.commands.Context.send_help
discord.Member.can_send
discord.Member.send
discord.ext.commands.HelpCommand.send_bot_help
discord.ext.commands.HelpCommand.send_cog_help
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 ...
There is a stickers argument
oh is it literally just send(sticker=<name of sticker>)? damn
wait NVM I understand it now
Are you on the master branch?
yes
xx
reinstalled master branched like 4 times
^ uninstalled before each time
Try printing discord.__version__
is it possible to restrict one select value in a drop-down menu to a user with a particular role?
i fixed it
Oh how
Not built in. You could implement it. Or you could just include that option only when a user with that role uses the app command or whatever.
could i do elif select.values[0] == "blah" then if role not in interaction.user.roles:?
That is the concept yes
hey, does @discord.default_permissions(administrator=True, manage_guild=True) mean I need both permissions or either of them?
and if it means both, how can I make it only need either?
I think it means either
If not, you use use local checks instead of discord ones
File "/home/container/247-casino-bot.py", line 30, in <module>
from discord.commands import Option
File "/home/container/.local/lib/python3.9/site-packages/discord/commands/__init__.py", line 27, in <module>
from .core import *
File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 49, in <module>
from ..enums import MessageType, SlashCommandOptionType, try_enum
ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (/home/container/.local/lib/python3.9/site-packages/discord/enums.py)```
how do i go about fixing this issue
Can you show your pip list pls?
its a requirement file
py-cord
DateTime
colorama
yfinance
aiosqlite
topggpy
loguru
upgradechat
pycryptodomex
uninstall topggpy and py-cord and reinstall py-cordand install topggpy with the github one
wdym by reinstall topggpy with the github one
The pip one doenst work with py-cord
gotcha ill give it a shot now
CLIENT.topggpy = topgg.DBLClient(CLIENT, 'mytokenhere', autopost=True, post_shard_count=True)```
```py
File "/home/container/247-casino-bot.py", line 89, in <module>
CLIENT.topggpy = topgg.DBLClient(CLIENT, 'myactualtokenhere')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: DBLClient.__init__() takes 2 positional arguments but 3 were given``` im no longer getting that previous error but im getting a new one
I cannot really help with that one
is there a function that basically does what the hovering x does on an embed?
you can remove embeds from a message if that's what you're asking
.rtfm embed
discord.EmbeddedActivity.spell_cast
discord.EmbeddedActivity.watch_together
discord.EmbeddedActivity.watch_together_dev
discord.EmbeddedActivity.word_snacks
discord.EmbeddedActivity.word_snacks_dev
discord.EmbeddedActivity.youtube_together
discord.WebhookMessage.embeds
discord.Message.embeds
discord.SyncWebhookMessage.embeds
discord.PermissionOverwrite.embed_links
discord.PermissionOverwrite.start_embedded_activities
discord.Permissions.embed_links
discord.Permissions.start_embedded_activities
discord.MessageFlags.suppress_embeds
discord.InviteTarget.embedded_application
discord.ext.pages.Page.embeds
discord.InteractionMessage.embeds
discord.Colour.embed_background
discord.ApplicationFlags.embedded
yes but not the embed the bot is sending
like essentially removing the autoembed from someone elses message
m.edit(suppress=True)
are bots allowed to edit other people's messages?
I was under the assumption they can only delete
no, but they can remove embeds
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 perfect
Raises:
Forbidden β Tried to suppress a message without permissions or edited a messageβs content or embed that isnβt yours.
you need manage_messages to remove embeds from other people's messages
alright thanks!
im making a game bot so a user can input a purchase with their coins, now they will input their order like x10 apples, x3 oranges, x5 bananas, however i want to store this in a list so ["10", "apple", "3", "orange"...] but i dont know how to split the numbers from the text
can you send the code you have now?
so im having them input it into a modal:
class Start(Modal): # interaction_4th, modal questions & response
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
# add the questions:
self.add_item(InputText(label="Your order", placeholder="x5 apples, x4 oranges..", min_length=10, max_length=1000, required=False, style=discord.InputTextStyle.long))
async def callback(self, interaction_4th: discord.Interaction): # once the submit button is clicked..
overwrites = {
interaction_4th.guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction_4th.user: discord.PermissionOverwrite(send_messages=True, view_channel=True, attach_files=True, embed_links=True, read_message_history=True, use_slash_commands=True),
}
guild = bot.get_guild(GUILD_ID)
category = bot.get_channel(ORDERS_ID)
order = self.children[0].value
split_order = order.split(",")
order1 = split_order[0]
order2 = split_order[1]
order3 = split_order[2]
total1 = extract_numbers(order1)
total2 = extract_numbers(order2)
total3 = extract_numbers(order3)
print(total1 + total2 + total3)```
I would suggest reading up on python string manipulation and list slices
i know partly how they work
sounds like you have a good starting point then
another option would be to have a modal with 4 fields, quantity/text/quantity/text and then they can submit that multiple times for bigger orders. that way you don't have to do any manual parsing
its just i can only have 5 fields in a modal and for people wanting to order more wouldnt be able to
yep
hence submitting multiple orders
not the best solution but it's an option
or just have a slash command with a bunch of options
so id have to use multiple modals?
well they could submit the same modal multiple times
would that work if i had multiple different items?
I don't see why not
you submit it once for 3 apples and 2 oranges
and again for 4 bananas and 8 pears
and then you just execute the orders one at a time
how would i do that?
you don't have to do anything special...
i didnt know you could submit them twice
your callback just treats each order as an order
you shouldn't have to care if it's their 1st or 100th order
yes
thanks :)
no problem π
if im wanting to access the results from the modal later on, how should i store the results?
well, how are you storing things like your user's money?
Not json plz π€
a database
do you not want to store the orders in the database?
do you need to store anything or would you just execute the order and store the results
i need to store it because later on i need to calculate the price and therefore get the items and quantity again
when is "later on"?
Is there some better way to make like counting then on every message to get channel and and check if its same as in database? i think is so bad for performce of bot to check every message.
i had idea to make instances of every guild where bot counting is setup on bot start and save channel.id into class instance but still i need to check every message
if it were me, I would deduct the money and add the items to the inventory right there in the callback
i have an embed that they can choose which payment to continue with
Like a counting bot?
I can't answer that for you, but I would probably just store it in memory (in a variable), I don't see the need to put it in the db
You could store it in a instance varible. Not sure if this is the best way but due to the property's of lists you could have
self.order =[]
MyModal(self.order)
# Modal callback
self.order.append(order_details)
im confused about how to store the values if the modal has been answered more than once
as a list
now im storing guild id and channel id and current number into database. i dont have idea how to keep variables after bot restart
so order_list.insert(0, amount)?
I was replying to phyr, sorry
oh sorry my bad
more like this #998272089343668364 message
ohh so just append
if you just add message id as well as current number, you only need to look at messages between that message id until now when the bot starts
do i need to call it self.order?
the assumption is you're in a class (a cog) and you have an instance variable named order
You would still need on message. Just filter out all messages from different channels.
To avoid calling the database constantly you can have a time-to-live cache with the channel ID. Just make sure to clear that value from the cache when it is changed.
oh, i dont seem to
Is this just for a small number of servers? (Less than 5) or do you want it to work on many
maybe im litle bit dump but can you explain what do you mean by that?
now counting is active on 6 servers i think but im scared if bot will grow it can make some bugs
But the intent is for it to grow π
you could just ignore everything that happened while the bot was down
although as I think about it I can see the issues that would cause
just wouldn't be a good user experience
if you mean me yeah it can be problem. someone is at number 7 my bot goes offline and poeple count to 9 and my bot goes online and bot remember 7 as last number
I know some bots add a reaction on every message for counting
that would let you know you've already checked that message
and also let users know the bot stopped tracking
i already put reaction to messages that bot check and delete messages that arent numbers in that channel but still people dont stop counting when bot is offline
right, but then when you're checking on startup you just skip messages that have the reaction
does this make sense @buoyant pier? ^
and does that solve the issue
i think it can work i will try that. thank you guys
an optimization once your bot gets big enough is to not build in a check on startup, but only check in on_message
so if a guild stops counting for a while you don't have to waste resources looking them up until someone starts counting again
It is a hard to solve issue. Its what programming is all about.
oh thats actualy sounds good. also i can make like message they start counting again after like day or something. thank you
im so sorry but some body pls help when i moved to cog and i have
when not
@love.error
async def on_application_command_error(ctx: discord.ApplicationContext, error: discord.DiscordException):
if isinstance(error, commands.NSFWChannelRequired):
await ctx.respond("This command can only be used in NSFW channels.")
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: pics.on_application_command_error() takes 2 positional arguments but 3 were given
add self as the 1st param
||basics of a Class in python||
im first time coding and some time can lose
stop i founded in site cog
@pics.command(name="love")
@option("choice", description="choice", choices=CHOICES)
@commands.is_nsfw()
async def love(self, ctx: discord.ApplicationContext, choice: str):
choice = choice.lower()
async with aiohttp.ClientSession() as session:
async with session.get(f'https://api.waifu.pics/nsfw/{choice}') as response:
response.raise_for_status()
data = await response.json()
image_url = data['url']
embed = discord.Embed(colour=0xfee692)
embed.set_image(url=image_url)
await ctx.respond(embed=embed)
async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
if isinstance(error, commands.NSFWChannelRequired):
await ctx.respond("Sorry, you can only use this in private messages!", reference=ctx.message)
else:
raise error```
yea fixed
it looks like this only suppresses the embed on desktop and not mobile, is this just a limitation of the discord mobile apps?
yea
sent from mobile, embed not suppressed but checked the same message on discord desktop and it was suppressed
im having trouble appending the info to a list
im getting myself confused
Is there any way to check if a user in voice is speaking? I searched google and found nothing useful, so I wanted to see if anyone here has figured it out
The following method only works on actual user mute status:
@bot.event
async def on_voice_state_update(member, prev, cur):
if cur.self_mute and not prev.self_mute:
print(f"{member} stopped talking!")
elif prev.self_mute and not cur.self_mute:
print(f"{member} started talking!")```
and look at the top of that page
oof
I may have to go to the dark side and create a discord.js script. If nothing else, than to make an event listener to pass to python
response = await ctx.respond(content="music player")
message = await ctx.channel.fetch_message(response.id)
when i run this it gives me an unknown message error
assuming you're using slash commands you can get the response message with ctx.interaction.original_message scratch that, one sec scratch that x2, it's right
bc im tryna send the message as a response to a slash command then edit the message later
i just wanna get the message object from that message so i can do message.edit()
yeah
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.ApplicationContext.interaction gives you an Interaction, https://docs.pycord.dev/en/stable/api/models.html#discord.Interaction.original_response gives back the message that was sent
ohhhh that makes sense thank you-
you can also use ctx.edit
if it's the initial response (no defer or anything before) then response.id is the interaction id
its gonna need to store the message object to use later
not the message id
since it returns Interaction
ohhh im dumb-
if you defer first it'll return a message
await ctx.respond(content="music player", ephemeral=False)
message = ctx.interaction.original_message
when i do this i get this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'function' object has no attribute 'edit'
wait no
that
ctx.edit is easier on your case
it's a coro
its bc i store the message
Is Interaction.message the same as the View.message
but if you are going to edit it, this is better
if the bot isnt playing any music it sends this message
else it sends a message with an ephemeral, i need to store the first message to edit it later
Skuid ππ½ππ½
On master branch, yes
I assume running User.mutual_guilds on a sharded bot would only return the ones on that shard; if this is the case what would be a way to see all guilds that the bot shares with the user, across all shards?
It should return across all shards
An AutoShardedBot functions code-wise as if it were single shard iirc
unified cache and all that
alright, tnank you
Is there a way i can complete a slash command without having to return a response? the bot has a command which juts dm's some information. If i dont use interaction.response.defer() it shows the interaction did not respond error on discord app, but if i use the defer method it just says bot is thinking... is there a way to remove that option as well?
You could respond to the interaction and then delete the response
thats what i did but i thought there might have been a better solution for it. Thanks you, ill just stick with this method then
Ah, ok. Well, there aren't really any other methods at the moment to not respond to an interaction without getting the error that the application didn't respond.
sadly no
thank you
what happens when you defer and do nothing else? (never tried this approache)
@coarse spire @hazy mango
The commands keeps looping on "the bot is thinking" message
for components based interaction, this is fine and allowed.
for app cmds, it will keep showing "the bot is thinking" for 15 mins, after which it says "bot didnt respond"
is it possible to delete it?
best way would be to send an ephemeral message saying "Sent DM!" or "Please check your DMs"
Oh damn I forgot ephimeral messages existed
Sorry I am not helpful, I just got curious after reading
talking about messages, I do have a problem with paginator.
it does send embeds the way its supposed to and the timeout works also.
it becomes problematic when its message reaches the end of timeout and was deleted.
I tried with try/except but still get an error each time that happens
# embeds is a list filled with embeds
try:
paginator = Paginator(pages=embeds, author_check=True, disable_on_timeout=True, timeout=300)
await paginator.respond(interaction=ctx.interaction)
except discord.errors.NotFound:
return
any ideas?
hey it is great to brainstorm
this shouldnβt happen tbh
but you can subclass Paginator and override on_timeout
the error is raised from there
not from paginator.respond
also which version are you using?
2.4.1
How does it normally react, in this situation?
I may have an idea
how do you access someone's display name?
because when i update my display name, it fires a member_update event
and i literally can't find any way to access the display name
The global display name? (Global nick name)
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
what is pomelo in this case
also what pycord version do i have to be in
for this to work
Pomelo is the name for the new username update
Only on master branch rn
how do i get it
Hi, is possible to get display name?
yes, you need to use the master version
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
Last line
The guy above you was asking the same thing π
See this
for some reason the last command gives this
?tag git
how can I get the master version? is it just pre-released verison?
@vast sun see this. last line
π
So ifound a problem with my music bot, the view for the song doesn't always last long enough for the song to end, so near the end of the song it just won't respond to any of the buttons, any idea how I'd fix this?
Set the timeout to a high number
change the timeout for the buttons
Maybe 10 mins
Ohh wait yea I can just set the timeout to the length of the song
Bc I do have that info
That might cause problems if someone pauses
Crap true- lmao thanks

Wait
What if someone just leaves it paused-
For some dumb reason
There's no way to unpause it-
Set indefinite timeout?
Set to None
Any reason to have it timeout?
Yea by default it is 3 mins
Almost perfect for most songs
Also is there a way to see how long it's been playing a song? Without storing the time it started it no?
You could use the message creating time?
Can't
It sends the message for the first song
Then edits it for every sobg after that
Ah
That message kinda becomes the player
Edit time?
.rtfm message.edited
Ye
:0 thank you I'll look into that
Never really thought it would come to use for anyone π
Well thinik Abt it
If you press last song button
In the first like 10 secs
It plays last song
Else it restarts the song
This is actually really useful lmao
thank you- this helped so much
Is there a way to get a users status?
Thought of something like discord.User.status but thats not an attribute
.rtfm user.activity
Target not found, try again and make sure to check your spelling.
Hmm
how do i pick a type of option using the @option decorator? or do i have to use the other way
just making sure so there arenβt misunderstandings. type referring to string, int, etc.?
no like attachment
or member or whatever
the only thing on the docs is doing it without the decorator
yeah like string, int, members, attachments, and stuff like that
yes yes
would you like an example?
sure
unless it does it automatically when i do async def dspjfidso(ctx, osdjaoi: discord.Member)?
love the func name
thank u
@bot.slash_command(name = "upload")
@discord.option(name = "photo", description = "You can upload a photo here", input_type = discord.SlashCommandOptionType.attachment)
async def upload(
ctx: discord.ApplicationContext,
photo: discord.Attachment
) -> None:
...
I think something like that would work
If I made a typo, oops
it shows the attachment thing on discord but doesnt like it clearly
omg
i forgot await
ok it works thank you
now to figure out how to send the attachment
File = discord.File(photo)
Ctx.send(File)
i feel like thats too easy
Nope
well it did not work
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "bot.py", line 1210, in on_application_command_error
raise error
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/commands/core.py", line 358, in invoke
await injected(ctx)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/commands/core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: send_message() takes from 1 to 2 positional arguments but 3 were given```
what does your code look like?
await ctx.respond("hey", file)
i knew it was not that easy
also file=file says discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InvalidArgument: file parameter must be File
and attachment=file does not exist
How did you define file
async def sdfsds(ctx, file: discord.Attachment):
Oh so you want to resend the file the user uploaded?
yes
await ctx.respond("hey", file=newfile)```
i saw that on stackoverflow but it still says must be file
unless id id it wrong
you need to await the first line
how to get which menu is selected (discord.ui.select) by user but in int? used to acces list index
how can I edit a previously sent response ? like for a music bot, once the 1st song plays... it says the song name and when the next song plays, it just edits the previous message with new song's name?
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
so for my music bot i made a way to add all songs from a playlist to the queue, how do i display the full queue when its length could easily surpass 4096?
Use paginator
would that prevent this?
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds: Embed size exceeds maximum size of 6000
yep
yep
and how can I send message without using ctx? coz trying this:
@bot.event
async def on_wavelink_track_end(payload:wavelink.TrackEventPayload, ctx: bridge.BridgeContext):
vc = payload.player
vc.autoplay = False
try:
if vc.queue or vc.autoplay == False:
next_song = vc.queue.get()
await vc.play(next_song)
await ctx.send("Now playing: `{}`".format(next_song.title))
except wavelink.exceptions.QueueEmpty:
pass
gives me this error:
Ignoring exception in on_wavelink_track_end
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
TypeError: on_wavelink_track_end() missing 1 required positional argument: 'ctx'
store a dict of guild id vs channel
get the channel object from there and send
cant get ctx like that
won't tht be a very long process? like storing every possible channel (coz the cmd can be used in any channel) for every guild the bot is in?
i instead of using it, basically made my own version of it :D
with mine i just needa do this as the view an works perfectly
view=paginator(embeds)
well the bot can only be in 1 vc in a guild.. so whenever a user runs a music command, store the command's channel against the guild id in the dict. then you can get the channel from the event and send a message
you can delete the guild id from the dict when the bot leaves the channel
Hello, how can i get the guild id on a modal callback funtion (interaction.user.guild.id returns none)?
can anybody help me since im lost in the
ok i just use rtfm found out it was guild_id
imma test it
i returns None, weired
weird*
yes
frick i forgot
thanks
β€οΈ
(i told my mind to do it later lol)
hey still returns nothing
i added intents
the parameter name is intents
but interaction.guild_id should return regardless of intents. are you sending this in a dm?
also, show pip list
lmao
can u help me with it... how to get the channel from the event and store it then?
Hey I have a question. My bot is now in 1,400 servers and I've noticed the on_ready is quite terribly slow. I wanted to start sharding, but I have no knowledge on it. I don't develop much anymore and I run my free bot for fun. Any easy way to just implement sharding rq so I can go attend to my life and let my bot function without being super slow?
Sorry! I checked the docs and it did say Sharding is easy. But it was confusing to me.
Using translate btw.
https://guide.pycord.dev/popular-topics/sharding Basically, if you define your bot/client as discord.Bot for your bot now (for example, it's the same for all of them) just replace it with discord.AutoShardedBot
All about Sharding Discord Bots.
then, PyCord will automatically shard your bot
So when initializing the bot, use discord.AutoShardedBot.
I don't have to manually do it for each command?
client = commands.AutoShardedBot(intents=intents,chunk_guilds_at_startup=False)
I'm assuming you mean like this?
Yeah
How do you define how many shards you want / how many are split between them
Is there like shard=
You can just pass shards to commands.AutoShardedBot as well. For example: commands.AutoShardedBot(shards=4)
So it isn't shard_count
It's shards ?. And I'm assuming it'll just devide them across right.
Yeah, it's just shards
Alright. And for everything in my bot using bot. Like self.bot, does that need to change?
Self bot?
No I mean
self.bot.guilds.
Does this need to be self.bot.AutoShardBot.guilds
ig no
this will be enough maybe
Yeah it's working now.
Do shards have to restart seperately?
Or is it still all gonna be in 1
sry idh any idea abt it.. maybe someone else with better understanding could help
fwiw the reason on_ready is slow isn't because of a lack of sharding, but more likely because fetching all the members across 1400 guilds is a slow operation in itself
I did this >.>
Yeah but it didn't do this when it was in 400.
1400 and 400 is quite a large difference...
So if I shard it should let me avoid turning chunking off.
if sharding does fix it then that's good, but if not then you either have to accept that your on_ready will be slow (just manage your restarts better) or disable chunking entirely
For sharding is it shard= or shard_count? I'm seeing mixed opinions.
whatever the docs say
but at your size you don't really need to specify it
discord can set a recommended shard count
How do some bots manage their restarts differently per shard?
well strictly speaking shards are different processes
AutoShardedBot just manages it all in one client
Well upon sharding the on_ready started quicker and my ram usage went down
fair enough then
I didn't provide a shard count though
Do you know how I can print out the shard info?
yeah you don't have to
I'd like to know whats going on. Such as how many are being used.
probably on that docs page hold on
there's Bot.shards which will be a list of them
So print(Bot.shards)
Hey @cyan quail
@client.event
async def on_ready():
activity = discord.Activity(type=discord.ActivityType.listening, name="/help")
await client.change_presence(activity=activity)
print(bot.shards)```
How can you put this outside of an on_ready
So I can restart and always have the status
sorry for pinging
Don't do change presence in on_ready, there's a kwarg in the Bot class itself
Probably activity, check on the docs
got it
Iβm getting random 404 unknown interaction errors even tho im defering ?
hi, I did what you said... and the program is working as intended. here is what I did:
# Create an empty dictionary to store the channels
channel_dict = {}
@bot.event
async def on_wavelink_track_end(payload: wavelink.TrackEventPayload):
vc = payload.player
vc.autoplay = False
try:
if vc.queue or vc.autoplay == False:
next_song = vc.queue.get()
await vc.play(next_song)
# Get the guild ID from the context
guild_id = vc.guild.id
# Check if the guild ID exists in the dictionary
if guild_id in channel_dict:
channel = channel_dict[guild_id]
await channel.send("Now playing: `{}`".format(next_song.title))
except wavelink.exceptions.QueueEmpty:
pass
# Clear the channel_dict dictionary if the queue is empty
if not vc.queue:
guild_id = vc.guild.id
if guild_id in channel_dict:
del channel_dict[guild_id]
@bot.bridge_command()
async def play(ctx: bridge.BridgeContext, search: str):
"""Simple play command."""
guild_id = ctx.guild.id
channel_dict[guild_id] = ctx.channel
await ctx.defer()
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
else:
vc: wavelink.Player = ctx.voice_client
try:
tracks = await wavelink.YouTubeTrack.search(search)
if not tracks:
await ctx.send(f'No tracks found with query: `{search}`')
return
track = tracks[0]
await vc.play(track)
await ctx.guild.me.edit(deafen=True)
await ctx.reply("Now playing: `{}`".format(track.title))
except TypeError:
try:
pl = await wavelink.YouTubePlaylist.search(search)
if not pl.tracks:
await ctx.respond(f'Unable to access the url: `{search}`')
await vc.play(pl.tracks[0])
await ctx.reply("Now playing: `{}`".format(pl.tracks[0].title))
await ctx.guild.me.edit(deafen=True)
for i in pl.tracks[1:len(pl.tracks)+1]:
await vc.queue.put_wait(i)
except Exception as e:
raise e
I just want your review on this, is this ok? Please improve me if you think I could do anything better in the code . Thanks :D
looks good π
i would make 1 change tho
π
it might be better to store the channel only if the song played successfully
also, forgot a return at the end of this?
π€
so that if I use play after adding a playlist, it just adds into the queue instead of skipping the queue and playing the recently requested song?
oh yea makes sense
Are there any workarounds for determining speaking status start and end?
if you wanted, you could have a bool parameter to play now instead of adding to queue
The best I have right now is exporting discord.js user speaking status. I mean it works but it's resource heavy and might need two bots
an event when a user starts speaking in a voice chat, and when they end
voice events dont come through the main gateway iirc. so it might be weird to dispatch that as a normal event
most voice stuff isnt documented too unfortunately
##1984 was already a giant headache (it had to workaround bugs in discord clients) π
Summary
When a Voice Channel is being recorded, users' recordings start when they start speaking, and not when the recording was actually started. This PR adds silence at the start of the recor...
I'll back up to explain what I'm trying to do. I have a voice bot speaking to gpt. What I want to do is have the user speak to initiate the recording, and when he stops add that to the buffer and send that to openai's whisper for transcript
oh interesting
Right now I have to use a command to initiate the recording. Soo.... after searching I just found discord.js could give me an event on speaking. I just export that now. But it's clunky
you could determine the pause on your own
not super easy, but possible
decide a timeout duration
read the buffer I guess?
create your own Sink and override the write method. this is called for every packet, and the bytes are passed to it
beware tho. voice on discord is a very dark place 
o.o hows that?
Can a tasks.loop() get started as multiple instances? or how could I create a task that i can start with different params
I can't send a custom emoji through a webhook
Yes you can
i think you can create a copy of the loop. or you can create a function that returns a task loop
Ok I'll test my code some more
@everyone role needs to have external emoji perms. known discord issue
Hm
would asyncio.create_task with a coro be better then
cause i assume asyncio just creates the task and doesnt care if theres already one
task loops are just asyncio.create_task under the hood
hm
it just takes a coroutine.. there is no such thing as a "duplicate" task
you can make your own version of a task loop pretty easily tbh
do i look smart om
iβm wanting to store the inputted values from a modal that can be submitted multiple times so that i can use the inputted information later. but iβm not sure how to store it and how to store the values if the nodal has been answered more than once
What's the event on a user start speaking and end speaking?
So there isn't really an explicit event for start speaking and end speaking
Discord has a general SPEAKING event, and it should have the currently speaking members
Pycord doesn't directly expose any of this, but you might be able to work your way around stuff
oof
The voice client will have a ws attribute
This is of the DiscordVoiceWebSocket class
At the end, it calls _hook
Which currently does nothing
https://github.com/Pycord-Development/pycord/blob/master/discord/gateway.py#L780-L781
You can override this method
This is incredible so far
Before all that, you might want to enable logging and check if the event actually gets sent for end speaking π
Even if it doesn't it's still huge
Lul
To override that method, you will need to subclass ofc.
In order to use your custom Websocket Class, you will need to subclass VoiceClient and override this method
https://github.com/Pycord-Development/pycord/blob/master/discord/voice_client.py#L371-L377
And use that when connecting
You can bubble the websocket events up into the VoiceClient if that makes life easier
That would be a good library contribution if you are interested
Modify DiscordVoiceWebSocket.from_client to save a reference to client (the VoiceClient). And then just call a method in the _hook
You are amazing :3
Lol no worries
This is probably entirely wrong >.>```from discord.voice_client import VoiceClient
from discord.gateway import DiscordVoiceWebSocket
class CustomDiscordVoiceWebSocket(DiscordVoiceWebSocket):
async def _hook(self, args):
msg = args[1]
op = msg['op']
data = msg.get('d')
# Handling the speaking event
if op == self.SPEAKING:
user_id = data['user_id']
speaking = data['speaking']
if speaking:
print(f'User {user_id} started speaking')
else:
print(f'User {user_id} stopped speaking')
await super()._hook(args)
class CustomVoiceClient(VoiceClient):
# A method where we handle the connection
async def connect(self, *, timeout, reconnect):
self.ws = await CustomDiscordVoiceWebSocket.from_client(self)
self._connected.clear()
await self.ws.poll_event()
self._connected.set()
async def on_voice_state_update(self, data):
await super().on_voice_state_update(data)
self.channel = self.guild.get_channel(int(data['channel_id']))
await self.channel.connect()
async def connect_websocket(self):
self.ws = await CustomDiscordVoiceWebSocket.from_client(self)
self._connected.clear()
while self.ws.secret_key is None:
await self.ws.poll_event()
self._connected.set()
return self.ws```
naice
looks pretty good π
not sure what you are doing here tho
self.channel = self.guild.get_channel(int(data['channel_id']))
await self.channel.connect()
also, why this part?
# A method where we handle the connection
async def connect(self, *, timeout, reconnect):
self.ws = await CustomDiscordVoiceWebSocket.from_client(self)
self._connected.clear()
await self.ws.poll_event()
self._connected.set()
I'm a moron π
the normal thing is completely different
https://github.com/Pycord-Development/pycord/blob/master/discord/voice_client.py#L379-L416
How do I change the discord.ScheduledEventLocation value to a discord.StageChannel?
you mean when using event.edit?
Yes
you just pass the channel in
admittedly the docs aren't very clear on this, but location allows channel objects
Did that; got this
huh hold on
Also tried: py event.edit(location = discord.ScheduledEventLocation(value=StreamServer.get_channel()), but a state parameter is required, and don't know where state comes from, looking at the documentation and GitHub code
what you did the first time is correct
just checking, does this line return a real channel object if you print it?
It printed out correctly
i think i've found the issue anyway, will PR a fix
Great! Thanks
So if I try again it works?
...hopefully?
i got the error the first time i tried editing
then added prints to debug on a different bot
but then it never errored again on either
possibly a discord issue since i didn't actually change anything
Isn`t also better to use get_channel and fetch_channel if get doesnt really get the channel?
perhaps but that wasn't the issue here
(and you can assume get to be reliable for the most part)
Is there a way to remove a cooldown set with @commands.cooldown() if, for example, there is an error in the command format?
I would like to store data about who was most recently awarded a certain role. I would assume that involves storing the user ID in a certain place and overwriting it when a new user is awarded that new role.
I could use a SQL database but that seems a bit overkill, is there a better way to do this or is it best to stick with the database?
Doesn't seem to work. I don't get any opcodes from the hook. It's like the hook isn't even being hit
I think I'll give up for now. If I can commission somebody to get it working I would! π
oh boy...
I think for now I'll use a twin bot and pass the status from discord.js
does received_message get called?
I get this from some print to consoles I got
GPT-Voice#4094 voice state updated: <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=None> -> <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=1111734121857826846 name='GPT-4-Voice' rtc_region=None position=0 bitrate=128000 video_quality_mode=<VideoQualityMode.auto: 1> user_limit=0 category_id=1088622266100756590>>
alphabeta.#0 voice state updated: <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=1111734121857826846 name='GPT-4-Voice' rtc_region=None position=0 bitrate=128000 video_quality_mode=<VideoQualityMode.auto: 1> user_limit=0 category_id=1088622266100756590>> -> <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=None>
alphabeta.#0 voice state updated: <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=None> -> <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=1111734121857826846 name='GPT-4-Voice' rtc_region=None position=0 bitrate=128000 video_quality_mode=<VideoQualityMode.auto: 1> user_limit=0 category_id=1088622266100756590>>
Not that I can tell from this at least
hmm doesnt seem useful
I'll stop for now. Maybe when I come back to it I'll find something obvious I'm missing
if i change the code in a cog and reload is it meant to update with the changes? or have i done something wrong
@prisma flicker
yes reloading the extension will update with changes changes you make
it does not want to work for me
what changes did you make?
iβm wanting to store the inputted values from a modal that can be submitted multiple times so that i can use the inputted information later. but iβm not sure how to store it and how to store the values if the nodal has been answered more than once
basically if you have the ctx, it's ctx.command.reset_cooldown(ctx)
are you sending the modal from a button? and the button can be pressed again and again?
you could also set this to False
https://docs.pycord.dev/en/master/ext/commands/api.html#discord.ext.commands.Command.cooldown_after_parsing
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...
yes and yes
so you could have a dict with the message id as they key, and your data as the value (probably a list/dict)
wait, wdym?
is that correct?π when i pasting
@mod.command(name="action", description="Create a moderation action")
@option(name="user", description="The user to take action on", type=option, required=True)
@option(name="action", description="The type of action", type=option, required=True, choices=ACTIONS)
@option(name="timeend", description="The duration of the action (optional)", type=option)
@option(name="reason", description="The reason for the action", type=option, required=True)
async def action(self, ctx: commands.Context, user: discord.User, action: str, reason: str, timeend: str = None):```
```` from discord.commands import SlashCommandGroup, OptionType
ImportError: cannot import name 'OptionType' from 'discord.commands' (/usr/local/lib/python3.8/dist-packages/discord/commands/__init__.py)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "core.py", line 114, in <module>
bot.load_extension(cog)
File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 777, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cmd.mod.mod' raised an error: ImportError: cannot import name 'OptionType' from 'discord.commands' (/usr/local/lib/python3.8/dist-packages/discord/commands/__init__.py)```
well it's SlashCommandOptionType (from discord, not discord.commands), but you rarely need to use that manually
so you don't need the import at all
also type=option will break the whole thing, you don't need that either because it will inherit from the annotation
Also dont use ctx: commands.Context that is a slash command and not a prefix command ;3
@mod.command(name="action", description="Create a moderation action")
@option(name="user", description="The user to take action on", required=True)
@option(name="action", description="The type of action", required=True, choices=ACTIONS)
@option(name="timeend", description="The duration of the action (optional)")
@option(name="reason", description="The reason for the action", required=True)
async def action(self, ctx, user: discord.User, action: str, reason: str, timeend: str = None):
like that?
upd
upd
The buttons on my bot don't last very long, after a couple of minutes they stop working. I think it's a timeout issue, but I've seen bots with buttons that last much longer. Does anyone know how I can solve this?
timeout=None in your view
are you intending to remove all your other options?
thank you
otherwise the changes you're making are correct
oh well
you still need ctx after self
You can increase the timeout. However this will not last in between restarts. Nelo and Zervyrel show how to make it last in between restarts of the bot
just that the previous typehint was wrong
upd code*
ok you're BASICALLY there py ctx: commands.Contextwhat zerv was pointing out here is that this shouldn't be commands.Context, but rather discord.ApplicationContext (or just leave it as ctx)
but again i removed/updated, and again that problem
File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 774, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/mikis/cmd/mod/mod.py", line 7, in <module>
from discord.commands import SlashCommandGroup, OptionType
ImportError: cannot import name 'OptionType' from 'discord.commands' (/usr/local/lib/python3.8/dist-packages/discord/commands/__init__.py)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "core.py", line 114, in <module>
bot.load_extension(cog)
File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 777, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cmd.mod.mod' raised an error: ImportError: cannot import name 'OptionType' from 'discord.commands' (/usr/local/lib/python3.8/dist-packages/discord/commands/__init__.py)
i have a similar problem, when i put just ctx, it becomes an option in the slash command and with discord.ApplicationContext it says AttributeError: 'NoneType' object has no attribute 'value' im so confused
what about option?
That is weird, do you have anything else than py-cord installed?
you're actually using option, but you aren't using OptionType (which the error is calling out)
can you show the code here
class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
@admin.command(name="givemoney", description = "Bot owner only")
@option("member", description = "The user that you want to give money to", required = True)
@option("amount", description = "The amount of money you want to give", required = True)
@option("reason", description = "The reason for giving the money", required=True)
async def givemoney(self, ctx: discord.ApplicationContext, member: discord.Member, amount: int, reason: str):
await ctx.respond("abc")
that gives the nonetype thing error
how is admin defined
admin = bot.create_group("admin", "Admin commands", guild_ids=[1129032612288147526])
fixed, thanks
no i imported it
hmmm don't do that
you shouldn't import bot to cogs
slash groups in cogs are defined a bit differently
inside the class but outside the init, you should create a SlashCommandGroup ```py
admin = discord.SlashCommandGroup(...)
@admin.command()
async def command(...)```
ah reloading works now thanks
allgood
Sorry to bother but does anyone know how i'd go about making a slash command option where I type in lets say 100 and it'll then display the choices as 100k, 100m, 100betc.
Autocomplete
Here's the slash autocomplete example.
.rtfm member.add_roles
Thank you π
The method is the same
In 1: Application command names must be unique can it at least tell me which i have like 100
You have to check your code
i commented like half of them out and it still says it ajfoisdjfds
Is it yet possible to allow multiple selection on a slash command option?
ig you can code it yourself with autocomplete, but not natively
sup
reloading cogs wont add new slash commands is that normal or
As in functionality or displaying cuz GitHub issue --> #2015
is there an easy way to get all emojis from message?
i think there was something like that
well u cant use them if they dont display right?
thats not what i mean
if you make a new slash command and then reload the cog then it doesnt show up you have to restart the whole bot
RegEx?
I don't know how you are returning it
im stealing it
Well obviously displaying no, but... Just checkout the issue you'll understand 
(<a?)?:\w+:(\d{16,21}>)?
I think that should work
i think that works on :emoji_name: and the lower one
i am pretty sure discord.Message.content, and clean_content as well, returns emojis in <:name:id> format, and i only need that
i think i'll figure it out
thanks anyways
Unloading reloading and loading in
no it should work on both
alright
if only one role fail to delete(exemple roles is 5 roles) (Forbiden), will it steal delete the 4 other roles that the bot have permisisosn to delete
if atomic, yes
I see but how do you know which one(s) failed ?
you can check the member again
I see thank you !
π€©
I could also call the method on each role and it woudl be equivalent on atomic=True ?
but I would know for each roles if it failed without checking the member
if you do it role by role and atomic is false, you would be able to catch which role removals didn't work
I see, I will do this yes thank you !
at least I think this is how it works
Will try it thank you for you help
anyone know why Iβm getting random 404 unknown interaction errors even tho im defering?
is there a way to get a list of the bots dm channels? i tried "bot.private_channels" but that returns an empty list
is there a way i can have a button with a url that uses a different style
no, url buttons only have one style
but you could have a styled button that sends an ephemeral message containing the link or something
but that seems kinda clunky
yea bc i made a better looking emoji i wanna use instead of the dumb one that style uses-
im guessing theres no way i could do that?
url buttons can have emojis is that's what you're looking for?
yeah sorry, I don't think that's possible
no worries
no way i could like fork pycord and just change that? or is that pic a discord thing?
It's Discord's
is there no way to have no text or anything with the button? closest thing i found was using an invisible unicode thingy but that makes the icon off centre
i really dont see why id want a label or anything here-
ended up going with this- looks a lil better
Couldn't you have put the link button on the second (index 1 ) row?
i plan of having multiple buttons and they all just gonna have emojis so having one button thats a lil wider than the others wont look nice
like imma have at least another row hopefully full
ok whatever floats your goat
but yea ill see how i like this might change
If my bot is in 1,000 servers and I restart it. Do I need to wait some time before using guild.member if I wanna accurately fetch everyone?
You will need to wait until on_ready is dispatched
So, I'm responding to an interaction (when the user clicks a button) with another view. Is there any way to edit the original interaction and disable that button but still keeping the response to the interaction?
I've tried many different ways but none seem to work
Assuming you're subclassing view, inside the callback you'd do button.disabled = True and update the message by await interaction.message.edit(view=self)
Then you can reply with the new view
oh, and, I need to reply with the new view as an ephemeral message as well π
Pass in ephemeral=True while replying then
ephemeral doesn't exist for interaction.message.edit
No wait what are you trying to do
ephemeral can be only used in interactions
Here you wanted to disable the button so we used interaction.mrssage.edit
To send a new ephemeral message you'd want to do await interaction.response.send_message(..., ephemeral=True) if I'm not wrong
But if I edit the message first and disable the button, I get discord.errors.InteractionResponded: This interaction has already been responded to before when I try to respond to it
and if I disable the buttons after i've responded with the new view, it modifies the new view to the old one
You're supposed to disable the button first then edit the message
Can you show your code
I know, I am doing that
@discord.ui.button(label="Auto-setup", custom_id="autosetup", style=discord.ButtonStyle.blurple, row=0)
async def auto_setup_callback(self, button, interaction):
button.disabled = True
await interaction.message.edit(view=self)
await interaction.response.send_message("Do you wish to automatically configure the bot for this server?", view=confirm_auto_setup(), ephemeral=True)```
You get any errors?
Yeah. discord.errors.InteractionResponded: This interaction has already been responded to before
That worked, thank you so much π
Np π
bump
Depends on your code, but in my experience, discord just sometimes does that for no apparent reason (maybe ping or slow code, idk?)
If it doesn't affect your bot, then just ignore it.
ive added a cooldown for my cmds (1 hour) with slash commands and so when the error occurs, users have to wait an hour to run the command again which is majorly affecting my bot tbh and i need to get it fixed asap
ill send my code one second
@shift.command(description = "Send a shift start message in #sessions.")
@discord.guild_only()
@checks.mr_only()
@commands.cooldown(1, 3600, commands.BucketType.guild)
async def start(self, ctx: discord.ApplicationContext):
await ctx.defer()
e = discord.Embed(colour = 0x2B2D31)
e.title = "Bakery Shift"
e.description = "A shift is happening!"
nam = ctx.author.nick if ctx.author.nick else ctx.author.name
e.set_footer(text = f"Hosted by {nam}", icon_url = ctx.author.avatar.url)
e.timestamp = discord.utils.utcnow()
ses = self.bot.get_channel(1110287864262033510)
await ses.send("<@&1086399112922009650>")
await ses.send(embed = e)
await ctx.respond("Success! Shift successfully started.")
ignore indentation Iβm on mobile rn
Why are you... deferring?
I don't see any reason to defer in this code tbh
afaik ctx.respond can automatically defer if you respond after 3 seconds
before i was deferring i was still getting unknown interaction but I can try again
odd
Try without defer
Or.... use logger/profiler to check where you have bottlenecks
What hosting and pycord version?
How to check if bot has perms to mention a role in a specific channel
2.3.2 is my version
Afaik there is no permission to mention a role, if you can write message, then you can mention basically
But what if I'm not sure if the bot can mention that role
oh yes
Or that?
just request the permission when the bot is added to the server...
Thanks
But it's mention everyone
I don't think most people would give it
Well but to be able to use it, you have to request it nevertheless.
I just wanted to check something
I'll think about that later
thanks for your help
Wait
Whether that is before or after the bot joins you have to "ask" for it. Either in the bot adding menu or through some kind of message...
You can check it easily
guild.me -> bot Member
Member.guild_permissions -> Permissions
and mention_everyone
yes I wasn't sure if mention_everyone could mention roles
guild.me.guild_permissions.mention_everyone
thank you
I really hate it, but sometimes guild admins can randomly disable some perms
This is bad especially for perms like mention_everyone, because bot won't even get error when trying to mention
but usually that happens when inviting the bot, right?
You can just disable perms in roles menu
Or... Not give perms when inviting
But isn't the role "managed by the bot"?
oh alright, I thought you can't do anything with it xD
Yup
does anyone know how i would input the data that has been inputted into a modal into a database but the modal has been answered multiple times?
how can i get someones display name with the new user name system?
with the master branch
wdym?
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
@fervent wing
How do you plan on inputting it if it was only answered once?
i think ive found a way to do it. do you have any knowledge of databases?
Which Database?
mysql
What are you wanting to know?
okay so ive written this:
con,cur = openCON()
cur.execute(f"INSERT INTO details (userID) VALUES ('{interaction_1st.user.id}')")
con.commit()
closeCON(cur,con)```
however it doesnt insert anything
and i think thats why im getting an error later on
Still you should learn best practices
for your sql library, they'll show you the right way to do it
ill stick with f strings for now
if you are building a f-string.. print it is it valid SQL
it should work because ive used the exact same format before except this time its not inserting snything
should != is working
wdym?
do you want to troublehsoot the issue, or believe something that is not working "Should" work

i get an error later on mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE userID='1037772222145765406'' at line 1
con,cur = openCON()
sql = f"INSERT INTO details (order_details) VALUES (%s %s %s %s) WHERE userID='{interaction_4th.user.id}'"
data = [q1, order1, q2, order2]
cur.execute(sql, data)```
ID is an INT
You're mixing %s with f strings? whyyyy π just throw in one more %s
itβs easier
so howβd i eliminate the error?
in your DB schema is id an int or a string?
iβve got it as a BIGNIT
but you are comparing it to a string... which mysql wont do without you converting it...
so it will have to be INT?
so leave it as int
there is no need to set it to an int... the varable will be an int
so what data type shall i set it as
try this: userID={interaction_4th.user.id}
same error
print the completed f-string and test it in a mysql client so trouble shoot the query itself.. as this is not really a pycord issue
how do i end a previous user interaction if the same user initiates the same new interaction by using the same slash command
Can anyone explain to me why a slashcommand within a "cog" works fine for one, but when I try and add a second it just doesn't populate, neither does my code seem to reach the breakpoint and for the life of me I can't find out why! I have code readily available to read. I'm tearing my hair out.
are the methods for your slash commands the same name?
I literally copy and pasted my working slashcommand (with autocomplete) and changed the appropriate variables and function names and it doesn't work. Doesn't even breakpoint.
No
can you share the code please
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the "unitget" command and its associated autocomplete works perfectly fine.
however the mapget command refuses to even populate the autocomplete field
in mapget you take an argument gametype but your @option is named mapget
oh shit
when the command is called from the slash command
which name does it take the function name?
the names just need to match
right OK
for unitget they're both unit
completely overlooked it, you know when you spend so long looking at something
You sir are a legend.
happy to help π
Can someone please explain to me this docstring of discord.Member.add_roles():
|coro|
Gives the member a number of Role\s.
You must have the ~Permissions.manage_roles permission to
use this, and the added Role\s must appear lower in the list of roles than the highest role of the member.
Given this role structure in my server:
- Admin
- Mod
- User
- something
Does that mean that if the user has only the User Role, I cannot add the Mod Role to them? That doesn't make any sense in my opinion but maybe I'm understanding it wrong...
||Oh and since when does discord format - as bullet points lol?||
the bots role must be higher than the users highest role
yeah ok that's what I thought
its normal discord hierarchy, works the same way
So the docstring is just a bit wrong