#Basic Pycord Help (Quick Questions Only)
1 messages Β· Page 38 of 1
Like said, it's your code, if you think it needs a re-write then it probably does
well I don't know, that's the thing
It's impossible to say, because we didn't write the code and we most likely won't either.
damn, this sucks. i've really done it to myself
my brain tells me i should be able to just convert these into cogs but when I look at the docs I feel like passing out
would it be advisable to make a separate cog for each command? that's more or less what I have going on here
No. You'd most commonly want to put multiple commands in one cog, and group the commands so they all have something in common
so if I have mute, kick, ban, and warn commands, I'd most likely put those four in a cog named moderation
okay, makes sense
before i jump in the deep end here, what exactly is preventing me from simply putting a decorator above all my functions to label them as commands?
so it looks like each command is parsing the command message itself?
here's a full example for more context
import discord
import helper
errors = {}
################ Module Start ################
async def main(client, message, args):
if len(args) == 0 or args[0] == 'help':
await message.channel.send(embed=helper.generate_help_embed(client, metadata))
return
await message.delete()
await message.channel.send(' '.join(args))
################ Module End ################
metadata = {
'emoji': ':speech_balloon:',
'name': 'Say',
'description': 'Make the bot say something.',
'aliases': ['say'],
'permission_level': 'Member',
'syntax': '!say <message>',
'subcommands': [],
'usage_examples': ['!say Hello World!'],
'function': main
}
very simple one
A command in Pycord looks like this:
@discord.command
async def my_command(ctx, arg1, arg2):
right
the command handler does everything that you're currently doing individually
my pickle comes in the fact that I'm working across many files. I've tried passing the context myself but I haven't managed to make it work
helps a ton, and will definitely help cut down your codebase
that's why I want to improve the structure. the new way is so much better
You're using Pycord, right?
yup
I'd suggest learning how its command handlers work, and then rewriting your bot. Instead of having all of this mumbo jumbo, it'd all be nice an organized
i'd love to rewrite it if it didn't have so many moving parts
i feel that it is possible to just tweak each command one at a time and register them as commands as I go, but I simply cannot get the commands to register because I'm passing the incorrect client context
if my bot is initialized like so:
client = discord.Bot(intents=discord.Intents.all(), command_prefix='!')
importing client within my modules should let me register the commands, no?
My suggestion would be to completely start over and copy/paste the parts you want to actually use. Trying to rewrite something that is already messy will take 10 times longer
Hey, I've started getting errors on startup since updating to v2.3.1 (from v2.3.0). When I add cogs to a bot instance, it throws this error:
AttributeError: 'Bot' object has no attribute '_bridge_commands'. Did you mean: 'bridge_commands'?
I setup my bot object like this:
bot = bridge.Bot(command_prefix=commands.when_mentioned_or("$"), intents=intents)
show full error
Traceback (most recent call last):
File "C:\Users\Nicholas\Documents\GitHub\TitanBot\TitanBot.py", line 53, in <module>
bot.add_cog(quotes_module)
File "C:\Users\Nicholas\Documents\GitHub\TitanBot\venv\Lib\site-packages\discord\cog.py", line 656, in add_cog
cog = cog._inject(self)
^^^^^^^^^^^^^^^^^
File "C:\Users\Nicholas\Documents\GitHub\TitanBot\venv\Lib\site-packages\discord\cog.py", line 545, in _inject
bot._bridge_commands.append(command)
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute '_bridge_commands'. Did you mean: 'bridge_commands'?
it tells you what's wrong right there
Unless I'm understanding it incorrectly, the issue is inside cog.py, where it should use bridge_commands instead of _bridge_commands. But since this is part of the library itself I don't know how I'm supposed to make it use bridge_commands
ooh i see
What version of pycord are you using?
2.3.1
Yes
The changelog says 2.3.1 was supposed to fix this issue but with AutoShardedBot, so I wonder if there was a regression somewhere for the regular Bot class
https://docs.pycord.dev/en/master/api/sinks.html#discord.sinks.AudioData this says that i can read and save this audio to file but i cant find any information as to how to do that
i ran into this yesterday and found that fix from middledot
hadnt checked if that had fixed it or not
so ig not
is Thread.applied_tags working yet? it just returns an empty list for me
guild intents?
So I tried swapping Bot with AutoShardedBot just to see if it would work, and interestingly it fails, which is exactly what v2.3.1 was supposed to fix. I'm going to try reinstalling pycord in case it's just some jank with my virtualenv
do you need intents for it?
I have
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
Are you doing this in a slash command?
yup
or rather, how do you access applied_tags
Not a large amount of data, it's basically just two strings (or one actually since I'm supposed to store headers):
headers = {
'Client-ID' : client_ID,
'Authorization' : "Bearer " + access_token
}
But thanks, the global variable was the simpler solution, it works as intented now π: (simple boolean that acknowledge auth or not)
I can just move to a forum post
I am not comfortable with classes (never created or used one for my bot) nor databases, so I would not know how to proceed and use them
So, so far, I'm glad the global variable did the trick π
Pycord is a rather advanced library, users should be comfortable with basic Python before approaching.
Read rule 1 in #help-rules
I think I manage basic Python enough to have a bot and a few slash commands/modules running without using classes (or at least, build one). When looking at the Python tutorial from w3 for instance (great website imo) I basically know everything except for classes that I never had to use so far π€·ββοΈ
I basically choose this library because it was the only one out there with a simple and well written guide, opposed to other Python libraries that only have a basic documentation
After reinstalling, the issue is still present. If I downgrade back to 2.3.0, it works as expected
To be clear:
When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.
We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.
You might want to report it as a bug
I can do that. I'll start building a minimal reproduction sample
Huh. I copypasted the sample from https://github.com/Pycord-Development/pycord/issues/1800 and it throws the error too
Looks like that PR didn't actually fix it π
Oh nevermind, I clicked the wrong run config in Pycharm π
Understood 
Alright, I've got a minimal reproduceable sample. Seems like the issue only arises when adding commands inside of cogs:
import discord
from discord.ext import bridge, commands
from discord.ext.bridge import bot
class SampleCog(commands.Cog):
@bot.bridge_command()
async def test(self, ctx):
await ctx.respond("test")
intents = discord.Intents.all()
bridge_bot = bridge.Bot(command_prefix=commands.when_mentioned_or("!"), intents=intents)
bridge_bot.add_cog(SampleCog())
bridge_bot.run("token")
I'll get to work on a bug report
Yeah that's not how cogs work lol
Well, it's worked ever since I started the bot with discord.py π
I didn't know that it worked in a different manner
But this is py-cord chief
I know, when i migrated to py-cord I didn't have to rewrite the code
It worked as-is so I assumed that was the way to do it
I've had my cogs setup like this for around 9 months. What's the proper way to set them up then?
Here's the slash cog example.
I don't see any differences aside from the command decorator and the comment at the bottom saying the bot instance should be in a separate file
In my actual bot I have these in separate files, I just put it all in one so that I could make a minimal reproduction sample
they still should be in different files just for the sake of convention
Alright, I moved them into separate files and can still reproduce the error. Is the example code otherwise fine? If so I can go ahead and post the issue
yeah
Hi, I'm currently using commands.Bot for my bot. If I switch to discord.Bot, will things like ext.tasks still work?
yes
okay, thanks!
discord.ext.tasks works independently of discord
How do I add a response after a slash command is used?
But it is
I'm having trouble setting a large list for autocomplete
It's a list of country names
@bot.slash_command(guild_ids=[813967937038974997], name='shipping', description='Calculate shipping costs on sugargoo for your specified country & weight')
async def shipping(ctx,
country: Option(
str,
name="country",
description="Country you are shipping to",
autocomplete=countries
),
weight: Option(
int,
name="weight",
description="Weight of parcel in grams"
),
width: Option(
int,
name="width",
description="Parcel width",
default=15
),
length: Option(
int,
name="length",
description="Parcel width",
default=15
),
height: Option(
int,
name="height",
description="Parcel width",
default=15
)):
autocomplete=countries
countries is a list of every country name
Traceback (most recent call last):
File "C:\Users\elich\PycharmProjects\sugargoobot4\venv\lib\site-packages\discord\bot.py", line 856, in callback
return await command.invoke_autocomplete_callback(ctx)
File "C:\Users\elich\PycharmProjects\sugargoobot4\venv\lib\site-packages\discord\commands\core.py", line 996, in invoke_autocomplete_callback
if len(inspect.signature(option.autocomplete).parameters) == 2:
File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 3118, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2867, in from_callable
return _signature_from_callable(obj, sigcls=cls,
File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2242, in _signature_from_callable
raise TypeError('{!r} is not a callable object'.format(obj))
TypeError: ['Albania', 'Algeria', 'Andorra', 'Angola', 'Anguill... (this goes on but message length limit)] is not a callable object
it works fine when I return the exact same list from a coroutine
as far as i know autocomplete has to be a corountine
can I use @bridge.has_permissions in slash commands?
like will it add both the default_permissions and internal check
How do I put an options menu in a slash command (discord.ext.commands.slash_command)?
Anybody know the coro for setting a slowmode?
why does this not work?
@bot.command()
async def test(ctx):
guild = ctx.guild
user = "647146794366795797"
role = guild.get_role(1047120025166827562)
await user.add_roles(role)```
i tried get_user but its not a thing
do you have intents?
but you know how to get a user?
user = bot.get_member(id)
thats what have done
now and it says User' object has no attribute 'add_roles'
so this would be right
user = bot.get_user(647146794366795797)
so this would also work
await user.add_roles(role)
but it doesnt
still get_member not get_user
also do you use py-cord or dpy?
which one?
replit
?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
All of a sudden, now my bot isnt working because none of my bot scripts can import functions from other files
from mod import successEmbed
in cc.py
and ModuleNotFound is being raised
cogs.module
I would do this from main.py or some file outside the cogs folder, but cc.py is in cogs folder
i love replit
errored while installing
imma just use vs
thanks for your help anyway
replit is not greate for a discord bot
also how do I import a file which is outside a folder without manually giving the path
i know i have been having issues for awhile
cuz the path may change due to me running it locally and on a vps
why does vs just say discord is not defined
after i ran this
py -3 -m pip install -U py-cord
pip show py-cord
brain hurtsss
it works but python file still says its not there
its erroring on this ```import discord
from discord.ext import commands
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)
bot.remove_command('help')```
saying commands is not defined
nvm fixed it
it was cuase i had both installed
You need an actual user object
Is it possible to hide a slash command from anyone except me?
I know guild_ids exist and that I could set it to my own server, but I want to check if there's another method, especially one that involves me using that command in DMs.
is there any way to delete thread after some time?
anybody know whats wrong with this? (something to do with the callback) ```py
async def kick(ctx, member: discord.Member, *, reason=None):
view = View()
if reason==None:
reason=" no reason provided"
yeskickbutton = button(label = "yes",ButtonStyle = discord.ButtonStyle.green, emoji = 'β
')
nokickbutton = button(label = 'no', ButtonStyle = discord.ButtonStyle.red, emoji = 'β')
async def yeskickcallback(interaction):
interaction.guild.kick(member)
interaction.response.send_message(f' just banned {member.mention} for {reason}!')
yeskickbutton.callback = yeskickcallback
async def nokickcallback(interaction):
interaction.response.send_message(f'alright, i wont ban {member.mention}!')
nokickbutton.callback = nokickcallback
view.add_item(yeskickbutton)
view.add_item(nokcikbutton)
await ctx.send(f'are you sure you want to kick {member.mention}?', view=view)```
what's the error
ima pull it up
and use py when you do the triple ticks so people can see the syntax highlighting
how
?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.")
how tf do you escape backticks, i couldn't figure out how to make them show up
ty
anyone know the issue (yes ik in ctx.send it says ban its a typo)
i wish i could help you but i'm also here for a question
ok
oh wait
?
yeskickbutton is only defined if there is no reason
if i understand what you're trying to do, you want those defined regardless (i think)
It's \` to escape them
ik
swear when i tried that it became mumbo jumbo
Gotta do it after each one
Np haha
whenever someone gets the opportunity, I am trying to utilize extensions to register my commands to the main script. Within my command additem.py, where the main function is additem(), I have written a setup like so:
def setup(client):
client.add_command(additem)
print("Loaded command: additem")
My code looks congruent to the examples as far as I can tell, but nonetheless I get the error
TypeError: The command passed must be a subclass of Command
this is up there with the most embarrassing questions i've ever asked, I forgot to add () to the end of the decorator @commands.command(). I only notice these things after I ask the question
been wrestling with this for 30 minutes just to notice it now
tysm 4 the help
np
is "discord.on_unknown_application_command" only for slash commands?
I can not call this event
what's wrong
@commands.Cog.listener()
async def on_application_command(context:discord.ApplicationContext):
await context.channel.send("L")
or
where is the self?
ohhhhhh my god
Is there anyway to make a fully public bot with website configuration with Pycord?
do you know python (Flask/Django), html and css?
my friend knows HTML and CSS im learning flask
Hi, is it possible to add a "fancy" name to a @user_command? I've seen it is some bots. For example a command with name="check_user" would like nicer with a facny name "Check User". Is it possible with PyCord?
if you create a group yes
How do I check if a user with a specific role is in a voice channel?
Use discord.on_voice_state_update event, and verify if the member has the role, and verify if they are in a voice channel through the after VoiceState.
Hey, i've got a question. How can i check when the guild emoji name changes, Looking thruthe docs on_guild_emojis_update will only get called once a emoji is created/deleted
There probably isn't a record in your table with that user id
are you able to create user_command with a bridge bot? I can't seem to find any documentation on it, although the docs state that it should inherit all the features of a regular bot
@bridge.user_command is a no go, so there must be something I'm missing
it's just @discord.user_command
Hello! I have a quick question
What I need it to do is when the user selects 2 of the choices it will send out a GIF that matches the 2 things that were selected. I tried looking on the DOCS but couldn't find anything or I'm not looking hard enough ( EX: The user clicks Red and Blue = Sends a GIF, User Selects Blue and Green = Sends a GIF )
class mix(discord.ui.View):
@discord.ui.select( # the decorator that lets you specify the properties of the select menu
placeholder = "Choose a potion", # the placeholder text that will be displayed if nothing is selected
min_values = 2, # the minimum number of values that must be selected by the users
max_values = 2, # the maximum 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="π‘",
description=""
),
discord.SelectOption(
label="π’",
description=""
),
discord.SelectOption(
label="π§",
description=""
),
discord.SelectOption(
label="π΄",
description=""
),
discord.SelectOption(
label="π΅",
description=""
),
]
)
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")```
async def button(ctx):
embed=discord.Embed(title=f"Choose Wisely!", description="",color=0x660066)
embed.set_image(url="https://media.discordapp.net/attachments/999932873077424128/1047271785298657310/unknown.png?width=459&height=586")
await ctx.respond(embed=embed, view=mix()) # Send a message with our View class that contains the button```
This is what I have so far
Can't you just check if two options has been selected? Through the length of select.values?
I'm not sure I understand
oh wait
So would it have to be a different callback for combination or how would I get it to select the 2 values and send the gif matching its combination
In your callback, check if two options have been selected, then just make if statements for the different combinations
okay let me try
It now gives this error
selection = self.values[0]
if selection == "π‘" "π’":
await interaction.response.send_message("https://media.discordapp.net/attachments/957163963588681788/957164412807036928/yg.gif")
elif selection == "π‘" "π§":
await interaction.response.send_message("https://media.discordapp.net/attachments/957163963588681788/957166502258286592/yc.gif")
lse>, <SelectOption label='π§' value='π§' description='' emoji=None default=False>, <SelectOption la bel='π΄' value='π΄' description='' emoji=None
default=False>, <SelectOption label='π΅' value='π΅' description='' emoji=None default=False>] disabled=False>:
Traceback (most recent call last):
File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 396, in _scheduled_task
await item.callback(interaction)
File "c:\Users\13129\Desktop\Python Bot\Slash.py", line 59, in select_callback
selection = self.values[0]
AttributeError: 'mix' object has no attribute 'values'```
Why are you doing self.values and not select.values?
Sorry, I thought it would be that because I saw self on the documentation. Iβll fix it
Why are you responding from two different accounts?
This is my main and the other is on my labtop
labtop runs the code and has the test/dummy account haha
@limber urchin I changed it to selection = select.values[0]
It gives no error in the terminal but says the interaction failed
And why are you only getting one of the selected values?
Does the 0 have to be 2?
Do you know basic Python?
It allows me to select the two colors
Started not long ago. Learning every day
Read rule 1 in #help-rules
Not sure if I'm still allowed to ask for help but I'm dumb... I knew what it was but was just acting before thinking. 0, 1, 2, 3 - I changed it to 1 as that takes 2 of the choices and it still gives me the interaction failed with no console error
?
Wrong reply
Why would changing it to 1 make it take 2 of the options?
Doesn't the numbering go by (0, 1, 2, 3, ETC.)? I changed it to the number 2 and it told me it was out of range but when I brought it back to 1 it worked again
Like I said, read rule 1 in #help-rules
I read it
That is not how Python works
you clearly do not know Python well enough to be making a bot yet
Thats kinda disrespectful ..
It is not
I have to learn/start somewhere
No
And a bot is not the right place to start
or learn
That's like learning to draw by painting the mona lisa
Making a discord bot isn't that advanced
It is obviously too advanced for you right now
Python is not hard to learn but without the basics you will have many problems
Read this
Oh okay. Having that background changes my view on it. 
Welp I'll try and figure it out. Thanks for the help
Is there anyway to make a fully public bot with website configuration with Pycord?
Why would it not be possible?
well i need help doing it
What do you need help with?
I mean yeah, to make a website you're obviously going to need HTML and CSS
And then you need a web server to make requests to
the only thing I rlly need help with is just getting the config from the website to the bot
Well you'd need to set up OAuth2 on your website to allow users to log in through Discord. Then you need to run a web server parallel to your bot that handles requests and applies configurations made on the website to a database.
okay thx
make it a tag
What should I call it? learnpython is already occupied
edit learnpython
Done
anyone?
ty
apologies guys, i keep coming back with odd questions
I've passed my BridgeApplicationContext to another file as ctx. As far as I can tell, there's no way to get the client id from this, correct?
ctx.user.id returns the id of the user who called the command (which is peculiar since ctx.author.id returns the same)
client as in the bot instance or as in the person who issued the command?
https://docs.pycord.dev/en/master/api/application_commands.html#discord.ApplicationContext.bot
https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Context.bot
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
or in other words, ctx.bot.user.id
i was traversing the docs for about 15 minutes and i swear i got lost in a maze
let me give this a go
that did the trick, i appreciate it
yw
how do i add buttons to an embed?
This is a misconception. Messages can have content, embeds, components, attachments, etc. They are all fields of a message. They are not mutually exclusive. Short answer, add it like normal
ohhh okay cool i thought there needed to be some special embed.add_button() or something. Thank you!
How do I get the invite used by someone when they join?
Can't seem to figure it out from the documentation.
Why are you mixing discord.Option and Option?
Can you mention a channel in an embed? <#somenumbers> doesn't seem to work
i noticed that the reason for the purge method does not show up in the audit log, but it should works as there a reason parameter
My commands arent loading in this specific cog:
class cc(commands.Cog):
def __init__(self, bot):
self.bot = bot
pyx = discord.SlashCommandGroup(name="pyx", description="PyX Server only commands", guild_ids=[933959481891622933])
@pyx.command(description="DM an user")
@commands.has_permissions(manage_guild=True)
async def dm(self, ctx, msg: Option(str, "Message to convey"), color: Option(choices=["Green", "Red", "Yellow"]), member: Option(discord.Member, "Member to convey to")):
if color == "Green":
color = discord.Color.brand_green()
elif color == "Red":
color = discord.Color.brand_red()
elif color == "Yellow":
color = discord.Color.yellow()
else:
color = discord.Color.dark_orange()
embed = discord.Embed(title="DM", description=f"```{msg}```", color=color)
embed.add_field(name="Sent by:", value=f"{ctx.author}")
embed.set_footer(text=f"Sent by {ctx.guild} | Hope you have a good day!", icon_url=ctx.guild.icon.url)
try:
await member.send(embed=embed)
except:
await ctx.respond("Member has DM's disabled", ephemeral=True)
embed = await successEmbed("Sent DM with no issues!")
await ctx.respond(embed=embed)
def setup(bot):
bot.add_cog(cc(bot))
syncing
I replaced a command but the old cmd is still there, but doesnt function ofc
yo
can we use @commands.cooldown decorator for bridge commands?
cuz there is @bridge.has_permissions deco for that
there is a bridge has perm
bz there are two types of has_permissions
one is internal, the commands one, the other is default_permissions
yes
it works for me
help
i see
not much familiar with the latest version
anyways thanks :D
pyx = discord.SlashCommandGroup(name="pyx", description="PyX Server only commands", guild_ids=[933959481891622933])
change name to cc
name="cc"
ah wait
cc = custom commands
didnt get u
so i had a previous /pyx verify cmd
I have a question:
Can I seta slash command for admin only by default? -> If the bot joins new server, several commands would have admin only permissions by default.
but i replaced it with dm
Um u mean permissions? or?
yup
but the verify cmd is still there and does nothing and dm cmd isnt there
@discord.default_permissions or @commands.has_permissions()
use both for safety as default_permissions may break
Thank you!
np
someone help pls
I cannot see your original message for some reason
hm? Must be a client side issue i guess.
same happened with me tho
it takes a while to register commands
i tried to bulk register , so
Β―_(γ)_/Β―
Probably. But if I understand correctly, I had a similar issue coz one of 2 reasons:
- there was a syntax error in my code (new code wasn't loaded)
- when using guild_ids=None -> it takes a time
u needa restart ur bot to register slash commands, don't u?
its been restarted for 48 hours!
guild_ids is not none
no syntax error
holy crap
same shi- is happening with me now π
if you specify guild_ids, it registers instantly for me.
nice ig its a bug
pycord 2.3 is full of bugs
not for me ig
rude pycord
yeah
it takes 24 hours to register slash commands in all the servers
meanwhile me using pycord 2.0
No that hasn't been a thing for a while
help me
Global commands register instantly now
please
i took a break from developing 6 months ago lol
What is it
meow
why are we facing such issues then 
i would rather recommend you not to test the pycord beta when it bugs too much instead of getting upset
im not testing
im on stable
pycord 2.3 is not beta
wait
is pycord 2.3 stable?
2.3 isn't particularly buggy? If I'm not mistaken it's one of the more reliable releases
bruh im lagging behind
But hm
.
Idk but I face some issues, lets get to my issue, not chat lol
you have 2.3.0 or 2.3.1?
So you have slash commands in other cogs that load?
im facing the same issue (but using 2.0)
yep
I did not mean the 2.3 that the 2.3 is stable I know but if you want to use the beta then do not do that if you have no idea
does it take time to bulk register slash commands?
And you're 1000% sure the cog actually loads
It shouldn't no
only that cog is having issues, logging is enabled, no ratelimiting, cog is loaded cuz i printed every loaded cog
cog cc was there
So let's say you print something in the cog's init as well
hm?
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
print(f"Loaded cog {filename[:-3]}")
In the cogs init function, not where you load the cog

Or alternatively, just print bot.cogs from some command
it printed it
Fair enough
What if you add your guild_ids to your command decorator as well? Not just the group?
meh both are same tbh
im using bridge commands
although its loading the prefixed commands, the slash commands dont get registered
Do you use guild_ids for all your other commands?
Are you using bridge.Bot
the cog only has one slash cmd group which has one cmd
yup
what about duplicate class / function names? you dont have any?
Yeah but in your other cogs
Or just use debug_guilds in your bots constructor, instead of adding guild_ids to all of your commands
No my bot is public
So?
only the cmds in CC cog are supposed to be guild-only
So theoretically if you moved these commands to an existing cog, they would load?
I dont know
Could you perhaps try
what about moving this outside of the class? coz its not pyx, but self.pyx in this case
pyx = discord.SlashCommandGroup(name="pyx", description="PyX Server only commands", guild_ids=[933959481891622933])
i do it like this for everything
I'm on mobile so I can't see quite correctly but uh
Is that has_permissions decorator indented?
yes
even if, that would raise an error if not lol
So if you instead changed it to discord.slash_command, does it load?
it isnt one right now?
Yeah same thing
Interesting
but my previous cmd in PyX isnt being removed
I don't think groups are broken on 2.3 though?
and the id is correct
Odd
I think so lol
Can you try reinstall 2.3
Already did
Iirc there weren't any changes
Nah they work fine for me
You're 100% sure another pyx group doesn't exist right
sure
can we have - in group names?
I don't think so? If I'm not mistaken it's limited to underscores
oh shit
But I think there's an internal check for that
Has to match this regex ^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$
Just use the search feature in VS Code to find duplicate names
My guess would be the huge magnifying glass that says "Search"
^^yes
Are you loading cogs in on_ready
How even
why :pepecry:
That's your issue I guess
How did you manage to do that?
whats the max number of commands i can register in a day
It says right there
^
Read the error
ah yes
You shouldn't sync/restart that often
If you're using cogs, you can reload them to update the command callbacks
oh
thats where i messed it up
wait
we are supposed to restart the bot to register slash cmds right?
Well yeah to initially register them
Not 200 times
Like the name, description, options etc
But after that if you're only updating the command's function/logic, you only have to reload the cog
yeah
i restarted it 3-4 times as the cmds were not getting "registered"
Hm
i obv didnt restart 200 times bru-
That being said I'm pretty sure you can sync without restarting the bot but that's the one thing that hasn't been fixed for a while
i guess u learn new things each day lmfao
Well that also used to be broken but it should be fine on 2.2 and above
@barren garnetr u overriding on_connect
Well his issue is that he can't sync at all for the rest of the day
Can't do much about that
ah sed times
so, will the cmds get registered within a day?
or do i hv to restart it manually tomorrow
could be bz of overriding on_connect
yes
You'd have to do it again
um
Bruh you literally said no earlier wyd
show ur on_connect please
no wait
im overridin start()
hm?
im using 2.0 π
@cyan quail i dont know abt what start() does but maybe its causing issues
update it, this aint like djs where u have big code changes
it shouldnt tho
it was working fine, until i added few more cmds
@cyan quail sorry for ping but,
is there a way for implementing both default_permissions and has_permissions into one for commands.Bot for commands that use SlashCommandGroup (if this even matters)
reading https://docs.pycord.dev/en/master/api/application_commands.html#discord.SlashCommandGroup, both are possible inside SlashCommandGroup itself
- pass in
default_member_permissionsas adiscord.Permissionsobject https://docs.pycord.dev/en/master/api/application_commands.html#discord.SlashCommandGroup.default_member_permissions - pass in
checksas a list of check functions fromext.commandshttps://docs.pycord.dev/en/master/api/application_commands.html#discord.SlashCommandGroup.checks
check decorators will work on individual subcommands, however note that default_permissions only works for the entire group; it can't apply to individual subcommands.
i have different perms for every cmd
I mean the cmd is inside a group
I want a way to have both the default_perms and internal check in one decor
don't think that's a thing
and again, the default_permissions decorator doesn't work on subcommands in the first place
does bridge.has_permissions apply both the checks?
oh
maybe? not sure
nvm then
How do I check if a role in a server exists?
Getting the role will return None if doesn't exist or not found
ty
How do i remove a option or edit one from a select menu? i can only find select.append but im looking for something like select.remove
How do I change the color of a role that I created:
await guild.create_role(name="Jail", colour=discord.Colour(000000), permissions=discord.Permissions
(permissions=0))
colour=discord.Colour(0xff0000)
after 0x add a hex code
ty
how can i check if a message is a system message?
is_system?
thats not a api reference
what do you mean by system message
but now it reacts to every message
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
Thx
oh
he still doesn't
show the menu
I'm using commands.Bot
don't do that
where are you saving the response for requests.get()?
oh
you're not trying to do that nvm
or are you
is the url in a string
Hi, I'm new to Pycord (and bot development in general), and was just going through Pycord Guide. I needed some help regarding my ENV file where my token is.
is the bot going to be open-source?
yeah so string
No, it's not.
what are you trying to do with the command
you should be fine just saving the token in a variable
m
any error?
The error I'm encountering is a TypeError, the token has to be in string format and even when I converted it to str type, it's still returning me that error. May I send you the code snippet?
why do you use requests?
uhh
_token = "(your token)"
without the ()
obviously
and then at the bottom
bot.run(_token)
'bot' being your bot variable
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/>
Alright, I'll try doing that. I was converting my token to string type using this:
import dotenv
dotenv.load_dotenv()
token = str(os.getenv("TOKEN"))
It didn't work though, for some unknown reason.
you have to do it at your own...
Did u import os?
yeah
I did.
Wait, I think I figured it out.
Alright, the TypeError is fixed but I came across another error.
discord.errors.LoginFailure: Improper token has been passed.
did you read the error?
Could anyone help me with this?
I regenerated my token and tried with the new one, but that didn't work.
I did.
I also double-checked if my token in the env file is under quotations.
how do i check again if the embed url is valid or not
embed url?
explain
embed.set_image()
how can i listen for member bans or kicks?
There is discord.on_member_ban
And unban
.rtfm discord.on_member_ban
Target not found, try again and make sure to check your spelling.
Fk this bot 
and kicks?
I couldnt find anything for that
do you know how i can filter this for timeouts?:
async for thing in ctx.guild.audit_logs(after=member, action=discord.AuditLogAction.member_update):
print(thing)```
Apparently its a limitation that there isn't a kick event, you can try using discord.on_member_remove, and fetch the audit log perhaps under that.
Do timeouts show up in audit logs?
thx
yes in member_update
Hmm no idea. Try looking in the docs
Persistent views?
bot.add_view(View())
Custom id on dropdown + None timeout on the view + adding the view as persistent view
Do all that and should be persistent
yes
Yes
but remember: It have to be in a class
Traceback (most recent call last):
File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
File "C:\Users\mario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Read the error....
Your bot is in a server without app cmd scope
?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
Your bot may be in another server and you may not know / forgotten
Print bot.guilds on ready and see how many guilds the bot is in
only the one
You must have specified a guild id for app cmds in which your bot isn't there
no guild ids specified
oh wait
i blame the other dev
im good now
check = cursor.find({"$and": {"guild_id": guild_id, "_id": author_id}})
(Pymongo) Does anyone know what the check returns if it doesn't exist? (Ik this isn't related to pycord)
How do I do that if it is not a url then it sends an error message
In embeds.0.image.url: Scheme "test" is not supported. Scheme must be one of ('http', 'https')
question. What's the best way to combine an f-string with a formattable token?
blah = 'asdf'
mystring = f"a={blah}&b={}"
This doesn't work because of course the {} is being evaluated at string creation. But I also cannot escape the braces. Looks like "old-style" % works.
mystring = f"a={blah}&b=%s"
# ...
myurl = mystring % 'jkl'
Is that the best way?
mystring = f"a={blah}&b=%s" + "jkl" Maybe this should work
Well I don't want to hardcode the addition; the string represented by "mystring" is a long querystring. I was trying to break up some aspects of it into f-string variables to increase readibility/reduce the length, but I need to combine it with the ability to apply dynamic data to the variable (Updated last example to reduce ambiguity)
How do i make the select menu show the selected option? it just goes to back to the empty placeholder every interaction
@discord.ui.select(
row=0,
min_values = 1,
max_values = 1,
options = [
discord.SelectOption(
label="Counts",
emoji="π’"
),
discord.SelectOption(
label="s",
emoji="π₯"
),
]
)
async def select_callback(self, select: discord.ui.Select, interaction: discord.Interaction):
await interaction.response.edit_message(content=select.values, view=self)```
mystring = f"a={}&b=%s".format("blah")
# ...
myurl = mystring % 'jkl'```
try this
Here is a example
class Dropdown(discord.ui.Select):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
options = [
discord.SelectOption(
label="Red", description="Your favourite colour is red", emoji="π₯"
),
discord.SelectOption(
label="Green", description="Your favourite colour is green", emoji="π©"
),
discord.SelectOption(
label="Blue", description="Your favourite colour is blue", emoji="π¦"
),
]
super().__init__(
placeholder="Choose your favourite colour...",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(
f"Your favourite colour is {self.values[0]}")
class DropdownView(discord.ui.View):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
super().__init__()
self.add_item(Dropdown(self.bot))
bot = discord.Bot(debug_guilds=[...])
@bot.slash_command()
async def colour(ctx: discord.ApplicationContext):
"""Sends a message with our dropdown that contains colour options."""
view = DropdownView(bot)
await ctx.respond("Pick your favourite colour:", view=view)```
Yeah, that's another option. I feel like that makes the initial string less readable, though. Will keep what I have for the moment (which also uses the %); I do appreciate the response!
Max_val
max_value =
placeholder="Choose your favourite colour...",
min_values=1,
max_values=1,
options=options,
)```
wait but how would i make it edit the original message? i dont want it to send a new one each interaction
What do you mean do you have to resend the message every time after selecting the roles?
Can you send a screenshot?
If it is this one then I recommend you to use PersistentView
do await interaction.response.defer()
and remove await interaction.response.send_message(f"Your favourite colour is {self.values[0]}")
what will that do
This will not answer the interaction
Because with edit_message it changes the message
so just await interaction.response.defer(DropdownView(self.bot))
Normally it is just await interaction.response.defer() but you also can try await interaction.response.defer(DropdownView(self.bot))
ah ok
Let me know if it worked
but now it gives This interaction has already been responded to before i mean the select menu is showing the item now
which is good, but now i cant edit the message hah
await interaction.response.defer()
await interaction.response.edit_message(content = f"Your favourite colour is {self.values[0]}", view=Dropdown(self.bot))```
should i do interaction.followup.edit_message()? or smth
This is because you have already queried the interaction with await interaction.response.defer() what exactly do you want to change in the message ?
i want to change the embed
like the text
the content
i want to
- select a option from the menu
- it shows up
- Content changes in the message
That means you want only "a" to be there when he changes the message
like lets say for example:
it starts with "hello"
and i click "bye" option
then it changes to "bye"
thats what i'd like
ok w8 i will try to do something
Thanks i appreciate it
class Dropdown(discord.ui.Select):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
options = [
discord.SelectOption(
label="Hello 2", description="Your favourite colour is red", emoji="π₯"
),
discord.SelectOption(
label="Bye", description="Your favourite colour is green", emoji="π©"
),
discord.SelectOption(
label="Bye 2", description="Your favourite colour is blue", emoji="π¦"
),
]
super().__init__(
placeholder="Choose your favourite colour...",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
if self.select.values[0] == "Hello 2":
await interaction.response.edit_message(f"{self.values[0]}")
elif self.select.values[0] == "Bye":
await interaction.response.edit_message(f"{self.values[1]}")
elif self.select.values[0] == "Bye 2":
await interaction.response.edit_message(f"{self.values[2]}")
class DropdownView(discord.ui.View):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
super().__init__()
self.add_item(Dropdown(self.bot))
bot = discord.Bot(debug_guilds=[...])
@bot.slash_command()
async def colour(ctx: discord.ApplicationContext):
view = DropdownView(bot)
await ctx.respond("Hello", view=view)``` try this
Error
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 were given
it needs string, and a view=
ups sorry i made a mistake
I'm pretty sure that solution is unrelated to the question amd won't solve it
content=""
try with self.select.values[0] self.select.values[1] and self.select.values[2]
TypeError: Dropdown.callback() missing 1 required positional argument: 'interaction'
@bot.command()
async def gtn(ctx):
await ctx.respond('Enter a number between 1 and 10.')
guess = await bot.wait_for('message', check = lambda message: message.author == ctx.author)
if (guess.content == '7'):
await ctx.send(f'You guessed it!')
else:
await ctx.send(f'No, try again.')
Spent the last one hour trying to figure out why the heck isn't this working. I just started learning Pycord (and bot development) btw.
The bot responds with the else block when the if block returns false, just like it should. However, when the if block does return true, the bot still prints the else block. Why is that?
put guess.content in str()
if self.select.values[0] == "Hello 2":
await interaction.response.edit_message(f"Hello 2")
elif self.select.values[0] == "Bye":
await interaction.response.edit_message(f"Bye")
elif self.select.values[0] == "Bye 2":
await interaction.response.edit_message(f"Bye 2")
yeah the issue is with the .edit_message
it needs a (content=f"{self.values[0]}", view=SOMETHING)
because then it doesnt know where to edit
This one work but just edit_message not ?
Wait, so guess.content is by default NoneType?
try it, but im assuming if someones message is just 7, it turns to a int
Why though.
idk man
try str()
I did, it worked (God knows why or how).
Thank you for the help, I genuinely appreciate it.
no problem
Try this
i did
same error
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 were given
this one ?
How many colors can you take 1 ?
if self.select.values[0] == "Hello 2":
await interaction.response.edit_message(content="Hello 2")
elif self.select.values[0] == "Bye":
await interaction.response.edit_message(content="Bye")
elif self.select.values[0] == "Bye 2":
await interaction.response.edit_message(content="Bye 2")``` try this
1 string aka "hello" or smth, and another which is view= to know where to edit
this will be the same error
yeah it is view use edit_original_message
TypeError: Dropdown.callback() missing 1 required positional argument: 'interaction' BRUHHHHHHHHHHHH
what is this lmao
Do you use edit_original_message
an this error comes ?
try await interaction.edit_original_message(content="ok")
ok last test
you forget something
same error
response
no
interaction.response
its interaction.edit_original_message
hmmm
says so in api reference anyways gn thanks for trying
await interaction.edit_original_message(content="Test", view=DropdownView(self.bot))
So on_webhooks_update has just channel as parameter, How can i tell if the before name is not the same as the after name?
What do you mean by "the button"?
You can create a view and an instance of a button and add it to the view
icl?
async def example(ctx, ...):
my_view = discord.ui.View(...)
my_button = discord.ui.Button(...)
...
my_view.add_item(my_button)
await ctx.respond(view=my_view)
Hey, is there a way to list who dmed my bot by any chance
discord.AutocompleteContext.bot
discord.AppInfo.bot_public
discord.AppInfo.bot_require_code_grant
discord.TeamMember.bot
discord.Bot
discord.Bot.activity
discord.Bot.add_application_command
discord.Bot.add_check
discord.Bot.add_cog
discord.Bot.add_listener
discord.Bot.add_view
discord.Bot.after_invoke
discord.Bot.all_commands
discord.Bot.allowed_mentions
discord.Bot.application_command
discord.Bot.application_commands
discord.Bot.application_flags
discord.Bot.application_id
discord.Bot.application_info
discord.Bot.before_identify_hook
.rtfm discord.Bot
discord.Bot.get_desynced_commands
discord.Bot.get_emoji
discord.Bot.get_guild
discord.Bot.get_message
discord.Bot.get_or_fetch_user
discord.Bot.get_partial_messageable
discord.Bot.get_stage_instance
discord.Bot.get_sticker
discord.Bot.get_user
discord.Bot.group
discord.Bot.guilds
discord.Bot.intents
discord.Bot.invoke_application_command
discord.Bot.is_closed
discord.Bot.is_owner
discord.Bot.is_ready
discord.Bot.is_ws_ratelimited
discord.Bot.latency
discord.Bot.listen
discord.Bot.load_extension
hmm cant seem to find it
Did you try reading the docs on the website?
Looking for some help with using custom emojis. I've never had luck using them. I've read docs that state that the bot needs to send in :AHYES~3:883745918128635904 format but discord seems to automatically remove the ID while it sends making it only send the name of the emoji. Any solutions?
@discord.slash_command()
async def test(
self,
ctx: discord.ApplicationContext,
emoji_name: discord.Option(str, description="The Emoji You Want To Test")
):
print(f"Emoji Name: {emoji_name}")
await ctx.channel.send(f"Here is the emoji: {emoji_name}")
await ctx.respond("Sent...", ephemerel=True)
It's <:AHYES~3:883745918128635904>
Then your bot isn't in a server with the emoji, or doesn't have permissions to use external emojis
that is a specific permission??
it has admin, and is in the guild the emoji was created in.
ahh got it. Emojis are annoying.
there were two emojis that looked the same but in 2 diff guilds. One the bot was in and one it was not.
my brain needs a break
I did, can't seem to find anything. However, apparently user has an attribute dm_channel which should return NONE if no dm channel is made with them
but running the code
@bot.command()
async def getservers(self, ctx):
activeusers = self.client.users
for user in activeusers:
if user.dm_channel is None:
continue
else:
print(f"User {user} has dm with you")
doesn't work (it should return me and it doesn't)
Well if you actually read the docs you should have found https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.private_channels
I did read the docs, I came across that, and I tried
@bot.command()
async def getservers(self, ctx):
dms = self.client.private_channels
print(dms)
for content in dms:
print(content)```
output:
[]
also the docs say that user.dm_channel should return a DMChannel object "if it exists"
sometimes you havenβt started a DM Channel with a user
im aware, im trying to find out which users have DM channels started
or does it only return ones where the bot initiated the dm channel
try it and see
I did, it returns nothing, even though I dmed the bot before I used it
Can a slash command re-call the same function without separating it out into some kind of helper function? I want to add a "play again" button at the end of a blackjack game without doing a bunch of refactoring
discord.EMoji doesn't work in option type in slash commands.
you can make a button class and redirect it to the original function.
ah that's a good idea
Because discord.Emoji is not a valid option type
that's not very helpful.
because, there are people who have raised this issue in github, however Dorukyum responded saying to use discord.Emoji. Therefore, i believe that it is a valid option type however, its just not working or broken
https://docs.pycord.dev/en/stable/api/enums.html#discord.SlashCommandOptionType
These are the option types that can be used
alright.
how do I send a message in a bunch of channels at once
I'll have a list of the channel IDs
and probably in a for loop I'd have to do something
and I don't know what that something is
I have somewhat of an idea but
I'll probably need your help
One of the best way to send a msg in a channel when you have an id is using bot.get_partial_messagable
.rtfm bot.get_partial_messagable
Target not found, try again and make sure to check your spelling.
Yeah that
Wrong spelling π
Pass the discord and text channel type
If you have a lot of channels then you might want to move away from using a for loop
It needs some asyncio knowledge tho
Create coroutines for the channel ids using list comprehension and then use asyncio.gather
Ignore this if you aren't familiar with asyncio and concurrency
I did
@client.event
async def on_ready():
print("Ok i started pinging")
while True:
for channel in channels:
cur = client.get_channel(channel)
await cur.send(f"<@&1047787659579379772>")
and it works
btw this is a spam ping bot
as you can clearly see it works lol
What's the DM equivalent for on_message()?
Hi, I needed some help. So, I've been trying the following method to run my bot using it's token in the ENV file:
import dotenv
dotenv.load_dotenv()
token = str(os.getenv("TOKEN"))
After this, I've created some basic commands. At the bottom, I've said:
bot.run(token)
This doesn't work for some reason, I triple-checked if I had defined the token file in the same directory as my script and if it was given under quotations (in the ENV file). What could be the possible reasons for this happening?
add print(token) and tell me what shows up
None
I think it's member.send().
yeah same
For now I've been doing that.
I'll try that
Although it's not very secure.
probably not
No, Windows.
open powershell,
then run
pip list | Findstr dotenv
This is the content of the ENV file:
TOKEN = ""
Under quotations is my token of course, lol
I'll try doing that
tell me what shows up
btw if you have dotenv and python-dotenv do
pip uninstall dotenv
pip uninstall python-dotenv
pip install python-dotenv
python-dotenv 0.21.0
ok so you have python-dotenv only?
This showed up on running pip list | Findstr dotenv
try reinstalling
Alright
it
Lmao ye. Yk what would be better? Rather than getting the channel each time in the while loop, get and create a list of them outside the while loop but inside the ready function. Loop through that
k
Perhaps
Same event. You would not have message.guild on it
that's good
Remove the spaces
that could be the problem?
Mostly
env files don't like spaces?
lol I didn't know..
sorry if you've uninstalled python-dotenv already.
Lol tias
You can use the asyncio.gather method and it would be much faster
On saying pip uninstall dotenv, it skipped it since "it was not installed". And on running pip uninstall python-dotenv, it did what it was supposed to.
Alright, I'll try that.
(Gotta reinstall python-dotenv)
This also didn't work.
I tried printing the token. Here's the output:
None
what's the DM equivalent of on_message()?
sorry for ping
I wanna listen for messages in a dm channel.
Ah okay, nevermind I fixed it.
dotenv.load_dotenv('token.env')
token = str(os.getenv("TOKEN"))
Here basically instead of 'token.env' (which is what the file is called), I was mentioning the entire path of the ENV file despite of it being in the same directory as my script.
I told you. You get it in the same event
o
How do I get an attachment in a slash command option? x: discord.File? x: discord.Attachment?
discord.Attachment
cheers
How would I make all my commands guild-only

I mean all my commands
Not adding the decorating to each and every one
I have no idea how to do this rip
in a recommended and safe way
why not?
I already have alot of cmds and I'm lazy
you dont even have to do it one by one?
Um how do I not do it one by one
That's my question here...
if value := self.children[0].value:
if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
await interaction.response.send_message(content="Url Invalid")
return
else:
embed.set_image(url=self.children[0].value)```it does not send my embed image
2 of my commands aren't registering wtf
there's no reason that I can think of as to why they aren't registering
they just.. aren't popping up in the slash commands list
Hm
Send the code of the cmd that's not registering
AND are you overriding on_connect
I made the top one to check if it was an issue with the thread_count command
@client.command(description="test command")
async def test(ctx):
await ctx.respond("Test complete!")
@client.command(description="Returns the ammount of threads there are; may take a while.")
async def thread_count(ctx, channel : discord.ForumChannel):
total_threads = 0
if channel.id == 1046978593059778661:
for thread in channel.threads:
await asyncio.sleep(0.5)
total_threads = total_threads + 1
await ctx.respond("There are " + total_threads + "in the forums channel.")
but neither register
@weak marlin discord.Bot I assume?
mhm
If you create another cmd, does it register?
Hm
Maybe check the integrations tab in server settings, that's what discord gives u
sure
^
async for thread
.
.
wdym by that?
Do you have a on_connect function
async for thread in channel.threads:
await asyncio.sleep(0.5)
total_threads = total_threads + 1
Traceback (most recent call last):
File "C:\Users\tsuyo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\tsuyo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\tsuyo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'async for' requires an object with __aiter__ method, got list
@weak marlin
you mean an on_ready?
No
well then I don't
think I found the problem
apparently I can't name a file "secrets"
that and
await ctx.respond("There are " + total_threads + "in the forums channel.")
had to change this to:
await ctx.respond(f"There are {total_threads} in the forum(s) channel.")
yeah it worked
oop need to remove those brackets
I don't know what you mean by file named secret but okay
Oh
I have a file named secrets that I import stuff from
Ohhhh
how do you remove all roles a user has?
do you know python?
yes
i just cant rembers the sytax for it
i thought it was this await member.edit(roles=[])
but it wasnt
remove_roles()
with one by one?
it's a coroutine
if value := self.children[0].value:
if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
await interaction.response.send_message(content="Url Invalid")
return
else:
embed.set_image(url=self.children[0].value)```it does not send my embed image
You're not sending the embed at all
clear but it is not the whole code
Then show the whole code
class MyModal(Modal):
def __init__(self, ...):
self.add_item(InputText(...)
async def callback(self, inter: discord.Interaction):
...
if value := self.children[0].value:
if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
await interaction.response.send_message(content="Url Invalid")
return
else:
embed.set_image(url=self.children[0].value)
...```this is the biggest part of the code but it is about the `self.children[0].value`
And what is self.children[0].value?
self.add_item(InputText(...)
And how do you know the URL is an image?
if value := self.children[0].value:
if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
await interaction.response.send_message(content="Url Invalid")
return
else:
embed.set_image(url=self.children[0].value)
```Well this is a Text Input the user can then write a link or not that is up to the user but if it is wrong an error should occur which is what happens with the code here but if the user enters a correct link the image is not sent at all just the embed title and description
That regex only checks for a valid URL, you still don't know if the URL points to an image or not
Oh and how do I do that ?
Dunno, I don't know how to write regex
But what I don't understand is if the URL is already checked I don't understand why I have to insert if it is an image or not
with this r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
So what if the user enters https://www.google.com
do you think that will show an image?
and how do i check now if it is a picture or not and how do i insert that in the code like this
Just do await member.remove_roles(member.roles)
For statement is a waste of time
def is_url_image(image_url):
image_formats = ("image/png", "image/jpeg", "image/jpg")
r = requests.head(image_url)
if r.headers["content-type"] in image_formats:
return True
return False``` is it possible to put that in my code
if value := self.children[0].value:
if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
await interaction.response.send_message(content="Url Invalid")
return
else:
embed.set_image(url=self.children[0].value)```
Also try to use asynchronous code everywhere in discord bots
It's highly recommended like so
?tag requests
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
np
I am getting AttributeError: 'Select' object has no attribute 'select_type' whenever using a channel select
the select is being sent normally, just can't be used
Py-cord version?
2.3.1
python 3.10.8
code```py
class View1(discord.ui.View):
def init(self):
super().init(timeout=None)
@discord.ui.select(select_type=discord.ComponentType.channel_select, placeholder="channels", channel_types=[discord.ChannelType.text], custom_id="channels_select", min_values=0, max_values=5)
async def callback(self, select: List[discord.TextChannel], interaction: discord.Interaction) -> None:
print(select)
await interaction.response.send_message("channels saved: \n" + "\n".join([c.id for c in select]))
yo guys is this valid python code?
a = dict.get("asd") or 0```
yes, but you can do a = dict.get("asd", 0)
ah, nice thanks
ctx.guild.default_role is everyone but is the one for nitro booster?
I probably found this issue
seems like select_type is missing in
https://github.com/Pycord-Development/pycord/blob/master/discord/ui/select.py#L66
discord/ui/select.py line 66
class Select(Item[V]):```
