#Basic Pycord Help (Quick Questions Only)
1 messages · Page 87 of 1
hello im trying to make a "reload" command for my cogs, but somehow isnt loading the new changes i make like adding commands and stuff like that
this is the code:
@bot.slash_command(name='reload')
async def reload(ctx):
class MyView(discord.ui.View):
@discord.ui.select(
placeholder="Selecciona una.",
min_values=1,
max_values=1,
options=[
discord.SelectOption(
label="mensajes",
description="anuncio, embed, purge, send"
),
discord.SelectOption(
label="whitelist",
description="Reinicia la whitelist"
),
discord.SelectOption(
label="donacion",
description="donacion, mensual"
),
discord.SelectOption(
label="sancion",
description="sancionar, perdonar"
),
discord.SelectOption(
label="seb",
description="wlseb, pgseb, sugseb, bugseb"
)
]
)
async def select_callback(self, select, interaction):
bot.reload_extension(f'cogs.{select.values[0]}')
await interaction.response.send_message(f"Se reinicio con extio el cog [**{select.values[0]}**]", ephemeral=True)
await ctx.respond('Selecciona un cog para reiniciar.', view=MyView())```
you will need to re sync the commands if you add/remove any
add await bot.sync_commands() at the end of your callback
lul
Hold on a fucking minute
this fixes #2015 ???
uhh
toolkit shot itself
@errant crane wake up
||hmm it got disabled because it was crashing the bot or smth||
ohh cuz of #github or what?
oh im not sure bout that
I saw that buttons caused the bot to go into an infinite loop but I assumed they fixed it and not just removed the functionality
no it was some regex issue ig
The last what I know is that you have to restart the bot to get the slash commands synced
this
Are you sure about that?
restart always works lol
that is right
||unless you didnt save the file||
this may or may not work
not sure
I use the auto save stuff x3
one last question, why its saying discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In 4: Application command names must be unique, when i try to sync it when all commands names are diferent?
no shit-
because it's trying to add commands that were already added
you need to unload, sync, reload, sync?
bruh that would ratelimit you if you do it too quick
py-cord really needs to improve the app cmds syncing scene
@bridge.bridge_command()
async def test(self, ctx):
await ctx.respond("test")
For some slash commands work but prefixed commands doesn't.. I have all intents enabled.
intents = discord.Intents.all()
client = bridge.Bot(prefix = "-", intents = intents, debug_guilds = [998272619159752786])
Any idea how I can make prefix commands work?
weird. do only bridge prefix cmds not work? or normal prefix cmds dont work too?
Do you have an on_message event?
nope
didn't try, I'll try now and let you know.
normal prefix cmds don't work too yeah
Anyone here have experience with async sqlalchemy?
import discord
from discord.ext import bridge
intents = discord.Intents()
intents.message_content = True
bot = bridge.Bot(command_prefix="!", intents=intents)
@bot.bridge_command()
async def hello(ctx):
await ctx.respond("Hello!")
bot.run("")
I copy-pasted this from the guide page, slash commands work but not prefixed commands :/
I do
I have this small function:
async def get_random_pg_dare(db: AsyncSession) -> Model.Dare:
query = select(Model.Dare).where(Model.Dare.rating == 1)
result = await db.execute(query)
result_list = result.all()
return random.choice(result_list)
and when I try to run it I get this error:
result_list = result.all()
^^^^^^
AttributeError: 'function' object has no attribute 'all'
Any idea what I am doing wrong? I tried to google but I'm not really finding anything helpful. My IDE also recognizes that result has all() method so I'm really lost here.
can you just do result.fetchall() instead
The exact same thing happens
bruh github doesn't have my repo indexed
can't even search right now
but I don't use session, I use engine
maybe that's not the "right" way to do it but it's worked for me
love that feature as well
That's not really helpful in this case ;/
why not?
@true panther it seems like the result assignment is not returning what you’re expecting there. I’d pop an import pdb; pdb.set_trace() right above that result = line and then see what result actually is
I store a "db" object as an instance variable in my bot
and then I do like engine = await self.bot.db.getEngine() in my command functions
because it's not answer to the question 
I'm just explaining how I use async sqlalchemy, which was your initial question 😉
😉
can you try result.scalars()?
oh that code does use sessions actually
async def get_sessions(self, guild_id):
if not isinstance(guild_id, int):
raise TypeError("guild_id must be an int")
sessions = []
async_session = await self.bot.db.getSession()
async with async_session() as dbsession:
async with dbsession.begin():
gtasession = await dbsession.execute(select(GTASession).where(GTASession.guild_id == guild_id).options(selectinload(GTASession.help_queue), selectinload(GTASession.session_members), selectinload(GTASession.session_votes)))
gtasession = gtasession.scalars()
for session in gtasession:
sessions.append(session)
return sessions```
okay, apparently when sqlalchemy docs say something returns list, it's not a list
I don't follow
your issue was result didn't have .all()
what does that have to do with lists?
I put it in a list comprehension and it works all of the sudden ¯_(ツ)_/¯
it doesn't exist
and this?
How would I be able to pong/stop an interaction without editing a message or sending a response interaction message? I'm pretty sure await interaction.response.pong() used to do this but it stopped working for me, and the button still has that typing animation on it.
Respond and delete it?
no
i swear interaction.response.pong did this
User does something with an interaction, I would edit a different message, and pong/mark the interaction as responded.
responding and deleting it looks terrible
I could have sworn the same thing at one point, but it seems we’re both wrong
- 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
Defer and forget
You need not send a followup for components based interaction
This is intended behaviour
Yo, is there a way to fetch a message with a given jump URL?
The URL contains the guild id, channel id, and message id (in that order)
It seems that the PartialMessageConverter might have a useful method for this named _get_id_matches.
Im not familiar with that, I just do it the manual way
Hmm.
Can someone provide a sample syntax on how to make prefix and slash commands altogether without the use of bridge?
what are you looking for?
could you describe what you are trying to achieve?
I wanna make few commands prefix-only, some slash-only, and some which support both like in bridge, but while using bridge I can't make an exclusive command right?
bridge still supports the @bot.slash_command and @bot.command things (and their cog counterparts)
I see, thank you
I'm debating on it.
Making a dummy ctx just to use PartialMessageConverter._get_id_matches isn't exactly ideal.
But I also don't want to have to maintain some complex regex.
I'm wondering if storing jump URLs is even worth it. I can just store the channel and message IDs in a string, which the converter even seems to accept funnily enough.. e.g. channel_id-message_id
Only thing I'd have to do there is split and convert to int.. 🤔
It's not really that complex
Not really the point, I'd rather just not deal with it. It's complex enough that I don't want to do it. And yes, I could just pull it from PartialMessageConverter whenever it needs to be updated but I'd rather not do that.
can commands be made visible to staff?
slash cmds? you can use default_permissions and allow only admins or people with manage_server perms
config_server = SlashCommandGroup("config_server", "This commands cans see", guild_only=True,
permissions=["administrator"])
I have been trying this way
how can I send a modal in the interaction.followup?
interaction.followup.send_modal() don't work
ok
and how can I edit the response message with the followup?
because interaction.followup.edit_original_response() don't work
AttributeError: 'Webhook' object has no attribute 'edit_original_response'
.rtfm webhook.edit
and how do I do it wiht interaction.followup.edit_message() ?
is anyone haveing issues with the audio recording?
It's working just fine here
im getting so many errors and i just copied it from github, can you help?
Ok, Show me the errors
discord.sinks.errors.MP3SinkError: ffmpeg was not found. is this pip install ffmpeg?
downloaded, then what?
uh wait
you have to add it to path
assuming youre on windows
dam! i shall pass on that
How can I check which BucketType is it ? It's not working
print(BucketType.user == BucketType.user)
Output:
False
no for same once
oh edited
...that returns True though?
what's your real code
you probably want isinstance instead
def check(type: BucketType) -> commands.check:
async def predicate(context: commands.Context) -> bool:
command_name = context.command.name
await self.cd.add_column(command_name)
kwargs = {
"context": context, "rate": rate, "per": per, "type": type, "reset_per_day": reset_per_day
}
print(BucketType.user == BucketType.user)
if type == BucketType.role:
kwargs["role_id"] = role_id
return await self._role_predicate(**kwargs)
elif type == BucketType.guild:
return await self._guild_predicate(**kwargs)
elif type == BucketType.channel:
return await self._channel_predicate(**kwargs)
elif type == BucketType.category:
return await self._category_predicate(**kwargs)
else:
return await self._user_predicate(**kwargs)
doesn't work, any idea?
why don't you just print the type...
its printing BucketType.user
so it'll go to the last else, right?
Ya, but if I pass type = BucketType.guild, then also it's going to last one
do isinstance(type, BucketType.guild) or type is BucketType.guild work
lemme try
everything works now, vaule for type param was wrong
thank you
== and is both are working
Error:
Ignoring exception in view <Paginator timeout=180.0 children=4> for item <Select type=<ComponentType.string_select: 3> placeholder='Filter' min_values=1 max_values=1 options=[<SelectOption label='Alle' value='all' description=None emoji=None default=False>, <SelectOption label='Sturm' value='sturm' description=None emoji=None default=False>, <SelectOption label='Mittelfeld' value='mittelfeld' description=None emoji=None default=False>, <SelectOption label='Abwehr' value='abwehr' description=None emoji=None default=False>, <SelectOption label='Torwart' value='torwart' description=None emoji=None default=False>] channel_types=[] disabled=False>:
Traceback (most recent call last):
File "C:\Users\Pro 8\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 421, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Pro 8\Documents\Programmieren\Discord Bots\ZZGamesucht\football-minigame\cogs\management.py", line 752, in select_filter_callback
await paginator.edit(await interaction.original_response())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Pro 8\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 348, in original_response
data = await adapter.get_original_interaction_response(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Pro 8\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
Code:
paginator = Paginator(pages=pages, custom_view=NewTradingPlayerView(self.players), author_check=False)
paginator.remove_button("first")
paginator.remove_button("last")
#TODO: add user input processing
await paginator.edit(await interaction.original_response())
def check(message):
return message.author == interaction.user and message.channel == interaction.channel and message.content.isnumeric()
user_input = await interaction.client.wait_for('message', check=check, timeout=60)
print(user_input.content)
await paginator.edit(await interaction.original_response())```pain
why don't you just use paginator.respond?
it's erroring because presumably you haven't responded yet
because I want the process in just one message
when I have a message (message 1) and I click on a button on that message (mesage 1). then the original message (message 1) edits to a new message (message 2) and the button on message 2 edit the message to a paginator with paginator.edit (first time works). But that paginator has a custom view (Select Menu) and editing the pagnator after a select menu choice was taken don't work
Or wait no
Oh yeah different thing
You could either wait until https://github.com/Pycord-Development/pycord/pull/2105 gets merged. After that, you can simply pass interaction to paginator.edit
Or, defer the interaction response, and then pass interaction.message to paginator.edit
what is the problem
`import discord
from discord.ext import commands
client = commands.Bot(command_prefix="#")`
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Basically just add
intents= discord.Intents().defualt()
Then pass intents=intents to your bot.
default*
do command cooldowns reset when the bot is restarted?
You also seem to have dpy installed. Py-cord doesn't raise that error
Do you want to use dpy or py-cord
Which is better?
Both are slightly different. Neither is perfect. You should choose what you like. The main difference is found in the Slash cmd implementation
Since you are asking in py-cord server, you will be recommended py-cord
ok do you have a YouTube channel explaining about py-cord?
there's the docs and the guide
which advatage does the async start have? I don't really see any as the code still stops and does not execute any code further down
What
Asynchronous function have the ability of running at the same time. Not in a sequence like normal functions
import discord
from discord.ext import commands
import asyncio
from src import Bot
from settings import TOKEN
bot = Bot.Bot(
command_prefix=commands.when_mentioned,
activity=discord.Activity(
type=discord.ActivityType.playing, name="with granades"
),
status=discord.Status.idle,
)
async def main():
async with bot:
await bot.start(token=TOKEN)
await asyncio.sleep(5)
print("Done")
asyncio.run(main())
I've wrote this little start to test it but the done is not printed
and as far as I understood this addition, it should execute the wait and print after that
maybe I just don't understand this feature
iirc, bot.start will block, but you can use asyncio.gather to run other coroutines alongside it
ill show an example
so I could for example let a quart server run alongside this bot?
yes thats possible
nice, now I only need to learn flask/quart xD and html css and a little js ;-;
you would need the async run method for quart btw
I don't know what you mean
ahh I see what you mean some googeling solves problems
haha
async def blacklist(self, ctx, userid: int, time: Optional[str]):``` ive got the userid in my command set to int but inputting a user id asks for a valid integer?
Take str and convert to int internally
please send the code snippet
Oh no my bad i was searching if someone had that error, didnt meant to send it https://i.imgur.com/P1Ki9RZ.png
well now i need help xd, im moving all my comands to cogs, but when im trying to move one that use bot.wait_for im getting this error
RuntimeError: Task <Task pending name='discord-ui-view-dispatch-40b84af78e0e8d857609e122bbeb3e81' coro=<View._scheduled_task() running at C:\Users\deadz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py:414>> got Future <Future pending> attached to a different loop
You somehow have multiple event loops running. Can you show one of your cog files?
wich one?
Show the one you are getting the error in
dont nest classes. it could cause conflicts
also, dont use global variables
assign them to an object
to modify the messages, how are you doing it? I am using the following form and it is giving problems
@discord.slash_command(name="edit", description="edit message")
@discord.default_permissions(administrator=True)
async def edit(self, ctx):
embed = discord.Embed(title="Test message", description="This message will be edited in 5 seconds")
message = await ctx.respond(embed=embed)
# let's wait 5 seconds
await discord.utils.sleep_until(discord.utils.utcnow() + timedelta(seconds=5))
await message.edit(embed=discord.Embed(title="Edited message", description="This message has been edited"))
ctx.edit()
await ctx.respond()
await ctx.edit()
yk you can just do await asyncio.sleep(5) to sleep 😭
is much better?
much simpler and cleaner than what you are doing
Do that with me irl please
discord.utils.sleep_until is only meant to be used as a shortcut for when you have a datetime object until which you need to sleep
it just calls asyncio.sleep internally
import time
import sys
voxy = sys.voxy
voxy.sleep()
time.sleep(28800)
voxy.wake()

||never use time.sleep in your bots btw. always asyncio.sleep||
Thank you very much, I didn't know the difference between the two. Taking advantage of the fact that I have you here, I want to make the style dynamio, I had thought of passing a method but it throws me an error.
@staticmethod
def select_color(isPremium):
if isPremium:
return discord.ButtonStyle.green
return discord.ButtonStyle.red
@discord.ui.button(label="Premium", style=lambda self: self.select_color(self.isPremium), emoji=f"{Emojis.owner.value}")
async def button_callback_premium(self, button, interaction):
await interaction.response.edit_message(embed=embed_edit, view=None)
Is this possible?
you could override the style inside __init__
like this
class MyView(View):
def __init__(...):
super().__init__(...)
self.my_ultimate_button.sytle = ...
@discord.ui.button(...)
async def my_ultimate_button(...):
...
you could have the check inside init

I've been here for a day or so, I think I'm starting to get tired hahaha.
replace voxy with sergi 🙃
and run
oki
how did ctx.guild.icon.url "not work"
that is the correct way to get the url
Although if the guild doesnt have any icon, guild.icon will be None, so you cant get the url attribute from it
make sure to check guild.icon is not None before accessing the url attribute
Also what are your intents @fervent cradle
Just use display_name?
The pfp makes it funnier
I'm trying to make a task run at a certain time but I know that the function may take longer to run. I get an error saying that task shouldn't have a ctx parameter so how do I add a defer() function into it?
Why do you need a defer in your task?
I know the task will take longer, and I don't want it to fail cause it took too long
or do I not need that because its a task compared vs a command?
It doesn't matter how long the task takes
But I'd suggest not having it take longer than the interval between tasks
thanks!
Why does interaction.response.send_message return an interaction and the returning variable’s message attribute returns None? This used to return a message object, aka the actual response message of the interaction. Kinda weird.
Can’t even get the message it sends
interaction.message is only available for components.
So how can I get the message sent from an interaction that’s not a component
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 ...
I ran this code and got the below shown error i am not really sure what caused it but it successfully created a forum post
class Cog(commands.Cog):
def __init__(self,client):
self.client = client
self.task.start()
@tasks.loop(count=1)
async def task(self):
forumChannel = await self.client.fetch_channel(id)
await forumChannel.create_thread("test", content = "testing content")
Unhandled exception in internal background task 'task'.
Traceback (most recent call last):
File "C:\...\Python\Python311\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop
await self.coro(*args, **kwargs)
File "i:\starpredetor\Code Projects\Projects\Python projects\SSU-Bot\cogs\news.py", line 17, in task
await forumChannel.create_thread("test", content = "testing content")
File "C:\...\Python\Python311\site-packages\discord\channel.py", line 1336, in create_thread
ret = Thread(guild=self.guild, state=self._state, data=data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\...\Python\Python311\site-packages\discord\threads.py", line 168, in __init__
self._from_data(data)
File "C:\...\Python\Python311\site-packages\discord\threads.py", line 206, in _from_data
if thread := self.guild.get_thread(self.id) and data.pop("_invoke_flag", False):
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Object' object has no attribute 'get_thread'
Where is your task named postnews? And where do you define id
dont worry about that
its named task
not postnews
I just wanted to know what caused that error
The stack trace is about a task named postnews.
well yeah im aware
i changed the name of the task from task to postnews while pasting the code here
i can assure you the stack trace was caused by the code above
And where is id defined?
i didn't wanna paste the id so i changed the actual numeric id to the letters "id"
Is your cog really named Cog? That can sometimes cause issues
the cog is named something else
Anything else you renamed you'd like to mention? 🙂
thats about it
you know what actually wait ill paste actual code
class News(commands.Cog):
def __init__(self,client):
self.client = client
self.postnews.start()
@tasks.loop(count=1)
async def postnews(self):
forumChannel = await self.client.fetch_channel(1123222090858889286)
await forumChannel.create_thread("test", content = "testing content")
not much change here
the stack trace Unhandled exception in internal background task 'postnews'. Traceback (most recent call last): File "C:\...\Python\Python311\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop await self.coro(*args, **kwargs) File "i:\starpredetor\Code Projects\Projects\Python projects\SSU-Bot\cogs\news.py", line 17, in postnews await forumChannel.create_thread("test", content = "testing content") File "C:\...\Python\Python311\site-packages\discord\channel.py", line 1336, in create_thread ret = Thread(guild=self.guild, state=self._state, data=data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\...\Python\Python311\site-packages\discord\threads.py", line 168, in __init__ self._from_data(data) File "C:\...\Python\Python311\site-packages\discord\threads.py", line 206, in _from_data if thread := self.guild.get_thread(self.id) and data.pop("_invoke_flag", False): ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'Object' object has no attribute 'get_thread'
So I've never used this method myself, but looking at the error it looks like self.guild in threads.py isn't being initialized correctly for whatever reason
What version of pycord are you on?
the thread it created
latest i believe
Can you give me a version number
2.4.1 to be exact
thats the latest...
well yeah the person i am working for wanted me to open a post in the forums channel each time the bot is started and post some things so the only method i could find to create post was this
in discord.ForumChannel
although i think it is trying to create a channel thread and not a post maybe thats whats causing the error
Any idea how can i fix this:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/jishaku/features/python.py", line 190, in jsk_python
async for send, result in AsyncSender(executor): # type: ignore
File "/usr/local/lib/python3.9/site-packages/jishaku/functools.py", line 124, in _internal
value = await base.asend(self.send_value)
File "/usr/local/lib/python3.9/site-packages/jishaku/repl/compilation.py", line 214, in traverse
yield await func_a(*self.args)
File "<repl>", line 13, in _repl_coroutine
await _ctx.guild.create_sticker(
File "/usr/local/lib/python3.9/site-packages/discord/guild.py", line 2621, in create_sticker
data = await self._state.http.create_guild_sticker(
File "/usr/local/lib/python3.9/site-packages/discord/http.py", line 1672, in create_guild_sticker
initial_bytes = file.fp.read(16)
AttributeError: '_io.BytesIO' object has no attribute 'fp'
import asyncio
import requests
import io
Guild = _bot.get_guild(123)
Stickers = Guild.stickers
for sticker in Stickers:
try:
image_data = requests.get(sticker.url).content
image_file = io.BytesIO(image_data)
await _ctx.guild.create_sticker(
name=sticker.name,
description=sticker.description,
emoji=sticker.emoji,
file=image_file,
reason='KEK'
)
except discord.HTTPException as e:
await ctx.send(f"Failed to create sticker {sticker.name}: {e}")
await asyncio.sleep(1.5)
Not sure if this contributes to the issue, but use aiohttp instead of requests for asynchronous
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
yeah did it now with aiohttp and bytesio and pil
nice
.rtfm bot.walk_application_commands
discord.ext.commands.Bot.walk_application_commands
discord.ext.commands.AutoShardedBot.walk_application_commands
discord.ext.bridge.Bot.walk_application_commands
discord.Bot.walk_application_commands
discord.ext.bridge.AutoShardedBot.walk_application_commands
discord.AutoShardedBot.walk_application_commands
idk maybe click the thing
can't I set a local image as footer in an embed using icon_url like this em.set_footer(text="Sincerely your CheesyDragon Bank", icon_url="attachment://src/assets/bank-1071.png") ?
because the result is like this :/
Pretty sure you can. What does your code look like?
@commands.slash_command(name = "wallet", description = "see your money from your pocket and your bank")
async def wallet(self, ctx: discord.ApplicationContext):
bank = await db.get_member_cash(cash="bank", user=ctx.author.id, guild=ctx.guild_id)
pocket = await db.get_member_cash(cash="wallet", user=ctx.author.id, guild=ctx.guild_id)
em = discord.Embed(
title="Bank statement",
description=f"Pocket".zfill(8).replace("0", " ") + " | " + f"{pocket}" + ""
f"Bank".zfill(8).replace("0", " ") + " | " + f"{bank}" + ""
)
em.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
em.set_footer(text="Sincerely your CheesyDragon Bank", icon_url="attachment://src/assets/bank-1071.png")
await ctx.response.send_message(embed=em)
The file is (from content root) there src/assets/bank-1071.png
?tag localfile
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
You only put the name in the url
Not the location
You need to set the name in discord.File and send it as a file in the same message
in an embed too?
Yes
This is for embed
okay, I'll try
I wonder if you can use a local file in the footer tho
It might only work with the main image and the thumbnail
guess I'll find out
i don't see why not?
else I'll have to use github to host the image 😅
uhhm PermissionError: [Errno 13] Permission denied: 'src/assets' how the f windows?
Hey what is the cause of this error?
AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?
my code was working fine yesterday, but when I tried to run it today I got the error above.
here is the full traceback:
File "/Users/jstrouse/Desktop/coding/EvReboot/EvReboot/evbot/bot.py", line 252, in <module>
goodBot.run()
File "/Users/jstrouse/Desktop/coding/EvReboot/EvReboot/evbot/bot.py", line 232, in run
super().add_cog(NormalCommands(self))
File "/Users/jstrouse/Desktop/coding/EvReboot/venv/lib/python3.10/site-packages/discord/cog.py", line 656, in add_cog
cog = cog._inject(self)
File "/Users/jstrouse/Desktop/coding/EvReboot/venv/lib/python3.10/site-packages/discord/cog.py", line 548, in _inject
command._set_cog(self)
File "/Users/jstrouse/Desktop/coding/EvReboot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 603, in _set_cog
self.cog = cog
File "/Users/jstrouse/Desktop/coding/EvReboot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 830, in cog
self._validate_parameters()
File "/Users/jstrouse/Desktop/coding/EvReboot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 708, in _validate_parameters
self.options: list[Option] = self._parse_options(params)
File "/Users/jstrouse/Desktop/coding/EvReboot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 748, in _parse_options
option = Option(option)
File "/Users/jstrouse/Desktop/coding/EvReboot/venv/lib/python3.10/site-packages/discord/commands/options.py", line 225, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
File "/Users/jstrouse/Desktop/coding/EvReboot/venv/lib/python3.10/site-packages/discord/enums.py", line 786, in from_datatype
if datatype.__name__ in ["Member", "User"]:
AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?```
could you show the code for the cog named NormalCommands
sure
at least the decorators and definition
class NormalCommands(commands.Cog):
def __init__(
self, bot
):
self.bot: MainBot = bot
@slash_command(name="view", description="Get eBay views")
@commands.check(check_access_view_command)
@dynamic_cooldown(decide_cooldown, type=BucketType.user)
async def view(self, ctx: ApplicationContext, link: str, amount: int):
new_link = Validation.link_validation(link)
if new_link is None:
await ctx.respond("Invalid eBay link")
return
rewards = PaidRewards(ctx)
if amount > rewards.view_limit:
await ctx.respond(f"Max views is {rewards.view_limit}")
await ctx.respond("reeeeeeeee", ephemeral=True)
# @slash_command(name="test")
# async def test(self, ctx: ApplicationContext):
# x = Snowflake()
# x.id = 1123321195849318465
# await ctx.user.add_roles(x)
async def cog_command_error(self, ctx: ApplicationContext, error: commands.CommandError):
if isinstance(error, commands.CommandOnCooldown):
cooldownMSG = ConvertTime(clean=True).convert_and_format(
int(error.retry_after), separator=" and"
)
await ctx.respond(f"You are on cool down for another {cooldownMSG}", ephemeral=True)
elif isinstance(error, CheckFailure):
await ctx.respond(f"You do not have access to this command", ephemeral=True)
else:
raise error # Here we raise other errors to ensure they aren't ignored```
is that it?
to replace what?
@slash_command(name="view", description="Get eBay views")
@commands.check(check_access_view_command)
@dynamic_cooldown(decide_cooldown, type=BucketType.user)
+ @discord.option("link", type = str, description = "Enter a link")
+ @discord.option("amount", type = int, description = "Enter an amount")
async def view(self, ctx: ApplicationContext, link: str, amount: int):
alright I'll try that
How to setup logger? I did what's in the docs but nothing gets printed to the console
Do you import annotations from __future__?
they didnt
is the description of an embed mandatory? is there a way to have just the title
yes, just pass in the title embed = Embed(title="sometitle")
oh so it isnt mandatory
can i also somehow get rid of this ugly gap
what did you use to get this?
discord.Embed(title=f"Weather information for {city.capitalize()} ({area.name}) in {area.country}")```
I assume the temperature is added with .add_field()? If so idk, unfortunately. I don't get a gap this big.
how do u add ur embed? do you also add fields?
theres no description, u told me to remove it, just a title
its really just the title, and then add_fields
hello, could someone help me and possibly tell me why my code is not working? The bot does not want to leave the voice channel and no errors come up.
Pls dont crosspost
how does an emoji get into the bots cache to use get_emoji what do u need to do
emoji = iteminfo["emoji"]
emoji_id = await extract_emoji_id(emoji)
emoji_obj = self.bot.get_emoji(emoji_id)
print(emoji, emoji_id, emoji_obj)```
this just doesnt print the object, as if it doesnt exist in the cache even tho theres a guild with it and the bots used the emoji
:test: 1002979645848830022 None```
and if you do fetching it?
but how does it even get into the bots cache
For what?
umm
am i wrong lol
i read but didnt see anything to check if token is online
well I am master in python. noone code faster than me
Looks like not the master of reading docs
guild download completed + we should've an on ready event
lmao
oh cmon. i know that.
imagine I host my bot on replit
LMFAO
I joined
Lmfao
@empty crypt I'm waiting
and then try to host on glitch
then your question is answered
no I cant check if my bot is already online and if i rrun on glitch my bot run 22 instances
lemme signup
that makes no sense
lol
Create bot which checks if bot is online
Stonks

Btw, mb host discord bots jam after the survey?
WTF IS THIS GAME
💀
ez
I spent most of my time reading this stupid stuff
lmao
nah
cmon
yeah
PAHAHAHA YIKES
i wasnt really that mood
wtf does it matter if you're the "fastest" at coding if it's all wrong anyway
come nowi dare you
LMAO
(and we should probably keep this in #general)
I fixed your nickname <3
broo
I dare anyone come to that challenge again. I am new to that thing so i had to read everything slowly
We don't give second chances here
good idea
you were slower than lacosst0 who also never done this before
fear?
I bet you all my owo i will win next one
Bot's literal only purpose, no commands just ping the bot and make it send an error in a channel if the bot is not online
epic
I spent 1 min translating the task cuz my english is just slow

come on
you have to change my name back if i win next
Bot which pings other bot if it's offline so the other bot can see the message and wake up

huh maybe I do this just a little too much
LOL AND THE OTHER SHOULD DO THE SAME
come on i dare yall
@empty crypt #general
XD
Проблема навыков, мой друг
oopsie sorry
probably translated
who knows
В россии никто так не говорит.
Максимум люди, которые хотят секса
Russian and Ukrainian are pretty similar
Most Ukranians know russian tho
btw, #general
lmao
Yep that doesn't work
Try using master branch
Also try using typing.Anotated on master branch
wait so I can't use from __future__ import annotations?
what does typing.Anotated do exactly?
Yeah that breaks stuff unfortunately
It is a way to make type checkers happy while having something else in the type hint
Example usage would be
async def hi(ctx, hello: typing.Anotated[str, discord.Option(...)]):
...
Don't put the input type inside discord.Option when using that
This might work when using future annotations
how would yall go about triggering multiple bots with the same command at once? (bots for sound playback in different channels) can i use a bot prefix and / at the same time? and how would i make a command exclusively slash or prefix
The bot for the examples is down again....
Multiple bots with same cmd would require all bots to have same prefix
You can use both, slash cmds and prefix cmds in commands.Bot
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
hmhm guess i'd initialize my bot as commands.Bot then, can i just differentiate/make a command exclusively slash or prefix like this?
after some modification it shows the desired behaviour 👍
how to disable a button in pycord
.rtfm Button.disabled
Bruh, how to count the number of reactions to a message?
Do you realize message.reactions return a list of the reactions?

Dumb question: How would I put a standard Discord emoji like
into the title of an embed?
Putting :people: just prints the string (unlike a response), and it doesn't appear to be a standard unicode emoji.
Still interested in answer, but I found a workaround of 👥︎ for now 🙂
Add a backslash behind the emoji
And copy that
Should look like that
Huh...
title=f" Total Player Count (All-Time)", prints the following... Interesting...
I swear I saved too, lol
Is the emoji in a separate server
It's a "vanilla" emoji AFAIK
Like, it's not unicode, but it's also not a server emoji
What
In the same server where you ran the command in the screenshot?
No no, I was being big dumb. It was in a different server, it wouldn't work, etc... Sry.
However, on the subject of "vanilla" Discord emojis:
- ⚠ is a unicode emoji for "warning"
- ⚠️ is
:warning:and isn't unicode (AFAIK, unless I'm being dumb)
\⚠️
oh...
Still different though... \:warning: gives the above. Interesting... Ignore me though... I'm just goin crazy over emojis over here, haha 😅
The Discord emojis are literally Just Twemojis; https://twemoji.twitter.com
my man just deleted his question, I was literally spending the last 10 mins reading trough the docs... bruv;
Best example I could find; --> https://github.com/Pycord-Development/pycord/blob/master/examples/basic_voice.py
@commands.command()
async def join(self, ctx: commands.Context, *, channel: discord.VoiceChannel):
"""Joins a voice channel"""
if ctx.voice_client is not None:
return await ctx.voice_client.move_to(channel)
await channel.connect()
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/examples/basic_voice.py at master · Pycord-Development/pycord
If you use Unicode emojis they will be converted to discord emojis
can i somehow trigger a bot that uses prefix commands with another bot that sends that command? cuz it doesnt seem to work, or is there any other way to trigger it
Why?
How can I add buttons to my embed?
have you read the pycord guide on buttons?
yup, and I can't find where it talks about embedding them :(
not inside?
no, that's not possible
I have a large cog base discord bot I wrote in discord.py, which uses hybrid commands using @commands.hybrid_command and I'm using response views for buttons. How complex would migration be to pycord?
You want to switch to py-cord?
Yes, I'd like to use the voice functionality that py-cord offers and discord.py lacks
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
Its not that hard to switch to py-cord
Thanks, I'll take a look
For prefix and slash_command in one you have to look for bridge command
I see, I take it hybrid_commands don't work then?
hybrid_commands don't exist in pycord
bridge command in pycord is same as hybrid cmds in dpy
@silver moat can help me please ?
Just ask
Don't look for people to help you
while reloading cogs, this error shows up
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BridgeCommand' object has no attribute 'name'
what shall I do to fix this?
I'm sure reloading cogs is broken atm
huh
i tried unloading and loading too
still the same error
I'm sure that's what reloading does internally lmao
man
I want to transfer 8000 bans from one discord to another one. How can i do it good and efficiently without getting ratelimited?
for loop and let pycord handle the ratelimits for you
Okay
Because of this I unfortunately have to ditch bridge.
Changing the code, the cog loaded and worked fine with commands.command() decorator, but after adding commands.slash_command() just below it, it presents me with this error: TypeError: Callback must be a coroutine.
it works on master branch
Is there a way to change default values for all views in a code (like timout time, disable_on_timeout and so on)?
you could make a base class to use instead of discord.ui.View
And... Replace original class?
inherit your individual vew classes from the base class
like:
class BetterView(View):
....
# changes
View = BetterView
dont overwrite View
just leave it at BetterView
you classes could be
class MyFirstView(BaseView):
...
Why? btw
I just don't wanna change View to BetterView everywhere
overwriting could cause issues and we dont support monkeypatching
why could you not use the base class everywhere?
put it in a utility file
and import it wherever you have view classes
It would just be find+replace discord.ui.View with myfile.BetterView though?
There will be the same result as with monkeypatching lmao
Okay, thanks for the tips anyway
is this a good way and would this work?
import asyncio
ncguild = _bot.get_guild(12345)
count = 0
async for ban in ncguild.bans(limit=None):
try:
newreason = f"Transferred Ban. OG Reason: {ban.reason}"
await _ctx.guild.ban(ban.user, reason=newreason)
count += 1
except Exception as e:
await _ctx.send(e)
yield count
and does it also work if the user isnt on the discord where he is goint to be banned?
how can i pack two ids in this method?
what is get?
from discord.utils import get
Has someone already added an view.insert_item?
ik this isnt pycord related but py await self.execute("INSERT INTO inventory (userID, itemID, quantity) VALUES ($1, $2, $3);", int(id), str(item), amount) how do i like insert into the inventory with the itemID being on the items table and the itemid on the inventory is a fk referencing the itemSerial pk on the items table maybe with an inner join or something im really not sure
what can i do?
yeah you can only have some 5k non guild banned members
not sure
huh
but i am at 1981 bans right now
oh then it might be 1k 💀
dk
you could use your own ban manager
if you really wanted
what you mean?
like if a person joins then check if they are banned on the other server
no
maintain your own database of banned members
if a person with a matching id joins, kick them
yeah its just like the same
like a globalban
you could also ban on discord instead of kicking, but you would need to maintain some sort of a rolling list
yea but it would be very bad to get the bans from discord on every join 💀
your local db would be almost instant
yeah true
lol carl bot cant handle the error right😂
lul
but i dont understand, like why do they to this
if you ban a member he also isnt on the guild after this
the member should have joined the guild when you ban
that has a very big limit
is there a max limit for normal bans?
but if you ban when the member isnt in the guild, it has a small limit
that might be 10k. let me check
lol thats very low
like big servers with 100k users?
i think 10k is low
okay how to find out whats the limit
okay
or wait we have our own discord support
is there a way to check the rate limit headers
@waxen whale 
^
not when using the library
yes
FUCK U
there is only a limit when banning users who are not on the server
not sure but 1k?
1k?
imma look
yea thought so
but i banned 1981 users who are not on the server lol
that would be a safety issue
the limit might be x/per time
ah okay
1981 users who are not on the server, or 1981 total users? 🤔
no we had 0 bans on the discord before i run my code
oh hmm
this code
the error apperaded after like 15 minutes
wait but i can check it like this right?
import requests
headers = {
'Authorization': f'Bot Token'
}
url = f'https://discord.com/api/v9/guilds/12345/bans/12345'
response = requests.put(url, headers=headers)
remaining_requests = response.headers.get('X-RateLimit-Remaining')
reset_timestamp = response.headers.get('X-RateLimit-Reset')
await _ctx.send(f'{response}\n{response.content}\nRemaining requests: {remaining_requests}\nReset timestamp: <t:{int(float(reset_timestamp))}:F>')
@proud mason what does it mean
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url(url = url, session=session)
msg = await webhook.send(file = file)
print(msg)
>>> None```
I would like to get the message object from the posted webhook here, however, this always returns None - Is it not possible to get the message object this way?
Idk the raw api in detail. Try asking in ddevs server
For some reason one of my check decorators is being skipped i think
I can't figure out how to disable or delete a view after a button is pressed, how can i do that?
def __init__(self, phrase : Phrase) -> None:
self.phrase = phrase
super().__init__()
@discord.ui.button(label="Aprobar", style=discord.ButtonStyle.success, emoji="👍")
async def button_callback_approve(self, button, interaction : discord.Interaction):
await self.disable_all_items()
reviewer_discord_id = interaction.user.id
reviewer = await User.get(discord_user_id=reviewer_discord_id)
self.phrase.reviewer = reviewer
self.phrase.approved = True
await self.phrase.save()
await interaction.response.send_message("Frase aprobada!")
@discord.ui.button(label="Rechazar", style=discord.ButtonStyle.danger, emoji="👎")
async def button_callback_reject(self, button, interaction : discord.Interaction):
await self.disable_all_items()
reviewer_discord_id = interaction.user.id
reviewer = await User.get(discord_user_id=reviewer_discord_id)
self.phrase.reviewer = reviewer
self.phrase.approved = False
await self.phrase.save()
await interaction.response.send_message("Frase rechazada!")```
edit the interaction response and pass self to the view param
Check decorators should go below the command decorator
Command decorator should be the topmost one
https://uploads.wolfieog.xyz/14l7YnHs5Ixte0Z2Gpv3FT6VcKjXYRnvJpnYPwR8 this is how i have my method structured
the red box is being skipped

Pass None if you want to delete the view entirely
Ah hmm
What's the contents of that check?
edit the interaction? what do you mean?
ignore the print, that was to test if the method was even being called
which it isnt
.rtfm interaction.edit_original_response
Oh wait sorry
oh,
interaction.edit_original_message(None)
like this?
If you have sent a message already, use interaction.message.edit
Pass None to the view parameter
interaction.message.edit(view=None)
@proud mason if i comment out my last decorator, it works
Hmm
Oh huh
Yes
What are the contents of that one?
I don't see anything that would cause issues
neither
Do >2 checks not work on any cmd
Your last check is raising an error
That's why the 2nd last one isn't working
The checks are executed in a bottom->up order
When then it works right?
nope
The checks are working
So yea it is raising
This
but, the artist value is none
the check is not even called
the artist check is ontop of the timeline check
I think the checks are called bottom to top
The ones closer to the function are called first
i thought it was top to bottom
I think in prefix cmds it is top to bottom 💀
ffs
Fked up disparity
ill test it
👍
But prefix cmds reverses them
Huh that's actually wrong
Can i send multiple photos at once and if yes how
Yes. Pass a list of discord.File objects to the files parameter
alr ty
@proud mason time to sort my decorators, thanks for helping
so do i do it like this?
lists are [] not {}
oh sorry lol
also you can just leave the content param unset
ctx.send(files=[discord.File(), discord.File()])
kk
Please ping me when responding ^^
Pass wait=True when sending
Thank you!
is there any way to prepopulate a modal field with a parameter of a slash command that invokes the modal?
Something like
self.add_item(InputText(label="Phrase", placeholder="Phrase for the bot to say", prepopulate=parameter))
pycharm keeps complaining about this line:
if ctx.author.guild_permissions.kick_members:
Am I doing sth. wrong?
(its working though)
I don't think that's possible, but why do you need a modal and a slash command?
I have a /suggest command. But users keep writing the suggestion after the command. I still want to use the form to give it a title and some extra context. So I though I could pre-fill a field with the words written after the command
So don't support any options in /suggest?
right now it doesn't
You can ignore it
Prefill the value
.rtfm inputtext
discord.ui.InputText
discord.ui.InputText.custom_id
discord.ui.InputText.label
discord.ui.InputText.max_length
discord.ui.InputText.min_length
discord.ui.InputText.placeholder
discord.ui.InputText.refresh_state
discord.ui.InputText.required
discord.ui.InputText.style
discord.ui.InputText.to_component_dict
discord.ui.InputText.type
discord.ui.InputText.value
discord.ui.InputText.width
discord.InputTextStyle
discord.InputTextStyle.short
discord.InputTextStyle.long
discord.InputTextStyle.singleline
discord.InputTextStyle.multiline
discord.InputTextStyle.paragraph
perfect, I was about to try exactly that.
Haha
is there a way to also fix it?
ik this isnt pycord related but py await self.execute("INSERT INTO inventory (userID, itemID, quantity) VALUES ($1, $2, $3);", int(id), str(item), amount) how do i like insert into the inventory with the itemID being on the items table and the itemid on the inventory is a fk referencing the itemSerial pk on the items table maybe with an inner join or something im really not sure anyone
If you're not using an orm you'd have to insert the item first, get the id, then insert the id here
well im having a separate issue from this right now lol
UPDATE inventory SET quantity=$1 FROM items WHERE inventory.userID=$2 AND inventory.itemID=$3 AND inventory.itemID = items.itemSerial;``` i think that its trying to insert a string into the itemID in the inventory from items which is an integer
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: DataError: invalid input for query argument $3: 'item1' ('str' object cannot be interpreted as an integer)```
So do int()?
traveling across discord servers I have found such thing
it's like additional profile info provided by bot
is it possible to create something like this using pycord
and if yes where I can find more info about it
@ionic hull
thanks!!
i tried running my discord bot on my python but what happened is that is came up with this syntax error, why? (i scribbled out my bot token)
?tag replit
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
@strange jackal ^
thanks
ive done all the steps then this error pops up when i try run my code
also:
Why NOT to use Repl as a hosting platform
You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.
- The machines are super underpowered.
This means your bot will lag a lot as it gets bigger. - You'll need a web server alongside your bot to prevent it from being shut off.
This isn't a trivial task, and eats more of the machines power. - Repl.it uses an ephemeral file system.
This means any file you saved via your bot will be overwritten when you next launch.
IMPORTANT
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for a vps.
and second of all
#help-rules top block, rule 1: learn python
If u need a server to learn more about python stuff > https://discord.gg/python
k
how would I go about sending this type of formatted message from my bot
like this sort of screen
discord.Embed
discord.Embed.Empty
discord.Embed.add_field
discord.Embed.append_field
discord.Embed.author
discord.Embed.clear_fields
discord.Embed.color
discord.Embed.colour
discord.Embed.copy
discord.Embed.description
discord.Embed.fields
discord.Embed.footer
discord.Embed.from_dict
discord.Embed.image
discord.Embed.insert_field_at
discord.Embed.provider
discord.Embed.remove_author
discord.Embed.remove_field
discord.Embed.remove_footer
discord.Embed.remove_image
Ah, thank you. I managed it that way. 😄
how can i get the message author in auto complete
.rtfm Autocompletecontext
on_voice_state_update
player = self.client.lavalink.player_manager.get(member.guild.id)
AttributeError: 'NoneType' object has no attribute 'player_manager'
``` i know about none type, i recive this before the bot has the chance to cache all members
@silver moat i belive you helped me a long time ago on enabling caching so the whole thing works
^ chunk_guilds_at_startup
also if not, is there a way to make chunk_guilds_at_startup hapen in a faster mannor
or am i limited by the gateway
@signal sandal Don’t ping helpers for help, even if they have helped you before.
sorry
how do I send a paginator in response to an on_message listener? I only have a Message object, so I don’t have an interaction or a context to use, and there are as far as I know only two ways to send a paginated response, paginator.send and paginator.respond
btw docs say to check out #ext-pages here on the discord, but I’m not seeing that channel anymore. maybe because v3 is going to revamp things considerably?
Add bot.wait_until_ready at the top of that function
.rtfm wait_until_ready
discord.Client.wait_until_ready
discord.AutoShardedClient.wait_until_ready
discord.ext.bridge.Bot.wait_until_ready
discord.Bot.wait_until_ready
discord.ext.commands.AutoShardedBot.wait_until_ready
discord.AutoShardedBot.wait_until_ready
discord.ext.commands.Bot.wait_until_ready
discord.ext.bridge.AutoShardedBot.wait_until_ready
Uh yes that is a very weird state rn. I'll try if I can work on a better solution
As of now, you could make a fake Context, using bot.get_context(msg)
And pass that
async def on_voice_state_update(self, member: discord.Member, before: discord.VoiceState,
after: discord.VoiceState):
voice = discord.utils.get(self.client.voice_clients, guild=member.guild)
player = self.client.lavalink.player_manager.get(member.guild.id)
if not voice:
if player:
await cleanup(player)
return
elif voice.channel != before.channel: # ignore if the member joined a voice channel
return
elif member.bot:
return
if after.channel != before.channel:
memberlist = []
for m in before.channel.members:
if not m.bot:
memberlist.append(m.id)
if player.current and player.current.requester not in memberlist:
player.votes.clear()
if not memberlist:
if player.is_playing:
await cleanup(player)
await voice.disconnect(force=True)
``` thats the entire block, where should i add the wait until ready
should i use this just after the aysnc def? await self.wait_until_ready
yes. But self.bot and don't forget () at the end
ok one sec
async def on_voice_state_update(self, member: discord.Member, before: discord.VoiceState,
after: discord.VoiceState):
await self.bot.wait_until_ready()
voice = discord.utils.get(self.client.voice_clients, guild=member.guild)
player = self.client.lavalink.player_manager.get(member.guild.id)
if not voice:
if player:
await cleanup(player)
return
elif voice.channel != before.channel: # ignore if the member joined a voice channel
return
elif member.bot:
return
if after.channel != before.channel:
memberlist = []
for m in before.channel.members:
if not m.bot:
memberlist.append(m.id)
if player.current and player.current.requester not in memberlist:
player.votes.clear()
if not memberlist:
if player.is_playing:
await cleanup(player)
await voice.disconnect(force=True)
```updated
still throwing the error AttributeError: 'Music' object has no attribute 'bot'
Also, just use member.guild.voice_client instead of discord.utils.get
Why not pay attention to your own code instead of simply copying what I said
You have named your bot self.client
So use that
whoops
late for me didnt notice
self.client.lavalink.player_manager.get(member.guild.id) and for this i can just swap for member.guild.voice_client
ive now hit a diffrent wall line 408, in music player = self.client.lavalink.player_manager.create(ctx.guild.id) AttributeError: 'NoneType' object has no attribute 'player_manager'
ods are bc of caching again
stick the wait until and then ill come back
your lavalink client is most likely not initialized yet
it is, just my code requires me to cache the member list so that takes a bit
but if i could write a event handeler for this where if bot is not ready and command is requested, repond with the bot is not currently accpeting etc etc
maybe ill attack that tmr
should get some sleep in
while loop time
would something of this mannor work? if not self.client.is_ready:
Use asyncio.Event
Ty
thank you, that made the cog reload without any errors.
i can use prefix commands in cogs now, but slash commands dont show for some reason, they did before i created cogs, any idea?
why can't we just make a release already ;)
Bob™️
.tag slashnoshow
Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
I'm learning how to use role connections
is it pssoble to update user's role connection via pycord?
like this in docs
nope, go and learn OAuth2
I don't mean that in a mean way, but OAuth2 is not helpful /applicable for 99% of users so the library isn't built to support that
I have already authorized using oauth2, received code and exchanged it to bearer access token
but yeah also #998272089343668364 message
where should I pass this token to continue?
Sorry, I haven't done this myself before, so I do not know.
anyway thanks
i see, should i load cogs before on_ready or the opposite?
this is what i currently do
and yeah, the bot does have application.commands scope, slashes were working before
im using the master branch
cogs should be loaded before on_ready
ah
YO they showed up
thank you for the help
Nice
yay
what editor is that
sublime text
oh nice, thank you! that makes sense to me. I wonder if it makes sense for the paginator API to render something that can then let the caller decide how to send (via interaction.response, ctx.whatever, some other means). in my case, I’m storing a discord user ID in the db and then later sending a message to the user with that id
ah dang, the guard is strong: TypeError: expected Interaction or BridgeContext, not <class 'discord.ext.commands.context.Context'>
can i not create command groups in bridge module?
you should be using Paginator.send?
sorry, you’re right. had a conditional and I copy-pasted poorly. I got it working! thanks!
Can I create a dynamic cooldown with an async function?
nvm, i got the answer through docs, dont know how i missed it beforehand
I have a basic question, which I am confused about.
So when I use ctx.respond, I want it to mention the user, but I have no idea how to use it. Any help?
what is the reason for needing an async func?
Do you mean mentioning the user in text like this?
@brisk palm
Like this
slash commands aren't replies so that's not possible
aaah got it
replies also need a message to reply to, which doesn't exist
so yeah, mentioning them in raw text is probably your best bet
Gotcha, coz I was confused, saw a guy doing it on youtube, and I was like, doesn't work on mine for some reason
Thanks for the help man!
i am trying to load something from a database
np
@fervent cradle please do not crosspost
no, your problem is large enough that it would calls for a thread
you can try using asyncio.run (https://docs.python.org/3/library/asyncio-runner.html#asyncio.run)
I said #help-rules
your post contained insufficient information
I tried using asyncio.run but i got this error:
RuntimeError: asyncio.run() cannot be called from a running event loop
ok try using this lib with it, https://pypi.org/project/nest-asyncio/
so what are the ways of taking user input
Why are you using asyncio.run?
Why not use asyncio.create_task
Or bot.loop.create_task
Text messages
Slash commands parameters
UI (Buttons, select menus, modals)
Reactions
so how do i take it from a text message
ok so lets say i want the user to start a game (and call the bot) by entering a slash command, and then the program returns instructions for the game and asks the user for further input numerous times, how would i implement this chain of events
would i create separate functions for each time i require further user input
Are discord.Colour values 0-255 or 0-100 (or something else)?
More features to make your bot cool and snazzy.
is it possible to get the date of a member's last interaction? I'm trying to make an inactivity list command
Hey, how do I check how many messages a user sent to the whole server? This is similar to from: user parameter in the search option that returns the amount of results (amount of messages)
last interaction? like the last time a user used your bot's command? nope the api give you anything like that. you can use your own database
no easy way to do it. even the search feature is only for users and not bots
ah
was thinking more of messages than commands
then any other ways?
but yes, again, I can use my own database hehe
not a way i would recommend. you will need to go through the message history of all the channels in the server
very bad way and could easily ratelimit you
i ❤️ 429
nope not that either
yea lol
thanks
what practical use can i make of from bridge.map_to?
it is for bridge group commands
since slash groups cannot have a base command, you need to map it to a subgroup
see this. you cannot have a command called /afk and also have subcommands.
this feature is available in prefix groups tho
where .afk and .afk set can both exist
so by using map_to, you could have the /afk command at a subcommand like /afk help or smth
while the prefix variant stays at .afk
I want to add permanently disabled buttons kinda like headings for the other buttons, what's the best way of doing this? Using a decorator above an empty callback function seems kinda pointless
v3 is not complete and there is not eta for it
oh so 2.4 is the latest one? okay thank you
the stable release is 2.4.1 and latest one is 2.5 (master branch). docs for both can be found at https://docs.pycord.dev
Pycord is a modern, easy to use, feature-rich, and async ready API wrapper for Discord. Features: Modern Pythonic API using async/ await syntax, Sane rate limit handling that prevents 429s, Command...
Its still 2.4.1 not 2.5
yea lul. 2.4.1 is the "stable release"
is it possible to loop embeds
Is there a reason why discord.Member.display_name would return the username and not the display name for a user with a new discriminator-less username? Is this just API growing pains of the new name system, or am I doing something wrong?
how do i edit a message, where the file gets edited bc when i do
await message.edit(file=file)
``` it adds an file and i want that the file that is already in it gets edited
cause display name internally returns the nickname or the username
global_name returns the global display name iirc?
depends on what version youre using
pass attachtments=[] instead
Ahh, so if the user doesn't have a specifically assigned Guild name it will just return the username? Would be nice if default functionality was to return Global name instead, but I understand if it's not possible. Thanks 🙂
Also, I don't see a global_name attribute for Member in the docs. If I'm on the latest stable version, does this function exist?
Ahh, gotcha. Thanks for the info
thx
My bot isn't properly displaying a custom emoji
and instead is showing
when I inputted:

I tried in an embed and outside of an embed
I also tried adding spacing
and using discord.partialemoji
you probably got the ID wrong
or the bot role/@everyone needs the Use External Emoji permission
got that beforehand
And the ID was from \ing the emoji
how would I get it correctly?
is the bot in the server with the emoji
No
it's an external emoji from another server
is that required?
yea
Ok just uploaded the emoji to the server the bot is in, and it worked!
Thx

The current stable version doesn't have the updates for the new usernames
Sorry for noob question, but is there a way to get the version with the updates through pip? Or is it only available through GitHub?
Did you run the command with git?
Yeah, you can do pip install and then the git url
- 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 here ^
finally got a chance to keep testing this out, and the pagination buttons aren’t working 🤔 no exceptions thrown, no debug level logs 🤔
Ahhh, understood
Thank you for the efforts
How to set timestamp in an embed?
embed = Embed(timestamp=<datetime>)
try disabling author_check
embed = discord.Embed(color=0xBEFFE1)
embed.set_author(name="Error!")
embed.add_field(name="Spacey Boi",
value=" is not actively responding to the music command right now, please try again in a few minutes")
embed.add_field(name="Support Server", value="If you need help, feel free to join my support server over at [support.spaceyboi.com](https://support.spaceyboi.com)")
embed.set_footer(text="Spacey Boi! • https://spaceyboi.com", icon_url=self.bot.user.display_avatar.url)
await ctx.respond(embed=embed)
else:
await self.client.wait_until_ready()
try:
currently using this but how would i implement asyncio
also do i need a parenthesis at the end of
self.client.is_ready
yeah i do whoops
dont check is_ready if you are also using wait_until_ready. simply use wait_until_ready, as it will immediately return if the client is already ready
oh wait
i use wait until ready to stop errors
why are you waiting until ready if is_ready is true?
i had an error yesterday most likely bc i forgot the paren
commands shouldnt work until the bot is ready
so i threw it in to stop so i could sleep lmao
?
gonna do this now and restart any try ```
if not self.client.is_ready():
embed = discord.Embed(color=0xBEFFE1)
embed.set_author(name="Error!")
embed.add_field(name="Spacey Boi",
value=" is not actively responding to the music command right now, please try again in a few minutes")
embed.add_field(name="Support Server", value="If you need help, feel free to join my support server over at support.spaceyboi.com")
embed.set_footer(text="Spacey Boi! • https://spaceyboi.com", icon_url=self.bot.user.display_avatar.url)
await ctx.respond(embed=embed)
else:
try:```
client.is_ready() will return true inside a command. it is because commands wont run until bot is ready
you wouldnt need a check for ready in a command
you were doing some lavalink stuff right
well, i do bc my command requires the member list to be cached
you would need a separate asyncio.Event for it
indeed
oh
sorry but im not quite sure how i would go about implimenting that
are you sure the command runs before on_ready is fired?
yeah
woah. this is interesting. ill check this out
bc other commands work
i have commands that are not dependant on the member list running
hmm



