#discord-bots
1 messages Β· Page 41 of 1
Whether guild presence related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache...
You can just try discord.Intents.all() for testing purposes
ok
so the activity worked
but it wasnt activity lol it was my
the status still says offline
Started this at 6pm yesterday, it's now 8am.
My code is now fully adapted for cogs and completely error free.
Thank you so much @sick birch @primal token.
I'm going to bed lol
Great! Have a great night
Youre welcome, Good night
i fixed it
dw its because i had mobile_status instead of raw_status
ok sorry for being annoying but last thing
is it possible to change .created_at and .joined_at to a timespam
like instead of
created 2 years ago
joined a month ago etc
please ping me if anyone replys because im coming of my pc now
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
@slate swan
like this? <t:1595028120:R>
the style parameter should be 'R'
how I've made that
not really sure how to put it how you want it tho
that's just the formatting
just use this function
How can I send a message to any user who reacts to my bot's message? I know how to check for the user being the same person that initiated the bot user == message.author, but how do i define the user as any person on the server?
are you looking to dm them or ping them in the same channel as the reaction?
DM
@client.event
async def on_reaction_add(reaction, user):
ChannelID = id
if reaction.message != ChannelID:
return
if user.reaction.emoji == ":thumbsup:":
await user.send('message')```
try that, I'm not well versed with discord.py, but I imagine that'd work based on how I've used reactions before
as an event sorry, my bad
Do you want this to happen after a command or just independantly? I'm guessing in a command as that's the more common use case, like:
- you invoke a command
- bot sends a message asking you to react
- DMs you after you react
Yea, the latter. The user initiates a command, the bot sends an embed, and then any user can react to get more information DM'd to them
In that case, you're looking for discord.Client.wait_for
!d discord.Client.wait_for here's the relevant documentation
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
How do I allow any user to react and get the information? Wouldn't user==message.author limit to just the initiator?
The only checks you need to have in that case are that the command invocation guild is the same as the reaction guild
Something like this? Where would I draw the user from, though
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
pass
else:
await user.message.send('message')
You don't need to check user
You have to check the message, that's about it
yes but don't i need the user information to DM them
reaction, user = await client.wait_for(...)
is how you get the user
please someone help me π
await ctx.send('>>> ``'+'\n'.join(list(map(lambda id: await self.client.fetch_user(id),db["mock"])))+'``')
Trying to use await in lambda which doesn't work but is there another way to do this?
I can't use asyncio.run since i'm mapping the values so I can't include self.client in parameters
nvm
Try get_user
I don't understand what you mean? π
Oh i mean complicated
Is there any function with return owner as user ? , I want i someone type !bug the bot dm me , even if i am not in guild
Members.send , but how can I get owner as members!
oh so you're switching to mongodb?
Hmmm switching to MySQL
Form mongodb
nice
But me mongo is easy
mongo is a pain π
!d discord.Guild.owner
property owner```
The member that owns the guild.
Hmmm I am talking about bot owner π
bot.application.owner
I'm not sure how it would work for team applications, so I usually just use a check function
but if it's just you, that'd work
Hey, with Modals, is it possible to send multiple modals? Like, after 1 is submitted, the bot sends a 2nd one? Sorta like a page system
Not everything I want on the modal fits on it π¦
Can someone show me how you can make a discord command that prints what you say?
@bot.command()
async def check(ctx, arg):
await ctx.send(arg)
this isnt sending why??
π€
should be working i think
idk why
check you other stuff
@bot.command()
async def check(ctx, arg):
await ctx.send("test",arg)
doesnt send
@limber bison
@bot.command()
async def check(ctx, arg:str):
await ctx.send(f"{arg}")
try this , btw your also ok , may be u mistaking somewhere else
did u import commands ?
oh u r on client
nvm
whats your client/bot instance ?
wym?
from discord.ext import commands
?
The code
what thing u change ?
How to put timestamp in embed field value?
If you mean that you want see your files then just click the file icon
thx
β
@realfight.error
async def additem_error(self,ctx , error):
await client.application.owner.send(f'{error}')
how can get the complete callback ???????????????/
its only sending the last error!
hikari, forks like disnake, pycord etc....
discord.py has buttons & slash commands support in the master version too
discord.py has buttons & slash commands support in the master version too
Are there any guides on how?
ty
here examples of views (buttons, dropdowns, e.t.c): https://github.com/Rapptz/discord.py/tree/master/examples/views
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
discord.py 2.0.0 came out on pypi 8 minutes ago
Yep
So uhh. When I do print(interaction.channel.type I get public_thread, but when I print the type, I get it as a class.. how can I just get public_thread?
print(interaction.channel.type)
print(type(interaction.channel.type))
if interaction.channel.type == 'public_thread':
```The if statement doesnt work is what I am trying to say.
Can someone help me please
Try interaction.channel.type == discord.ChannelType.public_thread
alright I believe that worked
now to figure out the rest lol
Can modals only be sent as a response to a slash command?
Or can I use regular commands like !newmodal?
Coz it'd be nice to have multiple modals sent in a row so I can get more than like 5 questions on my application form xD
Only to interactions
They include components interactions
Do you know how to send a 2nd modal after the first is submitted?
You canβt βchainβ modals so just send a button to get a new interaction
class LevelCog(commands.Cog, name='Leveling'):
'''rank, add, subtract'''
def __init__(self, bot):
self.bot = bot
#create leveling database
@commands.Cog.listener()
async def on_ready(self):
setattr(self,'db',await aiosqlite.connect('level.db'))
await asyncio.sleep(3)
async with self.db.cursor() as cursor:
await cursor.execute('CREATE TABLE IF NOT EXISTS levels (guild INTEGER, user INTEGER, level INTEGER, xp INTEGER, ssc INTEGER)')
what would i put instead of self.db.cursor() to make it work inside a cog?
everytime I click the button on my game it says "This interaction failed" (screenshot 1) and if I add defer here py await self.view.message.edit(view=self.view) await ctx.defer() this error happens (screenshot 2)
show code
more?
yeah
i just accidentally pressed enter;(
https://hastebin.com/uwirizepan.lua - callback of button
- you can only defer once because it is an interaction response
- you need to defer the new interaction to make the "interaction failed" go away
how come ur using ctx.defer?
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.
Your modal is empty
Why is it when I create a new thread using my bot, it doesnt automatically appear under the channel? I have to speak in it to make it appear..
that's how threads work, you join it only when you send a message in it
how would I make my bot DM a user after sending a certain message?
!d discord.abc.User.send -- DM a user
No documentation found for the requested symbol.
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
abc.User doesn't have send for some reason 
because there is a ClientUser π«
@pulsar abyss
wait it got messed up
?
would something like this work? (i literally have no idea what im doing and have never coded)
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('43725'):
await my_user.send("Beautiful message")```
no it won't
my_user is not defined
my_user should be the user you want to dm
i guess it's message.author for you
ofc
man i wasted so much time googling stuff and i could have just asked here this whole time π
it does lol
pretty sure abc is just the folder for abstract base classes e.g User lol
ye
so no need really to provide the folder either as the namespace has already been initiated
await cur.execute(f"INSERT INTO music_style VALUES({ctx.authour.id},'heavy metal')")
Will this work ?
Or not ?
1 - #databases
2 - no it won't
2 , why ?
How can I insert then ?
Nvm not why question
because your insert VALUES into music_style, but you dont give columns
It only have 3 columns
INSERT INTO table_name (column1, column2) VALUES (value_for_lumn1, value_for_column2)
that is how it works
And the f string thing ? CTX.author .id ?
Will work ?
no, it's author, not authour
can anybody help me? I'm trying to install chatterbot but it gives me an error when I run pip install -U chatterbot, here is the error.
ERROR: Could not build wheels for srsly, which is required to install pyproject.toml-based project```
Lol with author will it work author ?
You should show an example with place holders to prevent SQL injection
it will ig
prevent?
How u insert values ?
sqlites syntax is query, (values,)
F string ?
That is so
well, noid is right, not with F strings, with using place holders
?
What's that , how it work ?
I don't think this is related to the topic of this channel
what db are u using?
it is related to my discord bot
but the question itself is not
Now on mongodb, switching to mySQL
which channel should I got to then?
for mysql it's py query = "INSERT INTO something (col1, col2, col3) VALUES (%s, %s, %s)" cursor.execute(query, (value1, value2, value3))
so %s's will be replaced with value1, 2 and 3
if you do fstring, some user with name yes'; DROP TABLE users; could break your sql
Is it possible to set a thread to delete after an hour after it has been spoken in?
archive?
Sure. Whatever works. I just want it to remove itself after someone has spoken in it, but not right away, after an hour
I don't think it will be in VALUES section ,
!d discord.Thread.auto_archive_duration ig
The duration in minutes until the thread is automatically archived due to inactivity. Usually a value of 60, 1440, 4320 and 10080.
So what ever the input it will take it as value
Creating it ?
It you r creating bot host it on you pc to understand things
After complet u can host
Ohh
Sory
Is your setup function async ?
π€
Share you code
lemme show you, you do:
cursor.execute(f"INSERT INTO beautiful_table (guild_id, user_name, score, level) VALUES ({ctx.guild.id}, '{ctx.author.name}', score+10, level+1)")
``` and if a user has the above nick, this will hapen:
```sql
Executing query: INSERT INTO beautiful_table (guild_id, user_name, score, level) VALUES (8123059703147203, 'yes'); DROP TABLE beautiful_table;', score+10, level+1)
```SQL query is executing step by step, and when it sees `;` it counts everything after it as a new query, so first some data will be inserted and then your table will be deleted, and then code `', score+10, level+1)` will not work
that's why you use place holders
to prevent this shit from happening
any error?
what is code?
of your cog
!paste
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.
So, Iβm about to start this new job and they use discord and M336 as a bot to receive all of there jobs that they need to input for the day or the next day. They are always coming in and I know there is a better way to automate a bot of some sort to take the info from discord and input it into the website that they use to import all the data. I know it wonβt be perfect bc sometimes you have to use brain power to decide on situations or if someone doesnβt import the job the correct way. I was just hoping someone could get me started on the right track and I would definitely pay you well. Let me know if this is in your wheelhouse and if so, hit me up!
Ohh k , so I need to be more carefully when I deal with user inputs and Nick and username think
M336 π
aahh.
Im using the command in a thread.. What am I doing wrong? await interaction.thread(auto_archive_duration=60)?
should it be await interaction.channel.thread(auto_archive_duration=60)?
Else I can user this method
!rule 9
oh snap, my bad...is there a channel in here that u can? I've been apart of this server for years now
this is a rule for whole server
can someone help me in general then?
When I try and change to interaction.channel i get TypeError: 'Thread' object is not callable π€
interaction.channel returns Thread object, to change auto_archive_duration you need to do thread.edit(auto_archive_duration=60), so await interaction.channel.edit(auto_archive_duration=60)
Ctrl + Z?
is that a no?
omg. i was so close lol
@silk fulcrum sirrrr
await conn.execute(
table.insert(),
{"id":1, "value":"v1"}
)
What about this method ?
Same as Mongodb !!!
It's , on site
almost like sql is in the name π€―
SQLAlchemy support
lmao
bro on 9 percent
Well the whole name shows that its SQL based lol
well he didnt get that
either way it would depend on drivers lol
What ?
await conn.execute(
table.insert(),
{"id":1, "value":"v1"}
)
This will work with SQLAlchemy right ?
what commands dont work?
Just learned CPython isnt JIT compiled only other implementations are, i hope it gets one
indentation just completely broke
looks like it were nested lol
bruh command inside command inside command
fix indentation and everything be good
well then do it on pc
Very sus
At last people can stop using the GitHub link to install discord.py v2.0
Roulette game git code ?
Guys what's use of discord.py[speed]?
what is that π³
I saw on discord.py official server
showmepls
am I your embed visualizer or what
Love day?
well, it's a package with speed up
Whats different between discord.py and this?
more speed ig 
Good guess ig
It just installs additional packages with faster implementation of some stuff (they are just written in C). I can guess they are using uvloop instead of asyncio loop and probably some aiohttp speedups like async dns, ujson and other stuff
Oh ty
that would actually be helpful like if someone makes some good embed combos saves a lot of braincells for other PPL some gist like how to make good embeds 
Yes π₯°
value is required if u are doing embed.add_field
you can use \u200b which is a zero width space
"\u200b"
Why does my on_guild_join not always does what it needs to do and send the message where it's supposed to send
async def register(ctx):
con = sqlite3.connect('userinfo.db')
cur = con.cursor()
cur.execute("""INSERT INTO userinfo (userid, balance)
VALUES(ctx.message.author.id, 0)
""")```
sqlite3 table has already created, but why my code no work?
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connection.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
prefix = await self.cursor.fetchone()
await self.connection.commit()
return prefix or '>'
Guys i have this function to get prefix
I want that when someone mention my bot it sends the bot prefix
How to do that?
Yep
can someone help here?
Anyone help pls
async def register(ctx):
con = sqlite3.connect('userinfo.db')
cur = con.cursor()
cur.execute(f"INSERT INTO userinfo (userid,balance) VALUES({ctx.message.user.id},0)")
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
ive updated the code but it still no work
how to fix?
Do u get an error?
no error on console
Does the message send?
ok
no
Union[User, Member]: Returns the author associated with this contextβs command. Shorthand for Message.author
async def register(ctx):
con = sqlite3.connect('userinfo.db')
cur = con.cursor()
cur.execute(f"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id}, 0)")
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
updated the code, but still not working :/
?
no it doesn't send
Does cur.execute return anything or is it void
intents enabled? u have on_message anywhere?
Which library is this?
!d sqlite3.connect
sqlite3.connect(database, timeout=5.0, detect_types=0, isolation_level='DEFERRED', check_same_thread=True, factory=sqlite3.Connection, cached_statements=128, uri=False)```
Open a connection to an SQLite database.
and get urself an error handler
so how do i fix it?
@slate swan
yes i have but i got this code
await bot.process_commands(message)
so it isnt the problem
You have to do con.commit() to save changes
alr
hello
Also do u have error handler in ur code?
no
Hey
yes?
Hey as in greeting
i'm a starter
async def register(ctx):
con = sqlite3.connect('userinfo.db')
cur = con.cursor()
cur.execute(f"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id},0)")
con.commit()
cur.close()
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
still no work
Put a print statement before sqlite3.connect and after cur.execute
how to make bot
and also what do we need to code
Do you have a basic understanding of python?
maybe
i just started in 3 days maybe
@bot.command(name="register")
async def register(ctx):
print("Connecting...")
con = sqlite3.connect('userinfo.db')
cur = con.cursor()
cur.execute(f"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id},0)")
con.commit()
cur.close()
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
it did print connecting... but database still not work
Id learn python basics before trying to make a bot
i know a little bit discord py
!resource python
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Ty π
Click this
done
.
Read a bit, pick something u like and start learning
ok
and my codes ready
Wdym
Attach a debugger and see where it stops working
Cool
how
my bot server now has verification
thanks for the site
Also check out sqlalchemy for working with sql databases
What site?
resources site
Okay
it stopped working starting from this command
con = sqlite3.connect('userinfo.db')
@lone lichen
!d sqlite3.connect
sqlite3.connect(database, timeout=5.0, detect_types=0, isolation_level='DEFERRED', check_same_thread=True, factory=sqlite3.Connection, cached_statements=128, uri=False)```
Open a connection to an SQLite database.
?
Iβ m reading it so I can see how Itβ s done
ok
And u dont get an exception?
no
Try to pass in full filepath for db argument
ok
it still doesnt work @lone lichen
async def register(ctx):
print("Connecting...")
db = sqlite3.connect('/Users/bai/Documents/Personal Things/PythonDiscord/UserInfo/userinfo.db')
cur = con.cursor()
cur.execute(f"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id},0)")
con.commit()
cur.close()
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
Put the part where u insert into db in a seperate py file and run it there
And see if it inserts into db
And instead of ctx.author.id put any number
no
I wanna see if that would work
ok
nope it didnt work
Idfk, try reinstalling sqlite3 or restarting ur ide
...
anyone
maybe it wasn't feeling well
π
Where is it supposed to send a message
async def register(ctx):
db = sqlite3.connect("userinfo.db")
cur = con.cursor()
await cur.execute(
"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id},0)",
(
ctx.author.id
),
)
con.commit()
cur.close()
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
i changed the code, but still no work! :/
How the heck do you want to reinstall a builtin module lmao
Oh Itβ s builtin π
Yeah
I usually just use an orm
async def register(ctx):
db = sqlite3.connect("userinfo.db")
cursor = db.cursor()
cursor.execute(f"INSERT INTO userinfo (userid, balance) VALUES ({ctx.author.id}, {0})")
db.commit()
cursor.close()
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
How to get this thing working? database was already created but it just cant connect or insert?? this already wasted so much of my time :/
is the table created 
yes it is
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Unclosed connector```
i am getting this error
Probably the wrong bot application?
naah its the same
Other than that, there's no explanation for that error
someone pls help
(According to me)
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.
Traceback (most recent call last):
File "main.py", line 7, in <module>
bot = commands.Bot(command_prefix='$')
TypeError: init() missing 1 required keyword-only argument: 'intents
i need help
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
!e
mport random
import string
def keygen(length): #function
output = "".join((random.choice(string.ascii_letters + string.digits)) for x in range(length))
print("your key: ", output)
keygen(20)
@honest quartz :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | mport random
003 | ^^^^^^
004 | SyntaxError: invalid syntax
#bot-commands
sorry couldnt find bot commands
async def register(ctx):
db = sqlite3.connect("userinfo.db")
cursor = db.cursor()
await cursor.execute(
"INSERT INTO userinfo (userid, balance) VALUES (?, 0)",
(ctx.author.id),
)
db.commit()
cursor.close()
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
is it like this? not working
why await cursor.execute?
its not aiosqlite to await
ok fixed
async def register(ctx):
db = sqlite3.connect("userinfo.db")
cursor = db.cursor()
cursor.execute(
"INSERT INTO userinfo (userid, balance) VALUES (?, 0)",
(ctx.author.id),
)
db.commit()
cursor.close()
em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
await ctx.send(embed=em)```
is it like this? not working
still not work
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.
it is
thats ur whole code πΏ
so u just have that one function in the file u are running? 
How do I convert if ladder code to ctx code?
When you have no imports but python can hack your brain
what u are saying dosent make sense
How do I convert this:
to smth like this:
hybrid**_**command
these aren't even commands just some random message on sending some stuff
Yes
But these are the only things working
the rest isnt
better do that in on_message only when u have decent command make a command function
That's what I was doing
But the actual commands aren't working
yeah so just make that hybrid_command() and u good to go
u have a process_commands ?
in on_message
Even when it was @bot.command() it wasnt working
that the reason why
also u prolly not syncing ur tree either
wdym by that
Where should process_commands be
just add await bot.process_commands(message)
last line of on_message
no one gonna comb thru ur ss and find out where error is there u have debug all this by urself
Or send the code
its so small my glasses cant read bro
string concatenation π
What does that do tho
still doubtful unless like u have dev in very good mood
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.
lol
do u have the intents and perms?
how do u run all this without any imports...?
why not just use listen()???
ok
Why am I stuck here now
Honestly, I don't know enough about Discord.py to help you :(
Most I can do is say try the documentation π
???
Also can someone explain how to use aiohttp
Just check their docs
Just wait or try again
more explaining on my part
lol
Use @bot.listen() instead of @bot.event
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
What kind of genius construction is this
try:
pass
except:
print("EnvironmentError")```
Pass does nothing it can't cause any exceptions
I didn't make that part
tbh I just blindly copied from google that part
its so that the bot doesn't run multiple instances apparently
π§
very dumb on my part i know
How does try: pass help with that lmoa
Literally nothing will change
it throws an error which is annoying so i dont disturb it much
Probably runtime error and you definitely don't handle it like this
I honestly never had a need to handle it because I do graceful shutdowns
It often occurs because of bad shutdown
I have an uptime bot running which causes multiple instances
Cringe
There isn't even an error π
Jk
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.
I have both tbh
I originally used everything in event
but now i am using bot.command
but since i switch to bot.command, it hasnt been working
Have you tried changing @bot.event to @bot.listen()
I have a question. Now that discord.py 2.0 has been released, which one do you recomment for slash command bots:
discord.py ou discord-interactions?
discord.py obviously
discord-interactions was created to add support for interactions to dpy because it didn't have them, now it does so why not use the main lib
Nope
client.load_extension(f'cogs.{filename[:-3]}')```
still nothing
code it DEAD
i am new tod discord2.0
send code
intent = discord.Intents.all()
client = commands.Bot(command_prefix=commands.when_mentioned_or('$'),
intents=intent)
client.remove_command('help')
async def load():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
asyncio.run(load())```
wtf is commands.when_mentioned_or
why don't u directly make it a string
command_prefix='$'
π€¦ββοΈ
await load_extension like the error tells you to do
i am getting the error in load()
It allows the bots mention to be used as a prefix as well
:o
new error
Is it a string value?
What is it :D
nvm i fixed that xd
My code still dead :/
discord.ext.commands.errors.CommandNotFound: Command "test" is not found```
Can someone explain why this happens? Code seems to be perfect π
Itβs a function thatβs returns a string or multiple.
Do you actually ever load the extension.
Can anyone help me with my code
iscord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ping' raised an error: TypeError: object NoneType can't be used in 'await' expression```
import discord
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def ping(self, ctx):
await ctx.send(f'Pong! {round(self.client.latency * 1000)}ms')
def setup(client):
client.add_cog(Ping(client))
uff
Bruh
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connection.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
prefix = await self.cursor.fetchone()
await self.connection.commit()
return prefix or '>'
Guys i have this function to get prefix
I want that when someone mention my bot it sends the bot prefix
How to do that?
hi i want to send the answers the user put into a modal to be sent into a channel but i get this?
You need a discord.TextChannel object
Ig you need to fetch the channel
@client.event
async def on_message(message):
if bot.user.mentioned_in(message):
await message.channel.send("My Prefix is " + asyncio.run(get_prefix())```
Don't start with a fetch, try to get the channel from the bot's cache
something like this i guess
Try
channel = client.get_channel(id)
Where is ctx defined
That's event
Do message.channel.send ig
why are you asyncio.runing that function though?
also, on_message only takes a message arg
And my prefix function takes arguments
How can I disable select menu after it's been used?
Guys why i am getting this error?
what are the best databases to use for a Discord Bot? (ex MySQL, SQLite etc)
Sqlite for small bots, postgres for bigger bots tends to be what alot of people use
this is one of many beauties of hosting on replit
rly depends on what ur storing
u already have something that occupies port 8080
why use sqlite ain't that sync
Hmmm no
atleast use aiosqlite
Me?
are u using sqlite?
try using a different port
what's in this events cog
Aiosqlite
I not event using asyncio it still showing error
u are prolly using something which uses asyncio.run
its not bot error, just use a different port
No
I never used asyncio.run in my life
do as enslo says then
guilds settings, users infos etc
Which port should i use?
this may be helpful for future
2056
Do it work same as 8080?
if 8080 is already occupied u wont use 8080
yes
also show whats inside of events cog as Asher said
ok thx
I still getting same error
show
show code for flask app and events cog
Ok
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "I'm alive"
def run():
app.run(host='0.0.0.0',port=2056)
def keep_alive():
t = Thread(target=run)
t.start()
π’
Looks like discord.py v2.0 is officially out, can someone confirm?
yes it's out
d.py v2.0 is on pypi
finally pip install shit
Awesome. Now I wonβt have to tell people how to manually install 2.0 lol

as you can read the port 2056 is already occupied by another program/process
just use the port 8080
this whole thing started cus port 8080 was occupied π
yo, i recently changed to dpy2.0 and since then my bot is coming online but it aint taking any commands
pls help ;-;
it is not even giving any errors
π
it is usually not occupied
check migrating to 2.0 page
ight ;-;
is it really worth migrating to 2.0???
yes
Basically, you get support for interactions
check the page and u will see if its worth it
thats it right? is it worth it tho?
Read the new added things #381965829857738772 message
also discord have implemented breaking changes, if you'll not migrate to a recent version of the library your Bot could broke
oh
dont have access to this link π
oh
there's more
I don't think "interactions" sum up all of the features
ofc there is more but thats all available to read on their site
yo completely new to cogs. Pls tell me the mistakes I have in this cog ;-;
Hey @cerulean shale!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
it's self.bot to use the bot object, not bot
can you pls elaborate?
also don't make Api call inside on_ready event
you've putted in your __init__
self.bot = bot
self.bot represent you bot object so whenever you need the bot object inside a function you should use self.bot
oooooooooooh
!d discord.on_ready also
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
Read the warning
ight
so in here instead of just bot.change_presence, i should use self.bot.change_presence?
@glad cradle sorry for the ping but just tell me this
Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.
Instead set the activity and status kwargs in the constructor of these Classes.
bot = commands.Bot(command_prefix="!", activity=..., status=...)
As noted in the docs, on_ready is also triggered multiple times, not just once.
Basically: don't π do π shit π in π on_ready.
cant i just define self.bot=bot tho?
yes it should be await self.bot.change_presence(...) however that's not a good idea
how to ping the message to which you are replying??
why should you do that, do you have any idea how OOP and classes work in python?
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
0 idea ;-;
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
sorry for wrongly phrasing my statement, but how do you tag the message you are responding too
It is also occupied
yes I understood and that pretty much answers your question
Wait wat
I just did
from main import get_prefiz
And i got a port error
How is this connected?
do you mean the reference of the referenced message?
@lone lichen when i removed from main import get_prefix my code started working and i not got port error
Do you know why was i getting it?
im extremely dumb , please forgive my low iq , what i was searching for was message.reply()
ok
could anyone plz help me?
yes, explain your problem
absolutely not 
it's okay, dw
that emojis gives me the creeps, jeez

replit moment
in shell showing same error
Python executes files when u import them
so if you have keep_alive() in there outside if __name__ == '__main__', it will get executed when u run the main file and when u import it, meaning, you will have 2 flask servers running on the same port
__name__
its cus of markup
just reminded me all those old 1.7.3 users on replit replit gonna update them all to 2.0 and then bot gonna crash for them
poetry auto update π
ahah
Lmaoo going to be fun
not really fun
this Link will be spammed
replit has many great features like shared ip, underpowered machines, shit code editor and more random issues
As if they will read it
π
π π
I just imported get_prefix from my main file not keep_alive
It's code editor messes up the indentation
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connection.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
prefix = await self.cursor.fetchone()
await self.connection.commit()
return prefix or '>'
Guys i have this func in my bot class
How can I use it in cogs?
and if you have a friend, you can take advantage of their collaboration feature and constantly delete each others code while trying to code at the same time
Lol
do you have access to a bot object in said cog?
How?
I not able to understand what you mean
ok, so just use bot.get_prefix then
It not worked
you need to give more details
error is pretty self explanatory
Ah it's giving me a object not prefix
Idk how to fix this error
what error
This
ok, you read the first sentence of it?
It says not awaited
I have to do await self.bot.get_prefix()?
I think you can figure this out without help
Hmmm?
Ye i fixed it now
Thanks for help tho
is there a way to disable select menu after its been used?
for item in self.children:
if isinstance(item, discord.ui.Select):
item.disabled=True
await interaction.message.edit(view=self)``` i have this code right here but i get error that `self` doesnt have attribute `children`
since self is in my parameters
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Select.values "discord.ui.Select.values").
New in version 2.0.
it doesn't have a children attribute
which makes sense because children is supposed to be the components of a View
you can use self.view.children there
which is just self...
what?
set self.disabled to True
ok but this makes the select menu to be sent disabled
i want to be disabled after its been used
probabilities that the View only has the select menu are high, but not sure so sorry
he checks with an if if the children is a selectmenu
the code i sent is working for buttons but i try to convert it for select menu
so he's looking for self
I didn't link that to show you ut's _init_
go to the doc
check it's attributes
if he only wanted to disable the selectmenu why would be using children in the first place
but i want to disable only the select menu π
I don't know, it's got nothing to do with the question either
then why are you using children??
cause i didnt know that ui.Select hadn't attribute children
that makes no sense at all but ok
nvm
so if you wanna disable the select menu that was clicked you do
self.disabled = True
and edit the message
if you wanna disable something else this advice is useless
so await interaction.response.edit_message(view=self)
or await interaction.message.edit(view=self)
Maybe the deleted message has no content
i am following a tutorial on slash commands they tell me to install this and i do it then they tell me to import slash commands i do all of that but i get error saying discord_slash does not exist
idk what i am missing
Discord.py has slash commands, why do you need the 3rd party lib?
@command(name="mute", description="Mute a certain member.")
@describe(
member="The member that is going to be muted.",
length="Amount of time to mute the member.",
unit="Unit of time.",
reason="Why this member is getting muted."
)
@choices(unit=[
Choice(name="Days", value=86400),
Choice(name="Hours", value=3600),
Choice(name="Minutes", value=60),
Choice(name="Seconds", value=1)
])
async def moderation_mute(
self, interaction: Interaction,
member: Member,
length: Range[int, 1, 2419200],
unit: Choice[int],
reason: str = "No reason specified"
) -> None:
second_amount = sec if (sec := length*unit.value) < 2419200 else 2419200
dt = datetime.now().astimezone() + timedelta(seconds=second_amount)
await member.timeout(dt, reason=reason)
await interaction.response.send_message(
f":ok_hand: Muted {member.mention} for `{reason}` until <t:{int(dt.timestamp())}:F>"
)
``` any ideas of improvement.
And yes the length/unit time is on purpose.
Would you guys use a database to store data such as user info, or user stats specifically for your bot.. Like let's say your bot gives each user a balance, would you guys store that in a database?
Balance yes but that's about it, anything related like user info I just get from the object.
Oh yeah I ment things that you can't get
oroight
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'url'

@client.command()
async def jod(ctx):
await ctx.message.delete()
res = requests.get(link).json()
em = discord.Embed()
em.set_image(url=res["url"])
await ctx.send(embed=em)```
res has no url key
i am new to discord 2.0

print(res)
I suggest seeing what it is
and switching to aiohttp
but it doesn't matter rn
uh that's not much
then ??
@cold sonnet
can u help me with the slash commands
import discord
from discord.ext import commands
from discord import app_commands
import interactions
class ping(commands.Cog):
def __init__(self, client : commands.Bot):
self.client = client
@app_commands.command(name='test' , description='Pong!')
async def test(self , ctx: interactions.CommandContext):
await ctx.send('Pong!')
async def setup(client):
await client.add_cog(ping(client))
slash command will work na?
you made a global slash command and didn't copy it to a guild
that'll take much time to sync
an hour or more
what can i do then?
oh you didn't sync at all
read the gist I sent
setup.hook??
what's that
i just made this π
[await channel.delete() for channel in [ctx.guild.get_channel(channel_id) for channel_id in [order.channel_id for order in await self.bot.orders_dao.get_all()]]]
Hey Guys I need help
just send problem
Reset your token
2.0 is now on PyPI so everyone will have problems with that
MTAw0TgOOTc1Nzc4NDYwODc50A.G2j0II.ltp21k-NZbHHiRT44E4Poosolt3493rjOvW4Og
should invalidate it
yes, its. a data access object for orders entity
Anyway, intents are required in 2.0
what do i do then?
LMFAO
some 0's are turned into O here
does it?
How the hell you typed it
@elder storm reset your token please
idk blame the OCR
ok
iphones have ocr
you should not reveal it here
What's that
it can be used in bad way
optical character recognition i believe
done still shows errors
I'm just trying to get discord to force reset it
oh ok
Understandable
works wrong
I am android user since my very first phone so idk about iphones
will it actually reset the token if u send it here?
Here, github, and a few other places
kinda sick
@unkempt canyon does it, no?
πΏ2.0 is out on pypi hmm
I can open it in the preview app and highlight and select and open links and whatnot from images
it is already for 10 hours or more what are u talking 'bout
would be funny watching people getting missing kwargs error for intents
already
well i just logged in to discord so
right now
like templete ping command in cogs with slash enabled and main file setup
how to raise a custom exception using the error handling event
raise CustomException? π³
i did that in my code but it's only being caught locally with a try except when i am adding isinstance in error handler it's not being raised
class CustomException(Exception):
pass
raise CustomException```
yeah that's not working
it has to inherit from another exception
if i use try except i can print it i can see but the error handler is not raising it
sure just a sec
raise CustomException(message)
it should be an instance, not the class
Ah yes
class InvalidFlag(Exception):
pass
raise InvalidFlag(message)
# in error handler
elif isinstance (error, InvalidFlag):
...
is that error raised inside a command?
no
Then how tf do u expect the handler to catch it π
in another function for a custom convertor
The error handler only catches errors while invoking a command
Can converters return a type other than themselves? How would that work with typehinting π€¨
wdym i didn't get u
What type should a custom converter return?
u can create custom convertor like discord.py does when u typehint with discord.Member
mine returns a list or a tuple
depending on a few cases
So the typehinted argument is a list or tuple, while the typehint says itβs a class?
Seems cursed
no argument is only a string and i parse it to return stuff
anything you wish to lol
the typehint stuff actually works this way ->
async def foo(ctx, arg: Converter):
...
``` `Converter` here needs to be an instance of commands.Converter with a `convert` method which returns the result, the raw argument is passed in the convert method...
Yeah I canβt imagine that playing well with typecheckers
The convert class method? Anything that you want the argument to be
Actually, is it a class method or a static method
Youβd expect arg to be a Converter instance
ok so i have another question u just said the error handler won't get triggered if not in command so y does the else condition in my error handler get triggered
but not the elif π
yeah
Guys help plz
M tryna make a Discord bot tht replies back but this bot isnt responding in my server even tho its online
π i didn't say that, hunter did
can you show the error handler code
i dont think you've really hidden the token but ok whatever
whats hour discord.py version
*your
how do i check tht?
2.0
check it using pip show discord.py , if its 2.0 add message_content intents
yes its 2.0.0
where to add?
@elder storm i thought you did discord.Intents.all() as i told you but ok sure
i did tht too and it didnt work
you can do something like ```py
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
error again
what error
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
read the dev portal part
bruh
weird though, message_content is not a previlaged intent yet
vilaged
what do I do?
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
https://discord.dev > applications > your bot > bot option > toggle the message content intents button to on
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
what is this and how do I fix it? (did python3.10 -m pip install -U discord.py[speed])
full error: https://hastebin.com/okedibeday.sql
thats what commands.parameter is for
https://github.com/Rapptz/discord.py/blob/5c7f6dd37e9b0e664a39520a025e247cca4b5b7e/setup.py#L48
cchardet is not supported for 3.10 yet, and the library is trying to install it
setup.py line 48
'cchardet==2.1.7; python_version < "3.10"',```
because you have 3.10
sed
that was fixed recently within discord.py
they didn't update it on pypi then maybe
yeah will come in 2.0.1
well then they can use the github version
$ git clone https://github.com/Rapptz/discord.py
$ cd discord.py
$ python3 -m pip install -U .[speed]
can use this
how do I implement this into requirements.txt?
dk if the speed version can be installed with pip directly or not
cchardet==2.1.7; python_version < "3.10
i have to downgrade my python version?
setup.py line 48
'cchardet==2.1.7; python_version < "3.10"',```
okay, I guess I'll just wait until cchardet is supported in 3.10
discord.py[speed]
just install the speed version dependencies conditionally instead of installation discord.py[speed]
!pypi cchardet
hmm written in c
if you really want some speed boost and you're on a Unix bases system you can use uvloop
it replaces the default asyncio event loop and provides better performance
!pip uvloop
just use third party compilers to compile the code before then run
have it
that needs strict type checking, else it will be of no use
tru
i am gonna make u do that

