#Basic Pycord Help
1 messages · Page 71 of 1
is it not good
if yes, I KNEW it

railway uses shared ip addresses
it's one of those ones
is it not a vps?
no
depends on the plan
i wanted to use digital ocean but idk how to set up docker
basically how railway works (for free at least) is it shoves a bunch of things on one machine and they all use the same ip address
nah it's not free
just use any old cheap vps provider lol
there's dozens
what plan do you have?
my friend would suggest pm2
this
oh i forgot railway actually killed their free plan
yeah
all free services eventually crumble lol
uh it looks confusing to set up
ok yeah, it's still listed in their docs https://docs.railway.com/reference/static-outbound-ips?
There is no guarantee that the IPv4 address assigned to your service is dedicated. It may be shared with other customers.
this?
changing your region should be fine
just look up "pm2 run python"
oh right
you want virginia anyways
the general point is, at the scale of your bot, a service like railway isn't viable
but pm2 isn't a hosting provider its just a Linux utility
so does pm2 uses your pc to host?
you use pm2 on your vps
ah i'll consider changing it asap
if you really can't move away from railway then do at least try the fixes we presented earlier, but if you keep running into issues then it's highly recommended you look into getting a linux VPS and setting up your bot on there
oh i got it
You should probably use webhooks for sending log messages
yeah right now im just going to prevent the error loop and hope it resolves the issue
whys that
if pm2 is scary, you can even use simpler utilities like screen or tmux
thought of it but it's troublesome if i were to change the log channel etc
it's literally just pm2 start file.py --interpreter (venv path)
yeah ik but people find things arbitrarily scary
Bypasses ratelimits
webhooks also have a lower ratelimit
dw it looks fine to me
wait im getting a lot of pings again one sec
regular channel sends are 5 per 5 while webhooks are 5 per 2 or so
I only pay $4 for a dedicated IP droplet on digital Ocean
is a droplet a vps
I pay way too much for a cluster of servers in openstack
god I hate when services make up a completely custom set of terms
I AGREE
Yeah
a friend of mine has an old plan and the vps is like 1.30 per month
I guess it has significantly less ram tho
are there limited usage?
or the cost is calculated by ur usage
Not entirely sure but I think I have to use a lot of network to get charged
a regular VPS is unlimited amount of compute time, and the main differentiation is amount of RAM and type and amount of disk
net bandwidth is usually insanely high so you'd never reach it
my bot is using a bunch of networks cuz my bot has to send a bunch of local images
I've rarely seen less than 1TB bandwidth
500 GB bandwidth and $0.01 per GB over
railway calculates network egress
yea and 500GB is much more than my entire household uses in a month lol
bruh that's so expensive
Need to run your bot 24/7? Get a cheap VPS.
Scaleway - EU
Time4VPS - Lithuania
Infomaniak - Western EU/CH
Hetzner - Germany/US
DigitalOcean - US
Vultr - US
GalaxyGate - US
HelioHost - US
- Self-hosting: Any computer
- Free hosting:
Herokudead :crab: - Kinda free: GCP, AWS (one year free micros), HelioHost (but with some constraints)
oh yea if you have a credit card oracle has an insane free vps tier
i tried it and it sucks
Should we add oracle to this ?
Never used it so idk
lol don't they give you a shitton of everything? whats wrong with it
it's not user friendly
you get like 40GB ram on the arm one
at least for me
do they give you a terminal or ssh
i forgot the details but the name reminds me of a hard time
lol
it was back in 2021
I would want to add a disclaimer, some people seem to have a good experience while some people have had a pretty bad experience
just put a note that it's free and thus nothing is guaranteed
didn’t GalaxyGate get a data breach
if a msg is sent in a forum channel, what is the message.channel object type?
and if it's in a vc channel, is the channel type VoiceChannel/StageChannel?
channeltype should be thread
voicechat, no clue, if i had to guess i'd say textchannel
just try and print it
Pretty VoiceChannels are messageable, so it would just be a VoiceChannel object
that's what i'm saying
just try it and print the type then we know
I think the docs are just out of date
It is typed as
MessageableChannel
PartialMessageableChannel = Union[
TextChannel, VoiceChannel, StageChannel, Thread, DMChannel, PartialMessageable
]
MessageableChannel = Union[PartialMessageableChannel, GroupChannel]
weird
Heyhey. Can someone remind me how I can add a thumbnail in an Embed with a file I have in BytesIO?
IIRC there's something with attachment://, but I can't find any relevant examples
Oh, do I add it as a file attribute to the message? (I would think that would show separately)
ah-hah! Conversation between @echo wraith and @shell radish proves useful
it still mentioned me lol
Audible or just badged? I added silent
Hmm I forgot
Getting the following error when trying to run a Pycord bot on Python 3.13 using MacOS
Traceback (most recent call last):
File "/Users/<redacted>/Documents/MyPrograms/ProfitGreen/bot/main.py", line 2, in <module>
import discord
File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/discord/__init__.py", line 27, in <module>
from . import abc, opus, sinks, ui, utils
File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/discord/abc.py", line 58, in <module>
from .voice_client import VoiceClient, VoiceProtocol
File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/discord/voice_client.py", line 55, in <module>
from .player import AudioPlayer, AudioSource
File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/discord/player.py", line 29, in <module>
import audioop
ModuleNotFoundError: No module named 'audioop'
It works now, thanks
.tag audioop
Pycord 2.6.1 may work with Python 3.13, but it is not officially supported and can cause various issues. Until Pycord 2.7 includes official support for Python 3.13, it is recommended to use a previous version.
For voice features in Pycord versions before 2.7, you might need to run pip install audioop-lts. Some users have reported issues with voice features when using Python 3.13, so ensure that you clear the __pycache__ and .pyc files before running your bot.
PyCord doesn't return cancelled_at
guild_entitlements_iter = guild.entitlements(exclude_ended=True)
guild_entitlements = await guild_entitlements_iter.flatten()
Also, why is on_entitlement_create() getting triggered twice for the same entitlement? I verified the entitlement ID is the same both times
Edit: https://github.com/Pycord-Development/pycord/issues/2752
canceled_at is under Subscription, not Entitlement
Is Subscription new? I can’t find it in the docs
Gib release plz 
Ugh. What the hell are you supposed to typehint when you get_channel and pass it into a function? If I typehint discord.TextChannel, then my calling method complains "Expected type 'TextChannel', got 'GuildChannel | Thread | PrivateChannel | None' instead "
If I typehint discord.abc.GuildChannel, then my .send() and .is_news methods show warnings
If I typehint discord.abc.MessageableChannel, then I get a runtime error "AttributeError: module 'discord.abc' has no attribute 'MessageableChannel'"
You should check it with isinstance
type it as GuildChannel | Thread | PrivateChannel | None lol
what warnings does .send() show tho?
Probably smith about it not being a valid method of None
Which makes total sense
Or just channel: discord.TextChannel | None = ... # type: ignore 🤓
😭
Anyone know why this been showing since the discord update
read the last line
Oh yeh 😂
thx anyway found the error
I wanna know if this is alright.
It works, but I'm looking to see if the structure is sound.
though I think I'm actually going to replace the literal file location with a static string so that its easy to read and change for all my functions.
also I added break after is_admin = true since there's no reason to go through the rest of the list if a match was already found
If you work with files, dont open them just like that
What do you mean?
Opening and writing a file is not asyncio, so its gonna block the whole bot
Does this mean that it can only read one file at a time or do you mean that multiple requests can't write the same file at the same time?
Each user has a different file.
This is only done because its a bot for ~30 people
is_admin = user_id in ADMIN_LIST
Saves the for loop
It means, if you write a file, it has to finish first the file. If someone else tries to use a command at that time, the command is not gonna work. That can lead to crashes, error and other stuff.
So while its reading/writing a file, the bot can do nothing else at that same time?
Yea
You said don't open them like that, so is there another way that will work?
Ah I see. I'll try using that instead.
Its pretty simple to use
@little cobalt I'm now using this. It works in discord. Does that look about right?
What type of File is that?
.txt
You forgot to await a write
And add encoding="UTF-8" next to the "r"
What does that mean?
So, for me, if I want to write something in my language. It doesnt know what do to with ä, ü or ö. And the encoding is for that.
So, I'm trying to use this but I don't know where to put @commands.cooldown in my function to get it to work.
docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.cooldown
Where do I put this: @discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)
in
below the command decorator
This isn't working though. The program just crashes.
When I open it, it instantly closes.
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
I don't get any error. It just closes itself. It doesn't do so when I just remove that line.
commands is imported from discord.
Ok, I have a proper error. I was running the program the wrong way where no error was showing.
should be discord.ext.commands
So I shouldn't even both importing commands for this and instead just use @discord.ext.commands.cooldown?
yes
This works. Thanks.
the example block I saw elsewhere was just using @commands.cooldown() so I didn't know why it wasn't working.
Because it did
from discord.ext import commands
Oh, so I missed a step by importing commands directly from discord
I feel like you should create a class to manage all of ur stuff, will be way more clear
Like a class for all of ur related « database » so you can do get_balance(target_id) and it just return you the thing. Might be way more clear if you use it in different commands
One thing I'm not really understanding is how events are ordered.
We have @bot.command() which is establishing how the command is seen and indicating that I'm implementing a bot command. The function that defines the command's behavior follows it.
Sandwiched between @bot.command() and the function itself is @commands.cooldown(), which gives the command a cooldown and throws an exception if the command is used on cooldown, but this exception doesn't go to the function that defines the command's behavior(?), so where do I handle it?
You can use the decorator @nameofurcommand.error
Or use a general event
on_command_error
I think I need to read about decorators more, because from the documentation I know what to use but not how to use it
Is there any downside to using commands.Bot over discord.Bot when fully operating on app commands?
My friend says commands.Bot provides additional functionality, which may or may not be useful, but he doesn't see any harm in keeping it.
Just want to confirm if there's any drawback to this approach.
.tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
@marble compass
ik this, just wanted to know if there is any performance issue or not, please read the above message
no there is not, its just some addition since you can also use prefix commands
but if you will not use at all prefixed commands there is no need at all to use commands.Bot
yeah I have not been able to convice him, he says just keep the options available
I might suggest using bridge.Bot instead then
ty
nah you shouldnt
rn bridge is kinda broken
oh okay
preference
how should i do to pass some local file as thumbnail inside a paginator ?
each pages should have a different one
(there might be a lack of support in the library for that)
send a file and use attachment://filename
So I'm getting this error, but in the documentation it says that it is discord.ext.commands.on_command_error()
I can't seem to figure how to handle errors that are caught before entering my function (like by commands.cooldown).
Issue is we cannot send files with paginator
luma told you before
Another issue would be that when passing from a pages to another one I will need to reset attachements which is not possible
How should I do ?
This module provides an easy pagination system with buttons, page groups, and custom view support. Example usage in a cog: API Reference: Page: Attributes content, custom_view, embeds, files. Metho...
let me try again, it gaves me an error first( ok its not in the same way)
ping me if I need to pr smth :p
ok but everything works, just i needed to use Page and not just do pages = embeds
thanks plun
well you might need
can you explain me how should i do here pls :
usually we have to do attachements = []
I had this issue when using another discord lib for python some time ago, and didn't have it w pycord
im doing like so
page = pages.Page(embeds=[embed], files=files, attachments=[])
pages_list.append(page)
paginator = pages.Paginator(pages=pages_list)
await paginator.respond(ctx)
so i dont really know how i should do to remove them
why attachments=[]?
to remove the attachments when editing the message
that's how we usually do
doesnt passing files= handle that already
nope
files = [] will not remove any previous file on it
i think it might be lack of support
i'll check the code
strange because in the code it should remove it:
https://github.com/Pycord-Development/pycord/blob/master/discord/ext/pages/pagination.py#L682
@fresh sierra if you manage to have a pure pycord mrc I can take a look
what a pycored mrc ?
i'll do that for u
so without using Lumabot, etc...
yep dw
and here it is
pages_list = []
for i in range(3):
embed = discord.Embed(title=f"Embed n°{i}")
files = []
if i == 2:
async with aiohttp.ClientSession() as session:
async with session.get(
"https://cdn.discordapp.com/avatars/707196665668436019/948a1b5911d8529767c8be676f7d5b92.png?size=2048"
) as response:
if response.status == 200:
test_file = discord.File(
io.BytesIO(await response.read()), filename=f"test.png"
)
files.append(test_file)
embed.set_image(url=f"attachment://test.png")
page = pages.Page(embeds=[embed], files=files, attachments=[])
pages_list.append(page)
paginator = pages.Paginator(pages=pages_list)
await paginator.respond(ctx)
@echo wraith
this happens when existing attachments on the image are no longer able to target an attachment:// found in an embed
passing attachments into Page does nothing
how should i do then to prevent this ?
but hm, paginator is meant to clear attachments every time...
that's what i saw on the code but not what is happening on my side
might have guessed the issue but not 100% sure
can you send the paginator without using an interaction
i.e. paginator.send
and see if you have the same issue
Yep, since im using bridge will that be the same as just using it inside a commands prefix ?
yes
Then it does not fix it
hm it's also broken on paginator.send? strange
Possible, but strange because it’s using attachments =[] at each edit
So it’s strange that it’s not removing it
ahhh i guess the send method technically wouldn't change anything...
maybe better to test directly
can you edit the lib files that your bot is using
I can, if you tell me what following change I should do
at around line 700 of discord/webhook/async_.py you'll see this; change the condition to if attachments is not MISSING:
(this likely needs to change regardless of this issue you're facing, as it means webhook.edit_message(attachments=[]) does not work)
yep it fixed it
hell yeah
man are you alright ?
LOL
how did you find this in like second
message.edit looked fine so the answer was webhook
(which is why i asked this)
well it doesnt look quite obvious for me but that's impressing ;)
actually
that fix might be naive
eh
it'll probably break if you pass files without attachments
if attachments is not MISSING or _attachments:
do you want me to try something ?
this works fine:
@Lumabot Test#4042debug exec
async with aiohttp.ClientSession() as session:
async with session.get("https://cdn.discordapp.com/avatars/707196665668436019/948a1b5911d8529767c8be676f7d5b92.png?size=2048") as response:
if response.status == 200:
test_file = discord.File(
io.BytesIO(await response.read()), filename=f"test.png"
)
msg = await ctx.send(file=test_file)
await asyncio.sleep(1)
await msg.edit(attachments=[])
i mean webhook edits (e.g. edit after defer) with files wouldn't work with the first fix i suggested
assuming the user didn't pass attachments
(which is usually the case)
so the adjustment here catches that situation
so what i just did using a slash commands should not work ?
i mean using a ctx.respond
it should be a webhook since i defer before no ?
i guess i'll break it down
because from my side even using it inside an interaction works fine, defering before sending the paginator
simplified version of current webhook code ```py
_attachments = []
if attachments is not MISSING:
_attachments = [a.to_dict() for a in attachments]
if files:
for index, file in enumerate(files):
...
_attachments.append(attachment_info)
if _attachments:
payload["attachments"] = _attachments
- this was an issue because `if _attachments` is `False` if the user passes `attachments=[]`
- if we change it to `if attachments is not MISSING`, this is `False` if the user passes `files` and not `attachments` - `files` requires the `_attachments` list, so certain attachment info would never send
- the final adjustment suggested was `if attachments is not MISSING or _attachments` - this catches every case (if the user passes `attachments=[]` then `attachments is not MISSING`, and if the user passes `files` then `_attachments` is truthy)
this was not an issue anywhere else because they handle it differently
How do I make the response to a command private? Like the commands that yield a ‘only you can see this’ message
ephemeral=True in the response
File "/Minecraft/soundboards/bot.py", line 304, in callback vc = await user.voice.channel.connect() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/discord/abc.py", line 1986, in connect voice = cls(client, self) ^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/discord/voice_client.py", line 233, in __init__ raise RuntimeError("PyNaCl library needed in order to use voice") RuntimeError: PyNaCl library needed in order to use voice ^Croot@v2202503261488325026:/Minecraft/soundboards# ^C root@v2202503261488325026:/Minecraft/soundboards# ^C root@v2202503261488325026:/Minecraft/soundboards# ^C root@v2202503261488325026:/Minecraft/soundboards# pip install PyNaCl Requirement already satisfied: PyNaCl in /usr/lib/python3/dist-packages (1.3.0)
Great.
pretty sure bots are not able to use the emoji field. You can still use unicode emojis anywhere in the status text though
As for your other error, idk
not emoji, i mean text
you need to specify which python version, in this case i think python3.11 -m pip install PyNaCl should do the trick
root@testserver:/Minecraft/docker/soundboards# python3.11 -m pip install PyNaCl Requirement already satisfied: PyNaCl in /usr/lib/python3/dist-packages (1.3.0)
what command are you us9ing to run your bot
python3 which points to python3.11
python3.11 bot.py it is the same
something on your system is screwed up then
pass activity to your bot constructor with https://docs.pycord.dev/en/master/api/data_classes.html#discord.CustomActivity
Ty
is it possible to make the bot send a message without the "<user> used <bot>" part above it? if yes, then how?
that would be ctx.send
but note you have to respond to a command
so either:
- use
respond(..., ephemeral=True)to send a hidden response, thenctx.sendafter - if you don't mind a *little* jank, you can do
ctx.defer(ephemeral=True)->ctx.delete()->ctx.send(...)
is it send_response?
no, just send but you might have to go to channel.send in docs
send and respond more or less use the same arguments
ctx.send didn't work, but when i do ctx.channel.send it "kinda" works? but gives an error message before sending the correct message
you have to respond once to commands; see #1132206148309749830 message
ctx.send should work regardless? oh well
ah, forgot that. Thanks
so in the second case the order will be defer, respond, delete, send?
the code at this point:
async def yt(ctx, query: str, embed: bool = True):
ctx.defer(ephemeral=True)
ctx.delete()
cmd = subprocess.run(["ytgo", "-d", query], stdout=subprocess.PIPE, text=True)
await ctx.channel.send(cmd.stdout if embed else f"<{cmd.stdout.strip()}>")
ah both defer and delete should be await
print(member.roles, member.roles[0], member.roles[0].id)
im getting this error from the code above
Application Command raised an exception: AttributeError: 'list' object has no attribute 'id'
kinda weird though but that is what written in the docs
async def say(ctx, msg: str):
await ctx.defer(ephemeral=True)
await ctx.delete()
await ctx.channel.send(msg)
I’m assuming ctx.channel.send doesn’t work in DMs and groups? What to use in that case?
It works in DMs
interesting…
But for groups, bots can only exist through interactions
So you can only respond
(You can also do user.send to DM a user)
just tried in a DM and it’s the same as in a group: it sends a buffering message “sending command” or something (greyed out), deletes it, and doesn’t do anything else
Idk send works regularly in direct messages
the user might have disabled bot DMs
and no you can't send a message with a bot into a DM
only as response to a slash command
Well in this context I think they're running a command in the dm
if anything the bot has to DM the user directly
? You can dm bots normally
I know, but unless it's a DM with the bot itself it can't work
Yeah we already established group dms are different
Yea but you can't make a bot send a message in a DM
aren't they talking about 1:1 DMs too rn
I guess they never specified
What's the context of this DM
is it you and the bot or you and another user
DM with a person
Then respond only
Oh
Because the bot cannot exist in another user's DM
Makes sense
Good catch lol
is there like a ctx.typeof or something to check if I’m in a dm/group? that way if true I can do respond instead
You can do isinstance on ctx.channel
Thanks
there's discord.DMChannel and discord.GroupChannel
While discord.abc.GuildChannel will cover every guild channel
(You could also check if channel.guild is None, but that doesn't cover the difference between DM and Group)
ah, that's even better. Thanks
since in my case I have to do the same thing in both DM and Group
it do be kinda weird to see the message body in the context, but this works in DMs and Group Chats now. Thanks 😊
:3
how do i get the webhook class with a webhook url
i read it yeah but what's the session arg?
an aiohttp session
aiohttp.ClientSession
aiohttp.ClientSession.auth
aiohttp.ClientSession.auto_decompress
aiohttp.ClientSession.close
aiohttp.ClientSession.closed
aiohttp.ClientSession.connector
aiohttp.ClientSession.connector_owner
aiohttp.ClientSession.cookie_jar
aiohttp.ClientSession.delete
aiohttp.ClientSession.detach
aiohttp.ClientSession.get
aiohttp.ClientSession.head
aiohttp.ClientSession.headers
aiohttp.ClientSession.json_serialize
aiohttp.ClientSession.loop
i've found examples but they did not pass the session argument
async with aiohttp.ClientSession() as session:
webhook = discord.Webhook.from_url(blurp, session=session)
await webhook.send("Hi")
on_message_edit() Triggering Like on_message() in Certain Servers
idk why 😔
more info?
https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.context might be a better thing to check in case discord changes something in the future. Both this and what nelo said work but I think this is the more "correct" approach as it is a specific check instead of implying from something else
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 ...
Is it possible to access the chat history in voice channels? I am able to send messages in the chat but not able to see the history.
for channel in voice:
# get all messages for channel
messages = await channel.history(limit=None).flatten()
print(channel.type)
print(channel.name, len(messages))
print(messages)
This returns an empty list
do you have message content intent
Yes my bot works fine on text channels and is able to access history. I only need access to the messages in the voice channel chat, not any voice data.
does the bot have proper permissions in that channel too?
From my knowledge, it should have adequate permissions for all channels. Would voice channel chat require different permissions than regular text channels?
also i would try with a lower limit (or any limit for that matter) to see if thats the issue
view the server as the bots role and see
You might also need the connect permission
Thank you! Turns out the bot does not have permissions to view the chat
From what I can tell users cant access the chat if they cant connect
Yep this might be it
Thank you both!
according to the docs the bot only needs read message history
When I view it as the bot role and click on the voice channel chat it says I don't have permissions. Text channel ones are fine
It says I can't view the history
so the check would be discord.InteractionContextType.guild in ctx.interaction?
No,
ctx.interaction.context == discord.InteractionContextType.xxx
basic python: :o
something (Enums) i haven't needed in 7 yrs of coding Python including 2 jobs: basic Python
i mean interaction isnt an iterator lol
Worked. Thanks
@echo wraith sorry to @ you but im trying to use your reactiveviews project and im having some trouble. when i run the code below i get the following error TypeError: ReactiveView.send() missing 1 required positional argument: 'ctx' and also just to test the reactiveviews out i have your counter example in the counter_test class so i doubt its an issue with that
@discord.ui.button(label="Continue", row=4, style=discord.ButtonStyle.success)
async def continue_callback(self, interaction: discord.Interaction):
await counter_test.send(interaction)
So I tried defining a cog and I threw my hello command in there, hoping that the command would become /greetings hello but instead it stayed /hello and is now requesting ctx as a passed variable. How do I get a command to be /greetings hello?
- you want command groups
- how is
botdefined? in cogs, you should be using@discord.slash_commandfor regular slash commands
Here's the slash cog groups example.
oh I didn't know I had to define them as slash commands in cogs.
why wouldn't you
for what you're asking for specifically, you need to define something like greetings = SlashCommandGroup(...) and then use @greetings.command
(conveniently, this matches the linked example above)
Can we continue in DMS ?
Nw for the ping
how can i correct the typehint for it typehint that as discord.Emoji ?
class EmojiConverter(commands.Converter):
async def convert(self, ctx: LumabotContext, argument: str) -> discord.Emoji:
emoji = EmojiSetupCog.get_emoji(ctx.guild, argument)
if not emoji:
raise commands.CommandError(ctx.translator.emoji.not_found)
return emoji
Maybe using typing.Annotated
But idk if ext.conmands supports it
yep it does not
is this a bad practice (for the roles)
await member.edit(
nick=member_data["nick"],
roles=[discord.Object(role_id) for role_id in member_data["roles"]],
)
why are you doing it ?
during a load backup
i want to put back each nick + roles saved as the moment
This is blasphemous, but has anyone used any of the AI platforms for all the discord.ui boilerplate stuff for Views? I just asked Claude to write something and on a skim it looks fairly workable, but curious if there are any specific gotchas I should look out for.
make sure you understand it before using AI for it
Well of course, just want to speed up development of the shitty parts.
I have been granted the members intent from discord minutes ago. I just added it to my bot and restart it. Now the on_guild_join and on_ready events are not triggered.
My idea was that the bot is caching all users. But is there any argument to ask him to not store them at start ?
FYI : My bot is in 32k server for around 3.9M users
yea thats gonna take a while to start
you can disable the cache of the member
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
Just saw that chunk_guilds_at_startup. Maybe the solution
yep, both can work but because of that you will no longer have all member of all guild cached
that's not a problem. I only use the intent for a precise guild.member_count. Which will be on-demand and not needed at startup
then you should completely disable cache
since you can use guild.fetch_member(limit=None) to get all member in 1 request
So I put my project on a different computer. Installed python, pip, and the pycord library in accordance with the install instructions, but it says ‘discord’ has no attribute ‘bot’ when I run bot = discord.Bot(intents = intents)
This is all that I have up to the error
check if what you installed is the right thing
Has anyone else noticed anything weird with modals since discord made the new UI update? This is a screenshot of one of my modals and if you look at the label for the second text field, the s in parenthesis is uppercase. But it shouldn't be: https://github.com/fiskenslakt/pzsd-bot/blob/f239d78a319d14f07f142343118b74ad54f0661e/pzsd_bot/ui/triggers/modals.py#L59
And it certainly didn't used to be. If i remember right, it was all uppercase before regardless of what the casing in the label was?
if you are using pip, then use pip list and send the output
uninstall discord and discord.py and re-install py-cord
I did that and now it gives me an earlier error.
from discord.ext import commands
Cannot import name ‘commands’ from ‘discord.ext’(unknown location)
you did not re-install py-cord
Oh weird. I didn’t delete it, just used install again. It’s working after I explicitly deleted it then installed it
Thanks
Someone else mentioned that it appears that inputs are forced to be title case for some reason
I almost wonder if they use text inputs throughout the app and wanted their titles to be consistent but forgot that it would affect bots to
I certainly wouldn't put it past them
Is there any way to implement a timeout for the view that renew after each interaction ?
yes, timeout is refreshed on every interaction
im not sure about that
let me try
Go read the code 
idk sometime im clicking the button and it get disabled
maybe there is another reason for this disable
is there a max timeout that get trigger or something like that ?
not unless you implement it yourself
can i it that im editing the message to replace the view but so the old timeout is still on ? and disable all the thing ?
If you are replacing the view it will go with whatever timeout that view has
so it will not keep it mind the old timeout
(5min timeout on the first view, edit the message for another view,the first view will never timeout and so edit the message )
It shouldent, but I guess it is possible that is a bug
uhh strictly speaking if you edit a view over another, there's no existing logic that stops the old view
oo
so that might be why i had that feeling about the timeout
so we should impletement something that stop the old view from working right ?
also can be memory efficient
you can try but it's not very straightforward
@fresh sierra if you don't wanna do it lmk 🙈
i let you this one ;)
components v2 should not effect this fix
affect*
fdajhgabj
Is it possible to know when an automod rule is enabled or disabled?
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...
Thy Wolfy
Why is discord.slash_command recommended over commands.slash_command?
they're the same
but in that screenshot, they were using bot.command inside a cog; this syntax doesn't work
Ah so they're just an alias
Any examples of OOP where slash commands are declared within the class? Or is it not possible?
Here there’s a class that doesn’t do anything other than subclass (and logs something, but that’s mot useful), and slash commands are still declared outside the bot class, making OOP somewhat pointless: https://guide.pycord.dev/popular-topics/subclassing-bots
uhhh if you mean in the bot subclass, it's never realllyyyy been designed that way
that's mainly relegated to cogs
we probably could add support for it? but might be strange to put it in the final versions of v2
my main question would be why
there's already 3 different intended ways to put commands into the bot, and probably more ways if you do it completely manually
Yeah frankly I don't see any need for another way of doing things
i don't particularly care either way, but i can see why people find it strange that you can't define commands in the bot subclass
@self.command doesn't work right
what are the limit for the ban ?
i have the impression here that its 2000 per 24h however what does that mean for non guild memebrs ?
it's per guild no? doesn't matter if member or not
and yes lala said it's 2000 per day
yep
but ok the non guild members had me a bit lost
strange but discord probably doesn't want people mass banning random IDs?
i.e. the 2000 limit doesn't apply if, theoretically, everyone you ban was in the server when you banned them
according to lala, no
from everything i just searched that is the case, but it's possible the behavior changed 
(and i think the error itself makes that distinction for a reason)

So per day you can only ban 2000 ids that are not currently part of your server?
How were you even hitting this limit
apparently
even tho i think this limit might also be from the current member according to the example of lala
You mean one bot could ban 2k and another bot do their own 2k?
I’m still curious how you even hit the limit though. What circumstances (there are a few, just asking yours) are you banning members that aren’t in your server, and to that degree?
That screen was not from me but from mid journey ig
And they ban bot for they don’t for they don’t unlimited image
And in my case since I’m making a backup system, if they save the ban I need to know the limit in case they have more then …
…wanna try this sentence again? 😅
Soundboard isn't in 2.6 right? I'm trying to download sounds
Wil be in 2.7?
No idea depends on the review and test willingness of others, but if you test it and find (or don't find) problems you can add a comment
Sorry I was lazy to finish
So in case they have more than 2k bans I will have to implement a cooldown system to not get rate limit or smth like that
could do kicks on join as an interim solution until you can ban again
Pretty sure it is a per guild limit
Ig those bot will spam join
doubt
If I make a bot that have as only point to get free image I’ll make a loop making them join and then get the free stuff
Like I thinking that a simple kick will stop bot from joining is a bit unrealistic
midjourney isn't even the best model or the easiest to exploit, idk why people go for it
That’s very dumb. You have to wait for a known spam account to join your server before banning it?
What about accounts that were part of your server but left (and then changed their name to something spammy)? Does it count against you when you ban those, since they’re not “currently” in the server?
I dont know much about it, it just would not make sense to have a per user limit like that because then there is essentially no limit if you can just get another user to do it ¯_(ツ)_/¯
look, 2000 bans per day is extremely high already
if you need that amount of bans regularly your server is unusual anyway
Well I am thinking of creating a moderation bot for the “unusual servers” who get high scam rates, and where administrators could get notifications about other servers and opt to pre-empt a scammer joining theirs
Granted I could also wait until they join and then ban, but seems silly to put a limit on one and not the other
there are already bots you can use to sync bans btw
im a bit lost with the invitable of thread
is it only for text channel thread ?
or also forum channel thread ?
what?
thread have a parameter invitable
but i dont really understand when can i use it and how, for instance i cannot create a thread and pass invitibale as an arg
It's just the setting for private threads whether anyone can add people or just moderators
i understood the issue
i mean its not really one but
invitable arg is only for text_channels thread
and not forum channels
yea because you can't make private forum threads
I'm noticing that when I try to mention a user inside an embed on Discord, searching for mentions (using mentions:username) doesn't display the embed, whereas it works fine with regular messages. Does anyone know of a workaround for this?
search their user ID
It aren't working sadly
it's not very user-friendly for normal users who may not know their IDs/how to use discord. Is there any workaround that lets us search by the display name or mention directly in embeds?
no
damn
or just put their literal display name in the embed
Got it thanks
I want to run an async method before my discord.Bot starts. Is bot.start() a better option than bot.run() for this, and what cleanup steps would I need to handle manually?
for that just use await bot.start()
Do I need to handle cleanup manually when using bot.start()?
cleanup?
By cleanup, I mean properly shutting down the bot, like this:
try:
await self.start(*args, **kwargs)
finally:
if not self.is_closed():
await self.close()
And also handling SIGINT/SIGTERM to stop the bot cleanly
or I could do this and keep using bot.run()?
ik it will be called before its connected to the websocket
Yes
hi! is there any way to check if the message is a forwarded one using pycord now?
( https://support.discord.com/hc/en-us/articles/24640649961367-Message-Forwarding
https://support.discord.com/hc/en-us/articles/24640649961367-Message-Forwarding )
Not yet unfortunately, there is a pr being reviewed here:
https://github.com/Pycord-Development/pycord/pull/2598
Feel free to try it out and add comments to the pr if you find issues -> pip install git+https://github.com/NeloBlivion/pycord@forwarding
thanks!
np
i think you do, i had to do it once for i dont really remember what
like i had some error by not doing like so
(to recap run had an issue so we had to use start but to start you should use something like than asyncio else it's gonna block all of ur loop
an async setup_hook along with bot.run() can be created with this method
#1132206148309749830 message
Why not just bot.loop.create_task
Override the bots __init__ and call it after super().__init__
Yeah, loop.create_task() works well for background tasks, but I designed this to function like dpy's setup_hook
@marble compass fyi you can wrap a link in <> to avoid the embed from rendering
yep
but as i said, the bot.run can be an issue
idk if it has been fixed
There shouldn't be any issue as long as you don't do anything blocking in the "setup_hook"
When a Cog gets to be 2K lines, how do you break it up? 😅
You can't really do 'sub-cogs', I take it. I'm using recursive cog loading, so if I add a subdirectory I could just split them out in there, right?
depends
is there is multiple commands i'll make different cog with one command in each
if its from helper function i'll make a helper file
Ugh, the other sucky part is organizing command groups.
if its from text i'll just go kfm
multicog
but i understand your point, is it only ur commands or the view associated with etc
I do keep my Views in a separate directory, so that won't be too much of a problem.
I use multicog already, but I don't recall the intricacies; can I .create_subgroup from a group I created in another file?
you usally just use the decorator
im not using it persoally but i think its something like
@subcommands("group name")
@commands
how?
how what
Honestly IDE code folding. You should not be separating things just because they are too long.
Are those 2000 lines all for commands belonging to a single coherent topic and all duplication-free?
Well, multiple related topics technically, since I have some subcommands.
Of course, this is built up over 4 years. I'm sure if I refactored the whole thing, it would come down some. But still I hate adding things to this (relatively) giant file.
What's the best way to add a subcommand group to an existing group defined in another file? Like is there some way to guarantee order?
What I typically do is move long blocks that are just generic utility within your commands to cogname_helper.py
especially if you reuse the same logic
Oh, I have that already. My bot does a lot of things.
Nearly 26K total lines of python between Views, dataclasses, Cogs, helpers, etc.
geez
if it's not the cog itself, some other file will inevitably end up being that long
you can't really avoid large files at that point unless you're crazy enough to split every function into its own file
you could change it to that you do a new file for every new view
Is it me or is 2k lines in one cog like nothing?
But everything relevant is together so why would you break that up
💀
I group my Views based on Cog. I am thinking of splitting those up, though, too.
what?
That 2K-line Cog file is just the Cog and its containing functions, not Views (another 800 lines for the related Cog) or anything else.
That's imports + typing + cog + one command with checks + setup for me lol
then you have bloated as hell code
typing doesnt take up any lines..
my entire main.py is 26 lines
Okay maybe not 500 but typing on strict does force you to resolve every Unknown or generics that exist
That's valid
Why would you do that to yourself
bro is making python into c
c isn't even that bad
True
hey, I had a bot running on pycord 2.4.0; I have just updated it to 2.6.0 and I'm getting a deprecation warning for this line in an on_message event:
if message.interaction is not None and message.interaction.name == "setup":
DeprecationWarning: interaction is deprecated since version 2.6, consider using interaction_metadata instead. See https://discord.com/developers/docs/change-log#userinstallable-apps-preview for more information.
fyi there's 2.6.1, you should update
whoops i mean 2.6.1
anyways, i'm looking at interaction_metadata and it doesn't seem to have the information I require (the interaction command for the message)
and yea i mean its exactly what it says
i need to listen for application commands invoked on another bot by a user in my use case
is there an alternative since interaction_metadata doesn't have such data
or would it be safe for me to stick to message.interaction
maybe i should make a separate post for this
i mean it'll be removed eventually
#1315663969595166720 message
aw man
time to remove a feature 😔
thanks for that link, couldn't find it
what do you need this for btw?
interaction_metadata.name exists internally, but discord doesn't want to document it as they consider it unstable https://github.com/discord/discord-api-docs/pull/6734
you can continue to use message.interaction until it's removed sometime down the line, there will be advanced warning to when you can no longer use it
if you really want to stick to interaction_metadata, you can either
- fetch the raw data
message = await bot.http.get_message(channel_id, message_id)
command_name = message["interaction_metadata"]["name"]```
- manually update your `discord/interactions.py` file to add the `data` attribute to `InteractionMetadata`
my bot listens to commands invocated by another bot to do automate certain actions (listening to a mafia bot game setup using the /setup command, listening to Dank Memer command invocations for reminders)
i see
Does anyone know how to avoid discord.errors.Forbidden: 403 Forbidden (error code: 50083): Thread is archived when someone is using a context app command ?
Try catch probably
the exception is raised in the defer... but I cannot .respond if I have this error
I wanted to make a post but.... I forgot an invite link and I have to wait 1h now in order to create a new post
maybe check this before ?
how can i know if im rate limit when creating webhooks ?
i would like to do something like so :
for i in range(1000)
await channel.create_webhook()
if rate_limit:
await asyncio.sleep(75)
would be way faster than waiting 75 seconds each time, since we can create around 50 webhooks before the rate limit of 75s between each
pragmatic approach: spam webhooks until you're rate limited and figure out what exception it throws
nah but honestly I don't think there's a way to directly tell that, the docs only say Forbidden and HTTPException
It does not raise error
Since its handle by pycord it just say retry after
Except when all of ur bot is completely block it does raise an error but its too late
why do you need so many webhooks in 1 channel
he's building a system to restore the last day's worth of messages in his server, and so he needs a webhook for each author
you don't
im p sure this is doable all via one webhook tho
you can pass username and avatar_url in Webhook.send
as such, you generally only need 1 webhook for any single channel
yea i just said what i think lumas thinking is
its an exemple
i do only use 1 webhook per channel
but the limit is shared so its the same, creating 100 webhooks in a channel or 100 in differents will cause the same rate limit
and what im doing is creating a webhook for each channel and each time waiting 75s, but if i knew when i was touching the rate limit i could create like 50 without waiting and then wait
don't create the webhooks beforehand, just create it on demand when you target that channel
already what im doing
let me show you
then what's the issue
async with asyncio.TaskGroup() as tg:
for channel_data in (
self.data["text_channels"] + self.data["voice_channels"]
):
if not channel_data["messages"]:
continue
channel_id = self._get_translated_id(channel_data["id"])
channel: discord.TextChannel = await self.bot.get_or_fetch_channel(
channel_id
)
if not channel:
continue
webhooks_for_channel = webhook_map.get(channel_id, [])
backup_webhook = (
webhooks_for_channel[0] if webhooks_for_channel else None
)
if not backup_webhook:
await asyncio.sleep(75)
tg.create_task(_load_message(channel_data, channel, backup_webhook))
my issue is tha ti would like to create as much webook as possible before rate limit and then when the rate limit hits i wait 75s for each
this may be a shot in the dark but in the discord UI, you can change a webhook's channel - can you do the same via the API to reuse the exact same webhook for every channel?
I can but it’s the same rate limit as crating a new one
So create new one is a bit better for I can send message in all channel at the same time
can't you just keep a counter
i mean you wont run it parallelly nor in quick succession, right?
so just do your thing until you count up to 75 webhooks, then wait?
So the issue is that I cannot really know where am I so when I will hit the limit
The solution might be to send a normal request using the self.bot.jttp and so then catch the error and start using the await
i think you are way overengineering this
If someone has an idea how to do that so it does also get handle by discord in a way but I do get the error also
having to restore a server is a super rare thing anyway (id hope...) so i dont see why 3 or 4 more minutes would matter (who has that many channels anyway?)
Its an hour difference
But yeah it’s true that it’s not a big deal
an hour??
It takes 75s per channel
do you have 5000 channels or smth
.
This is the rate limit
I cannot go faster than that hitting the limit that might be around 50 webhooks
So if instead of directly waiting 75s for each I could skip as much as possible and then wait it will be 1h faster
is this creating a new server or restoring a current server
Restoring a current one
Yeah but how ;€
you could just run into the ratelimit and let the library wait it out
Don’t you think doing the real request and catch the 429 and await it might work ?
So I did try that but it will flow the console of warning and then I get a global issue
And also an error
you're not trying to recreate it in parallel are you
So the webhook are not created in parallel
Because else I do get some global limit about webhook that 429 me
right
Do you have any counter issue about doing a real request (using pycord internal or a normal thing) and catch it ?
Because I don’t really see a better way rn
Will that messed up a bit pycord in a way
Even tho I don’t really think that’s possible
for what
So i would like to do smth like this;
Webhook = Https request to create webhook
If 429: await asyncio.sleep(75) and start back to use channel.create_webhook and asyncio each time
if you do it through the library, anything using HTTPClient.request will automatically wait on 429s; if you want to bypass that, you have to do manual requests through a ClientSession
Ok thanks so like a bot.ClientSession( and then a normal requests) ?
I’ll check that when im back home
you'd have to access bot.http._HTTPClient__session
(due to how __ vars work)
or you can just create your own clientsession
Should I do like this ?
async with bot.http._HTTPClient__session() as session:
async with session.get(f"create webhook") as response:
If response.status == 429:
Flag = true
data = await response.json()
not quite
If u have some docs / examples it will be really appreciated
you don't need to instansiate it
i.e. you start from the second line - async with bot.http._HTTPClient__session.get (or request, or whatever other method)
Good to know
And can i from the request get the webhook object ?
Or should I just fetch it
I mean for I can directly do webhook.send
like the Webhook object?
Is there a class where I should do webook = Webhook(data=dzta€
Yep sorry it was not really clear ;€
use Webhook.from_state(data, state=bot._connection)
(this is literally just the create_webhook code https://github.com/Pycord-Development/pycord/blob/master/discord/channel.py#L492)
allgood
it works perfectly, i went from 1:12:48 to 0:19:13
damn fair enough lol
does searching for webhooks contribute to rate limits
Fetching them yeah
I think all the route for wehooks are under the same bucket
So ideally don’t use channel.webhook() but more guild.webhook and itinerary
i never understood why they do that tbh
wait what ????
so instead of sedning a message to a channel
they use a webhook ?
why are they not just sending normal message ?
i think it's a ratelimit thing
the rate of logs is significantly higher than any other messages you would get on those bots
so offloading them to webhooks means that logging doesn't contribute to their global ratelimit
smart idea
then is it possible to find the webhook to use to send stuff without fetching it every time
yeah ofc
using a request you just need to pass the webhook id and token in some case
i honestly dont get why webhooks are treated differently
Because the only purpose of webhooks are to send messages
You just save the token and such yeah
(Or the full URL, pycord will parse it for you)
so why are bots sending messages so ratelimited then if they can just make webhooks?
because webhooks are also rate limit ;)
have you noticed how most bots don't do this
it's painfully inconvenient to use webhooks for regular message responses, logging is the perfect use case for them
also its not that rate-limit now that respond to an interaction is not touch at all
(webhooks in general, beyond discord, are just a way for sending messages)
hell, channel webhooks have half the ratelimit of message create (30/min vs. 5/5s = 60/min)
while interaction responses have a more generous ratelimit
My point is, why give webhooks higher ratelimits if they arent locked behind anything major?
what makes them so different?
i don't really have an "official" answer, but because the only purpose of webhooks is to send messages, and they can be utilized without a discord account or application, they're more susceptible to abuse/spam in certain conditions; they need some sort of limitation
but they have higher ratelimits than a bot, or isnt that what i just read
discord documented it as lower (30/min vs 60/min)
...but that might be outdated because im testing the ratelimit right now and i think webhooks were updated to 60/min anyway lol, so my entire argument is moot
because webhooks are also per channel
they face the same restrictions, it's just to offload the global ratelimit
oh
large bots like dyno have to request an increased ratelimit anyway, so i imagine discord support also has to test them to see if they actually need that increase
standard bot responses shouldn't really use webhooks, but something like logging is a pretty reasonable purpose
seems like a hacky workaround to me imho
only reason i see webhooks used is github repo updates and bots like tupper
hey that's a form of logging :)
How I see it is that they make sense in places where unprompted messages will be sent to one (or a small number) of channels
is it possible to create a post using a webhook for the first message ?
So right now im just sending a message with the bot but so it seems a bit strange to not have the name/profil of the real user
Yes
See thread_name
you didnt really understand my question
let me show you coz it wasnt really clear
this is what i meant
here instead of the bot creating the post i would like to use a webhook so i can put the same icon and avatar as the user that created it
that's exactly what thread_name does
^^
webhook = Webhook.from_url("url", session=aiohttp.ClientSession()) # or create one in the forum (Thread.parent) via the bot
await webhook.send(
thread_name="my very cool post",
username=...,
avatar_url=...,
content=?,
embeds=?,
)
I don’t mean send message in thread, I mean the creation of it
Luma
Or does it create it automatically
I didn’t know that send was also creating that’s mb, I was first creating the thread and then using thread.send
Thanks tho
thread_id (thread in pycord) targets an existing thread, while thread_name creates one (if it's a forum channel)
Ok, sorry for the misunderstanding
chill lol
I mean, they misassumed twice like.. rtfm lol
And this is a help channel.
more because i saw the send and i assumed what i was saying was not clear
and i read the docs about creating_thread, was not very logical for me that a send with a webhook could create a post. Again that's mb i was tired and i should have check ur answer first
| Traceback (most recent call last):
| File "/home/container/commands/backup/__setup__.py", line 856, in _load_message
| thread = await send_discord_message(
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
| File "/home/container/commands/backup/__setup__.py", line 848, in send_discord_message
| message = await backup_webhook.send(**kwargs)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1817, in send
| data = await adapter.execute_webhook(
| ^^^^^^^^^^^^^^^^^^^^^^^^
| File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 348, in execute_webhook
| payload["thread_name"] = thread_name
| ~~~~~~~^^^^^^^^^^^^^^^
| TypeError: 'NoneType' object does not support item assignment
+------------------------------------
is this a pycord issue ?
kwargs = {
"content": self._translate_mentions(message_data["content"][:2000]),
"username": message_data["author_name"],
"avatar_url": avatar_url,
"embeds": [
discord.Embed.from_dict(self._translate_mentions(embed))
for embed in reversed(message_data["embeds"])
],
"files": [
discord.File(
fp=attachment["path"],
spoiler=attachment["spoiler"],
filename=attachment["filename"],
)
for attachment in reversed(message_data["attachments"])
],
"allowed_mentions": discord.AllowedMentions().none(),
"wait": True,
}
if thread_name is not None:
kwargs["thread_name"] = thread_name
elif thread_id is not None:
kwargs["thread"] = discord.Object(thread_id)
message = await backup_webhook.send(**kwargs)
or else how should i do ?
I'll take a look
thanks !
oh that's silly
idk who designed that but thread_name needs to be handled in handle_message_parameters rather than execute_webhook
think it works right now if you don't upload files
It does without file
figured
It been some days I’m finding bug everytime I’m adding a new things lmao
Idk if I should call be lucky or not
hey better sooner than later
you probably find bugs because you do the most outlandish things and solutions
thank you
Might be really possible to
Ca you try pip install git+https://github.com/Paillat-dev/pycord.git@fix/webhook-thread-name ?
hello, i've been tempted to use the latest version currently available on the master branch
so uh, would that be a bad idea and how much?
It is very much stable rn iirc?
Unless you really need a feature in it, you don't need it
I dont know of any bugs that are on master but not on stable.
Yep I’ll try that rn
Honestly I was really sleepy I might have messed up smth
so really strange but when using ur commit i got this error:
File "/home/container/commands/backup/__setup__.py", line 1073, in load
await loading_methods.pop(task)()
File "/home/container/commands/backup/__setup__.py", line 786, in _load_webhooks
channel: discord.TextChannel = await self.bot.get_or_fetch_channel(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/utils/client.py", line 126, in get_or_fetch_channel
self.get_channel(channel_id) or await self.fetch_channel(channel_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 1875, in fetch_channel
data = await self.http.get_channel(channel_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 371, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
which doesnt really make a sens because you didnt edit this part right
(i think i know, its because my commit is not in yours so i cannot really create any other channel which give me a missing access )
Ok honestly I have no idea what I was doing yesterday. I'll take a better look when I have time and try to actually get this to work
no i think its just because it miss my commit
let me just add ur thing to mine so i'll test that
Wdym
so my commit permit me to create channel with everything, when im using yours i cannot create the channel (raise an error) and so later in my code it cannot get the channel
I'll just try to reproduce and fix it later
so since it was not very clear, ur commit might work, im gonna test it right now using the appropriate way
ok so after test in the right condition i get this error:
| File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1818, in send
| data = await adapter.execute_webhook(
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 225, in request
| raise HTTPException(response, data)
| discord.errors.HTTPException: 400 Bad Request (error code: 50109): The request body contains invalid JSON.
tell me if you need more info or something like so
No I just did bs yesterday also cause I didn't test it
Hello guys! How to create context commands available in private messages with any user in discord? If I click on user in dm I see the "apps" menu, so I suppose it is possible. Any relevant link or article will be highly helpful =)
been waiting for application emoji support for 8 months now 🥲
we're all waiting for 2.7
how many times have you said that in the last 24 hours
always in response to someone else asking for something 2.7
so it's clearly needed
only 3
Hi, I would like to use my database content (which stores specific STRING => discord categories IDs), to let my user choose a STRING from a list and let my command use the associated ID.
Can anyone guide me to an example on how to use dynamic choices list/dict returned by a function as a command choices ?
use autocomplete
discord.AutocompleteContext
discord.AutocompleteContext.bot
discord.AutocompleteContext.cog
discord.AutocompleteContext.command
discord.AutocompleteContext.focused
discord.AutocompleteContext.interaction
discord.AutocompleteContext.options
discord.AutocompleteContext.value
discord.Bot.get_autocomplete_context
discord.commands.context.AutocompleteContext
discord.ext.commands.Bot.get_autocomplete_context
Here's the slash autocomplete example.
Ty
Hello! Are there some guides about monetisation in addition to the one by Discord? Examples are fine too.
Currently have this code
class Points(commands.Cog):
def __init__(self, bot):
self.bot: commands.Bot = bot
self.request_channel = 1358740210153951336
self.history_channel = 1358740224431358114
class RequestView(discord.ui.View):
def __init__(self, User, Amount, Reason, Proof, timeout=None):
super().__init__(timeout=None)
self.User = User
self.Amount = Amount
self.Reason = Reason
self.Proof = Proof
@discord.ui.button(label="Accept", style=discord.ButtonStyle.green, custom_id="accept")
async def accept(self, button: discord.ui.Button, interaction: discord.Interaction):
if "____v[Executive]v____" not in [role.name for role in interaction.user.roles]:
await interaction.response.send_message("You do not have permission to use this command.", ephemeral=True)
return
embed = await utils.request_embed_builder(user=self.User, amount=self.Amount, reason=self.Reason, proof=self.Proof, colour=discord.Color.green(), status="Accepted")
self.disable_all_items()
await interaction.edit(embed=embed, view=self)
database.add_points(self.User.id, self.Amount)
embed_his = discord.Embed(title="Points Added", color=discord.Color.green())
embed_his.add_field(name="User", value=self.User.mention, inline=False)
embed_his.add_field(name="Points", value=self.Amount, inline=False)
embed_his.add_field(name="Added by", value=interaction.user.mention, inline=False)
embed_his.add_field(name="Reason", value=self.Reason, inline=False)
embed_his.timestamp = discord.utils.utcnow()
embed_his.set_footer(text="Points Management System")
await self.bot.get_channel(self.history_channel).send(embed=embed_his)
return
-# using seperate msg cuz char limit
However in the button i cannot access self.bot due to it being in the view class i believe.
What should i use instead?
Interaction.client is the bot
Ty
is it possible to have a coroutine in dynamic cooldowns?
or is there a way to manually assign cooldowns to a command instead of using the decorator?
are these slash commands or prefix commands
slash
i can't guarantee it works, but you can try command_func.__commands_cooldown__ = DynamicCooldownMapping(cooldown_func, bucket_type)
it can't be an async function, so you'll have to work around that
ah
command decorators also support the cooldown kwarg
probably easier
yeah but how can i work around that
Eh you can use bot.loop.run_in_executor
oh that's the way i am currently using rn, i thought there will be more efficient ways
Not particularly
The "efficient way" is changing the entire context to async, if you care to rewrite that part of your library files
So there is no need to pass self.bot to the class ?
Yea
you can pass the bot object to the view if you want too, whatever you prefer
I don't think we have any other guides, sorry
No problem. I'll see what I can do with the documentation available. Thanks for the reply!
my slash commands are not showing up, using debug_guilds and application.commands scope enabled
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
Ctrl+R(orCommand ⌘ + R) - Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
Also debug_commands is not as needed anymore as commands registration no longer takes a long time
Just make sure to restart your discord
still not showing up, I have a working bot already and commands are visible. I created copy of the same bot with different app on developer portal to test my codes to not test on main one
removed debug guilds its still the same
did you invite the bot with application.commands scope?
I did
Show your code
how do I change a role color through a bot?
I kinda cooked this up but have no idea how to actually tell the bot "hey this is a role"
....nevermind
nvm I'm still clueless as to how to get the role?
did guild.get_role not work
oh, guild.get_role exists, but the question is how do I get the guild now?
smth like... ctx.guild()?
ctx.guild
oh interesting, thanks
or is it always a specific guild ID you need
should be fine
no
it's a one-off, my discord broke so I have to use a bot to edit my own roles
found that the hard way, now: how to do intents again
that is the full error
it's likely your bot's top role is below the roles you are trying to edit
pretty sure that's inheriting from something no?
allgood
IT WORKED
nice
coding exercise to fix a discord bug over, thank you a lot
please use the docs and your IDEs autosuggest, dont just guess attribute names
issue is my IDE does in fact, not autosuggest for whatever reason
also for whatever reason I struggle to read/understand docs
VSC?
ya
of course
learn to, its a vital skill when programming
ya, I try to, funnily enough PyCord docs are ones I struggle with the most
why? its very well documented
oh yeah, it is very well documented, but the layout somehow messes with my brain
it's purely a me issue dw
I think it's just the fact everything is laid out at once instead of you uncollapsing things you need?
so I get distracted reading other entries
lol
Use pylance
Basedpytight better
That sounds dirty
Anyone else having issues running their bots at the current moment? Was getting outright connection issues, but now pycord just is never going 'ready'
(and messages here are slow to post, so I'm guessing there's an overall issue)
So I was starting up my bot and ran my help command that had worked before but now is not and I am not sure why I did check the code but do not see anything wrong.
Ignoring exception in command helps:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 122, in wrapped
ret = await coro(arg)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 825, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/container/cogs/NewHelp.py", line 162, in helps
await ctx.respond(embed=Help_Embed(), view=HelpOptions())
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 641, in send_message
await adapter.create_interaction_response(
File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 213, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options.4.emoji.id: Invalid emoji
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1098, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 331, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 128, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options.4.emoji.id: Invalid emoji
That is the error I am getting
class HelpOptions(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(discord.ui.Button(label="Invite Me!", url="Bot invite here", row=1))
self.add_item(discord.ui.Button(label="Support Server", url="Support server invite here", row=1))
@discord.ui.button(label="Delete", style=discord.ButtonStyle.red, emoji=":no_entry:", row=2)
async def delete_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.message.delete()
@discord.ui.select(
placeholder="Select a Category!",
min_values=1,
max_values=1,
options=[
discord.SelectOption(
label="Econamy",
description="Econamy commands",
emoji=":wrench:"
),
discord.SelectOption(
label="Config",
description="Configure the bot",
emoji=":wrench:"
),
discord.SelectOption(
label="Fun",
description="View all Fun commands!",
emoji=":magic_wand:"
),
discord.SelectOption(
label="Misc",
description="View all normal and mod commands!",
emoji=":robot:"
),
discord.SelectOption(
label="Moderation",
description="View all MOD commands",
emoji=":modlogo:"
)
])
async def select_callback(self, select, interaction: discord.Interaction):
if select.values[0]:
await interaction.response.edit_message(
embed=discord.Embed(
title=f"{select.values[0]} Help!",
description=cog_help[select.values[0]],
).set_footer(
text="Use help <command> to get additional help on a specific command."
)
)
@slash_command(description="Gives a list of commands and what they do")
async def helps(self, ctx):
await ctx.respond(embed=Help_Embed(), view=HelpOptions())
There is the code
:modlogo: is not a default emoji
