#Basic Pycord Help (Quick Questions Only)
1 messages · Page 43 of 1
no def init?
How do I have to build them?
You don't have an init method in your class, and you never call init on the superclass
can client.run and bot.run be executed in the same script?
why do you have it like that?
Have it like what, sorry?
I'm just trying to use client events and bot events in the same script, but it doesn't seem to be working. Just separate them?
Why do you have both client and bot?
anything you can do with client you can also do with bot, there is no reason to have both, and it will obviously break your entire code
If I have a list l=[]
And this list is sometimes filled l=[[P]] and sometimes so l=[[]].
How can I check in an if query if the list has a content or not?
just check the length?
What am I doing wrong?
async def get_qmark(user):
user = user.lower()
qmark = []
async with aiosqlite.connect(DB) as db:
async with db.execute(
f"SELECT qmark FROM qmark WHERE user = ? ", (user,)
) as cursor:
async for row in cursor:
qmark.append(row[0])
if len(qmark) == 0:
qmark = ""
else:
qmark = qmark[0]
return qmark```
are you getting any errors?
TypeError: object of type 'type' has no len()
type 'type'?
I do not know that is in the console
and what is row[0]?
So I select from the DB actually always only one thing and it is always only in a letter such as P, L, B, etc..
I think you can solve the whole thing maybe somehow better than how I did it?
As return I would like at the end only the letter or a -.
Well I am not going to write code for you
If I fechtone() the cursor how can I take the content out of there or check if there is content in there?
You can check if the result is an instance of sqlite3.Row
I don't know 😄
?
can multiple @ options be defined?
yes
@discord.slash_command(guild_ids=config['main_guilds'], description="Mass deletes messages")
@commands.has_permissions(manage_messages=True)
@option("messages", description="Amount of messages to delete.")
@option("member", description="Specific member to delete from.")
so this is valid right
yes
great then, I must have an issue.
Here's the slash options example.
I created a forum then, https://discord.com/channels/881207955029110855/1053439936147239043.
this issue must be longer than I imagined, because that's what I've done yet it doesn't work.
Read rule 6 in #help-rules
sorry.
I asked here because I thought it was a smaller issue, like not being able to do two options. But it seems bigger so I moved to a forum.
Also pls stay in one channel
Hey, I'd like to make a bot that gives people points for chatting. So basically the more they chat, the more points they earn
How can I have my list of guild ids for a slash command be updated by another command? Can I just write it to an sql table then access that from a subroutine, and have guild_ids=subroutine()?
How would i go about implementing something like that?
databases?
Why do you need to do that?
If you know basic python, that will be not that hard
We won't help you write an entire bot, get started on your own and come back when you run into issues
bot is a premium only bot which will only work in verified server that get added by the person doing the command
So basically i keep a count of how many messages each user has sent?
And increment their points based on that?
exactly
Okay
You don't want to query a database on every message, so cache that data and write to the database on an interval or something
Oh i see
you should register it with a global command and add an internal check.
because you can get rate-limited if you do register too many commands (200) in a day.
Yea I had that concern in mind, thats why i asked
Also i was thinking of something similar with voice chats too, so like the more time someone spends voice chatting the more points they earn. But i was concerned about people idling in the voice chat. If they just join a voice channel and go afk, i dont want them to earn points for that duration. Only active chat time.
If there are many people in different voice chats in the same server, then you cannot track them all.
Just like a user can only be in one voice channel at a time
Oh i see
That makes sense
Thanks for the help guys, i think i can now draw a flow chart and start writing some code
gl hf
Eh no xd
ok?
Well, one vc/guild/bot.
yes.
per guild / gdm / dm
bots can call?
"like a user"
I mean the general limitation of voice connections
ah ok
would be fun tho if you could call with a bot 
how do i check if a user has a certain role?
member.roles returns a list of roles
i figured it out, but now im getting a response invalid interaction application command from the bot
nvm fixed it just somehow had two instances of the bot running
And we would frequently get add calles for callertunes and nitro recharges
:kekw:
Right now I’m trying to come up with an idea of a reaction roles system using buttons with each button giving a customizable role from the database. I was thinking of using on_interaction for this since I can handle all callbacks for a reaction role message (from a check) in one. Is there another way of doing this that’s more efficient? Since I don’t want to have to create persistent views over and over again every time the bot starts up.
is the max length allowed in ctx.respond shorter than ctx.send?
I noticed that certain messages don't send with ctx.respond that do with ctx.send
is the max length allowed in ctx.respond shorter than ctx.send?
what do you mean by "max length"?
If you mean character limit, it’s the exact same as they’re both classed as discord.Message
the maximum amount of characters in the reply.
then #998272089343668364 message ?ref
If you mean character limit, it’s the exact same as they’re both classed as discord.Message
yes ik, i typed it before u said that, i have shit wifi
All good :)
well I'm having an issue, a certain message isn't being sent through respond that is thru ctx.send
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.
thing is it's openai, so the responses are GPT, so it's not always going to be the same length.
hm wait yeah i can use a constant 1 sec.
You could make a custom function to trim down the text to the character limit of a message (4029 iirc)
Visit this link to see the note. Giving the URL to anyone allows them to access the note, too.
Could you please use pastebin? I don’t like clicking on sites that I don’t recognize for my safety.
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.
see here, im using a constant message to print out the alphabet 10 times? (26 x 10 = msg length). If I'm using ctx.send it obviously doesn't respond but prints the output.
sure, it's self hosted privatebin but ok.
https://pastebin.com/SRfB31T6 @rare ice
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.
For embeds, the character limit is 1024, so you’d need to meet that limit
but if u see, when I use respond, there is actually no response, instead there is no response.
I recommend using a custom function for trimming text for your use case as I mentioned #998272089343668364 message ?ref
You could make a custom function to trim down the text to the character limit of a message (4029 iirc)
No dude, you don't understand. The embed is the same right? but if I use ctx.send() it sends, but not with ctx.respond
Send your error like I said
Both functions are the same, but .respond completes the interaction
Send your code with the ctx.respond
well it's exactly the same except im using await ctx.respond(embed=e)
do I seriosly need to send u the whole code for that?
How long is the duration between you executing the command and you responding to it
Ohhh right, respond times out after 3 seconds?
smart man smart man
oh? I figured I could send "processing" and then edit it to reflect changes. that way the person doesn't think it's broken?
ctx.respond(processing) and then edit
I recommend deffering
alright.
So it shows the 'Bot is thinking…' state
You need to send the view along with some message content. Also bot.command is a Slash command if you are using discord.Bot .
You also don't respond to both the Slash cmd and the select menu interaction
From what it looks like, you’re using an api such as openai, perhaps there is an error there?
Oh that’s not how you do it
Defer the first thing in the call back
You need to defer at the first line of your callback
is it? cus i remember in discord.js the description limit is 4096. I thought that would apply globally to the API? https://discordjs.guide/popular-topics/embeds.html#embed-limits
I'm not suggesting that.
wait wait mb as in "my bad" or "mega bytes"?
just need to clarify.
I meant it as in my bad
sorry. autism.
You’re good
Is it possible to run a bot from an IPv6-only network?
is there like an event to check if a member ran a slash command? specifically one of it's own slash commands
I'm sorry what?
did I not make sense?
no, I'm afraid not.
like discord.on_application_command()
is this specifically the bots application, or any bots?
.rtfm on_application_command
discord.Bot.on_application_command_auto_complete
discord.Bot.on_application_command_error
discord.AutoShardedBot.on_application_command_auto_complete
discord.AutoShardedBot.on_application_command_error
discord.on_application_command
discord.on_application_command_completion
discord.on_application_command_error
bridge.Bot.on_application_command_auto_complete
bridge.Bot.on_application_command_error
bridge.AutoShardedBot.on_application_command_auto_complete
bridge.AutoShardedBot.on_application_command_error
Bot.on_application_command_auto_complete
Bot.on_application_command_error
AutoShardedBot.on_application_command_auto_complete
AutoShardedBot.on_application_command_error
just for your bot
k ty
wait so, I'm trying to check if a user id matches something, and then stop them from using all commands. I can give an ouput, but the command still works. Is there a way to cancel the command?
return?
yeah I did that, didn't work/
it still goes through with the cmd
You might be looking for checks
??
dont I have to apply that to all commands tho...
There are global checks too
And cog checks
Try looking for them in the docs
oh ok ty
I was misunderstanding the use, it seems. Thank you for clarification :)
I hve a command that I respond to using ctx.respond I want to know how I can edit the responded message since the following code doesn't work: py msg = await ctx.respond(embed=em) await msg.edit(embed=em2)
Also if someone responds please ping me
Hello
does anyone know any good Python ML API , just something where it can take some text and based on some preference it can determine how much I'd approve or disapprove of this text ?
Respond returns an interaction
Use edit_original_response
.rtfm edit_original_response
hi this is my code:
people = []
if len(people) != 0:
peoplestr = "\n".join(people)
people is a list with member objects. and i want to build a str with all the member.names but i cant do "\n".join(people.name)
how can i do it?
Easiest way is to just iterate over the member list yourself and append their name to the string
.embed limits
field amount = 25, title/field name = 256, value = 1024, description = 4096, footer text = 2048
Note that the sum of all characters in the embed should be less than or equal to 6000.
@chrome skiff ^
\n is just 1 character (a newline character)
So 4096/8
About 512 lines ig
32 characters
Holy shit I just sent an embed with 2048 lines of "E" and it just went on forever lmao
4096/32
Ah
No \n is just 1 character
^
Mhm
You can use a paginator
There is pages ext in pycord
.rtfm ext.pages
Target not found, try again and make sure to check your spelling.
Pff it's on the docs
Why tho
Yeah
It's a cool ext
Hmm
Have you tried "reading the error"
Error and code?
Also fix this first
Send full traceback
Also the code seems to be different from the error you sent
I can't see ctx.respond in the code you sent
Also don't use requests
.aiohttp
?tag aiohttp
Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(http://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean)
discord.py uses aiohttp, so it should already be installed. An example of code using aiohttp and discord.py:
async with aiohttp.ClientSession() as cs:
async with cs.get('https://httpbin.org/json%27') as r:
res = await r.json() # returns dict
await ctx.send(res['slideshow']['author'])
For more help, see aiohttp's documentation: <http://aiohttp.readthedocs.io/en/stable/>
requests is fine for non asynchronous projects. But it will block the event loop for async ones
The error explains it all
id is positional only, and you're passing it as a keyword arg
if interaction.channel.id == TICKET_CHANNEL:
guild = bot.get_guild(GUILD_ID)
for ticket in guild.channels:
if str(interaction.user.id) in ticket.name:
embed = discord.Embed(title=f"You can only open one Ticket!", description=f"Here is your opened Ticket --> {ticket.mention}", color=0xff0000)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
category = bot.get_channel(CATEGORY_ID1)
ticket_channel = await guild.create_text_channel(f"ticket-{interaction.user.id}", category=category,
topic=f"Ticket from {interaction.user} \nUser-ID: {interaction.user.id}")
await ticket_channel.set_permissions(guild.get_role(TEAM_ROLE1), send_messages=True, read_messages=True, add_reactions=False,
embed_links=True, attach_files=True, read_message_history=True,
external_emojis=True)
await ticket_channel.set_permissions(interaction.user, send_messages=True, read_messages=True, add_reactions=False,
embed_links=True, attach_files=True, read_message_history=True,
external_emojis=True)
await ticket_channel.set_permissions(guild.default_role, send_messages=False, read_messages=False, view_channel=False)
embed = discord.Embed(description=f'Welcome {interaction.user.mention}!\n'
'Hello, How can we help you?',
color=0xe800ff)
await ticket_channel.send(embed=embed)
embed = discord.Embed(description=f'📬 Ticket was Created! Look here --> {ticket_channel.mention}',
color=0xe800ff)
await interaction.response.send_message(embed=embed, ephemeral=True)
return```
How can i make this a certain role use only?
by that i mean, i only want verified people to be able to use it but not the unverified people.
thank you
where i can learn coding
So I am making a log function in my bot, I managed to log messages etc. but would it be possible to log images / files and if, how would I do that?
How do you use discord.Interaction.followup? The docs say to use this when wanting to send more than 1 messages, which I want to do, but I can't figure out how to use it.
Is this a command or a view
View
.lp
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
.rtfm message.attachments
You can get them from over there
Oh, thanks.
Where would i put it?
Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
No tag application.commands found.
?tag missing-access
No tag missing-access found.
?tag missing_access
If you get a Missing Access (50001) error, you probably forgot to add the applications.commands scope.
To fix that, just replace YOUR_BOT_ID with your bot id and visit this link: https://discord.com/oauth2/authorize?client_id=YOUR_BOT_ID&scope=applications.commands
I think I tried that without success but will try again, thanks!
@fervent cradle ?
also show code.
debug_guilds=[1052587155471474798, 1034903696271753266]
Is the bot in both of these servers?
With the app cmds scope
Hello, does anyone have an idea, how i could check if someone got an uprank or an downrank
What is an "uprank" and "downrank"?
hello guys
how can i do this slash command
async def deneme(ctx, ad="", soyad=""):
response = requests.get(f"api/ad={ad}&soyad={soyad}")
file = open(ad + ".txt", "w", encoding="utf-8")
file.write(str(json.dumps(response.json(), indent=2)).replace("/", "/").encode().decode('unicode_escape'))
file.close()
await ctx.send(file=discord.File(rf'{ad}.txt'))
os.remove(ad + ".txt")
an uprank is when a user get's a role that is higher ranked than the one he had before, a downrank is the opposite
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
async def deneme(ctx, ad="", soyad=""):
response = requests.get(f"api/ad={ad}&soyad={soyad}")
file = open(ad + ".txt", "w", encoding="utf-8")
file.write(str(json.dumps(response.json(), indent=2)).replace("\/", "/").encode().decode('unicode_escape'))
file.close()
await ctx.send(file=discord.File(rf'{ad}.txt'))
os.remove(ad + ".txt")
Use on_member_update and compare the member's previous roles to the new ones
https://docs.pycord.dev/en/stable/api/events.html#discord.on_member_update
And what is your issue?
slash command
how can i do this slash command
I'm not going to write code for you
I'm not dealing with
?
english translation is wrong
ok?
I try but it doesn't work
ok?
help me
How am I supposed to help you if you don't tell me what's wrong?
Even though I tried hard, I couldn't make this code as a slash command and put it in secret message mode.
Okay? What did you try? What errors are you getting? What isn't working?
And what is "secret message mode"?
i have no idea right now
Then I can't help you
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands
Here are the examples, if you can't understand them, you need to learn more Python
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/examples/app_commands at master · Pycord-Development/pycord
where to get debug guilds
Right click your guild and copy ID
@tasks.loop(minutes=10)
async def sortchannels():
await bot.wait_until_ready()
zugeteilt1 = bot.get_channel(categoryid)
channels1 = zugeteilt1.channels
sorted_channels = sorted(channels1, key=lambda c: c.name)
print(channels1)
print(sorted_channels)
if channels1 == sorted_channels:
print("pass channels1")
pass
else:
for i, channel in enumerate(channels1):
print(i, channel.position)
if channel.position != i:
print(channel.position, i)
await asyncio.sleep(1)
await channel.edit(position=i)
can anyone help me? this isnt working and i am getting no error. it doesent do print(channel.position, i) but it isnt sorted correctly?
So is there any way to prevent the "RuntimeError: Event loop is closed" error when using client.close() ?
is it my account?
what?
test channel id?
import asyncio
No? It's the guild id

await asyncio.sleep(5)
your guild id? what else?
we dont know your guild id
I don't know? Try it and see
how do i get away from this
Get away from what?
we don't know about this
w h a t?
we don't know what guild id is
??????
English translation
ok?

english translation is wrong
And what do you want me to do about that?
can anyone help with this?
Find a server that speaks your language, no one here is going to understand you
how is this supposed to prevent my Runtime Error. I made a /stop command but I dont want the raised error to show up in my terminal..
try except?
you mean me?
no
spaxter can you help me?
with this
Have you tried printing the index of the loop to see if your if check is true? Or checked if the sorting works as you think?
my print(i, channel.position) befor the if statement gives me this:
0 0
1 1
2 2
3 3
....
Yeah? So your if statement is never true because all of those are equal
payload = await super().send(content, **kwargs)
TypeError: _Context.send() got an unexpected keyword argument 'file'
@bot.command(
name="deneme",
description="This is the first command I made!",
scope=1049907644892188753,
)
async def deneme(ctx, ad="", soyad=""):
response = requests.get(f"https://api/AdSoyad.php?Name={ad}&Surname={soyad}")
file = open(ad + ".txt", "w", encoding="utf-8")
file.write(str(json.dumps(response.json(), indent=2)).replace("\/", "/").encode().decode('unicode_escape'))
file.close()
await ctx.send(file=discord.File(rf'{ad}.txt'))
os.remove(ad + ".txt")
error code:
Task exception was never retrieved
future: <Task finished name='Task-17' coro=<deneme() done, defined at C:\Users\api\Desktop\ArexOyunda\arexbot.py:26> exception=TypeError("_Context.send() got an unexpected keyword argument 'file'")>
Traceback (most recent call last):
File "C:\Users\api\Desktop\ArexOyunda\arexbot.py", line 36, in deneme
await ctx.send(file=discord.File(rf'{ad}.txt'))
File "C:\Users\api\Desktop\ArexOyunda\venv\lib\site-packages\interactions\client\context.py", line 445, in send
payload = await super().send(content, **kwargs)
TypeError: _Context.send() got an unexpected keyword argument 'file'
Could you run pip freeze and send the output here?
Oh you meant me?
can i make it so the bot makes a webhook not me making a link and adding to code
.rtfm create_webhook
thanks
Hey guys what am I doing here wrong?
Ignoring exception in view <View timeout=180.0 children=5> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='0HcZv1' emoji=None row=None>:
Traceback (most recent call last):
File "/Users/BiBi/Library/Python/3.11/lib/python/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/Volumes/Exharddrive/discordprojects/booleanTest/main.py", line 168, in yes_callback
await inner_interaction.message.edit(embeds=[embed], view=None, files=[])
File "/Users/BiBi/Library/Python/3.11/lib/python/site-packages/discord/message.py", line 1455, in edit
data = await self._state.http.edit_files(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/BiBi/Library/Python/3.11/lib/python/site-packages/discord/http.py", line 362, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
view = discord.ui.View()
verify = discord.ui.Button(label="Verify", style=discord.ButtonStyle.green)
view.add_item(verify)
async def verify_callback(interaction: discord.Interaction) -> None:
if role in interaction.user.roles:
await interaction.response.send_message("You are already verified", ephemeral=True)
else: # start
member = interaction.user
WELCOME_EMBED = discord.Embed(title="Challenge")
WELCOME_EMBED.add_field(
name="How to verify", value="Click one of the 5 buttons here under, check which one is the correct one that u see in the image.", inline=False)
words = [] # len must be 5
for _ in range(0, 5):
gen = await bot.generate()
words.append(gen)
verify_view = discord.ui.View()
random_choice = random.choice(words)
generated_img = ImageCaptcha()
generated_img.write(random_choice, random_choice + ".png")
for word in words:
btn = discord.ui.Button(label=word, style=discord.ButtonStyle.grey)
if word == random_choice:
async def yes_callback(inner_interaction: discord.Interaction) -> None:
if inner_interaction.user != member:
await interaction.response.send_message("This is not yours", ephemeral=True)
else:
verify_view.stop()
embed =discord.Embed(title="all done", description="Successfully did the verification.", color=discord.Color.green())
await inner_interaction.response.send_message("Test")
await inner_interaction.message.edit(embeds=[embed], view=None, files=[])
await member.add_roles(role, reason="Verification")
btn.callback = yes_callback
else:
async def no_callback(inner_interaction: discord.Interaction) -> None:
if inner_interaction.user != member:
await interaction.response.send_message("This is not yours", ephemeral=True)
else:
verify_view.stop()
await inner_interaction.message.edit("INVALID.", view=None)
btn.callback = no_callback
verify_view.add_item(btn)
WELCOME_EMBED.set_image(url="attachment://{}.png".format(random_choice))
await interaction.response.send_message(embed=WELCOME_EMBED, view=verify_view, file=discord.File(f"./{random_choice}.png", f"{random_choice}.png"), ephemeral=True)
verify.callback = verify_callback
embed = discord.Embed(title="Verification", description="Welcome, please click the **Verify** button to verify.")
await channel.send(embed=embed, view=view)
anyway i can make a cooldown for a slash commands?
just do it normally
Here's the cooldown example.
what is the difference between client.run client.start and client.login ?
oh and client.connect
If you read the docs you will find out
Yeah I just found out, sry
@discord.app_commands.command(name="addrole")
async def add(self, interaction : discord.Interaction): #target_user : discord.Member ,wanted_role : discord.Role):
perms = False```
Raises : Extension 'cogs.role_manage' raised an error: TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
It's not discord.Interaction, it's discord.ApplicationContext
I think they are using discord.py
This isn't discord.py, you're in the wrong discord
My "ctx" variable suddenly stopped working. No functions are being called from it:
Traceback (most recent call last):
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'respond'
And whenever I start up my bot, this error occurs:
Traceback (most recent call last):
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 534, in register_commands
desynced = await self.get_desynced_commands(
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 360, in get_desynced_commands
elif _check_command(cmd, match):
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 275, in _check_command
as_dict = cmd.to_dict()
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 844, in to_dict
"options": [o.to_dict() for o in self.options],
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 844, in <listcomp>
"options": [o.to_dict() for o in self.options],
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\options.py", line 318, in to_dict
"type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'
Errors when calling ctx.respond and ctx.send
Problem started when i configured a help command, and the error now wouldn't stop even after removing it
@royal pulsar Please run pip freeze and send the output
aiohttp==3.8.3
aiosignal==1.3.1
altgraph==0.17.3
async-generator==1.10
async-timeout==4.0.2
attrs==22.1.0
certifi==2022.9.24
cffi==1.15.1
charset-normalizer==2.1.1
cycler==0.11.0
exceptiongroup==1.0.0rc9
fonttools==4.34.4
frozenlist==1.3.3
future==0.18.2
h11==0.14.0
idna==3.4
joblib==1.1.0
kiwisolver==1.4.4
matplotlib==3.5.2
mpmath==1.2.1
multidict==6.0.3
numpy==1.23.1
outcome==1.2.0
packaging==21.3
pandas==1.4.3
pefile==2022.5.30
Pillow==9.2.0
psutil==5.9.2
py-cord==2.3.2
pyad==0.6.0
pycparser==2.21
pygame==2.1.2
pyinstaller==5.4.1
pyinstaller-hooks-contrib==2022.10
pyparsing==3.0.9
PySocks==1.7.1
python-dateutil==2.8.2
python-dotenv==0.21.0
pytz==2022.1
pywin32==305
pywin32-ctypes==0.2.0
scikit-learn==1.1.1
scipy==1.8.1
selenium==4.5.0
six==1.16.0
sniffio==1.3.0
sortedcontainers==2.4.0
sympy==1.10.1
threadpoolctl==3.1.0
trio==0.22.0
trio-websocket==0.9.2
typing_extensions==4.4.0
urllib3==1.26.12
wsproto==1.2.0
yarl==1.8.2
This doesn’t occur on its own, someone is obviously running a slash command.
This error I’ve never seen before
Try downgrading to 2.3.0 and see if it was an issue in that release
I use 2.3.0 and know it’s a stable release
so was rc1
Yeah
2.3.0 results to the same error
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1147, in on_connect
await self.sync_commands()
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 629, in sync_commands
registered_commands = await self.register_commands(global_commands, method=method, force=force,
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 529, in register_commands
registered = await register("bulk", data, _log=False)
File "C:\Users\vgshi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 359, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
Got this error when I downgraded to 2.0.0b7, a version I was using before
the slash command permissions were changed at this time
the earliest release with the new permissions system was rc1
It's the same error as 2.0.0b7
Update: I removed commands and it works fine
so the commands are causing something to happen
Is there a way to update the choices of a slash command in runtime?
Here's the slash autocomplete example.
oh i thought that was just for choices that already existed
This is probably stupid, but when a user interacts with my view i update the embed in the message, yet even then discord says the interaction failed, how do i stop that from happening
tried interaction.response.pong() but that didn't do the trick
.tag idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
Send code
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Accept order", custom_id="Accept-order-button", style=discord.ButtonStyle.primary)
async def button_callback(self, button, interaction):
message = interaction.message
embedL = message.embeds[0].copy()
embed = discord.Embed(colour=discord.Colour.orange())
embed.add_field(name=f"{embedL.fields[0].name}", value=f"{embedL.fields[0].value}")
embed.add_field(name="Has been accepted by:", value=f"{interaction.user.mention}")
embed.set_footer(text=f"{embedL.footer.text}")
view = OrderFinishView()
await interaction.response.pong()
await message.edit(embed=embed, view=view)```
It changes the embed and view on that message. Just don't know how to make discord think the interaction was ok
_ _
What do I do now?
I'm also guessing it's something to do with the decorators
it also says In 3: Application command names must be unique
That means you're trying to register multiple commands with the same name
problem is, none of my commands have the same name
im guessing there's another instance of my bot running somewhere
Resetting your token will close any running instances, but if you have an instance somewhere without knowing it you probably have bigger problems to deal with
reset the token, the problem still exists
so for some reason which I do not understand, this part of my code:
@client.event
async def on_connect():
print(colorama.Fore.YELLOW + f"\n ---------\nStarting {client.user}\n ---------\n")
@client.event
async def on_disconnect():
print(colorama.Fore.RED + f" ---------\nStopped {client.user}\n ---------\n")
try:
os._exit(0)
except:
sys.exit(0)
Is disabling my help command or atleast, it is making it a "NoneType"...
Error:
line 33, in help
cmd_help = client.get_application_command('help').mention
AttributeError: 'NoneType' object has no attribute 'mention'
if I remove the 2 event's it works fine.
Read the docs and you'll find out why
Should I be getting the RuntimeError: Event loop is closed error whenever I force stop the bot?
Yes
ok, so that's normal
and running any slash command results in the same error
I reduced it to one command, still doesn't work
In 1: Application command names must be unique
I've done some debugging:
I have 4 commands (including help command) but only 2 is found in the bot
fixed it:
changed @bot.slash_command to @commands.slash_command
I'd just like to know why it's like that
That's how they're decorated in cogs
Well you could make your own help slash command usually looks s bit more fancy... but I believe there's a default guide to it too. Of how you're "supposed" to make it.
https://guide.pycord.dev/extensions/commands/help-command
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!
might as well make my own
Anyone know how to properly justify (ljust, etc) emoji? Seems it will add more spaces (I guess since it resolves as a single character sometimes but then the number of utf8 characters when printed)
These columns should all be aligned.
Found this, which isn't perfect, but definitely makes things much better
https://github.com/jquast/wcwidth#example
How can i access my SQL database from a phpMyAdmin server?
I need some help I don't know my issue. I spammed prints but it isn't helping me. Basically when someone loses on the "green" or "blue" or "red" button it executes both if self.win_type == 1: and elif self.win_type == 0: in the async def update_embed(self): function.
It's running async def update_embed(self): twice somehow. And it's running the win / loss but I don't get it.
I am so confused.
How do I make a command that just uses numbers in the name?
aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.1.0
certifi==2022.12.7
charset-normalizer==2.1.1
discord-py-interactions==4.3.4
discord-py-slash-command==4.2.1
frozenlist==1.3.3
idna==3.4
multidict==6.0.3
mysql==0.0.3
mysql-connector-python==8.0.31
mysqlclient==2.1.1
protobuf==3.20.1
py-cord==2.3.2
requests==2.28.1
typing_extensions==4.4.0
urllib3==1.26.13
yarl==1.8.2
No people just chat in here
am I blind or is it not possible to add users as interested to a scheduled event?
Ig no
:(
Is it a shared host?
Or you might have hit the limit for maximum Slash cmd updates per day
Does your host have multiple discord bots with a single ip address?
Or do you have your own vps with you own ip address
They why are you using a pterodactyl panel?
E.g. how can I make a command that is something like </123:0>
discord.VoiceClient.user
discord.VoiceClient.voice_connect
discord.VoiceClient.voice_disconnect
discord.VoiceClient.warn_nacl
discord.VoiceProtocol
discord.VoiceProtocol.cleanup
discord.VoiceProtocol.connect
discord.VoiceProtocol.disconnect
discord.VoiceProtocol.on_voice_server_update
discord.VoiceProtocol.on_voice_state_update
bridge.Bot.voice_clients
bridge.AutoShardedBot.voice_clients
bridge.BridgeApplicationContext.voice_client
bridge.BridgeExtContext.voice_client
Bot.voice_clients
AutoShardedBot.voice_clients
Context.voice_client
VoiceChannelConverter
VoiceChannelConverter.convert
#883236900171816970
if someone has youtube linked to their discord account, is it possible to get heir youtube id
I don't think so
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
OAuth2 should get you enough data to get their ID.
If i will make a lot of persistence buttons, will this buttons influence performance of the bot?
No tag PyNaCl found.
How would I be able to make a mute command (not timeout) which keeps track of when someone should be unmuted? For instance if I mute someone for 10 days, and my bot restarts within that time the timer would stop (obviously).
Can someone help me out with this?
.
Using a timer would be a bad idea.
Why not log the time the mute has started and log the duration of the mute. Then every so often checks if the time has run up and then executes off of that. So log the time the command was run, if the bot restarts have the bot check for all previously logged timers and start it up again. Furthermore when you're dealing with timers you probably shouldn't be actively restarting your bot.
Or just have something else keep track of the timer like an API or something.
Who just ghost pinged me
I actually just thought of just putting a date, so timenow + 10 days and when the bot hits that date it unmutes that specific person
That'll still require a timer / something actively running which is not the best.
But it'll work.
hey i asked this a while ago and still struggling any help?
It's best to use the timeout feature. It's easy, it's designed for what you want, etc.
Well, not in my case heh, but I have to look into how to make a log for this nonetheless
Database.
And why not in your case?
Timeout is a better option.
They can't rejoin your server and bypass it either.
Because now you gotta make a on_leave and on_join tracking with role persist. Just more work.
Is anyone going to admit to ghost pinging me
You see, the bot adds a role to a specific user on discord but I have a minecraft server which then links to people ingame making them muted too. and if ingame mutes then in discord it mutes too
same for unmute
never worked with a database before, so this'll be fun
(I have no idea where to get started)
Then use json.
And don't even say json sucks because I've used it to store millions of text.
.
It's not the best. But it works.
This Discord is not expected help.
I've been waiting to for my question.
Worst case worst use sqlLite.
I know sorry, just have no clue and been trying a lot wheres your issue?
I doubt i can help but ill try
It's above
whats wrong w sqlite
So you wanna know how to add reactions or check the length of something?
Nothing is wrong with it. I'm saying if he wanted a good database.
I wanna have it so if the user only inputs two options, it uses a specfic set of reactions but it would have to check for how many options used
so len would work?
So you wanna detect if they reacted to two reactions?
No ill show with a screenshot
Ignore the white bit, It should check how many options have been used and IF two options were used it reacts on the message with tick and X
So if the user has more than 2 options do "x" ?
If two options react with tick AND x
Did you make the options optional?
Yeah
Hmmm
Just test for if choice2 was used.
Then void option 3, 4, 5, 6, 7, etc if option 1 or 2 weren't used.
I'm sure there is a better way but I don't really know a lot about slash commands.
alright
To my knowledge can't you set the options to "None"
Then use an if statement to see if they have content
Yeah i've got it set Default=None
.-. I've never used your music thingy before.
So if option == None:
?
But then you will have a lot of if statements
Yeah
Just make a for loop. Then iterate through them.
So none would check if nothing is there right
Well make a for loop. Then a counter to see how many entries were entered.
If the counter >= 2 then do something.
I'm not sure what a better method would be tbh.
I'm not well knowledged in Slash Command options.
I saw something on google with *options: str then checks if options > 10 then it wont work and all that stuff
not tried that tho
Well in the decorator you could put *, options: str
Then detect the arguments within options.
wym here
@command.command
async def(self, ctx, *, options: str)
if options > 2:
Oh thank you, is *, having all options or smth
It's either *, options: str or options: str, *
But I think it's the first one.
And yeah the * is saying infinite arguments.
But like I said I'm not sure if slash commands work the same way. In a normal command, it'd work. So maybe it auto-makes options in the slash command?
Seperating it from options.
alr
async def poll(self,
ctx: discord.ApplicationContext,
message,*,options):
await ctx.respond(message,f"hi")``` 1 option..?
NGL, don't use json. Use sqlite or mongodb. It's better to use
Have you checked the example?
Here's the basic voice example.
The PyNaCl library needs to be installed\
how so?
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
- MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
- PostgreSQL (Very popular and robust SQL based database management system)
- MySQL (Another popular SQL based system, good start for learning SQL)
This is pycord, not discord.py
How are you installing pynacl?
python3 -m pip install -U py-cord[voice]
from discord.ext import commands
from discord.commands import SlashCommandGroup
from discord import option
class pollCog(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
Poll = SlashCommandGroup("poll", "Different Poll Groups")
PollOptions = Poll.create_subgroup(
"pollcreate", "help", "anonymous")
@Poll.command(name="poll")
async def poll(self, ctx, message):
await ctx.respond(message, "Yes And No")
def setup(bot):
bot.add_cog(pollCog(bot))``` Why isnt it respnding?
responding*
do you use commands.Bot or discord.Bot?
commands
why do you use bot: discord.Bot? then
?tag replit
Read this to find out how you can install Pycord in Replit
Old instructions: https://web.archive.org/web/20211128084858/https://namantech.me/pycord/installation/#replit
New instructions: #998272089343668364 message
Changed it to discord.Bot, no error no work
do you still use commands.Cog?
Yeah
?tag clients
No tag clients found.
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
so should i just remove commands.cog or should it be discord.cog
if you use discord.Bot use discord.Cog for commands.Bot use commands.Cog
No tag ffmpeg found.
My bot is not getting message content in on_message despite having the message intent enabled at both runtime and in the portal
Message content is still there if its from an on_reaction_add event though
any ideas?
re-fetching the message in the on_message event gives me the content
do you have both message intents enabled?
intents.messages and intents.message_content?
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
@young bone
from discord.ext import commands
from discord.commands import SlashCommandGroup
from discord import option
class pollCog(discord.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
Poll = SlashCommandGroup("poll", "Different Poll Groups")
PollOptions = Poll.create_subgroup(
"pollcreate", "help", "anonymous")
@Poll.command(name="poll")
async def poll(self, ctx, message):
await ctx.respond(message, "Yes And No")
def setup(bot):
bot.add_cog(pollCog(bot))```
fixed
I cannot see the slash commands again....
How can i access my SQL database from a phpMyAdmin server?
await ctx.respond(embed=PollEmbed)
PollEmbed.add.reaction("1️⃣")``` why no reaction?
slash commands are returning an interaction
How can I track invites??
Wym?
do i need interaction.PollEmbed then?
How do I globally sync my bot again?
Just remove the debug_guilds = Guild_ID ?
nvm its empty string
?
emoji = ":one:1054045453005627482"
msg = await PollEmbed.add_reaction(emoji)``` updated
thanks
Hello
Why do I get when I type /menu my menu but also a message with "application not responding"?
Where is my error?
import discord
from discord.ext import commands
bot = discord.Bot()
class MySelect(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.user_select(placeholder='Wähle einen User')
async def select_callback(self, select, interaction):
await interaction.response.send_message("Hallo")
print(select.values)
class SelectMenu(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bot.command()
async def menu(self, ctx):
await ctx.send("Hallo hier!", view=MySelect())
def setup(bot):
bot.add_cog(SelectMenu(bot))```
use ctx.respond instead of ctx.send
Oh thanks!
I don't fully understand, would I have to get the original message then context=PollEmbed
How can I get the user ID of all selected users from select.values?
does ctx.author return User or Member, if it's User, how do I change it to Member?
The same way you do it normally
.
Do you even understand the library
Zer literally provided you the method here which returns the message
yes..
I sorta have it
await edit_orginal_response(content=PollEmbed)
how do i respond to a interaction after deferring it?
no
just normal command
@commands.command()
async def …(self, ctx):
await ctx.defer()
# do a lot of things
# now how do I respond
Data safety. And faster
^ fixed, ty
Yeah but i was confused
I thought i was meant to edit the message then react or smth?
Or do i just get orginal message then add
mkay, I'll look into it ty
You just get the message..
does pycord have https://discord.com/developers/docs/resources/application-role-connection-metadata in there lib yet
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
i dont understand it but i think its so you can setup roles through other websites like sub on twitch role and stuff
Not yet
is this what it is?
You can't move a user to a voice channel if they are not already in a voice channel before, can you?
How should that be possible?
I am in the process of creating a Select User Menu and then I want all selected users to be moved to a Voicechannel.
But this only works if the users are already in a voicechannel or not?
they have to be connected to a vc at the server
Yes exactly what I thought
Imagine if you could force someone into a vc out of nowhere 
Hmm 😂
no 
people would abuse it
Exactly
get.original.message?
get.original.message??
💀
how would you get the messsage with a prefix command?
I don't know that's why I'm asking 
Zervyrel literally provided you the link https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.original_message
You should read the docs and look at examples instead of just blindly guessing
He just doesn't know OOP, just tries to invent attributes and methods
I believe he's been told to learn python on multiple occasions, but I guess #help-rules is non-existent to some people

But seriously, if you don't know OOP in Python, learn it before asking questions here.
👍
can you check if someone is on a free trial of a premium plan?
I was wandering if it is better to have a single database connection for my bot, or open a new connection each time I have a request (Sqlite)
A premium plan of what?
I think they mean server subscriptions
If i will make a lot of persistence buttons, will this buttons influence performance of the bot?
Depends on what the buttons do, but if you're talking about just having the buttons, not really unless you have an unreasonable amount of them.
...with mediocre traffic.
Hello,
can someone tell me why my voice channel is not deleted when I leave it?
The bot event is not executed at all
import discord
from discord.ext import commands
bot = discord.Bot()
@bot.event
async def on_voice_state_update(member, before, after):
print("HIIIIER")
# Wenn der Benutzer den Voicekanal verlässt, entfernen wir ihn aus der Liste
if before.channel and not after.channel:
channel_name = before.channel.name
users_in_channel[channel_name] = [user_info for user_info in users_in_channel[channel_name] if user_info[0] != member.id]
# Wenn keine Benutzer mehr im Voicekanal sind, löschen wir den Voicekanal
if not users_in_channel[channel_name]:
del users_in_channel[channel_name]
await before.channel.delete()
def setup(bot):
bot.add_cog(SelectMenu(bot))```
as someone who understands the basic concepts of classes from reading code but have never used them in my own code because i just never saw a major advantage to doing so. should i learn how to use and start using cogs? had someone tell me that my code is "unusable" because i dont use them
how do I get those four buttons to not show up at all? use_default_buttons = False just seems to disable them
#1047189308131508306
well, the advantages of using cogs are organization and fast reloading (basically testing your bot on the go).
while using cogs isn't mandatory, it is certainly a good practice
And you still kinda need to get comfortable with using classes (and other OOP concepts) if you want to develop using pycord
so you might as well
I personally found my implementations to be more flexible when I used pycord with OOP.
You don't load extensions on on_ready
You do it after initializing the bot instance
And it's not a courtoutine either lol yes
Can I get a command's description using the bot instance?
.rtfm walk_application_commands
.rtfm applicationcommand.description
Target not found, try again and make sure to check your spelling.
.rtfm .description
discord.AppInfo.description
discord.PartialAppInfo.description
discord.Cog.description
discord.SelectOption.description
discord.File.description
discord.Embed.description
discord.Attachment.description
discord.Guild.description
discord.Template.description
discord.PartialInviteGuild.description
discord.ScheduledEvent.description
discord.IntegrationApplication.description
discord.Sticker.description
discord.StickerPack.description
discord.StandardSticker.description
discord.GuildSticker.description
bridge.BridgeCommand.description_localizations
bridge.BridgeCommandGroup.description_localizations
Cog.description
How I can go through the commands is clear to me but how to get the description of it is what I don't get. The class ApplicationCommand doesn't seem to have any attribute that fits
You are actually looking at a SlashCommand.
which inherits from App.Commands
Has anything changed with the context menu lately ? I'm restarting my old bot i haven't used for 2 months and they don't appear in the right click
E: works on my private server
It might take a bit for them to be registered by discord. (Although I think that is kind of short now.). Try restarting your discord client sometimes discord dosent update global commands correctly.
So I understand that await ctx.defer() can take an ephemeral boolean argument, which should match the later response.
Is there a way to account for a deferred interaction response that is normally visible, but might have something like an error/reminder message? I'd prefer error messages be ephemeral but successful response to be permanent.
Could you please explain what you’re looking to do?
I have this design issue in a few places, but a basic equivalent example would just be, say, a command that can only be used between 10 and 12 GMT. Silly scenario, but it works for this purpose.
If the user tried to use the command at 14:00 GMT, I'd want to reply with an ephemeral message reminding them of the restriction. If there are no issues, then I'd want to reply with a permanent response after it's deferred.
It sounds like this may not be possible with how deferring responses works
But I thought I'd ask
Maybe I can defer after the error checking and just handle an "already responded" exception?
But ideally the error reminders should also be deferred
Does anyone know of an easy way to add/remove buttons with callbacks from views based on the interaction conditions?
The only way I can think of doing this atm is adding a separate discord button function to the class if a condition is met.
@discord.ui.button()
async def mybutton():
pass
If logical_test == True:
my_view.mybutton = mybutton
I haven't tested to see if this will work yet. It seems like there should be a simpler way built into the library.
.rtfm add_item
.rtfm remove_item
@winter dagger ^
Not sure how I missed that in the docs, thanks!
cache the value of the vanity invite uses.
then check if it is different from
await member.guild.vanity_invite()
Why do you need to defer?
There's some database consulting and permission checking that occasionally takes longer than discord likes.
The commands in question work just fine, it'd just be tidier if their replies didn't time out sometimes
Would it be possible for you to check the time before deferring? Or do you need to know data from the database to decide to error or not?
Is it possible to check using a bot whether someone is on a premium role free trial, or the real thing?
No
You can't access nitro's information
Not nitro, the server premium subscriptions
Is it possible to remove certain global slash command(s) from a guild without needing to reboot the bot? and vice versa?
You need a role object
Not just an id
Or at least a Discord object
Here you typed role = discord.Role
Doesn't look like type hinting chief
I also don't think you can add a discord.Role object into a database
true
You have to use a collection in mongo
also i recommend you use an async lib for mongo, a non-async (sync) lib will make your bot have stutters if it's making a lot of requests
for example motor for python -> https://pypi.org/project/motor
"lag" refers to internet connection.
?tag blocking
No tag blocking found.
?tags
youtube, wavelink, virtualembed, usercmd, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, solved, snowflake, slashcommandmention, rie, restartcmd, requests, replit-install, replit, removeall, pythonserver, python, paste, oracle, option, oop, official, objects, notpycord, norepl, nojson, nohelp, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, localfile, learnpython, json, intents, install_slash, install_git, install, inline-fields, importerror, idw, ide, how2sql, guide, getalpha, get_x, get-help, funny, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, closing, client, buttons2, buttonlimit, bridge, breaking-changes, bitwise, asset, applicationcommands-registration-delay, aoclbcode, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel, CVE-2022-36024
i meant stutters
.rtfm fetch_role
Isn't a Discord.Object enough
or
Here's the fetch role example.
.rtfm get_role
that URL is invalid
Here's the get role example.
Because they're not examples in the repo
They don't exist
Squid provided you the documentation
actually, you're right
I'm sorry.
what tf is this
await get_role[]
The hell is get_role[]
and role = find["role_id"] doesn't return a list. Don't know why you're type hinting a list
But doing it wrong confuses you
adding await to something only applies if the function itself is async
#998272089343668364 message
Can anyone help me out with this question I asked earlier? I am really confused.
not to bump my message but still need an answer to this for my bot
I have a bot that backs up and restores guild data from one guild to another. The problem I'm facing is that when I create emojis, it creates the first 50 emojis, but stops the code at await ctx.guild.create_custom_emoji for the rest of the emojis.
Looking at https://discord.com/developers/docs/resources/emoji, it seems it may be a rate-limit error, but I don't think Pycord has implement a rate-limiting handler for ctx.guild.create_custom_emoji...
A server without boosts can only have 50 custom emojis tho
Well it's 37 regular emojis, and 13 animated emojis. Has not reached the limit of either of them
Then implement your own limit for the creation
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.red)
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction:
if "ticket-" in ctx.channel.name:
channel = bot.get_channel(LOG_CHANNEL)
closed = ctx.channel.name
fileName = f"{ctx.channel.name}.txt"
with open(fileName, "w") as file:
async for msg in ctx.channel.history(limit=None, oldest_first=True):
file.write(f"{msg.author.display_name}: {msg.clean_content}\n")
embed = discord.Embed(
description=f'Ticket closes automatically in 5 seconds!',
color=0xe800ff)
embed2 = discord.Embed(title="Ticket Closed!", description=f"Ticket-Name: {closed}\n Closed-From: {ctx.author.display_name}\n Transcript: ", color=discord.colour.Color.orange())
file = discord.File(fileName)
await channel.send(embed=embed2)
await asyncio.sleep(1)
await channel.send(file=file)
await ctx.send(embed=embed)
await asyncio.sleep(5)
await ctx.channel.delete()```
How would i make this work?
What's not working
Explain what's not working, rather then saying "why isn't this working"
if "ticket-" in ctx.channel.name:
^
IndentationError: expected an indented block after function definition on line 96```
Read the error...
it needs an indent after async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction:
So I know I should make 50 emojis within a given time per guild, but how long is that given time?
I was looking at discord developer documentation and:
Routes for controlling emojis do not follow the normal rate limit conventions. These routes are specifically limited on a per-guild basis to prevent abuse. This means that the quota returned by our APIs may be inaccurate, and you may encounter 429s.
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/container/main.py", line 97, in button_callback
if "ticket-" in ctx.channel.name:
NameError: name 'ctx' is not defined```
wtf am i meant to put
you can define ctx by adding it to self inside the __init__ function and passing it in when calling it
so use self?
self.ctx after you defined it in __init__, yes
so self.channel.name:
ok
ctx is interaction in this case
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.red)
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
if "ticket-" in self.ctx.channel.name:
channel = bot.get_channel(LOG_CHANNEL)
closed = self.ctx.channel.name
fileName = f"{ctx.channel.name}.txt"
with open(fileName, "w") as file:
async for msg in ctx.channel.history(limit=None, oldest_first=True):
file.write(f"{msg.author.display_name}: {msg.clean_content}\n")
embed = discord.Embed(
description=f'Ticket closes automatically in 5 seconds!',
color=0xe800ff)
embed2 = discord.Embed(title="Ticket Closed!", description=f"Ticket-Name: {closed}\n Closed-From: {ctx.author.display_name}\n Transcript: ", color=discord.colour.Color.orange())
file = discord.File(fileName)
await channel.send(embed=embed2)
await asyncio.sleep(1)
await channel.send(file=file)
await self.ctx.send(embed=embed)
await asyncio.sleep(5)
await self.ctx.channel.delete()```
Like this?
you haven't defined ctx in the __init__ function
You domt even need to pass ctx to the view init
so interaction.channel.name???
✨ Try it and see ✨
seems correct to me
make sure you adjust the other things in there too
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/container/main.py", line 114, in button_callback
await interaction.send(embed=embed)
AttributeError: 'Interaction' object has no attribute 'send'```
its interaction.response.send_message
thx
always happy to help 🙂
also, i could be wrong but i think you can send multiple embeds instead of sending them separately with
await interaction.response.send_message(embeds=[embed, embed2])
also, making sure your bot has the correct permissions is always good so you don't get flooded with errors about being forbidden
example:
try:
await interaction.channel.delete()
except discord.errors.Forbidden:
errorhandling
#Also has the benefit of if a different error happens, you'll know
i need it to send to a strict channel
which is why are they different
ah
What are some things I need to check in order to properly add a role?
how can i use to different view sends on 1 embed?
Because even though my bot has administrator permissions, it's still not adding the role
Role must not be higher than the bot, I know that
Other than that, not sure
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.red)
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
if "ticket-" in interaction.channel.name:
channel = bot.get_channel(LOG_CHANNEL)
closed = interaction.channel.name
fileName = f"{interaction.channel.name}.txt"
with open(fileName, "w") as file:
async for msg in interaction.channel.history(limit=None, oldest_first=True):
file.write(f"{msg.author.display_name}: {msg.clean_content}\n")
embed = discord.Embed(
description=f'Ticket closes automatically in 5 seconds!',
color=0xe800ff)
embed2 = discord.Embed(title="Ticket Closed!", description=f"Ticket-Name: {closed}\n Closed-From: {interaction.user.display_name}\n Transcript: ", color=discord.colour.Color.orange())
file = discord.File(fileName)
await interaction.channel.send(embed=embed2)
await asyncio.sleep(1)
await interaction.channel.send(file=file)
await interaction.response.send_message(embed=embed)
await asyncio.sleep(5)
await interaction.channel.delete()```
This view and another view ill send both need to be sent onto the same embed
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Staff Application", style=discord.ButtonStyle.primary)
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
modal = MyModal(title="Staff Application")
await interaction.response.send_modal(modal)```
I have an async function that is meant to run in parallel with the bot. How do I make it so that it runs parallel and doesn't interfere?
You can either run it as a task, or use the bots asyncio event loop
https://docs.pycord.dev/en/stable/api/clients.html#discord.Client.loop
could you assist me?
You can't send multiple views on one embed
how can i do this then?
Create an instance of each view, iterate over the items and add them to a new view
any examples?
" iterate over the items and add them to a new view" how would i do this part?
Loop over each view's children and add them to your new view
How do you do an AThere mention, I tried searching and it's just a bunch of people saying "here" 
Just type @here
how to use reactions in bridge commands 
Error
Bot is online
Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "C:\Users\Zalama\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Zalama\OneDrive\Documents\GitHub\Grinder_Co\data\cogs\reaction_role.py", line 85, in on_raw_reaction_remove
member=guild.get_member(payload.user_id)
AttributeError: 'NoneType' object has no attribute 'get_member'
Code
@commands.Cog.listener()
async def on_raw_reaction_remove(self,payload:discord.RawReactionActionEvent):
guild = self.bot.get_guild(guildID)#server_ID
member=guild.get_member(payload.user_id)
if member.bot != True:
try:
with open(configFile) as fp:
ID = json.load(fp)
ID1 = ID["rrID"]["RRID"]
Create a thread @vale heath and show us your code and error there
ok
done
hi! Does anyone know how to send an embed with no name in the field like mirai does
theres some stackoverflow threads that say to use \u200b but that doesn't work for me
ayy figured it out just need to use embed.description
Hi! I'm looking for a recommendation, how should I test my discord bot which is composed only by commands? Is it possible to use pytest for this?
just use nodemon to restart after you safe the file
what?
nvm.. you have to run the command at discord to test it
yes but how hahaha that's my question
I was thinking about something like this but for that I need to make a class out of my Discord bot that currently it's a script (how can I make my bot a class? If I try to get all the code into a class my @bot.command does not work)
import pytest
import pytest_asyncio
@pytest.mark.asyncio
async def test_command(bot, message):
# Set up the message object with the appropriate content and author
message.content = "!command arg1 arg2"
message.author = bot.user
# Send the message and wait for a response
await bot.process_commands(message)
response = bot.last_response
# Assert that the bot responded with the expected message
assert response == "expected response"
I dont use pytest so...
never mind I can figure that out myself, my real question is -> How can I create a class out of my discord bot script? I had everything in a raw python file and now I want to make a class out of it, do you know if there is documentation about this?
sup, does anyone know how to make the slash command send a response that only you see?
Anyway to either get a message by content without fetching all messages?
Or is there a way to use the discord search?
ephemeral is probably what you’re looking for
.rtfm channel.history
That's the only thing tbh
No
Best approach is using history
Oh I'm late lmao
get channel.history and iterate through it a set check which checks if the content has the content required, etc
is there a way to have 2 bots communicating with each other when they are on the same computer?
Set up a web server on both and use http requests between them
how?
i mean how do i set up the web server
You can use something like aiohttp to set up a web app that listens for requests
thx
I have this view class which is a role select, I'm wanting to have an __init__ argument which would be the max_values of the role select. however you cant access self when defining a select menu decorator. is there any way around this?
class RoleSelect(discord.ui.View):
def __init__(self, max_values:int=5):
self.selected_roles = None
self.interaction = None
self.max_values = max_values
super().__init__(timeout=300)
@discord.ui.role_select(placeholder="Select roles...", min_values=0, max_values=self.max_values)
async def role_select_callback(self, select, interaction):
self.selected_roles = select.values
self.interaction = interaction
self.stop()```
I think you can do something with global variables, not sure if there's a better approach
global max_values
class RoleSelect():
def __init__(self, max_vals):
global max_values
max_values = max_vals
Create the select in the init using the actual select class and not the decorator
yes thanks
global max_values
class RoleSelect(discord.ui.View):
def __init__(self, max_selections:int=5):
self.selected_roles = None
self.interaction = None
global max_values
max_values = max_selections
super().__init__(timeout=300)
@discord.ui.role_select(placeholder="Select roles...", min_values=0, max_values=max_values)
async def role_select_callback(self, select, interaction):
self.selected_roles = select.values
self.interaction = interaction
self.stop()```
said `max_values` is not defined in the decorator
Can you manually create the select menu instead of via decorator
This is often the case, yes, having to query the database before deciding to error.
It sounds like I may just have to take an L on this one and leave it or compromise on message visibility
I have not actually tested it. Do you have to send a visible message to a visible defer and an ephemeral message to an ephemeral defer?
Does it throw an error?
The ephemeral value in the defer statement overrides anything in the respond statement. I was mainly wondering if anyone had found any sort of clever workaround apart from going through errors before deferring
Once Option() has choices set for a slash command, is it possible to update the choice list?
without a restart
I'm on phone and having troubles finding. Does defer have a defualt visibility? Or can you leave it blank
is it possible to detect when my bot is added to a server?
Its possible but there is no clean way to do it you might want to check out autocomplete.
Yes, on_guild_join()
yikes, i see, i can make a work around using autocomplete its just i was hoping for 2 values
thanks! I missed it somehow
my api server is intergrated into my bot and i run a websocket in it, i was hoping to be able to list the names of the connected client and then select them for it to supply the websocket connection ID
I think you would have to remove the original command
Manually create a new command with different args. Sync commands.
I dont think discord intends for this behavior so it might be buggy to
oh god
It's not a required argument so there would have to be a default. I believe it defaults to False
but i guess i can just make it find the websocket ID via the name
just keep updating the autocomplete
in a loop
well update a bot variable
how do make a option in a dropdown menu give you a role when selected but when unselected removes it?
Is it something that could be done with something like a dropdown menu? Those can be generated depending on where the command is used or who is using it
Autocomplete gets called you would not need a loop. Just get the info when the autocomplete function is called.
oh yeah lmao
.nohelp
Nobody helps you? See #help-rules #4, then you know why.
read the error
you also provided different code compared to your error, so i can't help you 
you havent defined a discord.Role object as role

what the hell is find :=
Hello :) How do i make a Slash Command that is available on all servers that the bot will join?
dont set guild_ids
.guide
Okay if thats it Thank You :)
@bot.slash_command(description="Sets the channel as the AI Harald Channel", name="setchannel")
@default_permissions(administrator = True)
async def setchannel(ctx)
Is that right?
this code you had was fine
damn it only works one time and after that the command isnt available anymore
ctx.respond and not ctx.send
.rtfm guild.get_member
Why it's giving me NoneType error 😑
Because you don't have member intents enabled
how to write a PM to a user through a bot, having only an id?
#1054285615560130582 message
It needs to be enabled in the developer portal too
Get the user from the ID and send them a message
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.get_or_fetch_user
Keep in mind that you can't DM someone unless they share a server with your bot, and their DMs needs to be enabled
user = await get_or_fetch_user(user_id) ?
It's a method of your bot instance
It's already enabled
Hey all, hope your are fine, I need to edit a ephemeral message sent like that (see capture below, can I do it with the returned Interaction id ?
Then use fetch_member, get_member only works if the member is cached
You can't edit ephemeral messages
#1054285615560130582 message
I did tried 🤔
Why are you asking for help in this channel if you already have a thread?
😭 very bad
Not really, it makes perfect sense
I was already referring to my thread 😐
Stick to your thread
I need the bot to be able to write letters but is not located at all on the servers
You won't be able to 🤷♂️
You can't DM someone unless you have a shared server

Is this a discord limitation?
Yes. Of course it is.
Imagine if bots could DM you out of nowhere, scammers would abuse that to no end
I can, if he has not blocked for non-friends ;-;
What?
As I understand it, a person can write to a random person, but a bot can't write to a person without shared servers?
A person can't write to a random person either. You need to share a server, or have them added as a friend
Yes you can lol
Since when?
People write to me to insult me even though we don't have shared servers and we're not friends, magic?
How do you know they didn't just leave the server after DMing you?
No, I'm not on this server for a long time and that's it! Only there is my server which is only for my friends.
I changed my account due to the fact that a lot of bots wrote to me, while I was not on any server, and there were no friends on the account
Is there an way to create a role that is seperated from others with the bot?
what do you mean by "separated from others"?
you know the option you can tik when creating or editing a role that it displays users with the role seperated from others. is there a way to do that with creating a role with the bot?
Did you read the docs? 
i tried
So what do you think this is?
interesting
I'm guessing you didn't actually read the docs
You don't define a role. You get it using https://docs.pycord.dev/en/stable/api/models.html#discord.Guild.get_role
Is it a coroutine?
???
Read rule 1 in #help-rules

it isn't
Learn Python before making a bot
Spiderman doesn't know python 
Once again, read rule 1 in #help-rules
Does anyone know how to pass info through extentions / cogs to other ones
I have a cog managing something for my server that another cog needs to access a list from
class Cog1:
def __init__(self, bot):
self.bot = bot
self.some_list = []
class Cog2:
def __init__(self, bot):
self.bot = bot
self.some_list_copy = Cog1.some_list # <---- idk where to get this from cross file
