#General Help
1 messages ยท Page 29 of 1
so i can't?
take a string or just take a user object
if i do discord.User as type. Could it take the ID?
maybe
are there interaction cooldowns?
how to send a second message after await ctx.responce
b!rtfm pyc followup.send
No results found when searching for followup.send in pyc
b!rtfm pyc context.followup
No results found when searching for context.followup in pyc
b!rtfm pyc applicationcontext.followup
No results found when searching for applicationcontext.followup in pyc
b!rtfm pyc followup
uh?
bot = discord.Bot(intents=intents)
AttributeError: module 'discord' has no attribute 'Bot'
edit: needed to install py-cord==2.0.0rc1, default will install to v1.7.3
Hello there, in the Discord API documentation, application command option type can be one of 11 values. (https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type)
Value 8 is ROLE (= discord.Role in pycord), which works as intended.
I don't see any existing type for a list of role, which would correspond to list[discord.Role] in pycord.
Does anybody know of any workaround?
My last resort would be to code an autocomplete showing all roles and leaving the option type as a str but if it was a built-in solution I'd rather use it hehe.
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
How do I define VoiceClient? My bot is in a voice channel but throws "NameError: name 'VoiceClient' is not defined"
when trying to execute the following code:
voice.play(discord.FFmpegOpusAudio("file.mp3"))```
What am I doing wrong?
If you're using this through a command and have ctx parsed then you can get the discord.VoiceClient for that specific guild through ctx.voice_client
Hey, what's the time out if you do use defer on a command ?
15 minutes
Awesome thanks ๐ป
Cane were help me? #994010481918492732 message
do role members api side not instantly update? when i do ctx.guild.fetch_roles() it says the role is empty of members, but has members in it on the server UI?
after some testing it looks like it can only see itself as a member?
yeah i feel like i'm going crazy, even after giving it admin/all the scopes i could think of i still can't see any other users when doing fetch_roles()
Why do you use fetch_roles when it's already cached tho
in the hope that it would do something different
I don't get you
caching doesn't always work. i remember there being issues with message content as well
at any rate i just tried the cached version and it has the same result
does seeing other members through roles.members require specific permissions?
I don't believe so, it works fine for me
try turning on all the intents
not sure if that will work
yeah i turned all intents on, tried different scopes... could you show me the code working for your bot?
and are you on rc1?
after further investigation output is the same between different releases. i'll make a thread in a minute unless anyone has ideas for why i can't retrieve members from roles
Btw how to make all button on a class like disabled?, Using self.stop() only make the buttons not responding
for child in self.children:
child.disabled = True
await interaction.response.edit_message(view=self)
Go over your commands and check the names
yo i found it
can an ephemeral reply be edited to non-ephemeral? i have a step that has to take place after a command is ran, but I don't want it to clutter chat, nor do I want other users to be able to mess with any components on it
async def webhook(self,ctx,member:discord.Member,*,reason):
await ctx.message.delete()
webhook = await guild.text_channels[0].create_webhook(name='Programx',avatar=None,reason='Bot Webhook')
url = member.avatar.url
async with aiohttp.ClientSession() as ses:
webhookm = Webhook.from_url(webhook.url, session=ses)
await webhookm.send(reason, username=member.name)
```
For this code, it creates a webhook every time the command is executed at the channel that the command is executed. Is there anyway to just create the webhook once and fetch the webhook afterwards without making a new one every time the command is executed?
Why isn't on_message_delete event firing? i've reduced my code to
print('hello world')```
but when I delete a message there's no output in the console. all intents are properly enabled and on_message works, so i'm not sure what i'm doing wrong.
Cane were help me? #994010481918492732 message
discord.errors.ExtensionNotFound: Extension 'errors' could not be found
even though i made the file it doesn't work
anyway this is the code
import discord
from discord.ext import commands
class Error(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(f"{self.__class__.__name__} is Ready!\n----------------------")
@commands.Cog.listener()
async def on_error(self, ctx: commands.Context, *, error):
if isinstance(error, Exception):
await ctx.send(f'{error.__name__}\n{error}')
def setup(bot=commands.Bot):
bot.add_cog(Error(bot))
nvm I figured it out
# /usr/local/bin/python3.10 /root/Bots/PublicBots/Bambus/main.py Traceback (most recent call last): File "/root/Bots/PublicBots/Bambus/main.py", line 32, in <module> bot.load_extension(f'/root/Bots/PublicBots/Bambus/cogs.{cog}') File "/usr/local/lib/python3.10/site-packages/discord/cog.py", line 783, in load_extension spec = importlib.util.find_spec(name) File "/usr/local/lib/python3.10/importlib/util.py", line 94, in find_spec parent = __import__(parent_name, fromlist=['__path__']) ModuleNotFoundError: No module named '/root/Bots/PublicBots/Bambus/cogs'
whats the problem?

Is there a way to check if an extension is already loaded?
nvm I read the wrong part of the docs
Is the init function triggered every time cogs are loaded even if they've just been unloaded or is it only on the first time a cog is loaded?
It cannot find the cogs folder
Figure out what the current working directory is and then load your cogs relative to that
So do print(os.getcwd())
And then supply any missing folders in the path for the cog when you use load_extension
how can I solve the problem that the webhook doesnt has a token associated with it
TypeError: issubclass() arg 1 must be a class
i was making a ticket cmd and when i pass in too many option arguments it throws this error
hey is it necessary for bot to have admin privilege to disable default role view for particular channel by doing this ? await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
Hi, how do you create a webhook?
Am struggling to finds the docs on creating it so am coming here to see if anyone knows how ๐
I meant the bot creating the webhook, not the user creating the webhook
@commands.slash_command(name="ticket",description="Creates a tickets panel")
async def ticket(self,ctx,channel: Option(discord.TextChannel,"In which channel",required = False),helpers: Option(discord.role,"Helpers",required=False)):
button = Button(emoji=":tickets:",style=discord.ButtonStyle.green,label="Ticket")
view = View()
view.add_item(button)
if channel is None:
channel = ctx.channel
async def btncallback(interaction):
guild = ctx.guild
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True)
}
global new_channel
new_channel = await guild.create_text_channel(f"{interaction.user.name}'s ticket",overwrites=overwrites)
button.callback = btncallback
em = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),title="Tickets",description=":tickets: Click the button below to make a ticket!")
await channel.send(embed=em,view=view)
await new_channel.send("test")```
Exception has occurred: ExtensionFailed
Extension 'cogs.support' raised an error: TypeError: issubclass() arg 1 must be a class
File "C:\Users\amito\Desktop\tests\cogs\support.py", line 6, in <module>
class Support(commands.Cog):
File "C:\Users\amito\Desktop\tests\cogs\support.py", line 16, in Support
async def ticket(self,ctx,channel: Option(discord.TextChannel,"In which channel",required = False),helpers: Option(discord.role,"Helpers",required=False)):
discord.Role
oh ty
how would i overwrite permissions for the helper role
Like edit the role?
yh
b!rtfm pyc discord.Role.edit
also i would have to put the helper role for every guild in a db right?
While sending a message, if i give a list with just 1 embed in the embeds parameter instead of giving it through the embed parameter, will there be any difference?
does anyone know how to fix this issue https://discord.com/channels/881207955029110855/994244891213320282
it finds it now but now are the cogs not working
Traceback (most recent call last): File "/root/Bots/PublicBots/Bambus/main.py", line 31, in <module> bot.load_extension(f'/root/Bots/PublicBots/Bambus/cogs/{cog}') File "/usr/local/lib/python3.10/site-packages/discord/cog.py", line 785, in load_extension raise errors.ExtensionNotFound(name) discord.errors.ExtensionNotFound: Extension '/root/Bots/PublicBots/Bambus/cogs/fun' could not be found.
how do I get my code to continue after a modal is canceled?
It just stops processing additional commands, appearing to the user like the bot has stopped until, timeout is reached
I could set the modal timeout to trigger some loop but I'd rather not if there's an alternative option
it does appear this is a discord limitation, but I wondered if there was a workaround
The workaround is to probably open an issue (if doesn't exist) or elaborate on the existing issue on the discord api docs
channel = await interaction1.guild.create_text_channel(f"mm-{interaction1.user.name}", topic=f"{guild.name} | Request ID: {numbergen}", category=category, overwrites=overwrites)```
error:
```Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\user\Desktop\Ayu Bot\main.py", line 250, in button_callback1
channel = await interaction1.guild.create_text_channel(f"mm-{interaction1.user.name}", topic=f"{guild.name} | Request ID: {numbergen}", category=category, overwrites=overwrites)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1170, in create_text_channel
data = await self._create_channel(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1051, in _create_channel
"id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'```
Every time
Alright thanks
with @commands.is_user(...), how do pass in multiple user IDs?
use many decorators
/root
try doing
os.chdir("/root/Bots/PublicBots/Bambus/")
Before loading your cogs with:
bot.load_extension("cogs.example_extension")
Thank you
youre a real legend
Lol thanks
btw @wicked ferry are you developing on ur pc and hosting on a separate machine?
Are you developing and hosting on that one server?
anyone?
looks like a problem with your overwrites
hmm i have the exact same code in a separate file and it works perfectly fine there..
Could someone give me a hand with this?
yes
can you show the code?
ping me when you are here
@stable torrent this is the relevant code. i have intents set as discord.Intents.all() and on_message() works which if im not mistaken requires the same intent.
print('hello world')```
this code, to my understanding, should print 'hello world' when a message is deleted, but it doesnt. ive tried deleting many messages in several channels.
Thank you so much for the help, by the way!
are you sure bot has permissions to view those channels?
yes, and it responds to on_message() events in the same channels appropriately
are you up to date?
try pip install git+https://github.com/Pycord-Development/pycord
just tried that, it uninstalled 'py-cord-2.0.0b5' and installed 'py-cord-2.0.0rc1', but still no luck
are you subclassing bot by any chance?
i'd like to see main file/bot file actually
will do! is pastebin ok?
yep
is there a quick way to check permissions for @/everyone?
list of perms that everyone has?
yeah, as in the "role" that shows up as @/everyone in the roles list
gotcha, thanks
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.
so guild.get_role(guild.id).permissions?
pretty much yes
alright, thank you!
i am going to scream thank you so much ๐ญ
im making a ticket comman nd i was wondering how would i send a message in the new made channel
get the channel id pass it to get_channel() and send the message
How can I check if a channel exists?
get_channel if that is None use Guild.fetch_channels than check if the channel is in that list. If it is not it does not exist.
if f"general-{interaction.target.name}" in interaction.guild.text_channels:```
would this work?
I think you have to fetch the channels if it is not in cache. Because discord does not send the channels when you look at the guild.
So you might have to add this in the else
if f"general-{interaction.target.name}" in interaction.guild.fetch_channels():
Also please only ask in one place.
Yea sorry for that :(
How do I add color to an embed?
color=""
from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.
What's the best way to make buttons work after restarting the bot?
Persistent views.
Here's the persistent example.
Thanks
color=0xYOURHEXCODEHERE
thanks
thanks
How do I put a description to the slash command?
description= in the decorator.
Thanks
File "C:\Users\natha\Desktop\venvs\artybot20\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\natha\Desktop\venvs\artybot20\lib\site-packages\discord\bot.py", line 1147, in on_connect
await self.sync_commands()
File "C:\Users\natha\Desktop\venvs\artybot20\lib\site-packages\discord\bot.py", line 770, in sync_commands
await self._bot.http.bulk_upsert_command_permissions(self._bot.user.id, guild_id, guild_cmd_perms)
File "C:\Users\natha\Desktop\venvs\artybot20\lib\site-packages\discord\http.py", line 359, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed```
Is this a bug?
This should've been fixed on the latest version.
Update to rc1
oh
Do I need to run the persistent view at boot up
or can I just make a command
like .activate
or something
A command would work too ig.
ImportError: cannot import name 'SuggestionButtons' from partially initialized module 'cogs.suggest' (most likely due to a circular import) (/home/container/cogs/suggest.py)
Brilliant
How am I supposed to do it then
I've just added it to the @bot.event
on_connect
You add persistent views on on_ready
@bot.event
async def on_ready():
bot.add_view(SuggestionButtons())
bot.persistent_views_added = True```
Should this work?
I've imported the SuggestionButtons class from suggest.py
Same error
Well, you should be able to find a way to prevent circular import.
Send what ur importing from suggest.py
is there anything like ctx.defer() but for buttons?
my button interaction takes longer than 3 seconds
b!rtfm pyc defer
discord.DeletedReferencedMessage
discord.DeletedReferencedMessage.channel_id
discord.DeletedReferencedMessage.guild_id
discord.DeletedReferencedMessage.id
discord.Embed.footer
discord.Guild.preferred_locale
discord.MessageReference
discord.MessageReference.cached_message
discord.MessageReference.channel_id
discord.MessageReference.fail_if_not_exists
b!rtfm pyc interaction.response.defer
No results found when searching for interaction.response.defer in pyc
Hm
b!rtfm pyc interactionresponse.defer
and you get interactionresponse from interaction.response
Couldn't find documentation for discord.commands.ApplicationContext.defer.
thanks! how to i send the actual message after i used defer? at the moment, i get "this interaction has already responded to before"
You can use a follow up message
b!rtfm pyc followup
can you give an example on how to use that? i'm too dumb. do i need to create a webhook for that?
await interaction.followup.send() I believe
Currently on the car and safari ainโt loading
no, interaction.followup creates the webhook for you
How do I add buttons to my message?
Here's the button roles example.
thanks
If I use interaction.channel.id when the button is in a thread, will I get the thread ID or will it return None?
guys help
@bot.slash_command(guild_ids=testbot, description="Mostra as estatรญsticas de alguem")
async def stats(ctx, player : Option(str, description="Nome do jogador")):
baseurl = "https://mush.com.br/api/player/"
endpoint = player
r = requests.get(baseurl + endpoint)
data = r.json()
rank = data['response']['rank']['title']
first_login = data['response']['first_login']
last_login = data['response']['last_login']
timestamp = first_login[:10]
await ctx.respond(f"<t:{timestamp}:d>")
this command manipulates an API here
here it is
first_login and last_login
they are timestamps
but it have more than 10 numbers
so the timestamp is wrong
i want to remove de aditional numbers
the last 3
i cant do .strip bcuz its an int value
oh
yes
ty
await ctx.command.invoke(ctx)
File "C:\Users\Davi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 357, in invoke
await injected(ctx)
File "C:\Users\Davi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 134, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
wtf
unknow interaction??
how
Most likely you took too long to respond ig.
you should defiantly look into using aiohttp over requests
Also think about deferring the response if it takes too long
Hey, I have a command that produces a graph and sends it in response to a slash_command. Using ctx.respond(file = discord.File(graphPath))sends an error, whereas ctx.send(file = discord.File(graphPath))sends the file but also a message saying "The Application did not respond". What command should i use to respond and send a file?
should I just do like an invisible ctx.respond first and then send file via ctx.send_followup?
ctx.response.defer() and then you could send it with ctx.send or however you like
Gotcha, thank you
Lol we just figured out that this was due to importing the wrong thing
ctx.response.defer() does work, but then the message "bot is thinking" persists for a while. I kinda prefer a ctx.respond message and then followup with file
Any dropdown menu examples?
Here's the dropdown example.
Hi.
How to make mypy happy about channel: Option(TextChannel)?
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label=":name_badge: USERNAME + HASHTAG", placeholder="e.g: Wumpus#0000"))
self.add_item(discord.ui.InputText(label=":underage: ALTER", placeholder="e.g: 187"))
self.add_item(discord.ui.InputText(label=":high_brightness: WARUM BEWIRBST DU DICH?", placeholder="e.g: Bin einf cool ka", style=discord.InputTextStyle.long))
self.add_item(discord.ui.InputText(label=":computer: HAST DU ERFAHRUNG?", placeholder="e.g: Ja hab Mee7 gecodet!", style=discord.InputTextStyle.long))
self.add_item(discord.ui.InputText(label=":thinking: WARUM GENAU DU?", placeholder="e.g: Ich kann 90s in Fortnite!", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Bewerbung!", colour = (discord.Colour.random()))
embed.add_field(name=":name_badge: USERNAME + HASHTAG", value=self.children[0].value, inline=False)
embed.add_field(name=":underage: ALTER", value=self.children[1].value, inline=False)
embed.add_field(name=":high_brightness: WARUM BEWIRBST DU DICH?", value=self.children[2].value, inline=False)
embed.add_field(name=":computer: HAST DU ERFAHRUNG?", value=self.children[3].value, inline=False)
embed.add_field(name=":thinking: WARUM GENAU DU?", value=self.children[4].value, inline=False)
channel187 = bot.get_channel(989603932995199026)
await interaction.response.send_message(f"{interaction.user.mention} Bewerbung wurde ans Team gesendet!")
await channel187.send(embeds=[embed])
@bot.slash_command(description = "test modal uwu ")
async def test(ctx):
modal = MyModal()
await ctx.interaction.response.send_modal(modal)```
Error:
```py
Traceback (most recent call last):
File "C:\Users\Noe\PycharmProjects\Bambus bot\venv\lib\site-packages\discord\bot.py", line 993, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Noe\PycharmProjects\Bambus bot\venv\lib\site-packages\discord\commands\core.py", line 357, in invoke
await injected(ctx)
File "C:\Users\Noe\PycharmProjects\Bambus bot\venv\lib\site-packages\discord\commands\core.py", line 134, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Modal.__init__() missing 1 required keyword-only argument: 'title'```
how to fix
You have to add a title
channel: discord.TextChannel?
you mean this?
if u want both Text and Voice
u use Union[discord.TextChannel, discord.VoiceChannel]
Here's the persistent example.
doesnt work
i did self.titel and did it in the super init
nothing works
it is title not titel
Thanks
Wait, it works without Option()?
Slash command btw
no, you need option.
Hi I fetched a message object and now I want to get the exact embed from the message and store it. How can I do this? I tried doing: embed = message.embed but it didn't work
Getting this error: AttributeError: 'Message' object has no attribute 'embed'

MyModal(title="")
odd. Never did for me. then again, I haven't tried it since beta.
i would recommend opening a thread for this.
and also use in the slash command
ctx.send_modal(modal)
Pretty sure its embeds
b!rtfm pyc Message.embeds
Docs are useful.
Can you give me example code?
Tried with ```py
@bot.slash_command()
async def test(ctx, chan: discord.TextChannel):
await ctx.respond(repr(chan))
But it doesn't show channel selection and `chan` is always None
Nvm, it actually DOES work
discord didn't refresh command arguments
I hate that
is there any way to hide the slash commands from guilds? so it only works in dms.
how would i make a slash command group only show to a certain role, i only see checks=[commands.is_owner().predicate], in the docs
pretty sure slash commands arent allowed in dms
they are
you can use them in dmยดs
ah alr
what is repr?
or am I just bad at python
It is the same as str() but with a different string.
https://stackoverflow.com/questions/1436703/what-is-the-difference-between-str-and-repr#:~:text=__str__ is used,string representation of the object.
Can I use the Pycord logo?
for?
right, probably fine
how do i refer to a method in a cog from a discord.ui.view class?
i dont have the bot object and thus cant initiate an instance
what is inside what
i have a seperate file from the main file with the cog in it
to use discord.ui.view i also have a seperate class there with the embed
how do i use a method inside the cog from the embed class
why can't you create the class inside the cog
i thought that was not good practice
It's only bad practice when you use more or unreadable code to do the same thing.
how would i remove something after a certain word in a string ?
basicly name returns
naruto-episode-1
but i want to remove the -episode-1 so i get just naruto
how would i remove that ?
i tried with .split but it idnt work
i had this animename = name.split("-episode-")[-1]
but it left the episode numbed
using name.split will return a list
.replace()
okey but what about the episode number that one changes
and item 0 of that list would be naruto
while item 1 would be the episode number
so name.split[0]
no
name.split("-episode-")[0] is the name
name.split("-episode-")[1] is the episode number
okey ill try that
nope it still says the episode number Xd
an no i cant do name.split("-episode-1")[0]
Xd
cause the episode number changes
okey i fixed it Xd
Thanks for the help !!
im still not sure how this fixes it
do i use inheritance?
well you can just use super() to get the method you want
I'm guessing it's impossible to know if a user has clicked a link button?
since link buttons don't have interaction_check
the issue is that the coroutine from the cogs uses self multiple times
yo! I'm trying to use https://github.com/Pycord-Development/pycord in my discord bot that uses it as a requirement. How would I have the server automatically install the developer version from the requirement.txt file if I'm hosting externally?
I just want the cd pycord then pip install -U .[voice]
I tried adding "git+https://github.com/Pycord-Development/pycord" but this wasn't enough for the setup script inside of the pycord directory
pip freeze > some_file.txt with the github version installed and inspect it to see the syntax for using git in requirements.txt
ahh it's referencing the local file path
py-cord @ file:///C:/Users/username/PycharmProjects/test-project/pycord
But it doesn't answer my question. What if I want something like channel: discord.Option(discord.TextChannel, "target channel")?
^^ I presuming I'm correct?
yep
link buttons cant have any functionality attached to them
thus its impossible to see if someone pressed the button
for the requirements.txt file is it possible to reference the local path and append an install command? for ex.
py-cord @ file://pycord+install -U .[voice]
mb if I should start a convo post, new to this server โค๏ธ
^^^^
how do I go by forcing it to go to 1 row down after "Quest Completions"?
I believe you can just set the row = 1 unless it starts with 1 then make it 2
hey is there a way to know who changed someone's nickname in an event
i could make it check the logs every time but is there a better way?
- plzz
Is there a keyword argument for intents for py ext.commands.bot
There is an attribute but I don't seem to find it anywhere (the keyword argument)
You need the message content intent
if i have an async function that does some stuff and returns some variables, how can i get these variables inside of my command function?
is there something similar to if it was a regular function i'd do a,b,c = function()
I have all intents on, but it doesn't seem to do anything
Did you pass it into your bot instance?
Ex.
client = commands.Bot(intents=discord.Intents.all())
i mean how would i await and get back the returned variables?
hello,
i have a problem
im new to pycord
i worked with discord.py before
File "/Users/tommy31/Desktop/py-tickets/main.py", line 3, in <module>
from discord.commands import permissions, slash_command, CommandPermission, SlashCommandGroup, Option
ModuleNotFoundError: No module named 'discord.commands'
im getting this error
Code smh
bruh
?tags install
-
Uninstall
discord.pyor any other forks of discord.py you might have with the namespacediscord.
python -m pip uninstall discord.py discord -y -
Install
py-cord
python -m pip install py-cord
Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.
Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
Updating to release candidate:
pip install py-cord==2.0.0rc1
Check if it is on release candidate
You might be on py-cord version 1.7.3
That version doesnโt support interactions and is just a fork of discord.py
ok
To check what version do pip freeze in terminal
i have the newest version
the 2.0.0rc1 one
do you have something else installed?
Make sure discord.py or any other forks of it bedside py-cord is uninstalled
Also any libraries that require discord.py
no
Trying it
just pycord
It works yo thanks
there is a way to edit messages via interaction?
like we have interaction.response.send_message as well
interaction.response.edit_message()
oh ty
guys help
i'm having trouble with API requests
@bot.slash_command(guild_ids=testbot)
async def api(ctx):
url = "https://mush.com.br/api/player/Panquekoo"
api = requests.get(url)
data = api.json()
rank = data['response']['rank']['title']
await ctx.respond(rank)
its an simple exemple
but the bot don't give any response
and like 20 secconds later appears a error message on console
Error 404 not found
unknow interaction
IT IS
also defer the interaction if it takes longer than 3 seconds
aiohttp is a dependency of pycord so it should already be installed
oh nice
there a way to remove all roles from a member and store all the role ids in a list
we know that there is a way
is there?
sorry
im testing out just getting a role list ive only got 2 roles but there is 3 in the list
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code:
10011): Unknown Role
getting this error when trying to remove roles
not sure how to go about fixing it
can someone teach me how to use aiohttp
there is documentation and a quick start thing. just google aiohttp
how do you turn a coma seperated string back into a list
ok
.split(",")
tried that but in getting it from a sql query and get this error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'sqlite3.Cursor' object has no attribute 'split'
can you show your code for it
Use cursor.fetch in place of cursor.execute
think ive done this wrong
Oop, fetchall I use a different lib than you
just to double check?
Yes, it might be nested in a list tho.
cursor.fetchall() takes no arguments (1 given)
would it be .execute then x = cursor.fetchall() ?
Ah yes sorry. Also now realizing that you only are returning one row so fetchone would be the best. :/ sorry for making it confusing
no worries :) im learning
somethin like that?
the split is also not working
A row object is similar to a dict. with the columns being the keys so doing.
roleList["RoleList"] will give you the value of that column. (This is so if you fetch more than one column you can get the right one.)
ah ok, thank you for the help :)
['988177984299081748,988606917301653525'] this is the list im getting out but i need it to be in the format
[988177984299081748, 988606917301653525]
and ideas?
still need the .url
is there a reason why rarity, name, patk, matk, defense, agt, element, classs, perc = asyncio.run(gacha()) isn't doing anything here?
https://pastebin.com/jA7pFAzY
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.
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (/home/runner/MetallicFrontDesign/venv/lib/python3.8/site-packages/discord/channel.py)
Did you uninstall discord.py
type โpip listโ in terminal and send the output
^^^
so discord and discord.py is still installed
ill show you the ouput when i unistall them
are you on replit
no
its a online linux vm
that i have
hm
i see what happended
i had discord in my requirements.txt
so it kept installing
Donโt remember, just some random reqs I copy pasted from and older project
I have two bots. One I use to test code and one that I run the tested and working code on. I created a command that shows the user's activity and it fully works on my test bot, but when the code is copy and pasted to the main bot the activity stops working. The attached image shows the difference when run, despite having the exact same code. I checked to make sure and it seems like both of my bots have the same intents enabled so I'm not sure whats wrong.
what version are you on?
an issue somewhat like that existed prior to #1365 on the repo but that PR isn't in 2.0.0rc1
you should probably update to the git master branch
Yeah I'm currently on 2.0.0rc1
yeah, i'd start by updating to the git repo and go from there
Im trying to get the message id of a response to a slash command and am doing message = await ctx.respond(embed=embed) but message.id doesn't return the right id
i'm so sorry to have to ask this but how exactly do i update
all good, do you have git installed?
yes
run this: py -3 -m pip install git+https://github.com/Pycord-Development/pycord
ok, done. looks like it didnt actually have to install anything. I just tested to see what would happen if I tried to host the main bot from the computer I use to host the test and it worked correctly. do you have any idea why that would be?
edit: they are both running the same version of pycord and all the libraries
tbh no, haven't heard of anything like that. could be failure to receive data on the other pc however not sure why that would happen
does your pip list look identical on both machines?
the one with a 1 drawn in is the machine that doesn't seem to work
pls any help
i don't see any way to fetch interaction
unless im tripping
okay so according to my research
u literally can't do this
cuz my end goal is to edit the slash command response
that's really weird, if anything I'd expect the other machine to not work as that one has discord.py and more installed, which causes namespace conflicts.
yeah thats definitely possible
message = await ctx.respond(embed=embed) will let message be an Interaction object, assuming its the first response
however, message.id will give you the Interaction object's ID, not the message
best bet to get the message:
interaction = await ctx.respond(embed=embed)
msg = await interaction.original_message()
how do I use bridge commands
it is cluttering to understand it
can someone give an example or smth?
Did you take a look at https://guide.pycord.dev/extensions/bridge/ yet?
Concept
If I use @tasks.loop to run a background task every x minutes, do I still need to tell the program to asyncio.sleep until it's supposed to run again? It feels like I'm doing things double currently.
No, tasks.loop automatically waits
Perfect, thanks!
Is it possible make a listener for auditlog?
how do you loop through a list of intigers and give the position
output:
added roles False out of30
code:
Its not in the event list you might be able to get it from the raw events or something
Extending this question, can the @tasks.loop be synced to the system clock or is it that way automatically? Basically wanting to undo any processing time and just keep the tasks at every two minute increment regardless of the processing time of each loop.
Ok thanks
Any idea why await ctx.respond and await ctx.response.defer() both might produce "Error 404 Unknown Interaction" but ctx.send() still works?
I think that is true. To test it you could add a asyncio.sleep() and wait a few minutes to see if it stays from schedule.
damn, forgot about index. thnaks :)
I had the asyncio.sleep() in there before set equal to the desired waiting time and over time it'd slowly creep second by second, but I guess I'll increase the sleep time and see if it still deviates.
respond and defer are attached to a interaction (slash command, button press, etc) discord allows for 3 seconds for you to respond before it deletes this interaction, if you still try to respond it will not be able to find the interaction.
send just sends a message attached to nothing. No time limit.
Could you send your code
Just checked. The asyncio.sleep() does affect the @tasks.loop so removing it should let it just loop normally. Maybe that was the slow desync I was experiencing, thanks!
guys help
i cant learn how to use aiohttp api requests
anyone recommend a yt tutorial?
one that is decent
Ohh, tysm. I didn't realize it would throw that error if past three seconds. I have yet to learn cloud databases/hosting, so I wrote some horrific workaround that saves data as a csv on discord and processing the csv takes more than 3s looks like. Putting ctx.response.defer() first works, thank you
yup, always make ctx.response.defer() the first thing in your command if it is going to take more than 3 seconds.
ctx.defer() exists
but I suppose they do the same thing and ctx.defer is really just a shorthand for ctx.interaction.response.defer
this is my slash command's code, i am trying to use the async def on_timeout coroutine but it doesnt seem to work, am i indenting in the wrong place?
you need to assign the timeout to the view, not the button
um i did that, i added timeout parameter to View
view = View(timeout=10)
view.on_timeout = on_timeout
yes_button.callback = yes_callback
no_button.callback = no_callback
view.add_item(yes_button)
view.add_item(no_button)
oh
you also need to override the on_timeout that's built in
is there a way to change the bot responce when defering from bot is thinking to something else?
nope
np
async def on_timeout(interaction):
yes_button.disabled = True
no_button.disabled = True
await interaction.response.edit_message(view=view)
await interaction.response.send_message("e")
view = View(timeout=10)
view.on_timeout = on_timeout
yes_button.callback = yes_callback
no_button.callback = no_callback
view.add_item(yes_button)
view.add_item(no_button)
just did that but it didnt work
define didn't work
so the timeout is working and what i mean is after the 10 seconds, the buttons dont respond leading to an interaction failed error, which is expected and mentioned on the guide as well that if the on_timeout coroutine isnt present then after the specified time the buttons will simple stop working. so the timeout is working just fine, but whatever actions i want the bot to take after the timeout which is specified on the on_timeout coroutine isnt happening
right, but you can't actually respond to a timeout
because there is no actual interaction
but in the guide it shows otherwise, that you can make stuff happen after the timeout, like edit the original message and say "the confirmation timed out" and disable the buttons and many bots have that feature in most of their confirmations
like this code here in the guide
class MyView(discord.ui.View):
async def on_timeout(self):
for child in self.children:
child.disabled = True
await self.message.edit(content="You took too long! Disabled all the components.", view=self)
@discord.ui.button()
async def button_callback(self, button, interaction):
...
@bot.command()
async def button(ctx):
await ctx.send("Press the button!", view=MyView(timeout=30))
you are editing the buttons, but not the buttons in the view
right, it doesn't respond to an interaction, simply edits a message
so where am i going wrong in my code? i am kinda confused right now
the whole on_timeout
async def on_timeout(interaction):
for children in view.children:
children.disabled = True
await interaction.edit_original_message(content = "e", view=view)
still didnt work
the ss above after the 10 secs timeout
the code:
async def on_timeout(interaction):
for children in view.children:
children.disabled = True
await interaction.edit_original_message(content = "e", view=view)
view = View(timeout=10)
view.on_timeout = on_timeout
yes_button.callback = yes_callback
no_button.callback = no_callback
view.add_item(yes_button)
view.add_item(no_button)
am i supposed to like rename children to button? and in the view.children to my button's name?
no, view.children is a list of all the buttons and select menus in your view
Here's the slash options example.
ty
well it still didnt work me , i have kept this is as the code and the timeout stuff still doesnt work
async def on_timeout():
for children in view.children:
children.disabled = True
await interaction.edit_original_message(content = "e", view=view)
view = View(timeout=10)
view.on_timeout = on_timeout
yes_button.callback = yes_callback
no_button.callback = no_callback
view.add_item(yes_button)
view.add_item(no_button)
Is there a particular reason that you aren't using classes?
well its coz this command is in a cog
that doesn't stop you from creating another class inside of it
i just thought that maybe it was possible without making a class and considering i have already coded 75% of the other code in the same command without a class
if i just use a class unexpectedly for just the timeout feature wont it mess with the rest of the code in the command
Do the button callbacks even work
yea the button callbacks work perfectly fine
only timeouts are giving an issue
how does it mess around with the rest of the code?
as per me for using the timeout in a class i will have to recode the whole command from scratch, i was trying to avoid that
you don't need to?
how?
i have no idea how i can fit in the subclass in my view
yes_button.callback = yes_callback
no_button.callback = no_callback
class MyView(discord.ui.view):
def __init__(self):
super().__init__(timeout=10)
self.add_item(yes_button)
self.add_item(no_button)
async def on_timeout():
for children in self.children:
children.disabled = True
await interaction.edit_original_message(content = "e", view=self)
literally only your view needs to change
okie
oi thanks
@bot.slash_command(guild_ids=testbot)
async def api(ctx):
async def main():
async with aiohttp.ClientSession() as session:
async with session.get(f'https://mush.com.br/api/player/{player}') as response:
print("Status:", response.status)
data = await response.json()
rank = data['response']['rank']['title']
type = data['response']['account']['type']
first_login = data['response']['first_login']
timestamp = str(first_login)
await ctx.respond(f"rank: **{rank}**\n type: **{type}**\nfirst_login: **<t:{timestamp[:10]}:d>**")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
guys help
this is my code
i tried to make an api request using aiohttp and asyncio
inside an command
but it does not work
please don't tell me you never learned asyncio
no
sorry to tell this to you
but im new to python and im just asking for some help
async with aiohttp.ClientSession() as session:
async with session.get(f'https://mush.com.br/api/player/{player}') as response:
print("Status:", response.status)
data = await response.json()
rank = data['response']['rank']['title']
type = data['response']['account']['type']
first_login = data['response']['first_login']
timestamp = str(first_login)
await ctx.respond(f"rank: **{rank}**\n type: **{type}**\nfirst_login: **<t:{timestamp[:10]}:d>**")
you only need this
forget about everything else
just that
p.tag idw
Command "tag" is not found
?tag idw
No tag idw found.
p.tag
Command "tag" is not found
p.tags
Command "tags" is not found
that's great
._.
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.
type pip list and send output
ok sorry
oh damn, alr thank you for helping me so much
discord and discord.ui
uninstall discord and discord.ui
got rid of them
and still the same error
restart the server
nope still the same issue
uninstall py-cord then install py-cord
does py-cord come with discord & discord.ui stuff?
I'm presuming I don't need to install discord and discord.ui?
pycord already had this stuff
how do I respond to a view interaction on a slash command so the "This interaction failed" message doesn't appear?
I can't use ctx.respond since it interprets this as responding twice to the main slash command.
Using followup works for completing the desired task, but the view still registers as non-responded
you respond to a button click/select menu selection with interaction.response.send()
b!rtfm pyc interactionresponse
discord.InteractionResponse
discord.InteractionResponse.defer
discord.InteractionResponse.edit_message
discord.InteractionResponse.is_done
discord.InteractionResponse.pong
discord.InteractionResponse.send_autocomplete_result
discord.InteractionResponse.send_message
discord.InteractionResponse.send_modal
discord.InteractionResponseType
discord.InteractionResponseType.auto_complete_result
b!rtfm pyc 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
if I'm using subclasses selects and buttons, does this need to be done in the callback within the class? or can this be called within the slash command?
callback
How could I format the traceback on on_command_error
what traceback
I mean, get the traceback
exception.__traceback__
This one returns the traceback of the ctx.invoke
How do you make choices in a slash command
Here's the slash options example.
It shows choices in one of them
Is there a way to make a cog's on_ready run when it's reloaded?
@commands.Cog.listener() is the decorator you want to use
This is the code:
class Logs(LemonCog):
def __init__(self, bot):
super().__init__(bot)
self.log_channels = {}
self.on_ready_fired = False
@commands.Cog.listener()
async def on_ready(self):
if self.on_ready_fired:
return
self.on_ready_fired = True
for name, channel in self.bot.config["logs"].items():
log = self.bot.get_channel(channel)
webhook = discord.utils.get(
await log.webhooks(),
name=f"{self.bot.user.name} logs")
if webhook is None:
webhook = await log.create_webhook(name=f"{self.bot.user.name} logs")
self.log_channels[name] = webhook
When the bot is started as normal, it reads the webhook and sends the message, but when i use a /reload command that reloads a certain cog, it says the webhook is None
Im doing this correctly right?
@commands.Cog.listener()
async def on_member_join(self, member):
print("worked")
guild = member.guild
one = guild.get_role(995034830473527346)
two = guild.get_role(995033551047237732)
member.add_roles(one, two, reason="Automated Join Request")
spacing is bugged btw
doing what right
for some reason print("worked") isnt even being called
the listener
check intents
Did you have the members intents?
: o
If there are erros in the console you should post the entire error when asking
there wasnt any weirdly
oh, strange
yea
it was just blank
and wasnt working
got it working now
i forgot await lol
it shoulve said enable tramollic(i forgot the name)...
new error : o
403 Forbidden (error code: 50013): Missing Permissions
Kinda self explanatory
Bump 
wdym
Was the bot invited with applications.commands perms? ^^
Yes, i believe so
Is the bot above the role it needs to give
And above the user's highest role you're trying to give the role to
the code basically adds a role to a new user
oh
im stupid ๐
i need to sleep
I do it so much lmao
What is the best way between @discord.ext.commands.slash_command() and @discord.application_command() ?
Or is there an other even better way?
wdym?
Sorry I meant @discord.ext.commands.slash_command() and @discord.slash_command()
I've always used @discord.ext.commands.slash_command() as the decorator for commands in my cogs, but I wanted to know if there was a better way to do so
Because I discovered that @discord.slash_command() was a thing
How can I install the latest version?
py -m pip install -U py-cord --pre
I mean, just do the shorter one. There's also discord.Cogs
Well depends if you want the latest stable or the pre release
2.0 is newer than rc1
So there are no difference ?
no, just made it llke that so i think easier to migrate?
because discord.ext.commands.command
i think
OK thx!
is there a way to make a member option in a slash command that only shows members with a specific role?
you mean autocomplete
sure?
How can I have a slash command bot and a prefix command?
bridge commands
Concept
?guide
?tag guide
Thank you
It does not work for me, it does not respond to the command
Bump bump
which command
The one in the example
the slash or the prefixed
both
Learn how to use the commands extension for Pycord.
And slash?
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
Thanks
What permissions do I need to create PermissionOverwrites on a category? I'm trying to have my bot create a category and then add overwrites to it, but it always fails at the second step with a 403 Forbidden: Missing Permissions error.
My bot has permissions to view channels, manage channels, and manage roles. I don't believe anything else should be required for what I'm trying to do. Giving the bot Administrator makes everything work, but turning on all guild-level permissions aside from Administrator does not work (and just giving the bot Administrator is not a solution that is on the table for me).
upgrade py-cord version to 2.0
I'm on 2.0.0rc1.
check application.commands scope on the dev portal under oauth2 and invite bot with new url then update pycord to 2.0 stable
I'll try that, thanks ๐๐พ
ctx.respond(embed=embed)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
help
thats not the entire error
we need more information
but
have you tried adding an await?
await ctx.respond(embed=embed)```
RuntimeWarning: coroutine 'BridgeContext.respond' was never awaited
ctx.respond(embed=embed)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
yeah add an await before ctx.respond
true thanks
class pending_button(discord.ui.Button):
def __init__(self, original_user, *args, **kwargs):
self.original_user = original_user
super().__init__(
*args,
**kwargs
)
async def callback(self, interaction : discord.Interaction):
guild = interaction.guild
user = interaction.user
role = guild.get_role(995143525882658877)
if role not in user.roles:
interaction.response.send_message(content="You do not have permission", ephemeral=True)
else:
view = discord.ui.View
view.add_item(item=discord.ui.Button(disabled=True, label="Status: Approved", style = discord.ButtonStyle.success))
interaction.edit_original_message(view=view)
DM_channel = self.original_user.create_dm()
await DM_channel.send("Your investigation has been accepted.")
interaction.response.send_message(content="Successfully changed status.", ephemeral=True)
TypeError: add_item() missing 1 required positional argument: 'self'
Am i tweeking rn
I dont see it
Im tired arent i
view.add_item is telling me i need self
oh i forgot () at the end of discord.ui.View
Dumb general question. I see that str's on the web version of Discord don't allow for new lines in Slash Commands while mobile does (odd difference, but mobile allows for an enter key while web doesn't). Anyone know of any loopholes to go about that for the web version? I tried adding a \n to my text but it doesn't add a new line.
how do i use has_permissions and bot_has_permissions checks in the latest version of pycord?
not quite sure how to make select members show up on an option in the slashcommand
how do i make certain events / commands only execute in a certain guild?
how to disable autosync slash command
Check the id of the guild where the interaction happened
how? are there any docs on this?
@open bear rtfm pyc Interaction.guild
How do I load command categories in the cogs folder like this
cogs
- Admin
ใ ค~ ban cmd
ใ ค~ kick etc - Info
ใ ค~ more commands
i currently have this but this doesnt work
the commented stuff is without the categories
please ping me if you know it
for f in os.listdir('./cogs'):
if f.endswith('.py'):
bot.load_extension(f'cogs.{f[:-3]}')
just realized that this is the same code that you have above
is it not working?
no because i need to load the folders with the commands in them in the cogs folder
this just load the files in the cogs folder but there are no files in there, only category folders
why do you have each command in a separate file?
you mean folder?
no
what
do you have a separate file for every command?
yes
lol why would you do that
that's like against the point of having cogs
instead of having separate folders for the categories i.e(admin, info, etc)
no its more orginised
well you do you ig
but nobody knows how to do it?
for each in f[2]:
should it not be for each in f:
for folder in os.walk("./cogs"):
for file in os.listdir(f'./{folder}'):
if file.endswith('.py'):
bot.load_extension(f'cogs{file[:-3]}')
actually just try the second one
Hey guys! I have a problem with responding with an embed to a slash command. Is it even possible? The command works when responding with a string, but not when i respond with an embed, it also doesn't return any error. Code:
stockembed = discord.Embed(title="Stock", description=f"{stock} stock left.", color=0x00ff00)
await ctx.respond(embed=stockembed)
Any error?..
doesnt return any error
What's the bot output
im sorry for wasting your time, it just fixed itself after 4 restarts 
are there still reasons to use rc1 over stable?
@commands.command(name="afk",description="afk")
async def afk(self,ctx,reason = None):
if reason == None:
reason = "Reason not provided"
data = await self.bot.pg_con.fetchrow("SELECT * FROM afk WHERE user = $1 AND guild = $2",str(ctx.author.id),str(ctx.guild.id))
if data:
if data[0] == reason:
e = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description="You are already afk with that reason")
await ctx.reply(embed=e)
await self.bot.pg_con.execute("UPDATE afk SET reason= $1 WHERE user= $2 AND guild= $3",reason, str(ctx.author.id), str(ctx.guild.id))
else:
await self.bot.pg_con.execute("INSERT INTO afk (user,guild,reason) VALUES ($1,$2,$3)",str(ctx.author.id),str(ctx.guild.id,reason))
embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{ctx.author.mention} You are now afk for: `{reason}`")
await ctx.reply(embed=embed)``` it says asyncpg.exceptions.DataError: invalid input for query argument $1: 984856281946943598 (expected str, got int) in line
i tried making them strings
but now it says
int is required
How long do buttons stay active? I noticed after some time they become unclickable
Hey ! How can I edit a slash_command response message after a send_message ?
typically interaction.edit_original_message is used; there's a rather convenient shortcut for this, ctx.edit
can u help w my error asw
uhhh let's see
well
it kinda says it already, it's expecting you to use string IDs
oh
but if i use str() it asks for ints
what error exactly did you get here
@commands.command(name="afk",description="afk")
async def afk(self,ctx,reason = None):
if reason == None:
reason = "Reason not provided"
data = await self.bot.pg_con.fetchrow("SELECT * FROM afk WHERE user = $1 AND guild = $2",str(ctx.author.id),str(ctx.guild.id))
if data:
if data[0] == reason:
e = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description="You are already afk with that reason")
await ctx.reply(embed=e)
await self.bot.pg_con.execute("UPDATE afk SET reason= $1 WHERE user= $2 AND guild= $3",reason,str(ctx.author.id), str(ctx.guild.id))
else:
await self.bot.pg_con.execute("INSERT INTO afk (user,guild,reason) VALUES ($1,$2,$3)",str(ctx.author.id),str(ctx.guild.id),reason)
embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{ctx.author.mention} You are now afk for: `{reason}`")
await ctx.reply(embed=embed)
####################################################################
@commands.Cog.listener()
async def on_message(self,message):
if message.author.bot:
return
data = await self.bot.pg_con.fetchrow("SELECT reason FROM afk WHERE user = $1 AND guild = $2",str(message.author.id),str(message.guild.id))
if data:
embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{message.author.mention} ; Welcome back from your AFK!")
await message.reply(embed=embed)
await self.bot.pg_con.fetchrow("SELECT FROM afk WHERE user= $1 AND guild= $2",str(message.author.id), str(message.guild.id))
if message.mentions:
for mention in message.mention:
data2 = await self.bot.pg_con.fetchrow("SELECT reason FROM afk WHERE user= $1 AND guild= $2",str(message.author.id), str(message.guild.id))
if data2 and mention != message.author.id:
embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{mention.mention} is currently AFK for reason: `{data2[0]}`")
await message.reply(embed=embed)
await self.bot.process_commands(message)
``` this is the full code
and the error is
oh wait
am i supposed to make only the user id a string
that error's on arg $2
while the first was on arg $1
so you're using both string and int ids simultaneously
so what do i do i dont get it
well
i use str() only on one arg?
you just have to match your datatypes correctly
data = await self.bot.pg_con.fetchrow("SELECT * FROM afk WHERE user = $1 AND guild = $2",str(ctx.author.id),str(ctx.guild.id))```
so seemingly from the errors, authors are strings while guilds are ints
hm
idk why but the bot disagrees
๐
just try str(ctx.author.id), ctx.guild.id i guess
okay ty
How do we access text voice channels?
Just normally with bot.get_channel? I donยดt find any ChannelType related to text voice channels
Or are these channels just threads?
else:
await self.bot.pg_con.execute("INSERT INTO afk (user,guild,reason) VALUES ($1, $2, $3) ", str(ctx.author.id), ctx.guild.id, reason)
embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{ctx.author.mention} You are now afk for: `{reason}`")
await ctx.reply(embed=embed)```
it says
syntax error
near user
in the INSERT INTO line
but i dont see any error
Hey guys, Am I the only one who has troubles with slash_commands in cogs after update? My commands just don't appearing...
send code
commands.slash_command
it imported from it
wait sen full ss without cropping
lol nvm
why does no one return
if there is such a guild
guild = client.get_guild(990641478164430918)
print(guild)```
my bot throw this error after that last update, what happend here?
new permission system in discord
someone?
I haven't had any problems
Is your client in that guild?
yes
for i in client.guilds
print(i.id)
See what that displays
@median aurora try fetching the guild
It might not be in the cache yet
I don't need this at all the fact is that I do a daily check by importing a file with a check function and the problem is that I can't get the bot to work before it is connected and I lack python knowledge
async def on_ready():
if __name__ == '__main__':
timer = Timer(3, check(client))
timer.start()
timer.join()```
<...>
asyncio.run(role_delete())```
client = commands.Bot(command_prefix = '!', intents=disnake.Intents.all(), test_guilds=[990641478164430918])
guild = client.get_guild(990641478164430918)
print(guild)```
Can I see your error?
You can try client.fetch_guild
if check.is_dev(ctx.author.id):
num = 0
devs_list = ""
for dev_id in database.dev_ids():
num += 1
dev_mention = f"<@{dev_id}>"
devs_list += f"`{num}.` {dev_mention}\n"
dev_em = discord.Embed(description=devs_list, color=database.theme_color)
dev_em.set_author(name=f"Devs List", icon_url="https://cdn.discordapp.com/emojis/979609228845129738.png?size=96")
await ctx.respond(embed=dev_em)
else:
errorEm = discord.Embed(description=f":error: You are not authorized to use the command.", color=database.error_color)
await ctx.respond(embed=errorEm, ephemeral=True)
Error: 'function' is not iterrable
dev_ids()
I know the error is due to for inin statment
but how to fix it
it returns a list
of all ids
You need a separate variable for thay
no..
Oh nvm
show your code for the dev_ids function
Hopefully it has a return statement
doesn't feel like it does
#dev IDs
def dev_ids():
with open(f"{config_file_path}", "r") as config_file:
configD = json.load(config_file)
return configD["dev_ids"]
can you show the full error?
Print configD really quick*
'_MissingSentinel' object has no attribute 'request'
helps only installing 2.0.0rc1
No like, the entire thing
when using client.fetch_guild
{
"dev_ids": [
808255522019999766,
432801163126243328
]
}
are you sure thats all there is?
ye
hm
none
Weird
if i make a var for that funcs then when i make a change in list and again call the var it shows the old list only
@median aurora can you do this for me real quick.
Print out that function in this script*
Also print the type along with it
๐ค
empty
Your sure your client is in the specified guild?
It would display there if you were in it
yes
That's odd then
Hm
is there no ctx in bridge_command anymore?
@slender lintel anything?
the error must be caused by something else then
Then iterate through the variable
its becoz i called a func in for in statement
Did that fix it?
no i knew it
BuBut how to I don't
Basically
ids = db.dev_ids()
for item in ids:
Do your stuff here
That's what I meant
wait i think i have tried this
but i will again now wait.....
Alright
same err
If that doesn't work either.
ids = list(db.dev_ids())
for item in ids:
Do your stuff hereโ
That'll convert it into a list object
@past gate what's your thoughts on this?
same
err
What's the error again
sounds good
same prob like me herehere: https://stackoverflow.com/questions/22633530/python3-typeerror-function-object-is-not-iterable
I'm just confused how it takes your list object as a function
recheck now
Right above the for loop can you print out that function and its type and send it here.
print(ids)
print(type(ids))
Whatever the variable was
<class ''list'>
@slender lintel
@past gate
I am now AFK
Set your AFK: No reason specified.
@slender lintel
Are you sure your error was on that line?
My bad
#list devs
@slash_command(guild_ids=database.owner_guild_ids, name="list-devs")
async def list_devs(self, ctx):
"""Shows bot devs"""
if check.is_dev(ctx.author.id):
num = 0
devs_list = ""
dev_ids = list(database.dev_ids())
for dev_id in dev_ids:
num += 1
dev_mention = f"<@{dev_id}>"
devs_list += f"`{num}.` {dev_mention}\n"
dev_em = discord.Embed(description=devs_list, color=database.theme_color)
dev_em.set_author(name=f"Devs List", icon_url="https://cdn.discordapp.com/emojis/979609228845129738.png?size=96")
await ctx.respond(embed=dev_em)
else:
errorEm = discord.Embed(description=f":error: You are not authorized to use the command.", color=database.error_color)
await ctx.respond(embed=errorEm, ephemeral=True)
What in the world
.
@commands.command(name="afk",description="afk")
async def afk(self,ctx,reason = None):
if reason == None:
reason = "Reason not provided"
data = await self.bot.pg_con.fetchrow("SELECT * FROM afk WHERE user = $1 AND guild = $2",str(ctx.author.id),ctx.guild.id)
if data:
if data[0] == reason:
embed = discord.Embed(color=discord.Color.from_rgb(13,99,143),description="You are already afk with thtat reason!")
await ctx.reply(embed=embed)
await self.bot.pg_con.execute("UPDATE afk SET reason = $1 WHERE user = $2 AND guild = $3",reason,str(ctx.author.id),ctx.guild.id)
em = discord.Embed(color=discord.Color.from_rgb(13,99,143),description=f"Updated reason to: `{reason}` ")
else:
await self.bot.pg_con.execute("INSERT INTO afk (user, guild, reason) VALUES ($1, $2, $3)",str(ctx.author.id),ctx.guild.id, reason)
embed = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),description=f"{ctx.author.mention} You are now afk for: `{reason}`")
await ctx.reply(emebd=embed)``` it says there's a syntax error after the last else statment near or at user
i dont see any
Print dev_ids(the variable one)
ive been stuck on this for hours ๐
Ik I saw you a while ago ๐
imma pay u fr if u fix it
Hello, is there any possible ways you can make a parameter that is adjustable?
For example :
.pay {member} 2000
and
.pay 2000 {member}
I want to make a pay command which has 2 parameters and those parameters can switch place depending on the user input
send the error tracE?
I'm officially confused
me too!
It shows the list. Says it's a list. But then it tells you it's a function
You can detect if it's a number vs a string
plzz slove
me in tuis prob from morning
look at your code
what if the file doesn't exist
the dev_ids call has to be returning None
No no. It prints everything correctly
theres no other way
anyone knows whats wrong with mine?
@past gate no joke. It prints everything fine. But says it's a function ๐