#discord-bots
1 messages ยท Page 158 of 1
using .format() is bad in sql like that
No it's not.
String Formatting Mini-Language
The String Formatting Language in Python is a powerful way to tailor the display of strings and other data structures. This string formatting mini language works for f-strings and .format().
Take a look at some of these examples!
>>> my_num = 2134234523
>>> print(f"{my_num:,}")
2,134,234,523
>>> my_smaller_num = -30.0532234
>>> print(f"{my_smaller_num:=09.2f}")
-00030.05
>>> my_str = "Center me!"
>>> print(f"{my_str:-^20}")
-----Center me!-----
>>> repr_str = "Spam \t Ham"
>>> print(f"{repr_str!r}")
'Spam \t Ham'
Full Specification & Resources
String Formatting Mini Language Specification
pyformat.info
it goes directly against sql sanitization of asyncpg (which this looks like)
this doesnt work in sql forget it
just use placeholder it saves ur time, ur sanity and also ur life but not my spelling
lol old but gold
L that removed my image sad
LOL who remove the embed
i did on accident
kekw
btw you didn't pass self to your function here
can anyone say me if im doing something wrong
when i run the cmd it just says "bot is thinking"
using pycord*
!sql-fstrings you shouldn't. that's what the python developers suggest and im quite sure they're more experienced with their own products
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
โข Python sqlite3 docs - How to use placeholders to bind values in SQL queries
โข PEP-249 - A specification of how database libraries in Python should work
does the embed get send in your channel?
do you get any errors in your console?
How can I make a json file as a database to make it save a channel id with the guild id of channel and set a name for the channel id?
That's possible?
I used json as a database for my level system that's why
!d discord.InteractionResponse.send_message - the method doesn't return the message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
As long as it's not too big, then probably
Hmm
how to disable a button if clicked?
W
!d discord.ui.Button.disabled
property disabled```
Whether the button is disabled or not.
Where else
Whatever
that's not how you make buttons
See what happens
no one worked
bro that's just a callback
where do you think a callback is called
yeah this seems right
any help about disabling buttons ?
you still have to edit the message with the view the buttons are in
ths
but it shows an 'interaction failed' error
Show the actual error from the terminal
no error
defer
^
@slate swan
i didn't understand , sorry my english is bad
@slate swan after that u cant do responses u have to do followups
Edit the message with the edited view the button is int
the disabling is inside a callback , how can i edit the message's view ?
or , how can i definie a new view
Edit using the callback's interaction
ok
can i get a code ? ๐ i'm beginner sorry
No
bruh ok
can i delete a message which is sent by response ?
yes
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
use this and delete
ok
error:
main.py:13: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension('cogs.crash')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main.py:14: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension('cogs.mines')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
code: https://paste.pythondiscord.com/ajibecohav
?
await it like
await bot.load_extension('cogs.mines')
like dat
async def onegai(ctx: commands.Context, channel_id):
await ctx.respond("Please pound me more with you ")
channel_id = int(channel_id)
voice_channel = bot.get_channel(channel_id)
vc = voice_channel
await vc.connect()
while ctx.voice_client.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3")):
while ctx.voice_client.is_playing():
await asyncio.sleep(.1)
await ctx.voice_client.disconnect()```
bot not getting disconnected after the sound file has been finished playing, no error nothing language- pycord
no
can you guys find the error please im not able to fix it ;-;
yo im trying to read the message history of a thread after detecting it getting deleted, but i get this error:
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel
@bot.event
async def on_thread_delete(thread):
if thread.category_id == 983745432192688138:
messages = await thread.history(limit=200).flatten()
for message in messages:
print(message)
# messages is now a list of Message...
is it something wrong with my code?
because i just get errors from this code
You can't get the history of a deleted channel
Detect what
im trying to log all messages in a specific threads under a specific category
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if itโs a private message.
alright
Help!
hm
How do I make my bot think?
Like some bots have the thinking... thing on the slash command.
defer
While they are loading something long.
yes its called defer
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
thinking=True u have to do
ty didnt know it off the top of my head
channeled inner yoda

I still can't figure it out.
await interaction.response.defer(thinking=True)
Ooh.
TypeError: InteractionResponse.defer() got an unexpected keyword argument 'thinking'
@shrewd fjord
which library you are using?
disnake
How do I make a specific hybrid commands that are only available for specific servers?
I used to do this:
@bot.command()
async def test(ctx):
allowed_guild = [123, 321]
if ctx.guild.id in allowed_guild:
async with ctx.typing():
await ctx.reply("Pass")
else:
return
but how do i do it with hybrid commands? maybe if the guild id is not in the list it would just not respond or just not appear in the slash command list for the guild
Hi guys
I am writing a Python code in order to scramble the data but it returns a syntax error because of site name
This site is https://app.folk.app/shared/French-VC's-mD2puZZ9RyakVW7ATq6VaFaFme7Cjjf9
folk is contact management designed for teams and individuals. Organize, collaborate, and activate your network
Can someone suggest me a solution how to scramble data from this site
https://app.folk.app/shared/French-VC's-mD2puZZ9RyakVW7ATq6VaFaFme7Cjjf9
folk is contact management designed for teams and individuals. Organize, collaborate, and activate your network
Is it possible embed a youtube video inside of a discord embed?
So instead of that I want the entire video to be playable.
i think it should be in a description tho wait lemme try it out
๐ค
ah it doesnt work tho
no.
u cant have a embed in a embed
Yeah i tried inserting everywhere in the embed
lol

ye xd
this is my code, i want to make the slash command paramater have a description on discord ```py
async def a(interaction: discord.Interaction, string: str):
@discord.app_commands.describe
its possible, but not with just the raw yt link
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
Can you send them as message for once
payloud?
payload it is, but who cares about var names
get_channel(channelid), not get_channel(id=channelid)
you dont need id= for bot.get_channel, just pass the int
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
Hello everyone. I'm quite new. Can i ask question about using BeautifulSoup?
Bs4 comes under website stuff, try asking in #web-development
Okay, thank you ๐
How do I output an apps_command error?
Huh
I'm using @app_commands.checks.has_permissions(administrator=True), but when a regular person without those permissions uses it, the error is sent to console and not to the user
!d discord.app_commands.Command.error
@error(coro)```
A decorator that registers a coroutine as a local error handler.
The local error handler is called whenever an exception is raised in the body of the command or during handling of the command. The error handler must take 2 parameters, the interaction and the error.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
Hey guys, i heard that discord-components is gonna get deleted, is that real?
What is that
Discord py have own buttons etc
update your version
Idk about that, but discord.py have a good enough UI support
is a library that has been around since discord py v2
Before discord.py add buttons and menu's
cul
An unofficial third-party library of discord.py for discord components. - GitHub - kiki7000/discord.py-components: An unofficial third-party library of discord.py for discord components.
So youre telling me i could use discord.py for ui?
Discord components are cool, but discord.py will support it on version 2.0. It is hard to wait, so we made a third-party library for using components such as buttons or selects!
Source: discord-components github.
Yeah i didnt use discord.py for months
Welcome back then
discord.py had buttons soon after when discord announced the feature, you just didnt know how to install it
CODE:
class create_account(discord.ui.Modal, title="ACCOUNT SETUP!"):
age = discord.ui.TextInput(label='Age:', style=discord.TextStyle.short, min_length=2, max_length=32, required=True)
region = discord.ui.TextInput(label='Region:', style=discord.TextStyle.short, min_length=3, max_length=56, required=True)
ready = Button(label="Account ready", style=discord.ButtonStyle.green)
remove = Button(label="Remove account", style=discord.ButtonStyle.red)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.edit_message(view=None, content=f"Succesfully created account!{self.age}{self.region}")
view = View(timeout=None)
view.add_item()
...
async def setup_callback(interaction: discord.Interaction):
await interaction.response.send_modal(create_account())
...
QUESTION:
How can i make a modal but without the class ?
Discord buttons were added a year ago!? ๐ฅน
Why are there buttons inside your modal subclass
dont mind the buttons its just the "age" "region" and " on_submit thing"
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
keyboard goes brrrrrrrr
modal = discord.ui.Modal(title="your title")
``` and then add placeholders using add_item
!d discord.ui.Modal.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
hm ok ill try thanks ๐
sarth ๐

sarth who\
async def custom_cooldown(ctx):
time = await self.db.fetchval("SELECT time FROM users WHERE user_id = $1", ctx.author.id)
if time == 0:
print("one")
return commands.Cooldown(1, 200)
elif time == 1:
print("two")
return commands.Cooldown(1, 120)
@commands.command()
@commands.dynamic_cooldown(custom_cooldown, commands.BucketType.user)
async def test(self, ctx):
await ctx.send("ok")
the bot is not responding, there are no errors, what could be the problem?
totally a nobody
ikr
good boy
your bot doesn't have permissions to have slash commands, probably because you didn't enable the application.commands scope in the dev portal
CODE:
class create_account(discord.ui.Modal, title="ACCOUNT SETUP!"):
age = discord.ui.TextInput(label='Age:', style=discord.TextStyle.short, min_length=2, max_length=32, required=True)
region = discord.ui.TextInput(label='Region:', style=discord.TextStyle.short, min_length=3, max_length=56, required=True)
ready = Button(label="Account ready", style=discord.ButtonStyle.green)
remove = Button(label="Remove account", style=discord.ButtonStyle.red)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.edit_message(view=None, content=f"Succesfully created account!{self.age}{self.region}")
view = View(timeout=None)
view.add_item()
...
async def setup_callback(interaction: discord.Interaction):
await interaction.response.send_modal(create_account())
...```
**QUESTION:**
How can i make a modal but without the class ?
modals don't need views
i tried a lit but nothing works
no no dont mind that
just the "age" "region" and on_submit
well, what you're doing is the proper way to create a modal...
the view thing is just something that i added
ok but i dont want it inside the class cuz idk how i can do other things with it
wdym?
so the Modal thing but inside the command and not the class
help pls
from discord.ext import commands
Well I have a question
I used to be good on JavaScript and now I started learning Python too and even learned how to make discord bot on python
But I have a question would it be better to make a bot on JavaScript?
Because mostly when I search on YouTube for features I want to add to my bot mostly I see discord.js videos
i see no reason to use javascript unless you're significantly better at javascript than python
Depends on what you're comfortable with
I am comfortable with both of them actually
guys ? please just answer this very simple question
I am actually comfortable with both but I want to know which would be better to use @slate swan @naive briar
how can i make a modal ( the thing that can be used to make a survey or smth ) but WITHOUT class ????
why... no, it's ok as it is. Any other way isn't really pythonic to say the least
bro i need it WITHOUT class to do other things with it that DOES NOT work with the class
What are you trying to do?
k so
unbiased opinion, discord.py
reasons:
- simple application commands structure and prefix command helpers
- Views support!!!! javascript doesn't have anything like that
- Utility libraries like jishaku, discord.js doesn't has a proper one like that
Cool
So basically discord.py can do anything which discord.js can do but even more?
Because like when I searched for a minigames bots etc with python couldn't find any
How can I get/fetch a guild in a cog with the Bot? It always returns None
async def setup(bot):
server = bot.get_guild(int(guildID))
print(server)
await bot.add_cog(RaffleMonitor(bot))
Mostly was js
ironically there's a tictactoe bot in discord.py's example folder
You need to wait until the bot is ready to use get methods
But like some other really good games I mean
dont mind the things i scratched so this makes a modal wow very nice but now when i want to get the "age" thing in the command where the modal gets printed it wont let me get the "age" is there a way to get it or ?
cogs are loaded before populating cache
Something like Akinator etc
fetch_guild gives me some weird error.
attributeError: '_MissingSentinel' object has no attribute 'is_set'
Just self.age
self.age
cogs are also loaded before connection to the gateway
no guys you dont understand
me and some friends were working on a bot and added akinator as a feature in it, in python
Oh really
So I need to use .wait_until_ready(), correct?
there's a cool python Library for that as well
the COMMAND thing not the CLASS like this
yeah, but probably not in setup
this is the COMMAND
Well can we talk in dms since you seem good in discord.py
In the init ?
this the CLASS
its not about the language maybe people just didn't care about making those with python
Because I am working on a bot too actually
i haven't touched discord.py in 1.5yrs lol but yea sure
What are you trying to do
probably in cog_load, so that you can call wait_until_ready
How r you working on that then
bro you serious i am trying to make a MODAL but NOT in the CLASS but in the COMMAND
Look at the example
I use load_extension, makes that any difference?
im not, lol
if you're talking about wyvern its totally different from dpy
its just written in python
Oh you are using wyvern to make your discord bot?
nope, cog_load is a method that you override in your cog
i might do that in future but currently im just making it to learn about discord api
Ok, thanks... I'll take a look further in the docs for it :)
I see
But what is the best to use though discord.py or nextcord etc
Wait until they say hikari
do you understand what i mean or do you want me to try to be more clear ?
discord.py has most support and nice codebase
disnake is nice too
hikari is the best choice if you don't wanna stay mainstream
my preference order:
hikari, disnake, dpy, nextcord, pycord, hata, pincer, naff, other shitty forks
So do it ๐คท
lmao
What is hikari and disnake never heard about them lmao
like do you understand it ?
hikari is a discord api Library written from scratch with a very low api
What are you trying to do is my question
it will seem like djs at some point due to its low level implementations
ok so a modal you know what that is right ?
disnake is a maintained discord.py fork
I used to play around with it, so probably
But if I want to make a really professional bot with all features like games / moderation / design / music / level, credit system etc what would you suggest to use ? @slate swan
ok well you know it is usually in a class
Alright good I am already using that
I already made 350+ lines for my bot till now
Level system / warn system / welcome message (on image) / ban/kick/mute / and some other commands
That's what I have for now
my clients.py is longer ๐
I have poll system too
And?
Planning to add ticket/giveaway and some other
But really ticket and giveaway seems hard lol
ok so i want to make it WITHOUT the class like not inside of a class but immediately inserted inside the @bot.command thing
hmm, im getting an error saying Client has not been properly initialised. Please use the login method or async context manager. The docs don't give me a clear instruction about what to do now. How can I fix this
I've been searching much and I see people do it at 1 hour long video etc
For ticket
Or 3 parts video
Feels hard to learn
It depends on how well you want it to function really.
Like
modal = ui.Modal()
modal.add_item(ui.TextInput(...))
await interaction.response.send_modal(modal)
?
Giveaway or ticket?
This is just like subclassing but less readable
I want ticket with buttons for open / close ticket and close have reason as dm etc
YES FINALLY THANKU VERY MUCH
Can you help me to do mine as well?
It's private but I will make it public
So I want to make it as a public bot ticket system
Yes
Oh shoot
Give me the file and I will tell you if the end result is good ๐
Nah jk I want to learn
So you learned from a video or document?
Hmmm
I wouldn't rely on YouTube videos for bot tutorials to be honest
Yeah I see
Why
I mostly made everything from learning by YouTube
Because I can't find any good documents that are easy to learn from
Most videos are out-dated and/or skip over important details in my opinion
What's fun about this is that you are literally learning nothing xD
Yeah they mostly out dated
So you suggest me to use docs?
thats what a normal user would do
usually I check docs > search StackOverflow > ask/search on Discord in that order if there's something I don't know
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
What is StackOverFlow
Stackoverflow 
this takes to disnake doxs lmfao, oh they fixed it
ill be honest ticket systems are wack now
just use private Threads
that does all that a ticket system would do
forum channels 
yeah modmail is a different case
Split the problem into smaller steps. Say you want to have a button that opens a new ticket, start by asking how do you create a button? Then think about how you can create your text channel/thread/whatever type of ticket system you want. Etc
Hmm
I don't know that views thing actually
Well I know a bit actually
Like how to make a button and after clicking it sends a message
That's what I know how to do
my code
But idk how to make it create new channel etc
!d discord.TextInput.value
The default value of the text input.
Yes
You need to get the value from it
how
Uh it's alright
Actually I am kinda busy now maybe later
I'll also try to know more about docs and StackOverFlow
!d discord.TextInput.value
The default value of the text input.
.value
where
Does your bot have the application.commands scope enabled?
ah ok ok i did it and it works but a big but in the database it now just smacks an empty thing instead of the values you gave in the MODAL
When I try to use:
await self.bot.wait_until_ready()
it gives me the following error: RuntimeError: Client has not been properly initialised. Please use the login method or asynchronous context manager before calling this method
But I'm kinda stuck about what to do cause? Either way I'm using bot.login wrong or im stupid
probably both
Why are you using the login method anyway
i think it has something to do with the on_submit thing
Because the error says so
do you know how i can input the on_submit ?
You didn't give it a callback
it needs a callback ?
Also you should subclass the modal
Yes, so it can respond to the interaction
wait wait to much, what do i do ?
how
What else should I do than?
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member=None, unit = None, reason=None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot mute yourself")
return
if reason == None:
reason = "Not specified!"
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
embed = discord.Embed(description=f"**Muted** {member.mention}\n๐ ใปUser {member.mention} is muted!\nโ ใปReason of mute is {reason}\n:boom: ใปTime of mute is {unit} seconds\n๐ง ใปMuted by {ctx.author.mention}")
embed.set_footer(text="ยฉ 2022 Pirates Developments. All rights reserved")
await member.add_roles(mutedRole, reason=reason)
await ctx.send(embed=embed)
if unit == None:
unit = "3600"
await asyncio.sleep(unit)
await member.remove_roles(mutedRole)```
any who can help me idk why my mute command dont work
what exactly do you need help with?
unit is a string, you should be passing an int or float
I'm trying to either get or fetch a channel in a cog, now I'm using self.bot.wait_until_ready() on the @tasks.before_loop but it gives me this RuntimeError: Client has not been properly initialised. Please use the login method or asynchronous context manager before calling this method
!paste send you full code please
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
start the task after the bot is running @high sun
I'm trying with the before_loop
yep i try with timemute and dont work
wot?
https://paste.pythondiscord.com/vedazofave, @fading marlin
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member=None, testing=None, reason=None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot mute yourself")
return
if reason == None:
reason = "Not specified!"
if testing == None:
testing = 3600
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
embed = discord.Embed(description=f"**Muted** {member.mention}\n๐ ใปUser {member.mention} is muted!\nโ ใปReason of mute is {reason}\n:boom: ใปTime of mute is {testing} seconds\n๐ง ใปMuted by {ctx.author.mention}")
embed.set_footer(text="ยฉ 2022 Pirates Developments. All rights reserved")
await member.add_roles(mutedRole, reason=reason)
await ctx.send(embed=embed)
await asyncio.sleep(testing)
await member.remove_roles(mutedRole, reason=reason)```
i tried this but dont work
you have to type hint testing with int too, otherwise its still a string
how are you starting your bot?
async def on_ready():
await bot.load_extension(name='cogs.repeater')
print("Bot is online!")
client.run(os.getenv("BOT_TOKEN"))
thats in main.py
use setup_hook instead
instead of?
on_ready
with a wait_until_ready in the setup_hook?
cause i'm using a get_channel inside the on_ready aswell
how do i do the interaction ? i cant figure it out
no, just replace the name of the function
that gives me AttributeError: 'NoneType' object has no attribute 'history' cause i'm trying to get the last message in a specific channel
in the on_ready
@naive briar i think i need to do like the submit button in the modal i nee that to do something else but idk how
do you still have the wait_until_ready on your before loop hook?
correct
and you're loading your extensions in setup_hook?
correct
anyone knows how the on_submit button works in a modal ?
what happens if you place the wait_until_ready inside the actual task instead?
cuz this doesnt work
it's missing an interaction parameter
oo ok
still gives me this:
RuntimeError: Client has not been properly initialised. Please use the login method or asynchronous context manager before calling this method
still pretty dark
you have to override Modal's on_submit with that
how ?
class A:
def method(self):
print("A")
def other_method():
print("B")
>>> a = A()
>>> a.method()
A
>>> a.method = other_method
>>> a.method()
B
that's what you have to do
is this for me ?
yes
do i need to use bot.login, Lee?
no, bot.run should be fine. It calls login anyway
th, it's so weird
it's an example of how method overriding works
ah ok
without the wait_until_ready it gives just a NoneType
well yeah because you're trying to find something that's not in the cache
A is the modal, method is on_submit, other_method is your on_submit
aah ok
no, that will error because you're not connected to the gateway. You should be using get and wait_until_ready
yeah that gives me AttributeError: 'coroutine' object has no attribute 'fetch_channel'\
how can i get a role by id using utils?
!d discord.Guild.get_role - you don't need to use utils
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
thx
so something like this
kinda, you don't have to call your modal a, nor call on_submit
ah ok
you're calling 2 coroutines and only awaiting once
ah i fixed that and that gives me AttributeError: '_MissingSentinel' object has no attribute 'is_set'
because you're not connected
so like this ?
Whats async before def?
asynchronous function
no, you don't override Modal's on_submit, you override the instance's on_submit. You shouldn't call on_submit either
could you send your updated code? with wait_until_ready and get
I never understood that...
huh ?
u can google a video to learn async python
async marks a function as being a coroutine. Coroutines have to be awaited to get their value, otherwise you'll either get an error or an awaitable
Can u give me an example, maybe?
you previously had an instance of Modal called a, a's on_submit should've been overridden, not Modal (fwiw it's a lot simpler if you just subclass)
ok so what do i change with what ? in this
https://paste.pythondiscord.com/ocujovehak
Above === is my main, other is my cog
but with wait_until_ready it doesnt even print Bot is online!
async def foo(): print("'a'")
def bar(): print("'b'")
>>> foo() # coroutine, is also an awaitable
<coroutine object foo at 0x0>
>>> x = foo()
>>> await x
'a'
>>> await foo()
'a'
>>> bar()
'b'
>>> x = bar # basically the same as doing 'foo()'
>>> x() # basically the same as doing 'await x' where x is an awaitable/coroutine
'b'
this is pretty much the basics of asyncio, I'd suggest reading up on it
don't call on_submit
where ? everywhere
the both times that you're doing it
the a.on
don't wait_until_ready in setup_hook, nor get_channel. Move the wait_until_ready inside a task before hook
remove a.on_ready(), yeah
ok
ValueError: Modal must have a title```
send your entire code please
you're sending the modal before adding a callback
here you sent the modal
await interaction.response.send_modal(create_account)
and 11 lines below you're adding a callback to a completely different modal
ah i have to put on_submit above it
?
sure
or what should i do ?
Hi
try what you said, if it doesn't work, send the new code and lmk
okidoki
RuntimeError: Client has not been properly initialised. Please use the login method or asynchronous context manager before calling this method
Is there a way to make the inputs only have 2 characters
k so here is the code and the error error ValueError: Modal must have a title but now the modal does not get sent which is a good thing i think
Wdym with this Move the wait_until_ready inside a task before hook
before you use get_channel, call wait_until_ready
ye, I have that rn
you're almost there. Instead of overriding a's on_submit, override create_account's on_submit, and delete the modal that points to a
Missing Permissions
your bot doesn't have the permissions to do what you want it to do
ugh idk anymore
If I add await client.login, it says this:
client_session: <aiohttp.client.ClientSession object at 0x000001EE6163C3A0>```
example https://github.com/Rapptz/discord.py/blob/master/examples/background_task_asyncio.py and docs https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html say that this should kinda work, unless we're missing something pretty obvious
you don't have to call login, it gets called automatically with bot.run
^
YESS it works but the modal doesnt close but it works
ok, thanks Lee. Appreciate ur time
you're very welcome
my new code
Is it possible to make a slash command parameter have a maximum character length
you can check in the function of the command
you still have to respond to the interaction
!d discord.app_commands.Range
class discord.app_commands.Range```
A type annotation that can be applied to a parameter to require a numeric or string type to fit within the range provided.
During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated "(in Python v3.11)") so type checkers understand the intent of the code.
Some example ranges...
where ?
in your callback (on_submit)
what do i have to put there ?
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").
New in version 2.0.
you're very welcome
๐
hey guys, can someone please give me a good website that will teach me how to do ui multiple choice using only discord.py?
a website?
Just watch one of those bad yt tutorials lol
Or read the docs like a masterdev
cant find one tho
Why dont you start out by looking at the github examples
try to understand them
then modify them
at least that worked for me
i tried to, but i only saw people that use pycord
i have to work with only discord.py
!d discord.ui.Modal and https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
but pycord sucks anyways
Led u beast
*Lee
๐ hehe
thx
install dpy
Hey! i have a question, whats an intent?
pip install discord.py
on cmd
hi i need help
Hey @indigo valley!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
they're "settings" (if you will), that tell Discord what type of data it should allow your bot to see
Okay, is it relevant for me?
Like, i need to know how to use it or its smth normal
generally speaking no, it's just something that gets sent whenever your bot connects to the gateway
import nextcord as discord
from nextcord.ext import commands
from nextcord.ext.commands import has_permissions, MissingPermissions, has_role
from nextcord import Interaction
from discord.utils import get
import asyncio
import Protocol # <- this is causing issues
import datetime
from datetime import datetime
import json
don't use bot and client either, stick to one
use commands.Bot
how can i add emojis in the create_text_channel function?
either unicode, shortname and copy-pasting the emojis dont work
Nothing, just realized i needed the =True
unicode should've worked
i'll try again
oh my lord, I used replace to replace a name (which is a template kinda name) but forgot to save it as a new variable
slashe comand no appeare https://pastebin.pl/view/d84f3ac2
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
ban_members
discord.Member (type hint)
hello, I wanted to send DM to someone with my bot. but I got error: @client.command()
AttributeError: 'Client' object has no attribute 'command'
@fading marlin can you help
https://pastebin.pl/view/d84f3ac2
slash no appear
no error
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
You are syncing them globally so it take up to an hour to see them. Also use either Client or Bot, not both.
ohhhhhh
you're not decorating your callback
that's been fixed, it should be pretty instant now
no, you don't have any events
@tree.command(...)
then how do i decorae it
How do I do that. I'm new to making bots so I don't know much
Also global, json, hard coded author id and duplicate code on elif. 
asking for bot token each time to start ahhhhhhh
await tree.sync(1043711872723070976)
TypeError: sync() takes 1 positional argument but 2 were given
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
it only takes kw arguments
await tree.sync(guid=discord.Object(1043711872723070976))
this is a test built on replit before i migrate to vscode
ok ty
'int' object has no attribute 'id'
?
err
full traceback please
You are giving like 5% of the the traceback
Traceback (most recent call last):
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 96, in on_ready
await tree.sync(guild=1043711872723070976)
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1059, in sync
commands = self._get_all_commands(guild=guild)
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 740, in _get_all_commands
commands = self._guild_commands[guild.id]
AttributeError: 'int' object has no attribute 'id'
lol
you're forgetting to surround the ID in a discord.Object
oh yeah
Traceback (most recent call last):
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 51, in balance
await open_account(str(author))
File "main.py", line 68, in open_account
users[author]['Wallet'] = 0
KeyError: '928109349140824125'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'bal' raised an exception: KeyError: '928109349140824125'
As much as we love to help solving issues, I know this code is from an old youtube video please don't use it.
oh...
it was the only economy bot vide w/ json and python i could find
and it had good review
It has a lot of issues and using a database is more ethical.
try learning the basics of python before jumping into making a discord bot
i did...
Yeah but i dont really wanna focus on sql or using mongo rn
Why not
ExtensionFailed: Extension 'cogs.admin' raised an error: ModuleNotFoundError: No module named 'discord_slash'
class Commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.admin_id = [985170190121730120, 826854630751076414]
@bot.slash_command(name="test")
async def _test(self):
embed = Embed(title="Embed Test")
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(Commands(bot))
?
Full traceback please.
How to make slash command in disocrd.py in cogs pls help
if this is pycord its @discord.slash_command
how to make this in discord.py
whats the full error
i dont know how to write slash, this is error
the class should subclass commands.Cog
ye so?
Well you aren't
class A: ...
class B(A): ...
B subclasses A
class Ping(Cog)
he was just giving example
ye so
so just second one but .Cog
you just have to subclass it
HOW
do the second one
but do .Cog not .cog
class Ping(Cog):
correct
love u brothers
your setup isn't right though
bot.add_cog is a bit wrong no?
remove commands.cog from the add_cog
are you using a debugger other than print()?
Debugging takes me hours ๐ข
eee
What do you refer?
this my code:
You are using asyncio.run and calling an async function but you don't run it in a context manager so this isn't utilized very good.
lmao the other day I was messing around with pagination, strings of 2k characters, and an echo command and for the life of me I couldn't figure out why I was getting a repeated value when in fact it what just the output + input ๐ญ
I spent at least 2 days scratching my head
Had something similar happen to me, apparently it took me 3 years to stumble across default mutables pit-fall
!e ```py
def foo(x, y: list[int] = []) -> None:
y.append(x)
print(y)
foo(1)
foo(10)
foo(12)
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [1]
002 | [1, 10]
003 | [1, 10, 12]
Classic one
Yea stuck on that one forever
Until toxickidz told me about it
Very early on during my concurrency journey race conditions was also another one
But I figured out those easily after a few tries
guess I got lucky, my linter warned me about that before I got used to it ๐ฌ
Which linter?
the worst of them all: whatever PyCharm uses
I cannot LSP install that to nvim I think
๐ , I got nvim on pyright and pyright alone
Typehinting is king
strict type hinting 
ftp = FTP()
ftp.connect(HOST, PORT)
ftp.login()
ftp.cwd('user/home/')
with open(save_file, 'wb') as f:
ftp.retrbinary('RETR ' + save_file, f.write)
ftp.quit()
I want to change the location of where the file is downloaded. Does any1 know how I can change the path. I was told to just open the py file where I want it to be saved but this will be a command and I want to change the download location path with each download depending on who its for
Hello, this isn't discord bots related.
Perhaps you can open up a post in #1035199133436354600 ?
@fading marlin, sorry for ping, u there?
hey
I need some help :(
shoot away
Look, i got a main.py and another file with a cog but its not ok...
There's no error, just not working.
you should use bot.load_extension and a setup function instead of importing it
okay, lemme see
pretty sure you HAVE to use setup function inside of the cog lol otherwise it will not work
async def setup_hook(self):
await self.load_extension("ping_cmd")
got this on main.py
and this on the cog one.
async def setup(bot):
await bot.add_cog(Ping(bot=bot))
you should pass the name of the module to load_extension
the filename (without the file extension)
setup is async...
no its not.
it wasn't pre 2.0, now it is. Plus add_cog is a coroutine, how do you expect it to be called?
So what's the error on my code
there are no errors
you've got a warning telling you that you don't have message content intents enabled
in the devs panel?
idk, at least in the code you don't
oh, ur talking of the intents = discord.Intents.default()??
Thanks!
you're welcome
Ok, i got at least no warning but now this is showing up: discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
can you show your updated code?
bot=bot? not saying thats it but ive never seen someone do that
i actually dont know what that does
you also have
i understand the class needs the bot thing to work
gotcha
why are you importing the ping on your main file? also rename your cog, you might be having some scoping issues
bot is a positional or keyword argument, you're just using it as a keyword argument. There's really no difference in using either in this case
isnt it necessary?
what is supposedly necessary?
just "bot" is necessary, you are just defining bot as "bot"
Nah, i just thought that would be necessary for the status thing
i mean kinda right, but you use it and define it in your init
Btw, still having the same problem: discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
send new code!
rename you cog class (probably use proper class naming convention), see if that fixes it
oh
I'm actually blind
setup_hook isn't decorated as an event, nor should you pass self as its parameters. You're not subclassing
Please don't joke about that here
Yes max_value
import discord
from discord.ext import commands
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on__ready(self):
print("Moderation.py is online")
@commands.command()
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, count: int):
await ctx.channel.purge(limit=count)
await ctx.send(f"{count} messages have been deleted")
@commands.command()
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, reason=None):
if reason is None:
reason = "No reason provided"
await ctx.guild.kick(member)
conf_embed = discord.Embed(title="Success", color=discord.Color.Random())
conf_embed.add_field(name="Kicked", value=f"{member.mention} has been kicked by {ctx.author.mention}", inline=False)
conf_embed.add_field(name="Reason", value=reason, inline=False)
await ctx.send(embed=conf_embed)
@commands.command()
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: discord.Member, reason=None):
if reason is None:
reason = "No reason provided"
await ctx.guild.ban(member)
conf_embed = discord.Embed(title="Success", color=discord.Color.Random())
conf_embed.add_field(name="Banned", value=f"{member.mention} has been banned by {ctx.author.mention}", inline=False)
conf_embed.add_field(name="Reason", value=reason, inline=False)
await ctx.send(embed=conf_embed)
@commands.command(name="Unban")
@commands.guild_only()
@commands.has_permissions(ban_members=True)
async def unban(self, ctx, userId):
try:
user_id = int(userId)
except ValueError:
return await ctx.guild.unban(user_id)
async def setup(client):
await client.add_cog(Moderation(client))
for some reason my code doesn't give embeds after ban or kick
any errors?
nope
well you've got an error handler that's eating them or you haven't enabled debug
!d discord.Colour.random - random is lower cased, not upper
classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a random hue.
Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
Problem "outdating is this wrong command? but that update that new command. but that's not kick , etc (but removed)
already remove codes , kick , etc only have 3 commands
problem no solution?
um?
wdym
How do I make a specific hybrid commands that are only available for specific servers?
I used to do this with bot.command():
@bot.command()
async def test(ctx):
allowed_guild = [123, 321]
if ctx.guild.id in allowed_guild:
async with ctx.typing():
await ctx.reply("Pass")
else:
return
but how do i do it with hybrid commands? maybe if the guild id is not in the list it would just not respond or just not appear in the slash command list for the guild. or is this not even possible
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
with these, do they have to be in a specific order or does it not matter?
@app_commands.checks.has_permissions(administrator=True)
@app_commands.guild_only()
Or can I only use 1?
with this the appcommands only can be invoke in guild
I know. I was just making sure that I could use both.
and there wasn't an order it needed to be in
and just a quick reminder, to @ someone using an id its: <@id>?
yes
Ty ty
ye
and for channels <#channel_id>
xd
and for slash command </:name:id>
y can mention slash commands
does it run the command or just post it in chat?
post it in ur chat and u can click send to invoke it
lmao
Atm I got a bunch of "Did you mean to use /command?"
I can replace /command (text form) with a link to the command >:D
How do I get the command ID? ๐ค
before you hit send you can right click the actual little popup above the text box
But I need to get it through my code
yeah then just copy it and paste it
Because I intend on selling this bot I am making lol
oh i see what you mean, im not sure
yes u can get
</name:id> btw i made a mistake
xd
My favorite part about making a new bot is when you finally make it, 1500 lines later, "Can you add this?"
like mother fucker -.-
๐
Alright it's probably shouldnt be 1500 lines..
But that's what refactoring is for ๐
explain, this is my command and update code and but it does not seem missing commands 3
This problem cannot be solved. Discord bot is useless. Do you know how to solve it?
times expel and invite and no command appears are 3
are your slash commands not appearing in the server?
yes
that already add ready script "hello" this does not appear /hello.
@upbeat otter hello?
are you busy lol?
there and nothing /bothost see not appearing
do not sync in on_ready, use setup_hook
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
@upbeat otter ohh
?
@upbeat otter how is explain example
Ah
Think there is on_ready change setup_hook
Correct?
Ok, check
or you can manually do that
async def setup_hook() -> None:
await client.tree.sync()
print(f"Synced Slash Commands")
client.setup_hook = setup_hook
welcome
no it's not good for performing other tasks except printing stuff
Hmm i see okay thx
setup_hook is triggered before any event in your bot is triggered, on_ready is triggered when your bot is fully loaded along with the cache and this may be triggered multiple times when you start your bot or at random times when your bot is running so it's not good to perform other tasks
๐ซ
no
how u talkin
How am I supposed to know, am ded
That certainly isn't discord.py
^
from discord import app_commands [for dpy]
๐
lmfao
well my brain is dying rn
YESSSSSSS]
imagine importing stuff
stuff
always remember to unimport stuff after using them
^
^^
import sys
sys.modules.pop("sys")
uwu
:3
SkillIssueException: no ๐ named "sys"
\๐
i can ๐
i can barely see the tail of the key xd
,
ayo i saw that
it was meant to be seen
seek me uwu ๐ณ
:3
yes
i didnt saw anything np ๐
see*
sea*
c*
gave up
๐ซ
.topic
const Discord = require('discord.js')
const client = new Discord.Client()
const db = require('quick.db')
const covid = require('novelcovid')
var prefix = "co!"
client.on('ready', () => console.log("thicc NUB is online like a proffesional NUB"))
client.on('message', async message => {
if (message.content.startsWith(${prefix}covid)) {
const covidStats = await covid.all()
return message.channel.send(new Discord.MessageEmbed()
.setTitle('covid19 stats')
.setColor("BLUE")
.addFields(
{ name: `Cases`, value: covidStats.cases.toLocaleString(), inline: true},
{ name: `Cases Today`, value: covidStats.todayCases.toLocaleString(), inline: true},
{ name: `Deaths`, value: covidStats.deaths.toLocaleString(), inline: true},
{ name: `Deaths today`, value:covidStats.deaths.toLocaleString(), inline: true},
{ name: `Recovered`, value: covidStats.recovered.toLocaleString(), inline: true},
{ name: `Recovered today`, value: covidStats.todayRecovered.toLocaleString(), inline: true},
{ name: `Infected right now`, value: covidStats.active.toLocaleString(), inline: true},
{ name: `Critical condition`, value: covidStats.critical.toLocaleString(), inline: true},
{ name: `Tested`, value: covidStats.tests.toLocaleString(), inline: true },
)
)
}
})
@client.event
async def on_member_update(before, after):
print(before.activities[0].name)```
why it is not loggin anything
you're missing presence intents most probably
nah
show nore code
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
this is only the code
enable intents.presences
intents=discord.Intents.all()
client = commands.Bot(command_prefix =[">", "."],intents=intents)
do you have multiple on_member_update s?
is it placed after bot.run()?
you'll get an error msg if its ratelimited
no error msg
!paste show full code
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
