#Basic Pycord Help
1 messages · Page 43 of 1
I dont really use GitHug
i mean venv and json are pretty similar
but a config.py like you can set variable and remove that file
so you havbe to keep ur token inside so not really secured
how to add flag emoji to SelectOption
with country code (us,gb)
filter_value = country code
dislay value = country name
emoji = 🇬🇧
no ?
got a list of countries right
its wider that that
and i just want to add the countries emoji next to the option
got it its fine
keep in mind that the limit is 25 for a string select
yeah looked that up
had to just add the top 25 countries i guess
maybe got users from max 5 of those
thanks anyway guys
Hi! Sorry to bother.```py
query("INSERT INTO strife (name, clouder, ID) VALUES (%s, %s, %s)", (name, clouderID, strifeID))
I'm trying to get this statement to work. However, I keep getting this error (passing in `('dfshfk', 315220045141770241, 'd35f21')`):```
Could not process parameters: str(dfshfk), it must be of type list, tuple or dict
What could it mean? I've tried making tuples out of different elements but i can't figure it out
For reference, these statements still work:```py
query("SELECT * FROM strife WHERE name = %s AND clouder = %s", (name, clouderID))
query("SELECT * FROM `strife` WHERE `name` = %s", (name))
```
That isn't py-cord related, you'd be better off in the python support server
My bad, thank you
#1252187716473327686 help me here pls
Resolved?
Hi there. I have a problem that my code runs multiple times, but there are only two messages in the channel:
async def fetch_messages(sellf, channel):
return [message async for message in channel.history()]
@commands.Cog.listener()
async def on_ready(self):
on_ran = False
with open('json/bot.json', 'r') as f:
data = json.load(f)
if not on_ran:
channel_id = data["marketplace_channel"]
channel = self.bot.get_channel(channel_id)
messages = await self.fetch_messages(channel)
for message in messages:
for embed in message.embeds:
title = embed.title
print(f"Embed Title: {title}")
for component in message.components:
for button in component.children:
print(f"Button Label: {button.label}")
print(f"Button ID: {button.custom_id}")
on_ran = True
This is my code. instead of 6 prints the bot prints them over and over again. Why is that?
you mean its printing the same message ?
and like at infinity ? or only a number of time
because channel.history also show some message that u cant really see like defer (and maybe ephemeral but im not sure)
Yes, but only a über of times
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
Embed Title: :gloves: |⭐️ alm do ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-alm_do
Embed Title: :crossed_swords: |⭐️ Fritz jigl ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
Embed Title: :rm: |⭐️ ani kaki ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-ani_kaki
Embed Title: :crossed_swords: |⭐️ Fritz jigl ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
Embed Title: Schicke das Bild des Spielers
Embed Title: :gloves: |⭐️ alm do ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-alm_do
Embed Title: :gloves: |⭐️ alm do ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-alm_do
Embed Title: :crossed_swords: |⭐️ Fritz jigl ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
Embed Title: :crossed_swords: |⭐️ Fritz jigl ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
this is a part of the prints
if you add a print before the for message in messages, does this print is triggered many time ?
no, only one time
solved the problem. I just restarted discord and resettet the config state of my bot
But I have another problem. I am trying to make my view persistent.
this how the head of my view looks like:
class SendPlayerView(discord.ui.View):
def __init__(self, vorname, nachname):
super().__init__(timeout=None)
self.vorname = vorname
self.nachname = nachname
self.send_player_callback.custom_id = self.generate_card_custom_id()
def generate_card_custom_id(self):
return f'buy_player-{self.vorname}_{self.nachname}'
@discord.ui.button(label='Mehr Informationen', style=discord.ButtonStyle.green, emoji='🛒')
async def send_player_callback(self, button, interaction):
the view has only one button, the timeout is set to none and the button has a custom_id, but I still get this error:
ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
Is it because of the way how I set the custom Id?
Mit custom_id=""
but then I can't pass a function. I can't do custom_id=generate_card_custom_id
That’s not how persistent views work
wdym?
pycord will only use the custom ids that were added to the bot. Any other will not work
only when they are in here: @discord.ui.button(label='Mehr Informationen', style=discord.ButtonStyle.green)?
.tag persistent
The Issue
When you send a message with a view, button for example
if your bot restarts, you will lose the ability to use this button.
How To Fix This
- Set your view timeout to
None
- By default, the view timeout value is set to 300 seconds
- Pass a
custom_idvalue to the view
- Custom ids must be unique
- Chose a custom id that has a meaning in relation to your view
- Add the view to the bot
- You can use the method
Bot.add_view(YourViewClass()) - Make sure to add the view when the bot begin ready
I know that, but I need parts of the class parameters in my custom id
I need the custom ID have this format buy_player-{self.vorname}_{self.nachname}
but that I can't do where I need to set the custom_id for the persistent
So do that
Unresolved reference 'self'
how should I do it then?
button = discord.ui.Button()
button.callback = self.callback
self.add_item(button)
sorry, but I don't understand what you mean
Instead of the decorztor
Do like that
in the init of the view?
class Backup_Config_View(discord.ui.View):
def init(self, bot):
super().init(timeout=None)
self.bot: Lumabot = bot
button = discord.ui.Button(emoji="✅", style=discord.ButtonStyle.green, custom_id=)
button.callback = self.button_callback
self.add_item(button)
async def button_callback(self, interaction: discord.Interaction):
I can’t do better on phone
You will need to do that according to ur code it’s just for u to understand a little bit
yeah, now I understand
anyone know how to get an animated banner on my bot? ive seen a lot of vids that use js but none with python as of now
using the master you should be able to edit the banner in the clientuser and put a bytes like gif
this?
nah not this nvm
using the master yes
is that possible to typehint that without using option or Option ?
async def load(self, ctx: LumabotContext, backup_id: discord.Autocomplete):
well after thinking yeah it make no sense at all, what i was meaning it do autocomplete(funct)
but i will have to use option or Option
anyone has an autocomplete example ?
for item in list
if item.startswith(userinput)
output.append(item)
its literally that simple for a dumb, non fuzzy search
well i am doing baclup_id|guild_id|time
so like i will have to make if its inside of it but how can i do for if the user select one option it then lead to a specifc thing
like it choose 1/1298U8U389/20 jun 2024
it will then choose 1
what
you can read the other selected options within an autocompletecontext if you mean that
no
so
when the user will select an option in the autocomplete, i want it return something else
f"{backup['id']}|{backup['guild_id']}|{formatted_time}"
so this will appear in the autocomplee
but i want only to return the backup['id'] as option chosen
how can i do that ?
construct optionchoices instead of appending plain strings into your output list
async def backup_id_autocomplete(ctx: discord.AutocompleteContext):
suggestions = []
for backup in result:
formatted_backup = f"{backup[0]}|{backup[1]}|{formatted_time}"
if ctx.value.lower() in formatted_backup.lower():
suggestions.append(formatted_backup)
return suggestions
so i should edit this part
like the value
yea just change the thing you append to your suggestions into an optionchoice with a value and whatever the display value is called
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
oooooo i will look at that
this save me
anyways i will need to make a better func because if the user put a number it not really relevant
did that but first doing start_with and then if in
can bot put on the camera / sharescreen ?
Hi, how can I check if a member is timed out ?
if member.timeout is None:
embed = discord.Embed(
description=f"**🎯 {member.display_name} n'est pas mute.**",
color=0xDF013A,
)
await ctx.respond(embed=embed)
return
await member.remove_timeout()
The bot don't return even if the member is not timed out.
Have you tried reading the docs?
.rtfm discord.Member
discord.Member
discord.Member.accent_color
discord.Member.accent_colour
discord.Member.activities
discord.Member.activity
discord.Member.add_roles
discord.Member.avatar
discord.Member.ban
discord.Member.banner
discord.Member.bot
discord.Member.can_send
discord.Member.color
discord.Member.colour
discord.Member.communication_disabled_until
discord.Member.create_dm
discord.Member.created_at
discord.Member.default_avatar
discord.Member.desktop_status
discord.Member.discriminator
discord.Member.display_avatar
didn't see anything about checking if a member is timed out
Communication disable = timeout
But agree that is not the best
Why does not call it timeout_until since it’s remove_timeout, timeout everywhere
.rtfm Member.timed_out
It doesn’t change anything
Why put communication_disable_until while everywhere else it’s timeout
whoops sorry, not ready to send that yet
so this doesn't throw any errors, but it also does not respond with anything. i did read the docs for on_message, but i'm still struggling to figure out why i'm not getting a response.
`import discord
import os
from dotenv import load_dotenv
load_dotenv()
bot = discord.Bot()
intents = discord.Intents.all()
...
@bot.event
async def on_message(message: discord.message):
if message.author == bot.user:
return
trigger = "suck it trebek"
if trigger in message.content:
await message.channel.send("Wonderful.")`
You need to pass the intent inside the discord.Bot
So discord.Bot(intents=
ahhh okay, thank you!
hmm now i'm getting a typeerror
TypeError: intents parameter must be Intent not <class 'builtin_function_or_method'>
intents = discord.Intents.all()
bot = discord.Bot(intents=intents)
should be report doc issue also on pycord ?
yes
done
reset or completly change ?
tried with a complete different seems to not have this
i guess the issue come if something is rate limit
then when u restart it told u that tasks before got removed
and when putting again the other token i got this issue and the cpu raise to 100
seems like a known issue
there is no difference
there is
completely change -> other bot
reset -> same bot
can someone take a look at this
My god stick to one thing
You opened a discussion, a thread, and now you're asking here
You don't understand, they really want help
i really want help
and stack overflow
bruh
it's not even officially released and you're acting like the world is going down if your issue doesn't get solved yesterday
it is on discord's official api, i am working for someone, and want to deliver the best for maintained relations
🙂
And it is specified it is still on preview which means stuff is subject to change.
Exactly
that's why I said not released
You need to specify contexts and integration_types in the command.
Example here: https://github.com/Pycord-Development/pycord/pull/2409/files#diff-c68509c6c687fbab81d7e214e2564dbd30caab0afdbde0a42f75ca969f6d8903
@young sedge
Why I have this error?
Error in TicketsSelector select_callback: 'Webhook' object has no attribute 'defer'
In this code
# Ticket Reason Selector
class TicketsSelector(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
@discord.ui.select(
custom_id="reason",
placeholder="Sélectionnez une raison...",
options=[
discord.SelectOption(label="Communication Services", description="Order a Communication Service!", emoji="🌐", value="communication"),
discord.SelectOption(label="TikTok Services", description="Order a TikTok Service!", emoji="📱", value="tiktok"),
discord.SelectOption(label="Development Services", description="Order a Development Service!", emoji="💻", value="developpement")
])
async def select_callback(self, select, interaction: discord.Interaction):
try:
guild = self.bot.get_guild(guild_id)
category = self.bot.get_channel(ticket_category_id)
await interaction.response.defer()
if "communication" in select.values:
ticket_channel = await guild.create_text_channel(f"🌐・ticket-{interaction.user.name}", category=category)
elif "tiktok" in select.values:
ticket_channel = await guild.create_text_channel(f"📱・ticket-{interaction.user.name}", category=category)
elif "developpement" in select.values:
ticket_channel = await guild.create_text_channel(f"💻・ticket-{interaction.user.name}", category=category)
if ticket_channel:
await ticket_channel.set_permissions(guild.default_role, view_channel=False)
await ticket_channel.set_permissions(interaction.user, view_channel=True, send_messages=True)
await ticket_channel.set_permissions(guild.get_role(ticket_staff_id), view_channel=True, send_messages=True)
tickets_form = TicketsForm(ticket_channel, self.bot)
await interaction.response.send_modal(tickets_form)
except Exception as e:
print(f"Error in TicketsSelector select_callback: {e}")
Wait
How would I go about creating double nested slash command groups?
eg. /tournament admin create
Here's the slash groups example.
that doesnt have a double nested example
you can’t defer and use interaction
.response_send modal
defer actually réponse to the interaction so u can’t do it again
Oh nvm, found it in the docs, I am just blind
if you mean do /group subgroup command it is
Here's the slash cog groups example.
in this one
What should I use?
don’t defer before sending a modal
like that’s just not possible
i would send the model first
then make ticket channels second
i mean his code looks like ir will be less than 3s
so just remove the defer should be okay
okay I think that "work", the error changed to Error in TicketsSelector select_callback: 'TicketsForm' object has no attribute 'to_dict'
can you show the full traceback
I think you can do e.traceback or something in the exception.
not 100% sure tho
How would I subclass a View to run a specific function every time a button is pressed? Something like on_interaction but for a button in a view.
Yeah no ik that. But the idea is to run that on all interactions with any component of the view, abstracting what component is used.
Basically in my peristent view I wanna load some stuff asyncrounously before doing something, and I don't wanna do that in every function for every button
then do that in the init
I can't run async in the init afaik
asyncio
wont that block the event loop?
2 options, you run the async stuff before making the view and pass the results as arguments or you use
.tag rie
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.
if not, make an async loader function that is called by the callback(s), unless it was already run before
just save it as self.run = True
and if that is true, dont call load() again in a callback
or this ^
I have fix some error, but I have this error Error in TicketsSelector select_callback: This interaction has already been responded to before
The code:
yeah but the view is a persistent view
oh well
I'll probably make a decorator
There is no need to defer after you send the modal. The reason for the error is you are giving 2 responses. A Modal and a defer.
That's what I'm doing rn
I was just trying to find a way to write that only once
Oh I will look that
Another question, with persistent views, is a view recreated for every interaction or is the one that is initialized kept forever
You initialized it and it is kept alive forever.
Ok thanks that's all I need hopefully
I am currently using pycord version 2.0.0 (<t:1657537200>). Is there any way to find out if updating to the latest version (2.5.0) includes any breaking changes? Thank you.
__init__.py
version_info: VersionInfo = VersionInfo(major=2, minor=0, micro=0, releaselevel="final", serial=0)
There should be very few breaking changes but looking through the changelogs will help. Let me check
https://github.com/Pycord-Development/pycord/blob/master/CHANGELOG.md No breaking changes are explicitly mentioned but it is possible that some of the removed/changed items are breaking, but unlikely
unless you use bridge there are no breaking changes I know of
Besides, if pycord adheres to semver, there can't be any breaking changes on minor versions
I haven't used bridge. If I remember correctly, the only change I made was adding a type to enums.py for StickerFormatType.
between 2.4 and 2.5 bridge got breaking changes
I will check the removed/changed in CHANGELOG.md.
Hope the robot will continue to operate normally after the update.
Thank you.
There are some breaking changes with 4 and 5
there’s this weird one with EmbeddedActivites where a few were removed/renamed
Do bots need a special intent or permission to display their presence?
My friend's bot is active on 4 servers 1 of which doesn't display bot's presence
nope, it’s just discord bug
bot can’t display presence of some server en some not in this case
So.... I want to try to use logging and dont want to see the token stuff at the file
is there a was to remove it?
I tried to play with the lvl and if I use WARNING I dont get it anymore
but warning is just the wrong one for it
when running bot and use any command for the first time it's gives me unknown interaction error
but when run the command again it works
do you use anything like time.sleep or requests?
no
there is a firebase realtime database which is connected to bot
is the database asyncio?
No
uh
help me
out of 20 times it shows unknow interaction error
and 1 time it runs without any error
GMGM!
class subscriptionCommands(commands.Cog):
subscription = SlashCommandGroup("subscription", "Update Server Subscription Settings", guild_ids=adminServer, default_member_permissions=discord.Permissions(administrator=True))
@subscription.command()
async def view(self, ctx: discord.ApplicationContext):
"View Subscribed Servers"```
I'm using Slash Command Group. Can I lock this set of commands to a specific role?
Try reconnecting to database everytime you use the command
.rie
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.
How can I lock down the group to a specifc Role
with commands.has_role()
gotcha, thanks!
I did same
I wouldn't use this for slash commands
@fresh totem better way is to do it inside discord, so it's actually hidden for everyone else
Yeah but then you don’t get any info thing, so no info about shard connection disconnection or else
And also if u use in ur code logger.info it will not appear
So I gonna write my own logging...
Well u can just add a level
Im doing that since i don’t want info from discord about shard etc and i want my own one from event
I just gonna create my own one
I added a custom level higher than info but lower than warning to then get everything about important discord
If u create a custom logging and not level else than discord u will not received rate limit info or things like that
You probably need to defer. You only get 3 seconds to respond to interactions. Things like database calls and API requests can sometimes take more than 3 seconds
.rtfm defer
discord.ext.bridge.BridgeContext.defer
discord.ext.bridge.BridgeExtContext.defer
discord.InteractionResponse.defer
discord.InteractionResponseType.deferred_channel_message
discord.InteractionResponseType.deferred_message_update
discord.ext.bridge.BridgeApplicationContext.defer
discord.ApplicationContext.defer
what's the best way to wait for a response from a guild member, in the context of a slash command? i see there's client.wait_for, but i don't believe that's what i want for this, right?
wait for it’s good if u want to send a message with a bot and the user have to shortly answer to it
You could also use modals.
hmmm
the problem is that it's not a function that's part of the ApplicationContext class
for context, i'm writing a jeopardy bot
my vision is that the bot asks a question, and then the user has 15 seconds~ to respond with the correct answer
but others can answer
so it would be looking at every message that replies to the original question
use the check attr if the wait for
I second this
the only other way without mci is to either DM the bot or ping the bot with the answer
but it won’t be a valid use case for the intent so it will be difficult to grow pass the verification barrier
i see
that's a good idea
i'll have to store the question/answer in a global scope variable
then blank it out
i'm still figuring out how i want to structure it
my larger goal is to build something similar to an actual game of jeopardy, but i'm starting out with basic question/answer functionality
because that's a lot of data to process and also a lot of complicated functionality
you need some way to organize questions and answers
and also some way to have an answer still be correct without it being verbatim
right
i've already got a database sorted
and i figure i can just set the message's content to lower and check it against the answer, lowered
any examples on how to incorporate Threads or multiprocessing? Trying to figure out how to record and play audio in a voice channel, but that would need to be run constantly and not just on commands.
hey, so i m using client + interactions + tree com,mands, is there anyway to make cogs work with that? i m kinda on 3500+ lines i cant just go back and redo xd
What is a tree command?
you should look into asynchronous approaches instead
I would love to have a pointer to where i can find examples of such
Even just trying to play a Queue of audio while the bot is still responsive to commands is making my head turn
for example Queue.get() is forever blocking
havent exactly found anything I can use thats not tasks which is limited to 1 seconds minimum
oh that makes sense(got confused), is there an easy way to just switch? :" i really wanna use cogs, etc
i have been switching every command ,etc
but i have some stupid questions xd
can i still use interactions while dealing with slashcommands or do i need to use ctx?
i m really confused between both
you can just use ctx.interaction for the interaction object
but most interaction attributes have a ctx shortcut
e.g. ctx.followup.send ≈ interaction.followup.send
i was using tree with client in discord.py
thats gonna be alot to switch
thank you btw
not really tbh
i have been trying, its not really working for me xd not even a hello :"
well, show your command code including the decorators
@pastel knot do you want to use discord.py or py-cord?
from discord.ext import commands, tasks
intents = discord.Intents.all()
intents.guilds = True
intents.members = True
intents.voice_states = True
intents.messages = True
class MyBot(commands.Bot):
def __init__(self, *, intents: discord.Intents):
super().__init__(command_prefix="/", intents=intents)
client = MyBot(intents=intents) #here i m honestly just lazy to change names
@client.slash_command(name="hello", description="Says hello")
async def hello(ctx:commands.Context):
try:
await ctx.respond("Hello!")
except Exception as E:
print(E)
#my old client code (discord.py)
class appcomm(Client):
def __init__(self, *, intents: Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
client = appcomm(intents=intents)
#with @client.tree.command(name="hello", description="Says hello")```
noooo make it back into a codeblock
like this?
no
do three back ticks followed by py to open it, and then three at the end
```py
hm
Also that is discord.py code and not py-cord
I think they know that lol
i wanna use py-cord but i can't switch xd
do you need prefix commands?
thank youu
Well if you wanna switch to pycord with slash only, delete all of the bot definition stuff except for the intents, and then do bot = discord.Bot(intents=intents)
and then it's @bot.command()
unless you use wanna cogs then it's a bit different
okay let me try
oh it worked! thank youu
so would it make a diffrence if i did that?
async def hello(interaction:discord.Interaction):
try:
await interaction.response.send_message("Hello!")
except Exception as E:
print(E)```
i mean used interaction instead?
because it worked for me and gave me a response
you should not do try except like
you have an event that gather all command error
If I define my slash command option with @discord.option can i then have a custom decorator on my command that uses *args and pycord will still know the command options because of @discord.option?
In other words, can I use *args, **kwargs on a slashcommand if options are specified with discord.option?
also shoule be ctx: discord.Interaction
i didnt really understood, can you write and example
def load_guild_or_raise(func: Callable[[Any, ...], Coroutine]) -> Callable[[Any, ...], Coroutine]:
async def wrapper(self, ctx: discord.ApplicationContext, *args, **kwargs):
guild: GuildAdapter = GuildAdapter(ctx.guild.id)
await guild.load()
if not guild.exists:
raise NotFoundError
await func(self, ctx, *args, guild, **kwargs)
return wrapper
then
# this is in a cog
@commands.slash_command(name="ping")
@discord.option(name="enable",
description="Enable or disable the ping feature",
type=bool,
)
@load_guild_or_raise
async def(self, ctx, enable: bool, guild: GuildAdapter):
await guild.disable_ping()
can I do this or will pycord crash?
the decorator load before the command so i dont think you can
even if I use discord.option?
that's a shame
you will get the option but not the response of the option
ooooo i just understood
you should do like so :
Because right now what I am doing is having a predicate check ant I hijack ctx to give him a .guild_obj
but that's messy and my type checkes gives warning everywhere
def load_guild_or_raise(func: Callable[[Any, ...], Coroutine]) -> Callable[[Any, ...], Coroutine]:
async def wrapper(self, ctx: discord.ApplicationContext, *args, **kwargs):
guild: GuildAdapter = GuildAdapter(ctx.guild.id)
await guild.load()
if not guild.exists:
raise NotFoundError
return True
return wrapper
then
# this is in a cog
@commands.slash_command(name="ping")
@discord.option(name="enable",
description="Enable or disable the ping feature",
type=bool,
)
@load_guild_or_raise
async def(self, ctx, enable: bool, guild: GuildAdapter):
await guild.disable_ping()
ooo
i think i just understood
you want to pass the guild attr
from the @local right ?
The problem is that I believe that will give pycord a function whoose signature is self, ctx, *args, **kwargs) aka wrapper
discord.ext.commands.after_invoke
discord.ext.commands.before_invoke
discord.ApplicationCommandInvokeError
discord.ApplicationCommandInvokeError.args
discord.ApplicationCommandInvokeError.with_traceback
discord.ext.commands.CommandInvokeError
discord.ext.commands.CommandInvokeError.args
discord.ext.commands.CommandInvokeError.with_traceback
discord.ApplicationContext.invoke
discord.Bot.after_invoke
discord.Bot.before_invoke
discord.Bot.invoke_application_command
discord.Cog.cog_after_invoke
discord.Cog.cog_before_invoke
discord.ext.commands.Context.invoke
discord.ext.commands.Context.reinvoke
discord.AutoShardedBot.after_invoke
discord.AutoShardedBot.before_invoke
discord.AutoShardedBot.invoke_application_command
discord.ext.bridge.Bot.after_invoke
i will not do it like so tbh so i dont really know how to do that but yeah you can do a funct that basically run everytime before
discord.Bot.invoke_application_command
this one
I'll try
yeah no
this is wrong
I'll open a more general post in #969574202413838426
I can't do it with invoke too because invoke dosen't allow me to pass additional parameters
lmfao
what even is the use case of using a decorator to add an option
just.. add the option
The idea is tha the decorator loads stuff from the db and passes it as an function aprameter
like it dosen't add the option to the discord command
but in the end I subclassed context and everything works fine
ah
why
if the bot is available on two servers, it sends 2 messages
(not 2 bot objects)
show code
i think you simply have 2 process_message
so the command is done 2 times
repove that
1 procces_message
why did you add ctx to it?
IDK
its (self, message: discord.Message)
its a message event....
not a slash command
I didn't do it initially, so I left it that way.
I didn't write the code
dev, that I used to pay xd
F
stop paying for that
I've been writing by myself for a year
what the actual fuck is this
?
read all the messages
ctx in on_message?
yea
that, and process application commands in a listener
normal
I'm well aware, just wanna clear it up
It was made clear here
Wait here
My brain decided to find other message
yea, but judging from their responses it isnt clear yet
I have my reasons for saying stuff
Is there any examples on how to stream voice channel audio to the bot?
I think i saw somewhere that bridge bot cant have sub sub commands
is that's true ?
out
Server Settings > Integrations > right?
I thought of* it but it only allows us to OVERRIDE the existing roles/channels, correct me if I'm wrong
I mean it allows you to completely customise who and which roles can and can't use the command
isn't that exactly what you want
Yes I could lock it to admins only and then override the other roles from within discord, you're right.
Thanks!
How can I await a send_modal after ctx.defer()
you cant
I have an if condition which slightly delays the send_modal and often it results in the: Unknown interaction error
yea you can't
modals have to be instantly responded to for all I know
Aight, thanks!
Discord when they don't love modals enough 
Calling ctx.respond() without parameters will just acknowledge the response?
will raise an error
You will get an error that you tried to send an empty message
So you should send a message
interaction.reponse.edit_message ?
If I want to both edit the message and respond with a modal, do I do self.message.edit instead of ctx.response.edit_message? and then ctx.response.sendmodal
So yes, you respond with the modal and do self.mesaage.edit
what does trigger the event on_bridge_command
because basically no command of my bot trigger bridge
because i did create my own function to create a multicog and a bridge support, however now those event are not triggered
so i think i should add something to these function for the bridfge event to work
and i did not change the invoke_application_command that should be the one to dispatch that
bridge error seems to work everywhere, bridge command completetion only for prefix
and on bridge command does not work at all
Hi, I'd like to lock down a command to a list of User IDs, what's my best course of action?
you could check for the id
Is there a way I could make it so it doesn't appear for others in the server?
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
wait
for others not really
Okay thanks, will have to go with predicate I guess!
only with permissions
Guild_ids=[]
that is for the guilds and not users...
Are user apps supported in pycord and are there any code examples on them?
There is a pr
.tag user_app
Tag not found.
Idk the tag
ah sadge, any way I can just use the PR for now or would that be a bad idea?
This one
I think u can since they should merge it pretty soon
Doope thanks ❤️
If you're a server admin or owner, guild settings > integrations
Nvm, trying to run the example code and the bot never authenticates with discord. I guess this project would have to wait for another day
I am running this code and it works. Make sure you set up the bot correctly on the discord developer portal
Is there a way to query a set of members without the members intent matching a specific criteria?
I thought I did. Maybe I was wrong?
how to disable the help command?
the default help message?
Yep
bot = commands.Bot(..., help_command=None)
Thank you
You could open up a post with your code if you want to.
.rie
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.
need to have None before adding blocking func
Any estimates on when the next stable version will be released?
pretty soon
i think i read maybe 26 or 28
but will maybe be delayed of a weeks
If i have some pillow in an async def funct,
does this will block my own bot ?
async def blocking_funct()
pillow...
@commands
async def command():
await blocking_funct()
does this will block
Yes?
how can i do for i does not block ?
use an async version of it if it exists or put it into its own thread
there is no async and for the own thread i have no idea of how does that in pycord
i did check at the
.rie
but this only work with def funct, and in my code with pillow i also need some async func
not specific to pycord lol
Google how to do threading in python
does it not need to be on the same loop has pycord ?
.
this only work with def func
and my func is async with some pillow in it
how to use run_in_executor as async if u prefer
welli will move to a post
Well I mean since the code is just the example code given in the PR I doubt there's anything wrong with my code. I've also hopefully setup the bot correctly so I'm going to put it up to that the PR is still under reivew / hasn't been merged
run just the pillow in that then... bruh
if im not doing that directly its for a reason ;)
so i will try to expplain u better
the function is like so
-> async query
-> pillow
-> async query
-> pillow
-> async query
-> pillow
- 10
so my goal is first to see if i can not make a function for each single time im using pillow and just wrap everything in a func
yea, do it all in one function, and call the pillow shit using asyncio
here a little part of it :
async def funct():
for channel_id in top_text_channels:
try:
channel = await bot.get_or_fetch_channel(channel_id[0])
async with Database() as db:
message = (await db.execute(f"SELECT SUM(msg_count) FROM stats_data WHERE guild_id = %s AND channel_id = %s AND timestamp >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL {max_time} DAY))", (guild.id, channel.id)))[0]
channel_name = channel.name
with Pilmoji(card) as pilmoji:
text_width = draw.textlength(channel_name.strip(), font=medium_25)
if text_width > 170:
while text_width > 170:
channel_name = channel_name[:-1]
text_width = draw.textlength(channel_name.strip(), font=medium_25)
channel_name = channel_name.strip() + "."
#pilmoji.text((80, [510, 572, 634][count]), channel_name.strip(), font=medium_25)
draw.text((300, [510, 572, 634][count]), translator.stats.guild.message.channel.value.format(number=message), font=italic_25)
count += 1
if count >= 3:
break
except:
pass
im like maybe just im not understanding what ur saying
so can you explain what here i should call with async
each draw.text and pilmoji.text ?
I don't get what's so hard about using this
???????
and as you can see here im using async and also def in the same one
so i will need to change anything
dude
to create sub func for each
so u are telling me to do
await bot.loop.run_in_executor(None, funct, 'put', 'args', 'here')
if i understand
because here each
draw.text((300, [510, 572, 634][count]), translator.stats.guild.message.channel.value.format(number=message), font=italic_25) which are kinda everywhere on the func are blocking it. So i will have to create a lot of funct and then executor all of them which will look like a mess
async def finished_callback(sink, channel: discord.TextChannel, *args):
recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
await sink.vc.disconnect()
files = [
discord.File(audio.file, f"{user_id}.{sink.encoding}")
for user_id, audio in sink.audio_data.items()
]
await channel.send(
f"Finished! Recorded audio for {', '.join(recorded_users)}.", files=files
)
I also want to save file on local machine in current directory , how to do that?
audio.file...
how to save that as .wav ?
file=discord.File("FILENAME.wav")
did you gpt that answer
it's wrong
because that's blatently wrong
it required IO data as argument
I dont use gpt
and I send the files other ways xd
@shell radish can you help please 🛐
I don't use voice
what is sink.encoding?
it's used format of audio
i mean the value
wav
you want to use aiofiles
I'm not sure what's that
it's a library
async with aiofiles.write("filename.wav", "w") as f:
await f.write(audio.file)
Alright , I'll try
How to fetch message from the api and not from bot's cache? bot.get_message(id) doesn't work after restart
.rtfm fetch_message
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
await bot.get_partial_messageable(channel_id).fetch_message(message_id)
And If ID is not bound to a particular channel or guild? Is it possible to fetch it?
no
I see. Thanks!
unless you brute force it
How to change voice channel's rtc region?
Found it. VoiceChannel.edit(rtc_region=...)
discord should handle that fine automatically
If that in pycord?
Maybe if you ask a full question someone can answer it
Polls aren't yet in stable
is there anyway for me to restart my bot.py file via a command? ik its weird as a question but sorta need it
python: can't open file 'C:\\Users\\Acer\\Desktop\\Discord': [Errno 2] No such file or directory
nvm, its because i started my bot thru pycharm
o
yep
yes but that completely stops the bot instance, i want it to also restart it ykwim
Yeah depend on ur host
Since I’m using pterodactyl
When something stop like exit it restart automatically
ahh
How would you implement a healtcheck for a bot running in a docker container?
(basically can be any command that fails if the bot is down)
just check if the process is still running lol
how to timeout someone for 7 days?
.rtfm timeout
how do i link slash commands in embeds like so:
</command name:command id:>
Command.mention
Can you get reaction events to the bot's own messages without the messages intent?
messages, not message content
even without message intent you should get the message content of ur own message / message u got ping in
what is the work of this function-- add_bridge_command(command)
adds a bridge command to the bot
how can i put the max_value as infinity for the discord.ui.Select() ?
The maximum is 25. According to ddev docs 25 is still the maximum for role/user/channel selects as well
yeah ik that but if i pass some options
if for example there are 23 options i cant put max_values 25 or it will raise an error
I think just using a len would work fine max_values=len(options)
yeah so i will need to move the options outside the discord.ui.Select()
but if there is no other solution
Hi there,
I cant get reactions working properly.
Is there a specific intent or permission im missing? This script hangs its self after the adding the first (out of 5) reactions. (It starts to send Heartbeat failed error messages)
for reaction in [...]:
await message.add_reaction(reaction)
Any tip is welcome
bot is admin
the function does not raise an error
what is message?
a video file with a text
message: Message = await channel.send(content="sometext", file=File(filename))
also every reaction works on their own so they are not invalid characters which has me even more confused
how can I create a comamnd that I can use anywhere in discord
using user_app
How kann I install the latest reales of pycord?
.master
pip install -U git+https://github.com/Pycord-Development/pycord
Thx
I wonder if you are being rate limited. Could you enable logging and look for ratelimit messages
.logging
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
FYI Master does not have user apps yet. There are instructions in the PR linked in the GitHub link
Am I missing something in the docs, or isn't it possible to get all "suspected of spam activities" members of a server?
Spammer Flag is already exposed in the API (I believe), and has been for a while (it's in the User Object's flags field, as the 1 << 20 or 1048576 Flag)
Hmmm, so nothing that gives me just a list of them from a Guild, I'll have to loop over all members?
yep
Shame... I want to kick those people from servers, not ban them straight up like Discord only allows you to do in bulk...
dont kick all those poor guy, maybe some have done nothing
u might have an issue with that
if u kick all memebr and dm them
if ur bot isnt certifed there is a lot of chance he gets flag
It is verified
so it should be okay
well it depends
but if u dont have hundred and hundred
it should be okay
Well yeah, I'm not looping over 58k members 😛
And you could just message before the kick and have slightly better chance of not getting flagged
WARNING: discord.gateway: Shard ID None heartbeat blocked for more than 790 seconds.```Whats that
U have a def function that block ur whole bit
Ah
Wasnt rate limiting. Was kinda my own stupidity altho i still dont quite get why it happens the way it did.
If you use asyncio.run(bot.start("tokeb")) it causes this werid behaviour while using loop.run_unitl_complete(bot.start...) does not. Dont know why cause i thought .run does that under the hood but who knows
Is there an example for default_permissions or however you hide commands from users?
@discord.default_permissions(administrator=true)
not more to it
oke- thanks mate
I think it has something to do with how many event loops are running. You you pass loop=bot.get_loop() or something to asyncio.run I think it works
import discord
import asyncio
import datetime
from discord.commands import option
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = discord.Bot(intents=intents)
This is my very small set of imports, what am I doing wrong / how do I fully become pycord
my packages:
aiosignal 1.3.1 1.3.1
attrs 23.2.0 23.2.0
frozenlist 1.4.1 1.4.1
idna 3.7 3.7
multidict 6.0.5 6.0.5
pip 24.0 24.1
py-cord 2.5.0 2.5.0
setuptools 65.5.0 70.1.1
yarl 1.9.4 1.9.4```
(I've been getting this error)
Traceback (most recent call last):
File "C:\Users\xboxa\PycharmProjects\USNUtilities\USN Util.py", line 9, in <module>
from discord.commands import option
File "C:\Users\xboxa\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\__init__.py", line 26, in <module>
from .context import *
File "C:\Users\xboxa\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\context.py", line 30, in <module>
import discord.abc
ModuleNotFoundError: No module named 'discord.abc'
uninstall everything then re-install everything
I don't need to install any package other than pycord, correct?
yeah
would you say the same thing for this?
Requirement already satisfied: aiosignal==1.3.1 in ./.local/lib/python3.12/site-packages (from -r requirements.txt (line 2)) (1.3.1)
Requirement already satisfied: attrs==23.2.0 in ./.local/lib/python3.12/site-packages (from -r requirements.txt (line 3)) (23.2.0)
Requirement already satisfied: py-cord==2.5.0 in ./.local/lib/python3.12/site-packages (from -r requirements.txt (line 4)) (2.5.0)
Requirement already satisfied: frozenlist>=1.1.1 in ./.local/lib/python3.12/site-packages (from aiohttp==3.9.5->-r requirements.txt (line 1)) (1.4.1)
Requirement already satisfied: multidict<7.0,>=4.5 in ./.local/lib/python3.12/site-packages (from aiohttp==3.9.5->-r requirements.txt (line 1)) (6.0.5)
Requirement already satisfied: yarl<2.0,>=1.0 in ./.local/lib/python3.12/site-packages (from aiohttp==3.9.5->-r requirements.txt (line 1)) (1.9.4)
Requirement already satisfied: idna>=2.0 in ./.local/lib/python3.12/site-packages (from yarl<2.0,>=1.0->aiohttp==3.9.5->-r requirements.txt (line 1)) (3.7)
[notice] A new release of pip is available: 24.0 -> 24.1
[notice] To update, run: pip install --upgrade pip
Traceback (most recent call last):
File "/home/container/bot.py", line 6, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
you have access to terminal right?
vastly shortened it bc I figured I didn't need a lot of the default stuff I got from pycharm
aiohttp==3.9.5
aiosignal==1.3.1
attrs==23.2.0
py-cord==2.5.0```
what can you do the server?
There's an option to reinstall the server, I've tried several times with deleting the file and reinstalling the entire server, it doesn't seem to change anything.
Using bot-hosting.net if you know enough to say something along the lines of "the best way to fix that issue is to not use it"
if they have a support server, ask them how to uninstall dependencies
you want to uninstall discord/discord.py and just install py-cord
Yeah, I've asked. No response but figured I'd ask here in case it was another issue.
Sounds good then, I'll leave yall alone. Thanks mate.
k
What is not defined?
Can you show the pip list pls?
is there an error when you run this or
written out, it would be discord.bot.Bot
maybe your "IDE" is just not picking that up
probably installed discord.py 💀
I had user which only installed dpy and was writing the bot in py-cord
is it possible for two slash commands in different files to be part of the same slash command group
yes
how?
easier way is to use pycord-multicog
it has some limitation but normally it should be okay for u
i'll take a look ty
is it possible to reload the multicog for updates, it seems that unload_extension and load_extension aren't working
Discord thinks that this is not a valid number. Why?
@discord.command()
async def delete_lobby(self, ctx: discord.ApplicationContext, lobby_id: int):
pass
the number is to long
How can I make it accept long ints?
Via discord.Option()?
Or is this discord limitation?
discord limitation
just take a string and parse it as int
discord uses a completely brain damaged kind of int
It is but there is a issue with discord unload doesn’t remove command
So using load and unload extension should work but currently isn’t because discord being bad?
Loading and unloading should work but does not work 100% as there is not a good way to remove/re-add commands to discord without hitting ratelimits. This time it is actually more of a pycord issue than discords.
Oh ok 
I have the strange problem that the channel object I get from an discord.Interaction has the wrong members attribute. It seems like it's listing every member in the guild instead of just the members that have access to the channel. Fetching the channel again solves that. Any Idea what might cause this?
It's in a button interaction
interaction.channel.members?
Interaction.channel.members show guild members or member in voice I think
yes
why and since when?
Also why did it work before and why does it work when I fetch the channel?
i think i said, but if u said it was saying members that have access to channel i was wrong
let me check the code
@property
def members(self) -> list[Member]:
"""Returns all members that can see this channel."""
return [m for m in self.guild.members if self.permissions_for(m).read_messages]
yep it should check the permission for the channel
it can be because of the cache
the cache is not updated and at this periode all member were able to see the channel
and fetching it change the cache
yeah but then a simple bot restart should suffice, right? But it didn't. Even after a restart it still showed the wrong list.
Idk if a restart will clear all the cache
.rtfm self.bot.clear()
Target not found, try again and make sure to check your spelling.
.rtfm clear
discord.on_reaction_clear
discord.Client.clear
discord.Message.clear_reaction
discord.Message.clear_reactions
discord.on_raw_reaction_clear
discord.RawReactionClearEvent
discord.RawReactionClearEvent.channel_id
discord.RawReactionClearEvent.guild_id
discord.RawReactionClearEvent.message_id
discord.Reaction.clear
discord.on_reaction_clear_emoji
discord.RawReactionClearEmojiEvent
discord.RawReactionClearEmojiEvent.channel_id
discord.RawReactionClearEmojiEvent.emoji
discord.RawReactionClearEmojiEvent.guild_id
discord.RawReactionClearEmojiEvent.message_id
discord.Bot.clear
discord.on_raw_reaction_clear_emoji
discord.ext.commands.Greedy.clear
discord.ext.pages.Paginator.clear_items
Maybe try with the client clear
It would be weird if it doesn't... Pycord doesn't save any data to disk so when you restart the bot, pycord has to build the whole cache again.
If pycord doesn’t save anything that’s strange
Tbh this is way above my knowledge so maybe someone will give u a better answer
Someone pls
Pls ping me when u got the answer
without sufficient intents, pycord is unable to retrieve permission information
It's not about permissions. I have all intents enabled. It's about channel.members returning all guild members instead of only the ones that can actually see the channel...
I don't see an interaction.members attr in docs
interaction.channel.members
oh yeah. Interactions give the bare minimum information required for the interaction to process. If the guild's members and channels aren't cached, then much of the information, including permissions, is unavailible
I guess you meant "including members" xD
no, I mean permissions
But the thing is, that it is in fact available, but wrong.
it is not availible
right, but it relies on the GuildChannel's permissions
the interaction bears a partial channel object with incomplete information
Oh, ok. So if those permissions are missing, it just assumes everyone can see the channel?
yes
Ok. And I guess a possible solution would then be to fetch the guild on bot start?
Does that fetch the channels too or would I have to fetch the channels manually then?
that does not fetch the channels
Also, I guess that problem does not occur with discord.Context, right?
discord.Context does not exist
I mean slash command. I think it's ApplicationContext xD
It would still exist
I'm just confused why I never came across this Problem before... This is the first time I hear about it. Before, it just worked...
cache
And that would also mean that I now have to fetch the channel every time I want to access its members...
you can get or fetch
But get uses the cache, doesn't it? And if the cache is the problem, get would not help here, would it?
Can i get and dm members somehow without intents?
intents.members
I dont have member intents. The bot is verified and discord doesnt give me
wait maybe not
you need member intents to access the on member join etc
so i guess so also need it to send dm
yeah you will need it help you cant get the member with the get_member
if you dont have this intents by discord its because they think you dont need it
Yes i know
and get will cache it? Or should I use get_or_fetch then?
Yep it will
So yeah u should use get or fetch
you can thank javascript for that
Ah yes 2^53 - 1
Try running this in console
let max = Number.MAX_SAFE_INTEGER;
let _8 = max + 1 , D = max + 2;
console.log(_8===D);
How I can determine who exactly triggered on_raw_thread_member_remove? As I see in state.py, it just dispatches event with RawThreadMembersUpdateEvent as arg for each removed member id without passing id
audit log?
seems, like there's no AuditLogAction for leaving from thread
is it possible to add data to a view that only applies to that specific view
ill try that out ty
class1 | class2
yeah but i mean
class LumabotContext(Lumabot_Prefix_Context | Lumabot_Application_Context)
this will not work
and if i put one before the other with a comma it just remove half of the autocomplete
Hello. I would like to rewrite my bot to use cogs. From my understanding currently, they're a way to group commands to reduce the length of main.py, and in discord, you use them eg. if you had a cog called math, you'd do /math add
My question is what determines the first name, i.e. /math?
Is it the name of the cog class or the name of the cog file or what?
Thank's for the assistance
cogs are not related to command groups
you can have a math cog or not and have /add and /subtract and have /math add and /math subtract
wait what? then what are cogs?
oh ok, so just for organising code, like modules?
yes
Is there a way to turn the show boost progress bar setting on and off via bot?
Guild.edit with premium_progress_bar_enabled looks like what you want
Okay thx
Hi, can someone help me with something?
So my project structure is a bit like this:```py
root:
-main.py
-cogs
--ranks_cog.py
-helpers
--helper.py
--firebase_helper.py
I need to use functions from the helper files from the ranks cog. How can I do this?
like how do I import those files?
use from ..helpers.helper import variable
Or from .helpers.helper import variable
Or a function in your cade
Honestly its much more simpler if you were to just make init.py files
Also it is more o less a general python question than pycord but ok
@quartz umbra
yea idk I asked the python community the same question on the official server to get nothing working in the end, so i thought maybe here somebody might be able to help
how do I actually make my error handling work on my main file? tried adding the code bellow, but it still not handling
@client.event
async def on_application_command_error(ctx:discord.ApplicationContext, error:discord.DiscordException):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond("Este comando está em tempo de espera", ephemeral=True)
elif isinstance(error, commands.MissingPermissions):
await ctx.respond("Você não tem as permissões necessárias para usar este comando.", ephemeral=True)
elif isinstance(error, commands.BotMissingPermissions):
await ctx.respond("Eu não tenho permissões o suficiente para fazer isso.")
elif isinstance(error, commands.NSFWChannelRequired):
await ctx.respond("Este comando só pode ser usado em canais NSFW", ephemeral=True)
elif isinstance(error, commands.NoPrivateMessage):
await ctx.respond("Este comando não pode ser usado em mensagens privadas.", ephemeral=True)
elif isinstance(error, commands.CommandNotFound):
await ctx.respond("Comando não encontrado.", ephemeral=True)
elif isinstance(error, commands.DisabledCommand):
await ctx.respond("Este comando está desativado.", ephemeral=True)
elif isinstance(error, commands.CheckFailure):
await ctx.respond("Você não pode usar este comando.", ephemeral=True)
elif isinstance(error, commands.UserInputError):
await ctx.respond("Erro no input do usuário.", ephemeral=True)
elif isinstance(error, commands.CommandInvokeError):
logger.error(f"Erro ao invocar comando: {error.original}")
await ctx.respond("Erro ao invocar o comando.", ephemeral=True)
else:
logger.error(f"Erro desconhecido: {error}", exc_info=True)
await ctx.respond("Ocorreu um erro desconhecido.", ephemeral=True)```
hey quick question when attempting to use start instead of run the main event loop gets blocked am i doing something wrong?
Run doesn’t trigger it but start does i didn’t have this issue using discord py so idk what the issue could be/I’ve even removed all my code but the start and same issue
Check if in ur code ur not using asyncio.run
Does anyone know where I can find all per route emoji rate limit
Like 250 per 48 for role creation etc etc
Do you use time.sleep or requests?
Why does unknow response does not trigger application error ?
basic answer, because ur invoke_application_command disptach hybrid_command_errror and not hybrid_command_error
how can i pass a checks for a commands.Group ?
Is it normal if ctx.command is none with slash comands?
Wait it's because I'm doing it in the overriden context
whatever
nope
No it is
because I was accessing it in the ctx's init
when I subclassed ctx
and command is set when running invoke not __init__
i was thinking u were talking in a regular thing like in a command or else
Can you please advise, what type of database is better to use for a public Discord bot (for many servers)?
.tag database
Tag not found.
.tag nojson
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!
sqlite -- aiosqlite (or Danny's wrapper: asqlite)
just need to be async else its really badt
Yeah I’m using Asyncio run
Neither I’m legit just starting the bot inside a alr created event loop and it’s blocking the event loop and causing a heartbeat timeout
so dont
This block all ur loop
that's why
? What else would i use I’ve got to start the loop
I’m doing some async work b4 hand so bot.run() won’t work
This has worked for awhile in discord py
if u are using @tasks.loop you can just do task.start
I’m not using tasks I’m legit just starting the bot
I removed all my code and same issue
loop = asyncio.get_event_loop()
loop.run_until_complete(client.start('TOKEN'))
you can do like this ig
i dont really see a reason of why not using bot.run i didnt understand why u cant)
th async is before the bot run or after
Before
Ik it blocks the after
But it’s blocking heartbeat
this is because u have a def function/non async
that is running
so it block ur current loop
I’ve got nothing running but the discord bot
I legit removed everything except the start
And the issue doesn’t happen with run
can you show me ur code ?
But like i said I’ve got work that needs to be setup before the bot runs
.tag past
Tag not found.
Did you mean...
paste
.tag paste
It’s legit just a start but sure lemme get my laptop
will be easier to help and understand
ok so u ust have bot.start
Yeah
well i did got the same issue as u
And that causes the error
I believe it’s a py cord bug
Bc I’ve used it fine in discord py
depend on how to use it because some user use it without issue
If you use asyncio.run(bot.start("tokeb")) it causes this werid behaviour while using loop.run_unitl_complete(bot.start...) does not. Dont know why cause i thought .run does that under the hood but who knows
I’ll try what you said but like i said I’ve been doing it like this for almost 3 years
Moved to cord and it’s a issue
try that :
if __name__ == "__main__":
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(bot.start(token))
except KeyboardInterrupt:
loop.run_until_complete(bot.start(token))
finally:
loop.close()
Bet Ty I’ll lyk if it doesn’t work
this should work
let me also know if it work ;)
yeah that worked tysm!
does pycord have a way to handle authentication for a website?
I'm trying to create a simple command to test the user-installed apps but im having some trouble.
My code
@bot.slash_command(name="ping", description="Muestra el ping del bot", contexts={discord.InteractionContextType.private_channel}, integration_types={discord.IntegrationType.user_install, discord.IntegrationType.guild_install})
async def ping(ctx: discord.ApplicationContext):
await ctx.respond(f"Pong! {bot.latency*1000:.0f}ms")
Error:
@bot.slash_command(name="ping", description="Muestra el ping del bot", contexts={discord.InteractionContextType.private_channel}, integration_types={discord.IntegrationType.user_install, discord.IntegrationType.guild_install})
ttributeError: module 'discord' has no attribute 'InteractionContextType'
It doesn't.
What are you trying to do for:
integration_types={discord.IntegrationType.user_install, discord.IntegrationType.guild_install}
and for:
contexts={discord.InteractionContextType.private_channel}
OH IS THIS FOR THE NEW USER COMMANDS THING
ye
I see!
I guess the pycord lib doesn't have InteractionContextType
what does that do in particular
yes a mod was telling me in #general that i need to isntall the PR, its not released yet in the lib
it lets you use commands anywhere no matter if the bot is installed on that guild
also lets you use in dms
ohhhhhhhhh
yea I got no clue
probably check the PR
it's not in docs yet right
pip install git+https://github.com/Pycord-Development/pycord@feat/ua
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
Last line.
@mild trout It was recently added to master. It should now work by installing the last line like dark mentioned.
niceee
thanx you guys, i never really installed directly from github
That is fine. We told you wrong originally as we did not realize that the branch was merged into master.
i saw the merge and i wrongly believed it meant it was already in the package hehe
👍 That is understandable for someone new to working with github 😄
When we say "master" that is the dev version that is not guaranteed to be stable (but is currently). You have to install this directly from github. We will post in #library-updates when there is an update to the pypi package (that you can than install normally)
Could py-cord have a method to load the cogs from the cogs folder, or load them automatically? I currently have this code but I'm not sure if it's the best way to start the cogs
I have something very similar:
# -- Setup Cogs --
with open(os.path.abspath("./setup.json"), "r") as setup_json: # Use the setup folder to get the cogs folder
cogs_folder = json.load(setup_json)["cogs_folder"] # Load cogs folder from setup JSON
with open(os.path.abspath(cogs_folder + "/cogs.json"), "r") as cogs_setup_json:
cogs_json = json.load(cogs_setup_json) # Json for the list of cogs
for sub_folder in cogs_json["sub_folders"]:
for file in cogs_json["sub_folders"][sub_folder]["files"]:
print(file)
file_path = f"{cogs_folder.replace('/', '').replace('.', '')}.{sub_folder}.{file}"
print(f"Loaded {file_path}")
bot.load_extension(file_path)```
if it works it works
only difference is that I have a json I read off of
haha you're right. In any case, I feel that it should automatically load the cogs without having to indicate each one.
True true that would be pretty useful
maybe a PR with a helper func would be good
On another note,
How accurate is the bot's guild cache?
I'm attempting to make a bot panel that integrates the bot but idk whether I should make a fetch request
if the bot gets added to a new server, does it get added to the bot's guild cache?
I think that by default py-cord saves all the guilds in cache, so the more servers you have you will consume more ram, in my case I prefer not to use the cache and when I need to obtain the guild I do a fetch_guild
To prevent bot rate limiting fetch_guild might be problematic (but hopefully not)
If you constantly need information about your bot's guilds you could leave it as default and just do a get_guild, anyway I'm not completely sure
ah ty!
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
Ah, I'm not quite getting the user though
oh yeah
I'm getting the guilds that the user is in
sorry
I copied the wrong link, no problem
alr I got the following to work:
for guild in user_guilds:
# noinspection PyTypeChecker
for bot_guild in bot.guilds:
if int(guild['id']) == int(bot_guild.id):
print(guild)
How would I run my flask app in the background as a thread?
I tried:
flask_thread = threading.Thread(main_flask.start_app(bot))
flask_thread.start()
However, app commands just break
(start_app starts the flask app)
wait
figured it out
just had to change my start command
async def start_app(bot_):
global bot
bot = bot_
app_thread = threading.Thread(target = app.run)
app_thread.start()
also the target wasn't set 💀
I have something like this (I'm using fastapi)
from api import run_api
async def run_bot(loop):
await bot.start(os.getenv('BOT_TOKEN'))
async def main():
loop = asyncio.get_event_loop()
await asyncio.gather(run_bot(loop), run_api())
if __name__ == "__main__":
while True:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
async def run_api():
server = Server(config=uvicorn.Config(app, host="0.0.0.0", port=25247))
await server.serve(sockets=None)
thanks!
Ok did some testing
and the cache does update!
which is epic
I added the bot and removed the bot from the server and when checking what it prints it prints both states
bot.load_extension("cogs", recursive=True)
Should attempt to load all the files in the folder.
thank you
There is a so much easier way to do it
And py-cord is already creating a loop so you dont have to do it again
Did you get it to work tho
I did! I asked ChatGPT! I set up my project as a library (using __init__.py everywhere), then say I wanted to use package2.module2 from package1.module1, i could just do (in module1): import ..package2.module2
Glad to hear it worked out :)
btw, do you have any bot hosting suggestions?
My prev host ain't gonna work now
I bought a raspi
What is your budget?
.tag hosting
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.time4vps.eu/ Lithuania.
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
Self-hosting: Free hosting: Kinda free:
Any computer. Heroku dead 🦀 GCP, AWS have one year free micros.
as cheap as possible tbh (we're not needed free tho)
hetnzer very good and cheap
railway if you want a US host
eu for the dub
wouldn't you want US because discord's server is in the US
or anywhere north america not including mexico
Doesnt make that big of a difference latency wise
In my experience
SparkedHost has both EU & US locations it seems like
The first result here for me
1usd / month
oh yea 💀
WARNING:discord.gateway:Shard ID 2 heartbeat blocked for more than 200 seconds.
Loop thread traceback (most recent call last):
File "/home/container/main.py", line 53, in <module>
bot.run(f"{token}")
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 756, in run
loop.run_forever()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever
self._run_once()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1987, in _run_once
handle._run()
File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 1181, in on_interaction
await self.process_application_commands(interaction)
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 864, in process_application_commands
await self.invoke_application_command(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 376, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 131, in wrapped
ret = await coro(arg)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 1009, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/container/commands/commands/login.py", line 41, in login
userData = await auth.login_auth()
File "/home/container/utils/authData.py", line 52, in login_auth
r = requests.put(f"https://riot-geo.pas.si.riotgames.com/pas/v1/product/valorant", headers=header, json=data)
File "/home/container/.local/lib/python3.12/site-packages/requests/api.py", line 130, in put
return request("put", url, data=data, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/requests/api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/requests/sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
File "/home/container/.local/lib/python3.12/site-packages/requests/sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/requests/adapters.py", line 667, in send
resp = conn.urlopen(
File "/home/container/.local/lib/python3.12/site-packages/urllib3/connectionpool.py", line 789, in urlopen
response = self._make_request(
File "/home/container/.local/lib/python3.12/site-packages/urllib3/connectionpool.py", line 536, in _make_request
response = conn.getresponse()
File "/home/container/.local/lib/python3.12/site-packages/urllib3/connection.py", line 464, in getresponse
httplib_response = super().getresponse()
File "/usr/local/lib/python3.12/http/client.py", line 1428, in getresponse
response.begin()
File "/usr/local/lib/python3.12/http/client.py", line 331, in begin
version, status, reason = self._read_status()
File "/usr/local/lib/python3.12/http/client.py", line 292, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/local/lib/python3.12/socket.py", line 708, in readinto
return self._sock.recv_into(b)
File "/usr/local/lib/python3.12/ssl.py", line 1252, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/lib/python3.12/ssl.py", line 1104, in read
return self._sslobj.read(len, buffer)
why im getting this strange error