#discord-bots
1 messages · Page 181 of 1
IMO defer first wont hurt anything.
Ahh.. I dont deserve that.. haha.. I feel like I lead you astray with my lack of understanding.
pymongo.errors.CursorNotFound: cursor id 3343587727049317749 not found, full error: {'ok': 0.0, 'errmsg': 'cursor id 3343587727049317749 not found', 'code': 43, 'codeName': 'CursorNotFound', '$clusterTime': {'clusterTime': Timestamp(1673983973, 3), 'signature': {'hash': b'}\r\x05o\xfejJ\x87!6\xf7?P\xa0\xb3\x00\xf7\xbf\x8fs', 'keyId': 7127295041399160841}}, 'operationTime': Timestamp(1673983973, 3)}
``` That is your entire error.
The cursor id is different each time.
nah, i've been dealing with this like for multiple days and asked multiple people, i think it might just be my server being too slow along with my messy code that is causing the problem. Probably will revamp when I have more free time but at the moment ill probably leave it as it is. It isn't causing much problems, it is just making one ort wo buttons not work every like 12 hours so it should be fine
So users.close() will solve the problem?
Thanks for ur help tho lol
To close the cursor
per their docs.
Cursors in MongoDB can timeout on the server if they’ve been open for a long time without any operations being performed on them. This can lead to an CursorNotFound exception being raised when attempting to iterate the cursor.
You're using pymongo, right?
That is what I was suspecting too
Yes
Pymongo is a blocking client
And when you do long blocking I/O things start getting funky in an asynchronous environment
It blocks your entire event loop from running
discord.py can no longer heartbeat the gateway, gets disconnected, and overall spotty connection
!pypi motor
For an asynchronous alternative
Some people already told him about that 
sigh
Shows how stupid I am 😛
But don't I need a synchronous method for the code to check one user at a time?
Oh my bad
I just popped in lol
Async or not, only one line of code can run at a time
Asynchronous programming, at least in Python, is not truly "parallel"
It uses just 1 thread, which is why things that block the entire thread (such as time.sleep() or blocking I/O clients like pymongo) can be problematic
@sick birch Can you please explain why I'm not seeing the error anymore with users.close()?
In the following code:
@tasks.loop(hours=24)
async def update_elo_ratings():
print("Updating all users from the database...")
# Get all the users in the collection
users = collection.find()
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
await asyncio.sleep(2)
users.close()
print("Finished updating all users from the database.")
Looks like some syntax errors are going on there
Is that just Discord or in your code?
My code
Yeah looks to be an unclosed quotation
Sorry updated version^
They are actually not unclosed, my bad.
As per your original question -
users was probably some sort of cursor object, when it was not closed, you were keeping an I/O operation open for a long time
Thanks. So if I change to motor do I have to change the entire code of mine? Or can I keep example collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}}
It will require a significant rewrite unfortunately
Better now than later down the road with a larger codebase
I heard motor is being retired and no longer maintained. Is that not true?
So using pymongo is really that bad huh?
It's not bad it's just not the right tool for the job
A screwdriver is not bad because you can't slice bread with them 😛
Where did you hear about motor being un-maintained/retired?
There was literally a PR merged a week ago
No currently active PRs or issues though 🤔
Guessing that's because they're just on top of things
Nvm I could be wrong
You know who else is on top of things, eric
Guy's a type machine
I understand, thank you. My apologies, I am still learning
That's okay
someone know how i can get a text from TextInput?
!d discord.ui.TextInput.value
property value```
The value of the text input.
ty
note about document based dbs^
Do I have to close users when I use motor instead of pymongo?
Or should I use it to stop the I/O operation?
You will still probably have to close it
Or if motor provides a context manager (like aiosqlite) does, you won't have to manually
Ok thanks
Error: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "" is not snowflake.
What does this mean in the context of this code
await message.add_reaction(f":{num2words.num2words(i+1)}:")
No need for ::
Traceback (most recent call last):
File "main.py", line 8, in <module>
from discord import app_commands
ImportError: cannot import name 'app_commands' from 'discord' (/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/init.py)
why wont it import
You're probably on an older version of discord.py
oh
how do i update it
then it says "Error: Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji" o:
What IDE are you using?
Are these custom emojis or default emojis?
default
Can we see them?
1️⃣2️⃣3️⃣ etc
repl
replit
Should just be pip install -U discord.py then
thx
await message.add_reaction("1️⃣")
oh, is there a way to do it like, with numbers because its in a for loop that can iterate anywhere from 2-9
or do i have to do it using a list of the emoji strings
emojis = ["1️⃣", "2️⃣", "3️⃣", ...]
gotcha
hi! someone has a little code of aiosqlite? i dont understand nothing of documentation and idk what to do

Here's an example of how you'd integrate aiosqlite with discord.py. This is just a framework I'd like you to off of rather than copy and pasting (it most likely won't work if you do that)
class MyBot(commands.Bot):
def setup_hook(self) -> None:
self.db = await aiosqlite.connect("filename.db")
bot = MyBot(command_prefix="!", intents=discord.Intents.all())
@bot.command()
async def db_operation(self, ctx: commands.Context, ...) -> None:
async with bot.db.execute("<SQL QUERY HERE>") as cursor:
# operate on `cursor`
await ctx.send("Database operation complete!")
bot.run()
thank u
someone know how i can send a modal after someone click in one button?
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
i was trying
await interaction.response.send_modal(Mymodal())
but it was giving a error
What error?
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
Can you show us your code?
i cant bc it has some personal things inside
We can't really help then
usually means the callback timed out doesnt it
Yeah
You have 3 seconds to respond to an interaction
If it takes longer you can defer()
well, in the case of a modal you cant defer
class Mymodal(discord.ui.Modal, title='z'):
answer = discord.ui.TextInput(label='t', style=discord.TextStyle.short, required = True, placeholder='q')
async def on_submit(self, interaction):
await interaction.response.send_message('k')
if str(c) == str(d):
await interaction.response.send_message('a')
else:
await interaction.response.send_message('b')
class Button(discord.ui.View):
@discord.ui.button(label="x", style=discord.ButtonStyle.green, emoji="y")
async def mybutton(self, interaction, button):
...
await interaction.response.defer()
await asyncio.sleep(1)
await interaction.response.send_modal(Mymodal(timeout=None))
looks like the defer did not solved, that just gived me a different error:
discord.errors.InteractionResponded: This interaction has already been responded to before
you can't defer
and then send a modal @velvet sierra
i suggest not sending a modal at the end if ur doing a bunch of shit
create a seperate buttoni
to send a modal
ye, mb, i changed the places and it worked, it give a small error of
discord.errors.InteractionResponded: This interaction has already been responded to before
but all looks like working fine, i'll do the real test rn
Since discord.py is an ascio loop, does that mean anything inside of the bot script would be ran constantly as well?
Can I make it infinitely print things?
no its not
There is member.guild_permissions but you may be looking for channel.permissions_for(member)
what do u mean top 3?
permissions aren't ordered in any specific way
that doesn't exist with user permissions.
yea u got some custom stuff going on
owner by default has all perms
how is your most_common func setup?
im assuming it just gets all member perms from guild and counts each perm and gets the lowest count perm?
well u have .most_common
but u said u wanted least common
well cause
roles override those permissions
u should check role permissions rather than individual perms
day in the life of a programmer
does anyone know how to call a discord bot's command but through a website?
i need to access some discord info through my website and was wondering if there was a way
how would i make an api for discord bot commands
youd have to run both the web framework and the discord bot client in the same file tho
im not sure
not exactly. your best bet tho is using a database
especially if you just need to access data
well, what i was aiming for was checking if a user was in a server
just use oauth?
u can see all servers the user is in as well as mutual servers
yup
wym?
Hi, what is the best way to keep a discord bot script running in Ubuntu
what is ubuntu
Just leave the program running? 🤷
Well, it closes after I close my SSH session
Wait ima give I guide
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
Containerising application is better than just running it
Well I was using nohup before but my bot was crashing for no reason.
No error message. I thought it was a memory leak, but it wasn't
Linux-based OS
How the heck do error messages and memory leaks relate
I mean, the script crashing due to memory leak
Like killed by OOM killer
I saw in system logs it was before, and I fixed it, but now it is crashing even with low memory usage
Anyone know best hosting website for discord.py bot & pycord
✌️
Am i dumb, or what?
File "/home/hedmad/Files/repos/Milton/milton/cogs/math_render.py", line 71, in on_message
await self.bot.wait_for("reaction_add", timeout=300, check=event_check)
TypeError: Client.wait_for() missing 1 required positional argument: 'event'
The "reaction_add" is the event?
The signature is wait_for(event, /, *, check=None, timeout=None)...?
Ok - nevermind. I'm just an idiot
No that's not what's called memory leak
?
Perhaps you meant memory overuse
What's the difference? asking genuinely
Like memory building up overtime isn't memory leak?
Memory overuse is when you exceed amount of RAM available, memory leak is program issue that leaves unused stuff in memory
To be more precise "memory for object you finished operating with was never deallocated"
After program is killed memory it used frees up
What buffers
BytesIO
I used tracemalloc to pinpoint it
Anyways your problem is in different thing
Still trying to figure out
You used nohup?
Follow my guide instead and use docker
And has a high usage
Docker isn't gonna affect its performance
@bot.slash_command()
async def banner(ctx, user:discord.Member):
user = await bot.fetch_user(user.id)
banner_url = user.banner.url
embed = discord.Embed(title=f"{user.name}'s Banner", color=0xFF0000)
embed.set_image(url='{}'.format(banner_url))
await ctx.send(embed=embed)```
I just notice something here updated code 😅
"{}".format(string_instance)```
is the most useless thing I've ever seen, no offense
Why not do url=banner_url bruh

i am trying to add easy_pil for my discord bot via poetry but for some reason it cant recognize the package
what do i do
like it ads it but then it gives some error related to aiohttp
!pypi easy-pil
Send the error then
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\user\Desktop\Other\Bots_For_Sell\cleevno\bot.py", line 97, in ea
await interaction.guild.create_custom_emoji(name="emoji1",image=img)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 3010, in create_custom_emoji
img = utils._bytes_to_base64_data(image)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 612, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 598, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
AttributeError: 'File' object has no attribute 'startswith'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ea' raised an exception: AttributeError: 'File' object has no attribute 'startswith'```
code :
@app_commands.describe()
async def ea(interaction:discord.Interaction):
def check(reaction, user):
return user == interaction.user
await interaction.response.send_message('**Please react to this message with the emoji you want to add**', ephemeral=False)
the_reaction = await bot.wait_for('reaction_add', check=check)
await the_reaction[0].emoji.save("1.png")
img = discord.File("1.png")
await interaction.guild.create_custom_emoji(name="emoji1",image=img)
print("Done")```
!d discord.Guild.create_custom_emoji - the image arg needs to be bytes
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") to do this.
ok
Because no versions of easy-pil match >0.1.9,<0.2.0
and easy-pil (0.1.9) depends on aiohttp (>=3.6.0,<=3.8.1), easy-pil (>=0.1.9,<0.2.0) requires aiohttp (>=3.6.0,<=3.8.1).
And because discord (rev master) depends on aiohttp (>=3.8.2,<4.0), easy-pil (>=0.1.9,<0.2.0) is incompatible with discord (rev master).
So, because project depends on both discord (branch master) and easy-pil (^0.1.9), version solving failed.
at /opt/virtualenvs/python3/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237│ packages = result.packages
238│ except OverrideNeeded as e:
239│ return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240│ except SolveFailure as e:
→ 241│ raise SolverProblemError(e)
242│
243│ results = dict(
244│ depth_first_search(
245│ PackageNode(self._package, packages), aggregate_package_nodes```
Why th does easy-pil requires aiohttp ☠️
its in requirements.txt
Just git clone it then remove the requirement
@naive briarthanks it worked
Or literally just use Pillow
you could switch back to an older version
nvm this
wait actually its' the famous replit issue lol
just create a new repl ig
???
is there any option where if the user who is executing the command doesnt have a guild avatar so that we can disable a button?
File "c:\Users\maxje\Documents\Plugins\Python\DiscordBot\Main.py", line 15, in <module>
with open('config.json') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
``` can were help?
It's obvious error
Define the path if file exists
how
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
!d discord.Member.display_avatar
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
returns default avatar as well
is there an api with unlimited use that is free to use? she can also have a cooldown
hello, i have a problem with a simple command:
@bot.command()
async def server_info(ctx):
embed = discord.Embed(title=f"{ctx.guild.name}", description="Información del servidor:", timestamp=datetime.datetime.utcnow(), color=discord.Color.orange())
embed.add_field(name="Creación del servidor:", value=f"{ctx.guild.created_at}")
embed.add_field(name="Dueño del servidor", value=f"{ctx.guild.owner}")
embed.add_field(name="ID del servidor", value=f"{ctx.guild.id}")
embed.set_thumbnail(url=f"{ctx.guild.icon}")
await ctx.send(embed=embed)
the problem is in the last line
I'm still receiving raise CursorNotFound errors logs. Do anyone know how to fix this problem? I'm using pymongo.
is there an api with unlimited use that is free to use? she can also have a cooldown
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Exact error?
What does api need
pymongo.errors.CursorNotFound: cursor id 3343587727049317749 not found, full error: {'ok': 0.0, 'errmsg': 'cursor id 3343587727049317749 not found', 'code': 43, 'codeName': 'CursorNotFound', '$clusterTime': {'clusterTime': Timestamp(1673983973, 3), 'signature': {'hash': b'}\r\x05o\xfejJ\x87!6\xf7?P\xa0\xb3\x00\xf7\xbf\x8fs', 'keyId': 7127295041399160841}}, 'operationTime': Timestamp(1673983973, 3)}
no_cursor_timeout=True
just any api that can be used indefinitely (the api can also have a cooldown for each use)
And they have unlimited uses?
.bm
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
So like this?
@tasks.loop(hours=24)
async def update_elo_ratings():
# Get all the users in the collection
cursor = collection.find(no_cursor_timeout=True)
users = cursor
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
await asyncio.sleep(10)
cursor.close()```
you can see which apis offer no authentication, they'll probably have unlimited uses if they do not do stuff with the ip addresses and limit uses
✅ this should work
Most do yes
What is wrong with it?
.bm
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
you're only declaring a useless variable
but ok
So should I remove it and keep the rest?
yes
NameError: name 'users' is not defined
pymongo.errors.OperationFailure: noTimeout cursors are disallowed in this atlas tier, full error: {'ok': 0, 'errmsg': 'noTimeout cursors are disallowed in this atlas tier', 'code': 8000, 'codeName': 'AtlasError'}
Am I the only one with this issue?
@slate swan is the google translate api also free and unlimited?
you can't use cursors which do not have timeouts
learn python
Dude you just told me to remove the variable
ok and
And the error occurred
I'm learning, thanks
;-;


Add it back
And make
no_timeout_cursot or something to False
no_cursor_timeout=False
cursot UwU
Keyboard 
I'm changing my code to use motor instead.
I heard motor is much better
it's the same but just asynchronous
async def kick(ctx, userName: discord.User, *, reason: str):
await kick(user=userName, reason=reason)
I read thru the docs a bit and looked up some examples but i have 0 idea why this isnt working
/nvm im dumb i got it
Seems to be missing the decorator
Unless you just left it off while pasting
yeah i just left it out when copy pasting
@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
this ended up working
A recommendation, if your bot is supposed to be database heavy, then PostgreSQL is the best option.
It's not really database heavy. But I want to get rid of all the errors I'm getting.
So I changed the code to:
@tasks.loop(hours=24)
async def update_elo_ratings():
# Get all the users in the collection
users = await collection.find().to_list(length=None)
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
await collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
await asyncio.sleep(10)```
@sick birch Do you think to_list() method can be used to retrieve the results of the find method as a list, instead of a cursor. and this should not give me any cursor errors anymore?
I'm using motor now btw
I think there's limit
Not sure, I don't use mongo sorry
if message.channel == channel:
if message.content in list:
if mention == 'None':
msg = await echannel.send(f"``{message.author}`` wants to be promoted to ``{message.content}`` ``ini\n[Action Required!] Please reply with 'confirm' to accept this promotion``")
else:
msg = await echannel.send(f"{mention} ``{message.author}`` wants to be promoted to ``{message.content}`` ``ini\n[Action Required!] Please reply with 'confirm' to accept this promotion``")
def check(m):
return m.content == 'confirm' or m.content == 'Confirm' and m.reference and m.reference.message_id == msg.id
message_id = payload.message_id
if message_id == msg.id:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g: g.id == guild_id, self.bot.guilds)
if str(payload.emoji) == "\U00002705":
role = discord.utils.get(guild.roles, name="[I] Member")
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
await self.bot.wait_for('message', check=check)
await echannel.send("Confirmed")```
Can someone help?
instead of replying to the message with confirm I'd rather do reaction tick or cross
hey, i used to make discord bots a couple of months ago but i know the main library got discontinued or something so could someone please send an updated template thanks
Discord.py is not discontinued
If that's what you mean by the "main library"
hey robin can I get ur help
oh really? I dont remember much but I remember the creator quitting
It's still more or less the status quo
well, has anything changed since i heard discord is getting rid of text commands
@sick birch
Yeah there's been quite a few changes
I could recommend reading the migration guide
I recommend nextcord for slash commands it's been good for me so far
@bot.slash_command(name="hi", guild_ids=[38292928])
async def command(inter: nextcord.Interaction):
await inter.response.send_message("hi")
disnake is better 😈
danny came back after seeing everyone scattered across different libraries, dpy v2.0 finished development on august, and the message content intent became privileged on september
I personally would just recommend discord.py since your existing codebase may already be in discord.py. It also has the most support and maturity IMO
"maturity": the 2k kids making a discord Bot without knowing python
I'm referring to the people who've been contributing for years
The one good / bad thing (depending on how you look at it) that came out Discord.py's toxic community is that it keeps most newcomers / inexperienced developers from contributing, lol
o_O Some things could be implemented in a better way (eg slash commands)
Every library has its flaws
Though I personally haven't had any issues
I find it intuitive to work with
so far ive been cool with the command tree and transformers
ImportError: cannot import name 'ReturnDocument' from 'motor.core'
from motor.core import ReturnDocument
I installed motor with pip3 install motor, is there anything I'm missing?
thats more of a #databases question but ReturnDocument appears to be part of pymongo, not motor itself
File "C:\Users\Name\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Name\Desktop\PM-Beta\PM-Beta.py", line 131, in on_guild_channel_create
euser = await audit_user(guild, discord.AuditLogAction.channel_create)
File "c:\Users\Name\Desktop\PM-Beta\PM-Beta.py", line 34, in audit_user
e = await guild.audit_logs(limit=1, action=action).get()
AttributeError: 'async_generator' object has no attribute 'get'```
Do you know how to fix this code using motor?
# Increment the counter and use it as the case ID
counter_doc = await counter_collection.find_one_and_update({"_id": "case_counter"}, {"$inc": {"count": 1}}, return_document=ReturnDocument.AFTER)
if counter_doc is not None:
case_id = counter_doc["count"]
else:
# No documents match the query, create a new document with a counter value of 1
await counter_collection.insert_one({"_id": "case_counter", "count": 1})
case_id = 1```
https://discordpy.readthedocs.io/en/stable/migrating.html#moving-away-from-custom-asynciterator
dpy 2.0 moved away from their custom iterators so you'll have to rewrite it using anext()/__anext__()
fix what, the import error? its described in their docs where you'd import ReturnDocument:
https://motor.readthedocs.io/en/stable/api-asyncio/asyncio_motor_collection.html#motor.motor_asyncio.AsyncIOMotorCollection.find_one_and_update
So I need to borrow that function from pymongo? Is there no way to only use motor to do the same thing?
thanks
motor itself installs pymongo as a dependency
can i still use prefix commands if my bot isnt in a 100 servers?
below 100 servers you dont need to verify to enable message content, and any message that mentions the bot or goes to its DMs will receive message content regardless
Why do I then have to import it from pymongo?
go ask the motor devs that
so it can only read messages that mentions the bots or dms, not all messages?
if you dont enable the message content intent that is
oh alright ill enable it
!intents
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.
??
Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
that tag is describing what intents are and how you'd add them to your bot constructor
also please make sure you've reset your token
what part of the bot's tag are you confused about?
unrelated topic, with the prevalence of embeds in bot and webhook messages, i have to wonder why discord still has a setting to disable embeds outright
you need to specify what gateway intents your bot will be using when it connects to discord, as described by the tag
hide your token btw
How?
well the link i sent describes it...
If you need to get next item from an iterator without a loop, you can use
anext()(new in Python 3.10) or__anext__()instead:
# after
it = channel.history()
first = await anext(it) # await it.__anext__() on Python<3.10
... ```
why doesn't commands with ctx work for me?
bot isnt running, bot cant see your message being sent, bot cant read the content of that message, bot isnt processing your message as a command, bot doesnt recognize the prefix of your command, bot doesnt recognize the command, etc.
we need to see your code, output, and what you've tried typing in discord to figure out what the issue is
Hey! Is there maybe a way, to define a function, then make a lot of ifs and if one of the if is true, then set a variable to a specified number, thats in the function, and then run the function? It should probably look something like this, but sadly its not working.
def fankson(fanksonvariable):
print(fanksonvariable)
@client.event
async def on_message(message, fanksonvariable):
if message.author == client.user:
return
if message.content.startswith('$statsimportant'):
fanksonvariable = 0
if str(message.guild.id) == first_server_id:
fanksonvariable = 1
fankson()
elif str(message.guild.id) == second_server_id:
fanksonvariable = 2
fankson()
else:
await message.channel.send("You don't have a license.")
I can send code
you made it a parameter of your function, so why not pass the value to your function? i.e. fankson(2)
!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.
wdym, can you please give me an example?
def get_stats_for(guild_id):
... # ^^^^^^^^ a function parameter
# in on_message:
guild_id = message.guild.id
if guild_id in licensed_guilds:
stats = get_stats_for(guild_id)
# ^^^^^^^^
# passes the value of the guild_id variable as a function argument```
hmm code itself seems fine, is the bot able to read messages in whatever channel you typed !hello to?
the bot could read the message
thank you, my only problem is that every licensed guild has its own unique variable. Thats why i want to check for every licensed server, and then set the fanksonvariable to the unique variable, and then run the stats.
so not just check if its licensed or not, but check what is its unique 2-3word identifier
presumably it said in the console that the bot was ready, right? and is that everything in your code? no on_message event?
@client.event
async def on_message(message):
if message.content == "!hello":
await message.channel.send("Hello how are you?")
``` if so the code goes as the bot responds
an on_message prevents commands from running unless you explicitly tell your bot to process them
How can you change that?
do what the FAQ says, use bot.process_commands() or make it a listener
you should probably consider using a dictionary to map the unique value to each guild, e.g. guild_fankson = {first_server_id: 1, second_server_id: 2}
@client.command()
async def hello(ctx):
await ctx.send("hello how are you?")
await client.process_commands(message)
So?
it has to go inside your on_message event, and also match the same name you used in the @ decorator
you defined your Bot instance under the variable name client, and process_commands() is a method of Bot
thank you, lemme try making it.
So whoever is @client above must also be a client below. being
there are still a few unclear things in my head, but ill try 😊
So is that correct?
im sorry but i still dont get it.
it has to go inside your on_message event
How can that be done, that i check for the guild id, if its = to a specified guild id by me, set a variable to a value set by the code, and then run a function with that variables inside.
I tried with ur code, but i still dont get how, and why it doesnt work... 😢
I see
will test it right away
Should I close the connection to the database after it updated all users?
@tasks.loop(hours=24)
async def update_elo_ratings():
# Get all the users in the collection
users = await collection.find().to_list(length=None)
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
await collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
await asyncio.sleep(10)```
you're dealing with the fundamentals of functions, functions can define parameters (i.e. inputs) and when you call a function you can pass an argument/value to each of those parameters
https://docs.python.org/3/tutorial/controlflow.html#defining-functions
so if you want it to have a certain value, call the function with that value and the parameter will have that value inside the function
assuming the connection isnt being used 24/7 probably, but it looks like you've connected to the database outside of your loop
I'm using motor and this code. I don't want to keep an I/O operation open for a long time. It should close the connection after it's done updating all the users. Do I have to include some extra codes to do that? @hushed galleon
if you open the connection inside your loop, then you shouldnt have to worry about any side effects when closing it afterwards
So this is the connection right?
"mongodb+srv://botname:password@cluster2.logfuua.mongodb.net/summoners"
client_mongo = MotorClient(uri)```
Let me explain what I mean. So yesterday I received this kind of error.
pymongo.errors.CursorNotFound: cursor id 3343587727049317749 not found, full error: {'ok': 0.0, 'errmsg': 'cursor id 3343587727049317749 not found', 'code': 43, 'codeName': 'CursorNotFound', '$clusterTime': {'clusterTime': Timestamp(1673983973, 3), 'signature': {'hash': b'}\r\x05o\xfejJ\x87!6\xf7?P\xa0\xb3\x00\xf7\xbf\x8fs', 'keyId': 7127295041399160841}}, 'operationTime': Timestamp(1673983973, 3)}```
@hushed galleon the hello command works but if someone leaves the server there is no message
@sick birch told me: users was probably some sort of cursor object, when it was not closed, you were keeping an I/O operation open for a long time
So I changed to motor. And I don't want the same thing happened again.
Motor probably provides an async ctx manager to handle closing for you
You'd have to refer to docs as this is becoming #databases
With that being said. Is there anything I have to change to my code to use an async ctx manger? Here is the code once again:
@tasks.loop(hours=24)
async def update_elo_ratings():
# Get all the users in the collection
users = await collection.find().to_list(length=None)
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
await collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
await asyncio.sleep(10)```
Not sure
Never used motor
I would check their documentation
huh, it seems windows has denied your script permission to start a socket connection?
no idea
Might be a old version of aiohttp or they could try changing asyncio to use window selector policy
Is this Mac OS or Windows?
Windows
What version of aiohttp?
Aiohttp?
i would doubt that would be the issue if the bot was working earlier, but tbf i havent seen an error like that before
That error is related to DNS
So something is wrong with the DNS
As far as I can see
Do you guys use an async ctx manger?
I mean when you are updating information about users etc
You sure you even have internet connection? And does ping to different hosts work?
How would I make a giveaway end command?
depends what your giveaway has, but you would just presumably disable the prior buttons then pop out a user at random based on who joined
my giveaway tool uses reactions
then clear reactions if ya want
i want to say just get the reaction then reaction.remove
but ill have to double check that for ya in a sec
ok
quick search just says you can do the whole message with clear_reaction() on the message obj
!d discord.Message.clear_reactions
await clear_reactions()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes all the reactions from the message.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this.
there you go
could anyone tell me at which part of the docs i have exactly to look for dc bot sending dm as response from a command
!d discord.Member.send
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.11)") 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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
king
Hello! odd question but, ive been trying to figure out how to integrate this one module into my discord bot for the last few hours and quite honestly i have nothing to show for it, i keep hitting a wall and was wondering if anyone could help me out? https://pychievements.readthedocs.io/en/latest/ is the module in question
@sick birch So far, I have not encountered any Cursor errors with motor, even when not using the 'close' function.
What is the way to handle and ignore errors like 'discord.ext.commands.errors.CommandNotFound: Command "customgames" is not found' ?
@bot.slash_command(description="Change the bots pfp")
@application_checks.has_permissions(administrator=True)
async def change_pfp(interaction: nextcord.Interaction, avatar:nextcord.Attachment):
with open(avatar, 'rb') as image:
await bot.user.edit(avatar=image)``` this is my code and im trying to make a command that will change my bots pfp, this is the error im getting ```TypeError: expected str, bytes or os.PathLike object, not Attachment
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not Attachment```. anyone know a fix
You mean hyperlink?
You need to use this iirc
!d discord.Embed.url
The URL of the embed. This can be set during initialisation.
!d discord.Attachment.read | You can use this and set it as the pfp of the bot iirc
await read(*, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.
New in version 1.1.
so do i replace the bot.user.edit with that??
Ya since it's async
or where do i add that at
Long I/O waits are not a problem for async
No? It returns a bytes object
Wastes resources at worst
where would i put that at
You would pass it to await bot.user.edit(avatar=image)?
So you would just do
await bot.user.edit(avatar=await avatar.read())
ok
its giving the same error ```py
@bot.slash_command(description="Change the bots pfp")
@application_checks.has_permissions(administrator=True)
async def change_pfp(interaction: nextcord.Interaction, avatar:nextcord.Attachment):
with open(avatar, 'rb') as image:
await bot.user.edit(avatar=await avatar.read())
dont open it
ok
Remove the first line after the function definition
so this
alr i got it
Yep! btw add a space after the word avatar in the parameters
What is the optimal way to handle CommandNotFound error?
Ignore it
Good way to ignore it?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
pass
else:
raise error```
Bots that say "did you mean X" when you type the wrong command are annoying
You don't even need to do that
I would let it log just for logging purposes but other than that just ignore it
Ok
how can i make a command so that when someone authorizes with my bot and They allow the bot to join servers for them, and if they leave the server i can run a command that will pull them back in
asking for a friend
Will do
Thanks
We're probably not going to be helping with those kind of bots here
wym those kinds of bots?
There have been these bots going around recently that force users to stay in a server against their will
thats not what im trying to do so can someone help
That seems to be exactly what it is
Why do you want to pull a user back into a server if they leave?
That seems to go against the intention of "leaving" a server
I would take a look at Discord's Developer Terms of Service Section 2b.
if they leave server and cant find invite and i can just rejoin for them 😃
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.11)") 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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Even then is... questionable. You're DMing a user that is no longer in your server
yeah thats why i want my method
The other method is even more questionable and certain violates Discord's developer policy and terms
Just send them an invite to your server. It'll most likely fail since they no longer share a server with your bot, though so that makes it much better
but if i cant invite them because they have me blocked
but they dm my friend saying they want to join and he cant make invites
That is the user's choice and in accordance with the developer policy
If they have the setting enabled, that means they do not want to be contacted from bots that are in their server and you have to respect that
Your Application must respect user decisions to opt out of or block the Application, as applicable.
https://discord.com/developers/docs/policies-and-agreements/developer-policy
they want to join
Create some other avenue for them to contact you for an invitation link
Forcing all users to stay in a server just for a few users that do actually want to rejoin is against Discord's policies
Sorry, but I see too many ways that this could be used maliciously. Not sure we can help you in accordance with rule #5. I would recommend taking a read through some of these links:
https://discord.com/developers/docs/policies-and-agreements/developer-policy
https://discord.com/developers/docs/policies-and-agreements/developer-terms-of-service
https://discord.com/guidelines
https://discord.com/terms
no just that user
you know, if they blocked you, I don't think that you should go out of your way to "allow" them to join your server in that way
If it's just one user it shouldn't be a big deal to give them your Discord contact information if they need to rejoin back
Why waste the time and effort creating a whole Oauth application process just for one user?
Just add them as a friend and they can DM you whenever for an invite 😄
bot = discord.Bot(command_prefix='!', activity=activity, status=discord.Status.online)
^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'
!intents
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.
it would be commands.Bot assuming that you imported from discord.ext import commands at the top of your file
Traceback (most recent call last):
File "C:\Users\rhino\OneDrive\Desktop\Xenon Order bot\main.py", line 21, in <module>
intents.message_content = True
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Intents' object has no attribute 'message_content'
what discord.py version are you on?
try uninstall discord and discord.py and then just install discord.py
pip uninstall discord, pip uninstall discord.py, pip install discord.py
I wanted to create a command where the bot designates roles to a certain user upon mention
eg. c-role @user
the role ids/roles will already be defined in the code
does anyone know how to do this?
import logging
import discord
from discord.ext import commands
logging = logging.getLogger('Discord')
print ("loading...")
spooky = commands.Bot(
command_prefix="c-",
intents=discord.Intents.all(),
case_insensitive = True,
help_command=None,
)
@spooky.event
async def on_ready(server):
print("Hello World!")
@spooky.event
async def on_ready():
if .guild.id != 1063661449832058961:
return
log_channel = spooky.get_channel(958975903839428668)
mm_role1 = .guild.get_role(1063671567046946897)
mm_role2 = .guild.get_role(1063699294227537940)
@spooky.command()
async def mm(ctx, member : discord.Member):
await member.add_roles(mm_role1, mm_role2)```
this is kinda what I've done so far, I want it to be so the bot recognises the server id and then the command c-mm @user will add certain roles but I'm kind of stuck
In on ready you dont have guild defined
Also why do you have two on_ready events anyway?
Your command async def mm should not be inside on_ready
You most likely do not even need the 2nd on_ready
@spooky.command()
async def mm(ctx, member: discord.Member):
...
is good enough
okay! thank you,!
how do I make it so the bot recognizes roles in a certain guild?
!d discord.Guild.roles
property roles```
Returns a sequence of the guild’s roles in hierarchy order.
The first element of this sequence will be the lowest role in the hierarchy.
This?
yes, thank you!
Also when you define mm_role1 It’ s only accessible inside that on_ready function and not in the command
I see, I've updated my code to this:
import logging
import discord
from discord.ext import commands
logging = logging.getLogger('Discord')
print ("loading...")
spooky = commands.Bot(
command_prefix="c-",
intents=discord.Intents.all(),
case_insensitive = True,
help_command=None,
)
@spooky.event
async def on_ready():
print("Hello World!")
log_channel = spooky.get_channel(958975903839428668)
mm_role1 = discord.guild.Role(1063671567046946897)
mm_role2 = discord.guild.Role(1063699294227537940)
@spooky.command()
async def mm(ctx, member: discord.Member):
await member.add_roles(mm_role1, mm_role2)```
but it gives me an error whenever I run it
What error
Traceback (most recent call last):
File "/Users/myname/Custom bot/main.py", line 20, in <module>
mm_role1 = discord.guild.Role(1063671567046946897)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Role.init() takes 1 positional argument but 2 were given
!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.
Also you dont use discord.Guild class
U need an instance of that class which represents a specific guild
I see, am I able to dm you quickly if that's okay?
Yea sure ig
thanks !
Can someone help:
discord.app_commands.errors.CommandInvokeError: Command 'review' raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'reviews.json'
Read the error
Does anyone know how to add a dynamic timestamps to embeds?
!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.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
thanks!
hii, I still need some help with this if ur free
Just ask it
middleman.add_field(
name="Date added:",
value=f"{datetime.utcnow}",
inline=True
)
await ctx.send(embed=embed)```
code at start:
discord.utils.format_dt(datetime.utcnow(), style="R")```
It's not an in-place operation
I'm trying to make it display in this format:
eg. Date added: 5 years ago (constantly changing as time changes) but it displays like this instead
dynamic_timestamp = discord.utils.format_dt(...)
my_embed.add_field(..., value=dynamic_timestamp)
I see, so I need to include it within the command?
Yes
got it, thanks!
it displays as a dynamic timestamp now, but rather than it constantly changing as time changes, it simply just says "11 hours ago"
dynamic_timestamp = discord.utils.format_dt(datetime.utcnow(), style="R")
embed=discord.Embed(
title="⠀⠀ User Added﹕ ✦",
description=f"{member.mention} is now a <@&1063671567046946897>",
color=discord.Color(0x7896a1)
)
embed.set_thumbnail(url=member.avatar)
embed.add_field(
name="Added by:",
value=f"{ctx.author.mention}"
)
embed.add_field(
name="Date added:",
value=dynamic_timestamp,
inline=True
)
await ctx.send(embed=embed)```
It'll change when the hour goes up
is there a limit to the amount of rows in a view?
yes but it is starting at 11 hours, rather then the second it has been added
5 rows per view
5 buttons per row
1 select menu per row
thanks
Probably because it's utcnow instead of just now
okay!
You're probably UTC - 11 I'm assuming
yeah
how do i take an argument as a list of users
!d discord.ext.commands.Greedy
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
membesr: commands.Greedy[discord.Member]
use variadic if its at the end of the parameter
yep *members: discord.member
does anyone know how to program so that after "who are you adding?" the bot will recognize the person being roled by either mention or discord id?
@spooky.command()
async def add(ctx):
await ctx.send("Lets start! Who are you adding?")
button1 = Button(label="role", style=discord.ButtonStyle.blurple)
button2 = Button(label="role", style=discord.ButtonStyle.red)
button3 = Button(label="role", style=discord.ButtonStyle.green)
button4 = Button(label="role", style=discord.ButtonStyle.blurple)
button5 = Button(label="role", style=discord.ButtonStyle.blurple)
async def button1_callback(interaction):
await interaction.response.edit_message(content="**Adding as role!**", view=None)
view = View()
view.add_item(button4)
view.add_item(button5)
await ctx.send("What games can they do?", view=view)
async def button5_callback(interaction):
await ctx.send("role added!")
button5.callback = button5_callback
button1.callback = button1_callback
view = View()
view.add_item(button1)
view.add_item(button2)
view.add_item(button3)
await ctx.send("What role will they receive?", view=view)```
and before sending the response "What role will they receive?"
This is going to get a bit trickier than you expect
So if you're 100% sure you're up for it I can tell you
Otherwise best to rethink
I'm up for it
sorry If I'm a bit slow or ask questions though 😭
!d discord.ext.commands.RoleConverter.convert
await convert(ctx, argument)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
am I able to dm you, because I'm really confused? :
I would prefer we keep things here
But you basically using the RoleConverter to parse a Role
BTW this is what discord.py uses under the hood when you do : discord.Role
If it's inside an interaction you may have to construct a mock context from interaction
are you able to give me an example of what it would look like in my code? Im still really confused
it's supposed to work like the bot asks a question > the member gets pinged/id is sent and bot recognizes that as the person they are going to be adding or removing roles from
how to do code like this:
def shared_cooldown(rate, per, type=BucketType.default):
cooldown = Cooldown(rate, per, type=type)
def decorator(func):
if isinstance(func, Command):
func._buckets = CooldownMapping(cooldown)
else:
func.__commands_cooldown__ = cooldown
return func
return decorator
but for app_commands?
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
@terse coyote ^ just a simple decorator
^
IndentationError: expected an indented block
``` uhh error...
here code:
```@client.event
async def on_guild_join(guild):
print(f'Bot has been added to a new server: {guild.name}')
print('List of servers the bot is in: ')
for guilds in bot.guilds:
print(guilds.name)```
AH
Hmm werid
why are my commands not working when my event is ?
^ , or the event is blocking
@bot.event
async def on_message(message):
if message.channel.id == 1060675394585505904 and not message.author.id == bot.application_id: #use ur channel id
try:
headers = {"Authorization": api_key}
params = {"user_id": message.author.id, "message": message.content}
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get("https://v6.rsa-api.xyz/ai/response", params=params) as resp:
json_response = await resp.json()
message1 = json_response["message"]
msg = await message.reply(message1)
except Exception as e:
msg = await message.reply(e)
await bot.process_commands(message)
``` have this still doesnt work
look where you're processing commands
auto indents fked up
(inside the if statement)
Send stop signal to a process
Loop should close gracefully
Depends from where you wanna do that
i cant define bot with a function
but i can define bot with class, but __init__ cant be async
anyone has any clue on how to work it out?
i did some research on OOP but still has no clue
huh
!d discord.ext.commands.Cog.cog_load
await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
New in version 2.0.
but if i use it in a class
the function will become a method
You use this in a Cog subclass
Method is just a function bound to object
test1 is called a Cog subclass in this case?
i thought Test is the class?
Yes
Why can't class be a subclass lol
Your OOP knowledge is probably not well organised, I advise to take additional course to settle things
💀 ok
are there any recommended courses?
corey's yt tutorial
I can't recommend any concrete ones, but you can search on resources like udemy, stepik and !resources
Hey sarth
yo👋
yeah
been screwing my bot for 1 year and its still ded
We're currently making bobux bot
We have await is_stupid(...), BadModal, Girlfriend.AMONGUS and other cool stuff
💀
is_stupid
And yeah we have whole user_insults.json
my man is building terminator on discord 💀
There are 5 of us
maybe not directly related to discord bots (but i want my bot to send the image) , but my images from this hosting service are not embedding into discord. what may be the reason and can i fix it?
https://live.staticflickr.com/65535/48378381527_aa3c6a39a4_o.png
I am being rate limited with discord's api
stop using replit
then you're making too many requests to the api
How can I reduce the requests?
@vale wing Hello little help sorry explain:
there "why" same list server , list server... is bad example "list server: hola server, como server , etc"
code:
embed.add_field(name="List Server", value=f"{guilds.name}")```
why are you adding a field for each guild then
yeah, but no idea much sorry.
how field idea example:
List Server:
Hello server
como server...
you should make a string with the guild names; ```py
", ".join(g.name for g in client.guilds)
oh but is no is json?
sorry is python lol.
okay sigh.
hmm moment think,,,
i see but no cant explain sorry, i am no good.
i see found search google
are u auto syncing all cmds?
maybe is "value=self.create_list(top_users, [f'<@{user}>' for _, user in top_users]),"
idk.
lol
Bros making nuker or something
embed.add_field(name="List Server", value=","(guilds.name for guilds in client.guilds))
TypeError: 'str' object is not callable
You don't put for loop into string Lmao
Yeah but no sorry i am no good sigh.
embed.add_field(name="List Server", value=(guilds.name for guilds in client.guilds))
i see think remove ","
I recommend learning python further
That's only if your calling arg in function
yeah already but i am no professional
but i am little .
This is basic python bro…
Okay.

But yea your learning
Ye.... new to discord.py
Unless your using Replit I thought it's impossible to be rl
Hmmm...
I am not.
i will fix it
hmm think no solution lol.
Are you using bot or client
I think enabling logging will show what requests you make and how often, try that
is client.
(yeah is client.event)
"client = commands.Bot(command_prefix="&", intents=intents)"
It's fixed now
@severe mural can you please explain what exactly your problem is? If you are struggling to talk in English just use translator (you speak spanish right?)
Glad to hear
yeah, no problem there example:
Correct
:
List Server:
my Server,
Server Husho, etc...
incorrect
:
List Server:
my Server,
List Server:
Server Husho... etc
Problem there code look:
Just put server name to field name and server description to field value
Hmm
for guild in guilds:
embed.add_field(name=guild.name, value=guild.description, inline=False)```
Dunno if in dpy they've kword only
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
i see.
Too bad
maybe is example: Value to description.
In disnake everything's better
!d disnake.Embed.add_field
add_field(name, value, *, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
Yeah love them being positional
Example I provided does that
yeah moment check think complicated.
ah guilds.description do not exist.
or yes, maybe but error " expected an indented block"
Everything except modals 💀
💀
!d discord.Guild.description
The guild’s description.
It does
Indents issue, make sure to indent your code properly
Nextcord modals >
Nextcord has best modals you say?
yeah....
Yessir
I've used them multiple times flawless
Idk seem similar to disnake ones except they assign them as attributes
A Python wrapper for the Discord API forked from discord.py - nextcord/modal.py at master · nextcord/nextcord
What's that?
Project some regulars here are involved into
Wouldn't this send multiple embeds?
modal = Modal(...)
results, m_inter = await modal.wait()```
ewwww
Nextcord cleaner don't lie
yeah
there last is list server
there is correct and error: #discord-bots message
listGuild = []
for guild in client.guilds:
listGuild.extend(guild.name)
Then all you do is use listGuild variable in value
Hmmm
last there is value=?

example "value=(listGuild))"
lol.
maybe
@slate swan wtf
Imho having consequential parts of code in different places is bad code design and all libraries actually do that for some reason
Simple answer...
guild_names=""
for guild in client.guilds:
guild_names+=guild.name +"\n"
embed.add_field(name=...,value=guild_names)
user_log = await guild.audit_logs(limit=1, action=action).get()
How?
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guild’s audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
Just use the default example? ^^^^
?
Error:
AttributeError: 'async_generator' object has no attribute 'get'```
.
What about it?
Doesn't fit
Why not
await audit_ch(guild, discord.AuditLogAction.role_create)
And why not just use anext like the other person suggested if you don't want to do an async for loop
I am simply callbacks hater
user_log = await guild.audit_logs(limit=1, action=action).get()
return user_log.user```
Or flatten
what
That is a thing right
When was it outdated
What should I do? How to update?
I'm not talking to you
Was changed in 2.0.0a
So many people have given suggestions of what to do, all valid, why do you keep ignoring them?
Or that's not builtin
I don't understand how to update
Screw them I am disnake user
:/
No one told you to update
And what then needs to be done for the code?
literally like 3 people have answered
Consider actually reading the messages people send.
I read, but I don’t see anything other than sites
.
.
.
Like 4 different ways you could do it
How will this help me?
so have you read it?
Yes
Have you used a for loop before?
I highly recommend at least knowing some python before trying to make a bot
I know python, it's just difficult to understand the meaning of words through a translator
bot.load_extension(f'cogs.{file[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
read the error
How to turn on?
just add the term await in front of it
but really learn english before learning python
everything is going to be clear after that
or memorise the meaning of certain term in python
Ok..
Is the function async?
No
I know that "await" should be written with "async"
But the code worked on another PC
No "await"
Show the full code
What does the read line say
if file.endswith('.py') and not file in ["config.py"]:
bot.load_extension(f'cogs.{file[:-3]}')
print(file[:-3])```
cog loading is now async
Why can't I use "@bot.command()"? Could this be because I used a bunch of "@bot.event"?
My "@bot.event":
on_guild_channel_update
on_member_join
on_guild_channel_create
on_guild_channel_delete
on_guild_role_create
on_guild_role_delete
on_guild_update
on_guild_role_update```
there's no thing like bot.message
Ouch
@bot.command()*
Sorry
!intents you need message_content intents for that to work
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.
No
My code:
async def test(ctx):
await ctx.send("Text")```
Bot ignores
...
Test code
your code will not work without that intent.
atleast read what the embed says
My code:
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="pm.", intents=intents)
bot.remove_command('help')```
the code for commamd should be above bot.run
Yes
async def test(ctx):
await ctx.send("Text")
bot.run(token)```
can you show your full code
!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.
Heyoo, just a quick question:
Im coding a Bot thats checking Ports. Its working. Now i want it to loop every minute but i dont want to use the .sleep function because its blocking ressources (am i right there?).
Is it smarter to use a scheduler then or is ther a better way to solve that problem?
Only dm
from discord.ext import commands
import json
color_1 = 192
color_2 = 192
color_3 = 192
default_whitelist = [
]
black_list_bots = [
]
with open(r"cong.json") as f:
j = json.load(f)
token = j["token"]
prefix = j["prefix"]
intents = discord.Intents.default()
intents=discord.Intents.all()
bot = commands.Bot(command_prefix="pm.", intents=intents)
bot.remove_command('help')
#Code "@bot.event"...
@bot.command()
async def test(ctx):
await ctx.send("Text")
bot.run(token)```
do you have an on_message event
Yes
if yes, change .event on it to .listen()
with the brackets
async def on_message(message):
if not message.author.bot:```
1 min
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Thk
uuuh perfect, thank you for the tip ^^
What's code for command deleting
Like when i say !down it sends respond but deletes my message
!d discord.ext.commands.Context.message
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is “synthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").
Changed in version 1.1: Added the new `delay` keyword-only parameter.
How does one get the current track time / position for a playing mp3 in dpy/disnake?
does it require something jank like incrementing time since the start via cron or something and pausing on pause or something? That sounds awful, it'd be really cool if dpy/disnake just knows and can yield that info
Hi, I don't have much experience with logging module, but just setting up logging for disnake with a file loaded that file with 56 mb of stuff
are you logging debugs too?
Yes
it should be 56mb either way, unless you have tons of dependencies
it's not the task of a discord wrapper's job to control what your voice server is playing
the sole task is sending packets
read your voice server's docs to find out
I want to create toggleable chat filters for my bot. Basically it replaces a member's message with a completely different string when turned on...
Is it possible to edit another user's message with discord.py?
no
trying to setup custom context, getting discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'approve'
am i doing this wrong or something
async def approve(self, *args, value: str, **kwargs) -> discord.Embed:
return discord.Embed(description=f"{self.author.mention} {value}", color=discord.Color.green())```
```py
from objects.context import Context
@commands.command()
async def ping(self, ctx: Context):
await ctx.approve(value=f"Pong! {round(self.bot.latency * 1000)}ms")```
Uh, u do know that it isn't how you can change the commands.Context class right?
What if I want to create a webhook for the channel and send a translated message using it?
yeah you can send a webhook message
Okay, so how can I create one to mimic a user's profile (display name and avatar)?
I never done webhooks with the API
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
it has the arguments you need
Yo
I have made this event so that if a member id is saved inside the 'muffled' list, the member's message will be replaced with a webhook with the same display name and avatar that says the "muffled" text
@client.event
async def on_message(message):
if message.author.id in muffled:
webhook = await message.channel.create_webhook(name="Themis Message Filter", avatar=message.author.display_avatar)
await webhook.send(textmuffle(message.content))
I get an AttributeError
Attribute error to?
Traceback (most recent call last):
File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kiranira\Desktop\Coding\discord.py\themis\main.py", line 18, in on_message
webhook = await message.channel.create_webhook(name="Themis Message Filter", avatar=message.author.display_avatar)
File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\channel.py", line 587, in create_webhook
avatar = utils._bytes_to_base64_data(avatar) # type: ignore # Silence reassignment error
File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 612, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 598, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
AttributeError: 'Asset' object has no attribute 'startswith'
.display_avatar.url
it takes a string ( the url)
thanks
I remembered printing display_avatar, but idk what was the data type , but it returned url, idk if it was str 😂
It returns asset obj :0
is it possible to run 2 bots in one project ?
Running diff file from each terminal, yes
!e ```py
class Asset:
def str(self):
return "spooky"
asset = Asset()
print(asset)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
spooky
:0
Print the type 🗿
i mean this
from discord.ext import commands
client = commands.Bot(command_prefix="!")
bot = commands.Bot(command_prefix=".")
@client.event
async def on_ready():
print('The bot is ready')
@bot.event
async def on_ready():
print('The bot is ready')
@bot.command()
async def copy(ctx,server:discord.Guild):
await ctx.reply("**Copying...**")
guild = client.get_guild(server.id)
new_guild = await client.create_guild(name=guild.name, icon=guild.icon)
print("eheh")
client.run("token")
bot.run('token')```
Breh
Bro just create 2 several bots
Weird stuff
ofc the type will be Asset, but printing the object will always return the str
i want them to connect with each other
If you need interprocess communication embed API
Demn
don't this is bad in many ways
ok
Or whatever websocket on local machine
create a simple api or database integration to connect the bots
Seems legit
Same line raises another error
TypeError: startswith first arg must be str or a tuple of str, not bytes
Returning bytes like obj
Full traceback
!d discord.Asset.url
property url```
Returns the underlying URL of the asset.
Weird it's not bytes
:0
How do you use startswith and on what
Traceback (most recent call last):
File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kiranira\Desktop\Coding\discord.py\themis\main.py", line 18, in on_message
webhook = await message.channel.create_webhook(name="Themis Message Filter", avatar=message.author.display_avatar.url)
File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\channel.py", line 587, in create_webhook
avatar = utils._bytes_to_base64_data(avatar) # type: ignore # Silence reassignment error
File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 612, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 598, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
TypeError: startswith first arg must be str or a tuple of str, not bytes```
What is data and how do you get it
And why the heck do you check for a literal bytestring
A wait that's internal

Yea
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
@teal glade avatar=await user.display_avatar.read()
message.author?
Idk what is your user
It's for this event
If you know OOP you got what I meant
i know about this. i need to do general cooldown for all commands. when member uses 1 command, next command he can use after certain amount of seconds
Next command globally?
I only want to make one for every channel, so how do I check if a webhook was already made?
hey, i'm trying to run a python bot for discord, but the on_message function isnt working
import discord
import mysql.connector
client = discord.Client(intents=discord.Intents.all())
TOKEN = 'your_bot_token'
CHANNEL_ID = 'your_channel_id'
cnx = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database"
)
@client.event
async def on_message(message):
if message.content.startswith("!register") and message.channel.id == CHANNEL_ID:
accountname = message.content.split(" ")[1]
discordid = message.author.id
cursor = cnx.cursor()
query = f"UPDATE account SET reg_mail = '{discordid}' WHERE username LIKE '%{accountname}%'"
cursor.execute(query)
cnx.commit()
cursor.close()
await message.channel.send(f"{accountname}'s account has been updated successfully!")
client.run(TOKEN)
when I try the !register command in the designated channel nothing happens


