#Basic Pycord Help (Quick Questions Only)
1 messages · Page 88 of 1
one sec
await self.client.wait_until_ready()
lavaclient = lavalink.Client(user_id=self.client.user.id, player=CustomPlayer)
lavaclient.add_node(host='127.0.0.1', port=2333, password='gmkwob', region='us')
lavaclient.add_event_hooks(self)
self.client.lavalink = lavaclient
ic
all the lavalink related commands stay in a single cog right?
so you could make a self variable in the cog init
smth like self.lava_ready = asyncio.Event()
yeah
in your connect nodes method, do self.lava_ready.set() at the end
and in your cmds, add await self.lava_ready.wait() at the top instead of wait_until_ready
or you could use self.lava_ready.is_set() to return errors n stuff
oh cool
i had copied the error and footer stuff from a diffrent cog and stuff so it had bot, and i was tired yester day and i didnt catch it lmfao
also where would i add that?
oh lol
@slash_command(description="Play some music (use again with no music selected to access menu). ")
async def music(self, ctx, search: Option(str, description="Music query or URL", required=False, default=None)):
await self.lava_ready.wait():
embed = discord.Embed(color=0xBEFFE1)
embed.set_author(name="Error!")
embed.add_field(name="Spacey Boi",
value=" is starting up 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.client.user.display_avatar.url)
await ctx.respond(embed=embed)
else:
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.respond(f"You need to be in a voice channel", ephemeral=True)
player = self.client.lavalink.player_manager.create(ctx.guild.id)
try:
``` this?
my current setup without the asyncio event seems to work okay
should i still make the change?
async def music(self, ctx, search: Option(str, description="Music query or URL", required=False, default=None)):
if not self.client.is_ready():
embed = discord.Embed(color=0xBEFFE1)
embed.set_author(name="Error!")
embed.add_field(name="Initializing",
value="Spacey Boi! is still starting up, 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.client.user.display_avatar.url)
await ctx.respond(embed=embed)
else:
try:
running this +
@lavalink.listener(lavalink.events.QueueEndEvent)
async def event_queue_end(self, event: lavalink.QueueEndEvent):
guild_id = event.player.guild_id
guild = self.client.get_guild(guild_id)
await guild.voice_client.disconnect(force=True)
Uh there is a small gap between wait until ready, and the node connection completing yk
ic
Mhm
doubt any errors will be uncaught
any how, thanks for ur help
i asuume i will be back
im sure there is a far better way to do this but , ```
if not self.client.is_ready():
if uc < 100000:
embed = discord.Embed(color=0xBEFFE1)
embed.set_author(name="Error!")
embed.add_field(name="Initializing",
value="Spacey Boi! is still starting up, please try again in about 30 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.client.user.display_avatar.url)
await ctx.respond(embed=embed)
if 100100 < uc > 200000:
embed = discord.Embed(color=0xBEFFE1)
embed.set_author(name="Error!")
embed.add_field(name="Initializing",
value="Spacey Boi! is still starting up, please try again in a 20 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.client.user.display_avatar.url)
await ctx.respond(embed=embed)
if uc > 250000:
cut off bc char limit
uh are you sure this is correct 100100 < uc > 200000
fixed
< uc <
yeah late night work is a bad idea, yet i do it
very pleasing not to see errors spamed
fr
so clean
uc = len(bot.users)
while uc == 50000:
print("50k")
while uc == 100000:
print("100k")
while uc == 150000:
print("150k")
while uc == 200000:
print("200k")
while uc == 250000:
print("250k")
while uc == 300000:
print("300k")
while uc == 350000:
print("350k")
``` is this stupid or functional
basicaly prints when cached list reaches x ammount
wait, could i have it like
while uc == 50000+-x ammount:
uc = len(bot.users)
while 40000 < uc < 50000:
print("50k")
while 90000 < uc < 110000:
print("100k")
while 148000 < uc < 160000:
print("150k")
while 190000 < uc < 210000:
print("200k")
while 248000 < uc < 260000:
print("250k")
while 290000 < uc < 310000:
print("300k")
while 348000 < uc < 352000:
print("350k")
``` updated
why while loop
exactly 💀
uc never gets updated inside the while loop either. so it is basically a while True loop
?
wdym
You could use self.add_item in the view init, and pass instances of discord.ui.Button
Make sure to set the rows for all buttons
bot.get_user or guild.get_member is returning none even tho the user exists because its my id
Why? 
thx
Where are you accessing it?
Also, passing int right?
mainly in a flask app
yk like for a dashboard
adding them in init moves them to the far right, they should be on the left instead. Is this possible?
And how do you access the bot?
And how do you deploy?
Uh not an easy way iirc. You need to reorder view.children
argh
but thank ya
Wouldn't it be more intuitive for buttons added in init to be placed on the left and all buttons added after that to be on the right (in chronological order)?
i think the buttons through decorator are added through __new__ and not __init__
not sure
or wait
do you call super init before or after adding your buttons?
try calling super init after add_item
👍
doesn't work, since add_item appends the item to self.children which doesn't exist before super init is called
Could I just create self.children manually?
ah
nope. bad idea
you could see the workings of the decorator if you want
I'll take a look
hmm i just had a look. cant really use that
making empty functions might be the easiest way here
That's sad but prob best, thank ya
Tbh, I didn't really understand the decorator code, where does it append the button to the view?
yeah it doesnt. it sets this func.__discord_ui_model_type__ = Button. and then __init_subclass__ picks it up from that
Shouldn't it be possible to change __init_subclass__ to get it to work?
If so, might be wise to change it for the entire library to make it more intuitive
you could try your own solution
but yeah a mixture of add_item and decoraor is rare
Just going to create a thread
#1125007798254702652
Can anyone guide me on how to add aliases for prefix commands in bridge module?
aliases=[""]
just like regular text-based commands
So that means I just need to do this,
bridge.bridge_command(aliases=["alias1"])
Last time I tried this didn't work, must have missed something, I'll re-check
nice, that worked! thanks again!
Any way I can programmatically get the old username of someone ?
The old username badge?
I'm not sure if bots can access that
I didn’t think so. I was trying to see if I could access the previous username and update my db with the new.
please don't tell me you used usernames as a primary key...

What is the best away to add new functions to base Classes (for example to Interaction or Context) (maybe monkeypatching?)?
Like add await ctx.debug() to send embed with debug info
degug?
typo
hi, it's me again
I continue learning how to use role connections
I have already created a connected role using my bot
and I see my linked role and app info in my profile
the problem is - other server members don't see the app info
and even I if i view server as any role I don't see it
any thoughts where have I mistaken?
Heya, what would this type of view be called in the docs?
uhm, embed?
Hello. There was a problem understanding how to work with Cogs. Can you explain? I understood how to use Cogs, but not how to create them...
You should only add new functions to Context
Interaction is a Discord Model. Those shouldn't be and cannot be modified
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
They have __slots__ defined. So you can't even add attributes/methods
Oof
I looked into this first but didn't get an answer
Subclass Cog?
and add _init_ with self.bot
But, Can I modify InteractionResponse?
Do I need to create a Cogs folder in the folder where the main code file is located?
I wanna add an ability to auto-update embed if InteractionResponse wasn't used in components callback
Nope. That too is a Discord Model iirc. Try checking the docs
If it is a Data Class, you could modify it
Not necessarily. But recommend if you have more than 1-2 cogs
I have already succeeded with monkeypatching InteractionResponse
Will all Cogs be able to access the main database?
I already know, that I can add something like that if I modify view._scheduled_task and add finally to it
Yes, never had problems with calling sql from code
Thank you
I tried using await interaction.delete_original_response()but I somehow get the following error:
Ignoring exception in view <EmbedToolView timeout=180.0 children=20> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Confirm' emoji=None row=4>:
Traceback (most recent call last):
File "C:\Users\user\Documents\Programming\AIM-Bot\venv\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\user\Documents\Programming\AIM-Bot\cogs\messages.py", line 513, in cancel_editing
await interaction.delete_original_response()
File "C:\Users\user\Documents\Programming\AIM-Bot\venv\Lib\site-packages\discord\interactions.py", line 506, in delete_original_response
await func
File "C:\Users\user\Documents\Programming\AIM-Bot\venv\Lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
can you show the callback for the button?
@discord.ui.button(label="ᅠᅠCancelᅠᅠ", style=discord.ButtonStyle.red, row=4)
async def cancel_editing(self, button: discord.ui.Button, interaction: discord.Interaction) -> None:
"""Callback for the cancel button.
Parameters
------------
button: discord.ui.Button
The button that was clicked.
interaction: discord.Interaction
The interaction that clicked the button."""
if self.canceled_before:
await interaction.delete_original_response()
return
self.canceled_before = True
button.label = "ᅠConfirmᅠᅠ"
await interaction.response.edit_message(view=self)
how can i detect when my bot is abt to go offline/shutting down?
i need it so i can close db connections
afaik it's impossible to predict future, so I recommend you to subclass Bot class and override close func
class BetterBot(Bot):
async def close(self):
await self.aiosqlite_clean_up()
await super().close()
async def start(self):
await self.aiosqlite_start()
await super().start()```
yeah this is the best way
||start might be better than login||
login is more fun
Took one hour to cache everything lmao, but atleast only one command is unuseable
how to get user server name?
.rtfm guild.name
How would I go about sending a message after a button timeout?
Lmao wtf? How big a bot do you have?
355k rn
💀
1 hr tho
Don't wanna be anoying, but any ideas?
There are quite a few replys
But, u could make a shutdown function where you disconnect from your db
Who are you refering to?
defer before deleting
thx
Gn
hi
i added the button
but i cant the button how to disabled true on clicked
help me
@versed fern
.rtfm button disabled
discord.ui.button
discord.Button
discord.Button.custom_id
discord.Button.disabled
discord.Button.emoji
discord.Button.label
discord.Button.style
discord.Button.to_dict
discord.Button.type
discord.Button.url
discord.ui.Button
discord.ui.Button.callback
discord.ui.Button.custom_id
discord.ui.Button.disabled
discord.ui.Button.emoji
discord.ui.Button.from_component
discord.ui.Button.is_dispatchable
discord.ui.Button.is_persistent
discord.ui.Button.label
discord.ui.Button.refresh_component
Set button.disabled to True
Then use interaction.response.edit_message and pass view=self
i tried but :
AttributeError: 'Interaction' object has no attribute 'disabled'
code:
def __init__(self, user_id, user_name):
super().__init__()
self.user_id = user_id
self.user_name = user_name
@discord.ui.button(label="Create", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction):
user_id = self.user_id
user_name = self.user_name
# createNewUser(user_id,user_name)
button.disabled = True
# await interaction.response.send_message('Kullanıcı oluşturuldu....', ephemeral=True)
await interaction.response.edit_message(view=self)
self.stop()
What IDE/text editor are you using?
what is this IDE?
💀
huh?
Oh, wait, probably vscode
pip list in terminal and send output
okay
aiosignal 1.3.1
asgiref 3.6.0
async-timeout 4.0.2
attrs 23.1.0
certifi 2022.12.7
cffi 1.15.1
charset-normalizer 2.1.1
colorama 0.4.6
configparser 5.3.0
discord 2.2.3
discord.py 2.2.3
discord-py-interactions 5.7.0
discord-typings 0.6.0
Django 4.2.1
EasyProcess 1.1
emoji 2.6.0
entrypoint2 1.1
frozenlist 1.3.3
gevent 22.10.2
greenlet 2.0.2
idna 3.4
MouseInfo 0.1.3
mss 9.0.1
multidict 6.0.4
numpy 1.25.0
opencv-python 4.8.0.74
packaging 23.1
Pillow 9.5.0
pip 23.1.2
psutil 5.9.5
PyAutoGUI 0.9.54
pycparser 2.21
PyGetWindow 0.0.9
PyMsgBox 1.0.9
pyperclip 1.8.2
PyRect 0.2.0
pyscreenshot 3.1
PyScreeze 0.1.29
pytesseract 0.3.10
pytweening 1.0.7
pytz 2023.3
requests 2.28.1
screeninfo 0.8.1
setuptools 65.5.0
sqlparse 0.4.4
tomli 2.0.1
typing_extensions 4.7.0
tzdata 2023.3
urllib3 1.26.12
websocket 0.2.1
websocket-client 1.4.2
windows-curses 2.3.1
yarl 1.9.2
zope.event 4.6
zope.interface 6.0
So are you using discord.py or pycord?
um yeah i using discord.py
i stopped using it for a long time and so i forgot a lot of things
i restarted
Ok, so switch the interaction and button args here:
class newUser(discord.ui.View):
def __init__(self, user_id, user_name):
super().__init__()
self.user_id = user_id
self.user_name = user_name
@discord.ui.button(label="Create", style=discord.ButtonStyle.green)
- async def button_callback(self, button, interaction):
+ async def button_callback(self, interaction, button):
user_id = self.user_id
user_name = self.user_name
# createNewUser(user_id,user_name)
button.disabled = True
# await interaction.response.send_message('Kullanıcı oluşturuldu....', ephemeral=True)
await interaction.response.edit_message(view=self)
self.stop()
yw
I want to add 📥 & 📁 to a button, when I copy and paste them into my code they convert to :strings:, which don't render back into an emoji if placed in label= or result in an exception ('Invalid emoji') if placed in emoji=. Copy and pasting the emoji equivalent \📥 & \📁 from a google result into my code works, but doesn't render it in Discord style. How do I get this working?
You can't
Ah, thanks
I'm trying to handle errors globally, but it seems like on_command_error isn't called when I raise(mysql.connector.Error) when using /map. So my question is, is this because global error handling only allows for Pycord's specific errors? If so, how am I supposed to handle non-pycord errors?
@bot.event
async def on_command_error(ctx, error):
if (error, mysql.connector.Error):
print("sql error!")
print("Error occurs")
if isinstance(error, commands.MissingRequiredArgument):
ctx.send(
"You are missing arguments. Please use `/help` to ensure that you are using the command correctly.")
else:
ctx.send(f"An unexpected error occured: {error} ")
@bot.command(name="map", brief="shows map", description="Shows the map of the community")
async def showMap(ctx):
# print(ctx.guild.id)
raise mysql.connector.Error
await ctx.respond(f"Her's the url: placeholder")
you could download the relevant emoji from twemoji and upload it as a custom emoji in a server
Thanks for the suggestion, and that doesn't require Discord Nitro or anything?
you can get a fairly decent quality image by right-clicking the emoji in discord web
nope
ill show you one sec
like that
@hearty gorge
Legend thank you!!
haha no worries
I'm trying to get the embed object from an old message. When I fetch the message using it's ID, it returns an _EmptyEmbed object. Is there any way to fix this?
Greetings, I am trying to ping a role with a slash command however when the slash command goes through, the ping shows up but is not highlighted nor does anyone get a notification. I keep seeing people talking about "allowed_mentions" and I've tried using it in several different ways, but no luck.
I've attached the code that the slash command is in, and an example message when the command is ran. Any help, if possible, would be appreciated
this might have something to do with the fact that you are mentioning in followup.send
bot permission are kinda fucked up on discord's end with regards to interactions
try doing the same in a normal response message without deferring
hey everyone, if i defer() with ephemeral=True, does interaction.response.send() also become ephemeral?
you have to ephemeral both
ok ok thx
if you defer, you can't respond. However, the ephemerality of the interaction is determined by the original response. For example, you if defer ephemerally, the follow-up must be ephemeral. However, you cannot defer non-ephemerally and send a follow-up ephemerally and vice versa.
ah right thanks!
Wow.... that worked! Thanks, can't believe that was the issue
not really, it's just webhooks
Yeah right
Interactions are webhooks under the hood
Mentioning slash commands don't work at all? https://cdn.nziie.xyz/u/0hvG91I1krLp https://cdn.nziie.xyz/u/vCfg12AWxbZO but i saw another bot mentioning slash commands in an embed
Makes sense
Not everything renders in modals
Chat input is not the same as input text
Ah my bad
yeah they patched that
but i even did a valid slash command with the bot's id, and no mention
you can't just mention non-existing commands
ik i mean as a user
Right click on the command after selecting it in chat input
and having developer mode enabled
Not sure if that works on mobile
Yep
it doesn't
That also works
Yes, but not on mobile 💀
Big F
There is so much that doesnt work on mobile xd
where do I set guild_only in a command group?
do I set it in group.command() or SlashCommandGroup()
it has to be set on the top-level, so the command group
keyword_commands = SlashCommandGroup(
name="keywords",
description="Manage trigger keywords for guides (requires Manage Server)",
guild_only=True
)
like this then?
aight thanks
I'm having a problem with py-cord, and it's that after a while of not having used the bot, when a command is executed, it gives a 404 error as "unknown interaction", but when I run it again (the command), it doesn't happen anymore. Is it a code error or something? It happens with all commands.
Seems like a Discord thing
with modals, is there a way to tell if the user pressed 'Cancel'?
there is no definitive way
Afaik no, but you can use timeout system with buttons like:
User presses the button
Modal opens
Wait 180 seconds
If no modal answer, then user closed the modal
That's not an entirely reliable way of doing it since it could genuinely be just left open for 180 seconds since user is AFK or something
But its fine I'll just do a different approach to what im doing which is buttons being disabled when the modal is open and so far when the user clicks 'Cancel' i need a way to re-enable the buttons
Why do you need to disable the buttons?
I hope this fits in here but I wanted to ask if anyone can help me with pip venv.
Hi, is there any testing library for pycord like dpytest?
not as far as I know?
dpytest might actually work with pycord
you would need to try it and see
Although pycord has its own testing extension in the works
bob
does autocomplete not filter if theres not so many items? lets say i have 4 items does it not filter for those?
mhm?
ah okay i thought it was just something with my code
expansion_amount = round(random.randint(400, 5000), -1)
if await self.increaseBankCapacity(uid, expansion_amount):
l = f"Your bank space has been successfully expanded by **{expansion_amount}**"
else:
l = f"Something went wrong with the transaction!"
return l``` how can i generate the expansion amount into a variable if the user inputs multiple use items, but i also want to be safe if they input a large number like 1k (if they reach that many items) How can i potentially prevent it from taking a long time to reply as well?
is this an efficient way of removing documents?
async def on_guild_remove(self, guild: discord.Guild):
guild_id = guild.id
collections = await self.db.list_collection_names()
async def delete_documents(collection, guild_id):
await collection.delete_many({"guild_id": guild_id})
coroutines = []
for name in collections:
collection = self.db[name]
coro = delete_documents(collection, guild_id)
coroutines.append(coro)
await asyncio.gather(*coroutines)
coroutines.clear()
this part could be better done using TaskGroups
also, no need to define delete_documents inside the method??
async def delete_documents(self, collection, guild_id):
await collection.delete_many({"guild_id": guild_id})
async def on_guild_remove(self, guild: discord.Guild):
guild_id = guild.id
collections = await self.db.list_collection_names()
async with asyncio.TaskGroup() as task_group:
for name in collections:
collection = self.db[name]
await task_group.create_task(self.delete_documents(collection, guild_id))
something along the lines of this?
yes but i dont think you are supposed to await create_task (in order to gain advantage of TaskGroup)
oh yeah my bad, appreciate the feedback!
oh yk if you are just calling a single function from delete_documents, you could just ditch that and directly call collection.delete_many
what are de differences between ctx.reply() and ctx.respond() ?
after re-generating a bot token, do you need to do the OAuth2 url thing again?
Uh depends
ctx.reply is for prefix cmds and ctx.respond is for app cmds
But both are the same for bride cmds
No
ah weird, I’m getting a 404 error with ctx.defer() all of a sudden in a new deployment env
are you on pycord 2.4.1
I think discord might be having some stability issues or something
is there a limit to the amount of pages you can have in a paginator
uhh your memory.
incredible very cool
was looking at the docs about editing my bot's username with a command, i see that discord.ClientUser.edit returns a discord.ClientUser
do i actually have to set my bot.user to this or what do i do with it
actually scratch that bot.user cant be edited, safe to ignore?
it just returns the updated value for convenience
Is there a simple way to convert mentions to plaintext as discord displays them? (@colin instead of @cosmic fern), without using message.clean_content, as ideally I want to convert them before sending the message.
unfortunately clean_content doesn't seem to support escaped mentions, and will return something like <@ 857027925944696873> instead of the mention as it is displayed in discord (when using for example, allowed_mentions=AllowedMentions.none())
not that I know of. You could try using message.mentions and doing str.replace.
Right, though that would still require sending the message first I guess
and actually
that's essentially what clean_content does, so not sure that would work
ah yeah thats exactly what clean_content does. So i'd need to write another set of re.escape functions for escaped mentions I guess
transformations = {
re.escape(f"<#{channel.id}>"): f"#{channel.name}"
for channel in self.channel_mentions
}
mention_transforms = {
re.escape(f"<@{member.id}>"): f"@{member.display_name}"
for member in self.mentions
}
# add the <@!user_id> cases as well..
second_mention_transforms = {
re.escape(f"<@!{member.id}>"): f"@{member.display_name}"
for member in self.mentions
}
transformations.update(mention_transforms)
transformations.update(second_mention_transforms)****
hi my bot running with prefix but i want to bot running with slash command
how can i change
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
okay
hey i visited the link
my bot running with cog
i cant changed my bot slash command
see those for slash cmds in cogs
huh okay
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'
intents = discord.Intents.all()
# shard_count = 1 # toplam shard sayısı
# shard_ids = [0] # mevcut shard ID'leri
# AutoShardedBot
bot = commands.Bot(intents=intents)```
@proud masonbro how can i changed
You need to give your bot a prefix
i dont used prefix, i am using slash commands
Prefix is still a required argument
The error tells you it's required
yes i understand
import discord
from discord.ext import commands
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name ="me", aliases=["balance","user"], help="hello komutu")
async def info(self, ctx):
if findUser(ctx.author.id):
# Embed mesajı oluşturma
embed = discord.Embed(
title=" :crown: Owner",
description=":small_red_triangle: {}'s Burger Joint (:hamburger::hamburger::hamburger:) \n *The best burgers are here!*".format(ctx.author.name),
color=discord.Color.dark_orange()
)
# Embed mesajına alanlar ekleme
embed.add_field(name="Balance", value=":dollar: ${}".format(0), inline=False)
embed.add_field(name="Income(per hour)", value=":money_with_wings: ${} | :hamburger: {}".format(0, 0), inline=False)
embed.add_field(name="Total Burger", value=":hamburger: {}".format(0), inline=False)
embed.add_field(name="Playing Time", value=":hourglass_flowing_sand: {}".format(0), inline=False)
embed.add_field(name="Level", value=":diamond_shape_with_a_dot_inside: Level {}".format(1), inline=False)
# Embed mesajına resim ekleme
user_avatar = ctx.author.avatar
embed.set_thumbnail(url=user_avatar)
# Mesajı gönderme
await ctx.respond(embed=embed)
def findUser(user_id):
import sqlite3
conn = sqlite3.connect('general.db')
cursor = conn.cursor()
# Kullanıcıyı kontrol etmek için SQL sorgusunu oluşturun ve çalıştırın
cursor.execute('SELECT * FROM users WHERE user_id = ?', (user_id,))
result = cursor.fetchone()
# Sonucu kontrol edin
if result:
cursor.close()
conn.close()
return True # Kullanıcı varsa True döndürün
else:
cursor.close()
conn.close()
return False # Kullanıcı yoksa False döndürün
async def setup(bot):
await bot.add_cog(Info(bot))
i cant used slash command
AttributeError: module 'discord' has no attribute 'slash_command'
Isn't it commands.slash_command?
And slash commands can't have aliases
Have you read the docs or the guide?
no how i read docs or guide?
The docs are linked in #faq
And here is the guide ^
I read but I still can't integrate the slash commands into my bot
import discord
from discord.ext import commands
from discord import app_commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name ="ping", description ="ping command")
async def ping(self, ctx):
await ctx.respond(f"Pong! Latency is {self.bot.latency}")
async def setup(bot):
await bot.add_cog(Ping(bot))
i run this command in my bot but i can't use the command
@prisma flicker
so i have a function
and i want to use it in both a slash command and a normal command
is there a way to check if the command excecuted is a normal command or a slash command?
Uh are you using dpy or smth?
Show pip list
?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)
Use discord.Bot if you only want slash cmds and not prefix cmds
@proud mason this my pip list
i using discord.py
i don't know how to sync slash commands in my bots
global or local
ah bruh
this is pycord server
you should ask for help in dpy server
pycord and dpy have completely different way to add slash commands
||or you could have just directed them to dpy server||
we don't discriminate based on libraries :)
.gg/dpy
maybe its time to move to pycord
.
just use bridge.Bot
I'm working on a embed tool using buttons and modals. What's the easiest way to edit the embed (which has the "Edit Title" button below) in the callback of the edit title modal (which gets send after pressing the "Edit Title" button)? Should I just pass the message to the modal?
do you pass Context to the function?
check if the context is instance of discord.ApplicationContext or discord.ext.commands.Context
in the modal, interaction.message.embeds[0] would have the embed object
edit that
awesome, thx
Is there a way with the autocomplete functionality that it "removes" the non-matching strings?
I think I understand what you mean here are 2 autocomplete functions that would do what you want.
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_autocomplete.py#L109
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_autocomplete.py#L172
Unless you mean removing strings from the actual user text.
So essentially you do your autocomplete, and when you got to choose your item you are given your list for example
and you can click from that list
however if I have 3 words, and I type the first 2 letters of 1 of those words, I don't want the other 2 words to appear because they don't match.
so the list should essentially "shink" based on the autocompletion
ty
how would I go about implementing a cooldown for on_message?
async def on_message(self, message: Message) -> None:
if message.author.id == self.user.id:
return
try:
await self.handler.handle_message(message)
except Exception:
if isinstance(error, ApplicationCommandInvokeError):
error = error.original
self.bot.logger.error(error, exc_info=True)
await message.channel.send(
f"""
:confused: An error occurred.
{error}
""",
ephemeral=True,
)
this works fine, but i can't think of a clean way :/
The same way you do with prefixed command.
and how do I do it with a prefixed command
.rtfm has_role
@has_role(someroleidorname)
oh ok thanks mate
discord.ext.commands.errors.MissingRole: Role 1115022176035283035 is required to run this command.
great it works but it gives error
can I like make it send a message saying u need the role to use the command or smthing?
instead of printing the whole error there
on_application_command_error listener
bet
You're not. I've seen real stupid people.
lol
https://sourceb.in/Pu31C1obxd getting this error could anyone show me why?
i dont know where the error's coming from, nothing in the stacktrace
solved
intents issue 
Is there a decorator for an error handler for an entire slash command group (for example, if I have a slash command group that only server admins can use, what would be the syntax for the error handler for that?)
@proud mason your paginator PR is still in progress right?
I think you can use @group.error
Where group is your slash command group name
.rtfm group.error
This didn't work for me, the error handler isn't being called, though maybe I'm going about it wrong?
Something like this is what I'm trying to do
it is complete. just not merged unfortunately 
Any idea why code like this
# more code unrelated to the embed
embed = discord.Embed(title=f"Newest image from {handle.website_name} for query id = {query_id}",
description=f"{text_notif}\n" if len(text_notif) > 0 else "")
embed.set_image(url=post.url_file)
await channel.send(embed=embed)
``` Having style of url like this
<https://website.net/art/the/path/image.png>
Throws an error like this?
```bash
Unhandled exception in internal background task 'check_for_feed'.
Traceback (most recent call last):
File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/ext/tasks/__in>" # journalctl cut of that part
await self.coro(*args, **kwargs)
File "/root/commission_02_2023/bot/cogs/dbserver.py", line 372, in check_for_feed
await channel.send(embed=embed)
File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/abc.py", line 1616, in send
data = await state.http.send_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.image.url: Not a well formed URL.
Like, am I supposed to process the url somehow? I can access the link via my browser just fine
What is post.url_file?
That is not a file image link @glossy forum
Type of post is a small dataclass I created for storing some of the fetched data from the website
.url_file is a str attribute containing a link to the file
which does contain the right value
edit: okay, it actually works as expected for one website, but doesn't for the other
so it's on me
how to get a wavelink server?
my slash and message commands aren't being correctly registered
they show up in the integration settings but they don't show up in / and right click on messages
there are no errors in the cog and there should be no issue with registering them
I've waited for over an hour for them to register correctly but it never happened
does anyone know why
Did u invite the bot with application.commands option?
I should add, they register correctly in debug guilds
debug guilds make commands "guild commads". they will only be registered in those guilds
remove debug guilds parameter completely and they will show up in all servers
I have it in the bot's constructor
Yep remove the parameter. That make all commands global
does anyone have experience with passing roles to guild.create_custom_emoji() ? I'm having trouble actually letting people use the emojis I make, right now they don't work unless you have the administrator perm?
Did you add the permissions for the other roles?
Do you mean enable external emojis for that role?
Im not really sure if its also counts to custome emojis
ye I don't think that's the problem
Hello. Which method is responsible for waiting for a message?
Do you mean wait_for("message")?
Yes, thank you
Hello, why does the nonce return as None?
await channel.send('testing', nonce=99)
last_message = await bot.get_channel(1111111111111111111).history(limit=1).flatten()
print(last_message[0].nonce)
print(last_message[0].content)
None
testing
Any pointers on implementing something like a timeout? Like, applying a role for a set amount of time, for example.
Messages from channel.history will not return the nonce set. It is only for verifying a message when sending one
channel.send return the message object, so there is no need to fetch it from channel.history
message = await channel.send(...) message.nonce
how do i check if a specific slash command was ran in an on message event
could you elaborate further?
Slash commands don't go through on_message
oh, well i have a check in the on message event that checks if the value in a json file is 1 or 2 depending on that stops from the commands being used
.rtfm message.interaction
ah any better way to do what im trying to do?
are you trying to stop commands from running based on a config file?
if yes, use global checks
.rtfm discord.bot.check
no, i have a json in which the maintenance mode is set to true or false, i want to be able to run just that one command if its in maintenance
so all other commands should fail?
this will be the way
you can make your own Exception that inherits from ApplicationCommandError, and raise that in the check saying smth like "Bot in maintenance"
you can even handle this exception class in your error handler
and send a message to the user
if bot isnt in maintenance, return True
i have the logic, yes, i want to disable it, it disables all commands though
oh do you only want to disable a single command?
then use the check on that commad
.rtfm check
discord.CheckFailure
discord.CheckFailure.args
discord.CheckFailure.with_traceback
discord.ext.commands.check
discord.ext.commands.check_any
discord.ext.commands.CheckFailure
discord.ext.commands.CheckFailure.args
discord.ext.commands.CheckFailure.with_traceback
discord.ext.commands.CheckAnyFailure
discord.ext.commands.CheckAnyFailure.args
discord.ext.commands.CheckAnyFailure.with_traceback
discord.AutoShardedBot.add_check
discord.AutoShardedBot.check
discord.AutoShardedBot.check_once
discord.AutoShardedBot.remove_check
discord.EmbeddedActivity.checkers_in_the_park
discord.EmbeddedActivity.checkers_in_the_park_dev
discord.EmbeddedActivity.checkers_in_the_park_staging
discord.EmbeddedActivity.checkers_in_the_park_qa
discord.ext.commands.Bot.add_check
4th
noo, i have a check in the on application command to see if the maintenance is enabled, if it is, i raise my error, however, i want to be able to disable it, i dont know how i can check if the command im running is the one to disable it
How to silently (without log in audit log) delete messages with bot? I saw nqn deleting users messages to replace them with webhook message
ctx.command ?
huh i dont think thats possible
Odd
But how nqn does that?
Even bots don't show who deleted the message
Like if I deleted it by myself
so i just check if thats the name does it work with groups
Is it possible to have a bot "playing a game" with rich/custom data like this?
nope
sadge
idk i didnt it was possible.. maybe ask in ddevs server or wait for someone else
audit log only shows up if someone else other than original author deleted the message
uh not sure. try it and see
otherwise you also have ctx.command.parent
bot-deleted messages aren't audit-logged?
Uhm... Nope?
yeah thought so
nqn server
I don't get it
.rtfm webhook.delete_m
try that, but i dont it'll work
Deletes a message owned by this webhook.
no, not at all
i dont think one can be 100% sure with anything discord api related

WTF
wait wtf really?
Although i was hoping this 
Hi, is it possible to create one event listener for every event?
So the listener would get called when any event occurs and it should be possible to get the name of the event in the callback.
I think you can replace bot.wait_for
I need to check that, GitHub mobile is so bad
Nah, need more stuff
Why do you need this by the way? I have an idea how to do it
I am storing some tasks I want to run on certain events in a database. And when any of the possible events get triggered I retrieve the according rows from the database and execute the tasks.
But the execution is handled by a custom class, so it's always the same code in the event listeners.
And I'm trying to avoid creating multiple listeners with always the same code.
I know all listeners are listed in bot._listeners
You can crate dynamic functions generator I guess
Like loop through the list and declare listeners with parameter inside
Or... Find low level func
Wait for other helpers tbh, I can't really check stuff from phone
Hm. Well I'll have a look. But can I create two listeners for the same event or can only one listener be created per event?
You can have multiple listeners, but only 1 event
In other words:
bot.event will replace original, but bot.listener won't
oh ok, good to know
👍
Another question: Does the bot have to share a guild with the user it's trying to fetch?
Wdym?
You can fetch anything with id, but get only if this is in bots cache
So fetch_guild always works
So fetch_user will always work?
Yup
ok thx
Guild has fetch_member?
yes
You can get info about server members only if your bot on this server and has members intents
Otherwise, you can't get info from the server
How do i make a command that has a button in it
Do i just add whatevers in the tag
?tag buttons2
You send a message with a view
i see thanks
What's the best way to set the color of an embed? I'm currently using a button (Edit Color) to open a modal. In here, I set the value to previous_color= str(interaction.message.embeds[0].color). When the modal is submitted, I'm currently trying to set color to the hex code received (e.g. #9b59b6). This currently doesn't work:
Ignoring exception in modal <cogs.messages.ColorModal object at 0x000001ED5020A710>:
Traceback (most recent call last):
File "C:\Users\bruno\Documents\Programming\AIM-Bot\venv\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
File "C:\Users\bruno\Documents\Programming\AIM-Bot\cogs\messages.py", line 574, in callback
user_embed.color = int(self.children[0].value)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: '#9b59b6'
The modal callback:
async def callback(self, interaction: discord.Interaction) -> None:
"""Callback for when the modal is submitted.
Parameters
------------
interaction: discord.Interaction
The interaction that submitted the modal."""
user_embed: discord.Embed = interaction.message.embeds[0]
user_embed.color = int(self.children[0].value)
if self.tutorial_embed:
await interaction.response.edit_message(embeds=[user_embed, self.tutorial_embed])
return
await interaction.response.edit_message(embed=user_embed)
Since this currently doesn't work, I was wondering if this even is a smart approach or if there is a better way?
Hm i dont see anything about having 2 buttons in a single line. Do i just duplicate
and i have to rename "MyView" to something else
Just add another decorator and function
i have no clue what that means i am a sped
class View(...):
@discord.ui.button(...)
async def button1(...):
...
@discord.ui.button(...)
async def button2(...):
...
Like that
ah\
I am using a mongo database which stores information from the server. To speed up the queries I have thought of creating a local variable as a cache where I store temporary information and it is restarted every X hours, if the server does not use it, it is deleted from the system.
Do you think this is a good idea?
if it's not out of sync and doesn't use too much memory, sure
is it a good idea to use different databases for stuff? say postgres for currency and all that more of interactive stuff like afk and all and idk mongo for moderation to store all the servers and their configs? or should i just use postgres for everything
try converting it to a string and convert it to rgb and plug it in discord.Colour.from_rgb()(https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Colour.from_rgb)
pymongo with motor?
as long as it works it is fine
I was referring to the cache
so is it better to have it in 2 or no.. ill be hosting both locally either way
but pymongo, it doesn't support asynchronous methods, does it?
Motor is pymongos async module
better to have one because of scaling? Like you would be hosting 1 instead of 2.
yes ik
When i restart the bot. The buttons stop working how fix
or it will just stop working after a short time
if you want buttons that always work:
Here's the persistent example.
ah
so they normally just stopp working after a short time
idk what I did wrong here
nvm got it
I figured it out. Is it possible to name thiis other than MyView
@bot.check
async def allChecks(ctx):
if await bot.isBlacklisted(ctx.author.id): raise blacklistError()
if bot.checkMaintenance():
if ctx.command.parent == "dev" and ctx.command.name == "maintenance": return True
raise maintenanceError()
return True
``` im trying to do a check to see if the command name matches, however, this seems to fail for me im unsure why, it works to enable, but i cannot stop it once its in maintenance
Nice Token
it gives me an error with the token, anyone knows what caused it?
yeah i know, forgot to hide it, I'm trying to make it work since 4 hours ago
I already resetted it bth
Thats not how envs work
^
zervyrel ur smart u always help
lul
that's what my friend told me to do
It was not working before too
1, dont use replit
2, replit has its own env in settings, so creating ur own env file is still visible to others
That's my first bot, I want to try pycord
The env is basically a dictionary. You should have something like this in your env file
TOKEN = mytoken123
Then os.environ["TOKEN"] (getenv might work to but i know my way works for sure.)
jan is right to there should be a tab on the side that lets you set envs and even insert the get statment automatically
while ur here do u know why the command isnt being checked for the name and the parent?
it tells me that environ is not callable
https://docs.replit.com/programming-ide/workspace-features/secrets
Read this. Then it also shows how to access it. (Your original way was correct buy my way is just a bit different.)
k thanks
ctx.command.parent will return a Group object or None not a string
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.ApplicationCommand.qualified_name might be the best thing to look for to
ctx.command.qualified_name == "dev maintenance"
ah yes exactly what i was looking for thank you
or not this still doesnt turn it off
@bot.check
async def allChecks(ctx):
if await bot.isBlacklisted(ctx.author.id): raise blacklistError()
if bot.checkMaintenance():
if ctx.command.qualified_name == "dev maintenance": return True
raise maintenanceError()
return True```
```py
def checkMaintenance(self):
r = self.getValue("maintenance")
return True if r == "1" else False``` currently `r` is set to 1
Can you print ctx.command.qualified_name, just to be sure it is returning the right thing
thats weird
I might wound mentwlly special but is it possible to make the bot play a .mp3 when in a vc
Play it thru the mic or smt
This should help you get started: https://guide.pycord.dev/voice/playing

Are you using slash or prefix commands?
slash
parent None
print(f'parent name {ctx.command.parent.name}')
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'name'
@bot.check
async def allChecks(ctx):
if await bot.isBlacklisted(ctx.author.id): raise blacklistError()
if bot.checkMaintenance():
print(f'parent {ctx.command.parent}')
print(f'parent name {ctx.command.parent.name}')
print(f'command name { ctx.command.name}')
if ctx.command.qualified_name == "dev maintenance": return True
raise maintenanceError()
return True
``` command name wont get printed
My test seems to work. Can you show how you are creating the group?
from discord.commands import SlashCommandGroup
dev_commands = SlashCommandGroup("dev", "developer commands")```
def __init__(self, bot):
self.bot = bot
greetings = discord.SlashCommandGroup("greetings", "Various greeting from cogs!")
@greetings.command()
async def ping(self, ctx):
print(ctx.command.qualified_name)
This gives me greetings ping
# Sets maintenance mode
@dev_commands.command(description="Toggles maintenance mode")
@commands.guild_only()
@isDeveloper()
async def maintenance(self, ctx, action: bool):
await self.bot.maintenance(action)
embed = discord.Embed(title="Maintenance mode stopped!", color=discord.Colour.embed_background())
if action: embed.title = "Maintenance mode started!"
if action: await self.bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Activity(type=discord.ActivityType.playing, name="in maintenance mode"))
else: await self.bot.change_presence(activity=discord.Activity(name="for /help", type=discord.ActivityType.watching, status=discord.Status.online))
await ctx.respond(embed=embed, ephemeral=True)``` this is my command
im also running the developer version of pycord unsure if that matters
File "C:\Users\ethan\PycharmProjects\pythonProject\musictest.py", line 7, in on_ready
await connect_nodes() # connect to the server
File "C:\Users\ethan\PycharmProjects\pythonProject\musictest.py", line 16, in connect_nodes
await wavelink.NodePool.create_node(
AttributeError: type object 'NodePool' has no attribute 'create_node'
I copied exactly the guide
yes, but are you doing it in the @bot.check? thats where i am checking the name of it
Im sorry, I am not knowledgeable with voice. I would create a thread so that someone who is can answer it.
I would think the check would pass the same ctx but I can test
would be lovely
I did a little digging. The docs is outdated
I guess you are right. I have the same issue
well thats that then
ill keep it as if ctx.command.qualified_name == "dev maintenance": return True for now tho thanks for the help
What is strange is that the ctx object is the same
thats weird then, i haven't got a clue what shenanigans are going on in the back
printing just ctx.command also only returns the group name in my case dev
could you update to the latest dev version?
Ok, I found something. Both commands are run through the check. So the first time it runs the group command through the check. And then it runs the sub command
Nah, they are good now. I found the issue
i remember fixing that tho
oh
yeah i can update just a second
hmmm wait
that is only the hooks
another PR for om
@fervent cradle @grizzled sentinel does the check run 2 times?
yes
once for the group and once for the command
although jans only runs once because the check fails on the group
ah so you could do if isinstance(ctx.command, discord.SlashCommandGroup): return or smth
ic
just me always having issues with slash groups? lmao
i really dont get how running hooks and checks for slashgroups is not a feature
you can weed out the groups using this if you want the old way back
even discord considers the group as the "command" and subcommands as "options"
if isinstance(ctx.command, discord.SlashCommandGroup) and ctx.command.name == "dev":
return True
if ctx.command.qualified_name == "dev maintenance":
return True
Would this work? So that only one group is returned true automatically
tbh the 2nd one wont be required
the 1st one should be enough
or wait
are you trying to block the command or allow it?
return True allows it
allow only that command
ah
yes so thats right
yeah, thanks a lot guys
um is there also a way to make __init__ async?
class SearchView(discord.ui.View):
def __init__(self, bot, timeout: Optional[float] = 90):
super().__init__(timeout=timeout)
search_place = await self.bot.getSearchPlaces(3)
self.add_item(discord.ui.Button(label=search_place, style=discord.ButtonStyle.blurple))``` im trying to do this
__init__ cannot be async.
You could put the async call into a load coro and await that after the object creation...
e.g.
class SearchView(discord.ui.View):
def __init__(self, bot, timeout: Optional[float] = 90):
super().__init__(timeout=timeout)
async def load(self):
search_place = await self.bot.getSearchPlaces(3)
self.add_item(discord.ui.Button(label=search_place, style=discord.ButtonStyle.blurple))
view = await SearchView(bot, 100).load()
# or
view2 = SearchView(bot, 200)
await view2.load()
@fervent cradle
Error in the host now:
Traceback (most recent call last):
File "/home/container/main.py", line 43, in <module>
bot.run(os.getenv("TOKEN"))
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 717, in run
return future.result()
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 696, in runner
await self.start(*args, **kwargs)
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 659, in start
await self.login(token)
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 509, in login
raise TypeError(
TypeError: token must be of type str, not NoneType
Looks like the environment variable "TOKEN" does not exist
use dotenv.load_dotenv() to load the variables into the environment.
pip install python-dotenv
If you named your .env file anything other than .env you have to use dotenv.load_dotenv("path/to/.env")
@queen willow hello?
uhh no
dotenv is an external library
use pip install python-dotenv to install it
is it possible to hide commands from that list when you type / from certain roles?
I already installed that
then just dotenv.load_dotenv(path)
without the os.
yes, but only server moderators can do that
ah no, sorry. Wrong. @queen willow
sorry, i missworded it, is it possible to hide certain commands from certain roles? so say the ban command cant be shown to normal people but to mods and stuff it can this is how im doing it rn
@bot.slash_command(name="dm", description="Send a DM to a user")
async def dm(ctx: discord.ApplicationContext, user: discord.User, *, message: str):
# Check if the user has an allowed role
if not any(role.id in allowed_roles for role in ctx.author.roles):
await ctx.respond("You don't have permission to use this command.")
print(f"User {ctx.author.name} tried to use the DM command but was denied.")
return
# Defer the response
await ctx.defer()
try:
# Send a DM to the user
await user.send(f"`{message}`\n\nThis message was sent by {ctx.author.mention}.\nIf you wish to respond to this message, please do so in the server. I cannot recieve messages.")
# Let the command invoker know that the DM was sent
await ctx.respond(f"Message sent to {user.name}.")
print(f"Message sent to {user.name} and reads as follows: '{message}'. This command was used by {ctx.author.name}")
except discord.Forbidden:
# The user has DMs disabled or has blocked the bot
await ctx.respond(f"Couldn't send a message to {user.name}.")
print(f"Message could not be sent to {user.name} and reads as follows: '{message}'. This command was used by {ctx.author.name}")
dotenv.load_dotenv(path)
bot.run(os.getenv("TOKEN"))
@queen willow that should work
yes, but only server moderators can choose which role(s) to hide/show the command from
dotenv.load_dotenv() takes the .env file and loads all variables, that are defined in the file, into the environment so that you can access them using os.getenv()
so this wouldnt be done through code?
so theres not a better way to do this huh, but if i made the function not async then it would be blocking
nope, but you can set a default permission for a command
should be
good
Am not
-to @full basin 1m ok
⏱ Timed out dark.py for 1 minute
Calling async functions from sync functions during a running event loop is never simple or "good"
What does your getSearchPlaces function do?
basically returns just random choices specified by the input, but i got told even these functions should be async
||harder-|| what
SORRY
LOL
Sure thing will do when I'm back in Germany
https://docs.pycord.dev/en/master/api/application_commands.html#discord.commands.default_permissions
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...
Hehehe
sounds like it doesn't need to be async...
If there's no waiting for a server response or something similar involved, it doesn't have to be an async function...
@solemn idol @waxen whale @full basin leave thanks
What's the code of the function? @fervent cradle
well then its syncronous...
excuse me? 
ah so I would use actual permissions instead of roles, got it 👍
If there's no await involved in your custom function, it's syncronous xD
Even if the function call itself may be not blocking, the execution of random.choice is still blocking
"dotenv" is not defined
I imported load.dotenv
right so i can remove async from all my functions that arent using anything to communicate with api or whatever
import dotenv ...
or should i still keep it for good practice lmao
good practice is to not do anything that you shouldn't need to do.
pretty much jeah... Basically any function where no await statement is used
is there a way for the bot to notice reactions to messages without it being an embed or the bot being the message author?
listen to on_reaction_add or on_raw_reaction_add and filter out the messages you want or don't want
Thank you soo much! I'll read up on those two methods 🙂
thanks so much for the advice, thankfully i didnt have so many functions yet, ill test out the entirity of the bot later to see if i've missed some removing awaits but if it doesnt whine i think its fine
np
ah while you're here why not idk why this keeps failing and users can sell stuff they dont own
async def sell(self, ctx, item: str, amount: str):
if amount not in ["all", "max", "maximum"]:
amount = int(dehumanizer.dehumanizer.parse_string(amount))
else:
amount = await self.bot.hasItem(ctx.author.id, item, amount)
if amount <= 0:
await ctx.respond(embed=discord.Embed(description="You need to sell at least one item", colour=discord.Colour.embed_background()), ephemeral=True)
return
if amount == 0:
await ctx.respond(embed=discord.Embed(description="You haven't got enough of this item in your inventory to sell!", colour=discord.Colour.embed_background()), ephemeral=True)
return
info = await self.bot.getItem(item)
await self.bot.removeItem(ctx.author.id, info['id'], amount)
await self.bot.addBalance(ctx.author.id, int(info['price']*self.config.sell_value))
embed = discord.Embed(colour=discord.Colour.embed_background(), title="Item(s) sold!", description=f"You successfully sold {amount}x {info['emoji']} {item} for **{self.config.currencyEmoji} {humanize.intcomma(int(info['price']*self.config.sell_value))}**")
await ctx.respond(embed=embed)```
```py
async def hasItem(self, uid, item, amount):
val = await self.fetchval("SELECT quantity FROM inventory INNER JOIN items ON inventory.itemID = items.itemSerial WHERE userID=$1 AND items.itemID=$2;", int(uid), item)
if not val or val < int(amount):
return 0
else:
return val
it gives an error with the token again, should I declare it as token="TOKEN" or token=TOKEN?
in the .env file
TOKEN=<your token here> (without the <>)
exactly what I did lol
ok, pls send your current code again
maybe open a thread for this.
but it seems like you don't check the result of removeItem and just give the money to the player
yeah
that's what I just wanted to ask too xD
what's the full name of your .env file @queen willow
it should be .env
if it is, you don't need the {}
just
.env
TOKEN=your token here
ah right lmao
You should really start using Google to.solve simple matters
Traceback (most recent call last):
File "/home/container/main.py", line 45, in <module>
bot.run(os.getenv("TOKEN"))
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 717, in run
return future.result()
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 696, in runner
await self.start(*args, **kwargs)
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 659, in start
await self.login(token)
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 509, in login
raise TypeError(
TypeError: token must be of type str, not NoneType
same error
Thx, I’ll give it a try
Did you load the env file?..
he did, but maybe wrong path
Helping with no code isn't useful
yes dotenv.load_dotenv("home/container/example.env")
@queen willow try dotent.load_dotenv() without path
if the .env is in the same directory as your bot.py
yes it is
Then don't add a path
then the path isn't needed
Let the lib do it by itself
But the value embed.color returns is a hex code right?
is it alright if i dm you with a question or two about the information i found?
sure
Afaik, yes
Hmm, makes it harder to deal with
@queen willow and btw, if I were you, I'd regenerate the bot token. One could be able to decipher it from the image...
k I will
same error
no, it's an int
I use embed.color as a value for the modal, so users see the previous color code. It would be better to allow them the enter hex codes as well. How would I do that?
For me it returned something like #fb6628 or whatever
Seems like a hex code to me
oh really?
discord.Embed().color should return an int afaik...
But I wasn’t sure if it’s hex or rgb so I figured I might just ask
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
You can also get the rbg
ah actually it returns a Colour object. And if you do str(Colour()), you get a hex string
Oh thank ya
I did that but It gave the same error, if you need the code, it's here : https://sourceb.in/rLZoxlzpJX
you should be able to use it like an int though
So Color.value is rgb?
It said raw int in the docs
Colour().to_rgb()
Ok thx
what is your .env file called?
And hash would be hex code right?
hash is something completeley different xD
Oh oke haha
str(Colour()) is hex
Color codes are confusing af
and int(Colour()) is int
I find hex is the most user friendly
but rgb is ok too
u can do discord.Colour.red() or green() or whatever too thats the easiest
Lacks customizablility tho
if u really want to u can just do .random() always a random colour
example.env
ok, call it just .env and it should work.
if you want to call it example.env you have to load it using dotenv.load_dotenv("example.env")
And please use google more often 🙂
ah that, I forgot, you already told me to do so
It worked, thank you very very much ❤️
you too The Silly Squid
you're welcome. And remember: Use google more often xD
one more question since they're blocking it blocks other users from using commands tho no?
Well, for the millisecond it takes to compute the function, yes, but not really though. The bot will get the request but may delay it because of the function. At least that's my understanding of it. But making the function asyncronous by simply putting an async before it, wouldn't change anything about it.
ah so theres nothing i can do about it
nothing you can do could improve it significantly imho xD
But even if you could, it wouldn't make any noticeable difference
ah okay
def match_search_places(place, coins = 0, item = "Nothing"):
match place:
case '...':
if random.random() < 0.5:
if random.random() > 0.5:
return f"..."
else:
return f"..."
else:
return f"..."
case '...':
if random.random() < 0.5:
if random.random() > 0.5:``` is there a more efficient way of doing this deciding if u get an item or a coin, or just dont get anything
Well there is an esoteric way
.tag asyncinit
Add this to you class to allow async init-
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
Just copy paste that into your class
Then make your init function async
And do await MyClass(...)
That's all
oh wow.
If only I had known this earlier xD
why?
You should use buttons instead for reaction roles
they are complex
easier to use reactions
They're really not that complicated, and they solve a lot of problems you'll run into with reactions
How do I remove the author of an embed? Tried the following:
user_embed.set_author(name=None, icon_url=None)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.author.icon_url: Not a well formed URL.
You should use discord onboarding instead of reaction roles
is discord onboarding GA now?
should be
lemme see
If I intereprett https://rollouts.advaith.io/ correctly it is
Lists Discord's server experiments and their current rollouts, treatments, and overrides.
nice
why did you cross this out though
Cause it wasn't the answer they were looking for
Is it even possible set the author to None after it was set?
is there a different method to remove the author?
nope
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
where in hell did that come from
docs
I swear I read through all a the methods
ig not
Sorry for bothering you, no idea how I didn't see this
how do i create the different type of text in an embed
with ` and *
test test
test
the boxes are fields
so in the field it would be like name = "*text: *"
just add the *, `
Example:
`hi` is hi
*hi* is hi
**hi** is hi
__hi__ is hi
👍
*test*
I have a custom bot class with some additional attributes assigned to it, However all the classes from the discord library that reference the bot (E.g. AutocompleteContext.bot) type hint the bot reference as discord.Bot rather than my custom class which means that type-checkers like mypy or Pycharm warn that the additional custom attributes do not exist on the discord.Bot class. How do I fix this without using # type: ignore?
hmm ig there could be a fix by making these classes inherit from typing.Generic
🤔
my bot class or pycord's?
pycords
oof, that sounds like a "deal with it until it gets fixed" kinda thing
as of now, you could make subclasses for each of such classes and type hint bot as your bot class? bad solution ofc
and then use these subclasses for typehinting everywhere
would I just need to override the typehints in the __init__() method's arguments and the assignment to instance variables?
you might not even need that
just simply
class SomeClass(...):
bot: MyBotClass
not tested ofc
I don't understand how to initialize a cog with bridge commands. I get
Extension 'cogs.badwords' raised an error: TypeError: issubclass() arg 1 must be a class
full error please?
Concept
That's it unless you want a full stack trace.
Yes, I've seen that. I have similar code, the only difference is that it's more complex and uses bridge_group :P
code would be helpful
yes you can use bridge groups too. smth like this
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bridge.bridge_group()
@bridge.map_to("hi") # not sure if this is required
async def hello(self, ctx):
await ctx.respond("Hello!")
@hello.command()
async def bye(self, ctx):
await ctx.respond("Bye!")
yeah traceback would be good
Yeah, I know. That's why I'm confused why it doesn't work.
The decorators take the same args as far as I understand? name help alieses etc?
yes. the args are just passed into the decorators for slash and prefix cmds
from discord.ext import bridge
from discord.ext.bridge import BridgeContext as Context, Bot
class Badwords(Cog):
def __init__(self, bot: Bot) -> None:
super().__init__()
self.bot: Bot = bot
@bridge.bridge_group(name="badword")
async def badword(self, ctx: Context):
if ctx.invoked_subcommand is None:
return
@badword.command(name="add")
@can_have_fun()
async def add(
self, ctx: Context, user: Member, lives: Optional[int] = 3, *, words: List[str]
):
...
def setup(bot: Bot):
bot.add_cog(Badwords(bot))
hmm and error traceback?
bot_1 | Traceback (most recent call last):
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 786, in _load_from_module_spec
bot_1 | setup(self)
bot_1 | File "/code/cogs/badwords.py", line 184, in setup
bot_1 | bot.add_cog(Badwords(bot))
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 656, in add_cog
bot_1 | cog = cog._inject(self)
bot_1 | ^^^^^^^^^^^^^^^^^
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 548, in _inject
bot_1 | command._set_cog(self)
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 1378, in _set_cog
bot_1 | subcommand._set_cog(cog)
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 603, in _set_cog
bot_1 | self.cog = cog
bot_1 | ^^^^^^^^
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 830, in cog
bot_1 | self._validate_parameters()
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 708, in _validate_parameters
bot_1 | self.options: list[Option] = self._parse_options(params)
bot_1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 748, in _parse_options
bot_1 | option = Option(option)
bot_1 | ^^^^^^^^^^^^^^
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/commands/options.py", line 230, in __init__
bot_1 | raise exc
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/commands/options.py", line 225, in __init__
bot_1 | self.input_type = SlashCommandOptionType.from_datatype(input_type)
bot_1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/enums.py", line 807, in from_datatype
bot_1 | if issubclass(datatype, str):
bot_1 | ^^^^^^^^^^^^^^^^^^^^^^^^^
bot_1 | TypeError: issubclass() arg 1 must be a class
bot_1 |
bot_1 | The above exception was the direct cause of the following exception:
bot_1 |
bot_1 | Traceback (most recent call last):
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 178, in wrapped
bot_1 | ret = await coro(*args, **kwargs)
bot_1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
bot_1 | File "/code/cogs/service.py", line 46, in load
bot_1 | self.bot.load_extension(module_name)
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 910, in load_extension
bot_1 | self._load_from_module_spec(spec, name)
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 791, in _load_from_module_spec
bot_1 | raise errors.ExtensionFailed(key, e) from e
bot_1 | discord.errors.ExtensionFailed: Extension 'cogs.badwords' raised an error: TypeError: issubclass() arg 1 must be a class
bot_1 |
bot_1 | The above exception was the direct cause of the following exception:
bot_1 |
bot_1 | Traceback (most recent call last):
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
bot_1 | await ctx.command.invoke(ctx)
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 1545, in invoke
bot_1 | await ctx.invoked_subcommand.invoke(ctx)
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 950, in invoke
bot_1 | await injected(*ctx.args, **ctx.kwargs)
bot_1 | File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 187, in wrapped
bot_1 | raise CommandInvokeError(exc) from exc
bot_1 | discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.badwords' raised an error: TypeError: issubclass() arg 1 must be a class
hmm
self, ctx: Context, user: Member, lives: Optional[int] = 3, *, words: List[str]
``` probably this line
yeah i dont think you can use Optional or List
you will need to use discord.Option
also, avoid this
you need it for text-based commands
Both worked on text-based commands and are used in converters in examples in docs
¯_(ツ)_/¯
slash commands are like duct-taped
Okay, List is a no-no then. Thank you for assistance!
||many parts of this library are||
sometimes i do like dpy's approach of using typing instead of discord.Option
but then it proceededs to use docstrings n stuff to get the description etc... 
Yee, a lot of it feels junky, but then again, it is supposed to work with Discord 
Oh, one more question: do I need to sync slash commands somehow? I can't find anything like that in the docs but I remember there was something like that in discord.py 
Pycord does it automaticaly unless you are doing things out of the ordinary. Then it is bot.sync_commands()
How long does it for them to register more-less?
guild commands <30 secs Global commands <5 min but normally less then 1 min.
how can i use pycord in replit
thou shalt not use replit
what?
?tag replit
thanks
But basically this too. Replit should only be used as a last resort.
i'm using it to host bots
The first section in the link explains why this is a bad idea. But if its your only options I guess it will have to work
is there another choice
.tag hosting
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com US https://www.vultr.com US
https://www.ovh.co.uk EU/Canada https://www.hetzner.com Germany/US
https://www.time4vps.eu Lithuania.
Self-hosting: Kinda free:
Any computer. GCP, AWS have one year free micros.
Good hosting sites (mostly free):
https://railway.app
https://oracle.com
https://render.com
They're not getting synced 
.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)?
Note: you should be able to answer "yes" to all of these queries.
It should be all the same stuff minus a few
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
should be no
I'm guessing there's different method to loading/unloading cogs with bridge commands? Using bot.load_extension or bot.unload_extension I get Command raised an exception: AttributeError: 'BridgeCommandGroup' object has no attribute 'name' 
Hey
I'm surprised to have this error, do you have any ideas?
discord.Bot(intents=intents, command_prefix=os.environ.get('PREFIX'), case_insensitive=True)
^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'
Has anything changed?
Do you have anything else than py-cord installed? also discord.Bot doesn't have a prefix
why is my slash command not showing up when i put /? it doesnt have errors and should clearly work
No, it works on a docker, which is all the more strange.
refresh discord with ctrl + r
i did and it still doesnt show up
you installed 100% something else that is not working with py-cord.
i just deleted all my pip installs and installed py-cord again
it still isnt working idk why
do you use discord.Bot or commands.Bot?
non
wavelink install discord.py???
yes
i opened a thread
you shouldnt have discord.py installed
only py-cord
But how did the Russian who coded this thing get pycord to work with wavelink???
1 + 1 = 4 
Its code works, it should have been put on python 3.10. I don't understand, he broke the matrix
async def play(ctx, search: str):
vc = ctx.voice_client # define our voice client
if not vc: # check if the bot is not in a voice channel
vc = await ctx.author.voice.channel.connect(cls=wavelink.Player) # connect to the voice channel
if ctx.author.voice.channel.id != vc.channel.id: # check if the bot is not in the voice channel
return await ctx.respond("You must be in the same voice channel as the bot.") # return an error message
song = await wavelink.YouTubeTrack.search(query=search, return_first=True) # search for the song
if not song: # check if the song is not found
return await ctx.respond("No song found.") # return an error message
await vc.play(song) # play the song
await ctx.respond(f"Now playing: `{vc.source.title}`") # return a message```
how fix when it just plays the song without being in a vc lol. I had to make a command just to make it join
youtube is against the Tos and can get your bot banned
dont care
lol
How did you install wavelink?
by installing it?
bro where did you get that code from
"pip install wavelink"
isnt that how you normally install things in python
The one in docs only works with verison 1.3.3 of wavelink and lower btw
Yes
And that installs discord.py as a dependency
That's what zerv is saying
Use master branch
?tag install
- 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


