#Basic Pycord Help
1 messages · Page 20 of 1
there dont work modals
it`s bad module(d.py)
Coroutines are present everywhere. Not just in modals.
in responds
in sends
everywhere
wtf
@lofty parcel
sorry for mention
I feel useless to anyone, I’m dumber than a cat, plus I’m blind, I don’t deserve to be a programmer and a bot developer
You're doing ctx.respond when you should be using ctx.send_modal. Don't know why you modified that line /shrug
thx, dark, but it don`t send result in my dm
class cardCommands(commands.Cog):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
card = SlashCommandGroup("card", "View, Trade and Sell your Cards!")
@card.command()
async def inventory(self, ctx: discord.ApplicationContext):
"View your Card Inventory"```
This is a group command, how can I lock the `inventory` command to server admins only
normally I use:
```py
@discord.default_permissions(administrator=True)
but this doesn't seem to work with group commands
how do i use @option
this example explains it pretty well
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
okay thanks
1 more thing, when i create cog class, how can i access the bot object in @slash_command decorator? i need to access bot.main_guilds (custom attribute)
I solved the problem, I moved the group object to the class attributes
i just need some of the commands in cog to be only in the main guild
I am not trying to deal with the timeout problem:
ERROR:asyncio:Task exception was never retrieved future: <Task finished name='discord-ui-view-timeout-2840ebd01534e1844d2f1979a8c4d407' coro=<ButtonsMatch.on_timeout() done, defined at /app/commands/global/match_games.py:94> exception=HTTPException('401 Unauthorized (error code: 50027): Invalid Webhook Token')> Traceback (most recent call last): File "/app/commands/global/match_games.py", line 105, in on_timeout await self.message.edit( File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 1194, in edit return await self._state.interaction.edit_original_response( File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 428, in edit_original_response data = await adapter.edit_original_interaction_response( File "/usr/local/lib/python3.10/site-packages/discord/webhook/async.py", line 221, in request raise HTTPException(response, data) discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
Why does the button say that the message does not exist if it does?
What's your timeout? Is it greater than 15 minutes?
yes
yeah then the interaction expired
is for a button to prox of duration 1-3h hours
Is it possible to mention a role without pinging everyone who got the role?
Depends on what you mean by that
If you send a normal text message and mention a role in it
I should clarify. Whom do you want to ping?
Is it no one or a subset of people that have the role?
You might just want to send a normal msg then
How to create option args
Here's the cooldown example.
the idea is that the message is updated, this is what it looks like now
It doesn't happen every time you do that commands older than one day have worked without problems and you can modify the message.
Then save the original response which gives you a message object.
And then edit it.
I can't install Pycord
?tag install
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
use the master branch
2a fails
End of error message:
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for aiohttp
Failed to build aiohttp
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
^
There is this line as well error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
read that again
Read the website and follow the steps
@bot.slash_command(description="Add xp to a user in a particular server.")
async def add_xp(ctx, guild_id:str, user_id:str, exp:str):```
Why is it giving me "input a valid integer" when I try using the command
🤔
I'm trying to parse a string into integer later in my code but idt this should affect it
For some reason it's only allowing integers 2^53 (When I'm trying input as a string)
Trying to create a fuzzy autocomplete feature for my bot, how can I retrieve the "option" that has been typed for my fuzzy search? At the moment I'm return the below, how can I retrieve the "unit" in the options? do I need to pass something in the method?
This is my full function
IT fails to INSTALL
Comment out the command, run your bot and remove the comment and run again.
AutocompleteContext.options returns a list of past selected options. If that's your question.
ah
The idea is "unit" should have the string of the thing I'm looking for
I want to then pass that to the fuzzy lookup
Is unit an option the user selects?
typing the unit should then return the options based on a fuzzy return
Then refer to this.
So you don't pass it to the autocomplete function.
Autocomplete only receives its own context
ctx.value returns the value the user is inputting
Here's the slash autocomplete example.
See ^
Thank you so much
I installed VS 14.0+, and installing still fails
I already installed the VS thingy
for c++
unless you really really really need 3.12, just use 3.11
:( okay
Which event reference is for button presses?
on_interaction
But that is also for Menus and slash commands
So you would have to check for it
How can I put an emoji in a button?
Thanks, I think I figured it out by using the button view instead
There is a emoji= kwarg
Read the docs
I added it and it says it takes in a string but I'm getting an invalid emoji error from this. I'm sure it's obvious but could you point out what I'm doing wrong?
@discord.ui.button(label="Create Ticket", emoji=":envelope_with_arrow:", style=discord.ButtonStyle.primary)
Eh, try emoji=discord.PartialEmoji.from_str(":envelope_with_arrow") or look for the emoji online and pass it to emoji=
Copying it from online worked, thanks
I'm following up on this (sorry for extremely late reply). I've narrowed down the occurrence. It only happens when I send the message with @ everyone in a public channel and the users spam the buttons attached to the message. Once the button spam commences, the message resends again and again for as long as they continue to spam it.
Again, ZERO circular functionality in the code, zero on_message, and a very basic button response function.
PIP attached
context: #1132206148309749830 message
Do button views expire? The button I want to act off of will be created and just sit there for a long time. Can I still use a view callback in this case or does it have to be on_interaction event listener?
hey everyone is it better to create a new thread or add to a similar thread?
Buttons have a default timeout of 3 minutes
Create your own thread.
?tag install
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
2b fails for me
C:\Users\Wolfie\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'C:\\GIT\\Project-Shadow-Trello-Webhook\\pip': [Errno 2] No such file or directory
Using python 3.11.7
I was told to downgrade
maybe to 3.10
I am testing the Persistent buttons, but when I create one and restart the bot, it throws the error
import discord
from discord.ext import commands
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None) # timeout of the view must be set to None
@discord.ui.button(label="A button", custom_id="button-1", style=discord.ButtonStyle.primary, emoji="😎")
async def button_callback(self, button, interaction):
await interaction.response.send_message("Button was pressed", ephemeral=True)
class ButtonPersistentView(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="persistent", description="Press the button to see the view persistence status")
async def persistent(self, ctx):
await ctx.respond(f"Press the button! View persistence status: {MyView.is_persistent(MyView())}", view=MyView())
def setup(bot):
bot.add_cog(ButtonPersistentView(bot))
Du you add the view to a add_view?
I didn't understand your question, sorry
So, you have to add the view to a add_view at your bot
I usually add the view at the on_ready event
You’re required to add the view to your bot using bot.add_view(your_view) is what they’re saying
can't it be done from the cog?
.rtfm add_view
As you can see, there’s no such function for cogs
so how do I make it modular?
commands.Cog.listener?
Basic events (on error, on ready etc) either go in the main file or listeners exist
@commands.Cog.listener()
async def on_ready(self):
self.bot.add_view(MyView())
thank goodness for the listener
thxx
Do i understand this correctly?
i should be able to use modal_submit with a modal dialog and then i can use defer() to do my longer processing?
It's called callback in pycord. And you use interaction.response.defer() to defer the interaction which gives you 15 minutes to send a follow up.
aha, thank you
im trying to create a bot and i keep getting this error: AttributeError: module 'discord' has no attribute 'Bot'
my code: ```py
import discord
bot = discord.Bot()
@bot.event
async def on_ready():
print("ready")
bot.run("")```
as well as my pip list here:
aiohttp 3.8.6
aiosignal 1.3.1
async-timeout 4.0.3
attrs 23.2.0
charset-normalizer 3.3.2
frozenlist 1.4.1
idna 3.6
multidict 6.0.5
py-cord 2.4.1
typing-extensions 4.9.0
yarl 1.9.4```
uninstall and reinstall py-cord
lovely, thanks so much
is there an easier way to unban people other than to just go through the ban list and unban them 1 by 1 with asyncio sleep so it doesnt get ratelimited
Thanks 🙏
There's no bulk unbanning endpoint.
If you want to unban a specific user, discord.Guild has a method
nah, just want to unban 4k people from a raid
Then no, you have to iterate over the ban
hey im trying to get the ctx users Display name tried
ctx.user.global_name
ctx.user.name
doesnt work
im using latest py-cord version
can someone help please
Lastest version doesn't have pomelo.
Only the github version does.
Before Pomelo- Versions 2.4.1 and before
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo- Versions py-cord-dev 2.5.0 and up
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
Sorry guys, I'm looking at the operation of persistent buttons, I'm creating an option in which the user can set the max time of functionality of the button for example 1h-5h. Do you think it is a good idea to make a bot.loop.create_task(self.wait_timeout())
def __init__(self, value_one:str=None, value_two: int= None, timeout_match: datetime=None, bot=None):
super().__init__(timeout=None)
self.value_one = value_one
self.value_two = value_two
self.timeout_match = timeout_match
if self.timeout_match is not None:
bot.loop.create_task(self.wait_timeout())
async def wait_timeout(self):
await asyncio.sleep(self.timeout_match)
self.disable_all_items()
self.stop()
No date for version 2.5? 
Eh, im sure the release will be soon
Wouldnt storing a datetime object and then comparing be more simple
a dictionary with id_message : time?
then I still have time to update the code, thanks for the information.
Hi.
async def shop_add_pack(ctx, cardpack_name: Option(str, "Name of Card Pack", choices=fetchCardSeries()), price: Option(int, "Price of Item in Shop", choices=[])):
How can I dynamically change the choices, fetchCardSeries() fetches a list of items but it gets executed at run-time and doesn't change when the command is ran again so the items stay the same even thought the list is updated.
How can I fetch the list when the command is run to get the updated list, I tried:
choices=lambda: fetchCardSeries()```
but no luck.
you cannot do that without resync the command or restart the bot
you have to use autocomplete for it
Could you elaborate on this please
Here's the slash autocomplete example.
choices it like a hard coded list so you cannot really change it without a restart of the bot, while you can change the list with autocomplete
Just a note. Users can enter something not in the auto complete. So you will need to check that they selected a valid choice yourself.
Thank you, guys!
Hey all. I'm trying to make a select menu conditional based on a passed variable. Any help will be much appreciated.
class skillForm(discord.ui.View):
def __init__(self, characterName, prevInteraction, skillsType1):
self.characterName = characterName
self.prevInteraction = prevInteraction
self.skillsType1 = skillsType1
super().__init__(timeout=None)
s1check = False
s2check = False
s3check = False
highlightSkills1 = str
highlightSkills2 = None
highlightSkills3 = None
if self.skillsType1 == True:
@discord.ui.select(
placeholder="Primary Skill",
min_values=1,
options=craftingSkills
) # a custom_id must be set
async def skill_callback1(self, select, interaction):
self.highlightSkills1 = select.values[0]
self.s1check = True
await interaction.response.defer()
Of course the if self.skillsType1 == True doesn't work because it's outside the def. I'm probably just being stupid here. Is there a better approach?
You have to subclass the select
And add the options
Hey, how can we lockdown grouped commands to a specific server so those commands don't appear in other servers
class grindlistCommands(commands.Cog):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
grindlist = SlashCommandGroup("grindlist", "Grindlist Commands")
@grindlist.command()
async def view(self, ctx: discord.ApplicationContext):
"View the grindlist"```
SlashCommandGroup probably has a guild_ids param
I am using the @commands.guild_only() tag in some of my commands and I can still run the command in the DM or just view it. Should I put something else in?
grindlist = SlashCommandGroup("grindlist", "Grindlist Commands", guild_ids = ["id_01", "id_02"])
The decorator is an internal check. It will not not register the command in dms
and how should I do it so that the command does not appear in the private?
You cant unless you register the command to specific guilds
How use Slash Package here?
What is a slash package?
to import slash cmds
No Module Named 'discord_slash'
that is not py-cord
server name?
idk
Py-cord has slash commands. It's just not discord_slash
what then?
Official Pycord Guide: https://guide.pycord.dev/
And the user left...
they were not using Pycord anyways ¯_(ツ)_/¯
how do i get a reference message, if i use commands.slash_command?
Should be ig
Theres no reference message in slash commands
Would sending a message to every guild (like an announcement) work or would the API not like it sending that many messages at once? Would it even work or would it take forever to actually finish running? Currently at 1,750 servers
how do i make a new line with slash commands
New line as in?
Youd probably need to asyncio sleep a few secs
i don't recommend doing it because iirc it can get your bot quarentined
I just did a fresh install of my bot with the requirements and now there is a problem with Option. Where there a breaking change in the last month ? I install from: git+https://github.com/Pycord-Development/pycord
File "D:\Documents\bot discord\timed_role_je\cogs\StatsCog.py", line 14, in <module>
class StatsCog(Cog):
File "D:\Documents\bot discord\timed_role_je\cogs\StatsCog.py", line 31, in StatsCog
@stats.command(guild_ids=guildIds, description="Show the stats of the bot")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\core.py", line 1256, in wrap
command = cls(func, parent=self, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\core.py", line 693, in __init__
self._validate_parameters()
File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\core.py", line 711, in _validate_parameters
self.options = self._parse_options(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\core.py", line 769, in _parse_options
option = Option(option)
^^^^^^^^^^^^^^
File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\options.py", line 227, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\enums.py", line 802, in from_datatype
if datatype.__name__ in ["Member", "User"]:
^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?
I install: git+https://github.com/Pycord-Development/pycord@fc7b1042c4a9a942b9996dfe96f56aac059e179c It is working on that version
.pomelo
Before Pomelo- Versions 2.4.1 and before
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo- Versions py-cord-dev 2.5.0 and up
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
but it would still be good to know if there is breaking changes
Is Spotify classified as discord.ActivityType.listening?
How to get bans count of a guild using discord.py?
discord.py: len([entry async for entry in ctx.guild.bans])
Though I did not test this. ctx would be the application context.
pycord: len(await ctx.guild.bans().flatten())
I did test this one. ctx is once again the application context.
Thanks!
bans = ctx.guild.bans()
count = 0
async for ban_entry in bans:
count += 1
There is not supposed to be a breaking change. Can you ensure you have no other discord libraries installed. And if the issue persists create a big report.
Yes, but technically it is not the only thing that could be classified as listening.
I figured it out, I now am using isinstance(activity, discord.Spotify)
Since Spotify is represented by the Spotify object instead of Activity
For future reference if you are using discord.py you should use there support server as it is not the same as Pycord. (As shown by alucard)
Okay, Thanks and sorry.!
there is no other discord library
aiofiles==23.2.1
aiohttp==3.9.3
aiolimiter==1.1.0
aiomysql==0.2.0
aiosignal==1.3.1
aiosqlite==0.19.0
attrs==23.2.0
certifi==2024.2.2
cffi==1.16.0
charset-normalizer==3.3.2
colorama==0.4.6
cryptography==42.0.2
frozenlist==1.4.1
idna==3.6
iniconfig==2.0.0
multidict==6.0.5
mysql-connector-python==8.3.0
packaging==23.2
pluggy==1.4.0
psutil==5.9.8
py-cord @ git+https://github.com/Pycord-Development/pycord@fc7b1042c4a9a942b9996dfe96f56aac059e179c
pycparser==2.21
PyMySQL==1.1.0
pytest==7.4.4
pytest-asyncio==0.23.4
python-dateutil==2.8.2
python-dotenv==1.0.1
pytz==2024.1
requests==2.31.0
six==1.16.0
stripe==8.2.0
typing_extensions==4.9.0
urllib3==2.2.0
yarl==1.9.4
The only difference is the py-cord version
Does client.get_message(message_id) get data from the bot cache? May be pointless to use it with on_raw_message_delete if so.
yes
Ok this is a simple question, how can i get the value of username and print it using print()?
@bot.command(name="verify", description="Verify your account")
async def verify(ctx, username: discord.Option(str, "Put the exact in game username")):
username: discord.Option(discord.SlashCommandOptionType.string)
why do you have username two times?
what do you mean
The internet say is correct
if you want you can delet one of them
if is not correct
I tought this is not a mistake but ok, i read wrong on internet ig
Can the bot user cache be disabled?
So you would have to fetch anything?
Yes, it is for a function of the bot that must get all of the users it shares guilds with
if i change bot to client, the command works again, but the command which shows me all of my coins wont work then
how to get icon from the guild
guild.icon
@to_do_group.command()
async def get(self, ctx,
name:discord.Option(str, autocomplete=getAllToDoLists(ctx.user.id), description="The name for your to-do list.")):
I'm a bit stuck on how to structure the above. I have the function getAllToDoLists which basically gets the user's to-do lists from a database. However, how do I pull from that database with the user's id when I can't access it in the parameter?
I'm not sure how I should structure my code to achieve that
waait
I think I remember the autocomplete func having another parameter
yep that was it
it does have an interaction
AutocompleteContext
is there a workaround i can do to dynamically display layers in a world from an option the user selected?
how do i use <t:{time.time() + 600}:R> in a discord bot?
description=f"Your token has been generated and expires in <t:{time.time() + 600}:R>"
Example:
discord.utils.format_dt(datetime.now(), "F")```
thank you kind sir
You have to use autocomplete, based on the past option using AutocompleteContext.options
Here's the slash autocomplete example.
.rtfm AutocompleteContext.options
having issues with an error that has never come up in my 3+ months working on this bot
no clue what's causing it
What is your py-cord version?
running latest
had no errors 2 days ago
just opened the file today and now it's full of warnings
fixed it through editing pylance's typecheck overrides
I have a bot that regularly disconnects, and after it does, I see a log message I put into on_ready, but the other functions of the bot cease, and on discord the bot appears offline. Where might I look first to work out why this might be happening?
can you send the code of your bot
actually
are there any errors in your bot's console?
No errors in the bots console. Code is here : https://github.com/markng/roll-call/blob/main/roll_call_bot.py
the "we have logged in as blah" message prints
does on_message function at all
Hello. how can i check if the server has an active subscription?
how can i handle multiple users running the same command at once? 9/10 times one user will recieve The application did not respond error and they still will get cd for command
it's probably one of the following reasons:
- something to do with the way your command was written
- the bot's connection to the internet/cloudflare
- Discord was just bad
It's documented as SKU(s) under the docs. But not quite sure how you'd get it for a guild, I don't see a method or attribute unless it's not documented.
i can only find "primary_sku_id" https://docs.pycord.dev/en/stable/api/application_info.html#discord.AppInfo.primary_sku_id
but thats for games.
i did manage to find this pr wich i think is what i want. https://github.com/Pycord-Development/pycord/pull/2273/files
but i have no idea how to use it
You might need to install the master branch.
?tag install
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
not sure if it worked, but "fetch_entitlements" now gave me another error.
ill play around a bit.
thank you for the help
jup. worked. now i only have to understand how to actually implement it without any documentation...
documentation has also a master branch. so that should work for me
Is it possible to check for a users role outside of a command event, specifically I have an on message event that will send the message off to an ai for a response but I want to limit who is actually able to speak to the ai / have their messages read by it
All I keep finding results on is checking roles for commands but that doesn't really work for what I've got cooking
The message object has an author attribute that returns a discord.Member object (if the message is in a guild)
Right, and I can get console to print out a users roles but for whatever reason if I try to do a "if 'Rolename' in message.author.roles" it doesn't find anything, idk what I'm doing wrong lmao it's late
Because message.author.roles is a list of discord.Role objects, not strings
You have to get the role
.rtfm get_role
i hate that theres a difference, i didnt know about the get role section, its fixed now ty
Difference of what? It's always been like that.
No i know i just mean like when I'm printing stuff out to console and something looks like itll work one way but doesn't
Because most objects have a __str__ which usually returns the name.
Hi
I'm running version pycord 0.1.1 (don't ask..)
And now getting the error
KeyError: <StickerFormatType.unknown_4: 4> when starting the bot.
I assume it's due to a breaking change and I need 2 update? Is there a version that I can update to to fix this without having to work on any breaking changes/adjust code? I only have mobile rn 😅
Updates are always recommended during security and compatibility changes
so yes, run the update
hey guys i have a stupid question is it possible for a bot to see a users bio or like description ?
no, discord doesn't want bots to read that
private info and stuff
okey thx
pycord is not the same at py-cord
pypi pycord is for video decode
dont use requests for your bots
What? For SLAG?
ye
That's only to get data from micron.com
?tag requests
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
np ^^
It would do so much for moderation, though. Too many people with "🟣 Admin" in their bio
Please show all of your dependencies (pip list)
Can't auto mod do this? That way only discord sees it but you can still have custom rules
Does automod work on bios? I didn’t see that option but it’s been a while since I’ve looked
Most people shouldn't fall for that
But this is Discord...
Our server attracts a lot of Discord newbies in general.
After looking, automod only looks at usernames, not bios.
I don't think any bot can read the About Me
Correct, that's the discussion, Wolfy asked if Discord's built-in AutoMod could, but it cannot.
So there are no available protections for users being duped by fake role names in scammer bios.
Unless someone wants to check all of the bios
Yeah, we do occasionally. But that's a shitty mod experience.
Like this should never be able to happen. People brand new to Discord can't always tell that's falsified, especially through DM.
Discord should have that in the API. If users can see it, bots should be able to see it.
Are you deferring the command that could help
No I am sending a non deferred, Im now looking into it, that looks like it could solve the issue
Await ctx.defer()
Oh wait, my bad, I am deferring it and it throws that error
My bad, it might have been planned but not released, or I'm just completely wrong 1
i thought you could access that info with oauth2
i remember being in a server which had access to check your current activity and if it was a specific one you'd get an auto ban
are u running any tasks or have a database thats blocking
?
thats from Intents.presences
unrelated to bios and pronouns
Possibly, but that's a lot of work (especially since pycord doesn't work with oauth2 (at least easily))
Is it possible to get connections from a user profile, such as eBay and Xbox?
I am trying to show an emoji in the state of my bot, but it is not showing, nor does it return any error, the text is shown but the emoji is not
await bot.change_presence(activity=discord.CustomActivity(name=status, emoji=discord.PartialEmoji(id=1191100279106576526, name='burple_check'),status=discord.Status.online))
i don't think they support emojis, just text
which is stupid
but it is what it is
This bot has an emoji
thats unicode text
yeah, thank you
yeah, I was reading the Discord API, I was just wondering if it could be done with pycord
I had all my slash commands disappear, restarted the bot a million times, re-invited it, still only some of them are showing up yet all cogs showing as loaded during startup. Any suggestions or troubleshooting ideas? I didn't change anything which is odd, but the commands have been out all day.
I am making a Game that involves clicking a button, the game has teams and once a team has clicked a button they are not allowed to press the button again. The game itself is contained in a Cog and I want the Cog to be informed about who pressed the button, how can I do that?
class QuestionPost(discord.ui.View):
def __init__ (self, question: JeopardyQuestion, voice: discord.StageChannel):
"""
Initializes the QuestionPost instance.
Args:
question (JeopardyQuestion): The question to display.
voice (discord.StageChannel): The voice channel to move the user to.
"""
super().__init__(timeout=None)
self.question = question
self.voice = voice
@discord.ui.button(label="Buzz In", style=discord.ButtonStyle.blurple)
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
button.disabled = True
user = interaction.user
button.label = (f"{user.name} buzzed in!")
await interaction.response.edit_message(view=self)
await user.move_to(self.voice)
await user.request_to_speak()
Here is where I want the Button to Update:
async def show_question(self, uuid : str):
"""
Asynchronously shows a question to the players.
Args:
uuid (str): The UUID of the question to show.
"""
if uuid in self.question_post.keys():
question_data = self.game.get_question_by_uuid(uuid)
embed = discord.Embed(
title="🌟QUESTION🌟",
description= "Here is the question again! \n" ,
color=discord.Color.random()
)
question = QuestionPost(question_data, self.stage)
await self.question_post[uuid].edit(embed=embed, view=question)
You could probably use a bot var
you actually can't because multiple instances of questions or whatever would break it unless each question can be uniquely identified from another (such as using an ID)
I assumed that would be obvious
it's not
Is it wise to Pass the Cog itself and then Updating the required in the Cog itself?
I have modals set up in separate modules that get imported to my main script. I want to create a new channel with the command and then send the interaction response to that channel, but I'm struggling to find out the proper flow for this. Any advice?
You can't. Interaction responses are sent in the same channel they got originally called.
Understood. Is there a way to return the data provided in the interaction instead, and then construct my own response?
What are you trying to do?
I'm creating a bot that integrates with my business panel and allows users to submit tickets via interaction.
I have other bots that use modals but they, as you said, send reponses to the same channel and that works for those.
You could just send an ephemeral response.
And then send whatever data the user submitted with channel.send
Well, the purpose of the creation of the new channel would be that it would send and receive messages for the ticketing system in that channel.
That logic is pretty easy to do since it just uses API, but that initial interaction is where I'm struggling.
I am trying to create a Option in a slash command with a Enum. I am not sure why it is not working:
@discord.option(
"language",
description="The language of the output",
default=Language.MANDARIN,
type=Language
)
@slash_command(guild_ids=guildIds, name="membership", description="Show you current membership")
async def show_membership(self, ctx: ApplicationContext, language: Language):
await self._show_timed_role_of_member(ctx, ctx.author, False)
i get the error:
What's the flow exactly?
class Language(Enum):
ENGLISH = 1
MANDARIN = 2
User submits interaction. Simple enough.
The data from the interaction, which includes an account email and the query itself, is sent through my panel's API to the ticketing system, which creates a new ticket.
A new channel is created for the user, and the information they submitted from the ticket is the first message from the bot.
Any responses to the channel by the user or staff member are collected by the bot, embedded, and added to the ticket on the ticketing system.
The only thing I really am struggling with is returning the data from the modal, since I've only ever used modals to return ephemeral messages or otherwise in the same channel it is sent in.
So the only issue is just sending the data to the channel
Guild.create_text_channel returns the created channel
You use that returned object to send whatever info you want
No, the issue is accessing the data submitted from the modal.
Here's the modal dialogs example.
You can see there how you access the data.
I suck at explaining my question, I'm sorry. So pulling from the example, is there a way to return the value of InputText to the modal_message command so that it can be used away from the modal class?
Keeping in mind my modals are placed in a separate module
can you have async innit
I feel like there is a joke to be made using the spelling error but I can't find it
Heyo! Was just wondering what I need to do to get it to recognise/find the discord module.
Code
``
import discord
import config
bot = discord.Bot()
@bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")
@bot.user_command(name="Say Hello")
async def hi(ctx, user):
await ctx.respond(f"{ctx.author.mention} says hello to {user.name}!")
bot.run(config.TOKEN)
``
My error:
line 1, in <module> import discord ModuleNotFoundError: No module named 'discord'
🙂
Have you installed it?
pip install py-cord in your terminal
yeah
Am I meant to have the discord/discord.py module installed?
I tried with them and it didnt work
so yeah
Anything else I should try?
how can i add more than 25 choices for slash command?
oki
then you should be able to import it
is it possible?
that’s a great question
did you break something?
hmm
i just wanted to use something other than nextcord with a simpilar api like this
yis this one way better
?
pycord better
ye lol
oo
oki good night
gn
is there any reason why interaction.resonse.send_message doesn't show as a function in my ide (pycharm) the resonse doesn't show that send_message id a fnction that is available to it
maybe because you misspelled “response”?
also that’s not how python intellisense works
thats just me miss typing here, its definetly spelt correctly, like it works but intelij just doesnt recogniise it
iirc, they only go one layer deep
so it would autocomplete interaction.response
but not response’s attrs
hi
I'm getting a discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Why is that
What permission does it need
if it knows the type it should (but it doesn't for some reason)
you are probably trying to register a command in a guild your bot is not in
ok I fixed my prpeviois error
but Now a small error
message = await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))
correct_answer_given = False
def check(answer_msg):
print(f"Received message: {answer_msg.content}")
print(f"Reference message ID: {answer_msg.reference.message_id}")
print(f"Expected message ID: {message.id}")
return (
answer_msg.author != bot.user
and answer_msg.reference
and answer_msg.reference.message_id == message.id
)
OOOOOOOOOOHHHHHHHHHHH WAIT
The reference message Id is not being equal to actuall message id
That was the issue
respond returns an interaction, not a message
So how I get the Id of the embed I sent?
through respond
When I use use answer_msg.reference.message_id
It gives the correct value
but that's for replies
I need it beforehand to check
it
that should just be await ctx.interaction.original_response()
wdym
that is how you would get the message associated with the message you responded with
yeah but I need to check it right
basically the bot will only those answers that are replied to the riddle embed
I understand
yeah
you know how to get a message's ID right
yes
so you can check it
.
interactions are not messages
so the ID is different
if await ctx.interaction.original_response() returns a message, what does that mean
message = await ctx.interaction(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))
so I change it to this?
no
I see
you would respond as usual, without the message assignment. Then, use await ctx.interaction.original_response() to store the message object
you are saying that I get the refrence from interaction itself?
instead of the message
the reference message stays the same
await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))
message = await ctx.interaction.original_response()
yeah but I would need the id of the message for my sent interaction
you have a message object
yeha but it stores the id of the interaction
no, this message is a Message object
the only thing you need the change is outside the function
ok I don't understand shit
I just want the message id of the interaction instead of the intereaction id
So that the reference would be equal to it.
message = await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))
correct_answer_given = False
def check(answer_msg):
print(f"Received message: {answer_msg.content}")
print(f"Reference message ID: {answer_msg.reference.message_id}")
print(f"Expected message ID: {message.id}")
return (
answer_msg.author != bot.user
and answer_msg.reference
and answer_msg.reference.message_id == message.id
)
try:
answer_msg = await bot.wait_for('message', check=check, timeout=30.0)```
+ await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))
+ message = await ctx.interaction.original_response()
- message = await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))
these are quite literally all the changes you need in your code
this?
yes
do you understand OOP lol
i am a machine learning engineer
english is not just my mother tongue
i am making a discord bot first time
do you understanding object-oriented programming
yes
i know you are talking about instance variable of the message class
of which the message object is created
ok
yw
im follow you on github in return
ty
how does one create a followup response for a modal?
Docs say Interaction.response.followup has:
Returns the followup webhook for followup interactions.
But I have no idea what that extends from
interaction.response.followup.send?
tried that
await interaction.followup.send_modal(AddItemModal(message=self.view.message, title=self.title))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Webhook' object has no attribute 'send_modal'
wait...
OH
Followups can't send modals
Ask discord
what should I do instead
Don't defer.
Send a button then that opens the modal
How would i get Py-cord 2.5 so the pomelo works properly? (Considering py-cord-dev doesn't work anymore)
Nevermind (git+https://github.com/Pycord-Development/pycord)
Hello! How I can add buttons when is View initialized? (I can't figure out how to bind a callback function to a button)
class ViewClass(View):
def __init__(self, ...):
super().__init__(timeout=...)
self.add_item(... # here)
I take it I should create a subclass for the buttons? I just don't see any other way out
class ButtonClass(Button):
def __init__(self, ...):
super().__init__(...)
def callback(self, button: Button, interaction: Interaction):
...
Here's the confirm example.
.
Button callback has to be set after button creation
mybutton.callback = mycallback
is it necessary to make a select class? cant we just declare it without it
I need examples
it depends on your implementation
Uhh, anyone ever seen this before?
pip3 install -U py-cord@git+https://github.com/Pycord-Development/pycord
WARNING: Generating metadata for package py-cord produced metadata for project name unknown. Fix your #egg=py-cord fragments.
Discarding git+https://github.com/Pycord-Development/pycord: Requested unknown from git+https://github.com/Pycord-Development/pycord has inconsistent name: filename has 'py-cord', but metadata has 'unknown'
ERROR: Could not find a version that satisfies the requirement py-cord (unavailable) (from versions: 1.7.3, 2.0.0b1, 2.0.0b2, 2.0.0b3, 2.0.0b4, 2.0.0b5, 2.0.0b6, 2.0.0b7, 2.0.0rc1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.2.0, 2.2.1, 2.2.2, 2.3.0, 2.3.1, 2.3.2, 2.3.3, 2.4.0, 2.4.1)
Didn’t they remove development
In some updates on this server
What do you mean? The github URL is still https://github.com/Pycord-Development/pycord
Oh I misread I dunno
Updated setuptools and pip itself and it magically worked. Friggin weird.
Hiya,
So when trying to run my bot I get this error:
AttributeError: module 'discord' has no attribute 'Bot'
This was not happening yesterday.
Here is my code:
import discord
import asyncio
import os
bot = discord.Bot(command_prefix='!%') # Defining the bot
@bot.event # Logged in
async def on_ready():
print(f'I am logged into the discord api as: {bot.user}')
@bot.event()
async def on_member_join(self, member):
await member.send('Welcome to the server!')
auto_assign_role = discord.utils.get(member.guild.roles, name='Member')
if auto_assign_role:
await member.add_roles(auto_assign_role)
print(f'Auto Added Member Role to {member.display_name}')
@bot.slash_command(name='ping', description='Check my latency!') # Ping Command
async def ping(ctx):
latency = round(bot.latency * 1000)
embed = discord.Embed(
title='Pong! :ping_pong:',
description=f'My current latency is: **{latency}ms**',
color=discord.Color.blurple()
)
await ctx.respond(embed=embed)
@bot.slash_command(name='donate', description='Donate to the creators of the bot') # Donate Command
async def donate(ctx):
embed = discord.Embed(
title='MAGI WALLET: 96Ld2MYadxQbNCBGcbPYDhXkEDurNbGH65',
description='Donating helps the bot by keeping it online',
color=discord.Color.blurple()
)
await ctx.respond(embed=embed)
# Cogs Stuff only beyond this point
async def load():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
@bot.command(name='reload', description='Reloads a cog.')
async def reload(self, ctx):
async with ctx.typing():
embed = discord.Embed(
title='Reloading all cogs.',
color=0x808080,
timestamp=ctx.message.created_at
)
for ext in os.listdir('./cogs/'):
if ext.endswith('.py') and not ext.startswith('_'):
try:
self.bot.reload_extension(f'cogs.{ext[:-3]}')
```
embed.add_field(
name=f'Reloaded: `{ext}'
)
except Exception as e:
embed.add_field(
name=f'Failed to reload: `{ext}`',
value=e
)
await asyncio.sleep(0.5)
await ctx.respond(embed=embed)
@bot.command(name='unload', description='Unloads a cog.')
async def unload(self, ctx):
async with ctx.typing():
embed = discord.Embed(
title='Unloading all cogs.',
color=0x808080,
timestamp=ctx.message.created_at
)
for ext in os.listdir('./cogs/'):
if ext.endswith('.py') and not ext.startswith('_'):
try:
self.bot.unload_extension(f'cogs.{ext[:-3]}')
embed.add_field(
name=f'Unloaded: `{ext}'
)
except Exception as e:
embed.add_field(
name=f'Failed to unload: `{ext}`',
value=e
)
await asyncio.sleep(0.5)
await ctx.respond(embed=embed)
async def main():
await load()
await bot.start('my token you no get xD')
asyncio.run(main())
Can you show your pip list?
Also discord.Bot does not have a prefix
Whats the pip list
You dont know what the pip list is?
well I do, its just I dont know how to access it
Package Version
------------------ ---------
aiohttp 3.8.6
aiosignal 1.3.1
annotated-types 0.5.0
async-timeout 4.0.3
asyncio 3.4.3
attrs 23.2.0
certifi 2022.9.24
charset-normalizer 2.1.1
colorama 0.4.6
decorator 4.4.2
disnake 2.7.0
frozenlist 1.4.1
idna 3.6
imageio 2.22.4
imageio-ffmpeg 0.4.7
moviepy 1.0.3
multidict 6.0.5
numpy 1.23.5
packaging 23.1
Pillow 9.3.0
pip 24.0
proglog 0.1.10
py-cord 2.4.1
pydantic 2.4.2
pydantic_core 2.10.1
replicate 0.13.0
requests 2.28.1
tqdm 4.64.1
typing_extensions 4.8.0
urllib3 1.26.13
yarl 1.9.4
got the pip list xD
is disnake needed?
disnake is also from discord.py?
No, its a different library
okay, I may need some guidance here:
I want to make a bot that works similar to an announcement channel w/ publishing, right?
the issue is, how do I copy the message, word for word and with an attachement?
the attachement will always be a .png
and it will always contain one
Thank you!
.rtfm message.attatchments
Target not found, try again and make sure to check your spelling.
discord.on_message
discord.Message
discord.Message.activity
discord.Message.add_reaction
discord.Message.application
discord.Message.attachments
discord.Message.author
discord.Message.channel
discord.Message.channel_mentions
discord.Message.clean_content
discord.Message.clear_reaction
discord.Message.clear_reactions
discord.Message.components
discord.Message.content
discord.Message.create_thread
discord.Message.created_at
discord.Message.delete
discord.Message.edit
discord.Message.edited_at
discord.Message.embeds
Compares Discord libraries and their support of new API features
Oh wow thanks didnt know that existed.
Is it possible to create a modal or something similar off the back of a slash command from a user for them to select a datetime from a dropdown?
Modals can't have dropdowns.
Forgive my ignorance, what options are there?
Only text inputs.
I'm thinking of the bot messaging a user and them being able to choose the date-time from a dropdown.
So its free-type options for the user only?
Yes.
No worries - thanks for your help.
i have a command /trivia with parameter topic: which is important but is it possible to have a optional parameter like language: where if user doesn't type anything it will just be handled by code? Or something like that
yes
Here's the slash options example.
aha
How to sync slash commands?
with sync_commands
but Im not sure if it works to 100%
Have the AutoComplet a limit
No not really
okay, but why i dont see the 32 from this list
['Paper (1)', 'PurPur (2)', 'Fabric (3)', 'Forge (4)', 'Bungeecord (5)', 'Wordpress (6)', 'Basic (7)', 'THE ISLE (8)', 'Euro Truck Sim 2 (9)', 'American Truck Sim (10)', 'Satisfactory (11)', 'Python (12)', 'CurseForge Modpacks (13)', 'ARK (17)', 'Terraria (18)', 'tModLoader (19)', 'Next Cloud (20)', 'TVS - Temp Voice System (21)', 'TS - Ticket System (22)', 'ECS - Embed Creator System (23)', 'BCS - Button Creator System (24)', 'MH - MySQL Handler (25)', 'Python Lifetime (27)', 'Palworld (29)', 'Webhook Test (31)', 'Test V1 (32)']
discord only shows 25 of it
the other ones have you to type to see them
that is how autocomplete also works at your Phone
This is in an async def function(): its saying key word url
view = discord.ui.Button(label = "CLAIM", url = "https://gg.gg")
await ctx.respond(embed = embed, view = view)
Here's the slash cog example.
@finite plover
thx
Hi, how can react when a user switch the side from a paginator
You need a view. You cant pass the button to the view kwarg
view = discord.ui.View()
view.add_item(discord.ui.Button())
Didn't you get an answer to this in a thread
yeah but idk how can i work with thios
You'd subclass the paginator and override the method
Do your stuff, then call the super() method to not lose what the method was originally doing
AttributeError: 'SlashCommand' object has no attribute 'command'
What's the meaning of this?
@image.command(name="some command", description="some description")
@commands.cooldown(2, 7200, commands.BucketType.user)
@commands.has_permissions(manage_messages=True)
lol nvm
i got the function defined wrong
What's image
My guess is it was supposed to be SlashCommandGroup
yes
i forgot to change the function name
Hi. I have a quick question.
If I create a task loop, specifying it's looping interval times in a variable
@tasks.loop(seconds=delay_seconds)
Can I update the variable time to update the loop accordingly, or I need to stop the loop and start it again to make the change take affect?
Try it and see
Very useful answer. Thanks.
Answer was loop.change_interval method if anyone else have the same question.
Can I populate a command option choice with a guild's current automod rules?
Here's the slash autocomplete example.
yes
why i add new slash command (now there are 8) but it doesn't show up?
That depends on many things. You haven't showed any code.
what can i show? slash command doesn't show up before remove one
Comment out the command. Run your both. Remove the comment. Run again.
Okay i will try it later
Perfect, thanks. I got it setup
can the bot wait for message inside a button callback?
it doesnt seem to so when i am doing it
async def button_callback1(self, button, interaction):
button.disabled = True
msg = await bot.wait_for("message", timeout = None)
Im getting a certificates error when i try to launch my bot
idk why
from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')]
didnt have intents on nvm fixed
.tag certif
Tag not found.
uhh
.tag sslfix
If you're getting the [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108) error on a Windows host do the following:
Download and install this certificate here: https://crt.sh/?id=2835394
--> It can be installed by double-clicking the file and installing it to Local Computer, download link location: https://beans-took-my-kids.reeee.ee/38qB2n.png
For those curious, it was caused by this:
https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA03l00000117LT
actually might not be the same thing
Hey, the docs state that discord.Member has a history() method. Can I actually get a user's message history without having to provide a channel context?
(It's weird because it's https://docs.pycord.dev/en/stable/api/models.html#discord.Member.history but the example still references a channel)
Is there still no way of getting a member's chat history without iterating through every channel?
Yes, by the looks of it. My bot iterates through all guilds and channels.
Then separates that data into each database for each user
@commands.Cog.listener()
async def on_button_click(self, interaction: discord.Interaction):``` is there such an event in pycord?
yes
its on_interaction
but that triggert all the interaction stuff so you have to filter it
How do I determine what type of interaction is button click ?
It’s completely dumb. I want to be able to get the messages of someone when they’re banned (for audit purposes) but iterating over every single channel is so wasteful. 😩
how to handle on modal submit event?
I'm making a view to return if it has interacted, i.e. an on_click_button:
# View
class ConfirmView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.is_confirmed = False
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green, emoji=f"{Emojis.green_tick.value}")
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
self.is_confirmed = True
await interaction.response.edit_message(
content=f"{Emojis.pensil_edit.value} Cleaning {interaction.user.mention}...",
view=None,
embed=None)
# command /example
async def example():
#--
view = ConfirmView()
await ctx.respond(embed=embed, view=view, ephemeral=True, delete_after=120)
await view.wait()
#--
if view.is_confirmed:
print("On click")
This should be correct?
No. View.wait waits for a timeout or a manual stop
and how should I do it?
You have to add self.stop() to your button callback. At the end.
Thx bro

thxx
Yeah, it is. In my case I am logging all of the messages.
Hi, how can i add to my slashcommandgroup a nother group like test add <command>
pr test remove <command>
You can't
is there an easy way to run a function at the start of every hour
you mean instead of a task?
yeah
cause afaik tasks only use relative time (seconds from x) instead of set times
they can run at set times
You can have two levels of groups. https://guide.pycord.dev/interactions/application-commands/slash-commands#sub-groups
Here's the background task example.
I still like aiocron a bit more than internal tasks.
yeah, this
oh thanks
Only downside to aiocron is that you can't use their decorators with Cogs (or any class), so you have to define and start them from __init__ (or a method called from init)
re: message deletion, when are messages "bulk deleted"? Does that happen when you ban a user and opt to remove all messages from 'x' time?
those are two different api requests
banning has an option to remove messages
but bulk deleting is its own separate thing
Who can bulk delete? I've definitely never seen a UI interface for it
commands like purge
it’s an api thing
Quick question, does the library offer some way to clear cache or refresh the bot? My bot reaches upto 4 gb ram when it’s idle is only 200mb and is in 25 servers only (it’s just a basic level bot)
But out of curiosity on this point, do you know what Discord uses when you Ban + Delete? Are several on_message_delete events fired, then?
¯_(ツ)_/¯
I think it’s the buttons in rank command response which cause it, at least noticed this happen after deploying buttons to rank command
I make the view timeout after 600 seconds
what are you storing
I’m using a PostgreSQL database to store server id; user id; xp
Pretty basic, i feel it’s the buttons which act up, any example gist code link to make memory optimised buttons?
what intents do you have enabled
It’s the level roles button, servers can customise this upto 3 buttons (my bot is being used in big servers tho like 99k members)
discord.Intents.default()
Pretty sure I have overwritten it in the next line to enable members intent and presences intent
yeah members intent is why you have such a high memory usage then
Oh I see, thanks for lmk
the buttons are negligible in comparison
If I turn it off, will it affect the bot’s ability to sense messages to add xp
Oh
i don’t know how your system works
Members? Probably not, if it has messages.
Sorry about that; i better try it than ask, thank you so much 🙏
Is there a way to run a function at a specific time every day?
#1132206148309749830 message
Oh, it is also in the docs, I am blind
i need help im trying to attach a callback to an existing button everytime the bot is started but its not doing anything
async def suggestion_callback():
print("Works")
@bot.event
async def on_ready():
print("Ready!")
channel = bot.get_channel(1206445575759724619)
message = await channel.fetch_message(1208606430924636221)
view = discord.ui.View.from_message(message)
view.children[0].callback = suggestion_callback
the message referred to does have a valid button view
does async for ... in audit_logs retrieves all the entries at first, or does it fetch them as needed ?
Also the oldest_first options does not seems to be working. It return the newest_first
In the docs it says oldest_first (bool) – If set to True, return entries in oldest->newest order. Defaults to True if after is specified, otherwise False.
Fixed it, what tests do you need to run to make PR ?
What the hell is that.
Use persistent views if you want callbacks to persist
Here's the persistent example.
nevermind it was just bot.add_view(MyView())
...weird, Discord doesn't seem to fire any event when deleting messages during ban?
nm, it was being weird. Sometimes it sends bulk, sometimes not.
Is there a way to determine whether a Member is banned in the current guild/server? Doesn't seem like it, but asking in case it's buried somewhere I'm not looking.
Need some brainstorming assistance -- So ban and message deletion are separate events, and ban reasoning is even more separate, being in the Audit Log. I always want to alert (to a channel) when a user has been banned, but I'd also like to get the last message or two that was deleted, if that option was selected.
My current ban event hook attempts to grab the Audit Log entry and display that in the alert. My new hook sets the user id in an internal dict so that on_message_delete/on_bulk_message_delete can be matched to a ban event.
So what might be a good code path to include that in such an alert, if available, knowing that there may be times a user is banned but no message delete event would be fired.
Ban Event -> Catch Deleted Message(s) via Event -> Fetch Reason -> Display completed alert
Ban Event -> No Assoc Delete Event -> Still Fetch Reason -> Display completed alert
If i need to wait an hour after a command to make the bot send a message
should i asyncio.sleep or use other thing
Asyncio.sleep
its got a limit
Is the limit that small?
Wasn't it like 15 minutes?
I sleep 20 minutes in a callback and it works.
oh ok?
Docs don't mention any limit.
Is it possible to pass parameters to a Cog?
yes
Do I just add a non-keyword argument to load_extension?
How do I pass the parameters?
i can't find a reason why would need to do that tho
Actually an extension (I often get confused on the two). It is for running something before all of the cogs are loaded in setup(client) if a certain command line flag/argument is present.
so how would checking that inside the cog help
I forgot I could actually use sys.argv within an extension
you're thinking of the interaction response limit after being deferred
sleep doesn't necessarily have a limit, it could just be considered unreliable the longer you sleep
I feel attacked
I mean, it's fine to use it if it works for you
I just personally opt for tasks if I'm waiting for anything beyond a few minutes
Just shitposting on the being “considered unreliable the longer you sleep”
Ah LOL
is there a way to fetch audits logs without discord.audit_logs ? The current implementation seems broken
it fetches multiple times the same logs
i found a solution for it. You just need to change in the after strategy self.after = Object(id=int(entries[0]["id"])) to self.after = Object(id=int(entries[-1]["id"])) . Because when using after, list is reversed and appears in ascending order (older entries first). So you want the after to be the newest entry (the last one). Also removed the oldest_first options. Now the before and after are behaving as expected
in AuditLogIterator
import discord
from discord.ext import commands
from globalsupport import config_support
class Weiterleitung(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
channelweiterleitung = self.bot.get_channel(config_support().weiterleitung_id)
if not before.channel or before.channel and after.channel:
if after.channel.id == config_support().warteraum_id:
nickname = member.nick
name = member.name
if nickname == None:
if name.startswith("@"):
await member.move_to(channelweiterleitung)
if nickname != None:
if nickname.startswith("@") or name.startswith("@"):
await member.move_to(channelweiterleitung)
else:
return
def setup(bot):
bot.add_cog(Weiterleitung(bot))
this is my cog, to move people to a different channel when their name starts with "@"
if i join the channel with a "@" it moves me but if i then remove the "@" and join the channel again it still moves me
does anybody know why?
print both of the variables and see what they actually contain, then you can troubleshoot with that info
most probably one of those variables prefixes an @ like @username
btw, else: return can be completely removed
Hello! What does py-cord documentation version v0.1 mean? Is this the master?
context?
it’s a bug
Master version has file READ_ME, at the bottom of it is a link to the documentation v0.1. I tried to find documentation for this version
Can someone explain me how i use the on message cooldown in a cog
yes this is master, it is just a visual bug. You can change your version at the bottom of the sidebar if needed
events don’t have cooldowns
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
events don’t have cooldowns
is there a way to pass variables to extensions, or is there an on_load or smth for cogs? i need to establish a database connection when I load my cogs
pass it through the bot object
i already replied to you
oh
how are subcommands like this made?
@azure cobalt ^
cool, thanks
can't fetch_channel(id)
why ??
also get_channel(id) retuning None
yt-tutorials, youtube, xy, wavelink, virtualembed, usernames, usercmd, update, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, this, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, sqli, solved, snowflake, slashcommandmention, slashblog, rie, restartcmd, requests, replit-install, replit, removeall, pythonversion, pythonserver, python, practices, pp, pomelo, persistant_view, paste, partial_objects, oracle, option, oop, om, official, objects, notpycord, norepl, nojson, nohelp, nohello, no_status, name-conventions, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, logging, localfile, learnpython, json, intents, install_git, install, inline-fields, importerror, idw, ide, how2sql, helpgist, guide, git, gif_avatar, getalpha, get_x, get-help, gather, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, cmd-limits, closing, client, chatgpt, buttons2, buttonlimit, bridge, breaking-changes, botvar, bitwise, asset, applicationcommands-registration-delay, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel, 429
exception
?tag exception
print your id variable and see what it is. if it's none, then it's none. if it is an id and get_channel is returning none, then the bot doesn't have access to the channel. also make sure the id is an integer, not a string.
please provide code or else i cannot help you.
update your version of pycord
okh let me try this
Requirement already satisfied: py-cord in /data/data/com.termux/files/usr/lib/python3.11/site-packages (2.4.1)
did you do this
async def send_message(channel_id,role_id,embed):
print(channel_id)
print(type(channel_id))
channel = bot.get_channel(channel_id)
print(channel)
await channel.send(f'<@&{role_id}>',embed=embed,username="Global Boost Detector")
How to upload an animated avatar for your bot
To use and upload an animated avatar you can run the following snippet as standalone script:
import discord
import asyncio
# Intents to enable certain events
intents = discord.Intents.all()
# Create a Discord client instance with intents
client = discord.Client(intents=intents)
# Event to handle bot's initialization
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
# Upload animated avatar
try:
with open('yourpicture.gif', 'rb') as avatar:
await client.user.edit(avatar=avatar.read())
print('Animated avatar uploaded successfully!')
except Exception as e:
print('Failed to upload animated avatar:', e)
# Run the bot
client.run("YOUR_TOKEN")
That should be all, have fun!
but the fun fact is i run the code by eval and it's working 🙂
idk whyyy
print(bot.get_channel(1101552767404888084))
this is working in on_message()
but not working in other function
send your full code, even where you are using the function. everything related to the issue. without this i cannot help you.
run pip freeze in your terminal as well and send the output.
async def xx():
print(bot.get_channel(1101552767404888084))
this function printing the channel name if i use in on_message() or in slash command but not working(returning None) in send_message() function
run pip freeze in your terminal and send the output here
kindly check your dm
it's too long lmao XD
you can just send it here
as a .txt file
@loud kayak
if you're just using pycord for your project, you don't need that many packages.
do you have git installed on your machine? @ivory beacon
yeap
.install
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
ok let me check
kindly read this:)
i saw
use ```py
channel = bot.get_partial_messageable(id)
await channel.send(...)
but working in other function like on_message() 😪
where are you calling this function
like i asked, but won't give the code
wait
.
no, where are you calling that function
let me push to git
how do i make it in my command have
/signup sendemail [true or false]
check dm
i sent you git link
can't you just send it here?
i hope you can read my code 🙂💔
if you can't answer my question, i can't help you. where are you using that function
im not gonna search for the function in your code.
global_boost_detect.py
180 Number Line
as file ?
no, where you are using the function.
it's literally 15 functions calling each other

🙂💔
bad practices
i never tried how to make discord bot:)
the issue is that you are passing around a stale bot object
how can i fix it:)
didn't working in my function 🙂💔
the channel id has to be wrong
no that's not the issue
working in eval
with same id
doesn't make sense for it to not work in a function but to work in an eval command
no i literally just told them why it doesn't
don't import it. Pass it through the function.
^
okhhh
you have no idea what i meant by it being "stale"
the object wasn't being updated, since it was being imported
yeah and that should be obvious because the API calls weren't going through
👋 im trying to attach the following image onto an embed, but it doesnt work: https://en.numista.com/catalogue/photos/allemagne/6058b1ae922851.03589029-original.jpg
I just noticed however that the image wont load in discord
however if you actually go to the image it does load
so, im quite confused as to what is going on here?
is there something about this image that just doesnt make it work?
does Paginator has built-in features for adding select menu like this? or i need to create manually the menus selector? I'm not referring to the page navigator button
i created that menu. it was manual
how do i make pagjnation pages persistent? do i only need to set the timeout to None?
how can i have dropdown menu, without callback and interaction failed message?
Hello! Can you please tell me by what logic the position of the Role and CategoryChannel is determined?
@commands.Cog.listener("on_message")
async def on_message(self, message: discord.Message):
if isinstance(message.channel, discord.channel.DMChannel)
...
thx
hello!
what's the difference between ctx and interaction?
i realized in my old file i have both
await interaction.response.send_message("Hello!")
and
await ctx.respond("Hello!")
both in slash command, they seem to do the same thing
ctx is ApplicationContext for slash commands
interaction gets passed to components like buttons, and it is a discord.Interaction object
ctx.respond internally does interaction.response.send_message or sends a followup if the interaction was deferred
so they are essentially the same thing, just when it's slash commands you can use ctx instead of interaction?
oh WAIT nvm i got it
thanks!
Message components get interactions slash commands get ApplicationContext that includes interaction+more info
@tasks.loop(minutes=1.0)
async def pay_business_owners_loop(self):
await self.bot.wait_until_ready()
# ensure we arent already paying business owners
if self.is_paying_business_owners:
return
now = datetime.now()
if now.minute == 0: # check if its :00
self.is_paying_business_owners = True
try:
await self.db_utils.pay_business_owners(self.bot)
except Exception as e:
channel = self.bot.get_channel(1129214926259494962)
await channel.send(f"Failed to pay business owners because {e}")
print(f"Failed to pay business owners because {e}")
finally:
await asyncio.sleep(600)
self.is_paying_business_owners = False
else:
# if its not 00 just return
return``` hey I am having an issue where for several hours its only paying out once, then eventually it will start to pay out double, any ideas why?
get_channel can be None
hmm i dont think that would be the case because there's other errors being posted there before and after businesses startred randomly paying double
Still weird that its happening two times
yeah, it makes 0 sense
whats more stupid is it works correctly for several hours than randomly break
my best guess is that it is somehow running the tasks twice in a minute
can i send link button via webhook ?
only webhooks created by bots can send components (such as buttons)
If you only want to pay out on X:00 you could just set the task to run at those times. You can pass a list of datetime.times instead of minutes
That might help a bit
oh wtf
i never knew that
ill be giving this a shot, thank you
any ideas for this?
code?
import logging
from os import path
import discord
from discord import bot
from discord.commands import option
from discord.ext import commands
class TestCommand(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
logging.info(
f"Cog {path.basename(__file__).removesuffix('.py')} loaded successfully"
)
@bot.command(description='test command')
@option(
"image",
description="The image to add to your embed!",
required=True,
)
async def testcommand(self, ctx, image):
embed = discord.Embed(
title='Test Embed',
description='Test Description'
)
embed.set_image(url=image)
await ctx.respond(embed=embed)
def setup(client):
client.add_cog(TestCommand(client))```
it does not work with the image I linked above but it does work with other images
and I noticed that the image https://en.numista.com/catalogue/photos/allemagne/6058b1ae922851.03589029-original.jpg does not load on discord, but I can go to it on a browser and itll show the image. so that makes me wonder if something is going on with the image..
then just post the image on discord and copy the media URL
thats not really an option. the url is stored in a database alongside many other images from the same website
this is just a test cog I made to see if images embed properly
fooling around with the real cog I run into the same problem - urls from that website do not load properly in the embed, but if I replace the url with ones that load into discord properly, it works just fine
figured..
is it your website or
nope
so I assume they blocked images from loading on discord? idk how thats possible..
i mean, i dont think discord uses any of these UAs
yea, weird, their embeds dont seem to work whatsoever
well depending on how many images we're talking, it might just be easiest to "host" them on discord
Considering the coming change on CDNs, not really tbh
why not?
You are loading it from inside discord
so its always gonna work
Plus, the changes are already in effect lol
They arent afaik
to my knowledge they are
and as long as you request that media via discord, it will always renew the "lease" so to speak
view ?
discord has a handle little embed debugger that helps with debugging: https://discord.com/developers/embeds
in this case, the website just hates discord
most likely anti bot measures
seeing as they are protected by cloudflare
mew?
Hey! I'm trying to subscribe to on_application_command, check if the slash command was run in a discord.TextChannel, and send an ephemeral error message if the slash command was not run in a text channel. My command creates a thread, which makes an error if you try and make a thread from in a thread.
After I send that error, how do I stop the actual command from trying to execute from within on_application_command?
webhook = discord.Webhook.partial(result[1], result[0], adapter=discord.RequestsWebhookAdapter())```
How can i use this in pycord?
Pycord offers support for creating, editing, and executing webhooks through the Webhook class. Attributes avatar, channel, channel_id, created_at, guild, guild_id, id, name, source_channel, source_...
Can i use webhooks with a webhook token and a webhook id and set a own avatar?
yes
ooo thats interesting, thank you for informing me about that 🙏
ive asked the website devs whats going on, then
I suppose if they say they wont revert it there's nothing much I can do aside from saving the image locally and uploading that..?
the embed I made was a test cog so I can see if the embed works with images. the actual url is in a database
well just save the url in a database
yeah but then id have to upload every image on discord 💀
it means this is a bad idea and we shouldn't support it (but it works anyways so just ignore it)
you could just do that automatically
maybe
if your bot isn't blocked
okay thank u
have the bot download every image and upload it, then snag the link?
yeah
I mean, yeah that could work
thanks for the help though, and the embed resource
perhaps its a website bug and theyll fix it but if not I guess ill do that instead
how to get current page in paginator? that i can used for custom_view
i need to know current page to updating the custom_view
setting up a task does not work for me
import logging
from os import path
from discord.ext import commands, tasks
class TestCommand(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
logging.info(
f"Cog {path.basename(__file__).removesuffix('.py')} loaded successfully"
)
@tasks.loop(seconds=20.0)
async def test(self):
print("Test!")
def setup(client):
client.add_cog(TestCommand(client))
output: nothing
Add the wait for ready and also you forgot to start the task
thank you, that worked!
maybe im delusional but i remember there was a way to make get requests using the discord.Bot object...
You mean ```py
bot = discord.Bot()
bot.http
?
Or requests with aiohttp?
Yes that was it
how to send components via webhook?🙂💔
same thing as a bot
How can I fetch a message from a StageChannel?
ah, I was in an older version, thank you
how do I determine if a slash command came from a guild or a DM
Is it not possible to use id in something like that:
bot.get_guild(id=…)```
I am going to try something
I hooked a debugger on a command in DMs, ctx.guild is None
some of my slash commands are not appearing in discord
@bot.slash_command(name = "save", description = "Save the configuration, can only be used by the owner")
async def save(ctx : discord.ApplicationContext) -> None:
if int(bot.owner_id) == int(ctx.author.id):
config.save()
await ctx.respond("Configuration saved")
return
await ctx.respond("You are not my owner")
try restarting discord
Does anyone have an idea how I can determine the arrangement in an embed field?
For example, if I say I have a heading:
Text 1 | Text 2 | Text 3 | Text 4 |
And then I want to determine the sizes of the fields so that it looks like this afterwards:
Text 1 | Text 2 | Text 3 | Text 4
Hello | How are you? | Nice | Great
Instead of
Text 1 | Text 2 | Text 3 | Text 4 |
Hello | How are you? | Nice | Great
you could use a description instead of the fields
or you add spaces
Spaces are automatically removed?
When I insert this, the spaces are removed and not displayed.
f"{var_1} | "
???!?
Member intents?
yeah, fixed it by using channel.voice_states
Ok
it also has member informations. but very weird that channel.members returns a empty list
i think its a cache problem or smth
Could be

