#Basic Pycord Help
1 messages · Page 35 of 1
Permissions aren't intents
go to Bot > Privileged Gateway Intents
oh wait its right above that
yea just scroll up
oh I am stupid
also is there any way to make a message get sent in a certain channel at a specific time of day?
Unclear
Basically the @tasks.loop are some kind of while
so you can add a parameter for it run only at this time
what about it
i think he didnt read the whole guide but only the example
You can also pass in a datetime.time object or a sequence of them in the time parameter which will make it run at the specified time(s).
the datetime part
or just google "python datetime" and you'll find enough
get a channel by ID and .send() using it
i might be to late
that doesn't seem like a datetime.time object
it should be, strptime return a datetime out a str
i didnt wirte the import from datetime import datetime
it takes a datetime.time, not datetime.datetime
i see
that confuses me
thanks for the correction
what part
everything
so ```py
partial_channel = bot.get_partial_messageable(id)
await partial_channel.send(...)
if you do it in a cog and have the task properly defined you can just do
channel = self.bot.get_channel(channel id here)
await channel.send(...)
lol
i've never seen partial_messageable used ngl
when should you use it over get_channel
you forgot it could be None, so you would need to get_or_fetch it
right
you don't need the full channel object to send a message
it exist for the channel ?
self.bot.get_or_fetch_channel ?
and get partial handles that?
partial is just a partial object. It doesn't have any information about it other than ID basically
and that is enough to send a message
nope doesnt exist
ah ic
so you can just send on that regardless of the channel being cached or not?
yeah, you still have to handle the channel deleted case yourself tho
well if its deleted you have different problems /hj
also why does all fetch return None, except the channel return an error ? is that a reason ?
edge cases are stupid I agree
what do you mean?
yes
do not build anything into your bot that handles anything but the best case
become lawless
if i do self.bot.fetch_channel on a delete channel, it will raise an error
All fetches make an API request and will throw an error if x does not exist
role = interaction.guild.get_role(int(role_id)) or await interaction.guild._fetch_role(int(role_id))
get relies on cache
this doesnt
I do not get datetime
get_or_fetch_user too but i think its different
To make it better, time in any way shape or form is every developer's hell
yeah because it's a private method
I do not understand
examples/background_task.py lines 28 to 33
@tasks.loop(
time=time(3, 0, tzinfo=timezone.utc)
) # Task that runs every day at 3 AM UTC
async def time_task(self):
channel = self.get_channel(1234567) # Your Channel ID goes here
await channel.send("It's 3 AM!")```
i will send u what i want to know if that possible to u in a minute
hah! get channel prevails! /j
this makes no sence
e
as i said, time is hell for most developers :)
but yea, check this
what are you confused about
the example uses from datetime import time
I copied the code and it doesn't work
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
# suggestion possible ?
#member :
await bot.get_or_fetch_user() # -> raise no error and return None
#role
role = guild.get_role() or await guild._fetch_role() # -> raise no error and return None
#channel
channel = bot.get_channel() or await bot.fetch_channel() # raison error
#fix :
try:
channel = bot.get_channel() or await bot.fetch_channel() # raison error
except:
channel = None
# suggestion1:
await bot.fetch_channel() do not raise error
# suggestion2:
await bot.get_or_fetch_channel() # -> raise no error and return None
why, what part, error etc etc
it'll only run at 3am utc
need to explain more we are not magician
is it 3am utc for you?
yeah because get_or_fetch_channel() doesn't exist and guild._fetch_role() is an internal method
(someone know the command ?)
I know but does a get_or_fetch_channel() can exist ?
and maybe also a get_or_fetch_role
File "d:\Rembot\bot.py", line 203, in <module>
@tasks.loop(time=time(3, 0, tzinfo=timezone.utc))
^^^^^^^^
NameError: name 'timezone' is not defined```
probably also directly imported from datetime
that's what utils.get_or_fetch() is meant to accomplish
channel = utils.get_or_fetch(discord.Channel, channel_id) doesnt look really good compared to the base get_or_fetch_member but i think i can still do member.get_or_fetch_channel = function that will use utils.get_or_fetch
from discord.utils import get_or_fetch :)
5 characters saved
how do i change the datetime timezone?
put a different timezone there i'd guess
"doesn't work" is a most terrible description of your issue
what doesn't work, why do you think / know that
I have it set to send at a certain time but when that time comes it doesn't send
did you start the task?
yes
show your code
do you know what UTC is?
no but like you have to do get_or_fetch(discord.Channel, channel_id) or something like that and not only put the id.
yeah
I am in utc+2
it is in silly squids code
please learn how utc works
that might be, but you also failed to copy it properly
you forgot the self parameter in the task function
?
if you are not using a cog, pls remove the self.bot and only use bot.get_channel
oh wiat
it is 15:26 in utc rn
also are you starting the loop with qotd.start() ?
they said they do
google UTC
ok mb
I took my time and added 2 instead of subtracting 2
sorry, I expected people to pass 5th grade math
I think someone has trouble with equations, then computer science may not be the field for them
he wants to do computer science ?
instanceof("programming", computerscience) = True
but also everything will be difficult
math are everywhere
like illuminati !!!
pycord has an event that checked if user used a command? I mean something like this:
on_use_command or something like that
on_application_command for slash commands
do not use that with @bot.event though, make a listener
sure thanks
is there a way to refresh discord slash commands cause I hate having to wait after making a slash command
restart discord
alr
ctrl+r
ty
how do I create a channel with a bot? I've never done it and I don't see it on the docs
anc give roles*
and*
and how do I see if a user has a role 😐, im kinda asking for a bit but the docs aren't very well written (no offense to anyone I just think it leaves out a lot)
it is at the docs
where?
I searched up role, give role, channel, create channel
search for it
i did
depends on the context
i mean context in the literal sense, not in code
gotcha
inside of a category
and a text channel
this category is in the guild that the command was invoked from?
yea
i see ctx.guild.create_text_channel
how do i reference the category?
is it like ctx.guild.get_category or smth?
what do you gonna do if you dont have ctx?
i do have ctx
categories are also just channels internally
you can use ctx.channel.category
^^ if you wanna create it in the category the command invoked in
if not, you need to get the category
ye, i just want to get it
it's already there
this bot is only for my server so wont be in any other servers so it will always be there 100% of the itme
time*
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 ...
probably just fetch it to be safe
or better yet, run a check if its none, and if it is, then fetch
always good to fetch conversatively
(or use discord.utils.get_or_fetch to make that one line)
ratelimits aren't a problem here
Yea, but if its already cached, why not use that
quicker, if anything
I started to do all the time get and fetch
yea it's nice but you can't always use it
hmm, the category doesn't seem to work
that is right
im doing this await guild.create_text_channel(f"{user.name}s-cell", category=guild.get_channel("1234883417217302619")). It's creating the channel but not in the category
it should be an int not a str
you did ""
duh, lol
and user.name can have illegal characters so be aware of that
what happens in that case? are they ignored, or will it fail?
throws a 4xx iirc
wait, don't pomelo usernames use the same charset as channel names now?
no space, only a-Z and 1-9, dashes, underscores?
and .
hmm, how about removing roles from someone? how would I do that
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 are useful :)
A lot of stuff is with get and fetch
edit :)
whats the difference between a member and a user
how do I get a member from a user?
A user is just a plain user
A member is basically a guild-user
you can go member > user but not reverse
oh yea that makes sense
but member has everything a user has anyway iirc
what is snowflake
an ID
read the documentation :)
but i'd just use edit because the lsit of roles you pass there is what the member will have after the fact, so if you pass an empty list, it removes all the roles instantly
ah
really the best advice i can give you is to use the docs, a lot
sometimes you need to think a little, like if a ban function is on a member or a guild (actually both in the case of ban in particular, nice example
) but you can really find everything you need on the docs, what type everything needs to be, etc
How to pycord
pycord is an ffmpeg wrapper
how can I make my buttons persistent view when my class takes parameters?
class ManualReview(discord.ui.View):
def __init__(self, primDept, secDept, dob, age, firstName, lastName, primCallsign, secCallsign):
super().__init__(timeout=None)
self.primDept = primDept
self.secDept = secDept
self.dob = dob
self.age = age
self.firstName = firstName
self.lastName = lastName
self.primCallsign = primCallsign
self.secCallign = secCallsign
@discord.ui.button(label="Accept", style=discord.ButtonStyle.green, custom_id="manual_accept")
async def accept_callback(self, button, interaction):
await Onboard.onboard(self, interaction, self.primDept, self.secDept)
...
@discord.ui.button(label="Deny", style=discord.ButtonStyle.red, custom_id="manual_deny")
async def deny_callback(self, button, interaction):
...
Learn all about implementing buttons in your Discord Bot using Pycord.
when using the View i'm doing
self.bot.add_view(ManualReview(self.primDept, self.secDept, birthday, age, firstName, lastName, primCallsign, secCallsign))
await logs.send(f"{interaction.user.mention}", embed=embed, view=ManualReview(self.primDept, self.secDept, birthday, age, firstName, lastName, primCallsign, secCallsign))
but its not working
I cannot just do bot.add_view() because it takes parameters
i dont see why thats a problem
because the parameters are variable to a command, how am i supposed to set it on initilization
add the view to the bot when the command is called
i do, yet it doesnt work
the buttons dont work when I restart the bot
you are creating a different view lol
yea, dont
pass the view you made
vooiw = ManualReview(self.primDept, self.secDept, birthday, age, firstName, lastName, primCallsign, secCallsign)
self.bot.add_view(vooiw)
await logs.send(f"{interaction.user.mention}", embed=embed, view=vooiw)
yea
the buttons still dont work when the bot restarts
Here's the persistent example.
still doesnt support my usecase
hm i htink what i said was actually wrong, apparently it works differently and you dont need to pass exactly the view you made
mb
?
class ApplicationModal(discord.ui.Modal):
def __init__(self, primDept, secDept, bot, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
bot is being passed from a cog
did you also do self.persistent_views_added = True
that looks unrelated
i dont think that does anything
might be important 
tbh i never did persistent views so thats about all i can tell you
in the example its just a bool to track which views have been made persistent
it doesnt actually do anything outside of their use
ah yea
yea idk
what if you just create a dummy version of your view with whatever parameters and add it to your bot in the on_ready, and then in the command you make the version of the view you want
should work i think
i can try to just supply None
if your view still is made then
yeah it didnt like it
2024-04-30 19:54:26.046070 | loaded cogs.verification.verify
Traceback (most recent call last):
File "F:\Coding\[bots]\SOFLRP\bot.py", line 32, in <module>
client.add_view(ManualReview(None, None, None, None, None, None, None, None))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Coding\[bots]\SOFLRP\cogs\verification\manual.py", line 9, in __init__
super().__init__(timeout=None)
File "C:\Python311\Lib\site-packages\discord\ui\view.py", line 183, in __init__
loop = asyncio.get_running_loop()
^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop
yea idk, everything else would be guessing
maybe someone else knows
its definitely possible tho
yea
Hey guys, I keep getting 'NoneType' object is not subscriptable, any ideas?
the AddBalance and GiveItem arent breaking it btw
something is none, what that is is in your error
yes, it is
no
else python wouldn't explicitly say it's none
it wasnt
i was doing a try catch
give me a sec
im removing it
i was printing it in console
no clue what those are
oh wai tnvm
hold up
thats the part of the error that isnt useful
nvm fixed
yea i just realized that
hello, how can I make autocomplete with guild channels like this?
why use autocomplete, you can just do input_type = discord.TextChannels
TextChannels doesn't exist and TextChannel does nothing
Why it does nothing ?
idk
Did you restart ur dusxord
Also you should use the decoration it will be easier for you and better looking. If you want to keep ur thing without decorator I will check why it doesn’t work for you
Here an example for using decorator
@commands.slash_command()
@discord.option(name="member", input=discord.Member, required=False)
@discord.option(name="round", input=int, default=1, required=False)
async def rockpaperscissors(self, ctx: discord.ApplicationContext, member: discord.Member, round: int):
thanks
I've tried and it works with decorators.
but how do I make the name parameter be different from the variable in the function argument?
ah, there is a parameter_name...
Yep or you can use the name localization if you want to have different name for each country
Does anyone know how to help? I want to make a persistent view with a class that takes parameters, and I can’t just do bot.add_view(ManualReview()) because if the parameters
you would need to store the custom parameters in a database and load them when you are creating the view
Their issue is, i think, that the view needs kinda "working" parameters, and not just a bunch of empty strings for example
I tried helping them yesterday but i got stuck at that, my last idea was also just to pass any parameters but i dont think that works for their views
I dont have time to do a deep explanation but you should probably create a help post and ping me their and I will get back to you later
When I get a chance I will
is there an official lib for testing bots? I found dpytest on github but that doesnt seem to have much work done recently. How does one write their unittests properly?
honestly i doubt you need unit tests in the scope of discord bots
usually its enough to just test your commands with a few inputs and make sure nothing dumb can happen
I have like 20 different functionalities it is taking over and with every line of code I write I feel fear to break something
wdym
If I improve a game or something I want to be sure I didnt break a part of it in the process
make an error handler that sends any error into a channel on your server
and test it yourself as much as you can
well undesired behaviour might still occure without it fully breaking. So I guess the answer is no real unittesting library?
i wouldnt know of one, maybe the others do
alr thx nevertheless
we do not have an official lib for unit tests
It's there a way to get the current ping with the gateway?
i use {round(self.bot.latency * 1000)}ms but not sure if thats the exact right one
but i labelled it "API latency" in my command so i guess it is the gateway ping
ok thanks 🙂
I was able to add it to my status page
Is there a way to get the voice channel count in a category
yes
there is no attribute but you can just sum them
And how?
like that :
voice_channel_count = sum(isinstance(channel, discord.VoiceChannel) for channel in category.channels)
checks if its a voice channel
it check if the first arg is a part of the class of the 2 arg
so if channel is a class discord.VoiceChannel
so you can use that for everything
isinstance(1, int)
etc etc
Ah okay thanks
Didnt work
Today the task repeated again
It repeats after the first time
Like the first task works great, the seconds sends two times
is there a way to get the user from AutocompleteContext
which user?
command sender
check the docs for the context stuff especially
way faster than asking here
and you learn new stuff too
yea i did, coudnt find it
couldnt*
just search for autocompletecontext
when I do something like deleting a channel, adding roles it requires the person who ran the command to have permissions to do that. Is there a way to bypass that?
i did
don't add the discord. infront
I did too just now and it's right there
there was no author
oh
what the flip
im blind ⁉️
that's not default behaviour, only the bot has to be able to do that
oh?
really?
lemme test that
Autocompletecontext, not ApplicationContext
for autocomplete it's ctx.interaction.user
unless author is an undocumented shortcut
I was reading applicationcontext x3
ok its interaction
Open à post post ur code and the issue and ping me I will look at that later
#1235497796694704208 is there a way to do that with bridge ?
Whats the command for /ping?
its {bot.latency} 
ok
@bot.command()
async def ping(ctx):
await ctx.respond(f':ping_pong: `{bot.latency * 10000}` is the ~~bot~~ app ping!')
```?
you did 1_0000 not 1_000 ;3
btw you can do a _ at big numbers
ik that trick
like ```py
number: int = 1_000
also, that will be in ms
(with 1000)
thats what I want, ms
yea just so you add it after the number :)
erm how do I run a while true loop with the bot still online?? I did it with threading but it still doesnt work
for what?
just some code that i need to run every few seconds
what does it do
it simulates a stock market
its not relevant to the solution though
ah
you can use tasks for that
Here's the background task example.
yes
k
now what if I wanted to have it do something every 5-20 seconds
but its random
can i just put a random.randint in it?
no
how should I do that then
you can change the interval of tasks though
ah
One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for: How...
so just make another task to change the other one's interval
am I doing this wrong? nothing is happening
do you start it?
oh, how do I do that
all here
nvm i see
why am i getting this error when trying to fetch a channel?
File "C:\Users\path-to-venv\venv\Lib\site-packages\discord\client.py", line 1805, in fetch_channel
data = await self.http.get_channel(channel_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\path-to-venv\venv\Lib\site-packages\discord\http.py", line 285, in request
async with self.__session.request(
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: '_MissingSentinel' object has no attribute 'request'
show the line in your code that causes that
can you run pip list in your console and post the output here
a2wsgi 1.10.4
aiohttp 3.9.3
aiosignal 1.3.1
annotated-types 0.6.0
anyio 4.3.0
attrs 23.2.0
beautifulsoup4 4.12.3
blinker 1.7.0
Brotli 1.1.0
certifi 2024.2.2
charset-normalizer 3.3.2
click 8.1.7
colorama 0.4.6
DateTime 5.5
Discord-Anti-Spam 1.8.1
fastapi 0.110.1
Flask 3.0.3
frozenlist 1.4.1
fuzzywuzzy 0.18.0
gunicorn 22.0.0
h11 0.14.0
idna 3.6
itsdangerous 2.1.2
Jinja2 3.1.3
keyboard 0.13.5
lxml 5.2.1
MarkupSafe 2.1.5
multidict 6.0.5
mutagen 1.47.0
ngrok 1.2.0
packaging 24.0
pip 24.0
py-cord 2.5.0
pycryptodomex 3.20.0
pydantic 2.6.4
pydantic_core 2.16.3
pytz 2024.1
requests 2.31.0
setuptools 68.2.0
sniffio 1.3.1
soupsieve 2.5
starlette 0.37.2
sudo 1.0.0
typing_extensions 4.11.0
urllib3 2.2.1
uvicorn 0.29.0
websockets 12.0
Werkzeug 3.0.2
wheel 0.41.2
yarl 1.9.4
yt-dlp 2024.3.10
zope.interface 6.3
are you running that before on_ready?
nah
where are you running that line of code
what is Discord-Anti-Spam?
like something for an user dont spam ?
you mean an official discord thing ?
In a file other than the main one (where the bot is running). Is that the reason?
in a cog init or where? can you show the function
how the attribute bot is def?, shouldn’t be self.bot since its a cog ?
i think they run it in a cog init using the passed bot parameter so they don't need self, and all that is running when the cog loads aka before on_ready
its not a cog
not possible
show the function
It's big enough
we need some info here
i`ll try to make it shorter
do like function :
remove until the channel = await
its not called in main.py
i mean just your main file 
Please copy and paste your code here. This makes it easier for everyone helping you.
Why is it so hard to show your file
You ain't hacking the nasa and we don't care at all what your bot is about
i always forget that
@arctic plover use that
bot.py:
import discord
bot = discord.Bot(intents=discord.Intents.all())
main.py:
from bot import bot
@bot.event
async def on_ready():
print('Ready')
bot.run('token')
web.py
@app.post('/feed')
async def feed_post(request: Request):
xml = await request.body()
await youtube_handler(xml)
return Response(status_code=204, media_type='text/plain')
youtube.py:
from bot import bot
async def youtube_handler(xml):
# useless code
message = 'Any message'
channel = await bot.fetch_channel(1229836602516312104)
message = asyncio.run_coroutine_threadsafe(channel.send(message), bot.loop)
like this
This is not how you handle a bot in multiple files.
You use cogs.
wtf lmao
this is the code from the Internet, I didn`t redo it
w h a t in the HELL
I'm assuming you don't know how to code. So, learn python first then come back at developing bots.
?tag lp
Resources For Learning Python
- Official Beginner's Guide
- Shortcut to guide for people new to programming and people with experience programming
- Official Tutorial
Other Resources To Learn Python
- Automate The Boring Stuff for complete beginners to programming
- Learn X In Y Minutes for people with experience programming
- Swaroopch is a useful book
- Code Abbey has practice for beginners
- W3Schools is a good resource for general use
You have to do this when using a web application, you can't just use await
...what
import uvicorn
import fastapi
import asyncio
import discord
import threading
bot = discord.Bot(intents=discord.Intents.all())
async def main():
await bot.get_user(584650504710127616).send('hi')
app = fastapi.FastAPI()
@app.get('/')
async def index():
await main()
return 'Hello World'
def run_bot():
bot.run('token')
bot_thread = threading.Thread(target=run_bot)
bot_thread.start()
uvicorn.run(app, port=8000)
Output:
INFO: 127.0.0.1:52423 - "GET / HTTP/1.1" 500 Internal Server Error
RuntimeError: Timeout context manager should be used inside a task
you should use same loop
why threading?
To run the bot and the server at the same time ._.
it`s example
.rtfm bot.start
you dont need threading for that
It won't change anything
there is no reason to introduce threading into something that doesnt need it at all
and you end up with hellish stuff like this
(apparently)
I was just explaining why you need to use run_coroutine_threadsafe
yea, but please dont use threading
its completely unnecessary and overcomplicates things
kk
But how to fix it?
how do i populate options with a dynamic list of something for the select menu?
currently i just have the sample but i want to be able to set an arbitrary amount of options (like taking an input number, lets say 10, and then it just puts 1-10 as options)
the specific use case im trying to do is to list people in a voice channel and then display them as choices
i think the easiest way to do it is to just pass the voice channel members to the view init, and then handle creating the options there, and then just do options = choices
but there might be a better way, never did selects
ill try this out, thanks!
When I do
@bot.command()
async def start_server(ctx):
subprocess.run(f'{SERVER_PATH}\\run.bat', shell=True)
or
@bot.command()
async def start_server(ctx):
os.system(f'{SERVER_PATH}\\run.bat')
I always get this error, but that file is in the same dir as the .bat file
well, that isn't really specific to pycord
is there a correct way of doing this LOL
class PartyView(discord.ui.View):
def __init__(self, bot):
self.bot = bot
self.choices = []
for i in range(10):
self.choices.append(discord.SelectOption(label=f"Option {i}"))
@discord.ui.select(
placeholder = "Select an option",
min_values = 1,
max_values = 2,
options = self.choices
)
async def select_callback(self, select, interaction):
await interaction.response.send_message(f"Selected option {select.values[0]}")
im not sure if im just blanking but i cant seem to access choices in the init?
or maybe im just misunderstanding how decorators work 💀
pass the vc members to the view and make them the values
im not sure selectoptios work without a value
hold on
ah no the value is the label by default
but it should work the way you did it
did you restart discord after changing it
well, not technically a discord problem (maybe?)
its just that its not accessing the choices list for some reason
you can do it without the decorator
like that :
select = discord.ui.Select(placeholder=ur thing, etc etc options=self.options)
self.add_item(select)
select.callback = self.select_callback
nope, i think its more a python feature
what does mean OOP ?
object oriented programming
ok
this fixed the funky thing about not being able to access the choices from the init but now im running into weirder issues 😭
class PartyView(discord.ui.View):
def __init__(self, bot):
self.bot = bot
self.choices = []
for i in range(10):
self.choices.append(discord.SelectOption(label=f"Option {i}"))
def select_callback(self, select):
select = discord.ui.Select(placeholder="Select an option", min_values=1, max_values=1, options=self.choices)
self.add_item(select)
select.callback = self.select_callback
class Party(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command()
async def check(self, ctx, channel: discord.VoiceChannel):
vc = self.bot.get_channel(channel.id)
member_ids = [member.id for member in vc.members]
await ctx.respond(" ".join([f"{member_id}" for member_id in member_ids]))
await ctx.respond("Choose flavor!", view=PartyView(bot=self.bot))
still playing around with the logic so im not really going to put the member list in as choices before i understand wtf im doing
- You didnt super init your view
- you are missing your select decorator
relevant

nope like that
move this into your init
and do 1.
like that :
class PartyView(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
self.choices = []
for i in range(10):
self.choices.append(discord.SelectOption(label=f"Option {i}"))
select = discord.ui.Select(placeholder="Select an option", min_values=1, max_values=1, options=self.choices)
self.add_item(select)
select.callback = self.select_callback
async def select_callback(self, interaction: discord.Interaction):
like that
also keep the select callback async
you can reduce it with
select = discord.ui.Select(placeholder="Select an option", min_values=1, max_values=1, options=[discord.SelectOption(label=f"Option {i}") for i in range(10)])
and to access to the value i know but label idk,
value is like that :
value = interaction.data["values"][0] for one choice and values = interaction.data["values"] for multiple
but dont dropdown choice need a value ?
no
nope, only label
i said this above already
value defaults to the label
also its really easy for the choice to put member
They only want the members in a certain voice channel, not simply a member selector
here, you can replace the choice by a discord.ComponentType
ooo
so no that will not work
but to do that that view need to be added constantly to put the channel_id or something like that
just pass the channel members to the init
i doubt the view has a lifetime of more than a few seconds
yep if the view doesnt last that not quit difficult
I was going through the docs, still couldn't figure it out, how to respond to slash commands with ephemeral response? (which is only visible to the user who issued command)
I tried ctx.respond("Message", ephemeral=True), no luck
Thats the way. How it doesnt work?
it's sending normal messages as response.
Are you deferring the interaction?
yes
You must pass ephemeral=True to ctx.defer too
What
if i have more than 100 msg, only 100 are deleted
The max per request is 100.
You should purge the channel twice if it's more than 100.
its WAY more than 100
Hoy can i handle that?
Can i loop the history until is no longer >1?
hey guys!
I got an unstable behavior with if bot.user.mentioned_in(message):
it works well when I reply to a bot message(so context will not contain the mention info, but message.mentions will contain the bot as a member).
it sometimes doesn't work when I mention my bot with '@' sign.
Python debugger shows <@&1234> while bot's id is not 1234.
However, when I paste <@&1234> to discord, it's converted to my bot name correctly.
Why does a bot have two different id?
Need some help. 🍻
That'd get you ratelimited very quickly
You can try splitting the purge
Hmm, bots used to have different IDs like very very very long time ago. Have you tried fetching that ID to see if your bot object is returned?
it does.
I've noticed that @sign results a '@&' token rather than a normal '@' token.
@& are roles
Youre probably mentioning your bot's role, not the bot itself.
I've been laughing for 2 minutes. 
Is there an easy way to find out which invite code a user used to join the server?
Because the member object doesn't have this information, does it?
Nope
You can just store each invite to see which one has gotten 1 more utilisation
The thing that I don’t understand is why we can’t access to the invite code because on discord we have something to do that, the new thing
not with bots (yet)
I think they will not add it to bots. They have dealt with a lot of abuse with invite tracking and such.
Yo, guys, I can't seem to find a menu in pycord's documentation in regards to messaging users privately, is such option even available with pycord? Because the standard method of using await member.send("Text") doesn't really work for me. and responds to my command with Uknown integration message
you need to do both
respond to the interaction
and send the message
with that : await member.send("Text")
you only send the message in private message, but you dont answer too the interaction
Thanks <3
Which pycord version supports wavelink?
it’s which version of wavelink supports pycord
so which?
all of them
Summary Wavelink does not work with py-cord because of discord.py Reproduction Steps I did pip install wavelink then discord.py was installed automatically Expected Results The wavelink works with ...
yeah, exactly
at least the recent ones
wavelink works, it’s just the guide’s outdated
so i don't get it, wavelink needs discord.py utils to work so it installs, but we can no longer import discord bcs we got some kind of conflict, right?
you can get around the discord issue by not installing it
there’s a flag you can set that would make it not install dependencies
so is this not true? #1132206148309749830 message
yes
okay, i got it
thank you
but wait, how it will fix ModuleNotFoundError: No module named 'discord.utils'?
you need to cleanly uninstall discord, discord.py and py-cord
then you can re-install py-cord independently
it works, thanks
It work again ?
2.5 was giving an error
While 2.4 was working
how can you refresh a page with discord.ext.pages
well how do you use paginator.refresh() would be a better question
Paginator.refresh doesn't exist
What are you trying to do?
Link the documentation to that.
It's probably not stable.
What are you trying to do that makes you think you need to use that
so basically I've setted up pages that will show information about specific users but the page need to get the information from a seperate json file
and when i use the command to show the pages it shows the information entered before the bot started not the updated one
sorry if my explanations aren't that clear
this is View.refresh for handling components, unrelated to paginator
how are you loading the pages
because ideally whenever you use the command you should be making a new Paginator
import discord
from discord.ext import commands, pages
from discord.commands import Option
class Case(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.pages = [
[
discord.Embed(title="Mutes", description=""),
discord.Embed(title="Warns", description=f""),
]
]
def get_pages(self):
return self.pages
#commands...
def setup(bot: commands.Bot):
bot.add_cog(Case(bot))
You should create your pages on each command invocation.
That's how you'll get the latest data from your json.
thanks
is message id unique to discord as a whole or only to guilds??
i mean can 2 separate servers have the same message id
To discord
Every id is unique
JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!
- It's a file-based data storage, which makes it vulnerable to race conditions
- You'll need to implement your own synchronization primitives to avoid corrupting data
- If you're not careful, you could accidentally wipe your entire JSON file.
Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.
- Async libraries exist on pypi for each of these
sqlite --aiosqlite(or Danny's wrapper: asqlite)
postgresql --asyncpg
mongodb --motor - Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
- You can impose uniqueness constraints to ensure against duplication
- The Python libraries enforce synchronization for you
- The query language is intuitive, you can get running with simple queries in just a few hours!
hours? nah, way quicker
Is there an event that catches new messages specifically in one channel only?
No
Alr, my bad
just make an if clause
There is one issue
The list of channels I want to track is dynamic. Sometimes I add something to this list and sometimes I remove something from it. Should I update event to track new channels everytime that happens?
I am adding these channels somewhere else in the code directly to the database
Nvm, I think I can just create a list somewhere in the bot itself and add/remove these channels from there when updating.
use a database
can I run multiple pycord instances one as an API gateway and others provide different features? so users won't get affected when I'm actively coding for new features.
Is it still not possible to set a custom bot status that doesn't include "Playing" or "Watching", etc.?
It is possible.
Can you give an example or correct mine? This doesn't seem to work:
bot.activity = discord.Activity(type=discord.ActivityType.custom, name=f"Testing custom status.")
bot.activity = discord.CustomActivity(name="Custom status")
Is there a way to check that a message exists?
Some kind of caching must be going on because my bot is thinking that a message still exists after being deleted
try to fetch it
yes, your bot caches a lot of stuff
I don't think you can fetch messages
discord.abc.Messageable.fetch_message
discord.PartialMessageable.fetch_message
discord.TextChannel.fetch_message
discord.ext.commands.Context.fetch_message
discord.Member.fetch_message
discord.VoiceChannel.fetch_message
discord.ext.bridge.BridgeExtContext.fetch_message
discord.Thread.fetch_message
discord.Webhook.fetch_message
discord.ext.bridge.BridgeApplicationContext.fetch_message
discord.SyncWebhook.fetch_message
discord.ApplicationContext.fetch_message
discord.User.fetch_message
discord.DMChannel.fetch_message
discord.GroupChannel.fetch_message
how to create command groups inside cog?
Here's the slash cog groups example.
@cobalt comet
no, i mean message command groups
Idk if they also have groups
yes, it is in the guide
how do i do this part inside cog?
that is at the slash command tab
where is it at the guide?
no it is said that it's for message commands
here
like what's the decorator for command group inside cog?
for the message command it is a good question
i found out that BridgeCommandGroup does exist lol
Message command = prefix command ?
yes
Here's the bridge commands example.
This will help u
just a quick question so the discord.ext its just normal discord import?
its discord.ext
that's not what they're called
message commands are something completely different
how many inputs i can add to modal?
i checked and its 5 if i want more then 5 then i need two modals?
yea, but at that point i'd consider if modals are the right choice
why do you need so many different inputs
for a ticket system
well, you cant follow up a modal with another modal instantly
so i think you have to make it another button press or whatever you do rn
or you combine multiple things into one textfield
text x5 max
yh yh
ok thanks
A good way to "hide" this drawback is to have the button actually serve a purpose instead of just saying "continue" you could have 2 buttons, a confirm and an edit for example
pycord still isnt good with python 3.12 right
why?
because i need the exception module from sys lib and its in 3.12
so i can move to 3.12
that's what I'm saying
Do I really have to pass bot instance to every view with buttons I create?
class Report_vent(discord.ui.View):
def __init__(self, bot):
self.bot = bot
super().__init__()
Can't I just do something like this?
report_channel = await interaction.fetch_channel(REPORT_CHANNEL)
without doing self.bot.fetch_channel xd
No
an interaction object does not have a fetch_channel method
and how many views do you have that this is an issue lol
also the naming convention for classes is Pascalcase, not a mix of snakecase and making the word capital
i changed and now i have no module name discord
well, install py-cord lol
i have
you do not
If you install a new version of python it does not have any modules
and this is most likely still using your python 3.11
you should use a venv anyway, if you don't already
i have venv
include-system-site-packages = false
version = 3.12.3
from the venv file
I don't think it's working then
you maybe know how to fix this?
fix your venv I suppose
because I don't think it's working right
and uninstall python 3.11 to make sure there's no weird stuff
interaction has interaction.client which is the bot object
I'm refactoring my bot from a single module into cogs, and in the cog i'm testing, None is suddenly being returned from self.bot.get_channel when previously it was returning the channel object, what are possible reasons for that? Could it be missing intents or something? from not passing the bot object to the cog correctly? I went into a debugger and checked its value:
>>> self.bot.intents
<Intents value=3276799>
Any way to edit a message of an expired interaction? (the 15 minutes limit)
The interaction is responded as it should but the command could take more than 15 minutes and can't edit it past it:
HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
save the response message
that channel just isn't cached
Usually happens when your get runs before on_ready
oh hmm, so the cog loads before on_ready?
yes
i think you can use await bot.wait_until_ready() in the cog init
I'm not sure if that works but it should
i'll look into that, thanks
Actually, it might get stuck lol
Because it loads the cog but the cog load gets delayed until the bot is ready which never happens
Well, tell me what happens, I'm curious now too
haha i'll let you know then yea
oh wait, the cog's __init__ method can't return a coroutine, so I can't call that function at all
heh
honestly i just run the get_channel in every command i need it in, i never did it at cog level, so not sure what the best solution is for this
yea I was originally just invoking it at the moment when I actually needed the channel, I've only changed it to being defined in the cog's init method because I figured if i could get away with just calling it once i might as well
but it's already cached, so i suppose it's not a big deal
yea maybe someone else knows the best way to do it at cog-level like this
changed it back to invoking it when i need it and it works again, so you were definitely right about it not being cached yet. thanks for your help @sage tendon
np
Does anyone know if its still possible to make command groups with a main command? So like
/command -> Does some thing
/command add-> Does something else
/command remove -> does something else
dont think thats possible or has ever been possible, no
yep its not possible
When someone creates a forum thread
Does pycord fire on_thread_create() event?
How can I differenciate between threads in a text channel and in a forum channel?
check the parent channel type
yes
Thanks, will do
How to solve python int too large to convert to c int?
str(timedelta(seconds=round(track.length / 1000)))
what
what
well first of all i dont get the issue, and secondly, that is unrelated to pycord
- Problem in input number
- Haha, I forgot (srry)
Int too large?
I remember on an exam we had a task to count how many digits greater than 10 there are in a number converted to base25 from this base10 expression:
4 * 625 ** 2024 + 3 * 25 ** 2023 - 2 * 5 ** 2022 + 10
And python somehow managed to calculate the answer head on 😅
Am I being dumb?
Why does message.author return the bot for a slash command invocation?
Okay it was message.interaction.user
But is there a way to get the member object and not just the user?
ctx.guild.get_member(message.interaction.user.id).display_name
my god. fixed
interaction.user will be member in guilds
wasn't the case from my testing
because display_name didn't return my guild-nickname, just my global name
nah i changed it now, dw, im not touching that again :>
(i dont wanna break it)
what am i doing wrong that the options are not displaying on discord?
code:
@bot.command(description="Choose loop mode")
@option("mode", description="Choose mode", choices=["none", "song", "queue"], required=True)
async def loop(ctx, mode: str) -> None:
did you restart discord? also, required=True is not necessary
why not if it is required?
because thats the default
required defaults to true
oh, okay, i will check it and let u know
still nothing
it's like option decorator doesnt work
should i change @bot.command to @bot.slash_command?
i think you can't typehint it in the function header if you use the option decorator
but not sure
hmmm, let me check
i did some tests and nothing changes at all
remove the typehint
restart discord
try again
i dont know if this example is outdated, but there is typehint
with option decorator https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
yea ok you probably have to use bot.slash_command then
i wasnt sure because i always use cogs
i did it
strange thing, because u guys literally use bot.command in the slash commands guide https://guide.pycord.dev/interactions/application-commands/slash-commands#syntax
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
if you are using discord.Bot, then bot.command is valid
but otherwise slash_command
yes, i do
and it doesnt work anyway
lol
i will try to use slash_command and let u know
Can you try typehinting discord.Option instead of the decorator
my only idea still is that you didnt restart discord (not your bot, like, discord on your pc)
because that looks like it should work
i've done it probably 20 times (i restarted the bot many times too), i added the command yesterday, but today I wanted to use it and saw that it doesn't work as it should, that's all
it works perfectly, thank you
yeah, option decorator looks so clean
but w/e, if it works dont touch it
btw bot.slash_command changes nothing
just fyi
where are you importing the decorator from
from discord import option
try removing the command, running the bot, then adding the command back
i was thinking it was the missing type parameter, but it should default to str, so idk
okay, to satisfy your curiosity, i created another command that uses the decorator and everything works correctly, so it's probably something with commands sync, because i think at the beginning this command didn't have a choice of options
so it should work
yea maybe
one more question, for some time now when i use any command it pops up for about half a second and then i get a response from my bot, it's not a big deal but it annoys me a bit, is it the fault of my bot or my discord?
discord
any idea how to fix it? restart/relog doesn't work
do i need to reinstall?
its just a bug that discord hasn't fixed yet because weekend or something
probably gonna be fixed on monday tbh
oh, okay, thank you for help 🙂
lets say i have a button which is attached to a message with an embed, how do i get the content of the embed, footer, title etc etc
interaction.message.embeds[0]
ah okay, thank you
that throws out <discord.embeds.Embed object at 0x000001665039B910>
yeah, surely, you know how to get the information from an Embed object, right?
ah yeah nvm im a little slow, im more than a couple beers in 😅
code is best served when sober
is create_thread a correct way to create post in a forum channel? it runs without any effect. no errors, no warnings.
there's no message argument, you're looking for content https://docs.pycord.dev/en/master/api/models.html#discord.ForumChannel.create_thread
Threads with Pycord
you need to use float, int are number between a certain range so
how do you even get message for a slash command invocation since ctx.message return None
no, I get them as part of channel history for a certain purpose
Ok
Is it possible to edit a user's message?
No
I've seen a bot that like imitates a user, like my name and profile but it says APP next to it
how does that work?
That's a webhook
that's what a webhook is?
Webhooks can be used for a lot of things
Hmm. Do you have any idea how I might approach adding something like this?
no idea
alright thank you
is it true that code for discord.py has a chance at working with pycord?
less so every day
i see
pycord is a discord.py fork, but everything since slash commands were added is different
discord.py does slash commands completely differently than pycord, for the worse because discord.py's version sucks
Most of the code inside your commands should still work for the most part (you might have to change a few lines relating to how you respond) as that is mostly just python
I see. I do prefer py-cords version. Can I clarify something? I've just watched a youtube video and from my understanding, are webhooks just a way for someone to interact with a discord guild via POST HTTP requests?
discord.Webhook
discord.Webhook.auth_token
discord.Webhook.avatar
discord.Webhook.channel
discord.Webhook.channel_id
discord.Webhook.created_at
discord.Webhook.delete
discord.Webhook.delete_message
discord.Webhook.edit
discord.Webhook.edit_message
discord.Webhook.fetch
discord.Webhook.fetch_message
discord.Webhook.from_state
discord.Webhook.from_url
discord.Webhook.guild
discord.Webhook.guild_id
discord.Webhook.id
discord.Webhook.is_authenticated
discord.Webhook.is_partial
discord.Webhook.name
I see. Is it possible to create and delete webhooks entirely programatically if the bot has administrator commands?
yes
Alright, so to my original problem of attempting to imitate a user, when i wanna send a response, does this pseudocode sound right? ```
- create new webhook with username as user and profile pic as user
- create coroutine that sends a POST request to this webhook url to send the actual response
- Delete webhook
By the way, do webhooks register immediately?
wdym immediately
like you know how global slash commands can take upto an hour to register while when you set guild ids its essentially immediate? I wanted to know if this process occurs quick enough to be feasible.
And for final clarification (so sorry!), it is possible to create a webhook url in pycord only, right?
it takes like 10 seconds
Nah, slash commands never take that long
should be fine...
slash commands are virtually instant
its just a dumb thing discord said when they were released
oh i see.
it might take longer with HUGE bots but idk
.
it might seem that they take longer because the discord client is slow as hell, thats why you always restart discord after adding / changing a command
It did used to take that long, they just made it better and there is less stress of bots switching over
wdym
like a webhook is an interface where you can customize the username and profile picture, right? They each carry a URL. I understand you can create a webhook instance from a URL, but is it possible to create a brand new webhook with URL in a given channel in py-cord only? (and delete it)
i think i made a bot like 2 days after slash was added, and it took max 2 minutes or so lolw
but yea idk
TextChannel.create_webhook This is the shorcut way to do that
thank you
I'm so rusty to discord bot dev, I haven't made one in like 2-3 years 😅
all good, we are happy to help
🙂
You only need to create the webhook once
Per channel
Every time you send on a webhook, you can do it with a custom name and profile picture
But that will affect old messages via the webhook too, no?
No
When you create a webhook, the username and pfp are just default placeholders
Webhook.send includes username and avatar_url params
So if i send a message with a red pfp, and then a message with a blue pfp, and restart discord, both messages will still have their proper pfp?
Yes
I guess I need to teach a certain bot dev about that then because they are KILLING my webhook section in my server
If you've ever seen bots like tweetshift in action it might make more sense
doesn't that create a huge storage concern for discord though? i mean those pfps are essentially "undeletable"
sounds like a discord problem 
They're attached to the message itself
actually im dumb forget this
This is all a single webhook
Does a deferred message just have None as its content?
Idk if it counts as a message
I am almost certain it does, i had a few issues when a deferred message was put into the channel mesage history
You can’t really
how to get the ctx message again 💀 i hate how its not ctx.message
ctx.messagz return None
ctx.response right
Ctx.get original response
Ctx.message is user command so ctx.message can’t be the response of the bot
Cos bridge will break everything
If you defer, can you right click > copy id
Ifs its not invisible yes that true
I forgot that
Then fetch it and see what happens
The problem with this concept is that intrinsically, first response does not return anything useful
Maybe get_original_response works idk
This give the message object of the first response
Ok, a deferred message's content is an empty string
There you go
Does a defer invisible too ?
what
Does a defer invisible =True is also considered as a message ?
invisible doesn't apply to application commands
i doubt it'd be different
Wait so then if I only have to make one webhook per channel, is there a way to see if there's an existing webhook for a channel so I don't have to store a dB?
Noting all the URLs?
Like, if there's no webhook on the current channel, create one, if not, use the existing one
Nope I was thinking invisible but apparently it doesn’t exist so
invisible DOES exist, but only for components
You have an attribute webhook, guild.webhook
it hides the "thinking" text
Yep ik for component and I was thinking it was also working with command but since not my question was useless
yes you can fetch webhooks https://docs.pycord.dev/en/master/api/models.html#discord.TextChannel.webhooks
oh no you were correct
guild.webhooks fetches every webhook in the guild
didn't consider that
then you can just filter by webhook.channel
both can work
Ah, and message.channel returns a TextChannel, right? So if len(TextChannel.webhooks) == 0, I create a new webhook?

