#Basic Pycord Help (Quick Questions Only)
1 messages · Page 6 of 1
is this just a name change?
you now check permissions from the channel instead of the member
so if before you were doing ctx.author.permissions_in(ctx.channel), it would become ctx.channel.permissions_for(ctx.author)
as one example
I see
this is more inline with how discord shows permissions to the user (i.e. opening a channel's edit menu to see all user and role permissions)
yeah its a pain to change it everywhere 
definitely cool for new coders but migrating is e.e
if it wasn't now, you're more or less guaranteed to run into breaking changes somewhere along the line
ultimately just a part of development
yep
hi guys, trying to set up a venv for my bot repo and it is an absolute nightmare lmao
i'm using vscode as my ide
when i made the venv it automatically detected it and asked if i wanted to switch to it, i said yeah
all good so far. but when i install stuff with pip, it installs to my global packages, not to my venv
and when i run where python i get my global installation in program files or whatever
pretty sure vscode also has a ui interface for package management for your venv
oh really ???
shouldnt this be working ??
this is using normal cmd prompt, when i try to activate the venv in the default vscode bash terminal it doesn't even recognise the command
python -m pip
ughhhh yep that was it lmaoo
installing that now, thank you
does pycharm have source control tools? might install it
you mean git?
yeah sorry
What would be the best way to repeat a command? I’m sending a request and if the return containers a certain word I want it to just retry instead of them manually retrying the command.
pycharm's awesome but do note it's fairly different to vscode so if you're comfortable with vs then you might not enjoy the switch
is it a slash command?
Yes
use a command mention
i've used vscode for quite a while - if it'd be a rly steep learning curve then i might stick with it
so they click and enter
^ either print a mention, or if you want it to be "automatic" then you'd need to give them some sort of component to reinvoke it with a new interaction token
all good
you're welcome
I’m currently using ctx.invoke which works but when the command is invoked ctx.respond doesn’t work. So it sends the request but there’s no user feedback because it can’t respond. Would there be anything I could do with that?
ctx.invoke would be preferable to use with a new interaction token like i explained before
e.g. send a button, and in the callback py ctx.interaction = interaction await ctx.invoke(...)
Alright ty
https://hastebin.com/yerafaciri.rust - error
whitelisted = fields.ManyToManyField("Bot.UserModel", on_delete=fields.SET_NULL, null=True, related_name="whitelisted")
vanity_whitelisted = fields.ManyToManyField("Bot.UserModel", on_delete=fields.SET_NULL, null=True, related_name="vanity_whitelisted")
That error is coming from those 2 lines...
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
why is the value empty?
Hello, peoples. what is this error ?
the conflict between the discord namespace with py-cord and discord.py
How long should I expect Bot.wait_until_ready() to take on a bot in a few hundred servers?
Maybe a few seconds -10 seconds depending on your host and latency?
what was the class in which pycord auto converted normal commands to slash commands, was that on a seperate branch altogether?
b!rtfm pyc bridge
discord.ext.bridge.AutoShardedBot
discord.ext.bridge.AutoShardedBot.Bot.add_bridge_command
discord.ext.bridge.AutoShardedBot.Bot.bridge_command
discord.ext.bridge.Bot
discord.ext.bridge.Bot.add_bridge_command
discord.ext.bridge.Bot.bridge_command
discord.ext.bridge.BridgeApplicationContext
discord.ext.bridge.BridgeCommand
discord.ext.bridge.BridgeCommand.add_to
discord.ext.bridge.BridgeCommand.get_application_command
@royal spindle
so will ctx.send be converted to the ephemeral type in the slash command version of the same?
no, but ctx.respond will
so will the followup be automatically implemented?
text-based will be a reply
if i use ctx.respond 2 times
it does?
so if i disable the normal counterpart by doing client.get_command
will the slash version also get disabled?
I was actually looking for this class for this reason
the normal command has a boolean .enabled
you can’t if the server doesn’t have access to them in the first place
How can i get category id
whats the pblm here:
type_: Option(str, 'Choose Global or server leaderboard', choices=['Global', 'Server'], default='Global'),
order: Option(str, 'Order of Leaderboard', choices=['Ascending', 'Descending'], default='Descending')```
docs say providing default sets required to False, but still discord shows it as required argument while testing
how can i see in what servers my bot is
bot.guilds
just in case, can you set required=False anyway?
not directly, but you can use channel.history and then filter by the author of each message
https://docs.pycord.dev/en/master/api.html#discord.TextChannel.history for usage
?
how do i properly add a function to be executed before the main command invocation in a slash command? like before_invoke() but i couldn't get it to work with slash commands
still same response
should show | +2 optional
also cant send command leaving blank, so required not working in this case
Hi, so i have a question, i can make buttons, directly in the command? After @bot.slash_command, because i only need that button in one command, and it need a parameter of the command.
i've seen bots where it's possible to upload files with slash commands - how do I do that with pycord?
Typehint discord.Attachment for the option
Depends on what you're trying to achieve.
i'm still confused 
async def cmd_callback(ctx, attachment: discord.Attachment)```
Or you can also use Option
async def cmd_callback(ctx, attachment: discord.Option(discord.Attachment, "Drop a file"))```

comment out the command decorator, restart the bot, uncomment it and restart again
apparently there's a bug where options don't refresh without removing the command and adding it back
just tried this and got this

Can you show your code?
import discord
from discord.ext import commands
from discord.commands import slash_command
from discord.commands import Option #Importing the packages
import datetime
import json
config = json.load(open("config.json"))
class balls(commands.Cog):
def __init__(self, bot):#to Initialise
self.bot = bot
@slash_command()
async def cmd_callback(ctx, attachment: discord.Option(discord.Attachment, "Drop a file")):
await ctx.respond("Okay")
def setup(bot):
bot.add_cog(balls(bot))```
I want the button add a role to the member who clicked
Then no. Subclass ui.View outside your commands class
Alright
you forgot self
also current warning, discord seems to have broken attachment options which will error on the client https://github.com/discord/discord-api-docs/issues/5267
yeah it works now but where does the file go 
unless that's part of the problem in the github issue
how do i make a slash command that is only visible and usable by the bot owner
i don't think this is possible, but you can check if the user has a role or is the owner and then give different responses
ah, alright
Can we help?
Can you show the pip list?
Hey guys, I have 3 dropdowns and I’m trying to use all 3 selections for a query. Is there an easy way to pull all 3 values? Right now each one is a local variable within the callback
instead of pip install type "pip list"
just open cmd and type "pip list"
here
wtf xD
Thx you
Is it possible to send a message through timeout
I made a button with a callback function and id like to add a timeout to that, how would one?
the view
b!rtfm pyc discord.ui.View.timeout
oh ok
Is there any way I can host the docs page locally? I'm currently on holidays and don't have decent internet so loading the docs takes a while longer than I would like.
You can download it
I've downloaded the 'docs' folder from the github page, but don't know how to run it.
Hmm i dont think that will work
I only want it to respond to one user
But the whole server tho be able to interact with it
you said a timeout
Yeah? What else would you call it
To timeout if the user does not interact within x seconds
yes thats a view timeout
Yeah tho that wont really work in my case as everyone can see the button
But it only responds to one person
Does waitfor work for buttons?
then you're looking for an interaction check to check that the interaction.user is the person who ran the command
Im pretty sure you could do it using that
b!rtfm pyc discord.ui.View.interaction_check
hey guys so i use this code for a command, but i just noticed that the response is really slow, is there anyway i can speed up the response
@commands.slash_command(name="clown", description="make someone a clown")
async def clown(self, ctx, *, clown_guy: Option(discord.Member, "who's the clown out here big man?", required=True)):
await ctx.defer()
try:
clown_payload = {'image': clown_guy.display_avatar.url}
clown_src = requests.get('https://luminabot.xyz/api/image/clown', params=clown_payload)
clown_upload = imagekit.upload(file=clown_src.url, file_name="clown.jpg", options={})
clown_embed = discord.Embed(title="New clown for the circus!")
clown_img = clown_upload['response']['url']
clown_embed.set_image(url=clown_img)
await ctx.respond(embed=clown_embed)
except Exception as clown_err:
await ctx.respond(information.error_message)
print(f"Something went wrong with the clown command: {clown_err}")
How can i get category id
b!rtfm pyc discord.CategoryChannel.id
since you're getting someone from an API, it depends on how long the api takes to get you that response. indefinitely depends on the api latency/response time.
oh, so except for changing my api there is nothing much i can do for a faster resp?
not that I know of no.
ok
Also make sure to refresh your token since it's exposed now
should the image be deleted
whats the error raised when trying to build a member from non existing id?
Found it
Install sphinx locally, and run make html to generate the HTML files locally. Also install the docs extra requirements as well
whats up with this error, whenever i try to restart/stop script, it reloads cogs again and throws this err
Usually the case when u didn't await something in the code
but i cant find anything, also error is not pointing where the code is blocking
hm can u send the code ?
uhmm its a whole bot divided in 10+ cogs
#1004777736222539826
i just need the main.py file, which is the file that the bot runs as
this is the part of loading of cogs, it has no issues since 2 months
when i stop the script, bot adds cogs again which results in an error, then script finally goes off
Do messages ignore the delete_after parameter if the message is also ephemeral? I can't get mine to timeout at all
what is this error ?
if you click on the three dots in your file thing and click "show hidden files", what does it say?
nothing
mention me when reply a message from me
One message removed from a suspended account.
One message removed from a suspended account.
Can me Help Me?
add a ) at the end of the line
basic python?
yep
Who is it?
botinfo ()
^
you opened two ( but only closed one of them
the space doesn't matter
do you know basic python?
I watched 2 videos so medium
Year
Python
pls learn basic python first
write some code in the function or just write pass
@bot.slash_command(name="botinfo", description="Zeige Infos über den Bot")
async def botinfo(ctx, user:Option(discord.Bot, "Ping einen Bot", default=None):
Yes but where?
Könntest du bitte erst basic python lernen?
if you want to write code inside the function you add it on the next line
sonst wirst du viele probleme dabei haben
Also deutsch?
eigentlich nein
Thx
okey
also nicht in diesem channel
if imma be honest, i actually learnt python from making a discord bot in discord.py
Ich weis halt nicht was Lssa_VKP meint
how can I get the view from an interaction object?
lass mal eben zu #international-chat gehen
View.from_message(interaction.message)?
i think, yeah
How do I send a message to a specificied channel
await channel.send() iirc
And how do I define a channel by it's id?
channel = client.get_channel(id)
guild.get_channel(id)
or channel = guild.get_channel()
i don't think it needs await tho
oh wait that's true
if you use fetch_channel you need await if you use get_channel not
i forgor
or fetch_guild
My bot for some reason returns an empty string instead of the message.content. Anyone know the reason?
?tag intents
https://docs.pycord.dev/en/master/intents.html
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)
you need the message content intent
it kinda new. discord only started enforcing it in API version 10 and will start enforcing it in all version at the end of this month i think.
the part loading the cogs should work fine. probably one of the cogs i think
yes
ok thanks, my bot works again
Hello 🙂 How can i get all these bans? Will guild.bans(limit=999999) work? Thanks
would limit=0 work?
Thank you, I will check by trial and error 🙂
https://hastebin.com/yerafaciri.rust - error
whitelisted = fields.ManyToManyField("Bot.UserModel", on_delete=fields.SET_NULL, null=True, related_name="whitelisted")
vanity_whitelisted = fields.ManyToManyField("Bot.UserModel", on_delete=fields.SET_NULL, null=True, related_name="vanity_whitelisted")
That error is coming from those 2 lines...
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@grizzled sentinel Do u mind checking this issue?
Im not sure, its an issue with whatever lib you are using for your database. To me it looks like a lib error and not an user error. I would check there github for a similar error or contact there support
This might be of use as well -> https://stackoverflow.com/questions/7302619/operationalerror-operationalerror-unable-to-open-database-file-none-none
I'm having trouble adding multiple select dropdowns to a message. I assume it's possible but can't get it to work. I figured this would work but it's not: class TemplateSelection(discord.ui.View): @discord.ui.select( placeholder = "Choose X", options = options_list ) @discord.ui.select( placeholder = "Choose Y", options = options_list )
if you're doing it with decorators, they have to have their own unique functions
i.e. ```py
@discord.ui.select(...)
async def callback_a(self, select, interaction):
...
@discord.ui.select(...)
async def callback_b(self, select, interaction):
...```
Gotcha. How would I do it without decorators? I'm pretty new to the library
if you want it without decorators, you can construct them and assign the callbacks separately ```py
Notice capitalization
select_a = discord.ui.Select(...)
async def callback(self, interaction):
...
select_a.callback = callback```
this would make it easy to assign the same callback to multiple components, but you should ensure to use custom_id in the select menu to properly validate the input
Okay, I think I see how that goes together.
As for the message itself, how would I get both of them to show at the same time?
(also those code samples were written with the assumption you're doing them inside your view class)
if you're subclassing discord.ui.View:
- if you're using decorators, it'll be assigned to the view automatically
- if you're not, you should do
self.add_item(...)
then when sending the message, you just pass in view=... as a kwarg
Okay, got it. I'll fiddle around with this and see how it goes. Still getting used to Python object stuff
Thanks!
all good
its not that honestly
some value is empty
its similar tho i don't see a fix for it tho
do you know how to send the data of modal interaction response to a specific channel I have tried everything and it won't work
how do you check if someone has an avatar or not? this will make the bot send an error if the user has the default i'm pretty sure
.display_avatar.url
class DiscordColorField(fields.IntField):
def __init__(self, default=settings.colors.embeds, **kwargs):
super().__init__(default=default, **kwargs)
self.validators.extend([MinValueValidator(0x000000), MaxValueValidator(0xFFFFFF)])
def to_python_value(self, value: int) -> discord.Colour:
return value
Option(
ColourNameConverter,
name="color",
description="Color of the Welcomer embed if in embed mode",
autocomplete=color_autocomplete)
NAME_HEX_MAP: Final[Mapping[str, int]] = {color['name']: int(color['hex'][1:], base=16) for color in RAW_COLOR_MAP.values()}
COLOUR_NAMES: Final[list[str]] = list(NAME_HEX_MAP.keys())
def color_autocomplete(ctx: discord.AutocompleteContext):
return sorted(color for color in COLOUR_NAMES if color.lower().startswith(ctx.value.lower()))[:25]
class ColourNameConverter(Converter[discord.Colour]):
async def convert(self, ctx: Context, argument: str) -> discord.Colour:
try:
return discord.Color(value=NAME_HEX_MAP[argument])
except KeyError:
raise BadColourArgument(argument)
example of color
why is the keyerror rising?
Do cogs increase performance?
it shouldn’t affect performance.
paginator doesnt seem to work
class fun(commands.Cog):
def __init__(self,bot):
self.bot = bot
self.pages = [
"Page 1",
[
discord.Embed(title="Page 2, Embed 1"),
discord.Embed(title="Page 2, Embed 2"),
],
"Page Three",
discord.Embed(title="Page Four"),
discord.Embed(
title="Page Five",
fields=[
discord.EmbedField(name="Example Field", value="Example Value", inline=False),
],
),
[
discord.Embed(title="Page Six, Embed 1"),
discord.Embed(title="Page Seven, Embed 2"),
],
]
self.pages[3].set_image(url="https://c.tenor.com/pPKOYQpTO8AAAAAM/monkey-developer.gif")
self.pages[4].add_field(name="Another Example Field", value="Another Example Value", inline=False)
@commands.Cog.listener()
async def on_ready(self):
print('fun cog ready')
@commands.slash_command(name="meme", description="Generates a random meme")
async def meme(self, ctx):
paginator = pages.Paginator(pages=self.get_pages())
await paginator.respond(ctx.interaction, ephemeral=False)
``` what am i doing worong??
oh im dumb
im trying to do a discord.ui response that when you click the button it responds with an embed with two more buttons
Then put a view with interaction.response.send_message.
i did
@bot.command()
async def ticket(ctx):
button = Button(
label="Create A Ticket",
style=discord.ButtonStyle.green,
)
Option1 = Button(label="Request a Material Offer to Venerable",
style=discord.ButtonStyle.green)
Option2 = Button(label="Make a Purchase Order",
style=discord.ButtonStyle.danger)
async def button_callback(interaction):
await interaction.response.send_message(
"What Would you like to create a ticket about?", view1=view1)
button.callback = button_callback
view1 = View()
view1.add_item(Option1)
view1.add_item(Option2)
view = View()
view.add_item(button)
await ctx.send("Hi!", view=view)
what am i doing wrong
You should try subclassing, easier
Learn all about implementing buttons in your Discord Bot using Pycord.
@fervent cradle
does that include dropdowns?
Yes
this is very confusing
perhaps learn english sometime then
dude
whats the best alternative to restart while testing bot
Please don’t be rude, there is no need for that here.
Could you explain more?
like restarting bot many times hits ratelimits + a bit more time taking while developing bot
so better alternatives to restart
you linked a website. that website clearly explains and answers the question. they're not doing anything to help themselves- so why do i owe them any kind of respect
Okay but there is no point of being rude, it’s not going to help.
It’s a help channel for a reason, for people to get help with Pycord, Python and more.
i figured out the dropdown menu, but the response isnt working
class MyView(discord.ui.View):
@discord.ui.select( # the decorator that lets you specify the properties of the select menu
placeholder = "Choose a Ticket Type", # the placeholder text that will be displayed if nothing is selected
min_values = 1, # the minimum number of values that must be selected by the users
max_values = 1, # the maxmimum number of values that can be selected by the users
options = [ # the list of options from which users can choose, a required field
discord.SelectOption(
label="Request a Material Offer to Venerable",
description="Employee Only!"
),
discord.SelectOption(
label="Make a Purchase Order",
description="Purchase Something from Venerable!"
)
]
)
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
await interaction.response.send_message(f"I'm Creating a Ticket for you...")
i want to make it so if the user doesn't give a member, it'll just give information for themselves. how can i do that?
what am i doing wrong?
Use Option
And add "required=False
i'll try that
Any error??
i figured the response out
im trying to now have the bot create a text channel based on the name of the option
class MyView(discord.ui.View):
@discord.ui.select( # the decorator that lets you specify the properties of the select menu
placeholder = "Choose a Ticket Type", # the placeholder text that will be displayed if nothing is selected
min_values = 1, # the minimum number of values that must be selected by the users
max_values = 1, # the maxmimum number of values that can be selected by the users
options = [ # the list of options from which users can choose, a required field
discord.SelectOption(
label="Request a Material Offer to Venerable",
description="Employee Only!"
),
discord.SelectOption(
label="Make a Purchase Order",
description="Purchase Something from Venerable!"
)
]
)
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
channel = guild.create_text_channel(f"{select.values[0]} Ticket")
await select.response.send_message(f"I'm Creating a Ticket for you...", channel)
this doesnt work
i'm not sure what's going wrong
guild isn’t defined, it would be interaction.guild
wouldnt it be select?
Error?
No. Read the docs for discord.Interaction
b!rtfm pyc discord.Interaction
discord.Interaction
discord.Interaction.application_id
discord.Interaction.channel
discord.Interaction.channel_id
discord.Interaction.client
discord.Interaction.custom_id
discord.Interaction.data
discord.Interaction.delete_original_message
discord.Interaction.edit_original_message
discord.Interaction.followup
yes but its not an interaction
Ignoring exception in command rank:
Traceback (most recent call last):
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 877, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "c:\Users\CENSOR\Documents\Github\file-storage\Robot Maxx\cogs\levels.py", line 38, in rank
data = await self.lvl.get_data_for(member)
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discordLevelingSystem\decorators.py", line 62, in wrapper
return await func(*args, **kwargs)
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discordLevelingSystem\decorators.py", line 80, in wrapper
return await func(*args, **kwargs)
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discordLevelingSystem\decorators.py", line 104, in wrapper
return await func(*args, **kwargs)
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discordLevelingSystem\leveling_system.py", line 1432, in get_data_for
async with self._connection.execute('SELECT * FROM leaderboard WHERE member_id = ? AND guild_id = ?', (member.id, member.guild.id)) as cursor:
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 358, in invoke
await injected(ctx)
File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
interaction has an attribute of guild that is a guild object
oh i didn't think it would be that big
?tag paste
Well you set member to None so it’s going to be None. In your code you should put this to have member as ctx.author if member is None: py member = member or ctx.author
thanks, it works
this is all very new to me and while i do know how to code i never do stuff like this, i really appreciate anyone who helps me out in the future
how can i possibly share 1 slash command group between multiple cogs
should i just import it from 1 specific cog all the time
or there is a better way
after using await bot.close() is it normal for the terminal to not give a new line to type in another command?
because every time i use my slash command to shutdown the bot, i still have to kill the terminal to start it up again
is there a way to make it more bearable to start the bot again?
there is an reload method or smth
i tried that it's like when a window stops responding and you can't interact with it
maybe i'll try that
i know there is reload extension method, not sure about full bot
hi guys, have some very barebones code here that essentially just gets my bot online on discord (still learning how all this works) - when i run main.py my bot comes online, but does anyone know what's up with the little warning message abt python-dotenv in the terminal?
there is something going on with your .env file
may be you typed in something by mistake
on line 1
my env
token removed for obvious reasons
should my token be in quotes? is that the problem?
nope, appears to have made no difference
ohhh, it's the
env title=".env"
what should i change that to? is that line necessary?
no its not
you can just have ```bat
TOKEN=TOKEN_HERE
Hello.
Is it possible to disable a View after certain number of seconds (ignoring interactions)
I'm not talking about timeout
Just checked - No
Subclass view and use asyncio?
i want to pass a channel list to choice(slash) after sets operations with it, is that possible?
im new to python, how do i use asyncio?
after sending the message with the buttons
asyncio.sleep(10) //10seconds sleep
then you edit your message
ye but I want to do a giveaway sort of thing
Where it disables at a specific time
if you are new to python learn the basic´s of python
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
oh ok thanks, will look into it
Hey how can I get the inviter when someone joins over an invite link in a voice channel
Hi , how can i fix this error "no modules named 'telegram' "
hello, if i want to disable all items in a view,
can i use super().disable_all_items()
instead of
for child in self.children:
child.disabled = True
your cog should be initialised like this
so self.bot contains all the info of the bot
?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.
what's the error
nope doesnt work
oh crap lol
you should use member.id instead of member bcs you're comparing id to id
a member object will never be an int
is there a reason my cogs are not sending errors when they are loaded? When parts of my code are broken the cog doesn't load and it doesn't send errors to let me know how I can fix my code.
I think this is the solution. #1003696609722384466 message
perfect, thanks :)
Hello, I wanted to ask if it was possible to work with cogs+slash commands without needing to reload the whole bot when making changes. As far as I understand you need to load the cogs before executing the bot.run() method. Is that correct? am I missing something?
You can load and unload a cog on the go.
Loading:
https://docs.pycord.dev/en/master/api.html?highlight=load#discord.Bot.load_extension
Unloading:
https://docs.pycord.dev/en/master/api.html?highlight=unload#discord.Bot.unload_extension
or reloading:
https://docs.pycord.dev/en/master/api.html?highlight=unload#discord.Bot.reload_extension
how do you define a default emoji on discord?
i used the :name: but it returns invalid emoji, when i set the emoji on a button to it
hi guys, what exactly do lines like @bot.event do exactly? it's not syntax i've ever really seen outside of writing discord bots
i think i understand that 'bot.event' is an attribute of my bot object, it's the @ i'm confused about
problem resolved, using the emoji on keyboard works
The @ makes it a decorator
It's a common syntax in python. It's called decorator. Decorator is a function that takes other function (most of the times) and transforms it in some way.
It pretty much registers an event handler with the bot
So it takes the function below the decorator and runs that function every time the event is triggered
ahhhh
Python Enhancement Proposals (PEPs)
so if you have
@bot.event
async def on_message(msg):
pass
the function will be run every time a message is sent
how do you apply the same callback to multiple buttons which were created by a loop?
so this will do something every time it sees a message?
okay! thank you!
Just button.callback = function_name
i understand you now
Yeah it will trigger every time the on_message event is triggered
i did a whole course on python 3 on codecademy and i don't think they mentioned any of this haha
i assume i can find a list of all events in the readthedocs site
Yeah I believe so
here's my loop, should i put below it or in an async function
bot.event is a method that takes a function (on_messasge) and subscribes and event based on the function's name
you could do the same thing just by
def on_message(msg):
pass
bot.event(on_message)
I would recommend assigning the created button object to a variable and then setting the callback, and only then adding it to the view with self.add_item
theres no need to put await
hmm okay
Because await will run the callback
since the callback should only run when the button is clicked
So instead so this:
button = Button()
button.callback = function_name
await will not run.
And the function should take one parameter of type discord.Interaction
Well it awaits the coroutine
how do i grab the member who pressed the select option in my select menu
interaction.user
thank you
You're welcome
Actually it causes a syntaxerror
*typeerror
Pretty much it awaits an object representing a function, which is different from a coroutine
I kind of lost track of the development here, so I don't want to waste my time digging through blames. 
How I should handle command groups from legacy discord.ext.commands in Cogs? I came back to my project, did an update and got a million of type errors cuz types changed.
ah got it thanks
Were you using @commands.group?
yup
from discord.ext.commands import Cog, Context, group
class MyCog(Cog, name="My Cog"):
_bot: CustomClient
def __init__(self, bot: CustomClient):
self._bot = bot
@group(name="mygroup", invoke_without_command=False)
async def my_group(self, ctx: Context):
pass
What's the error you get?
Argument of type "(self: Self@ModerationUtilsCog, ctx: Context[Unknown]) -> Coroutine[Any, Any, None]" cannot be assigned to parameter of type "((Concatenate[CogT@group, ContextT@group, P@group]) -> Coro[T@group]) | ((Concatenate[ContextT@group, P@group]) -> Coro[T@group])"
Type "(self: Self@ModerationUtilsCog, ctx: Context[Unknown]) -> Coroutine[Any, Any, None]" cannot be assigned to type "((Concatenate[CogT@group, ContextT@group, P@group]) -> Coro[T@group]) | ((Concatenate[ContextT@group, P@group]) -> Coro[T@group])"
Type "(self: Self@ModerationUtilsCog, ctx: Context[Unknown]) -> Coroutine[Any, Any, None]" cannot be assigned to type "(Concatenate[CogT@group, ContextT@group, P@group]) -> Coro[T@group]"
Parameter 1: type "Concatenate[CogT@group, ContextT@group, P@group]" cannot be assigned to type "Self@ModerationUtilsCog"
"Concatenate[CogT@group, ContextT@group, P@group]" is incompatible with "ModerationUtilsCog"
Function accepts too few positional parameters; expected 2 but received 1
Keyword parameter "ctx" is missing in destination
Type "(self: Self@ModerationUtilsCog, ctx: Context[Unknown]) -> Coroutine[Any, Any, None]" cannot be assigned to type "(Concatenate[ContextT@group, P@group]) -> Coro[T@group]"
Parameter 1: type "Concatenate[ContextT@group, P@group]" cannot be assigned to type "Self@ModerationUtilsCog"
for some reason it doesn't recognize methods properly :/
interaction has no attribute values
interaction.data['values']
channel = select.guild.create_text_channel(f"{author}'s'{select.values[0]} Ticket")
.
im using seect
yeah
Hold on are you trying to get what the user selected or just the first value of the select menu?
Yeah I've never seen that before
Try removing the _bot: CustomClient part
It doesn't work because it's not even related to that 😩
await select.response.send_message(f"I'm Creating a Ticket for you...", channel)
Well the syntax appears to be correct
TypeError: send_message() takes from 1 to 2 positional arguments but 3 were given
Remove the channel part
then where do i add a channel
send_message will send it to the channel in which the interaction occured
so how do i create a channel when they press it?
Uh
Well
Just get the channel object
After creating the channel
And then use channel.send
i did it
but
the channel name is bad
it has the name and the numbers
async def button_callback(self, button, interaction):
it says that this line of code is invalid syntax
@rare ice sry for tagging u
it says this is invalid
I know this, but slash commands seems to only get registered if I load a cog before the bot runs
(nextcord seem to have the same issue, I wanted to get confirmation if this a problem on my end or not)
from the official examples: https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_cog.py
# The basic bot instance in a separate file should look something like this:
bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"))
bot.load_extension("slash_cog")
bot.run("TOKEN")
Then it’s most likely the line above it. Please send your full code of the button.
@discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.danger)
async def button_callback(self, button, interaction):
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
Do you have any code above that?
just my roblosecurity
i think its a glitch
how do i send that view when the new channel is created?
and its in that channel
@rare ice how do i fetch a channel by defining it by the current channel that your in
sry for taggin u again
Explain more please.
like i want the close button to close the channel
delete it
but all the channel fetching ive done is by name or id
@rare ice
i really need help
So uh. I'm trying to get some embeds to work with slash commands. i can't get them to work. even when i use embeds=[embedVar]
ok
and i need the permsiions to be only the one who created a ticket and the mods can enter the channel
async def testCommand(ctx: interactions.CommandContext):
testEmbed = discord.Embed(title='Testing', description="For testing")
testEmbed.add_field(name="What's Being tested", value="Seeing if Embeds can be sent")
testEmbed.add_field(name='Debug log', value=f"This Works! ")
await ctx.send(embeds=[testEmbed])``` Am i just using outdated resources or am i just dumb
@rare ice
are you typing the command in case sensitively?
well you're going to have to do that yourself with discord.Permissions
b!rtfm pyc discord.Permissions
discord.Permissions
discord.Permissions.add_reactions
discord.Permissions.administrator
discord.Permissions.advanced
discord.Permissions.all
discord.Permissions.all_channel
discord.Permissions.attach_files
discord.Permissions.ban_members
discord.Permissions.change_nickname
discord.Permissions.connect
interactions.CommandContext isn't a part of Pycord.
ik
could you direct me to somewhere that i could get assitance on that? 
but how do i add specific roles
since it looks like you're coming from another library, I recommend starting with the guide:
?tag guide
i started by using the Normal stuff. but i wanted to use slash commands. took me forever to even find a slash command Structure that works
do you mind sending what you tried and what error you got (if any)?
You want me to show the whole of what i have now?
await channel.set_permissions(select.guild.default_role, send_messages=False)
hi, i want to display a list of channels to choose in slash except some channels that i dont want to
that makes it available to everyone how do i limit it to a specific role
@bot.command(name = "test",description='Testing')
async def testCommand(ctx: interactions.CommandContext):
testEmbed = discord.Embed(title='Testing', description="For testing")
testEmbed.add_field(name="What's Being tested", value="Seeing if Embeds can be sent")
testEmbed.add_field(name='Debug log', value=f"This Works! ")
await ctx.send(embeds=[testEmbed])
if i do this the main error that's thrown is that AttributeError: 'Embed' object has no attribute '_json'
if i do it just embed
^^
it says that ctx.send doesn't have an attribute embed
so remove interactions.CommandContext for type hinting ctx.
i remember trying that and it not working, but i'll try again
like can i use set union or intersection?
at the moment, discord renders the channels shown when doing an option for discord.TextChannel and channels can't be removed or added to my knowledge.
uhm, any workaround then?
To add the discord.ChannelType.news channels to the discord.TextChannel channel list for slash commands, pass in channel_types=[discord.ChannelType(5)] into the option.
Credit: #997341890988998667 message
nah, specific that i dont want to
can someone help me understand why the first function here runs fine, but the second returns TypeError: command() takes 1 positional argument but 2 were given? obviously the second one is a useless function i'm just trying to figure out more how decorators work
can i list channels in autocomplete?
Here's the whole term error ignore that i am running it from a raspberry pi
oh wait- i think i understand now. i'm calling bot.command(self,on_ready). is there a way to avoid that?
and this is after removing interactions.CommandContext
could you make sure you're only using pycord? there could be a conflict between libraries
pip freeze
sorry if i'm being a bit dumb pycord is just the whole of Discord.py correct
bot.command is a called function so you need to add ()
at 1.7.3, yes

why is that not needed for @bot.event() above?
i do have a CRUD ton of other libs
it's just how it is
lmao, fair enough
ok so that's why. you have discord-py-slash-command and other discord.py libraries. you're going to need to remove those for pycord to work.
ohhh maybe because bot.command takes ctx but bot.event is a method without any arguments ?
make sure to remove discord.py
!tag install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord from git repository: (alpha)
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
yes
understood
send your updated code
up to you to decide, personal preference ig
we have all the features combined from discord.py, discord-py-slash-command and more.
i personally prefer pycord since it's updated more and maintained by more people
Do slash commands need to be added before running the bot (bot.run())? seem to only work that way
import discord
import os
from dotenv import load_dotenv
load_dotenv()
bot = discord.Bot(debug_guilds=[1004467511833677915],intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"!!! ALERT !!! {bot.user} HAS BEEN ACTIVATED !!!")
@bot.command()
async def on_ready():
print(f"!!! ALERT !!! {bot.user} HAS BEEN ACTIVATED !!!")
bot.run(os.getenv('TOKEN'))
my full code
hence why im working here :)
slash commands are automatically added when bot.sync_commands() is ran when the bot starts. please send any code or errors you have.
import discord
import os
from dotenv import load_dotenv
load_dotenv()
bot = discord.Bot(debug_guilds=[1004467511833677915],intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"!!! ALERT !!! {bot.user} HAS BEEN ACTIVATED !!!")
@bot.command()
async def on_ready(ctx):
print(f"!!! ALERT !!! {bot.user} HAS BEEN ACTIVATED !!!")
bot.run(os.getenv('TOKEN'))``` just needed the `ctx` parameter for the command.
did i uninstall discord too or no. I just wanna make sure i have the correct libraries
how do you add multiple buttons with the same callback
the only library you need for discord is pycord (don't quote me on that :/) so you need to uninstall discord.py and all other libraries but pycord.
when I add them to cogs, do I need to run bot.sync_commands() ?
Using this example:
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_cog.py
they only appear if I do this:
bot.load_extension("slash_cog")
bot.run("TOKEN")
but not when i do this:
bot.run("TOKEN")
bot.load_extension("slash_cog")
ahhhh thank you! i get it
uh i can't read any of that. try troubleshooting vs code or try uninstalling and installing again.
thats what i am talking about
how to troubleshoot
(no errors, they just don't appear on discord)
try reading somewhere along this road: https://code.visualstudio.com/docs/supporting/troubleshoot-terminal-launch
thanks ig
Is there a quickstart guide? I installed it but Vsc isn't seeing it as an import
bot.sync_commands() is automatically ran. but you need to load the cog before you run the bot. i typically use this bot structure for my main.py files if this helps:
import discord
from discord.ext import commands
# other imports
load_dotenv()
bot = # create bot
#load cogs/extensions
# on_ready event
#run bot```
ok, what about hot-reloading cogs?
Excited to create your first bot? Once you install Pycord, you can start right
Im interesting in never having to restart the bot
what you you mean by 'hot' reloading?
loading/unloading cogs without restarting the bot
not sure if that's possible since your code would need to update
Is there an Easier way to do slash commands?
@rare ice
async def button_callback(self, button, interaction):
await interaction.response.send_message("This Ticket will be Deleted in 10 Minutes")
AttributeError: 'Button' object has no attribute 'response'
send your full code.
easier how?
that is it
class CloseTicket(discord.ui.View): # Create a class called View
@discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.danger)
async def button_callback(self, button, interaction):
await interaction.response.send_message("This Ticket will be Deleted in 10 Minutes")
await asyncio.sleep(5)
you could try making a load and unload cog command and seeing if the code updates when reloading but idk/
Than what i had before.
could you run pip freeze for me and send me the output from your terminal?
ok that is what I was fearing. Currently im running a bot in a large-ish server (with prefix commands) and we can update it (adding new cogs, or reloading them) without stopping it. It seems this is not possible with slash commands, which is a deal breaker. Do you happen to know if this is a limitation with the discord API or discord.py/pycord in general?
oh it's just .slash_command lol
pretty sure its a limitation with pycord but again, im not sure since i've never tried what you're attempting.
so the usual way is restarting the bot everytime you make changes?
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.
you tend to have a production bot and a testing bot and only update the testing bot so it needs to load less servers
you have discord.py installed, that could be the problem. could you install it via pip uninstall discord.py?
oh thank god squid is here 
well it is only on one server, and we want to add new features incrementally and not delay them, and adding them at the same time. I do have a testing bot but still i dont want to restart it
well restarting your bot is inevitable. so you may have to.
it was avoidable with prefix commands
I pretty sure reloading cogs with slash commands is bugged anyways.
:(
yeah it only works with prefixed commands.
I just realized that no one opened an issue with that yet.
great, I should tbh
kinda really demotivated to make the switch to slash commands now. I have been reading conflicting opinions so maybe I can ask here:
is my bot going to stop working with prefix commands (a bot with <100 servers) in the near future?, or we don't really know
literally in 26 days
can I have a link?
to what?
to read more about that announcement
As the popularity and number of Discord bots grow, it's important to keep our users and developers safe and healthy. This means from time to time, like any maturing platform, we need to update our ...
@bot.slash_command(name="test",description="Testing Stuff")
async def test(ctx):
testEmbed = discord.Embed(title="Test Embed", description="For Testing Stuff")
testEmbed.add_field(name="What's being tested", value="Running embeds")
await ctx.respond(embed=testEmbed)```
is this good for sending embeds?
dang you beat me to it :(
um ok
or do i just flat out send the embed as is
it's bookmarked somewhere lol
sorry i meant discord.py
and py-cord isn't installed
yes that is how you should send embeds
good
tell me if I am reading this wrong, but it only affects bots that are in more than 100 servers? mine is not going to be in that situation ever
That was much easier than what i had before
alright, then yes, you don't need slash commands
dude what the hell
ah great, thank you all for the help
??
it simple as uninstalling them and reinstalling them. :\
How do i put options into my Slash commands? Like if i wanted input
Here's the slash options example.
you can set them either way
it's not that hard to reinstall it
sorry no.
the options thing you gave doesn't say how to set them as required or not
i fixed it
b!rtfm pyc discord.options
discord.Option.description
discord.Option.description_localizations
discord.Option.choices
discord.SelectOption.description
discord.commands.options.Option
discord.commands.options.OptionChoice
discord.ui.Select.options
discord.SelectMenu.options
discord.SlashCommand.options
discord.Bot.application_flags
there's this thing called required = True/False
what is the way to fix this
class CloseTicket(discord.ui.View): # Create a class called View
@discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.danger)
async def button_callback(self, button, interaction):
await interaction.response.send_message("This Ticket will be Deleted in 10 Minutes")
await asyncio.sleep(5)
#await channel.delete
Button' object has no attribute 'response'
@rare ice
flip button and interaction
in the params
ok
File "main.py", line 33, in button_callback
await channel.delete
TypeError: object method can't be used in 'await' expression
async def button_callback(self, interaction, button):
await interaction.response.send_message("This Ticket will be Deleted in 10 Minutes")
channel = interaction.channel
await asyncio.sleep(5)
await channel.delete
you need to call it
its a coro
channel.delete()?
... await channel.delete()?
alr, the last thing in my ticket bot, when i create the ticket, i want the channel perms to be only mods and admins, and also the person who created it
assuming tickets are text channels:
https://docs.pycord.dev/en/master/api.html#discord.TextChannel.overwrites
^
if i'm running
@bot.event
async def on_message():
pass
what do i need to get the content of the message itself? i thought it would be ctx.message, but on_message() doesn't take any arguments, so i'm confused now
@bot.event
async def on_message(discord.Message):
print(discord.Message)
so like this ??
yes but you need to process commands, put this after your print statement: await bot.proccess_commands(message)
almost 6969 messages, nice
how to fix it? it would not start either
for some reason including the discord.Message in on_message() is causing a syntax error
you should specify an argument
not object
message: discord.Message
@bot.event
async def on_message(message=discord.Message):
print(discord.Message)
await bot.proccess_commands(message)
``` here's what i changed it to - now i get a `AttributeError: 'Bot' object has no attribute 'proccess_commands'` when i actually send a message for it to print in my test server
oh mb spelling
is it process_application_commands? process_commands doesn't work either
are you using commands.Bot or discord.Bot?
discord.Bot, that's what i've been seeing used in examples. should i swap to using commands.Bot?
discord.Bot should work fine
bot = discord.Bot(debug_guilds=[1004467511833677915],intents=discord.Intents.all())
b!rtfm pyc discord.Bot.process_application_commands
ok so try that
okay well!! not crashing anymore! but when it prints to the console all it prints is <class 'discord.message.Message'> hahaha
do cog listeners still require the self argument?
what is the difference between discord.Bot and commands.Bot anyways ??
is there a way to put slash commands into a different document for the sake of Orgainization?
Here's the slash cog example.
the above might be what you are looking for
I've used add_cog before i just wasn't sure if it'd work with Slash
Works the same way :)
understandable.
would i do this instead for a slash command? @commands.slash_command() async def test(ctx):
instead of @commands.command()
Uh oh
so I tried to create the command in the document. but it doesn't seem to run
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
class testCommand(commands.Cog):
def __init__(self,bot):
self.bot = bot
@commands.slash_command()
async def test(self,ctx: discord.ApplicationContext):
await ctx.response("This Works")
nvm
i see it
can someone guide me on how to create buttons the guide on the website outdated and isnt working for
It still doesn't work. I fixed the one thing i saw but it's not showing on my bot
Hey, anyone know why I’m getting this error?
Error:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 715, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 846, in exec_module
File "<frozen importlib._bootstrap_external>", line 983, in get_code
File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/container/cogs/moderation.py", line 150
await member.remove_timeout(*, reason=reason)
^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/main.py", line 39, in <module>
bot.load_extension(f'cogs.{cog}')
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 787, in load_extension
self._load_from_module_spec(spec, name)
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 718, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: SyntaxError: invalid syntax (moderation.py, line 150)
Code:
@commands.command()
@commands.guild_only()
@permissions.has_permissions(manage_roles=True)
async def unmute(self, ctx, member: discord.Member, *, reason: str = None):
""" Unmutes a user from the current server. """
if await permissions.check_priv(ctx, member):
return
elif member == None:
await ctx.send("You must provide a member.", delete_in=5)
else:
await member.remove_timeout(*, reason=reason)
await ctx.send("unmuted")
if reason == None:
reason = "No reason provided."
except Exception as e:
await ctx.send(e)
hi, do you know if this fork of discord.py supports voice receive?
any1?
How do i make the bot react to embeds with slash commands
you can't add a reaction to embeds, you add reactions to the message of the embed
how do i do that?
If you already have the discord.Message object, you can use message.add_reaction()
would give you the message,
ah
interaction = await ctx.respond("Message")
message = interaction.original_message```
like this?
it's a coro, you should await it
and i couldn't get the slash_cog to work in a different document
bump
learn python ty
add store = False in load_extension
i got an error apparenly slash_cog couldn't be found
i literally followed docs 💀
b!rtfm pyc remove_timeout
and what does a star mean?
The asterisk doesn't mean you put it in your code as well. It represents how the values are taken.
slash_cog couldn't be found
show full error
there
Traceback (most recent call last):
File "/home/pi/S.H_pybot/main.py", line 17, in <module>
bot.load_extension('slash_cog',store=False)
File "/home/pi/.local/lib/python3.9/site-packages/discord/cog.py", line 857, in load_extension
raise final_out
discord.errors.ExtensionNotFound: Extension 'slash_cog' could not be found.
OH
I'm dumb
i followed the thingy.
i didn't know i was supposed to name it after the doc
and this is where they are
import discord
from discord.ext import commands
class testCommand(commands.Cog):
def __init__(self,bot):
self.bot = bot
@commands.slash_command()
async def test(self, ctx:discord.ApplicationContext):
await ctx.respond("Yes")
def setup(bot):
bot.add_cog(testCommand(bot))```
this is Test.py
and then main
import discord
from discord import option
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
token = os.getenv("DISCORD_TOKEN")
ver = os.getenv('Version')
intents = discord.Intents.default()
intents.members = True
bot = discord.Bot(intents=intents,command_prefix="-")
#When the Bot Starts
@bot.event
async def on_ready():
print(f"Bot is up")
await bot.change_presence(activity=discord.Game(name="Crusading isles Beta"))
bot.load_extension('test')
bot.run(token)```
idk why it's not working.
Whats the error? Also, try doing:
bot.load_extension('test', store=False)
i did
Whats the error?
Try to set guild_ids to the id of a guild that you will run the command in
So:
@commands.slash_command(guild_ids=[...])
hm I've heard that sometimes slash commands can take some time to display
So wait a few min
if i code it into main it shows almost instantly
the command. when i code it into the doc i removes the command
By the way, do you know if the cog loads?
how can i tell?
Add this to your cog:
@commands.Cog.listener()
async def on_ready(self):
print("Cog is online")
into my main, or into the Document?
Into the cog
Anyone ran into this issue?
Traceback (most recent call last):
File "/root/---/bot.py", line 137, in <module>
bot.run(bot.token)
File "/usr/local/lib/python3.9/site-packages/discord/client.py", line 715, in run
return future.result()
File "/usr/local/lib/python3.9/site-packages/discord/client.py", line 694, in runner
await self.start(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/discord/client.py", line 658, in start
await self.connect(reconnect=reconnect)
File "/usr/local/lib/python3.9/site-packages/discord/shard.py", line 462, in connect
raise item.error
File "/usr/local/lib/python3.9/site-packages/discord/shard.py", line 185, in worker
await self.ws.poll_event()
File "/usr/local/lib/python3.9/site-packages/discord/gateway.py", line 589, in poll_event
await self.received_message(msg.data)
File "/usr/local/lib/python3.9/site-packages/discord/gateway.py", line 539, in received_message
func(data)
File "/usr/local/lib/python3.9/site-packages/discord/state.py", line 635, in parse_auto_moderation_action_execution
event = AutoModActionExecutionEvent(self, data)
File "/usr/local/lib/python3.9/site-packages/discord/raw_models.py", line 462, in __init__
self.content: str = data["content"]
KeyError: 'content'
Bot has been running prior to this seemingly random error for about an hour, without issue.
Put bot.load_extension('test') outside of on_ready in your main file
What version of py-cord is that?
2.0.0
ok that worked
Alright cool
And you don't have dpy or any fork installed other than pycord, right?
Oh wait hold on
correct.
Just install the master version of pycord
Run
pip install git+https://github.com/Pycord-Development/pycord.git
I figured it was going to fix that. As it seems to be a new thing "AutoModActionExecutionEvent"
Yeah
would be dope if there was a known issue for it 🤔
(or better, if it were pushed to prod :P)
line 72, how come .avatar_url is not recognized as a method?
Its now .avatar.url
You're welcome
if any(word in BlacklistedWords for word in message):
can i use this to get all members of a server? guild = self.bot.get_guild(ctx.author.guild.id)
i want to get all of the members of the server and get their roles
how do you send multiple views in a message?
For some reason the Required thing in options isn't working
@option("write",description="Wrting your discription",required=False)```
it still requires it
when i use the command
nvm
How can i get the User without the message?
the command works up to that point
don't use json as a db
ctx.user?
it doesn’t really matter for smaller bots
i got it lol
ah ok
it absolutely does matter
nah it really doesn’t
of course it would be less performant than other options but if you’re just starting out it’s not that bad
well I'm familiar with json. and this bot's not gonna be that big
yeah personal-use types of projects that don’t rely on many reads and writes per second can use json
it's a bad practice and generally unreliable if you want to change information stored in it. if you use json as a db you generally don't make it failsafe either so the odds of changing one set of data and before it is saved, try to alter another; are not minimal and will absolutely make the json invalid and unusable.
unreliable unless you work with a small set of data
it's still a bad practice and you should switch to a proper db and use that practice instead- as it is both reliable for smaller and big projects. there's practically no reason to not choose a proper db over a .json file
I’ll just dm
can you pass ctx into a modal?
I want to add the output to a json where the user id is the key
by adding a variable to the __init__()
trying it now
Should i use SQL then? json is decent for what it's worth
yes you should. you can still just use a json-dict to save in sql if you really want that structure
I'm also a fan of storing data in a database
So Norman I'm not sure if I should use a thread for this or not but I'm still having issues passing in ctx. Should it be like this? ```python
async def btn1callback(interaction: discord.Interaction):
print("Submit Time Button pressed")
if interaction.user != ctx.author:
await interaction.response
#JSON
user_id = str(ctx.author.id)
await interaction.response.send_modal(MyModal(title="Time Submission", ctx= ctx))
class MyModal(discord.ui.Modal):
def __init__(self, ctx, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
print(ctx)
self.add_item(discord.ui.InputText(label="Please enter your time in the mm:ss format"))
# what is displayed as the Modal message
async def callback(self, ctx, interaction: discord.Interaction):
When I pass it in like this I'm getting an TypeError: MyModal.callback() missing 1 required positional argument: 'interaction' Error
you should in __init__(ctx) add self.ctx = ctx
and in callback don't add ctx. you instead refer to it by doing self.ctxwhere you need it, not in the callback()
Are you saying it should be like this? ```python
class MyModal(discord.ui.Modal):
def init(self.ctx, *args, **kwargs) -> None:
did you mean self, ctx?
class MyModal(discord.ui.Modal):
def __init__(self, ctx, *args, **kwargs) -> None:
self.ctx = ctx
do you mind explaining why that works? why do you need to set self.ctx = ctx?
could you give me your command for the modal? idk how to properly phrase a solution unless you do that :p
sure
well the whole command is kind of long. Are you looking for the sub classed callback?
for example await ctx.send_modal(modal)
or whatever you use to send the modal
ill just go by the example given from the docs wait
async def btn1callback(interaction: discord.Interaction):
print("Submit Time Button pressed")
if interaction.user != ctx.author:
await interaction.response
#JSON
user_id = str(ctx.author.id)
await interaction.response.send_modal(MyModal(title="Time Submission", ctx= ctx))
print(Submission_Info)
Submission_Info = await self.Submission_Info(ctx)
msg = await interaction.response.edit_message(embed = Submission_Info[0], view=view)
I'm using a button to call the modal
tbh, i don't understand what the issue is? is ctx not passed to the modal
so your suggestion to add self.ctx=ctx to the init worked but I was just curious as to why it was needed
was it just because the other class needed it defined?
I just want to understand why
Modals don't take ctx.
That's why interaction is "missing" in your original function
Why would you even pass ctx? You don't use ctx to respond to a interaction
True I'm having to go about this is a convoluted way but I'm trying to get the output from multiple dropdowns and then insert them into a database. Since dropdown selections are local variables i'm dumping everything into a json then at the end I'll take that json and turn it into a sql insert statement
You're explanation makes sense. I appreciate it 🙂
Just encountered something in 2.0.0 but not 2.0.0rc1.
If you have an import error in a cog, the bot will load without issuing any warnings (or crashing). The cog will just be skipped, so commands will disappear without explanation.
Is this a bug or intentional (for some reason)?
can someone explain (or link to an explanation) to me the difference between using commands.Bot and discord.Bot?
do i have to choose one or the other for my discord bot?
How do I globally set debug_guild?
In your bot constructor
Looks like you didn’t await
Yes. What argument
debug_guilds
is there an alternative to await ctx.respond and await ctx.send?
would member on line 105 be a discord.Member?
Which line is crashing?
Nothing jumps out at me there. Try adding some logging
Or fire up the debugger and step through
nvm i got it
Go for it
Nothing jumps out at me. I'd try those logging statements so you can pinpoint where it's happening
Or someone else may catch what I missed
get_role() isn't a coro, so it shouldn't be that
You're missing the event decorator mate
How frequently is discord.Bot.latency updated, if ever?
How many Input Texts can you have in a Modal?
5
View.message says this:
The message that this view is attached to. If None then the view has not been sent with a message.
I send a view with await ctx.respond(..., view=my_view), yet my_view.message is None. Am I misunderstanding this property?
are there any good online examples of per-server settings for bots written with pycord?
Without doing
# ...
if isinstance(error, SomeException):
error = error # type: SomeException
elif isinstance(error, discord.HTTPException):
error = error # type: discord.HTTPException
else:
# ...
is there a way to type hint that error is a certain exception class per statement?
that would make IDE's work, like pycharm
by doing error: <type>?
how to add option value pair in autocomplete list?
subcommands?
Modals?
Is there an efficient way to store data in python? I want to store question data for a quiz command
Is the bot only at one server?
json is a bit inefficient imo
I'm trying to create a button that prompts a user to upload an image but every time I click the button, it gets to the try except then doesn’t see the message and times out. I do have message intents enabled in the dev portal. Any ideas on how to fix this?
async def btn3callback(interaction: discord.Interaction):
print("Proof of Time Entry pressed")
if interaction.user != ctx.author:
await interaction.response
await interaction.response.send_message("Upload a photo of your time.")
print("After first interaction")
while True:
print("within while True")
try:
message = await self.bot.wait_for('message', timeout = 60, check = check)
print(f"message is {message}")
proof_of_time = message.attachments[0].url
print("message attached")
print(proof_of_time)
submission_info = await self.Submission_Info(ctx)
msg = await interaction.response.edit_message(embed = submission_info[0], view=view)
break
except asyncio.TimeoutError:
await interaction.response.send_message("Timeout. Please try again")
break
except Exception:
await interaction.response.respond("Please reupload your time photo.")
Eventually I want to be able to edit the original interaction with "interaction.response.edit_message" but right now I'm focusing on getting the attachment
it's a slash command
@event.command(name = "submit")
async def submit(self, ctx, proof_of_time: discord.Option(discord.Attachment)=None, proof_of_armor: discord.Option(discord.Attachment)=None, message=None):
I have it setup so it can except attachments when first starting the slash commands but there are known bugs so I wanted to have another way to add it. it works on my pc but not on my phone
Figured it out. I didn't have my check defined within the button
how to add option value pair in autocomplete list?
you can still use OptionChoice
Why are these Info Logs shown? It suddenly started showing up
Does anyone know how to set X and Y for this?
@discord.ui.button(label="✊ rock", style=discord.ButtonStyle.green, custom_id="self.rpsrock")
async def rock(self, button: discord.ui.Button, interaction: discord.Interaction):```
Can we add a cooldown to button presses?
I think yes if u want
How?
Idk tho
If i say ill make like a dict that contain yes or no
Like cooldown = [buttid]
if theres no support
No I thought if there was some kind of decorator like the one you have to add cooldown to commands
from discord.ext import commands, tasks
from datetime import time, timezone
class Shanza(commands.Cog):
def __init__(self, client):
self.client = client
self.remind_shanza.start()
@commands.Cog.listener()
async def on_ready(self):
global shanza_user
shanza_user = self.client.get_user(734346204892233768)
print("Cog: Shanza.py loaded")
# Minus 3 hours from UTC to get the current time in gmt+3
@tasks.loop(time=time(1, 52, tzinfo=timezone.utc()))
async def remind_shanza(self):
print("Test")
general_channel = self.client.get_guild(880368659858616321).get_channel(880368661104316459)
await general_channel.send(f"test thing")
@remind_shanza.before_loop
async def before_my_task(self):
await self.wait_until_ready() # Wait until the bot logs in
def setup(client):
client.add_cog(Shanza(client))
The cog doesn't seem to load at all. Any idea?
do i need to subclass discord.ui.View for every view i want to create?
yes
i try to run the bot but it says Traceback (most recent call last):
File "main.py", line 2, in <module>
from discord.ext import commands
ModuleNotFoundError: No module named 'discord'
did you install pycord?
Is there a way to set a timer to delete a message after a set time?
message.send(delete_after=seconds)

is that the original message?
wait what is message.send
message.send is from normal discord.py i think
i used discord.py for a bit so that's kinda faimilar to me
b!rtfm pyc message.send
ctx.send whatever 😄
yeah
it`s all the same 😄
in words yes, in code no
kinda ig
which one lol
how do you get the pfp of the user?

user.avatar.url
ctx.author.avatar or something like that
or ctx.author.avatar_url

it keeps changing, just test it out, while coding in visual code it shows you
That's what it was on 1.7.3, on 2.0 the .avatar is a discord.Asset so to get the url you must do .avatar.url
vsc doesn’t have the best autocomplete tho
idk but github copilot still autocompletes better
How do you do stuff with reactions, can you do stuff with them in different document
how do you code in microsoft word
b!rtfm pyc on_reaction
here are some reaction events
in my cog doc or do i have to do those in main?
I don’t understand what a cog doc is.
not a program document other than main
omg
either should work
in a cog, @discord.Cog.listener
in main, @bot.event
yes
Async def or the @
Is there a way to pass dynamic data to a select menu?
class AccountSelector(discord.ui.View):
optionss = []
def __init__(self, options):
super().__init__()
self.optionss = options
@discord.ui.select(
placeholder="Select an account",
min_values=1,
max_values=1,
options=self.optionss # Error here because self isn't in scope
)
can you delete a message by id?
yes
i got the reactions to work, but now i need to delete the message how would i delete it
b!rtfm pyc fetch_message
discord.User.fetch_message
discord.Member.fetch_message
discord.Thread.fetch_message
discord.Webhook.fetch_message
discord.DMChannel.fetch_message
discord.SyncWebhook.fetch_message
discord.TextChannel.fetch_message
discord.GroupChannel.fetch_message
discord.VoiceChannel.fetch_message
discord.abc.Messageable.fetch_message
after i do that can i just do message.delete?


