#Basic Pycord Help (Quick Questions Only)
1 messages Β· Page 91 of 1
Yo. Is there any way to send a message to a channel without using await?
damn
Not a good way. You are likely doing something wrong. Can you show your code
start a task with asyncio
he probably wants to send a message in an __init__ xD
from javascript import require, On
bedrock = require('bedrock-protocol')
import discord
from discord.ext import tasks
def start(ip, port, bot, relaychannel):
from javascript import require, On
bedrock = require('bedrock-protocol')
client = bedrock.createClient({
'host': ip,
'port': int(port),
'profilesFolder': "./authCache",
'skipPing': True,
'skinData': {
'CurrentInputMode': 3,
'DefaultInputMode': 3,
'DeviceModel': 'Xbox Series X',
'DeviceOS': 11
}
})
print("joining...")
@On(client, 'join')
def handle(event):
print(f"joined the game baby!")
@On(client, 'text')
def handle(name, packet):
print(packet)
print("Received text:", packet['message'])
channel = bot.get_channel(1129506516215537684)
#Cant Await to send to the channel
wtf
yep
why you need 2 import?
mc client?
minecraft
yes
isn't there an async version of the lib?
i dont think so
you dont think you or you didnt google it?
Try to make handle function async?
I just get this error
C:\Users\George\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\javascript\pyi.py:201: RuntimeWarning: coroutine 'start.<locals>.handle' was never awaited
del self.m[i]
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
oof
I think you may be able to do bot.loop.create_task(bot.send()), but this way you cannot get the result...
wdym by the result?
you can't get the return value of .send
The function executes but the return value is lost
ah
Isn't asyncio.run also works?
Target not found, try again and make sure to check your spelling.
.rtfm bot.event_loop
Target not found, try again and make sure to check your spelling.
.
that
pool
poll
pull
reset HEAD
oh yeah xD
Am currently working with db pools...
@echo needle bot.loop, not bot.pool, what I wrote earlier
okay
so bot.loop.create_task(bot.send())
ill try it
omg thankd
thanks
it works, ive spent like 2 hrs tryna figure this out
luv u
np π
how do i end a user interaction
Provide more context
return ctx*2
I'm having a bit of a skill gap. I'm writing to a CSV file in memory; how do I pass that to discord.File so I can add it in a response? (I'm assuming I need to use discord.File?)
... stuff
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(blah)
await ctx.respond(content="Your data...", file=discord.File(output.getvalue()))
But Discord is whining that the embed size is larger than 6000. I assumed this would be added as an attachment; should I be doing something else to force it?
Ah, apparently I had to send the output back into an io.BytesIO() instance
which one to edit the command message? (ctx.send) message?
discord.InteractionMessage.edit
discord.Interaction.edit_original_message
discord.InteractionResponse.edit_message
youtube_dl sometimes returns a manifest link instead of the actual url i got past this by checking if several formats retured the proper link, first one that did was used, is there a better way to do this
slash cmds right? ctx.send or ctx.respond ?
I'm kinda confused about how to add a link button component since it doesn't have a callback
.rtfm view.add_item
using that
π
it's select menu, ctx.send(view=myView()), i want to edit that message
after selecting
Use interaction.response.edit_message
ty
Sorry for the double pong
hi
I want to set up a pagination with the / command but I don't understand anything for how many hours
did you read the guide?
Here's an example of pagination with embeds for a slash command:
my_pages = [
Page(
embeds=[
discord.Embed(title="Page 1", description="This is page 1"),
],
),
Page(
embeds=[
discord.Embed(title="Page 2", description="This is Page 2")
],
),
Page(
embeds=[
discord.Embed(
title="Page 3",
description="This is page 3",
)
],
),
]
@client.command()
async def test(ctx):
paginator = Paginator(pages=my_pages)
await paginator.respond(ctx.interaction)```
Basically, you pass all pages you want in the my_pages list, then you just pass the list to the paginator in the command and respond with it. The paginator does the rest.
Yeah. Just modify the slash command to work with the cog, and modify the paginator to be paginator = Paginator(pages=self.my_pages)
im looking for a value in one list, then once i have this value, i will use its index position to find a value in another list, however the code i have now gives me an index number that doesnt work and idk why
if "orange" in values:
position = order_details.index("orange")
print(position)
multiplier = amount[position]
print(multiplier)
price = multiplier * 6.95
total_price.append(price)
print(price)```
Wouldn't a dict work better? Lol
yea but i wanna see if this way works
this is my code
con,cur = openCON()
cur.execute(f"SELECT * FROM order_details WHERE userID = '{interaction.user.id}'")
i = cur.fetchall()[0]
order_details = i['order_contents']
values = str(order_details.split(","))
print(values)
amount = extract_numbers_with_order(values)
if "ss" in values:
position = values.index("ss")
print(position)
multiplier = amount[position]
print(multiplier)
price = multiplier * 6.95
total_price.append(price)```
i found out that its not giving me the position
its giving me the total number of characters before "ss"
how do I get the usrname of author π i forgot how to code

cant figure out π i am touching my computer after 3 months
pls send help
.rtfm member.namd
Target not found, try again and make sure to check your spelling.
Lul
π whyd they change from ctx.username π
I don't think that was ever a thing
await ctx.message.clear_reactions() is this so correct?
for prefix cmds, yes
I'm making a slash command
I would like to add reaction there and then remove them all again.
ah
ctx.message doesnt exist for slash cmds
you will need to fetch the message after responding
like message = await ctx.interaction.original_response()
at this too?
message = ctx.respond("click")
await message.add_reaction("β
")
yes
await respond btw
what is the correct name for this?
# Remove all reactions from the message
await ctx.respond.clear_reactions()
# Edit the message with the time reached
await ctx.respond.edit(content=f "You won the game in {time_taken_seconds} seconds!")
assuming the last one is for example
@bot.slash_command()
def abc(ctx: discord.ApplicationContext) -> None:
original = await ctx.respond("Hello world!")
sleep(2)
await original.edit("...")
That is not gonna work ;3
Was worth trying
you can use ctx.edit
Why is this not accessible?
fsr if I comment out this line it does work again, why?
what error does it give
it's probably because of global and local variables, try adding global end_time just under your async def
I would but that just can't do since multiple functions have the end_time as a local variable.
I'm just curious why that local variable isn't in scope?
It should be right?
you could create another variable just make it equal to end_time then do your work with the new variable
it's because it's outside your function, any variables created inside a function will be only accessible within that function by default, even if you already have a variable of the same name
python probably sees the last line and thinks end_time is now a local variable
Oh god in like every other language it works way different
I'm really used to C# and C++
funny blue and yellow snake 
You could use classes and have instance variables instead
I could but I'm too lazy to do that 
I've already resolved the issue btw, I just removed the line. 200 iq play
You could just rename one of the variables
await ctx.respond("hfuioeshus", ephemeral=True") why is it not being ephemeral.
Are you deferring
yes
ok ty
Heya, i have question 
creation of a cmd using the UID verify event and entering the role for 3 and more servers for one game
how do i end the user interaction if user calls the slash command during the interaction
Timeout 
Buttom break interaction
(if not for yourself, then you can also break it by using global commands for interacting with interaction)
No emotes match your search
why guild.owner returns None everytime?
Where do you get the guild object from?
sorry, what's the question?
owner should only return a value if members intent is enabled
oh yes, i am dumb nvm
and how do I fix tht #0 thing after usernames? is it possible?
just remove it
@bot.event
async def on_command_usage(ctx: bridge.BridgeContext):
"""Simple command usage event."""
user = ctx.author
command = ctx.command
await bot.get_channel(1129841517457051648).send(f"**{user}** (`{user.id}`) used **{command}** in **{ctx.guild.name}** (`{ctx.guild.id}`)")
error:
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 40060): Interaction has already been acknowledged.
Full Traceback: https://paste.zorino.in/capizomurabokaza.sql
but I am not responding to the application cmd, I just want to send a message to a specific channel
are you sure the code part is where the error occurs?
File "c:\Users\Administrator\Documents\GitHub\Krishna\main.py", line 338, in help
await ctx.respond(embed=embed1)
That's where the error occurs
my bad. actually, the bot was hosted twice at the same time lol
but still, the event above doesn't work.. it neither gives any error nor sends the msg in required channel
.rtfm on_command_usage
Target not found, try again and make sure to check your spelling.
on_command_usage doesn't seem like a valid event
uhmm, so wht can i use instead?
.rtfm on_command
discord.on_application_command
discord.ext.commands.Bot.add_application_command
discord.ext.commands.Bot.application_command
discord.ext.commands.Bot.application_commands
discord.ext.commands.Bot.get_application_command
discord.ext.commands.Bot.invoke_application_command
discord.ext.commands.Bot.on_application_command_auto_complete
discord.ext.commands.Bot.on_application_command_error
discord.ext.commands.Bot.on_command_error
discord.ext.commands.Bot.pending_application_commands
discord.ext.commands.Bot.process_application_commands
discord.ext.commands.Bot.remove_application_command
discord.ext.commands.Bot.walk_application_commands
discord.commands.application_command
discord.on_application_command_error
discord.on_unknown_application_command
discord.on_application_command_completion
discord.ext.commands.AutoShardedBot.add_application_command
discord.ext.commands.AutoShardedBot.application_command
discord.ext.commands.AutoShardedBot.application_commands
you may be looking for just on_command
ohk
The following section outlines the API of Pycordβs prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
but apparently doesn't work with slash commands...
if you want application commands (too) use on_application_command
This section outlines the different types of events listened by Client. There are two ways to register an event, the first way is through the use of Client.event(). The second way is through subcla...
If you are using bridge commands, there is an event on_bridge_command too
@trim cipher ^
It will be fired for both, prefix and slash version
oh ty
I doubt that the code will catch everything newly added from the database, especially if this database is of a global type, but it seems that I have already found a solution, it's always worth complaining before I understand how to do it 
it is not getting triggered tho..
@bot.event
async def on_bridge_command(ctx: bridge.BridgeContext):
"""Simple command usage event."""
user = ctx.author
command = ctx.command
await bot.get_channel(1129841552697597972).send(f"**{user}** (`{user.id}`) used **{command}** in **`{ctx.guild.name}`** (`{ctx.guild.id}`)")
Oh right it is on master branch only
Forgot that π
lol, so I have to go with on_application_command atm
You would need both, on_command for the prefix version, and on_application_command for the Slash version
Also do you have any other non-bridge commands? Those will trigger that too
nah, every cmd is a bridge cmd..
I will go with adding both events until bridge cmd comes out on pypi
π
Is it possible for an api-using pycord function (like fetch or send) to raise an error because of connection issues? Do I have to account for that using try: excepts?
And when do HTTPExceptions actually happen? Retrieving the channel failed., how can it fail other than not found and missing permissions, which are 2 other exceptions?
how do i disable a dropdown menu after it has been interacted with?
select.disabled = True
#and
await interaction.edit_response(view=view) # the view object where the select is part of
Exact way depends on the way you define the view
any idea how I can mention such commands? in normal messages and in embeds??
i did this
select.disabled = True
await interaction_2nd.edit_response(view=Select())```
however it doesnt seem to diable it
</command_name:command_id>
You can get the command id by typing a command and right clicking it. You must have developer settings enabled
Yeah, that's wrong xD
How do you define your Select menu? Subclassing or decorator in a view?
class Select(discord.ui.View): # interaction_2nd, select menu
def __init__(self):
super().__init__(timeout=None) ```
okay thanks
well that's not how it works π
Take a look at this: https://guide.pycord.dev/interactions/ui-components/dropdowns
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
and also generally the guide
it does work
@wet coral they also have a property right? for mentioning?
like slash_command.mention
it works for me
</avatar:963218584404914247>
</avatar:963218584404914247>
I am looking for the option to create a /mute command that uses the discord application to users without the need to add a role.
huh, you can see a select menu?
yes
oh yeah, sorry.
disable it and then use self as view
i got it thanks mama
wdym "uses the discord application"?
i am pretty sure i can
slash_command.mention(name= command_name)
can I
.rtfm ApplicationCommand
discord.ApplicationCommand
discord.ApplicationCommand.after_invoke
discord.ApplicationCommand.before_invoke
discord.ApplicationCommand.call_after_hooks
discord.ApplicationCommand.call_before_hooks
discord.ApplicationCommand.callback
discord.ApplicationCommand.can_run
discord.ApplicationCommand.cog
discord.ApplicationCommand.cooldown
discord.ApplicationCommand.dispatch_error
discord.ApplicationCommand.error
discord.ApplicationCommand.full_parent_name
discord.ApplicationCommand.get_cooldown_retry_after
discord.ApplicationCommand.has_error_handler
discord.ApplicationCommand.invoke
discord.ApplicationCommand.is_on_cooldown
discord.ApplicationCommand.prepare
discord.ApplicationCommand.qualified_id
discord.ApplicationCommand.qualified_name
discord.ApplicationCommand.reset_cooldown
.rtfm ApplicationCommand.mention
Target not found, try again and make sure to check your spelling.
no, you can't xD
ah duck
so I have to painstakingly find ids ow?
.rtfm discord.SlashCommand.mention
nevermind, you can
would you look at that
yeah
okay so
sorry, thought ApplicationCommand is the real one
mention is a property, it doesn't have args
π€¨
so you need to have a SlashCommand instance for it to work
oh yea right
you must be thinking of "timeout"
.rtfm member.timeout
this is what it comes up w
<property object at 0x0000020071A952B0>
π₯΄ whats goin on ong
where do you want to mention the command? In a slash command callback?
do you want to mention the invoked command?
command.mention works tho
bro.
how did you use it?
also these ^
yeah, then it's the only way ig
no i mean how did you try this
Actually, if we're on that matter @proud mason, is it possible to mention a command and already pre-fill it?
lmao no
see this
lmao oke i get it now i see
hmm iirc, nope
discord limitation ig. try asking in ddevs server
nah, don't need it currently anyways
π
was just wondering xD
From which version is it possible?
it should be there on 2.4.1 iirc
might be there from before too
i have py-cord==2.4.1
yes so it will work
^
I don't understand how to do it better right now. Pylance in vsc says it would be wrong.
await interaction.response.send_message(content=f"> **d - Dein Rivale ist {rival_user_name}\n- **Bestzeit des Users:** {rival_user_time}\n- **Zeitunterschied zwischen dir und dem User:** {time_difference} Sekunden", ephemeral=True)
else:
await interaction.response.send_message(content=f"- Du hast __keinen Rivalen__ im Leaderboard!", ephemeral=True)
else:
await interaction.response.send_message(f'- Es wurde leider kein Eintrag mit deiner User-ID in unserer Datenbank gefunden, {interaction.user}. Bitte spiele zuerst mit `/tens` eine Runde.', ephemeral=True)
if rival_index <= len(self.leaderboard_list):
rival_user = self.leaderboard_list[rival_index - 1]
rival_user_name = rival_user[0]
rival_user_time = rival_user[1]
time_difference = rival_user_time - current_user_time
await interaction.response.send_message(content=f"> **d - Dein Rivale ist {rival_user_name}\n- **Bestzeit des Users:** {rival_user_time}\n- **Zeitunterschied zwischen dir und dem User:** {time_difference} Sekunden", ephemeral=True)
else:
await interaction.response.send_message(content=f"- Du hast __keinen Rivalen__ im Leaderboard!", ephemeral=True)
else:
await interaction.response.send_message(f'- Es wurde leider kein Eintrag mit deiner User-ID in unserer Datenbank gefunden, {interaction.user}. Bitte spiele zuerst mit `/tens` eine Runde.', ephemeral=True)
well there you have it. Just fix the indentation...
that looks gruesome, nothing fits together. We're using python, indentation matters here xD
ah, it was due to an error above
did you fix the indentation?
yes π
π
Is this normal that a slash command needs a long time to be registered and appear on the user's commands menu?
What do you mean?
I have coded a slash command and I can't see any errors when I start my bot. However, I can't find the slash command when I type the keywords
for member in ctx.guild.members:
async for message in member.history(limit=1):
"discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user"
what am I missing? I have default, members and message_content intents set up
How do you define the bot?
yeah, sorry, I just managed to figure it out:
the first Member it found was the bot itself, and it couldn't open a DM channel with itself
oh, lmao
also, apparently I misunderstood what the "async for x in member.history" does
I'm trying to get their last message from a specific guild
iirc discord has limits on how fast and how many commands you can register per minute and also per day ("There is a global rate limit of 200 application command creates per day, per guild")
Most of the time it's normal, because if you don't dynamically create 100+ commands, you will never have any problems
Just don't reload your bot every 10 seconds on every command change
What the problem? This is a for loop
You can get history as list if you want
messages = await channel.history(limit=123).flatten()
// messages is now a list of Message...
in a specific guild, for every member, I'm trying to get their last message (more specifically, the message.created_at) in that guild
somehow this lead to the bot trying to create a dm channel with itself
I'm not sure yet, but on the first member it finds (which I've verified is the bot itself), it returns this error:
Traceback (most recent call last):
File "/home/silk/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "/home/silk/proj/malbot/cogs/test.py", line 124, in activity
async for message in member.history(limit=1):
File "/home/silk/.local/lib/python3.10/site-packages/discord/iterators.py", line 123, in __anext__
return await self.next()
File "/home/silk/.local/lib/python3.10/site-packages/discord/iterators.py", line 325, in next
await self.fill_messages()
File "/home/silk/.local/lib/python3.10/site-packages/discord/iterators.py", line 344, in fill_messages
channel = await self.messageable._get_channel()
File "/home/silk/.local/lib/python3.10/site-packages/discord/member.py", line 392, in _get_channel
ch = await self.create_dm()
File "/home/silk/.local/lib/python3.10/site-packages/discord/member.py", line 189, in general
return await getattr(self._user, x)(*args, **kwargs)
File "/home/silk/.local/lib/python3.10/site-packages/discord/user.py", line 519, in create_dm
data: DMChannelPayload = await state.http.start_private_message(self.id)
File "/home/silk/.local/lib/python3.10/site-packages/discord/http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
client = discord.Bot() (The problem seems solved
Does it return user message history?
I assume that, instead of trying to get only the messages from the Member's guild,
it tries to get all the User's messages,
including those in private DMs with the bot,
and it creates a DM channel to see if there's... messages from the User...
If I understand correctly, member.history just tries to get dm messages instead of all messages in guild
Which is really strange
does anyone know why this slash command is not registered in discord?
intents etc. I have activated everything, and everything works without problems with the slash commands below.
Try discord.slash_command instead of discord.commands.slash_command
Do you mean with the import?
yes
Are Bots able to super react?
wdym?
ok I've verified it, it does actually just look for DM messages
and the docs for member.history are just copied from channel.history
^ this for e.g
Members are Messageables
afaik no, because bot doesn't has nitro
I just never saw super reactions with bots
If nothing works out, I can suggest just saving the last message from the user as an ID in the database and use on_message
Or... Go through the history of each channel and find a message there
yeah, that's what I'm settling on
what is the other name for it?
from discord.commands import slash_command, Option, SlashCommandGroup
from discord import slash_command ?
yes
Aight, thx thats what i thought
hhm, but that doesn't work either.
I would like to create the following commands:
/deletecounting
/adjustcounting
/setnumber
the other two were created without problems ...
Do you load your cog?
I want to create a slash command with option required integer input and option with choices. Is their any example or guide about it?
Here's the slash options example.
I would like to store data about who was most recently awarded a certain role. I would assume that involves storing the user ID in a certain place and overwriting it when a new user is awarded that new role.
I could use a SQL database but that seems a bit overkill, is there a better way to do this or is it best to stick with the database?
check the audit log?
I guess that could work too... though id prefer to know how to accomplish this in case I have to solve similar problems requiring the bot to store data in a similar manner to this
ig what im looking for is that I could store it in some config-like file under, idk, "LAST_USER_AWARDED_ROLE", and I can easily manipulate what that is set equal to
config files are not intended to be used for storage of persistent dynamic data
yes I know but I would like to know if there is something similar to this that I could store data in
im sure other programs have to do something similar to what I would like to do. How do they accomplish it?
they would use some type of database
Is interaction.custom_id == button.custom_id when a button is pressed?
yes
you could also tias
.tias
but that would involve writing a new (small) bot and creating an application because I can't use the bot that I'm currently working on yada yada yada xD
wait you guys test on production?
who?
oh, me xD
No, I test on my test bot, but I mostly do everything there so I'd need a test-test bot xD
Hello, can I send a variable to my button from a slash command ?
/search forthis
function to search for something on a db and return one id
PressButton > send id to client
Yes
Pass the variable to the view init
thanks I got it working !
I have a banner and if i try to print it the bot says i dont have one?!
I dont know?
Useless xD
Why?
Why i cant do that with a normal command and ctx.author.banner
Its dumb
intents?
Yeah but with intents it didnt work with ctx.author.banner
ok ask Discord
i think its not the reason from discord
in discord.py it works without it. (I dont use discord.py but i looked in the docs)
Nvm got it. Its in jda too. My mistake
@silver moat how can i get the banner if i fetched the user? user.banner isnt working
Well that's definitely the attribute
.rtfm user.banner
you didn't await the fetch
You didn't await your fetch
Ohhhhhhh oops
your fetch is awaiting you didn't it
display_banner?!
There's no display banner
What to instead of interaction.response.defer since there already was a response?
If i just use interaction.defer() ill get this:
AttributeError: 'Interaction' object has no attribute 'defer'
interaction.followup.send
You can't do .response.send_message if you defer
Wont work
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
Show code
class Menu4(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Lock", style=discord.ButtonStyle.red, emoji="π", row=0, custom_id="LockThread")
async def LockThread(self, button, interaction):
embed = discord.Embed(color=discord.Color.green())
embed.add_field(name="\n",value=f"Thread wurde geschlossen!")
await interaction.response.defer()
async with interaction.channel.typing():
await asyncio.sleep(3)
await interaction.response.send_message(embed=embed)
await interaction.channel.edit(locked=True)
@discord.ui.button(label="Archivieren", style=discord.ButtonStyle.red, emoji="π", row=0, custom_id="ArchiveThread")
async def ArchiveThread(self, button, interaction):
embed = discord.Embed(color=discord.Color.green())
embed.add_field(name="\n",value=f"Thread wurde archiviert!")
await interaction.response.defer()
async with interaction.channel.typing():
await asyncio.sleep(3)
await interaction.response.send_message(embed=embed)
await interaction.channel.edit(archived=True)
yeah defer is a response
i know for the send_message i should use interaction.followup.send now
use
embed = discord.Embed(color=discord.Color.green())
embed.add_field(name="\n",value=f"Thread wurde geschlossen!")
await interaction.response.defer()
async with interaction.channel.typing():
await asyncio.sleep(3)
- await interaction.response.send_message(embed=embed)
+ await interaction.followup.send(embed=embed)
``` instead
k
Your defer isn't raising the error, it's the send_message
oh boy its jsut too late, im sorry man. I literally just red it before and also implemented it, wont work because i didnt deferred. Then i deferred and removed the followup... thanks guys
average coding moment
hello there, is there any possible way to make like a middleware to intercept await ctx.respond? Or is there like a event that runs when a slash command has been executed and has NOT send anyhting?
on_interaction?
but that's for interactions in general as the name suggests
not really what i meant. I wanna intercept an embed from await ctx.respond, give it to an function and release the await ctx.respond with new embed
I mean if you're using ctx.respond to send an embed. Why would you want to get the ctx.respond again to find the embed when you already have the embed object in your code?
i wanna somehow automate this process and not copypasting some lines of code to do that π€¨
same thing when i want to add a new command and then forget about this embed editing part, that would be awful
functions exist wow
bruh
bruh
bro i am answering you with my message
same
if you're sending an embed with ctx.respond you're gonna be doing ctx.respond(embed = embed) can you not just, not do ctx.respond and just do work on the embed
i mean you're supplying all the data for responding yourself why would you need to respond then immediately intercept it
Well you could use custom context classes if you really wanted
How do I play an audio stream on a voice channel rather than a full file? I have an audio stream from elevenlabs. Just trying to reduce wait time on my bot
.rtfm discord.PCMAudio
You can use that
If I understood the docs correctly
In case the stream is not encoded,
.rtfm discord.FfmpegPCMAudio
hi! I actually was using wavelink with py-cord for sometime now. and I recently tried to update it to latest version from their GitHub repo. But I think it actually installed discord.py and other dependencies too. Now my code won't work coz I wrote it in py-cord.. so I uninstalled discord.py and wavelink and then re-installed wavelink with cmd shell pip install Wavelink --no-deps
Still, the code doesn't works. Any idea how can I fix it?
The error (if it helps):
File "c:\Users\Administrator\Documents\GitHub\Krishna\main.py", line 2, in <module>
import wavelink
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\wavelink\__init__.py", line 30, in <module>
from .enums import *
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\wavelink\enums.py", line 24, in <module>
from discord.enums import Enum
ModuleNotFoundError: No module named 'discord.enums'
uninstall py-cord too and re-install py-cord
ohk.
How to know how many commands do the bot registers or syncs?
You may be looking for bot.commands or bot.all_commands
My bot has two slash commands but it only shows that it has one command.
That's the built in prefix help cmd
.rtfm bot.walk_app
discord.ext.bridge.Bot.walk_application_commands
discord.Bot.walk_application_commands
discord.ext.bridge.AutoShardedBot.walk_application_commands
discord.AutoShardedBot.walk_application_commands
discord.ext.commands.Bot.walk_application_commands
discord.ext.commands.AutoShardedBot.walk_application_commands
Use this ^
how do i get the latest version (2.5 or 2.5.x or else) of pycord?
is something like pip install -U git+https://github.com/Pycord-Development/pycord ? or
pip install -U git+https://github.com/Pycord-Development/pycord@ad2e0722f00aa44c923b70de942042d0fdb1ea62 ?
and where can i find the current change between 2.4.1 and 2.5 or 2.5.x
?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
And you can see the changes in the changelog, here: https://github.com/Pycord-Development/pycord/blob/master/CHANGELOG.md
omg, thanks a lot
np π
I have seen that in the documentation you can set the default permissions when creating the group but I don't understand how it works. I only know how to do it in the method itself.
ban = SlashCommandGroup("ban", "Commands for ban a user from the server", guild_only=True,
permissions=["administrator", "ban_members"])
I only know how to do it like this
@discord.default_permissions(
administrator=True
)
Hey guys. I tried make custom commands, but it only register one slash command per guild id. When I make other slash command it just dont register, but first still works. Do anyone know solution? Both commands by structure are almost the same.
it is
.tag slashnoshow
Application Commands Not Showing Up?
- Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
which one code to share? where it loads extensions or custom command code?
both
okay
No. You can't get the guild banner.
In CustomCommandCog load extension function def load_custom_commands(self): for filename in os.listdir(self.command_dir): if filename.endswith(".py"): extension_name = filename[:-3] full_extension_name = f"cogs.commands.customcommands.{extension_name}" module = importlib.import_module(full_extension_name) self.bot.load_extension(full_extension_name) print(f"Loaded {full_extension_name}") print(f"[{timestamp}] Custom Commands loaded!") and custom command ***_hello.py ```
import discord
from discord.ext import commands
from discord.commands import slash_command
class CustomCommand798155873435910154_hello(commands.Cog):
def init(self, bot):
self.bot = bot
self.admin_rights = False
@commands.slash_command(name="hello", description="Custom command for guild Limro CodeX created by Limro-Sama.", guild_ids=[837053695040159764])
async def hello(self, ctx):
if ctx.author == self.bot.user:
return
if self.admin_rights and not ctx.author.guild_permissions.administrator:
return
await ctx.respond('hello')
def setup(bot):
bot.add_cog(CustomCommand798155873435910154_hello(bot))
now slash commands does not register at all. Only prefix commands work fine
why
do u have a on_connect in your code
I have on_ready in main.py file
but not on_connect?
nope
import os
import datetime
import asyncio
from discord.ext import commands
from dotenv import load_dotenv
from cogs.commands.createcustomcommand import CustomCommandsCog
from get_cogs_list import GetCogsList
cogslist = GetCogsList.cogslist
load_dotenv("./cogs/creds/credentials.env")
TEST = os.getenv("TEST")
MAIN = os.getenv("MAIN")
now = datetime.datetime.now()
timestamp = now.strftime("%d-%m-%y | %H:%M:%S")
bot = commands.Bot(intents=discord.Intents().all())
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="/help | =3"))
cache_path = "./cogs/commands/customcommands/__pycache__"
for file_name in os.listdir(cache_path):
if file_name.endswith(".pyc"):
file_path = os.path.join(cache_path, file_name)
os.remove(file_path)
print(f"[{timestamp}] Custom Commands .pyc cache cleared!")
custom_commands_cog = bot.get_cog("CustomCommandsCog")
if custom_commands_cog:
custom_commands_cog.load_custom_commands()
giveaway_check_cog = bot.get_cog("GiveawayCheck")
if giveaway_check_cog:
await giveaway_check_cog.giveaway_check()
giveaway_cog = bot.get_cog("Giveaway")
if giveaway_cog is None:
print("Error: Giveaway cog is not loaded.")
return
print(f"[{timestamp}] Connected! Synced commands successfully!")
for ext in cogslist:
try:
bot.load_extension(ext)
print(f"Loaded {ext} cog")
except Exception as e:
print(f"Failed to load {ext} cog: {e}")
#bot.run(MAIN)
bot.run(TEST)```
ok wait
main slash commands are working fine
dont load them inside on_ready
you mean get_cogs?
custom_commands_cog.load_custom_commands() this thing
dont do it inside on_ready
do it before bot.run()
what about other cogs in on_ready? move them outside too?
yes
also, dont change presence on_ready
you can just pass it to bot = commands.Bot(..., activity=discord.Activity(...))
why? xD
commands are synced on startup, before on_ready gets fired. if you load after it gets fired, they wont get synced
Okay thanks! custom commands are working now. Presence too.
nice
ohhh right
Sorted it - removed my messages so as not to waste someones time fyi.
is there anyway that i can avoid this?
ValueError: 'corrupt' is not in list```
```py
if "corrupt" in details.lower():
position = values.index("corrupt") - 1
multiplier = float(values[position])
price = multiplier * 8.65
total_price.append(price)
elif "corrupts" in details.lower():
position = values.index("corrupts") - 1
multiplier = float(values[position])
price = multiplier * 8.65```
if i input corrupts, then it thinks ive inputted corrupt and throws an error
How can I get the guild_id to use it for creating different tables in mysql, for every guild? Just cant find anything
Want to do someting like this:
mySql_Create_Table_Query = """CREATE TABLE DB_""" + int(guildid) + """ ( Id int(11) NOT NULL AUTO_INCREMENT, User varchar(250) NOT NULL, Message varchar(5000) NOT NULL, PRIMARY KEY(Id)) """
if you have a guild object you can simply do guild.id for that guild's id
you could check if corrupts is in details first before checking if corrupt is present
wouldnt it show the same error?
only if the list values does not have "corrupts" in it
if this is intended you can put it in a try except which will catch the error and then you can handle it yourself
Is it possible to implement the built-in help command for slash commands? I am currently looking that this guide: https://guide.pycord.dev/extensions/commands/help-command/ but it seems to be geared towards text based commands (please ping me if anyone has a solution)
Is it possible to keep messages ephemeral through multiple followups after a defer? As in, they're still ephemeral-like when you do it the obvious way, but with multiple followups, the bot is responding to itself, so it doesn't seem to keep the intended privacy
nvm, it turns out it works if you use ctx.send_followup() instead of interaction.followup.send()
Hey there! I want to check if someone uploads a video to a channel, but when I check if a user has attachment, it just simply gives me back an empty array for any attachment
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
print(message.attachments)
if message.author.id == 378801849496764416:
print(message.attachments)
Okay, I actually managed to do a workaround by fetching the message
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
if message.author.id == 378801849496764416:
msg = await message.channel.fetch_message(message.id)
print(msg.attachments)
And now I can see the attachments
you need message content intents iirc
there isnt a need for a help cmd for slash cmds, since the slash menu itself is descriptive
you probably have conflicting dependencies/packages
Do you have a requirements.txt?
yeah and re-install pycord
you did re-install py-cord right?
as in uninstall and install

Question
Is it possible to resize or scale the image for embeds?
It doesnt appear so. This has no effect, regardless of what I input. I guess I need to play around with the image size manually to get things looking right.
TYVM for your quick response π
does it work?
No π¦
Can you show your pip list pls?
pip list > pip.txt would create a text file with your list at cmd
#faq message
jishkucord, topggpy, py-cord, discord.py uninstall all 4
I think u need to uninstall discord.py
you have to uninstall and reinstall only py-cord
it would not work if you just uninstall the other library's
topggpy will install dpy
install it with no-deps flag
are you using a requirements.txt file?
how does it look?
did you freeze all libraries, or typed manually?
if you freezed all libs, you can remove dpy, and then use the no-deps flag in pip install
oof
we could create a tag for it to have it easier x3
For the pip stuff
yea
any way to get the voice history of a voice channel? like when members connected/disconnected?
Do you mean this?
Ya, im looking for a "history()" method that returned historical voice state data, but i guess ill have to track in real-time
I found a small bug, I think.
ctx.defer(ephemeral=True)
await paginator.respond()
leads to the buttons failing on the paginator. Easy workaround is adding ephemeral=True to the paginator call.
Is this worth a full bug report?
Easy workaround is adding
ephemeral=Trueto the paginator call
what do you mean by paginator call in this regard?
also, 2.4.1? what happens on master?
paginator.respond(<whatever>, ephemeral=True)
ah
I can check, but idk off the top of my head. If anyone cares I can do a serious bug report. I just wanted to see, since it's a small thing with an easy workaround that will probably suck to actually fix
It has something to do with the paginator trying to find the message it's responding to, but it can't for some reason.
I think so, yes. It was very consistent
can you send a non-ephemeral followup to an ephemeral defer?
Sort of. It doesn't error there. It shows in an ephemeral, but raises whenever you try to change pages
So make the bug report?
sure. no harm in making one
Can do
also, could you check if the issue is only with paginators, or any normal view too?
that will help the debugging process
For sure. Do you just mean other ui elements?
yes
Gotcha. Yeah, I'll get on that now. Just finished my actual work for the day
It was only with paginators and yes I'm on 2.4.1. Here's the bug report: https://github.com/Pycord-Development/pycord/issues/2173
how do i check if a user input is a valid emoji?
can anyone help me figure why i get an error from this? the error is:
File "c:\Users\kenan\OneDrive\Desktop\TBD Bot\bot.py", line 21, in <module>
bot=discord.bot()
^^^^^^^^^^^^^
TypeError: 'module' object is not callable
the code is:
import os # default module
from dotenv import load_dotenv
from discord.ext import tasks, bridge
import pymongo
import httpx
import json
intents = discord.Intents.all()
intents.message_content = True
bot = bridge.Bot(command_prefix=".", intents=intents)
client = pymongo.MongoClient("db")
mydb = client["Users"]
mycol = mydb['Accounts']
sus = json_data = json.load(open('sus.json'))
cogs = sus['cogs']
load_dotenv()
bot=discord.bot()
intents = discord.Intents.default()
intents.guilds = True
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers"))
print(f"Currently in {len(bot.guilds)} servers.")
servers = len(bot.guilds)
await bot.change_presence(activity=discord.Game(name=f"Watching {servers} servers!"))
for cog in cogs:
print('Loading', cog)
bot.load_extension(f'cogs.{cog}')
print('Loaded', cog + '!')
bot.run(os.getenv('TOKEN'))```
Your code says bridge.bot not discord.bot like the error
Its two lul
Oh yeah two bots
How can I disable the explicit content filter for my bot?
Hey, does anyone know why my user mentions sometimes aren't being formatted properly? Example here - it happens pretty inconsistently
Your own client didn't cache the user
Ahh I see. Assuming that I can't do anything about it then since it's on the client side?
yes, it's client side problem
If you never saw the user, you will just see id
You can easily cache the user if you find him in user list (right panel), see user's message or dm him
Or, to summarise, you cache the user when you see his avatar
why is the View.message attribute not available in a View's on_timeout?
At least I get this error in the on_timeout, when trying to use self.message: AttributeError: 'NoneType' object has no attribute 'edit'
Why does this return NoneType?
thread_message = await interaction.channel.fetch_message(interaction.message.id)
its a channel created thread
What are your intents?
intents = discord.Intents.all()
thread_channel_name = bot.get_channel(interaction.channel.id)
thread_channel_id_fetch = await interaction.channel.fetch_message(interaction.message.id)
match = re.search(r'Thread id=(\d+)', str(thread_channel_id_fetch))
if match:
thread_id = match.group(1)
print(thread_id)
This works, but wont work for a /reopen call.
And this seems waaay to complicated to "just" get the thread id but no other way worked.
it streams mp3 as it speaks https://docs.elevenlabs.io/api-reference/text-to-speech-stream
when I try to just directly use voice.play on the audio object I get "TypeError: source must be an AudioSource not generator"
hmm are you using any wrapper for the api? or requests/aiohttp?
you will probably need to create your own class
The client thing
from elevenlabs import generate, play
audio = generate(
text="Hi! My name is Bella, nice to meet you!",
voice="Bella",
model='eleven_monolingual_v1',
stream=True
)
play(audio)
That was just the example, in my code I returned "audio" to discord for the voice client to try to play
"returns audio as an audio stream"
hmm I'll try
import requests
CHUNK_SIZE = 1024
url = "https://api.elevenlabs.io/v1/text-to-speech/<voice-id>/stream"
headers = {
"Accept": "audio/mpeg",
"Content-Type": "application/json",
"xi-api-key": "<xi-api-key>"
}
data = {
"text": "Hi! My name is Bella, nice to meet you!",
"model_id": "eleven_monolingual_v1",
"voice_settings": {
"stability": 0.5,
"similarity_boost": 0.5
}
}
response = requests.post(url, json=data, headers=headers, stream=True)
with open('output.mp3', 'wb') as f:
for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
if chunk:
f.write(chunk)
Then play the mp3
you can even "stream" it instead of loading everything
let me go through source. one sec
I already have it working if I output the entire file
ic
well, I return a path after it does a save(audio, file_path)
hmm so you can subclass discord.AudioSource
how do you currently play? can you show where you use generate rn?
main function with on message event:
voice = get(bot.voice_clients, guild=message.guild)
file_path = sendtts(str(reply))
source = FFmpegPCMAudio(file_path)
voice.play(source)
(in the sendtts def):
audio = generate(
text=message,
#voice="Rachel",
voice="3EUfPs00hQIYWy6Kxcrx",
model="eleven_monolingual_v1",
)
save(audio, file_path)
return file_path
ah ok
so now what you should do is
do this. override __init__ and accept a parameter (maybe call it stream or smth)
save it on a self variable
then override read and return next(self.stream)
ez
mmm subclass a different class maybe? I don't see an init. Maybe ffmpegaudio?
https://docs.pycord.dev/en/stable/_modules/discord/player.html#AudioSource
might be wrong docs
you can always add new methods when subclassing
also the class depends upon what elevenlabs returns. does it return PCM audio?
mp3
as shown here:
import requests
CHUNK_SIZE = 1024
url = "https://api.elevenlabs.io/v1/text-to-speech/<voice-id>/stream"
headers = {
"Accept": "audio/mpeg",
"Content-Type": "application/json",
"xi-api-key": "<xi-api-key>"
}
data = {
"text": "Hi! My name is Bella, nice to meet you!",
"model_id": "eleven_monolingual_v1",
"voice_settings": {
"stability": 0.5,
"similarity_boost": 0.5
}
}
response = requests.post(url, json=data, headers=headers, stream=True)
with open('output.mp3', 'wb') as f:
for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
if chunk:
f.write(chunk)
mp3 is the compression format
er, mpeg?
if i understand correctly, pcm or opus are encoding formats
not sure
another thing to note. generate is blocking. you might want to do stuff on your own using aiohttp
Possible to get the roles from a role select like the order they were added?
Discord sorts them after selecting to the role hierachie. I guesst not but any idea to do that programming wise?
you'd need to keep track of adding roles to members and store that in a db I guess...
i dont think you can do that. discord limitation
but you can sort them in the order the roles were created... if that helps
Is it possible to delete or edit views of a message, when the bot shuts down?
I suppose the on_timeout isn't called when the bot stops?
I use subclassed bot with functions in async close
class BetterBot(Bot, ABC):
async def close(self):
self.cooldowns_save()
await self.aiosqlite_clean_up()
await super().close()
yeah, but how can I edit the messages that have view attached to them?
Probably save them somewhere right?
There isn't any bot attribute that stores all views or anything like that?
there is
it is not intended for public use iirc, so you will have to go through the source
but it might be smth related to bot._view_store
yea check that
Is there a way to make a text input box in a model bigger (i know you can have a single line one and a bigger one, but even bigger than that)?
You can only make singleline and multiline InputText
rip ty β¨
You don't really have any other options π
Also text only for a modal ;3
found it. bot._connection._view_store._views
lots of _ π
It need more _
looks like it's not supposed to be used xD
but thanks
Some documentation for all the "invisible" code would sometimes be great xD
its supposed be "invisible" yk
how do i run the bot
omfg

lmao
I can't lmfao
uhm...
what is a message update event?
mentioned in: https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.add_view
I don't really understand the purpose/usage of the message_id parameter
hey guys. Can pycord use localization on option names and descriptions? can I add localization to option names? @option("prize", description="Enter giveaway prize.")
afaik yes, but don't ask me how xD
I think so too
.rtfm localization
ok ty
Is it safe to pass a discord.Message object to other functions and have it "waiting" there for usage or can it timeout or something?
or should I use a partial message instead?
That's safe from what I understand
As long as you have a "strong reference" to the object, it should be fine
it's a strong reference by default, right? Because I saw that pycord also uses weakrefs somewhere
after doing some digging the output is lame encoding.
looks like this:
\xcaLAME3.100\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\x04(\xda\x8c\xb2\xed\x956T\x81\x84`\xd0\n\xe0\x00\xa4\xe0b\x8c\xf5\xba\x16\xc9%\x1d\xd0g\x8f\xf6aNB$\n\xc73}\xf2"\xe8\xb4T\x8a\xe4\xc1<x\x899\xd4J\x07\x06/\x9b.\x16\x1a"\xf6\x85\x19\x97E\x03\xcd\xdf\xfb\x96tT\\,\x11\x08\x01\xeck\xd5\xb9X\xd2\x15\xa3C\x138\xff\xff\xec\xd7i.2\x151\x99\xa5\x83C\xa8\x90X<J\xe3\xd1{\xd1T\xb9c\x8f\xdf\xff\xff\xf3o\xcd8\xa3\x1d\x0br\xca\x93Iec\xa0\x98n~\x8dy\x9a\xed\x95\xcc\xfc3}\xc3%7 C\xa0\x9bcv&\xd6\x8c\x82\xc2\x8
Their TTS class looks like this:
@staticmethod
def generate(
text: str, voice: Voice, model: Model, api_key: Optional[str] = None
) -> bytes:
url = f"{api_base_url_v1}/text-to-speech/{voice.voice_id}"
data = dict(
text=text,
model_id=model.model_id,
voice_settings=voice.settings.dict() if voice.settings else None,
) # type: ignore
response = API.post(url, json=data, api_key=api_key)
return response.content
@staticmethod
def generate_stream(
text: str,
voice: Voice,
model: Model,
stream_chunk_size: int = 2048,
api_key: Optional[str] = None,
) -> Iterator[bytes]:
url = f"{api_base_url_v1}/text-to-speech/{voice.voice_id}/stream"
data = dict(
text=text,
model_id=model.model_id,
voice_settings=voice.settings.dict() if voice.settings else None,
) # type: ignore
response = API.post(url, json=data, stream=True, api_key=api_key)
for chunk in response.iter_content(chunk_size=stream_chunk_size):
if chunk:
yield chunk```
the generate_stream is called and it chunks this lame encoding
display_name I think
https://docs.pycord.dev/en/stable/api/models.html#discord.ClientUser.display_name
Yeah I thought that as well but I don't think that works, pretty sure it's just the username without the descriminator, which isn't a thing anymore for most anyway
ah
currently on master, no stable release yet sorry

(we are being ghosted)
Is there an ETA?
I'll stick to current for now
My users are just gonna have to suffer with usernames for a bit
if i input harvs, then it prints 2x the price, anyone know how to stop it from happening?
for word in "harvester", "harvesters", "harv", "harvs":
if word in values:
position = values.index(word) - 1
multiplier = float(values[position])
price = multiplier * 8.50
total_price.append(price)```
Question: what do you all think of storing data in fs? Surely Im not the only one who hates databases
what's fs?
File system
I use MongoDB x3
- Lack of data integrity
- Limited querying capabilities
- Poor performance with large datasets
- Limited concurrency and transaction support
- Lack of security and access controls
- Lack of scalability
you can create failsafes but learning sql or whatever language is easier for the most part
These are just some that I thought of on the top of my head, if you would like me explain any of them further, please say so
Itβs not storing that much or secret data. Just users afk status, and event status (Simon says)
I try to avoid storing data
Wait. SimonSays is stored in a dictionary. Tell me how angry u are
Discord just stored that message you sent in JSON format
Does it look like Iβm discord π
Jk lol. For extreme data protection I store user data in .env
|| this is obviously a joke||
@round rivet what
your mom
thanks
I β€οΈ files.
If you are looking for something small and easy to understand, I recommend checking out MongoDB.
I have checked it out. Itβs so confusing
you have to learn some type of database eventually Β―_(γ)_/Β―
eventually
If you wrap your saving code in a single class/library you can replace the underlying storage without any code changes
How can I add an asynchronous function to the discord.User class? Do I have to subclass?
I was wondering how to use slash commands with a bot created by commands.Bot (commands from discord.ext)? I've tried @bot.command(), @bot.slash_command(), and @bot.command(description="desc"). Thanks!
if you use discord.Bot you dont have to change @bot.command()
dang thanks!
how to read attachment ?
the Attachment.read() no work, because return me an bytes
ehh just edit the user.py directly
what are you trying to do
it's meant to return bytes
But I want to do a custom function that uses a variable like db
im saying just edit the function in
why not add the method to your db class
I want to do something like await user.get_economy_profile()
subclassing isn't worth it because then you'd have to override the class everywhere
this is why forking exists
db.get_economy_profile(user)
But like once usernames are added into Pycord, I have to re-do the changes
idk you don't have many other options
squid's idea is likely more sustainable
or fork it on github and install your own branch, then you can sync the changes from the main repo whenever necessary
oh no merge conflicts
eh if you're adding your own single function then in theory you'd never conflict
I only need it on one bot so Iβll probably just edit the files
I have a feeling that vNziie just isn't reading my messages lol
I am but thatβs what Iβm currently doing with a database class, and it gets kind of annoying since Iβve been doing that method for so long
im trying make a command to upload an files
(only .txt files) because i need to read the file
but, the read return me b'' as binary
then you use open on the binary
probably with mode="rb"
the problem is an discord.attachment
file: discord.Attachment
what's wrong...?
you read the attachment, which returns binary data, and then you use that with the builtin open function that you normally use with files
It was that when using open it detected it with an attachment and not a text or file, so I only had to use requests and that was the solution
thanks for your help π
Can I get how long ago the user was last online?
Hello. I don't understand how to get the list of roles of the member who wrote the message.
@client.event
async def on_message(message):
if message.guild.get_roles(...) in message.author.roles:
...
This doesn't work because the User class doesn't have a roles variable. The message were sent to the server, not to the DM. The code runs but every time someone sends a message with the right role or someone is given or removed this role an error occurs
Is it possible to have a Discord bot create an event?
My thought is that I create a slash command where I query all the data and then automated at a later time I specify in the slash command will create the event from the bot and published?
And what is the error?
Every few mins, check if they are online and log it to a file
What intents are you using?
Is it possible to edit integration permissions in a server with a bot, other than via default permissions?
Can't see anything in the docs so guessing no, but figured I'd ask
Define the roles you want to find;
mod = discord.utils.get(ctx.guild.roles, id=0) ( or name=βxβ ) then use if mod in ctx.author.roles: β¦
Best thing to do is have a json βconfigβ file with your IDS and just import them into your cogs
All intents
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 399, in _run_event
await coro(*args, **kwargs)
File "C:\Users\ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ\Desktop\ΠΡΠΎΠ΅ΠΊΡΡ\server\bot.py", line 45, in on_message
if not message.guild is None and message.guild.get_role(1131159247879680021) in message.author.roles \
AttributeError: 'User' object has no attribute 'roles'```
What code is the attribute error pointing to?
The section
@slow vector, here is the part of the code that is causing the error
Maybe I misunderstood your question
The code is not in Cogs, it is in the main bot file
You need to get the 'Member' object to retrive the user's roles. You can't use a 'User' object for it
Code:
if not user.id in member.id:```
@client.event
async def on_message(ctx):
role1 = discord.utils.get(ctx.guild.roles, id=0000) # or (ctx.guild.roles, name="xxxx")
role2 = discord.utils.get(ctx.guild.roles, id=0000) # or (ctx.guild.roles, name="xxxx")
if role1, role2 in ctx.author.roles:
...
You're trying to see if an integer is a boolean
Try if member id == {}, unless that isn't what you're trying to do
i try to make a userinfo command with less infos if the user isnt on the server
how is the best way to check if a user is on the same server?
if member: discord.Member in ctx.guild:
... # pass true: member is in discord
else:
... # pass false: member not in discord
or you could just pass it as if member in ctx.guild if you define the member in the command
Iβve been out of the loop for a bit. Has there really not been any updates since March?
There have been no new releases since March, but a lot of progress has been made on the Master branch
Will slash command description_localizations update every time user changes localization on discord? Or only after bot restart?
Do you use sync_command?
if not you have to restart the bot everytime
nope
where I have to add it?
.rtfm sync_command
so I just have to add loop every for example 5 mins sync commands?
do you mean when someone changes their client language?
yeah
after how many mins?
kk, I will check one more time
for me it changes only after I refresh server (go to other and then back to server)
well that's still client sided, not sure on how well it works with cache but as long as you've added the necessary languages you don't need to do anything extra
Are you sure about that?
wdym??
what else are you meant to do
they're talking about a user changing the language on their discord app
oh wait nvm
also about sync_commands(). I am trying to sync custom commands guild_id after creating using this await self.bot.sync_commands(guild_ids=[guild.id]) , but it shows me Error: 400 Bad Request (error code: 50035): Invalid Form Body In 62: Application command names must be unique custom command name look like this ``` @commands.slash_command(name="hello", description="Test", guild_ids=[837053695040159764])
async def hello(self, ctx):
yes?
Let me try
@slow vector py if user in ctx.guild: TypeError: argument of type 'Guild' is not iterable
Code:
async def whois(self, ctx, user: discord.User = None):
if user == None:
user = ctx.author
if user in ctx.guild:
member = user```
ctx.guild.members
also, you should use user: discord.Member = None
@commands.slash_command(name="whois")
@guild_only()
async def whois(self, ctx, member: discord.Member):
if user in ctx.guild.members:
...
i want to get users which are not in the server
if user not in ctx.guild.members
Yeah let me try
ah ok
How to do it?
context menu commands
Learn all about Context Menus (User Commands & Message Commands) and how to implement them into your Discord Bot with Pycord!
see this
import discord
from discord.ext import commands
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, timeout=120)
action_row = discord.ui.ActionRow()
action_row.add_item(discord.ui.InputText(label="What is your name?"))
action_row.add_item(discord.ui.InputText(label="How old are you?"))
action_row.add_item(discord.ui.InputText(label="Have you worked in this line of work before?"))
action_row.add_item(discord.ui.InputText(label="Why do you want to work with us?"))
self.add_item(action_row)
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Job Application")
embed.add_field(name="What is your name?", value=self.children[0].values[0])
embed.add_field(name="How old are you?", value=self.children[0].values[1])
embed.add_field(name="Have you worked in this line of work before?", value=self.children[0].values[2])
embed.add_field(name="Why do you want to work with us?", value=self.children[0].values[3])
channel = interaction.guild.get_channel(1130274326281719848) # Replace CHANNEL_ID with the specific channel ID you want to send the callback
if channel:
await interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message(content="Error: Unable to find the specified channel.")
class Testing(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="apply", description="Apply for a job")
async def apply(self, interaction: discord.Interaction):
modal = MyModal(title="Modal via Slash Command")
await interaction.response.send_message(view=modal)
def setup(bot):
bot.add_cog(Testing(bot))
``` started learning forms but i have error
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 978, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/mikis/testing/form.py", line 35, in apply
modal = MyModal(title="Modal via Slash Command")
File "/home/mikis/testing/form.py", line 8, in init
action_row = discord.ui.ActionRow()
AttributeError: module 'discord.ui' has no attribute 'ActionRow'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord.ui' has no attribute 'ActionRow'```
What is ActionRow()?
i ops its old guid
import discord
from discord.ext import commands
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, timeout=120)
self.add_item(discord.ui.InputText(label="What is your name?"))
self.add_item(discord.ui.InputText(label="How old are you?"))
self.add_item(discord.ui.InputText(label="Have you worked in this line of work before?"))
self.add_item(discord.ui.InputText(label="Why do you want to work with us?"))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Job Application")
embed.add_field(name="What is your name?", value=self.children[0].values[0])
embed.add_field(name="How old are you?", value=self.children[0].values[1])
embed.add_field(name="Have you worked in this line of work before?", value=self.children[0].values[2])
embed.add_field(name="Why do you want to work with us?", value=self.children[0].values[3])
channel = interaction.guild.get_channel(1130274326281719848) # Replace CHANNEL_ID with the specific channel ID you want to send the callback
if channel:
await interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message(content="Error: Unable to find the specified channel.")
class Testing(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="apply", description="Apply for a job")
async def apply(self, interaction: discord.Interaction):
modal = MyModal(title="Modal via Slash Command")
await interaction.response.send_message(content="Please fill out the job application form:", view=modal)
def setup(bot):
bot.add_cog(Testing(bot))
correct?
you add InputTexts like this
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, timeout=120)
self.add_item(...)
self.add_item(...)
yes
and... i getting that
Ignoring exception in command apply:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 978, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/mikis/testing/form.py", line 33, in apply
await interaction.response.send_message(content="Please fill out the job application form:", view=modal)
File "/usr/local/lib/python3.8/dist-packages/discord/interactions.py", line 825, in send_message
await self._locked_response(
File "/usr/local/lib/python3.8/dist-packages/discord/interactions.py", line 1090, in _locked_response
await coro
File "/usr/local/lib/python3.8/dist-packages/discord/webhook/async_.py", line 221, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.2.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.3.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.2.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.3.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
hm
Can I make context menu commands for current users? Ex. Ban only for admins
i think you can use permissions
Here's the slash perms example.
they will for work context menu cmds too
Okay, i'll try it
channel = interaction.guild.get_channel(1130274326281719848) # Replace CHANNEL_ID with the specific channel ID you want to send the callback
if channel:
await interaction.response.send_modal(embed=embed)
else:
await interaction.response.send_message(content="Error: Unable to find the specified channel.")
class Testing(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="apply", description="Apply for a job")
async def apply(self, interaction: discord.Interaction):
modal = MyModal(title="Modal via Slash Command")
await interaction.response.send_modal(content="Please fill out the job application form:", view=modal)
like that?
nope
await interaction.response.send_modal(modal)
thats all
also, wtf is
await interaction.response.send_modal(embed=embed)
its where it will send
this should be send_message not send_modal
even though Modal is related to View, dont mix those two
testing*
isn't it better to use ctx instead of interaction at the slash command?
oh right
Ignoring exception in modal <testing.form.MyModal object at 0x7f12e04c0be0>:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ui/modal.py", line 341, in dispatch
await value.callback(interaction)
File "/home/mikis/testing/form.py", line 17, in callback
embed.add_field(name="What is your name?", value=self.children[0].values[0])
AttributeError: 'InputText' object has no attribute 'values'```
- async def apply(self, interaction: discord.Interaction):
+ async def apply(self, ctx: discord.ApplicationContext):
self.children[0].value
it will be value
i broke something, 
i know did that from here
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1164, in on_connect
await self.sync_commands()
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 534, in register_commands
desynced = await self.get_desynced_commands(
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 360, in get_desynced_commands
elif _check_command(cmd, match):
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 275, in _check_command
as_dict = cmd.to_dict()
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 844, in to_dict
"options": [o.to_dict() for o in self.options],
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 844, in <listcomp>
"options": [o.to_dict() for o in self.options],
File "/usr/local/lib/python3.8/dist-packages/discord/commands/options.py", line 333, in to_dict
"type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'```
```py
import discord
from discord.ext import commands
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, timeout=120)
self.add_item(discord.ui.InputText(label="What is your name?"))
self.add_item(discord.ui.InputText(label="How old are you?"))
self.add_item(discord.ui.InputText(label="Have you worked in this line of work before?"))
self.add_item(discord.ui.InputText(label="Why do you want to work with us?"))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Job Application")
embed.add_field(name="What is your name?", value=self.children[0].value)
embed.add_field(name="How old are you?", value=self.children[1].value)
embed.add_field(name="Have you worked in this line of work before?", value=self.children[2].value)
embed.add_field(name="Why do you want to work with us?", value=self.children[3].value)
channel = interaction.guild.get_channel(1130274326281719848) # Replace CHANNEL_ID with the specific channel ID you want to send the callback
if channel:
await interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message(content="Error: Unable to find the specified channel.")
class Testing(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="apply", description="Apply for a job")
async def apply(self, ctx, interaction: discord.ApplicationContext):
modal = MyModal(title="Modal via Slash Command")
await ctx.respond("please apply")
await interaction.response.send_modal(modal)
def setup(bot):
bot.add_cog(Testing(bot))```
beacuse when it wasnt i getting error but modal opened
hello again how fix?
after pushing button
what code is this format?
diff
make ctx.respond visible only for user
import discord
from discord.ext import commands
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, timeout=120)
self.add_item(discord.ui.InputText(label="What is your name?"))
self.add_item(discord.ui.InputText(label="How old are you?"))
self.add_item(discord.ui.InputText(label="Have you worked in this line of work before?"))
self.add_item(discord.ui.InputText(label="Why do you want to work with us?"))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Job Application")
embed.add_field(name="What is your name?", value=self.children[0].value)
embed.add_field(name="How old are you?", value=self.children[1].value)
embed.add_field(name="Have you worked in this line of work before?", value=self.children[2].value)
embed.add_field(name="Why do you want to work with us?", value=self.children[3].value)
embed.set_footer(text=f"Application submitted by {interaction.user.display_name}")
# try:
# await interaction.response.send_message(content="Please fill out the job application form:", view=MyModal(title="Modal via Slash Command"))
# except discord.HTTPException:
# pass
channel = interaction.guild.get_channel(1130274326281719848) # Replace CHANNEL_ID with the specific channel ID you want to send the callback
if channel:
await channel.send(embeds=[embed])
else:
await interaction.followup.send_message(content="Error: Unable to find the specified channel.")
class Testing(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="apply", description="Apply for a job")
async def apply(self, ctx: discord.ApplicationContext):
modal = MyModal(title="Modal via Slash Command")
await ctx.send_modal(modal)
def setup(bot):
bot.add_cog(Testing(bot))
``` how fix this error?
you never responded with something
for a what?
for the modal callback?
how make ctx.respond visible only for user
?tag ephemeral
An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.
To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)
This is the equivalent of hidden=True if you're coming from interactions.py
e.g.
await ctx.respond("Imagine a message!", ephemeral = True)
await interaction.response.send_message("Imagine a message!", ephemeral = True)
i tried all ideas for fixing idk how fix? can you help pls?
within your callback function (of the modal class) you can await interation.response.send_message("xxxx") (Or other response functions) to respond to the interaction.
i fixed thanks
class ExampleModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Type STUPID if you are stupid!"))
async def callback(self, interaction: discord.Interaction):
response = (self.children[0].value).upper()
if response == "STUPID":
await interaction.response.send_message("You confirmed you are stupid!", ephemeral=True)
else:
await interaction.response.send_message("You did not confirm the stupidity, therefore I don't think you're stupid")
... # Within Cog Class
@commands.slash_command(name="example")
async def example(self, ctx: discord.ApplicationContext):
modal = ExampleModal(title="Are you sure you aren't stupid?")
await ctx.send_modal(modal)
Is pretty much the break down
Is it possible to send dms to ppl in a server with a button attached to it that would spawn a modal?
yea
Hi, there,
Question, why does my bot manage to rename channels once every 2 to 5 minutes only twice? Has Discord changed anything?
1 every 10 minutes
Is Elon Musk the owner of Discord?

I can create and delete 50 channels but rename only once...
Yes 
Is this possible to get other user locale by user id?
Ephemeral Messages suddenly stopped working anymore.
I have changed nothing.
That seems, absurd?
Are you 100% sure you didn't change anything and it worked earlier
Are you sure that you did not add defer(). If you use defer you need to make defer ephemeral too.
.defer(ephemeral=True)
Hello! How can I ping a role through a button?
await interaction.response.send_message(f"ΠΠΎΠ²ΡΠ΅ ΡΠΎΠ²Π°ΡΡ ΠΎΡ **{interaction.user}** β {role.mention}")
I need the role to mention people
whats the best way to removed expired powerups should i keep it in an on message event or in a on_application_command or something? where it would delete the users powerups or all power ups from the db?
how were you going to get the role?
from slash cmd?
oh sorry
i misunderstood
you might need to play around with allowed_mentions
.rtfm AllowedMentions
pass an object of that to the allowed_mentions parameter in interaction.response.send_message
basically where should i run the removeExpiredPowerups function so that its the most efficient? Should i run it before every command? Or just every command where the user needs to use the economy part of the bot? Should i remove all the power ups? Or just the users power up
how do your powerups work? do they have a timer or smth?
thanks, looks like that's what I was looking for
yeah, pretty much
async def removeExpiredPowerups(self):
await self.execute("DELETE FROM powerups WHERE expirationTime < $1", utils.utcnow())
return "Your Power-up has ended"```
how?
yes
you could do this then
let me just find
and is it best to remove all of them? Or just the users that ran the command and let them know that what powerups were removed? Or maybe the person thats mentioned and the author or something idk
.rtfm cog_before_invoke
all of them should be fine for the most part
sql is powerful enough with the filtering
override this and add your method
what method? wdym
just add this to the cog?
async def cog_before_invoke(self, ctx):
await self.bot.removeExpiredPowerups()``` its just that simple
yep
should work
okay sick
while not py-cord related
def handle_place(place: str) -> tuple[str, str]:
places = response_json()['search_place_responses']
place_data = places.get(place)
if place_data is None:
return None, None
get_choice = random.choice(place_data)
messages = get_choice.get("messages")
item_probs = get_choice.get("gained", {})
if messages is not None:
sentence = random.choice(messages)
else:
sentence = None
if item_probs:
items = list(item_probs.keys())
probabilities = list(item_probs.values())
rand_item = random.choices(items, probabilities)[0]
return sentence.format(str(rand_item)), rand_item, "item"
if (coins_minmax := get_choice.get("coins")) is not None:
coins_gained = random.randint(*coins_minmax)
return sentence.format(str(Config().currencyEmoji), str(coins_gained)), str(coins_gained), "coin"
return sentence, None, None
``` this is my function for the search command, and my json structure looks something like this
```json
"search_place_responses": {
"Hospital": [
{
"messages": [
"You found yourself walking on top of needles, you fell to the floor and woke up years later"]
},
{
"messages": [
"... gives you a **{}**",
"The nice nurse gave you a **{}**"
],
"gained": {
"Silverware": 0.25
}
},
{
"messages": [
"You found **{} {}** ..."
],
"coins": [200, 250]
}
],}``` i was curious as to how can i make the chance of receiving the items smaller as in you would get coins more often than items since if theres just 1 item in the gained then the chance would be 100% for it, how can i make it a little smaller?
im not exactly sure
but you could add a None or some placeholder entry at the end
and give it highest probability
you can use weights with random.choice to control the probability
yeah i am in the gained
yeah so check if the item chosen is this
and what if its not? Then i tell them they gained None
cus i already have something for no items
ig
thats what most bots do iirc
or maybe smth like You couldn't find anything
add it to your messages and give it a high weight
but i am?
"messages": [
"You found yourself walking on top of needles, you fell to the floor and woke up years later"]``` b asically for when u dont find anything, i sort of want to make the chance smaller cus theres a 3 in 1 chance u get the item, and if its lets say a rare item but theres just 1 u get it 100% No matter what
oh do you mean like there is a place with only 1 item?
or what?
yeah, if its just 1 rare item its still got 100% chance to get it i want to lower that chance
you could add noodles at all such things? π€
wdym
Why is callback() not working?
That's nothing specific nor helpful for anyone
Class Setup(ui.Modal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_item(ui.InputText(
style=discord.InputTextStyle.long,
label="Label 1",
placeholder="placeholder 1",
required=True
))
self.add_item(ui.InputText(
style=discord.InputTextStyle.long,
label="label 2",
placeholder="placeholder 2",
required=True
))
async def callback(interaction: Interaction): ...
async def on_error(interaction: Interaction): ...
Its not even calling the callback function
I tried with and without self doesnt work
You're missing self
where is the self?
And you're not even telling what the error exactly is
(self, interaction)
Console errors?
So i removed self but still doesnt work
What's the callback
Nope no errors
do you also respond to the modal?
You're not providing relevant code at all
you need a line with interaction.response.send_message() without it, its not gonna work
Show the actual code
bad indents
Isn't it discord
class Setup(ui.Modal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_item(ui.InputText(
style=discord.InputTextStyle.long,
label="Project URL",
placeholder="Local database - Create a database on Supabase and use its URL. Make sure the database is empty.",
required=True
))
self.add_item(ui.InputText(
style=discord.InputTextStyle.long,
label="API Key",
placeholder="Local database - Create a database on Supabase and use its key. Make sure the database is empty.",
required=True
))
async def callback(interaction: discord.Interaction):
print("ok")
children = self.children
await Essential.hook_local_database(url=children[0].value, key=children[1].value)
embed = discord.Embed(
title="Setup Successful",
description="Your bot has been successfully set up.",
color=discord.Color.from_rgb(204, 0, 0))
embed.set_author(
name=f"Requested by {interaction.user.name}",
icon_url=interaction.user.avatar
)
await interaction.response.send_message(embed=embed)
async def on_error(interaction: discord.Interaction):
print("ok")
exc_type, exc_value = sys.exc_info()
embed = discord.Embed(
title=exc_type.__name__,
description=str(exc_value),
color=discord.Color.from_rgb(204, 0, 0))
embed.set_author(
name=f"Requested by {interaction.user.name}",
icon_url=interaction.user.avatar
)
await interaction.response.send_message(embed=embed)
Yea
unindent callback and on_error by one level
They're in the init
Oh bruh
also they should both have self as first parameter
Yea i put it ty :D
Excuse me, but causes an error only message.author.roles, which simultaneously accesses the User and Member class. The User class doesn't have a roles attribute so it throws an error, Member has this so the code works. I don't know how to fix it
Do you have conflicting libraries? Because that code works fine
Just add this to the top
if not message.guild:
return ```
Oh you said it's not in a dm, my bad
But you should still have that to catch dms
You can do member = guild.get_member(message.author.id)
Unfortunately still an error
Code:
@client.event
async def on_message(message):
if not message.guild is None and discord.utils.get(message.guild.roles, id=1131159247879680021) in \
message.guild.get_member(message.author.id).roles and not "text" in message.content.lower():
await message.delete()
await message.channel.send("Wrong form.", delete_after=10.0)```
Error:
```py
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 399, in _run_event
await coro(*args, **kwargs)
File "C:\Users\User\Desktop\Projects\server\bot.py", line 46, in on_message
message.guild.get_member(message.author.id).roles and not "text" in message.content.lower():
AttributeError: 'NoneType' object has no attribute 'roles'```
The error is still displayed but code works too
I tried everything and the error still comes up... I'm sad
"NoneType"
can you show your intents?
intent = discord.Intents.all()
intent.message_content = True
client = commands.Bot(command_prefix = '!', intents = intent)```
why do you have also message_content intents?
you can remove this line intent.message_content = True @candid coral
I removed it. Everything works, thank you a lot! β€οΈ
I wrote this at the very beginning of bot development, so I didn't think about it
The logic should also be
if ... is not None
You have
if not ... is None
I think this might evaluate like this
(not ...) == None
This line was redundant, but didn't fix the problem
You are right, but this didn't fix the problem
Even with this code, the bot doesn't see other commands

