#Basic Pycord Help
1 messages Β· Page 48 of 1
embed = (
discord.Embed(title="wow")
.set_image(url="...")
.set_footer(text="...")
)```
oh neat
thanks, it works great!
allgood
And I love automod
well, in my defense, 1 command to install and it uses cool unicide Β―_(γ)_/Β―
Hi, all! Weird question:
- Given the ID of a thread, what's the best way to determine the sent date of the latest message in it?
Get the thread, then its history with limit=1 and oldest_first=False
https://docs.pycord.dev/en/master/api/models.html#discord.Thread.history
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 ...
Oh, that's class. Thanks much!
And to retrieve a thread object based on the string ID - what would I use?
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 ...
Magnifique
Uhhh btw every channel/thread has a last_message_id attribute
So you can just pass it into discord.Object and get created_at
(There's also last_message, but it's cache reliant)
On Discord it is not possible to prevent the user from downloading a video. Is there a way to track when a user downloads a video?
Or do you have any suggestions on how I can embed a video on Discord without a user being able to download the video but still watch it?
Embed is only gif and image
Do you have any ideas on how I could best implement this?
You can't
your only shot is finding a video hosting site that does this, and even that is trivial to bypass
why are you even trying to stop them from downloading them
Because it is a video course that the users should not distribute as money is paid for it. But unfortunately you can't really prevent that except by telling people that it's forbidden and adding watermarks to the videos π
Vimeo is quite hard to download from if you disable downloads
I know it cuz I spent time hacking it
and it wasn't easy
Okay, but you can't embed Vimeo in Discord like you can with YouTube, right?
I can only insert the link and the user has to click on it to be redirected to Vimeo, right?
Don't believe so yeah
I don't see any reason why you'd ever wanna watch a video in discord
just link it
people have browsers for a reason
Okay okay thanks π
Do we have functions to easily manage emojis that have been uploaded directly on our bot?
manage how?
Get a list, covert an emote name to an emote id, and things like that.
Well, it came out after 2.6 released, so its certainly not in pycord yet
if you dont have like 400 emojis you can just put it into a class or something in an emoji.py file and map the names to their pasteable strings you can get from the developer website
thats what id do anyway
channel_types=[discord.ChannelType.category]
you dont need required=True btw
or the slashcommandoptiontype might work there too
and also, type is the second positional argument, so you can just remove the type= and save some space lol
no, the typehint in the function header is ignored if you use the decorator
make sure to restart discord
I see. I'll make a list then. Thanks for the reply!
btw, @lean garnet, i think if you pass channel_types the input type is ignored completely so you can also completely delete it
Okay thank you. The issue with the channels is resolved
np
Even then they can still screen record it.
You're trying to prevent piracy but- we all know that's not possible :)
Anyone know why this command ain't loading?
from discord.ext import commands
import discord
from helpers import config_helper, firebase_helper
class TesterManagement(commands.Cog):
def __init__(self, bot) -> None:
super().__init__()
self.bot = bot
@commands.slash_command(description="test")
async def list_test(self, ctx, list_test: int):
await ctx.respond(str(list_test))
def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(TesterManagement(bot)) # add the cog to the bot
I don't see it appear in the list, I think I've added the cog correctly, just can't see the issue:```py
cogs_list = [
"config_cog",
"info_cog",
"ranks_cog",
"stats_cog",
"ticketing_cog",
"tester_cog",
]
for cog in cogs_list:
bot.load_extension(f"cogs.{cog}")
bot.run(TOKEN)
are the cogs in a folder?
yea should I show my project directory?
.
βββ LICENSE.txt
βββ README.md
βββ __init__.py
βββ assets
βββ cogs
β βββ __init__.py
β βββ config_cog.py
β βββ info_cog.py
β βββ ranks_cog.py
β βββ stats_cog.py
β βββ tester_cog.py
β βββ ticketing_cog.py
βββ config.json
βββ database.db
βββ helpers
β βββ __init__.py
β βββ
β βββ config_helper.py
β βββ firebase_helper.py
βββ main.py
βββ requirements.txt
which keybind is that again?
why do you have an __init__ in your cogs folder
ctrl+r or just restart it
cogs.config_cog
what about it?
my structure is src | commands | boss > owner.py
'src.commands.boss.owner'
theirs isn't
so i added the guild_ids param and its loaded now, maybe I didn't give discord enough time to register the command? Someone told me it takes less than like 2 minutes on 2 servers (I've waited at least 10 i'd say)
cache
yeah, same here.
close and open
we already went over that
prolly smth like that
you need to restart discord
so anyways, i did have another question, if I can ask:
What's the best way to take a list as an argument? Not a mutable sized list, but just a fixed size. Is having an option for each element the only option?
i use | in my own personal bot to make one option take multiple things
just seperate the things by | when typing the option, and handle it in your code
(thats kinda ugly and i wouldnt do that for a public bot tho)
apart from that, yea, you can only really do multiple options
A question guys.
I'm using the @discord.default_permissions(ban_members=True) decorator so that users who don't have ban permissions can't execute commands. But is there a special decorator for when the bot has not been given the necessary permissions?
interesting. Cuz my particlar issue is sort of like a "check the options that apply to you" issue. Atm, i was thinking just bools for each possible option, but i was wondering if anyone had any cleaner solutions
thats just an exception you need to handle
ext.commands.bot_has_permissions
oh
yep
and what does that do
(this will raise CheckFailure, it's not a discord sided thing)
specifically, BotMissingPermissions
yea i just thought of the good old
try:
ban()
except ...:
ctx.respond("No")
could also write a global error handler that handles that, so you dont have to duplicate that everywhere
does commands.CommandNotFound apply to slash commands?
no
what about commands.MemberNotFound
that should work
probably if you pass a random user ID
how tf does this shadow any variable?
the class has nothing called "member"
okay.. apparently the for member in members BELOW was the problem
we have a functional draft PR if you wish to install
https://github.com/Pycord-Development/pycord/pull/2501
pip install -U git+https://github.com/Pycord-Development/pycord.git@refs/pull/2501/merge
Main Client additions:
app_emojiscreate_emoji(name, image)fetch_emojis()- set
cache_app_emojis=TrueinClientto automatically fetch on startup. There are no events, so any updates from the developer dashboard will require another fetch.
- set
fetch_emoji(id)
New classAppEmoji
Everything STC.
does the on_disconnect event get fired if my bot gets auto-disconnected because of this
yes
keep in mind that you overwrite the slash commands sync with it
Is there an even listener or a method to override that would allow me to run some code EVERY time a command is run, including application bridge and prefix commands
there's a few
on_command, on_application_command, and on_bridge_command all fire BEFORE the command runs.
if you want after, then add _completion to the end
(note that on_bridge_command fires ALONGSIDE the other two listeners - make sure you're not doubling events)
I do the following command message.poll.duration for polls, but it only returns None and not the poll duration?
it's because duration is only used during the poll creation
you should use expiry instead
oh, ok thank you
Thanks
what's the limit of characters a bot can send in a message?
4k
keep in mind that a space is also a character
import discord
import asyncio
from discord.commands import option, Option
from discord.ext import commands
from datetime import datetime, timezone, timedelta
import re
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
bot = discord.Bot(intents=intents)
@bot.event
async def on_message_edit(before, after):
print("Author id " + str(after.author))
print("Message id " + str(after.id))
if after.author.id == 713484585874227220:
print(after.channel.id)
if after.channel.id == 935343526626078850:
await process_voyage_data(after)
Question. I've got the following code. My bot seems unable to sense message edits from anyone in one, specific channel... except for a bot (carlbot).
Every other channel it senses fine for everyone, and it has administrator, and I can clearly see it on the sidebar for that channel, so I'm confused on why it wouldn't be sensing the message for users in that channel.
how did you define the bot?
Edited. (sorry for left ping on)
Edit: Somehow it's started to work after I added a third print statement (for who knows what reason), thank you for the response though.
Would the use of bot permissions be like this?
from discord.ext.commands import bot_has_permissions
@bot_has_permissions(ban_members=True, kick_members=True, manage_roles=True)
@discord.slash_command(name="user", description="πβ― Displays a member's information")
async def user(self, ctx, user: Option(discord.Member, description="Information", required=True)):
command decorator is ALWAYS first, but yes
Sorry, second question. The bot is... I think it's only sensing messages that were created AFTER the bot was restarted, and only those messages if they were edited. Thoughts?
if the bot doesn't have all of these permissions, BotMissingPermissions will be raised - handle this in on_application_command_error
on_message_edit relies on cache, which is empty when the bot restarts
Okay, whats the best method to sense all messages edited?
you probably want on_raw_message_edit instead, but note you may have to fetch messages on request
I'll look into it. Thank you.
(please read the docs on that)
Hi there!
I'm having trouble pinpointing the error even with explanations from Chat GPT or rereading the code.
Could you explain it to me in a few words?
Traceback (most recent call last):
File "C:\Users\xxxx\Documents\GitHub\Bot.Dystopia\.venv\Lib\site-packages\discord\ui\modal.py", line 342, in dispatch
self.remove_modal(value, user_id)
File "C:\Users\xxxx\Documents\GitHub\Bot.Dystopia\.venv\Lib\site-packages\discord\ui\modal.py", line 322, in remove_modal
self._modals.pop((user_id, modal.custom_id))
KeyError: (000000000000000, 'c47212bb6f180e78220674cc91b4f160')
i doubt user_id is 00000000
keyerror means a key you're trying to access doesnt exist usually
what's the code causing this
(i.e. whatever modal you sent)
oh wait i didnt realise that thats in pycord code
slash command first oki doki
class SteamID64(discord.ui.Modal):
def __init__(self, user_whitelist, modal_title):
# Initialize the modal with a title and an input field for Steam ID 64
super().__init__(timeout=None, title=modal_title)
self.add_item(
discord.ui.InputText(
label="STEAM ID 64",
placeholder="00000000000000000",
style=discord.InputTextStyle.short,
max_length=25,
required=True
)
)
self.user_whitelist = user_whitelist
async def callback(self, interaction: discord.Interaction):
# Suppress HTTP exceptions when sending the initial response
try:
await interaction.response.send_message()
except discord.HTTPException:
pass
# Stop the voice service if it is currently active
await serviceVoice.voice_stop(self.user_whitelist.voice_state)
self.user_whitelist.steam_id = None
steam_api_key = settingAddon.steam_api_key
embed = interaction.message.embeds[0]
steam_id = self.children[0].value
pattern = r"^\d+$"
# Reset the thumbnail in the embed
embed.set_thumbnail(url=None)
# Validate if the input is a proper Steam ID 64
if not re.match(pattern, steam_id):
await self.handle_invalid_steam_id()
return
# Fetch user profile using the Steam API
user_profile = apiSteam.PlayerSummaries(steam_api_key, steam_id)
# If the profile is not found, update the embed fields accordingly
if not user_profile.is_found():
await self.handle_profile_not_found(embed, steam_id, interaction)
return
profil_visibility = user_profile.get_visibility()
# If the profile is not public, update the embed fields accordingly
if profil_visibility != 3 or user_profile.user_games is None:
await self.handle_private_profile(embed, steam_id, interaction)
return
# Set the user's avatar in the embed
embed.set_thumbnail(url=user_profile.get_avatar_full("avatarfull"))
steam_name = user_profile.get_steam_name()
creation_date = datetime.datetime.fromtimestamp(user_profile.get_creation_date()).strftime("%d/%m/%Y")
# If the user does not own the game DayZ, update the embed fields accordingly
if not user_profile.has_game(221100):
await self.handle_no_dayz_game(embed, steam_id, steam_name, creation_date, interaction)
return
# Get the user's playtime in DayZ and update the embed fields based on the playtime
time_dayz = user_profile.get_game_time(221100) / 60
if time_dayz < 50:
await self.handle_insufficient_playtime(embed, steam_id, steam_name, creation_date, time_dayz, interaction)
return
await self.handle_valid_steam_id(embed, steam_id, steam_name, creation_date, time_dayz, interaction)
# Update the user's whitelist with the Steam ID
self.user_whitelist.steam_id = steam_id
and when exactly does the error happen
that is GPT generated code if i ever saw it
no mostly just
# Very descriptive comment
code that does exactly whats described
for every block of code
This is code I made myself, but I asked chat gpt to redo the form of the code.
oh yeah, i just thought those two in particular was very funny
is it when you submit the modal
it's just a test, I'll redo my modal
wtv works, but again i'm asking about the error...
I feel more like I'm being judged on my code rather than getting help, it's a pleasure...
So...
then answer the question
i am TRYING to help, but literally can't if i don't know where it fails
Just a moment, I'm trying to apologize for using chat GPT to correct my error.
So, this error only appears when arriving at handle_valid_steam_id() after passing another handle.
For example:
handle_profile_not_found() -> Change steam ID -> handle_valid_steam_id() = Error
handle_valid_steam_id() -> Change steam ID -> handle_profile_not_found() = No error
async def handle_valid_steam_id(self, embed, steam_id, steam_name, creation_date, time_dayz, interaction):
# Update embed fields and play success sound for valid Steam ID
self.update_embed_fields(embed, steam_id, status="β
Trouvable", visibility="β
Public", steam_name=steam_name, creation_date=creation_date, dayz_time=f"β
{time_dayz:.0f} heures")
await interaction.message.edit(embed=embed)
if not self.user_whitelist.dev:
await serviceVoice.voice_say(self.user_whitelist.voice_state, "./addons/DSTP_Whitelist/sounds/step04_steamid/success.mp3")
else:
await serviceVoice.voice_say(self.user_whitelist.voice_state, "./addons/DSTP_Whitelist/sounds/soundBeep.mp3")
async def handle_no_dayz_game(self, embed, steam_id, steam_name, creation_date, interaction):
# Update embed fields and play error sound if user does not own DayZ
self.update_embed_fields(embed, steam_id, status="β
Trouvable", visibility="β
Public", steam_name=steam_name, creation_date=creation_date, dayz_time="β Non possΓ©dΓ©")
await interaction.message.edit(embed=embed)
if not self.user_whitelist.dev:
await serviceVoice.voice_say(self.user_whitelist.voice_state, "./addons/DSTP_Whitelist/sounds/step04_steamid/error_has_game.mp3")
else:
await serviceVoice.voice_say(self.user_whitelist.voice_state, "./addons/DSTP_Whitelist/sounds/soundBeep.mp3")
The problem is that, for the moment, the code remains exactly the same for both functions.
So I asked chat GPT to rewrite the code for me to check whether I'd made a mistake in the way I handled functions or the sending of audio messages.
could you perhaps try changing the first block py try: await interaction.response.send_message() except discord.HTTPException: passto a simple await interaction.response.defer()
and then, replace all interaction.message.edit to just interaction.edit
That's chat gpt I don't use that. Forget that part of the code, it's just AI bullshit.
I'll film you how it works for a moment.
This problem also occurs when I use voice messages. If I play a short beep I don't have the problem.
So it's probably related to the audio. What I don't understand is that I turn it off at the beginning to avoid any problems.
ohhhhhhhhhhhhhhhhhh
can you show how the modal is sent in the first place?
(also to be clear, you can completely ignore the error with no side-effects, but it would be good to deal with)
I didn't quite understand, it's only sent by the button.
right, so can you show the code used there
class SteamID(discord.ui.Button):
def __init__(self, user_whitelist):
super().__init__(
label="SteamID 64",
style=discord.ButtonStyle.blurple,
custom_id="steamID64Button"
)
self.user_whitelist = user_whitelist
self.modal = modalSteamID.SteamID64(self.user_whitelist, "SteamID 64")
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_modal(self.modal)
await self.modal.wait()
it's because you're reusing the same modal object
instead, define modal inside callback
(in retrospect this is a silly error, but it's how you would get rid of it)
Let's see if it works.

Great, it works!
I'm still struggling with these little details!
I tested the defer and it also works perfectly, I used it for commands but I didn't know it existed for modals.
I'd go to bed less stupid.
Thanks for your help
allgood
Thanks! When it will be released?
On master it shouldn't be toooo long? But 2.7 idk when it'll be out
Doesn't matter their cog list doesn't load the init file
Aaaaand discord chat only now updated again
Fkin shite
:3
How do I override on_error? Like, for every command in a bot. I have a custom Exception type which I'd like the bot to print to the console and ignore.
there's global on_command_error for prefix and on_application_command_error for slash
Cool beans! What code do I need to write in the main file to override it?
if you've subclassed bot, you can just define it inside that
otherwise, use the @bot.event decorator
Ah. I have not subclassed bot. Is it as simple as @bot.event(on_application_command_error)? And do I only need to speciy it once?
no brackets, you name the function
and that will cover every error inside an application command
Just individual commands, though? So I'd need to subclass bot if I wanted to write a one-and-done for all of them?
i think you misunderstand... as i've described, @bot.error will override the default event handler
...Oh! Could you show me a rudimentary example?
Lemme read
do those automatic reconnects from discord fire the on_ready event
maybe we need a dedicated error handling example
Oh! This is just what I need! Thank you, @errant trout!
allgood
it's possible
so it doesn't always happen?
it generally shouldn't, but there are some cases where it has
i think it's higher chance after major disconnects, but discord's own behavior on the event is a bit finicky
is that for the on_resumed event
you could prevent it from triggering multiple times by setting once=True
i actually need it to trigger multiple times
resumed and ready are indeed different, where resumed is the one that's meant to fire multiple times, but it is also possible for ready
on_resumed i think would be more reliable?
so when a bot receives those reconnect things and reconnects, the on_resumed event is the one that always fires, right?
it should, yes. We have very little processing related to it, but discord describes it as such
Used to replay missed events when a disconnected client resumes.
where does the "Used to replay missed events when a disconnected client resumes." description come from
why is it called "replaying"
I may be a doofus.
I made a custom Exception (superclass Exception) which the new method doesn't seem to be catching. It just says this:
discord.errors.ApplicationCommandInvokeError
class PreconditionError(Exception):
def __init__(self, message):
super().__init__(message)
async def assertOrSay(cond, msg, ctx, ephemeral=False):
if not cond:
await ctx.respond(msg, ephemeral=ephemeral)
raise PreconditionError(msg)
``````py
# The objective
@bot.event
async def on_application_command_error(
ctx: discord.ApplicationContext, error: Exception
):
if isinstance(error, PreconditionError):
pass
else:
raise error
ok so, funny quirk about that one
if it's of type ApplicationCommandInvokeError, re-run the error handler with error.original
@bot.event
async def on_application_command_error(
ctx: discord.ApplicationContext, error: Exception
): # vvvvvvvvv This worked!
if isinstance(error.original, PreconditionError):
pass
else:
raise error
Thank you!
allgood
though uh, note that that will break for other exceptions
because original only exists on ApplicationCommandInvokeError
(and CommandInvokeError i guess)
for modals is there a way i can choose a custom character limit or no?
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, parent, timeout. Methods cls View.from_message, def add_i...
appreciate it
class TeamNameModal(discord.ui.Modal):
def __init__(self, *args, **kwargs):
super().__init__(title="Enter Team Name", *args, **kwargs)
self.opponent_name = None
self.add_item(discord.ui.InputText(label="Team Name", placeholder="Type the name of your team here"))
async def callback(self, interaction: discord.Interaction):
self.opponent_name = self.children[0].value
await interaction.response.send_message(f"Match accepted, you are now in the second team: `{self.opponent_name}`",
ephemeral=True, delete_after=60)
self.stop()
I'm making a modal that the idea is to return the opponent_name
await interaction.response.send_modal(modal)
await modal.wait()
opponent_name = modal.opponent_name
If I do not return a text message in the modal, the popup does not close correctly, but if I set it, it closes correctly. Is this the only way to close the popup?
Good morning by the way!

Modal is a class not an instance so it will not overwrite it in the self
You can try to pass it as a class variable so not inside the init but upper
class⦠:
oppenent_name = None
Def init () :
I understand that your idea would be to do something similar to this, right?
class TeamNameModal(discord.ui.Modal):
opponent_name = None
def __init__(self, *args, **kwargs):
super().__init__(title="Enter Team Name", *args, **kwargs)
self.add_item(discord.ui.InputText(label="Team Name", placeholder="Type the name of your team here"))
async def callback(self, interaction: discord.Interaction):
TeamNameModal.opponent_name = self.children[0].value
self.stop()
Yep something like so
I still have the same problem :/
There is something about the modal that I am not understanding
Show me how you get it
You should do β¦ = TeamModal.opponent_name
async def accept_match(self, interaction: discord.Interaction):
modal = TeamNameModal()
await interaction.response.send_modal(modal)
await modal.wait()
# ----------------- CODE -----------
return modal.opponent_name
Here you are using the instance to retrieve the opponent name and not the class
Because modal is the class initialized, you should do return TeamNameModal.opponent_name
Without initializing the class
async def accept_match(self, interaction: discord.Interaction):
modal = TeamNameModal()
await interaction.response.send_modal(modal)
await modal.wait()
# ----------------- CODE -----------
return TeamNameModal.opponent_name
Yeah like so since itβs a class variable
Did it work @valid panther ?
yes
In the end I solved it with await interaction.response.defer()
Defer has nothing to do with class variable as long as I know
But if it works it works

is there an event that listens for whenever an error is raised anywhere in the bot
on_error
.rtfm on_error
discord.on_error
discord.Bot.on_error
discord.Client.on_error
discord.ui.View.on_error
discord.ui.Modal.on_error
discord.AutoShardedBot.on_error
discord.ext.bridge.Bot.on_error
discord.ext.commands.Bot.on_error
discord.AutoShardedClient.on_error
discord.ext.pages.Paginator.on_error
discord.ext.bridge.AutoShardedBot.on_error
discord.ext.commands.AutoShardedBot.on_error
on_error is ONLY for events
isnt that enough? command_error and events
you could add some try and except to other stuff
well, my point being that they asked for an event that's raised for any error on the bot - such an event doesn't exist
so you really have to use try and except?
how do i send a modal?
Here's the modal dialogs example.
@weary meteor
ah, why is that not under the views directory π
because its not at a view
https://guide.pycord.dev/category/ui-components @weary meteor
use this instead
hey i'm trying to create a "modlogs" command say a user banned through but the ban was initiated through another bot is a there a way i can still find out who the user was?
events
Short answer be like
short answer be
why waste time say lot word when few word do trick
is it normal to be able to call that has the has_role check even if the user doesn't have the role ?
show your code
and ideally, you dont use these decorators for slash commands
just set up permissions inside your server settings
also has the added upside of not being visible to anyone else
and if you wanna tie it to a specific permission, there's a decorator specifically for that
@commands.slash_command(name="set_color", description="Set your color.", guild_ids=[1265373509455057006])
@commands.has_role(rolename)
@discord.option(name="color", description="The color you want to set.", type=discord.Color)
async def set_color(self, ctx, color: discord.Color):
guild = ctx.guild
member = ctx.author
role = discord.utils.get(guild.roles)
await ctx.send(f"Setting color for {member.display_name} to {color}")
self.bot.logger.debug(f"Setting color for {member.display_name} to {color}")
Ignoring exception in command set_color:
Traceback (most recent call last):
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/commands/core.py", line 432, in invoke
await self.prepare(ctx)
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/commands/core.py", line 353, in prepare
if not await self.can_run(ctx):
^^^^^^^^^^^^^^^^^^^^^^^
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/commands/core.py", line 460, in can_run
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/utils.py", line 705, in async_all
for elem in gen:
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/commands/core.py", line 460, in <genexpr>
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^
File "/app/.cache/pypoetry/virtualenvs/zorsbot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/ext/commands/core.py", line 1968, in predicate
raise MissingRole(item)
discord.ext.commands.errors.MissingRole: Role 'Les HabituΓ©s' is required to run this command.
well i mean it works exactly as it should
can't I make it so the 'non role' user can't even try/see to run the command ?
.
.
thing is I don't want it to be tied to a specific permission but to a role, the members of this role can do the command the others can't see it ? or at least maybe try to catch the error and show 'you have to be {rolename} to do that. has permission would not make me able to do so
:)
didn't knew you could do that
server settings > integrations
okay thank you very much for your help , also can I catch the error inside the function to send a message like admin should check up on integration permission, you shouldn't be able to see this ? feels off to have the bot just sending 'application doesn't respond'
you can write a global error handler for the exception that the role check throws here
@discord.Cogs.listener()
async def on_application_command_error(self, ctx, error):
if isinstance(error, discord.MissingRole):
await ctx.respond..
thank you !
can someone help me make my bot ban users not in the server?
if member:
await interaction.guild.ban(member, reason=f"...")
banned_users.append(user_id)
else:
user = await interaction.client.fetch_user(user_id)
await interaction.guild.ban(discord.Object(id=user), reason=f"...")
failed_bans.append(user_id)
you don't need discord.Object
you already fetched the user
(or if you don't want to fetch, just do discord.Object(user_id))
also in the first part you can just do member.ban, assuming you got them in the correct guild
thanks
like this?
user = await interaction.client.fetch_user(user_id)
await interaction.guild.ban(discord.Object(user), reason=f"...")
no...
you do one or the other - EITHER fetch user and do ban(user), or DON'T fetch the user and do ban(discord.Object(user_id))
ohhh
lemme try that now
ty
Good afternoon, sorry for the inconvenience.
I'm making an embed, with an image
base64_image = img_generator.generate_image()
embed = discord.Embed(title="TEST", color=settings.embed_color)
embed.set_image(url=f"data:image/png;base64,{base64_image}")
await ctx.respond(embed=embed)
(<class 'discord.errors.ApplicationCommandInvokeError'>, ApplicationCommandInvokeError('Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body\nIn data.embeds.0.image.url: Must be 2048 or fewer in length. Not a well formed URL.'), <traceback object at 0x0000018CF1CF0200>)
the set_image does not accept base64 ?
"url"
lol
what you put there isn't a url
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
pass a url or do it like above.
instead of passing it as base64, create the image and then pass it the path to the file
I understand
is it possible to clear a discord bot's message cache
Yes
Put that to []
i don't see "_connection" as a bot attribute
In docs? Because it's not documented
That goes for any var starting with _
(Probably)
i see
i get AttributeError: 'NoneType' object has no attribute 'clear' from this
Then you don't have a message cache
that is why you dont disable the cache
lol
you also cannot use get_x anymore
Can I get some eyes on my code please, I'm building another version of a previous bot I created, however for the life of me when I run the bot I can't get ANY slash commands to appear? I've gone through the code line by line vs my old bot and I just don't seem to be able to spot why the slashcommands aren't showing π¦
I've been looking at it for days now and accepted defeat, need some help - obviously I'm using py-cord otherwise I wouldn't be here π
did you try restarting discord?
Had several PC reboots since then π
then show your code
It's not a "keep restarting" your bot in debug error
its just never started, period.
so the slash commands are within a cog
I can confirm the cog is loaded via the log file
..what never started
sorry bad terminology, the bot starts however the slashcommand in question isn't recognised.
import logging
from utils.logger import CustomLogger
import discord
from discord import option
from discord.ext import commands
from discord.utils import basic_autocomplete
customLogger = CustomLogger(__name__, logging.DEBUG)
log = customLogger.get_logger()
class WarYes(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot.user
# Set slashcommand group and sub groups
grp = discord.SlashCommandGroup("waryes", "This is a collection of waryes commands")
unitgrp = grp.create_subgroup("units", "A list of unit commands")
# mapgrp = grp.create_subgroup("maps", "A list of map commands")
@staticmethod
def unitAutocomplete(ctx: discord.AutocompleteContext):
try:
with open('./resources/units.json') as f:
data = json.load(f)
result = next((unit['name'] for unit in data['units'] if ctx.value.upper() in unit['name']), None)
return result
except Exception as e:
log.error(f"{e}")
@unitgrp.command(description="Returns an embed with high level unit statistics")
@option("unit", description="You must use the Eugen stated unit name",
autocomplete=unitAutocomplete)
@commands.has_any_role('MEMBER', 'WARYES DEVELOPER')
async def getunit(self, ctx: discord.ApplicationContext,
unit: str):
unitname = unit.split(':')[0].rstrip()
print(unitname)
ctx.respond(f'Selected {unitname}')
def setup(bot):
bot.add_cog(WarYes(bot))
log.info("Cog loaded")
that is the code from my cog
happy to share anything else
alright, show your main file as well
import os
import discord
import dotenv
from commands.replays import ReplayFile
from utils.logger import CustomLogger
# Load Logger
customLogger = CustomLogger(__name__, logging.DEBUG)
log = customLogger.get_logger()
# Load Environment Variables
dotenv.load_dotenv()
# Bot Cogs List
cogs_list = ['waryes']
class YesManBot(discord.Bot):
def __init__(self):
self.uptime = discord.utils.utcnow()
allowed_mentions = discord.AllowedMentions(roles=False, everyone=False, users=True)
intents = self.set_up_intents()
super().__init__(
description="I am a bot written by .lynchie for the WarYes community discord.",
pm_help=None,
help_attrs=dict(hidden=True),
chunk_guilds_at_startup=False,
heartbeat_timeout=150.0,
allowed_mentions=allowed_mentions,
intents=intents,
enable_debug_events=True,
)
@staticmethod
def set_up_intents():
return discord.Intents(
guilds=True,
members=False,
bans=True,
emojis=True,
voice_states=True,
messages=True,
reactions=True,
message_content=True,
)
@staticmethod
async def handle_exception(message, exception):
log.exception(f'{message} %s', exception)
@staticmethod
async def setup_hook() -> None:
try:
for cog in cogs_list:
bot.load_extension(f'cogs.{cog}')
return
except Exception as e:
log.exception('Failed to load extension: %s', e)
async def on_ready(self):
log.info('Ready: %s (ID: %s)', self.user, self.user.id)
await self.setup_hook()
async def on_message(self, message: discord.Message) -> None:
if message.channel.name == 'dev_bots':
if message.author.bot:
return
try:
if message.attachments:
for attachment in message.attachments:
if attachment.filename.endswith('.rpl3'):
filecontent = await attachment.read()
replay = ReplayFile(attachment.filename, filecontent, message)
await message.channel.send(embed=replay.getembed())
except Exception as e:
log.exception('Failed to process replay: %s', e)
bot = YesManBot()
bot.run(os.getenv(str('DEV_BOT_TOKEN')))
sidenote, @commands.has_any_role('MEMBER', 'WARYES DEVELOPER') i dont recommend this, its better to set this up via discord's permission settings for commands
async def setup_hook() -> None:
try:
for cog in cogs_list:
bot.load_extension(f'cogs.{cog}')
return
except Exception as e:
log.exception('Failed to load extension: %s', e)
Nope. Cogs have to be loaded before the bot starts, and ive never heard of setup_hook
shit just realised, could it be the intents?
it's just me putting the code loading into a function
just do bot.load_extensions("cogs") right before bot.run
and I do an await in on_ready to run set_hooks
yea but you are loading the cogs too late
that is too late
ah ok
Copy that, will change now
of course On_Ready is the END of the process of loading
it works for prefix commands because they essentially just use on_message, but slash commands are only synced once during startup, and if there's no slash command currently loaded, it never syncs to discord
slash commands get synced at the on_connect event
which appens during startup
:3
np
To be honest my startup process is different to my v1, I never bothered with putting it on "on_ready" I originally did just a function
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
dotenv.load_dotenv()
cogs_list = ['maintenance', 'waryes', 'warno', 'match']
for cog in cogs_list:
bot.load_extension(f'cogs.{cog}')
return bot
logger = setup_logging()
bot = setup_bot()```
and then bot.run
never occured to me the issue was that
Lesson learn't about how the cogs/extensions load though.
my startup is
bot.load_extensions("cogs")
bot.run(config.token)
Every day is a school day
if you do "cogs" will it just load all the cogs in the directory?
yes
im not sure how it works if you have foreign / non-cog files, but i dont have that
can also load them in subfolders with that
Thank you once again, been a stumbling block for a while that has.
should of came here earlier, just figured I'd try and work it out myself.
Im at 30 lines
because of the twitch bot
yea well that doesnt count lol
i forgor, does python have syntax to do like
object.do_this()
.and_this()
.and_this()
.and_this()
the method has to return self
to allow chained calls
yeah. People can do that with embed creation
Are role mentions disabled by default for followup messages?
yes
why?
uhm I just did lol
but user mentions do work
using allowed_mentions=discord.AllowedMentions.all(), I was pinged
itβs just how webhooks work idk
uh, for what i know, webhooks do support everyone tho
probably so you canβt ping everyone or something accidentally
i've witnessed a few servers being taken over and spammed by webhooks, and im p sure @ everyone works
but yea role mentions are off by default i've noticed that too
off by default but it's possible to turn them on using allowed_mentions?
At least that's what worked for me...
yea
ok, because squid said it doesn't work xD
yes
initial reply was interaction.edit though...
and then a interaction.followup.send
I was referring to the follow up not being able to be in a different ephemeral state than the original reply. idk why I said that. Probably because I like just woke up
oh, ok. Thx
lol
Anyone know why these suddenly stopped working for me?
server = await bot.fetch_guild(discord_server_id)
members = server.members # now returns empty list
category = discord.utils.get(server.categories, name="my-category") # now returns None
what intents does ur bot has
bot = Bot(command_prefix="!", intents=discord.Intents.all())
this works: members = await server.fetch_members().flatten()
but I couldn't find any alternative to find categories
its not in the cache thats strange
using the id
you can fetch it
using which method?
self.bot.fetch_channel(id)
why are you fetching a guild, especially without first trying to get it from cache?
channel is textchannel, voice channel and categories
(with also the other things forum...)
and you should also very much avoid this
I was using members but it suddently started returning an empty list.
why ?
in short:
why do API request when cache do trick
because cache does not ?
it should
.
that is the problem that needs to be investigated
did you change anything since it last worked properly
I was having other issues too, I had to re-add my app to the channel. I was thinking maybe Discord rolled out some changes to app permisions
why?
Yesterday I suddenly couldn't connect to my server at all
wdym "connect to your server"
server = await bot.fetch_guild(discord_server_id)
This line would return None if I remember correctly
if you have a test server, did it happen for that too?
I don't have a test server
yea, but only after I re-added to my server using a new link. And I noticed the creation process was a bit different from last time
didnt really change in the past years for all i remember
are you sure the bot is installed on your server and not on your account as a user app lol
ok it is possible I don't remember that well
definitely sure
can you print bot.guilds
hmm ok it seems like that works and I can run members on the guild from there fine
then get guild should work fine as well
yes seems to work
that works partially, those certain properties of the guild won't be there
members, member count, etc
no idea then lol
but if get works, use that
you should always use get if possible
this never worked
Yea lookimg again I actually was using that instead of fetch when the second two lines stopped working...
Why is guild.name being None sometimes in on_guild_remove ?
how can i get a bot to be able to detect presence updates without caching ppls activities?
Use the events?..
if im importing functions from a different file in my cog and update that file, is it possible to reload my cog including that file?
You mean if you add a new import to your cog file?
yeah that would be one case, or if im updating one of the imports
Guys quick help why this name=f"{ctx.author.name}-zestaw" gives me for example @coarse yoke instead of the actual ping @royal spindle
ctx.author.mention
screenshot
but sometimes it gaves me just the id instead of the ping
show your code and what you see in discord
embed = discord.Embed( title="abc", description=f"Results for {ctx.author.mention}", color=discord.Color.green() )
that's normal
pings in embeds don't fetch the user
so if your discord doesn't have that user in cache it won't show the ping properly
the only workaround is to ping the user in the message content
Is it possible to make it show the nickname without ping? like "results for Kaygoo"
ctx.author.display_name
cuz ik discord caches that stuff automatically
how do i turn it off
turn what off
discord caching user activities
i saw that stuff in the objgraph.show_growth() output
there is no fine-tuned cache
Dumb question - how can you use once for cog listeners?
My listeners are done with @commands.Cog.listener(), and would want my on_ready method to just fire once.
isnt it just once=True ?
Ah, yeah it is https://github.com/Pycord-Development/pycord/pull/2403 -- it wasn't autocompleting in pycharm
kwargs can't be suggested automatically
No, but I wasn't seeing it at first even when trying it. It just needed a little persuasion is all
why its giving None?
for command in self.bot.walk_application_commands():
print(command.id, command.qualified_name, command.description)
output:
None setup antilink the antilink Logs
None setup autorole The autorole system
None setup feedback-costumer the feedback system
None setup giveaway the giveaway system
None setup logs every thing for you that related to logs
None setup ticket Ticket menu
None setup verify_v2 the verify v2 system
None setup welcome-v2 sets up the welcome message
bot.commands returns a list with all the loaded commands
there more commands and half id and half None
use this
for everything or to make an if?
everything
ok
the problem is that you're trying to print the IDs of subcommands
and subcommands arent commands by themselves
so qualified_id will print the ID of the parent command as described in its documentation
ok got it
on a low level, subcommands are considered options for the parent command
in on_member_remove why am i getting member.guild None sometimes and sometimes member.guild.me as None
any pattern as to when you get None for both?
idk i am having this problem at multiple places in multiple events
another event being on_wbhooks_update i get the channel and from the channel i get channel.guild and use the guild.audit_logs iterator and start getting Unkown guild
you can remind me how i can mention a command? something like that <name:/id>?
command.mention
but yea its something like that if .mention doesnt work
ok
It's
</qualified name:id>
Traceback (most recent call last):
File "C:\Users\iyadf\Downloads\mekov1\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\iyadf\Downloads\mekov1\PrefixCommands\Logging\LoggingEvents\MemberLogs\UserLeft.py", line 18, in on_member_remove
if not guild.me.guild_permissions.view_audit_log:
^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'guild_permissions'
this is the traceback
thanks
gives the bot's member object in a guild
is it maybe because these events fire in the time when there is a resume and py-cord doesnt get stuff from the cache properly or something ?
wdym where there is a resume
INFO:discord.shard:Got a request to RESUME the websocket at Shard ID 2.
the member object of the bot in that guild
because its groups
so you need to itinerate through it using for example subcommand for command.subcommands and then do subcommand.id
luma, we already solved this
i have seen nothing about the subcommand.id maybe that's mb ;)
maybe i will double check
cos if they dont that a new thing that i will learn
ok so it work like so
</name of subcommand:id of group>
good to know thanks
wat
i mean it will still all refere to the same thing
i might have not understand ur first sentence
if you prefere all of those are considered as options of the first one for what i understand
Why do the docs on https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.on_application_command_error say that a DiscordException is returned, even though it is a https://docs.pycord.dev/en/stable/api/exceptions.html#discord.ApplicationCommandError in all of my tests?
how can I get a role id from its str value ?
what do you mean?
something like roleid = ctx.guild.get_role_id_from_name("Admin role")
first of all, why do you only have the name?
cause and error returned it to me ^^"
show the code then
I'm sorry you must hate me sm rn ^^"
@discord.Cog.listener()
async def on_application_command_error(self, ctx, error):
message_beginning = f"An error occurred while executing the command {ctx.command}."
match type(error):
case commands.MissingRole:
rolename = error.missing_role
role_id = ctx.guild.???????
await ctx.respond(f"You don't have the required role <@{role_id}> to execute this command and "
f"shouldn't be able to see it. Please contact an admin.")
self.bot.logger.error(
f"{message_beginning} - MissingRole: {error} for {ctx.author}, that shouldn't happen check the "
f"integration settings and make sure this command is only visible to the right role.")
case _:
await ctx.respond("An error occurred while executing the command.Please contact an admin.")
self.bot.logger.error(f"{message_beginning} - Error: {type(error)}")
hoooo the union ! so I should use missing_role[1] !
missing_role returns the str of the role not the id
if you have only the name u can use the discord.utils.get
you're right I might mention people that would rather sleep ^^
But I'm still curious if there is a way for me to mention the role from it's name
you can disable ping but still mention in the chat if you want
hoooo can you please give me a link to the doc ? or explain a little more ?
Thats because you pass the role by name in your has_role decorator
discord.AllowedMentions
discord.AllowedMentions.all
discord.AllowedMentions.everyone
discord.AllowedMentions.none
discord.AllowedMentions.replied_user
discord.AllowedMentions.roles
discord.AllowedMentions.users
discord.Bot.allowed_mentions
discord.Client.allowed_mentions
discord.mentions.AllowedMentions
discord.ext.commands.Bot.allowed_mentions
using that
You shouldn't use has_role() anyway unless you use prefix commands only
I see thank you
okay !
I was able to did it it works perfectly thank you all
hi
throwing error
missing perms
I have all the intents and role hierachy set right
when i timeout it keeps saying missing permissinos
and im owner
and im not timeouting myself
maybe the bot doesn't have perms to do wtv?
Check if the bot has the explicit permission βtimeout membersβ
I fixed it
so apparently I can't timeout administrators...

but hey!
new problem to solve
get this error:
Error: 'str' object has no attribute 'to_dict'
code?
newembed.add_field(name = "Server ID", value = f"{serverid}")
newembed.add_field(name = "Creation date", value = f"{createdate}")
newembed.add_field(name = "Owner", value = f"{owner}")
newembed.add_field(name = "Member Count", value = f"{membercount}")
newembed.add_field(name = "Channel Count", value = f"{channelcount}")
traceback?
no problem
i'm assuming you made a custom error handler?
can you remove it or have it print out the traceback
one sec
tb = "".join(
traceback.format_exception(type(error), error, error.__traceback__)
)
make sure you add import traceback
running now
not printing
ughh
@edgy nest
I'm going to delte custom error handling
well you need to add a print
I did
Β―_(γ)_/Β―
now it's just straight up not giving me an error
@bot.command()
async def serverinfo(ctx):
membercount = discord.Guild.member_count
channelcount = discord.Guild.channels
createdate = discord.Guild.created_at
owner = discord.Guild.owner
rolenum = discord.Guild.roles
icon = discord.Guild.icon
serverid = ctx.guild.id
newembed = discord.Embed()
newembed.color = 880808
newembed.timestamp = datetime.datetime.now()
newembed._thumbnail = icon
newembed.add_field(name = "Server ID", value = f"{serverid}")
newembed.add_field(name = "Creation date", value = f"{createdate}")
newembed.add_field(name = "Owner", value = f"{owner}")
newembed.add_field(name = "Member Count", value = f"{membercount}")
newembed.add_field(name = "Channel Count", value = f"{channelcount}")
await ctx.send(embed = newembed)
oh goodness
yeah
alright well this is your problem line
newembed._thumbnail = icon
embed has set_thumbnail
omg
for all of them?
yeah
but you can have it send the traceback in discord
how to do that
*or terminal
i did await ctx.send but it don't send tracepback with it
just take that tb variable and send it in a message
ok lemme try
ok we r about to see
YES YES YES
Traceback (most recent call last):
File "c:\Users\NishanPC\Desktop\vscodeprojects\pythonbot2\main.py", line 158, in serverinfo
membercount = ctx.Guild.member_count
^^^^^^^^^
AttributeError: 'Context' object has no attribute 'Guild'. Did you mean: 'guild'?
ik
aight we about to see
Traceback (most recent call last):
File "c:\Users\NishanPC\Desktop\vscodeprojects\pythonbot2\main.py", line 170, in serverinfo
newembed.set_thumbnail = icon
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Embed' object attribute 'set_thumbnail' is read-only
tf
so how can I set the thumbnail
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
.. versionchanged:: 1.4
Passing `None` removes the thumbnail.
Parameters
----------
url: :class:`str`
The source URL for the thumbnail. Only HTTP(S) is supported.```
set_thumbnail(url=...)
do note though that icon can be None, but if it's an asset you will need to use icon.url
your embed.set_thumbnail
mb i just saw on the docs
same thing as your add_fields
it has to be a url huh
yes
how can i get pfp url
user.avatar.url
i mean for server
discord.Guild.icon
discord.Guild.explicit_content_filter
discord.Guild.verification_level
discord.PartialInviteGuild.icon
discord.PartialWebhookGuild.icon
discord.Guild.edit_welcome_screen
discord.Guild.default_notifications
discord.Guild.premium_subscription_count
discord.Guild.approximate_member_count
discord.Guild.approximate_presence_count
discord.PartialInviteGuild.verification_level
which you can then use icon.url with since it's an Asset
running rn
Traceback (most recent call last):
File "c:\Users\NishanPC\Desktop\vscodeprojects\pythonbot2\main.py", line 169, in serverinfo
newembed.set_thumbnail = ctx.guild.icon
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Embed' object attribute 'set_thumbnail' is read-only
it's a method...
that's not how subcommands work
Oki sorry :3
i think it can be because the cache is not updated at this time or something else
if your bot doesn't have it's own commands cached I'd be worried
what happens if you just get the command group
after reload all cog sometime the application_commands are None
and depends sometime it works and other time it return Noen
there's any example of how to use SKU's? I want when a user buy something the bot send a DM to him with "hi"
can I use HTML as a formatting option for sending messages from my bot?
nope :/
This question confuses me- discord supports markdown
yeah but html is more complete
awesome thanks
can you give an example
I am guessing you're making some kind of economy bot? Or... ?
You can make a /buy command that sees what user executes the command in which the bot then fetches the user and then user.send('s them a message. Hi')
I don't understand what you mean with SKU tho- stock keeping unit but I don't know why youd need it if you can just directly dm the user by having them execute the command.
mean this
Ah- so actual buying using apps
yep
Uff ok hold on gotta fill myself in-
Ah- ok so apparently you can introduce webhook logic by adding a webhook to your application via the discord dev portal
But then you'll also need to handle the webhook events so you should create a webserver like fladk
*flask
So pretty much discord makes a webhook requests once somebody buys something on your SKU- which you can then handle on your flask web server to then trigger a bot event to dm the user
user purchase information should be passed trough the webhook
(I am not certain of this in any way tho as I have not tested any of this myself)
@deft kestrel
omg, where? here?
I think so im not sure scrolling trough docs and guides rn but having a hard time-
pretty sure that'd break your bot
well if it actually switches everything over then yes π
I'm pretty sure too π
you can fetch the bot's current skus
I'm not sure if that's the only way or if there's an event, but if nothing else works, you can fetch them like once a minute and check for changes
Best I could find
This section outlines the different types of events listened by Client. There are 3 ways to register an event, the first way is through the use of Client.event(). The second way is through subclass...
But I don't think that does anything
Towards your needs
oh yea entitlements
I'm not sure if SKUs and entitlements are the same or how they're connected, that's beyond what I know lol
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 ...
do objects still get saved in memory when a discord bot disconnects before resuming a session? (thinking of on_resume)
any examples?
no
check the on_entitlement_... events in docs
SKU is the item to purchase, an entitlement is the record that you actually own it
an entitlement grants access to an sku
confusing+
Hi! Is it possible to use emojis in the strings returned for the autocomplete?
no
Ok. Thanks for the on reply!
just industry standards
"stock keeping unit" is a dumb af name
industry standard
is it normal for these kinds of objects to linger in memory
yeah, because member cache
how about things like timerhandle, ordereddict, list, etc
(i'm using asyncpg as well)
probably parts of cache
members have role lists attached to them
channels have permissions
this and that
i see
but then, why doesn't the number of lists at least equal the number of members?
because there's other lists that are snowflakes like guilds and channels
Β―_(γ)_/Β―
what i mean is, if members have role lists attached to them, why is the # of lists less than # of members
maybe they just don't have roles
so if they don't have roles they just don't have a role list attached to them at all, rather than a []?
is memory an issue for you?
yes
i'm noticing that my memory usage is increasing gradually
by an average of about 2-3 mb an hour
according to pm2
that's like normal
how
and the thing is, my bot's running on an ec2 free tier with 1gb ram, and the thing goes offline about once per week as a result of the memory growth
it's being used by 7.5k users, not including bots
oh so it doesnt go down. I see
it doesn't
at that point, it, as well as a the server it runs on, just crashes
easiest solution is disabling member cache
can't
my bot needs to be able to access members
and fetching them all the time isn't exactly an option
when, how often, what purpose
for example, it has a ban command
i tried running it with member cache disabled
didn't work
if it's a slash command you should recieve the full member object as a parameter
if not you can query/fetch members by name
it is
so it should provide a full member (or at least a user) object for your parameter
if not a member, you can use guild.ban with a discord.Object
and i assume i disable member cache using discord.membercacheflags.none()?
yup
you can also disable guild chunking too
fetches member lists
though if you're running a moderation bot, and you have logging cache is probably better off enabled
yes that's waht i'm doing
if i try to run that slash command with member cache completely off, i just get a "this application did not respond" with no error
your error logging is broken then
oh wait i do get an error
it's Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
The line above that should tell you what object is None that you're trying to get an ID from
I'm not using the delete() method for any messages yet I'm getting the error below on v2.5.1. I do use the delete_after argument when sending some messages through. Is this a known bug or do I need to handle it somehow?
2024-07-28 02:19:25,891:ERROR:asyncio: Task exception was never retrieved
future: <Task finished name='Task-2540795' coro=<Webhook.send.<locals>.delete() done, defined at /usr/local/lib/python3.10/site-packages/discord/webhook/async_.py:1799> exception=NotFound('404 Not Found (error code: 10008): Unknown Message')>
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1801, in delete
await msg.delete()
File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 967, in delete
await self._state._webhook.delete_message(self.id, thread_id=thread_id)
File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 2030, in delete_message
await adapter.delete_webhook_message(
File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
how does one tag a category
not possible
why are you not on 2.6?
The way importing and creating slash commands in cogs has changed or is it still the same way?
Having a bot running with py-cord version 2.4.1 that uses the import from discord.commands import slash_command but the example https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_cog.py shows how to import it with from discord.ext import commands and using it with @commands.slash_command()
Dont see in changelog that this behaiviour has changed
just use @discord.slash_command()
behavior didnt change, there just many ways to import the same thing in pycord
Well you- can / can't it's really weird if you <#CategoryID> it does resolve the category name with a # Infront but it doesn't actually mention it so it's plain text.
#1017401122031419463 β #1017401122031419463
apparently it's guild.owner that's none, but why?
but the members themselves are not none
You mean ones passed via options?
member1 is ctx.author, member2 is the one passed
I mean yea, you were already told member objects passed via options work even without cache of course
but guild.member just isn't cached and not explicitly passed either
disabling (member) cache is simply a pain you should try to avoid
and you said you were running on a free vps with 1GB right?
maybe with 7k+ members you should consider renting an actual VPS with more ram instead of trying to get around it with brute force
oracle has a free vps tier with like 4GB or more of ram
but you need a credit card to sign up
what is the listener to catch exceptions in views / other interactions?
on_error dosen't seem to do the job
dont ever use Bot.on_error
https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.View.on_error found this for views tho
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, parent, timeout. Methods cls View.from_message, def add_i...
why?
oooh thanks
feels wierd imo but fair enough
because you are overwriting pycord's entire error handling if you do
so you call super?
just dont use it, there's no point
I'm using bot.walk_application_commands() iterator that iterates over all bot commands. How can I differenciate between an actual command and command group? e.g I have math group and 2 commands in it: add and subtract. Iterator will walk through 3 commands: math add, math subtract and math
so I have a command for timing someone out
The command is ?timeout (days int) (hours int) (minutes) username
so a command could look like
?timeout 5 0 0 billybobjoe
but what happens is
If I don't set the timeout to some obscenely large value
it won't timeout the user
so if I set it for like 20 mins
nothing happens
try:
target = member
duration = datetime.datetime.now()
time_delta = timedelta(days = days, hours = hours, minutes = minutes)
timeout_until = duration + time_delta
timeout_until = timeout_until.
replace(tzinfo=datetime.timezone.utc)
print(str(timeout_until))
await target.timeout(timeout_until, reason = f"Ordered by {ctx.author}")
await ctx.send(f"βοΈ {target} was timed out for {days} days, {hours} hours, {minutes}, minutes")
except Exception as e:
await ctx.send(f"Error: {e}")
what's the method name?
no clue
.rtfm fetch_entitlements
Target not found, try again and make sure to check your spelling.
Well its called that. Bot method.
You also got events for creation, update and deletion.
And you also receive the entitlements data on each interaction.
how to "consume" a SKU? because if i want buy much products in the store like 2/3 subscriptions what i can do?
A consumable is like buying coins. You bought 100 coins and you get it in your profile
Or an item you can use

isinstance
groups are SlashCommandGroup
Alright, will do so. I guess I got confused by the walk_application_commands signature. It states that it only yields ApplicationCommand objects
Hi got a small question. When calling discord.VoiceClient.play i can define with the after= parameter a finalizer function. Usually this finalizer function only receives an error parameter from the play function. Is there a way to pass more than just the error parameter to the finalizer function without using global vars, for example the ctx?
overall, how frequent are username changes on discord? cuz my member cache is disabled but sometimes i need to get a member object from a user object when username changes for every mutual guild, what's the best way to do it?
fetch the member in the guild
so they're infrequent enough that you can do that?
so there is literally no way around it right
Hey I learned that giving guild_ids to my functions would help with discord syncing. I had a question is there any way for me to make an environement variable that will be passed to the 'guild_id' parameter or not ?
it doesn't help with discord syncing
it may be a short comprehension , but while develloping i found my commands to appear quicker if i gave a guild_id
that was true 4 years ago
if you give a guild it just makes the commands sync to a specific guild
But it doesn't mean your commands sync quicker as usually it would sync to all guilds
Now it'll still be shitty on all other guilds except the one in the guild_ids
And it would still need to resync and take a lot of time when syncing to all guilds once you're done testing on your guild_ids
ok thank you
as always, restart discord when changing any command metadata
press ctrl+r
is it possible to register the same command name with multiple input types ?
/choose_color <red> <green> <blue>
/choose_color <hex_color>
/choose_color <color_name_list
okay thank you !
hey is there any reason why my prefixed commands are running twice, my slash commands are normal - there's no duplicated on_message events and the cogs are only being loaded once
You're probably running your bot twice.
Very quick question, is more efficent to make a bridge insted of copy paste?
obviously
hey all how to you make a respond private ?
.respond(ephemeral=True)
ho ok thank you I'll read it in the doc , I couldn't find it
discord.ApplicationContext
discord.ApplicationContext.author
discord.ApplicationContext.bot
discord.ApplicationContext.channel
discord.ApplicationContext.channel_id
discord.ApplicationContext.cog
discord.ApplicationContext.command
discord.ApplicationContext.defer
discord.ApplicationContext.delete
discord.ApplicationContext.edit
discord.ApplicationContext.followup
discord.ApplicationContext.guild
discord.ApplicationContext.guild_id
discord.ApplicationContext.guild_locale
discord.ApplicationContext.interaction
thank you
Hi,
Let's say I've got a user who boosted my server and received the booster role. Gave them a reward by using the on_member_update listener. I'd like to give them another reward for the second boost. Any way I could do that? Booster role isn't given to the user twice, so which event listener should I use? OR is there a boost counter somewhere available?
you can use the default boost messages discord sends
Hmm... right, I'll do that. Thank you!
that ofc requires those to be enabled
isnt the case on all servers, if your bot is public
Isn't public yet, but will be. Is there a shortcut to retrieve the channel these messages get sent to?
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 ...
docs save lives :)
Thank youu
@sage tendon
[2024-07-29 08:25:38] [INFO] >> Loading cogs...
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.misc_cog
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.economy_cog
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.moderation_cog
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.administration_cog
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.staffapps_cog
[2024-07-29 08:25:38] [ERROR] >> Failed to load cog cogs.gamble_cog: Extension 'cogs.gamble_cog' raised an error: TypeError: Invalid class <class 'NoneType'> used as an input type for an Option
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 784, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/home/container/cogs/gamble_cog.py", line 12, in <module>
class Gamble(commands.Cog):
File "/home/container/cogs/gamble_cog.py", line 561, in Gamble
async def coinflipbet(
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/options.py", line 438, in decorator
func.__annotations__[resolved_name] = Option(itype, name=name, **kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/options.py", line 243, in __init__
raise exc
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/options.py", line 238, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 810, in from_datatype
return cls.from_datatype(datatype.__args__) # type: ignore
File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 795, in from_datatype
datatypes = [cls.from_datatype(op) for op in datatype]
File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 795, in <listcomp>
datatypes = [cls.from_datatype(op) for op in datatype]
File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 852, in from_datatype
raise TypeError(
TypeError: Invalid class <class 'NoneType'> used as an input type for an Option
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/bot.py", line 86, in <module>
raise e
File "/home/container/bot.py", line 82, in <module>
bot.load_extension(cog_path)
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 918, in load_extension
self._load_from_module_spec(spec, name)
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 787, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.gamble_cog' raised an error: TypeError: Invalid class <class 'NoneType'> used as an input type for an Option```
mind helping?
i literally have no clue why its doing this
holy balls
@option(
"choice", description="Choose 'Heads' or 'Tails'.", choices=["Heads", "Tails"]
)
@option(
"challenger",
description="Challenge another user to a coin flip bet.",
required=False,
)
async def coinflipbet(
self,
ctx: ApplicationContext,
bet_amount: int,
choice: str,
challenger: discord.Member = None,
):```
its just that
it worked yesterday and no commits have been made
try explicitly setting str as input type for both options
i've only disabled member cache
it works now
thanks i guess lol
idk where the fuck that came from
if i had to guess, discord API update
waking up with 400 errors and a down bot is NEVER a good thing π π
probably
very weird
yea i can really only imagine a discord api update then, or rather, discord api bug
is there a way to make it so if a cog crashes instead of the ENTIRE bot killing itself it will post in my staff chat and then keep the bot up but disable the cog
do you know why _system_channel_id is private? Cuz sometimes I have to use it because the system_channel attribute is none...
because if system_channel is None, there wont be an id
yet there is
that's my point
error handling :)
the id is set not the channel object
if system_channel is none, system messages are off
lemme wrap everything in try except and pray something works ong
nope
yes.
no, thats not how you do that
load_extension has a kwarg for that afaik?
does it?
that would be hella convienient
in my case
ctx.guild.system_channel was none but not ctx.guild._system_channel_id
cuz this literally happened overnight and i do have error handling for when they load and in every command
store=True I think
also, @stoic patio, can i ask why you are hosting on like the most expensive service possible when you're clearly budget-restrained?
It is store.
If True returns a dict with all the errors, if False it just raises the exception and closes the bot.
