#Basic Pycord Help (Quick Questions Only)
1 messages · Page 68 of 1
is there a way to have no timeout for a button?
Here's the persistent example.
Hay, how do i edit/update an embed ?
You edit the message with a new embed
E.g
embed = discord.Embed(...)
message = await channel.send(embed=embed)
embed.description = 'New description'
await message.edit(embed=embed)
thx that helped a lot
The timeout is set on the view timeout=None and the items in that view will continue to function until the bot is restarted
how do i edit an embed posted through an interaction ? .edit seems not to work on interactions
interaction.edit_original_repsonse
ty
How do I make a discord.Attachment object to a bytes object?
I may have missed it but how would I import my token from env or a txt. Prefer a TOKEN.txt so I can add it to a gitignore
If it's a text file just read it like normal
And why wouldn't you be able to add a env file to gitignore?
i want to do the .env route
TypeError: expected token to be a str, received NoneType instead
in my .env file DISCORD_TOKEN = “token”
import os
import random
import discord
from dotenv import load_dotenv # used to import the token from the .env file
#print(sys.path)
#defining the global variables
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.all()
client = discord.Client(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_ready():
print("Bot is now online!")
client.run(TOKEN)
this is a 100% private bot just because it is my first one using pycord.
I dont know why it is not working I tried updating things put the token in by itself it is fine but cant seem to find the env
You never call load_dotenv though?
your env should also look like
DISCORD_TOKEN=AVERYSECRETTOKEN
There should be no spaces or quotation marks
I believe quotation marks are fine, but they're not necessary
still, best practices, right?
oh, that would help on the next step. I had needed them on the last bot I made periods and spaces were messing that one up for some reason.
this is better... I think Improper token has been passed.
what's your bot ID?
Thank you. Apparently the small space in front of the token was enough to cause the failure. Same with the quotes.
thank you.
yay
yw
Where do you host the bot?
is there any need to use something like Reactor Pattern (https://en.wikipedia.org/wiki/Reactor_pattern) with a pycord bot? i assume pycord already has event handling built in
This section outlines the different types of events listened by Client. There are two ways to register an event, the first way is through the use of Client.event(). The second way is through subcla...
Is there a function to get all messages from a user ?
is title supposed to be in here?
await interaction.response.send_modal(TestFormModal(info=self.info, type="one"))
TypeError: TestFormModal.init() got an unexpected keyword argument 'title'
i tried putting it there
Learn how you can implement Modals in your Discord Bot with Pycord!
that error is what i got
pls ping if u reply 🙂
Code:
import json
import discord
from discord import option
from discord.ext import commands
bot = discord.Bot()
class createMessage(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(description="Create a new message.")
@discord.default_permissions(manage_guild = True)
@option("channel", description="Select the channel where the message will be sent.")
@option("raw", description="Upload the embed's JSON raw file.")
async def create_message(self, ctx: discord.ApplicationContext, channel: discord.TextChannel, raw: discord.Attachment):
global msg_channel, embed
raw_content = await raw.read()
raw_data = json.loads(raw_content)
embed = discord.Embed.from_dict(raw_data)
msg_channel = channel
success = discord.Embed(
title = "Message Created!",
description = f"Created by: {ctx.author.mention} [`{ctx.author.id}`]",
color = 0x2B2D31
)
await ctx.respond(embed=success, view=Components())
class Components(discord.ui.View):
"""Buttons for previewing or sending the message."""
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Send", style=discord.ButtonStyle.green)
async def send(self, button, interaction):
pass
@discord.ui.button(label="Preview", style=discord.ButtonStyle.gray)
async def preview(self, button, interaction):
await interaction.response.send_message(embed=embed, ephemeral=True)
def setup(bot):
bot.add_cog(createMessage(bot))```
Error: `discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body`
`In data.embeds.0.description: This field is required` 🤔
im prolly wrong but is it this line?
await interaction.response.send_message(embed=embed, ephemeral=True)```
bc the embed doesnt exist
it does?
oh ok sry
global variables suck
why not just pass the embed to the view init?
and why tf do you have a bot instance in the extension file 
your class must be missing this
(the args and kwargs thing)
Hello. I wanted to know if it is possible to make it so that I can send a command let's say "controller" in which there will be two changing buttons start and stop registration. When you press start in another channel, the start registration button will be launched, and when you click on stop registration, this button in channel will be disabled.
Can use some kind of ID
Why not?
You should only have 1 instance throughout your code
Well what's causing the problem exactly?
@modsettings_class.command(name="mod", description="Edit moderator roles", guild_ids=[guild_id])
@discord.option(name="action", description="What action to perform", autocomplete=actions)
@discord.option(name="role", description="Role to do actions for. There is no need of this field if using the action \"view\"." ,autocomplete=modactions)```
the option "action" doesnt show.
```py
async def actions(ctx):
return ["add", "remove", "view"]
async def modactions(ctx : discord.ApplicationContext):
if ctx.options[0] == "view":
return ["view"]
else:
return discord.SlashCommandOptionType.role```
Hey, does anyone know how to create User Commands from within a Cog? I've tried @commands.user_command(name="Test") but it doesn't seem to work
i need some assistance
It's @discord.user_command()
Global variables
^
Why autocomplete for actions when it has fixed 3 choices
that should work
What's the issue
print(f"Got guild: {guild.name}") # Prints correct guild name
times = 0
category = discord.utils.get(guild.categories, name=f'order{times}'.lower())
print(f"Got cat: {category}")
if category is None:
print("Category is none, making category") # Goes up to here, then no longer does anything. No errors in console
category = await guild.create_category(name=f"order{times}".lower(), position=0)
print(f"Created cat: {category}")
right_channel = discord.utils.get(bot.get_all_channels(), name=f"{name}".lower())
print(f"Got channel: {right_channel}")
if right_channel is None:
right_channel = await category.create_text_channel(f"{name}".lower())
print(f"Creted channel: {right_channel}")
await right_channel.send("Hi")```
Nothing happens after ```print("Category is none, making category")```, no errors in console, nothing printed. Guild is correctly fetched, bot has all correct permissions. What could be the problem?
anyone know
i don't understand 🤔
honestly i don't work with __init__() method much personally
sorry
autocomplete doesnt work sometimes when we edit previous values.. why is that man?
async def test(self, ctx: discord.ApplicationContext):
await ctx.respond("Ok")
await ctx.guild.create_text_channel("yo")```
My bot can't create channels or categories at all. It also seems like it can't get channels or categories by name or id, as it just returns None despite existing. Why could this be?
Nevermind, I made a new bot and everything works now. I think discord ratelimited the bot
If you got rate limited you need to fix the piece of code that got you rate limited. Making a new bot is only a temporary fix.
i would avoid fetching guild
get_guild should be enough
i have a quick question, for this line of code right here, instead of setting every role in the server, how do i only change the permissions for one specific role, eg ('verified' or 'moderator')
await channel.set_permissions(ctx.guild.default_role, view_channels = True, reason = f'{ctx.author.name} unlocked {channel.name} with --server')
Instead of passing guild.default_role , pass the role object of the role you want to set for
You can get the role object using guild.get_role(id)
Oh alright, thanks
how do I give slash command options a Description?
Set that in the decorator
.rtfm slash_command
discord.commands.slash_command
discord.ext.commands.Bot.slash_command
discord.Bot.slash_command
discord.ext.commands.AutoShardedBot.slash_command
discord.Permissions.use_slash_commands
discord.AutoShardedBot.slash_command
discord.PermissionOverwrite.use_slash_commands
discord.ext.bridge.Bot.slash_command
discord.ext.bridge.AutoShardedBot.slash_command
pass description="..."
tyvm
any way to retain previous modal inputs?
yes
how do i retain the previous values aside from saving them on a database?
url=
uh
Im not sure if its possible
self.children[num].value would return the modal item values. Not sure what you mean by "retaining" them
ohh i was doing some validations on modal inputs, but after submission, the modal resets
i tried await interaction.response.send_modal(modal=self) but it did not even work means the modal did not reappeared
so i was trying to make the previous input be the same as the previous input of the user
You cannot "chain" modals
This is a Discord limitation
i see so retrieving them from the database is the only way then
thanks
How fix it'
bots can't run slash commands from another bot, can they?
Means el is an int
How I can decide this problrem
I already try all methods
uhhh
bruh
item is an int
debug with prints
your sql query literally says SELECT rowid

how do i make my button a fixed size like this
how to pass a variable (res) to a discord.ui.View class? sorry for a rather stupid question but i havent used classes a lot before
class logging_command_view(discord.ui.View):
@discord.ui.button(label="Enable logging", style=discord.ButtonStyle.primary)
async def button_callback(self, button, interaction):
await interaction.response.send_message("You clicked the button!")
@bot.slash_command(description="Logging information and settings")
async def logging(ctx):
hasPermission = checkPermission("command:permissions:logging", ctx.author)
if not hasPermission:
await ctx.respond("You have insufficient permissions to do that.", ephemeral=True)
return
res = dbexec(1, f"SELECT messages_deleted, messages_edited FROM logging WHERE server_id = {ctx.guild.id}", fetch=1)
await ctx.respond("This is a button!", view=logging_command_view())```
are you trying to pass res to logging command view?
yep, i want to adjust the style of buttons depending on that variable
and i suck on classes so i have no idea how to do that
then you should override the init and store it on self
smth like
class MyView(View):
def __init__(self, res, *args, **kwargs):
super().__init__(*args, **kwargs)
self.res = res
that way you can access self.res wherever you have access to self in your class
oh right, thanks :)
also i would name classes in PascalCase instead of snake_case
right
oh if you want to do that then you will need to add buttons using the add_item method instead of the decorator
ok ill read the docs about it, thanks
Hello. How i can edit interaction.send_message?
Im trying
msg = interaction.response.send_message(embed=embed, view=view)
msg.edit(embed=new_embed)```
But doesnt work. Any idea ?
send_message doesn’t return the message object
use interaction.edit_original_response to edit the msg
Thanks. And just use embed=new_embed? like interaction.edit_original_response(embed=new_embed)?
mhm
how can I add other people as bot owners (so they pass the check is_owner())
I guess I'll make a custom check
set their ids when creating the bot instance
bot = commands.Bot(... , owner_ids = [...])
thanks
Possible to create a listener in pycord that listens for specific HTTP requests instead of Discord events?
Not with just pycord, no. You have to use something like aiohttp
As long as it's async
Okay ill try
class TestFormModal(discord.ui.Modal):
def __init__(self, plan, type):
super().__init__(timeout=None) # timeout of the view must be set to None
self.add_item(discord.ui.InputText(label="mail"))
self.plan = plan
self.type = type```
where would i put it?
i need to pass in plan and type
super().init(*args, **kwargs)
TypeError: Modal.init() got an unexpected keyword argument 'plan'
self.plan = kwargs.pop('plan')
self.type = kwargs.pop('type')
tried this as well no luck
You should also pass *args and **kwargs to the init
class TestFormModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)```
this is what i have and it gives that error
def __init__(self, plan, type, *args, **kwargs)
super().__init__(*args, **kwargs)
self.plan = plan
self.type = type```
Hello
I have a bot that’s made to regularly send messages to a set of channels. And it’ll do it all at once sometimes
So is there a limit by discord on how many messages can be sent before it being blocked ? Do I have to wait some time between every message (smth like half a second)?
How do i make an embed send when a button has been pressed? i've tried this:
await interaction.response.send(embed=n)```
It’s .send_message not .send
oh okay
i still get the same error
Yes, there is a rate limit on all endpoints.
``AttributeError: 'Interaction' object has no attribute 'send_message'`
^ General rate limit is 5 api calls per second
interaction.response.send_message
Are you using that
ohh i missed out response
uhh idk how to resolve thisdiscord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In data.embeds.0.thumbnail.url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').
You're sending an invalid url as the thumbnail, just like the error tells you
Alright, thank you both
i need to check if a user has sent a message in a channel
how can i check?
how do you attach video on an embed? embed.set_image definitely works on image but embed.video is not like set_image and a video does not work on set_image
You cant
Discord only allows setting images by bots
i have this function in a separate file
how is this thing working?
i thought when it went to that function whole control was only/i need to do everything what pycord does to connect to discord
Your interpreter is clearly telling you something is wrong
Run the bot and see what's the error
its not error, its pylint
i was asking how it worked
it wants me to follow some strict rules and here i am just testing it so didnt follow..
i see so only embeds allowed with vids are from social platforms then
No idea what you mean
its okay
thats correct
why would it not? 
so member has everthing to do validation etc.. and all the work?
you sure you have the correct pycord installed?
also ctx was not passed
ctx was not needed
everything work, and i want to know why
well member is an object of the class discord.Member
the library implements all the stuff that the api offers in there
if you are talking about the typehints, those are just hints. Although the slash cmd uses this to figure out the option type. so yeah you basically dont need to directly deal with the api. the library does it for you
really? i thought you need ctx to retrieve the member from the guild using the bot to edit that member??????
okay
its passed as argument in command
thanks both for helping
i didn't help though 😅
How do I replace Auth.COMMAND_PREFIX with a normal command_prefix?
usage = f"{Auth.COMMAND_PREFIX}{cmd_name} "
atleast u tried
When I replace it with usage = f"{command_prefix}{cmd_name} " I get the error NameError: name 'command_prefix' is not defined
.rtfm context.clean_prefix
And what should I do with it?
I just need this line with command_prefix
you wanted the prefix right?
gonna need more code. like where this is being used and where command_prefix was defined
The command_prefix is defined in another file
I want to display it or I make hard code
||you could just use context.prefix if you have access to context||
otherwise use bot vars to use a variable across files
?tag bot_var
No tag bot_var found.
Can I do that in one line?
?tag botvar
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
do what?
But I dont want that at all
I want to display the command_prefix
is command_prefix the prefix of your bot?
and do you have access to context?
Yes
Context is not defined

Im sorry
gonna need more code to help you
I send it to you privately
im wanting to get the content of a message in a
tasks.loop() but how do i do it?
is there any way to let my flask app get some data from a guild?
anything other than ipc
message.content
oh okay ty
it is better to directly communicate with discord api?
Doing that frequently will get you ratelimited
How can I embed a users name, tag and profile picture as title?
How can i cretae a channel wich is only visible for a specific role? Can anyone help me or say how i can find it in the docs?
str(user) would give name#discrim user.avatar.url would give the url
.rtfm embed.set_author for the "title"
I tried that but it doesnt work
overwrites argument
.tag idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
Thanks
Here user_av would not be defined
And that doesnt work either
I copied this from another code
And what is user?
I corrected await ctx.send(embed=em) that was the problem
And now the tag should be displayed
How can I do that?
just str(user)
can you put view classes in a separate directory in their own files and import them as needed?
yes
It works now but I want to add the tag
.rtfm user.discrim
Thats not what I need
what do you mean by tag?
The Discord tag like Spliqc#0001
the 0001 is the discriminator
you to build anything, you need to learn how to read the docs.
🥲
em.set_author(name=f"{str(user)}", icon_url=user_av.url)
It works now thank you
Learn all about Context Menus (User Commands & Message Commands) and how to implement them into your Discord Bot with Pycord!
thanks for your help
Hi, so when I execute a slash command, it seems it's actually running twice..? The normal output comes, but then a "sending command..." message above it leads to this (see attachment below)
with the error on top and the expected output below
although those buttons are also not working as intended, but that's a separate issue
Send code
use ctx.respond instead of ctx.send
sorry if this is a stupid question, but why?
OHHH WAIt
it's because the interaction expects a response
i seeee
yes
thank you :)
np
how do i set button to unactive
cuz that stupid vscode doesnt want to tell me possible functions 💀
||typehint when|| discord.Button for button and discord.Interaction for interaction
set button.disabled to True and edit the message again with the updated view
oh alright
Sorry to bug again, but I have 3 buttons within my VIew class, yet only one is showing up when I actually run the command:
class ReactionRolesView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Announcements", custom_id="button-announcements", style=discord.ButtonStyle.primary)
async def button_a(self, button, interaction):
...
@discord.ui.button(label="1v1s", custom_id="button-1v1", style=discord.ButtonStyle.red)
async def button_b(self, button, interaction):
...
@discord.ui.button(label="2v2s", custom_id="button-2v2", style=discord.ButtonStyle.green)
async def button_c(self, button, interaction):
...
i don't think it's actually using this class, since the ButtonStyle isn't even correct, but I can't figure out what else could be happening
The code that calls creates the instance of the view and attaches it to a message
Never mind! I've figured it out. I had left a duplicate class (I moved stuff around in a rework of my project) and the message was using that instead of the one above ;-;
coding is pain fun
These damn things that always do exactly what we tell them to do, not what we want them to do 🤪
FR
How can I get the two embeds to be deleted after await asyncio.sleep(3) has expired?
Error: py Traceback (most recent call last): File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\client.py", line 378, in _run_event await coro(*args, **kwargs) File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1164, in on_connect await self.sync_commands() File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 719, in sync_commands registered_commands = await self.register_commands( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 588, in register_commands data = [cmd["command"].to_dict() for cmd in filtered_deleted] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 588, in <listcomp> data = [cmd["command"].to_dict() for cmd in filtered_deleted] ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\commands\core.py", line 1183, in to_dict ] = self.default_member_permissions.value ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'flag_value' object has no attribute 'value' Code: py admin = SlashCommandGroup( "admin", "", default_member_permissions = discord.Permissions.administrator ) Please help 🙏
add in ctx.send delete_after, example: delete_after = 3
msg1 = await ctx.reply(...)
...
msg2 = await ctx.send(...)
await asyncio.sleep(3)
await msg1.delete()
await msg2.delete()
Or alternatively use this. That's a cleaner way of doing it
Do you mean that?
yes, now you can also remove await asyncio.sleep(3)
if they don't want anything after that
Try passing discord.Permissions(administrator=True) instead
thanks, that seems to work
how to get a user by id?
For what?
@fervent cradle
That is not how you get a user by the id
Target not found, try again and make sure to check your spelling.
.rtfm guild.fetch_member
If you have member caching enabled
https://docs.pycord.dev/en/stable/api/models.html#discord.User.id
This is seriously most I can say to help with the question... Is he trying to make a command which lets you ping someone to then get that users id or idk
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
I don't have the guild, I'm trying to get a user who isn't in the server.
Oh, I’m not sure if that’s possible.
A bot’s range typically doesn’t extend beyond the guild that it’s in (for security reasons), and also I doubt Discord’s API supports that
I could be totally wrong tho, so leave it to a staff member to give you a definitive answer :>
bot.fetch_member
will that get a user who isn't in contact with the bot in any way
But you need the users exact Tag for that to work though.
You need the id
I oh wait by id, oof thought he wanted the user id
Every user got his own ID
.rtfm bot.fetch_member
Target not found, try again and make sure to check your spelling.
.rtfm fetch_member
First one
Target not found, try again and make sure to check your spelling.
Mhm
isn't this restricted to just the server that the bot is in though?
all 3 of these
.rtfm bot.fetch_user
*user
Uh
ohhh this makes sense
you can fetch a user by their ID, but most operations require you to share a guild with them
pretty cool
hence, the difference between user and member
How would I get and return a members name? Not to mention but say I wanted to reply to a /hello command with Hello {name here}!"
Is that person the one who executed the command?
Yes
so to link it together: ctx.author.name
Ahhh thank you. That worked I was trying to pull it from the message.
is there any way to track people who react to a message?
.rtfm message.reaction
AttributeError: 'ClientUser' object has no attribute 'create_dm'
async def on_raw_reaction_add(payload):
guild = client.get_guild(redacted)
member = guild.get_member(payload.user_id)
if payload.channel_id == redacted:
if payload.emoji.name == "🔊":
roletogive = discord.utils.get(guild.roles, id=redacted)
await member.add_roles(roletogive)
try:
# Use the 'User' object associated with the 'Member' object to create a DM channel
dm_channel = await member.create_dm()
# Send the message to the DM channel
await dm_channel.send('You have signed up for a ping.')
except discord.errors.Forbidden:
pass```
What is weird is, it works fine for me
You're getting an error, but you say "it works fine for me". Do you need help or does it work?
I need help on why the bot would throw it out anyways
Traceback (most recent call last):
File "/home/nolsen/.local/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/home/nolsen/bot/bot/bot.py", line 820, in on_raw_reaction_add
dm_channel = await member.create_dm()
File "/home/nolsen/.local/lib/python3.10/site-packages/discord/member.py", line 189, in general
return await getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'```
why create a DM channel while you can just send it
Is there a reason you're creating a DM channel and not just using member.send ?
Isn't it needed now?
thanks
is there anyway i can get a message just from it's id?
.rtfm bot.get_message
tysm
this is probably a very dumb question, but is there a way to add buttons to a view with the @discord.ui.button decorator without manually defining them in a custom view class? because i would like to create many buttons using the decorator based off data that i have
i know about discord.ui.Button, but the callback with only the interaction argument has proven it very difficult to update the style of the button, given that the button clicked will be just 1/25 in a view
any help would be greatly appreciated
have you looked into subclassing Button ?
that gives you such a callback async def callback(self, interaction)
where self is the button object itself, and self.view will give the view object
if you have largely similar callbacks for many button, you could use this and only need 1 subclass for all those buttons
you can even override the init if you want to set some attributes or stuff on self
Here's the button roles example.
that is an example of button subclass
thank you. i did indeed think of that, im just not sure how to update the style of the button to the view, even when i have access to the button's self
while creating the button, you could set that in the init (or super init)
if in the callback, you could do self.style = ... and then edit the message with self.view
oh, that does make sense! its real late for me, but ill give that a shot in the morning. i think i see how that works
thank you!
np 🙃
@discord.option(name="channel", description="The channel to set as the log channel", type=discord.SlashCommandOptionType.channel)
this also shows the categories and voice channels, but i only want text channels
specify channel_types
thats another parameter
.rtfm channeltype
discord.ChannelType
discord.ChannelType.text
discord.ChannelType.voice
discord.ChannelType.private
discord.ChannelType.group
discord.ChannelType.category
discord.ChannelType.news
discord.ChannelType.stage_voice
discord.ChannelType.news_thread
discord.ChannelType.public_thread
discord.ChannelType.private_thread
discord.ChannelType.directory
discord.ChannelType.forum
pass a list of whatever of these you want
how come this is saying i passed 3 arguments when i only passed 2?
msg = await mychannel.fetch_message(mychannel.id, msgid)
What is the name of the error on cooldown
show the error
but i think we should use channel.history
.rtfm TextChannel.history
TypeError: Messageable.fetch_message() takes 2 positional arguments but 3 were given
why pass id of channel?
fetch message requires the channel id
fetch_message is an instance method
the instance is already passed to it
oh it doesnt?
in this case, the instance is mychannel
mychannel has the id on it
fetch message uses that id
How to write to a server member that the command is on cooldown
use error handler and check if error is command on cooldown
.rtfm oncooldown
sorry for flooding this channel with my issues but this is (hopefully) the last one
im trying to iterate through every user who has reacted to a message but it's throwing 'AttributeError: 'list' object has no attribute 'users''
in the docs however, there are 2 examples showing reactions.users() being used as a list (see https://docs.pycord.dev/en/stable/api/models.html#discord.Reaction.users)
how can i fix this?
how is it not int
ids are too big a number for discord to send as int
accept as string
take it as string then convert to int using
int(id)
reactions.users() is an async iterator. if you flatten it then it will be a list
when your brain types string instead of list 💀
almost had a heart attack when you said string 
i mixed up the 2 questions lol
i'm using python userslist = await reaction.users().flatten()
but it's still throwing 'list' object has no attribute 'users'
and how was reactions defined?
msg = await ruleschannel.fetch_message(msgid)
reaction = msg.reactions```
here 👀 is 1 reaction and 💀 is another reaction
each has an individual list of users
thanks a ton
it's working now
one last thing, is there any way i can pull the reactor's ID when iterating through them?
user.id ?
yeah i tried that and it's throwing AttributeError: 'Reaction' object has no attribute 'id'
you would do smth like msg.reactions[0].users[0].id
to get the id of the 1st user of 1st reaction
oh wait users is an async iterator
so smth like
async for user in msg.reactions[0].users:
user_id = user.id
break
or you can flatten it
now it's throwing TypeError: 'Reaction' object is not iterable
oh i need to flatten it im dumb
Ignoring exception in view <MedbayWelcomPageButtons timeout=None children=3> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='NFFC' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\philc\Desktop\Artemis-2.0\bot\src\cogs\medbayV2.py", line 134, in nffc_callback
nffcticket = await interaction.guild.create_text_channel(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1263, in create_text_channel
data = await self._create_channel(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1142, in _create_channel
"id": target.id,
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'
any idea why id get this error in some servers but not others?
ticket = await interaction.guild.create_text_channel(
name=f"NFFC-{interaction.user.name}",
category=NFFC_category,
overwrites=overwrites,
)
Read the errror
i have, but it works fine in other servers
still not working 💀
so why it doesnt work in other i have no idea
is it possible to access a user's about me content?
Oh right
Yea i edited this
No. Discord limitation
Where is NFFC_categorh defined?
fixed
Fetched by discord.untils.get(interaction.guild.category, name=‘NFFC’)
Can return None
Also what is guild.category?? Does that even exist
.rtfm guild.category
Target not found, try again and make sure to check your spelling.
Nope
Ik. The categories exist and it works in another server
It is guild.categories 👀
Yes but it might not be present in the bot cache
Was going from memory. My bad
is there a way to get the category even if its not in the cache?
How can i get an emoji from his name like :incoming_envelope:, bot.get_emoji() would work?
Can't think of any way other than fetching the guild
This is why you should deal with channel ids and not names
Okie. Thanks for the help
You could use utils.get on bot.emojis
how can i check if a message has an image attached?
.rtfm Message.attachments
What can I do with custom ids of modals/views?
Persistent views or differentiate between objects for logging or stuff like that
You can use it as you want
man, my brain was not functioning yesterday. i got it working quick this morning. thank you for your help! i really appreciate it
How to get a message's content from its link?
What exactly do you mean?
Whenever someone posts a message link in chat, the bot will get its contents
Getting its content as in downloading it to the bot?
get the channel by id and then get the message by id
You can also just make a bot event (on_message) which then checks if the message contains a message link.
Then you extract the IDs from the link by splitting at the "/" and dividing it into guild_id, channel_id and message_id then you get the guild channel and message objects and then you can simply put it into a variable. And then idk await that channel to send it into a different channel or wherever you want it to go.
I hope that is what you were looking for, at least that's how I understood with what you meant.
How can I create a timer specific to an event handler? Like: each time it is handled should be an independent timer.
discord.ext.tasks.loop
discord.ext.tasks.Loop
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
discord.ext.tasks.Loop.minutes
discord.ext.tasks.Loop.next_iteration
discord.ext.tasks.Loop.remove_exception_type
discord.ext.tasks.Loop.restart
discord.ext.tasks.Loop.seconds
One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for: How...
Here's the background task example.
or that
I had looked at tasks, but the examples assume you have timers set from cog load or bot load. I need tasks timers to be created on certain events, but I need to handle multiple timers. they may have different settings etc.
Should I create a thread for this instead? Wasn't sure if it was too complicated for here.
you can start tasks from anywhere
So, say I have an event handler setting these timers, if the event fires twice, then the two independent timers are created with different start times?
i think you can only run one copy of each task one-at-a-time
yeah thats my problem... any ideas how I can get a one time task to run when an event fires?
So wait do you want to run it every time event is fired or only once
I need a new timer every time the event fires, but it must keep running previous ones. For context, I am doing user verification.
you could use the one time event listeners available on master branch nope. Just understood what you meant
just use a normal event loop
Event loop? 
yes, event loop
How did event loop come into this
yikes. and here I thought my question was simple. I will make a thread, mb.
because it's like after n time you do something
ping us there
Uhh not exactly
they are asking for a timer
Event loop is a task switcher and a scheduler
Timer as in "do x actions after y seconds" ?
that's what I interpreted it as
i would just create a simple function that does this
async def call_later(time: int, coro)
await asyncio.sleep(time)
await coro
where coro is a coroutine (not a function)
you could also use loop.call_later but i find it weird to use
where did their thread go
a more detailed example-
async def msg_user(user: discord.User, content: str):
embed = ...
await user.send(embed)
# somewhere else like in a listener
coro = msg_user(user, "Hello there")
await call_later(60, coro)
# OR
asyncio.create_task(call_later(60, coro))
Sorry, was slow on mentioning you. I havent made a thread on disc before.
no worries. lets continue in the thread
you got this right?
yea sure
How to add a reaction to a message that the bot sent via discord.Interactions?
.rtfm interaction.message
.rtfm message.add_react
||interaction.message isnt available if msg is sent for an app cmd||
you would need msg = await interaction.original_response() then
so what do i need to react to the message, what code?
(i can't write pycord that good so don't yell at me)
and i can't really find anything in the docs
did you send the message from slash cmd or button/select menu etc
modal
ah
i made a modal that sends a message to another channel
so msg = await interaction.original_response will give you the message object
you can then use await msg.add_reaction(...)
yeah, i made this
tysm! struggled 30 mins on this you saved my time
haha np
.tias
kk lol
File "/home/container/bot.py", line 72
msg.add_reaction(✅)
^
SyntaxError: invalid character '✅' (U+2705)
forgot "
oh lol i forgot that exclamation marks 
they are called quotation marks btw
yeah sry my main lang is german
could you show your code?
Yes wait my pc is starting
class ticket(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Titel des Tickets", style=discord.InputTextStyle.short))
self.add_item(discord.ui.InputText(label="Inhalt des Tickets", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Neues Ticket!")
embed.add_field(name="Titel des Tickets:", value=self.children[0].value)
embed.add_field(name="Inhalt des Tickets:", value=self.children[1].value)
embed.add_field(name="Benutzer ID des Erstellers:", value=interaction.user.id)
await interaction.response.send_message("Dein Ticket wurde ans Server-Team von *an link so i don't advertise* gesendet!", ephemeral=True)
my_channel = await interaction.guild.fetch_channel(1092885376688984154)
await my_channel.send(embeds=[embed])
msg = interaction.original_response
await msg.add_reaction("✅")
await msg.add_reaction("❌")
quick question: if i have a string and i ask the user to guess a letter, how do i get the index of whatever that letter in the string is?
original_response is a method, not an attribute
str.find?
so it's await interaction.original_response?
it's both
Do you know how to call a method?
not really, i'm kinda a beginner
Read rule 1 in #help-rules
And if you know basic OOP you'll know the difference between a method and an attribute
Now I got this error 
Can you show the full stack trace, and not in a shitty screenshot?
pip3 list and show output
You are probably using discord.py and not py-cord
Package Version
------------------ ---------------------
aiohttp 3.8.4
aiosignal 1.3.1
arandr 0.1.10
astroid 2.5.1
asttokens 2.0.4
async-timeout 4.0.2
attrs 22.2.0
automationhat 0.2.0
beautifulsoup4 4.9.3
blinker 1.4
blinkt 0.1.2
buttonshim 0.0.2
Cap1xxx 0.1.3
certifi 2020.6.20
chardet 4.0.0
charset-normalizer 3.1.0
click 7.1.2
colorama 0.4.4
colorzero 1.1
cryptography 3.3.2
cupshelpers 1.0
dbus-python 1.2.16
discord.py 2.2.2
distro 1.5.0
docutils 0.16
drumhat 0.1.0
envirophat 1.0.0
ExplorerHAT 0.4.2
Flask 1.1.2
fourletterphat 0.1.0
frozenlist 1.3.3
gpiozero 1.6.2
html5lib 1.1
idna 2.10
isort 5.6.4
itsdangerous 1.1.0
jedi 0.18.0
Jinja2 2.11.3
lazy-object-proxy 0.0.0
logilab-common 1.8.1
lxml 4.6.3
MarkupSafe 1.1.1
mccabe 0.6.1
microdotphat 0.2.1
mote 0.0.4
motephat 0.0.3
multidict 6.0.4
mypy 0.812
mypy-extensions 0.4.3
numpy 1.19.5
oauthlib 3.1.0
pantilthat 0.0.7
parso 0.8.1
pexpect 4.8.0
pgzero 1.2
phatbeat 0.1.1
pianohat 0.1.0
picamera 1.13
picamera2 0.3.8
pidng 4.0.9
piexif 1.1.3
piglow 1.2.5
pigpio 1.78
Pillow 8.1.2
pip 20.3.4
praw 7.7.0
prawcore 2.3.0
psutil 5.8.0
py-cord 2.4.1.dev42+g279f616b
oh I should uninstall discord.py
yeah that can interfere
yeah most likely the error
why can i do self.message.id before bot restart but after restart i get nonetype not have id
why is message none then?
ty
oh really?
okay its interaction.message after restart but why?
k
Gonna need more context about what you are talking, but if this is regarding views, then the message attribute doesn't get populated across restarts
You should also reinstall py-cord when you do that
You still didn't show us the full error
yes its about view, thanks
Ignoring exception in modal <__main__.ticket object at 0x7f7936691de0>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
await value.callback(interaction)
File "/home/container/bot.py", line 72, in callback
await msg.add_reaction("✅")
File "/home/container/.local/lib/python3.10/site-packages/discord/message.py", line 1584, in add_reaction
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 367, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
you cannot react to ephemeral messages
Oh I’m stupid 💀
I acidentally made it ephemeral
now i am getting this error
Ignoring exception in modal <__main__.ticket object at 0x7fd125b2a2f0>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
await value.callback(interaction)
File "/home/container/bot.py", line 70, in callback
msg = await interaction.original_response()
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 316, in original_response
data = await adapter.get_original_interaction_response(
File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
you can try putting
msg = await interaction.original_response()
earlier in your code
earlier as in before sending a response
0ok
Ignoring exception in modal <__main__.ticket object at 0x7f2e08622230>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
await value.callback(interaction)
File "/home/container/bot.py", line 68, in callback
msg = await interaction.original_response()
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 316, in original_response
data = await adapter.get_original_interaction_response(
File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Neues Ticket!")
embed.add_field(name="Titel des Tickets:", value=self.children[0].value)
embed.add_field(name="Inhalt des Tickets:", value=self.children[1].value)
embed.add_field(name="Benutzer ID des Erstellers:", value=interaction.user.id)
msg = await interaction.original_response()
my_channel = await interaction.guild.fetch_channel(1092885376688984154)
await my_channel.send(embeds=[embed])
await msg.add_reaction("✅")
await msg.add_reaction("❌")
its my code
yeah
oh, then just
msg = await my_channel.send(embeds=[embed])
oh lol i'm seeing the error too
o/ Hello again squid and nom,
How would I go about dispatching a custom event? I've seen discord.py post about using bot.dispatch (assuming discord.ext.commands.Bot.dispatch()), but I am not finding a method like that in the docs.
ty it worked
It's not meant to be used by the user and that's why it isn't documented. bot.dispatch isn't a new thing.
The syntax for it is just
bot.dispatch("event", args1, args2...)
say your custom event is
@bot.event
async def on_sleep():
...
bot.dispatch("sleep")
If you find a need to use dispatch there's probably a better way to do whatever you're trying to do
is there a way to edit slash message responses?
ctx.edit("test") returns TypeError: Interaction.edit_original_response() takes 1 positional argument but 2 were given
content="test"
ah, thanks
Can you not add a description to bridged command arguments.
That way the options show a description, rather than being blank when using the slash version?
Ping me on reply pls
I have a cog that posts a message with a button that spawns a modal. And I want to handle the response for submitting the modal with another cog.
im trying to add auto completion to a slash command, can i have some help? i have the guide open but i cant seem to adapt it to my use case. this is my code: ```py
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
import hypixelapi
#load bot token from sys env
load_dotenv("secrets.env")
TOKEN = os.getenv('DISCORD_TOKEN')
api_key = os.getenv("HYPIXEL_API_KEY")
#create bot objects
intents = discord.Intents.all()
bot = commands.Bot()
#initialize param variables
item_name = "CRUDE_GABAGOOL"
crude_gabagool_count=0
username= "uAiden"
profile = "Banana"
hypixelapi.get_sack_data("uAiden","Banana",api_key)
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
@bot.event
async def on_message(message):
print("message-->", message)
if message.author == bot.user:
return
if message.content.startswith('hierarchal'):
await message.channel.send('Hello!')
if message.content.startswith('imagification'):
await message.channel.send(file=discord.File('logo.jpg'))
async def get_profile_names(ctx: discord.AutocompleteContext):
#setting up options the user may type
profiles = ctx.options["Profile"]
@bot.slash_command(name="auto",guild_ids=[958497524564500500]) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def setup(
ctx: discord.ApplicationContext,
profiles: discord.Option(str, choices=[
"Apple",
"Banana",
"Blueberry",
"Coconut",
"Cucumber",
"Grapes",
"Kiwi",
"Lemon",
"Lime",
"Mango",
"Orange",
"Papaya",
"Peach",
"Pear",
"Pineapple",
"Pomegranate",
"Raspberry",
"Strawberry",
"Tomato",
"Watermelon",
"Zucchini"]),
profile_name: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(get_profile_names))
):
await ctx.respond(f"You are on profile:{profile_name}")
bot.run(TOKEN)``` and so far, the bot runs, but i cant use any commands let alone see if my autocompletion is working. could it be that im inputting the guild id incorrectly?
does anyone know why bot.close isnt actually shutting down the connection?
client_session: <aiohttp.client.ClientSession object at 0x000002287604EC20>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000002287602FA00>, 98674.234)]']
connector: <aiohttp.connector.TCPConnector object at 0x000002287604E920>
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000002287604FB80>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000002287602FA60>, 98684.281)]']
connector: <aiohttp.connector.TCPConnector object at 0x000002287604FC10>```
it throws that error when i reconnect
how come this isn't working? it's not throwing any errors but when i upload an image w/ a message it deosnt detect
(inside on_message, msg being the message)
if msg.attachments:
print('message has file')```
Do you have message content intents?
I don't see why you need autocomplete
Autocomplete only needed when you have more than 25 options or they are dynamic in some way
yeah i realized that, but now i definitely need it for my next option
it seems like you have a static "set" of options.
yes, i've got all the intents on
show code?
i need to autocomple from a list of all minecraft names
as you type in
using namemc api
hello! I have a question, how to add a role for the person who clicks on the button? I want to do a verification command
i thinkk
bot = commands.Bot(intents = discord.Intents.all())
interaction.user.add_roles(...)
tysm ❤️
oh nvm got it working now
yall please bot.close isnt working
@fervent cradle @errant vale @fast badger Could you guys please make your own threads? ty.
Ping me in your threads too
how to do this add the role by id?
roles = interaction.guild.fetch_roles()
for role in roles:
if role.id == role_id:
interaction.user.add_roles(role_to_add)
Forgot to tag you. See above.
add_roles([
discord.abc.Snowflake(YOUR_ID),
discord.abc.Snowflake(YOUR_ID_2),...
]
)
oh, that also works.
no need to make extra API calls.
Fetch can give you really fast a rate limit
hmm, thx, sometimes i get confused
My bad. I am not used to pycord yet. I usually do this in node tbh.
I have a slash command for a select menu that seems to be working fine, but nothing shows up when I trigger it on mobile(ios). Do select menus not work on mobile?
what
I think there is no problem for a verification command
last time I chcked, a select menu works just fine.
Do you have an older discord version?
Do buttons not get custom ids for the view decorators?
wdym
oh nvm it was a typo elsewhere.
was wondering about that. I just forgot a paren. oops.
oof
I want to edit an ephemeral response to an interaction. Is it possible to do this, or do I need to delete the original response and respond again with the edited message?
yes, you can do this
Perfect! Thank you squid. you are my spirit animal lmao
Is there still a time limit editing ephemeral messages?
Im not really sure that you can edit ephermeral messages
Well you can edit them but they are not ephermeral after it
no, you can edit ephemeral messages any time and let the messages keep their ephemerality.
@sand niche no
is it possible to use the normal json embed because i cba to make it by myself and wanna use a generator
yes?
i dont see it in the guide
Im not really sure if there is a guide for it
everywhere i look tells me to do it differently
i have this big sample json that i need to add my variables and formatting to
Im not sure if this is helping
oof
could you maybe delete it pls? x3
thx
check this out, maybe it is helping
maybe ill just look at the json and convert to pycord convention so i can understand it better
How do i change the name of a category?
help
my code is
msg = await interaction.original_response()
but i get the error:
Ignoring exception in command umfrage_start: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped ret = await coro(arg) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke await self.callback(ctx, **kwargs) File "/home/container/main.py", line 613, in umfrage_start msg = await interaction.original_response() AttributeError: 'ApplicationContext' object has no attribute 'original_response' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'original_response'
.rtfm embed.from
please
app cmds have ctx and not interaction. rename your parameter
use ctx.interaction.edit_original_response
get the category from its id using guild.get_channel and edit using channel.edit
.rtfm guild.get_channel
.rtfm channel.edit
I was not sure if this will work thank you
Why this doesn't disable the button after pressing it?
class WaveButton(discord.ui.View):
@discord.ui.button(emoji=":wumpus_wave:", style=discord.ButtonStyle.gray)
async def waved(self, button, interaction):
await interaction.response.send_message(f"**{interaction.user.name}** sent you a wave!")
button.disabled = True
You need to edit the message with the updated view
oh
my @bot.slash_command() is this:
@bot.slash_command(description="Umfrage starten.") async def umfrage_start(interaction, frage, a_antwort, b_antwort, c_antwort = None):
use ctx
so can i remain the code how it is but i only change the interaction to.ctx?
to ctx*
like interaction.response.send to ctx.respond()
yeah that is basic pycord
v2 or v3? ;3
idk xD
the latest
Ignoring exception in command umfrage_start:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "/home/container/main.py", line 627, in umfrage_start
await msg.add_reaction("🅰️")
AttributeError: 'function' object has no attribute 'add_reaction'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'function' object has no attribute 'add_reaction'```
this is my code
@bot.slash_command(description="Umfrage starten.")
async def umfrage_start(ctx, frage, a_antwort, b_antwort, c_antwort = None):
if c_antwort is None:
id = str(ctx.author.id)
msg = ctx.interaction.edit_original_response
await ctx.send(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort)
await msg.add_reaction("🅰️")
await msg.add_reaction("🅱️")
else:
id = str(ctx.author.id)
msg = ctx.interaction.edit_original_response
await ctx.send(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort+", C = "+c_antwort)
await msg.add_reaction("🅰️")
await msg.add_reaction("🅱️")
await msg.add_reaction("🇨")
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
edit_original_response is a coroutine. But it doesn't make sense why you're using
^
Yes
Ignoring exception in command umfrage_start:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "/home/container/main.py", line 631, in umfrage_start
msg = await ctx.interaction.edit_original_response()
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 428, in edit_original_response
data = await adapter.edit_original_interaction_response(
File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook
code:
@bot.slash_command(description="Umfrage starten.")
async def umfrage_start(ctx, frage, a_antwort, b_antwort, c_antwort = None):
if c_antwort is None:
id = str(ctx.author.id)
msg = await ctx.interaction.edit_original_response()
await ctx.send(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort)
await msg.add_reaction("🅰️")
await msg.add_reaction("🅱️")
else:
id = str(ctx.author.id)
msg = await ctx.interaction.edit_original_response()
await ctx.send(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort+", C = "+c_antwort)
await msg.add_reaction("🅰️")
await msg.add_reaction("🅱️")
await msg.add_reaction("🇨")
What are you even doing...
also why this if you could just do ctx.author.mention?
idk, don't ask me
Kannst du die Basic´s von Python?
Remove the edit original response at the top
Change ctx.send to ctx.respond
Change the edit original response at the bottom to ctx.original_response
ja, wieso?
How do I get a specific guild's member count by its ID?
bot.get_guild and guild.member_count
isn´t it also counting the bots?
how do i fix my error?
...
oh lol
Ignoring exception in command umfrage_start: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped ret = await coro(arg) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke await self.callback(ctx, **kwargs) File "/home/container/main.py", line 631, in umfrage_start msg = await ctx.original_response() AttributeError: 'ApplicationContext' object has no attribute 'original_response' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'original_response
It's ctx.interaction.
got this error again
Ignoring exception in command umfrage_start: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped ret = await coro(arg) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke await self.callback(ctx, **kwargs) File "/home/container/main.py", line 625, in umfrage_start msg = await ctx.interaction.original_response() File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 316, in original_response data = await adapter.get_original_interaction_response( File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request raise NotFound(response, data) discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook
i don't even use a webhook
you do ;3
lol what
the slash commands ;3
could I see the changes again?
You're trying to get the original response when you didn't even respond to the slash command
@bot.slash_command(description="Umfrage starten.") async def umfrage_start(ctx, frage, a_antwort, b_antwort, c_antwort = None): if c_antwort is None: id = str(ctx.author.id) msg = await ctx.interaction.original_response() await ctx.respond(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort) await msg.add_reaction("🅰️") await msg.add_reaction("🅱️") else: id = str(ctx.author.id) msg = await ctx.interaction.original_response() await ctx.respond(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort+", C = "+c_antwort) await msg.add_reaction("🅰️") await msg.add_reaction("🅱️") await msg.add_reaction("🇨")
i made it like ctx.respond
dont do the msg stuff before the message
tyy it worked
How do i get the amount of members in a guild i tried members = guild.members but it returns the whole information of the guild. Can someone help me?
with bots or not?
Doesn’t matter xD
member_count
Ok thanks
Heyo, I'm not able to upgrade my pycord version above 0.1.1, any clue on how to upgrade?
I've tried pip install pycord==2.0.0
pip install --upgrade pycord
Ope just a sec
Uh, well I get this error while tryna run it
ModuleNotFoundError: No module named 'pycord'```
You don't import pycord. It's still import discord
And please use the latest version, not 2.0.0
Really? I thought was updated /gen
Unless you're using v3, no, it's still discord
I did upgrade to the latest a moment ago, I just tried 2.0.0 because nothing else was working lol
Ahh gotcha! Thanks!
Also, button component should work right? /genq
I keep getting this error 😅
from discord import Embed, ButtonComponent, ButtonStyle, InteractionType
ImportError: cannot import name 'ButtonComponent' from 'discord' (C:\Users\maddi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)```
can you show the pip list?
also discord.ui
Hmm latest is 2.4.1 right?
Wait no that was discord.py
I already have 2.4.1 installed in pycord
You can't have discord.py and pycord installed at the same time
I just uninstalled it 😅
Thought I already removed it
reinstall pycord when you do that
Is it possible for the attendees arg to autocomplete for users, but I want to be able to choose multiple users in the same arg (possibly separated by commas)
You'd need to get a string and parse it yourself
str,
if it was a str, would mentioning someone work? I want it to be as easy as possible for the user 🙂
Actually I'll just try it anyway
thanks guys
They'd have to @ the user themselves
Instead of the Discord autocomplete for members
I mean, iirc they discord autocomplete will appear once they type @
I have run a unit test through my select menu and always get this error:
======================================================================
ERROR: test_init (__main__.TestFirstBottomFishingBait)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\unittest\async_case.py", line 64, in _callTestMethod
self._callMaybeAsync(method)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\unittest\async_case.py", line 87, in _callMaybeAsync
return self._asyncioTestLoop.run_until_complete(fut)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\unittest\async_case.py", line 101, in _asyncioLoopRunner
ret = await awaitable
File "c:\Users\User\Documents\Coding\Bot\test_bottomfiishing.py", line 13, in test_init
self.assertEqual(select.placeholder, "Wähle deinen Köder aus")
File "C:\Users\User\Documents\Coding\Bot\Bot\lib\site-packages\discord\ui\select.py", line 188, in placeholder
return self._underlying.placeholder
AttributeError: 'FirstBottomFishingBait' object has no attribute '_underlying'```
Does anyone know what the problem is?
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
baits = sorted(await dab.get_koeder_grundangel(spotdaten.baittype, spotdaten.baitproducer))
options = [discord.SelectOption(label=bait) for bait in baits]
super().__init__(
placeholder="Wähle deinen Köder aus",
min_values=1,
max_values=1,
options=options,
custom_id="FirstBottomFishingBait",
)```
for what do you need the bot?
Is for me on my server
Do I need to remove the : discord.bot?
no
What? What should the picture tell me?
could you not just do ```py
list = []
for item in list:
self.append_option(discord.SelectOption(label=item))
after the init stuff
What would be the advantage of this?
it would replace x3
But I can't call the await function after init:
baits = sorted(await dab.get_koeder_grundangel(spotdaten.baittype2, spotdaten.baitproducer2))```
I just dont know what all the is
I can do at most that in the init but there I do not know where the advantage should lie?
async def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
super().__init__(
placeholder="Wähle deinen Köder aus",
min_values=1,
max_values=1,
custom_id="SecondBottomFishingBait",
)
baits = sorted(await dab.get_koeder_grundangel(spotdaten.baittype2, spotdaten.baitproducer2))
for item in baits:
self.append_option(discord.SelectOption(label=item))```
what is dab.get_koeder_grundangel?
This is a function that returns me the choices from a database.
is it a list?
There is a list back yes.
But the values can always be different that's why I can't write the values before in a list in the code
What can I do to make the time display look like it does in the third picture and not like in the second picture? The code for this is in the first picture
.rtfm utils.format
Thats style f right?
How and where should I write this?
Im not getting it right now
the docs explain everything
Can i set a command only display in a specific guild?
Any event function to call when someone boosts the server?
Hi, I want the bot to send messages in a particular channel but am not sure exactly how. Normally I would use:
channel = bot.get_channel(<id>)
await channel.send(<content>)
But apparently, this works no longer. Please help me, thank you!
Use get_or_fetch_channel
Something like this
it returned an error
AttributeError: 'Bot' object has no attribute 'get_or_fetch_guild'
if you do "bot.channel* you should see more
what do you mean
The autocompletion of the editor
File "c:\Users\duchu\Desktop\MMO\database.py", line 72, in addexp
channel = await bot.fetch_channel(1092403329323257956)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\duchu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\client.py", line 1824, in fetch_channel
data = await self.http.get_channel(channel_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\duchu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\http.py", line 604, in request
if not self._global_over.is_set():
^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: '_MissingSentinel' object has no attribute 'is_set'
😭
there is fetch_channel
What is the py-cord Version?
22.3.1
what
lol
Can you show the pip list?
?tag pycord
No tag pycord found.
Its should be py-cord and not pycord
High chance bot isn't logged in
did anyone know how to get status of a user type ?
or how to change type of a user to member ?
How to automatically restart after Discord's API rate limit?
get members intent, find mutual guilds, and get the member object.
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options.4: The specified option value is already used
Any clue what this means when there is only 1 option in the view (ui Button) and there are no duplicate custom IDs?
Show code?
class ExitCombat(discord.ui.View):
def __init__(self, profile, profiles, user_id, enemy):
super().__init__(timeout=None)
self.profile = profile
self.profiles = profiles
self.user_id = user_id
self.enemy = enemy
@discord.ui.button(label="Continue", custom_id="combat-exitting", style=discord.ButtonStyle.red)
async def first_button_callback(self, button, interaction):
reflection_direction = None
byte_array, updated_position = update_map_image(self.profiles[interaction.user.id], reflection_direction=reflection_direction)
file = discord.File(byte_array, filename="map_image.jpeg")
embed = discord.Embed()
embed.set_image(url="attachment://map_image.jpeg")
await interaction.response.edit_message(content = "", embed = embed, attachments=[], file=file, view = UIButtons(self.profile, self.profiles, self.user_id))
full traceback?
await interaction.response.edit_message(content = "", embed = embed, attachments=[], file=file, view = UIButtons(self.profile, self.profiles, self.user_id))
wait, what?
Traceback (most recent call last):
0|ethergame | File "/usr/local/lib/python3.10/dist-packages/discord/ui/view.py", line 414, in _scheduled_task
0|ethergame | await item.callback(interaction)
0|ethergame | File "/root/ethergame.py", line 5485, in first_button_callback
0|ethergame | await interaction.response.edit_message(content = "", embed = embed, attachments=[], file=file, view = UIButtons(self.profile, self.profiles, self.user_id))
sorry for weird bars...coming from server
I mean it is technically valid syntax
takes away old file and adds new
"technically"
Oooh, okay
so that's the best way to do it I've found
fair enough
It seems like the error is coming from UIButtons.
interestinng....see, this happened to me before and it was actually the code that called the ExitCombat view previously
But I can't for the life of me figure out what tf could cause that
I mean the stack trace shows that it got to the callback
show UIButtons code?
hehehe
Do you use anywhere in your code select menus?
holy frek yes I sure do
That's the issue
True
frek frek frek LMFAO

yeah should be that select menu's duplicate options
only select menus can have options
Yea, I completely forgot that this boss drops an item that's already in my backpack lmfao
You can't have 2 options with same name
Unless I'm reading it wrong.
thanks, gang <3
alr have fun
nahh, you 100% correct
Wait, so... Is there a way to delete/reset something from message? Or you can only use edit_message?
you can make most things = None, but not for discord.File
for some reason file = None doesn't work
I know, but... This looks cursed
File is used for uploading new files.
.
Attachment would be used to change existing files.
There's also supress embeds or something like that.
yeah, but... No await interaction.response.reset_in_message(True, view=True) or something like that?
you would have to use view=None for that
That's what I'm asking. Only like that?
well, view=discord.ui.View() also exists
but... You still need to use edit_message
yes
okay, thank you
If you don't like the syntax you can always implement your own abstration
It would be convenient to see this in Pycord, but maybe this is not so important feature
You can always make a PR on GitHub if you feel like you can implement it and it's useful
is there a way to make it so it will complete a task at a desired time? eg. send a message to a channel at 8pm est
Here's the background task example.
thank you
uh so, i've done command groups but they only work for regular commands not bridge commands
i've got @play.command(), should i make it @play.bridge_command()?
was wondering how variables work if multiple people use the bot? id like each user to have their own private variables
is that done automatically?
What do you mean by own variables?
yk mean storing their data in a database?
like if one user runs/setup to setup some constants, would another person running the bot override that if they ran /setup as well?
probably
yeah, just store each person's info in a database by using their user id
then im pretty sure it wont be overriden
never used a database before
where do i start to learn though
yeah im not the best at it either but just create a table, and select each variable from the table
Find a database that you like SQL or non SQL
sorry shoulda been more specific, what would be a simple database that would fit with pycord? i only need to store 3 variables for the user
also anyone wanna answer my question
im used to discord.py not pycord
bridge cmds are confusing
That depends on you
You can use MySQLite
Or mongo
isnt mongo kinda bad
is this good? https://pypi.org/project/DiscordDatabase/
No?
No
Use actual databases
what the fuck
It'll be useful long term
might do aiosqlite
wouldn't you get ratelimited to hell with that type of database?
Unreliability at its best 💀
Worst thing I've seen all day
Honestly probably my entire life
Its the dumbest idea ever
Whats the convention to add a function call to a slash command
I try adding one and it causes the command to not be registered
what?
When someone does a slash command, i want it to be run with one of my own functions so i can supply the output with information
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
I dont see anything on calling functions with a slash command there
Anywhere i tried putting my function to be called with the slash command didnt work
I'm really not sure what you mean.


