#discord-bots
1 messages ยท Page 163 of 1
@client.tree.command()
async def viewdb(ctx: discord.Interaction):
count = 0
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute("SELECT * FROM users")
result = await cursor.fetchall()
embed = discord.Embed(title='DB', description='')
for i in result:
count = count + 1
embed.description += f"\n{count} **<>** {i}"
await ctx.response.send_message(embed=embed, ephemeral=True)
im using this to see the db
Just a question, why are all colors in discord.Color functions? Why can't they just be a constant?
What
they are class methods
also colors class is just there to help u add colors its not really a dictionary to provide u colors so constants are not really needed
and cuz discord.Color.red() would make more sense than discord.RED
Not for chatGPT no
Hello
how to ping a role while sending an embed in the same message?
<@&ID>
It's all the same
how?
await interaction.response.send_message(f"<@&1045668908692164627> Donation Request From <@{interaction.user_id}>")
await interaction.response.send_message(embed=embed)```
when i use this, it only send the msg not the embed
oh okay
You can't respond using the InteractionResponse twice in the same interaction
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
oh, lemme check
!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
so i used ```py
await interaction.response.send_message(content=f"<@&1045668908692164627> Donation Request From <@{interaction.user_id}>", embed=embed)
but it isn't responding when i use the cmd
I try to delete data from my database with a command but I can't
def remove_verification(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "DELETE FROM verif WHERE guild_id =? AND role_id =?;"
cursor.execute(query, (guild_id, role_id))
cursor.close()```
@slash.slash(name = "delete_verification", description = "Delete verification and channel")
async def delete_verification(ctx, role_id):
guild_id = ctx.guild.id
guild = ctx.guild
if (not ctx.author.guild_permissions.ban_members):
await ctx.send(f"You are not authorized to use this command {ctx.author.mention}")
return
database_verif.remove_verification(guild_id, role_id)
channel = guild.find_channel('verification')
await channel.delete()
await ctx.send("The verification is removed successfully")
@slash.slash(name = "create_verification", description = "Create the verification and enter the id of the role to assign")
async def create_verification(ctx, role_id):
guild_id = ctx.guild.id
guild = ctx.guild
if (not ctx.author.guild_permissions.ban_members):
await ctx.send(f"You are not authorized to use this command {ctx.author.mention}")
return
if database_verif.get_verification(guild_id, role_id) is None:
database_verif.add_verification(guild_id, role_id)
channel = await guild.create_text_channel('verification')
embed = discord.Embed(title = "Verification", description = "Send `.verif` for access all channels.")
embed.set_footer(text=f"Verfication for {guild.name}")
await channel.send(embed=embed)
await ctx.send("Embed verification send")
else:
await ctx.send("The verification is already in place")```
you have to commit the changes to the database
self.con.commit()
and use aiosqlite really, sqlite3 will block your bot's actions
is good thanks.
Now how can I delete a channel with the channel name ?
when u realize chatGPT uses openai ๐
u can delete column not the values
u can set the values to null if u want
whats your point lmao
nothing xd
how wouuld i use or for something like if role or role2 or role3 in user.roles:
^ cause that way doesnt work
so idk how
this should work, if any of role1, role2, role3 in user.roles it will return True
any of em
i hope the user is a member object
if interaction.channel_id == 1045668910604754984:
if {bot.value} == 1:
await interaction.response.send_message(embed=embed, content=f"<@&1045668908692164627> Donation Request From <@{interaction.user.id}>")
return
else:
await interaction.response.send_message('You cannot use this command in this channel.', ephemeral=True, delete_after=5)``` the bot doesnt respond
@app_commands.command(name="ddonate", description="Sponsor A Giveaway!")
@app_commands.choices(bot=[
discord.app_commands.Choice(name="Dank Memer", value=1),
discord.app_commands.Choice(name="OwO", value=2),
discord.app_commands.Choice(name="Pokemon", value=3),
discord.app_commands.Choice(name="AniGame", value=4),
])```
it is alright in the code, here its not
u r using cogs?
yeah
show async def part
if {bot.value} == 1:
await interaction.response.send_message(embed=embed, content=f"<@&1045668908692164627> Donation Request From <@{interaction.user.id}>")
return```
when i use this, the bot doesnt respond, else it does
.
@app_commands.command(name="ddonate", description="Sponsor A Giveaway!")
@app_commands.choices(bot=[
discord.app_commands.Choice(name="Dank Memer", value=1),
discord.app_commands.Choice(name="OwO", value=2),
discord.app_commands.Choice(name="Pokemon", value=3),
discord.app_commands.Choice(name="AniGame", value=4),
])
async def ddonate(self, interaction: discord.Interaction, bot:discord.app_commands.Choice[int], prize:str, duration:str, winners:int, requirement:str = None, message:str = None):
gchannel = interaction.guild.get_channel(1045668910604754984)
embed=discord.Embed(
title="Giveaway Donation",
description=f"**Bot: ** {bot.name}\n**Prize: ** {prize}\n**Duration: **{duration}\n**Winners: ** {winners}\n**Requirement: ** {requirement}\n**Message: ** {message}",
color=0xff0000)
if interaction.channel_id == 1045668910604754984:
if {bot.name} == 1:
await interaction.response.send_message(embed=embed, content=f"<@&1045668908692164627> Donation Request From <@{interaction.user.id}>")
return
else:
await interaction.response.send_message('You cannot use this command in this channel.', ephemeral=True, delete_after=5)```
yeah, i tried
also remove {}
;-;
?
How can I get only 1 column in my database out of the 2 (I want to get the role_id according to guild_id)
i tried something like this
if FORole or GMRole or HCRole not in user.roles:
await ctx.response.send_message(f"You are not a coach", ephemeral=True)
but when i do it, it works except, if I do have any of the roles it still says the response.
Help me please
just return it
SELECT role_id FROM table WHERE guild_id=........
simple
On my file database_verif.py ?
if FORole in users.roles or GMRole in users.roles or HCRole in users.roles```
(or make a list for this roles).
select the role_id from the table and put the guild_id as condition
def get_role_id(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "SELECT role_id FROM verif WHERE guild_id =? AND role_id =?;"
cursor.execute(query, (guild_id, role_id))
result = cursor.fetchone()
cursor.close()
return result```
Is good ?
... bro u already know role id what's the query for then
ye that going to do it
role_list = [role1, role2, role3]
if role_list in user.roles:
๐คทโโ๏ธ
โคด๏ธ
^
remove role_id parameter xd
Where is the point of that?
My bot is on 99 servers and so I want to provide code that is up to par to pass the certification
.
UPDATE query :ducky:

Would easy-pil make my bot laggy etc if I made it public bot (using it for on_member_join image send
depends on how heavy the image work is
It's just 200kb image with a pfp avatar and some text on
pasting a image on a image is pretty heavy already ๐
use pil bro easypil for nubs
okie
pil is faster and maintenained regularly and huge community
Pil didn't work for me idk why lol
Oh
I'll try
skill issue 
easy pil uses pil in background
1 GB of RAM
4 GB of Disk Space
1 CPU Core
This enough to make bot run without lags or delay etc?
This is my host specs
@shrewd apex
how many servers? or users?
I mean I will make it a public bot so idk how many ppl would use it
should be fine ig for starters
show code xd
def get_role_id(self, guild_id : int):
cursor = self.con.cursor()
query = "SELECT role_id FROM verif WHERE guild_id =?;"
cursor.execute(query, (guild_id))
result = cursor.fetchone()
cursor.close()
return result```
i did if not in user.roles:
and when i do, it still says that i cant do it even if i have the roles
@somber sky
hmmmmmm
how did u create the table?
(guild_id,)
wait u just said code for verification stuff right so why are u still using a sync database?
I use a database to store each guild using the verification and the role id to assign once the verification is passed
print role id i think its a tuple
stll doesnt work.
lmao not my question at all
still
i said why are u using a sync db
what did u try?
if Coach_List not in user.roles:
await ctx.response.send_message(f"You are not a coach", ephemeral=True)```
Because I give you the choice to set up the verification and to remove it
try giving the user all 3 roles then try running the command
What is Coach_list
i did still didnt work
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
in doesn't work like that
what is the block (smthg) used to create a webhook?
wym.
do u know the difference between synchronous and asynchronous
!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.
oki!
You're check if a list is in another
I never really looked into it
thats what they suggested. I'm just trying to do this.
if FORole GMRole or HCRole isnt in the ctx.user then do something.
but if i do,
if FORole or GMRole or HCRole not in ctx.user.roles:
it doesnt work properly.
!e
wanted_roles = ["meow"]
user_roles = ["cat", "kitten"]
print(user_roles, wanted_roles in user_roles)
user_roled.append("meow")
print(user_roles, wanted_roles in user_roles)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | ['cat', 'kitten'] False
002 | Traceback (most recent call last):
003 | File "<string>", line 6, in <module>
004 | NameError: name 'user_roled' is not defined. Did you mean: 'user_roles'?
F
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
that doesnt really help lol
Hi I have problem when I want install discord for python. Can you help me please
It actually does if you read it
if FORole not in ctx.user.roles or GMRole not in ctx.user.roles or HCRole not in ctx.user.roles
It should be like this
Show the actual code
^^
No
The one that you did the
if FORole or GMRole or HCRole not in ctx.user.roles
Or the thing I showed it show be
Why don't you try it
how do i take the option's value? like by using which block
@app_commands.command(name="gaw", description="Ping for the giveaway.")
async def gaw(self, interaction: discord.Interaction, sponsor: str, message: str = None):
await interaction.channel.create_webhook(name={.sponsor})```
name = {.sponsor}
Show the code when you used that command
if FORole not in ctx.user.roles or GMRole not in ctx.user.roles or HCRole not in ctx.user.roles:
await ctx.response.send_message(f"You are not a coach", ephemeral=True)
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute(
'SELECT settransactionschannel FROM users WHERE guild = ?',
(ctx.guild.id, ))
data = await cursor.fetchone()
if not data:
pass
else:
channel = client.get_channel(int(data[0]))
if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
if any(role.name in nflRoleListNames
for role in ctx.user.roles):
await user.add_roles(teams)
await ctx.response.send_message(f"Signed {user.mention}",
ephemeral=True)
await channel.send(embed=signembed)
await user.send(embed=signdm, view=view)
async def button_callback(interaction):
view.stop()
await interaction.response.send_message(
"Successuflly Confirmed Sign.", ephemeral=True)
await user.add_roles(teams)
button.callback = button_callback
async def force_callback(interaction):
view.stop()
await interaction.response.send_message(
"Succesfully Removed Role.", ephemeral=True)
await user.remove_roles(teams)
force.callback = force_callback```
That's not how strings works
wdym
!f-string
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
ah ic
Or literally just pass the variable in
how to get the avatar url of the user mentioned?
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
^ @naive briar
I'm trying to understand what you're trying to get from it
if FORole or GMRole or HCRole isnt in the author then send you are not a coach.
If any of those are i author which is stated in the image, then do the rest of the code.
You're checking if the user has all of the roles, is that what you're trying to do?
!e
roles = (0, 1, 2)
print(0 not in roles or 1 not in roles or 2 not in roles)
roles = (0, 1)
print(0 not in roles or 1 not in roles or 2 not in roles)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | True
no.
im checking if it has any of the roles
sponsor: discord.Member
avatar = discord.sponsor.avatar
is it going to work?
im checking if it has any of the roles. If it doesn't have any of them then send you are not a coach.
would if any(role in [FORole, GMRole, HCRole] not in ctx.user.roles): work?
no lol
#1056508884761727046 can you help me there?
!e
wanted_roles = (0, 1, 2)
roles = (0, 1, 2, 3, 4)
print(any((role in wanted_roles for role in roles)))
roles = (0, 1, 3, 4)
print(any((role in wanted_roles for role in roles)))
roles = (3, 4)
print(any((role in wanted_roles for role in roles)))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
003 | False
Just keep testing until you get what you want ๐คท
how would i make it where if its not in roles
if (any((role not in [FORole, GMRole, HCRole] for role in ctx.user.roles))):```
Can someone help me please
How would I make a whitelist command? Pretty much,
The bot will leave the server if it is not whitelisted. If it whitelisted by doing /whitelist guildid, Then it wont leave the server.
@bot.event
async def on_message(ctx):
user = ctx.author
if ctx.channel.name != "verification":
return
if user.bot:
if not ctx.embeds:
await ctx.delete()
elif not user.bot:
if ctx.content != ".verif":
await ctx.reply("Deleting because it's not .verif")
time.sleep(3)
await ctx.delete()
if ".verif" in ctx.content:
guild_id = ctx.guild.id
role_id = database_verif.get_role_id(guild_id)
await ctx.author.add_roles(role_id)
embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
embed.set_footer(text = f"Added for {ctx.guild.name}")
await ctx.reply(embed=embed)
time.sleep(3)
await ctx.delete()```
The add_roles method needs discord.Role instance
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
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:
The last time I used asyncio.sleep it didn't matter how long I ran it for more than 0.5s
Your bot won't be being to do anything else in that 5 second if you use time.sleep
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
Oh ok
I still can't do it
@naive briar
What's the problem then
I literally just said
The roles argument needs to be a role object or literally any object with id attribute
@app_commands.command(name="avatar", description="see avatar")
async def avatar(self, interaction:discord.Interaction, member: discord.Member):
avatar = member.avatar_url
await interaction.response.send_message(avatar)```
doesnt give any output
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Where did you get this code, it's outdated for like 7+ months
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
oh..
so like
@app_commands.command(name="avatar", description="see avatar")
async def avatar(self, interaction:discord.Interaction, member: discord.Member):
avatar = member.avatar_url
await interaction.response.send_message(avatar)```?
wait uhh not that
I do not understand 
avatar = discord.member.avatar```??
You need an instance
wdym
Yes, I understand.
Just get a role id from your database or whatever, use get_role method or wrap it in discord.Object, then pass that to add_roles
roleid = 0
role = discord.Object(id=roleid)
await member.add_roles(role)
Also sqlite3 is blocking
!pypi aiosqlite
role_id = database_verif.get_role_id(guild_id)
role = discord.Object(id=role_id)
await ctx.author.add_roles(role)``` ?
@naive briar
https://paste.nextcord.dev/?id=1671885072465419
The timeout time is 1 hour to muchm can someone say why?
Just test it
What does timeout time is 1 hour to muchm mean
If i timeout a user for 1 hour the bot timeouts him for 2 hours
datetime.fromtimestamp(min(int((nextcord.utils.utcnow() + timedelta(days=28)).timestamp()),int((now + timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).timestamp())))
What is this abomination
@commands.command()
async def some(self, ctx) -> None:
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(f'Synced {len(fmt)} commands.')```
nothing happens when i execute the cmd
self.bot
not ctx.bot xd
oh
Help please
@bot.event
async def on_message(ctx):
user = ctx.author
if ctx.channel.name != "verification":
return
if user.bot:
if not ctx.embeds:
await ctx.delete()
elif not user.bot:
if ctx.content != ".verif":
await ctx.reply("Deleting because it's not .verif")
await asyncio.sleep(3)
await ctx.delete()
if ".verif" in ctx.content:
guild_id = ctx.guild.id
role_id = database_verif.get_role_id(guild_id)
role = discord.Object(id=role_id)
await ctx.author.add_roles(role)
embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
embed.set_footer(text = f"Added for {ctx.guild.name}")
await ctx.reply(embed=embed)
await asyncio.sleep(3)
await ctx.delete()```
Only if people knows how to read tracebacks
database_verif whats this bro
import os
import sqlite3
class Verification:
def __init__(self, database_name : str):
self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
self.con.row_factory = sqlite3.Row
def add_verification(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "INSERT INTO verif (guild_id, role_id) VALUES (?, ?);"
cursor.execute(query, (guild_id, role_id))
cursor.close()
self.con.commit()
def get_verification(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "SELECT * FROM verif WHERE guild_id =? AND role_id =?;"
cursor.execute(query, (guild_id, role_id))
result = cursor.fetchone()
cursor.close()
return result
def get_role_id(self, guild_id : int):
cursor = self.con.cursor()
query = "SELECT role_id FROM verif WHERE guild_id =?;"
cursor.execute(query, (guild_id,))
result = cursor.fetchone()
cursor.close()
return result
def remove_verification(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "DELETE FROM verif WHERE guild_id =? AND role_id =?;"
cursor.execute(query, (guild_id, role_id))
cursor.close()
self.con.commit()```
there is no database_verif????
If
nvm
query = "SELECT role_id FROM verif WHERE guild_id =?"
return result[0] try this i think it's going to return tuple
The ; at the end of the query ๐
@shrewd fjord can you help me?
good job xd
!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 would i make an emoji through a command?
creating a emoji u mean?
ye
Eh
tf
!d discord.Guild.create_custom_emoji
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.
thanks
oh demn they changed it?
hello, this error means discord py isn't installed?
nah bro
a variable named bot u r using not even defined
Why i am not able to chat in voice channels
Most basic error you could've get
import discord
from discord.ext import commands
@bot.tree.command(name="ping", description="Show the bot's ping in ms")
async def ping(inreraction: discord.Interaction):
bot_ms = round(client.latency * 1000)
await interaction.response.send_message("Pong!", bot_ms, "ms")
@bot.event
async def on_ready():
await client.tree.sync()
print("Bot online")

this is my code
() are missing?
How do I delete the embed sent by my bot along with my message ?
client not even defined brooo
or bot.tree.commands?
Voice verification is missing probably, if you're talking about this server
also bot and client both are same lmao
I don't see where bot is defined in this code
message = await ctx.send(some message)
await message.delete(delay=float)
TypeError: startswith first arg must be str or a tuple of str, not bytes
ahhhh i forgot the line with prefix etc
what that mean
nvm i found why
!d str.startswith
str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
if ......startswith("!") like dat xd
error tells u everything ๐
But i cannot type in the chat box too
Idk why I'm getting rate limit error from discord
Replit?
Yh
replit is like so many users use the same ip
and thus get ratelimited
need it? 
take or ๐ซ
@steel mango ๐
Nope I don't need
:((
verify
I don't see where this is related to this channel
i dont get it what does that have to do with an emoji
voice verify
i did it
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=">",intents=discord.Intents.all())
@bot.tree.command(name="ping", description="Show the bot's ping in ms")
async def ping(inreraction: discord.Interaction):
bot_ms = round(client.latency * 1000)
await interaction.response.send_message("Pong!", bot_ms, "ms")
@bot.event
async def on_ready():
await bot.tree.sync()
print("Bot online")
bot.run(token)
why application isn't responding
what's wrong with what i did?
You are using a bot but you are using client.
Read the error
You've defined bot, not client
vvoicechat 0
iinthe chat box, it says
you do not have permission to send messages to this channel
I changed all the bot into client but it still doesn't work
now interaction error
yes ty
C++ bots are good?
๐
Huh
someone can tell me what's the difference between : app_commands.command, client.tree.commands and bot.slash_command
do they do the same thing or there are differences
bot.slash_command is outdated
okay and app_commands.command?
Isn't I can make a bot in c++ ?
Yes, and what about it
@commands.command()
async def sync(self, ctx) -> None:
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(f'Synced {len(fmt)} commands.')```
not syncing
!d discord.ext.commands.Context.bot
The bot that contains the command being executed.
for me?
Any exceptions
when i do s!sync no response and no error
@client.tree.command(name="say",description="Say whatever word you want")
async def say(message, interaction: discord.Interaction):
await interaction.response.send_message("U asked me to say", message)
i don't understand this error
Is it good?
Probably, C++ is faster but you need to manage the memory that your program used yourself
Switch the argument position
Interaction always comes before other argument
not probably, it's actually faster xd
problem with guild params
it all started not working after the webhook thing
i switched the arg position
@client.tree.command(name="say",description="Say whatever word you want")
async def say(interaction: discord.Interaction, message: str):
await interaction.response.send_message(f"U asked me to say, {message}")```
try this
remove self
also
message: str
this
ahh ye forgot
Every argument in slash command callbacks needs a type annotation
(or type hint)
You're using the fstring incorrectly btw
is there any other way to sync slash commands?
why?
nono, he was right i edited it
oh
can u help me?
Wdym manage memory
How to specify the type of the argument in the arguments of a command.
Example :
@client.command()
async def say(ctx, message, time):
for i in range(times):
await ctx.reply(message)
it will return a TypeError because the arg times need to an integer. But when I do
(ctx, message, int(time)): ```
it returns a SyntaxError
please help me I'm lost ๐ญ
type hints
@bot.command()
def foo(ctx: commands.Context, arg: str): ...
@bot.command()
def bar(ctx: commands.Context, abc: int): ...
just because we're in the context of dpy does it try to convert the arguments to the given type, normally this is just used for linter/documentation and doesn't do anything at runtime
so in my case time: int ?
sure
it can raise an error if you don't provide a valid integer when you execute the command though
no problem
yes ill have to manage the error later with a try: expect
no, you have to use an error handler
what is that?
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.11)").
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").
Changed in version 2.0: The traceback is now logged rather than printed.
ah I know that
@bot.event
async def on_message_delete(ctx):
guild_id = ctx.guild.id
channel_send = database_log_message.get_channel(guild_id)
embed=discord.Embed(title = f"Message deleted in {ctx.channel}".format(ctx.channel), description = f"{ctx.author.name} Message deleted", color=discord.Color.dark_purple())
embed.add_field(name="Message :",value=ctx.content, inline=False)
embed.add_field(name = "Account created :", value = ctx.author.created_at)
await channel_send.send(embed=embed)```
You can help me please ?
what's database_log_message?
import os
import sqlite3
class LogMessage:
def __init__(self, database_name : str):
self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
self.con.row_factory = sqlite3.Row
def add_channel_log(self, guild_id : int, channel_id : int):
cursor = self.con.cursor()
query = "INSERT INTO log_message (guild_id, channel_id) VALUES (?, ?);"
cursor.execute(query, (guild_id, channel_id))
cursor.close()
self.con.commit()
def get_channel_log(self, guild_id : int, channel_id : int):
cursor = self.con.cursor()
query = "SELECT * FROM log_message WHERE guild_id =? AND channel_id =?;"
cursor.execute(query, (guild_id, channel_id))
result = cursor.fetchone()
cursor.close()
return result
def get_channel(self, guild_id : int):
cursor = self.con.cursor()
query = "SELECT channel_id FROM log_message WHERE guild_id =?;"
cursor.execute(query, (guild_id,))
result = cursor.fetchone()
cursor.close()
return result
def delete_channel_log(self, guild_id : int, channel_id : int):
cursor = self.con.cursor()
query = "DELETE FROM log_message WHERE guild_id =? AND channel_id =?;"
cursor.execute(query, (guild_id, channel_id))
cursor.close()
self.con.commit()```
you can also use a local error handler for your command
@bot.command()
async def foo(ctx: commands.Context, arg: int):
...
@foo.error
async def foo_error(ctx: commands.Context, exception: commands.CommandInvokeError):
if isinstance(exception, commands.BadArgument):
...
you need a discord.TextChannel object in order to call send(), but you only returned a row from your sqlite database rather than getting the actual channel
Imagine
How to do it ?
after you get the channel_id, you can combine it with get_guild()/get_channel(), e.g. ```py
row = cursor.fetchone()
assuming self.bot = <your commands.Bot instance>:
guild = self.bot.get_guild(guild_id)
channel = guild.get_channel(row[0])```
you don't need the guild 
technically you dont, but its a bit more optimized than Client.get_channel() since the connection state doesnt store a global mapping of channels
discord/state.py lines 1580 to 1591
def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
if id is None:
return None
pm = self._get_private_channel(id)
if pm is not None:
return pm
for guild in self.guilds:
channel = guild._resolve_channel(id)
if channel is not None:
return channel```
Where should I use it ?
well thats your decision, either in LogMessage.get_channel() or directly in your on_message_delete event
def get_channel(self, guild_id : int):
cursor = self.con.cursor()
query = "SELECT channel_id FROM log_message WHERE guild_id =?;"
cursor.execute(query, (guild_id,))
row = cursor.fetchone()
guild = self.bot.get_guild(guild_id)
channel = guild.get_channel(row[0])
cursor.close()
return channel```
?
you need self.bot assigned in your init too
class LogMessage:
def __init__(self, database_name : str):
self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
self.con.row_factory = sqlite3.Row```?
yeah
also worth noting that fetchone(), get_guild(), and get_channel() might return None, which can lead to future errors if you dont handle them
well i said you needed to assign self.bot, otherwise LogMessage cant use self.bot...
But how to use it I don't see where to put it ?
Basic python class knowledge
I don't usually do classes
so you see how you wrote self.con = sqlite3.connect(...)? you've assigned the self.con attribute on your LogMessage instance, and that lets you use it in your instance methods (thats why cursor = self.con.cursor() works)
yes
so if you want to use your commands.Bot instance, you should assign it as an attribute on LogMessage, and then add a parameter to __init__() so you can provide that bot instance when you're creating LogMessage(...)
bot = commands.Bot(command_prefix = "o!", description = "OtroBot is best bot on discord")```?
perhaps this example will explain what's going on ```py
class MyClass:
def init(self, bot):
# ^^^ defines a parameter for the class
self.bot = bot # assigns the bot as an attribute of self
def do_something(self):
# Now all instance methods have access to `self.bot`
channel = self.bot.get_channel(1234)
print('channel name is:', channel.name)
After you create your bot instance, you can pass it as an argument to MyClass
bot = commands.Bot(...)
my_class_instance = MyClass(bot)
@bot.event
async def on_ready():
my_class_instance.do_something()```
or you can go through a guide to Object Oriented Programming like this one by corey schafer
https://www.youtube.com/watch?v=ZDa-Z5JzLYM&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc
In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.
Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...
W helper
Thanks Bro you is very good helpers
How to manage if no show is defined ?
@bot.event
async def on_message_delete(ctx):
guild_id = ctx.guild.id
if database_log_message.get_channel(guild_id) is None:
return
channel_send = database_log_message.get_channel(guild_id)
embed=discord.Embed(title = f"Message deleted in {ctx.channel}".format(ctx.channel), description = f"{ctx.author.name} Message deleted", color=discord.Color.dark_purple())
embed.add_field(name="Message :",value=ctx.content, inline=False)
embed.add_field(name = "Account created :", value = ctx.author.created_at)
await channel_send.send(embed=embed)```
row is None in get_channel method @slate swan
Thanks
Hello guys, I have a question: Is there a way to check if the message (sent by the user) is a reply to the bot? I've found "message.reference" but this checks if the message is a reply to anything, I want to check if the message is a reply to the bot only. I'm using PyCord.
message.reference will return a message object
!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.
wha-
You wanna check if a person replies to only your bot's message?
I remember doing something like this for my bot lemme get it
discord.Message.reference will return a MessageReference object on which you can use the author attribute on it and compare it to your bot using bot.user or you can even comparing their ids just by comparing message.author.id and bot.user.id
author == bot.user will automatically compare their ids so that's cool and all
there is no author attribute for discord.MessageReference object
that's sad
Okay so I cannot check if the user replies to my bot's message?
I saw ๐
My internet's too slow ๐ it simply loaded discord.Message docs for some reason
Well @loud flicker there is a hacky way for this
!d discord.MessageReference.resolved
The message that this reference resolved to. If this is None then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type DeletedReferencedMessage.
Currently, this is mainly the replied to message when a user replies to a message.
New in version 1.6.
Okay so what's this
This returns the message object to which the reply was done
you can do smth like if msg.reference.resolved.author == bot.user or smth
Okay, I'll see if it works:
But then u will first have to check if the msg.reference.resolved is an instance of discord.DeletedReferencedMessage, which, if True, won't have an author attr then
But a common way to do this (how I would have done) is by using the above thing and adding another condition (with an or), which checks if the message reference exists, the bot is mentioned but the bot mention isn't in the list of raw_mentions or smth
Hacky but would work
'NoneType' object has no attribute 'resolved'
elif any(word in blacklisted_words for word in split) and (message.author.bot == False) and message.reference.resolved.author == self.bot.user:
the message was never replied to any message
Okay, I'll try again
that is why message.reference is None
Can someone help me, I've been waiting for more than 24 hours
It worked! Thank you!!
I think u will get a faster response in their discord btw
Not many people use nextcord here. Many (if not most) prefer discord.py
It is possible the same
What is the issue u r facing?
@commands.command()
async def sync(self, ctx) -> None:
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(f'Synced {len(fmt)} commands.')``` doesnt give any output
Did you forget to load the cog?
nope
Donate Cog Loaded
Fun Cog Loaded
Giveaway Cog Loaded
Moderation Cog Loaded```
it is in fun cog
i want start bot command
How can I send a deleted embed as I do with deleted messages in an embed ?
it doesnt respond...
@maiden fable
Do u have an error handler>
Need more info
me?
You cannot send an embed in an... embed
Yea
nope
Can u do print(x.name for x in bot.commands) on startup?
So how do you send a deleted embed in a channel ?
๐ฟ
bot.commands?
Just access the embed using message.embeds and do await log_channels.send(embeds=message.embeds)
Depends on how you defining the bot
Yea...
@shrewd fjord a little help would be nice
Me here xd
<generator object on_ready.<locals>.<genexpr> at 0x00000203A42C43C0>
it printed that
Wifi is tooo slow lul
print(x.name for x in bot.commands)
if i use bot , it is not defined
U r printing x only i am pretty sure
print(x.name for x in client.commands)
(x.name for x in client.commands)
@client.event
async def on_ready():
print("Bot is online.")
print(x.name for x in client.commands)```ye
Hm
wait u r using slash commands?
yeah
If yes then it's walk_commands()
Okay I ain't familiar with slash commands, sorry
like?
client.walk_commands()
!d discord.app_commands.CommandTree.walk_commands
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
Wait ahh forgir
Bot.walk_commands is for prefix cmds
Forgot ๐ sarth always here to get my back
bot.tree.walk_commands()
<generator object on_ready.<locals>.<genexpr> at 0x00000276A6FC4430>
for py @client.event async def on_ready(): print("Bot is online.") print(x.name for x in client.tree.walk_commands())
..
Not the appropriate channel
You might wanna delete the message
17 xd
~ 24
Thanks
What does that mean
About 24
^
Ok guys thanks for sharing
But ot, so take it to one of the OT channels
Your opinion
uh ..
Your all helpful
@slate swan
its a generator object, which is not in action...
channel_send.send @slate swan
Yes my bad
i dont understand 
!e ```py
print(a for a in (1,2)) #generator object
print(list(a for a in (1,2))) # an actual iter
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <generator object <genexpr> at 0x7f444e5ec1e0>
002 | [1, 2]
ye
mhm
Thanks
so how do i fix
@bot.event
async def on_message_delete(ctx):
guild_id = ctx.guild.id
if database_log_message.get_channel(guild_id) is None:
return
channel_send = database_log_message.get_channel(guild_id)
if ctx.content == ".verif":
return
if ctx.embeds:
await channel_send.send(ctx.embeds)
embed=discord.Embed(title = f"Message deleted in {ctx.channel}".format(ctx.channel), description = f"{ctx.author.name} Message deleted", color=discord.Color.dark_purple())
embed.add_field(name="Message :",value=ctx.content, inline=False)
embed.add_field(name = "Account created :", value = ctx.author.created_at.strftime('%d %B %Y at %H:%M'))
await channel_send.send(embed=embed)```
what?
your generator?
ctx.content is None
are you aware of difference between a generator and a list comprehension?
@commands.command()
async def sync(self, ctx) -> None:
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(f'Synced {len(fmt)} commands.')```
it doesnt sync, this was my problem
Where ?
first field
I don't see where to put it
he is saying the message content is empty
You are tryna send the deleted embed to the log channel, so there is no message content
I don't see ๐ฆ
Kk last one so how old
No idea
I am bad at guessing ages
Just give yo opiniob
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
if ctx.content is None:```?
use == instead
Sure
Please no
is is better here
consistency
PEP 8 crying in a corner
use case
if not ctx.content would be better in that case since they use if <trueish> format in their code.
If i want to timeout the user for 1 hour the the timeout will be 2 hours
I can't do it
not appropriate to this channel but https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee537574(v=office.14)
thanks
for further questions
which channel should i go to ?
first thing to do is google your problem
thats what i did, this was the first link that came up
I have a modal issue. if i comment out this section of my modal child class ```py
repo = discord.ui.Select(
options=[
components.SelectOption(label="Project MMO", value="Project-MMO-2.0", default=True),
components.SelectOption(label="AugmentsBot", value="AugmentsBot", default=False)
],
row=0
)
the modal works fine. When it's in though, i get `discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (4,).`
i'm not sure what i'm doing wrong here
My other two fields in the modal are of type TextInput. They work fine.
you can't have a select inside a modal
ah. that makes sense then. is there another way to have a set of options the user selects from in a modal?
I don't think so
sadly not, only possible thing in a Modal for now is getting text inputs
you could utilise that ๐คทโโ๏ธ
๐ค okay. i might just have separate commands for my options then. i only have the two so far.
Can someone help #1056624907083063347
Discord already provides a timeout slash command... why reinvent the wheel?
to make it even more flexible, it will also later be connected to a system of automatic penalties
it's too complicated
?
if it was me I'd use it like 3d4h6m (i.e. 3 days 4 hours 6 minutes) with string slicing
But i make it more user friendly
maybe you can filter out some useless stuff from the code
and what if all the duration fields are left empty
they are replaced by 0
someone know how can use cogs in the correct way
how are you currently using them?
i saw a few guides and tutorial but no one works correctly
i have the main.py and a cog for embed
are you getting any errors? what makes you think that you aren't using them correctly?
no errors, when i try to run a command the console says that command don't exists
!paste can you send your code please?
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
send your entire code please
here are the docs and an example if you need them:
https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
https://gist.github.com/pinheaded/ac880263084a65b8d2f769c1fa46a3d7
otherwise I'm not really sure what you need help with
thanks
What is the @bot.event of the members who already join ?
!d discord.Guild.members
property members```
A list of members that belong to this guild.
there's no event that gets dispatched to get every single member inside a guild... otherwise it'd get dispatched infinitely in an infinite amount of times
@bot.event
async def on_member_join(message):``` Is good no ?
that will get dispatched every time a new member joins the guild, and it's not the correct signature
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
How would I make a whitelist command? Pretty much,
The bot will leave the server if it is not whitelisted. If it whitelisted by doing /whitelist guildid, Then it wont leave the server.
Hello!
I was wondering if it was possible to restart the bot from within itself without having to kill the python script then re-running it as this is causing mounds of issues on my server.
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
how would i do the whitelist part
simple as a list containing whitelisted guild IDs
yea but like it would be through a command
/whitelist serverid
then it would go in the list
idk how to do that
whitelisted_guilds.append(serverid)
pretty simple
Is the repl.it good site for discord.py?
i use it but its not good lol
Why?
bot goes offline a lot
My bot is working 9 months
I want to make discord bot with discord.py i made already 1 with discord.js
Is discord.py better than discord.js?
They both boil down to the same thing really
Depends what language you're better versed in
dpy provides you with a lot of additional features like prefix command handling, better app command implementation and a bunch of utils ๐บ
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
Why do I keep getting this error?
nextcord.opus.load_opus()
TypeError: load_opus() missing 1 required positional argument: 'name'```
I tried putting "opus" inside of the () but it gives me the error:
OSError: dlopen(opus, 0x0006): tried: 'opus' (no such file), '/System/Volumes/Preboot/Cryptexes/OSopus' (no such file), '/usr/lib/opus' (no such file, not in dyld cache), 'opus' (no such file), '/usr/lib/opus' (no such file, not in dyld cache)
You need to give it the name of the Opus library file to be loaded
And that file has to exist, hence the second error
What does the library file typically named?
nextcord.opus.load_opus(name)```
Loads the libopus shared library for use with voice.
If this function is not called then the library uses the function [`ctypes.util.find_library()`](https://docs.python.org/3/library/ctypes.html#ctypes.util.find_library "(in Python v3.11)") and then loads that one if available.
Not loading a library and attempting to use PCM based AudioSources will lead to voice not working.
This function propagates the exceptions thrown.
Warning
The bitness of the library must match the bitness of your python interpreter. If the library is 64-bit then your python interpreter must be 64-bit as well. Usually if thereโs a mismatch in bitness then the load will throw an exception...
Same error, it does exist though thats the thing. Its on my system according to homebrew
Apprently its in my local/lib. Cant move it though. Tried doing this but says it doesnt exist.
nextcord.opus.load_opus('/usr/local/lib/opus')
Mac. Its fine.
See, its in the local/lib but it doesnt detect it some reason
Have you tried omitting the function call altogether and letting the library use ctypes to find it for you?
Tried doing ```py
import ctypes
libopus_name = ctypes.util.find_library('opus')
if libopus_name is not None:
discord.opus.load_opus(libopus_name)
else:
print('Could not find libopus library')```
But printed could not find it
Try ctypes.util.find_library('libopus')
Oh no it shouldn't matter
Ctypes wants that omitted anyway
Huh this is weird then if it does 100% exist
I'm not entirely sure where to go next
Have you tried asking someone in the Nextcord discord?
Well, didnt work because it gave be the couldnt find opus. ๐ข (root cause)
I shall do that now.
Yeah, sorry I couldn't help more
Nw, thanks for trying tho:)
How would I go bout calling a list from another file?
I did import examplelist, and then I did
narr = examplelist.get(ctx,key) but then I get a warning saying that examplelist has no attribute "get"?
I want to organise my list by having it in another file
To ping a channel you use the format <#ID_HERE>
Lists don't implement a .get method since they are not mapped objects
Dicts do, because k maps to v so dict.get(k) returns v
๐ _ _
Ah thanks
class enum.Enum```
*Enum* is the base class for all *enum* enumerations.
enumsssss
TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents' Why do I need this?
what are intents needed for? I copy the exact code from The youtube tutorials and I have a problem running
!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.
from enum import Enum
Now I get another error
its just error on error for no reason
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')```
channel = client.get_channel(343944376055103488)
channel.send(text, file=file)
'NoneType' object has no attribute 'send'
like wtf
its literally code I coppied word for word from a tutorial lmao
well the tutorial is months old to be fair
Im just trying to have my discord bot send a message on the server
whenever someone types
and another whenever I use a command word
but their 2 seperate practice
import discord
BOT_PREFIX = ("?")
TOKEN = ""
intents= discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_message(message):
possible_response = ['yo Duke is lame foe on gang', 'Bruh This bot shit easy fr fr ong', 'I want milk mommy pweeeeeazeee']
username= str(message.author)
message(message.content)
await client.send(random.choice(possible_response))
client.run(TOKEN)```
this is my simple code
that gives me errors
Try this #discord-bots message
it's not just about the date
youtube tutorials are factually horrible
yeah dude its terrible I wish I know where to get actual information for learning discord bts
if you have python knowledge, just the API reference
else, get python knowledge, then check the API reference
not in the way of studying every class, just when you have for example a channel, but you don't know how to send a message, then you check the discord.TextChannel class in the API reference
the discord.py github page has examples, that's a start too
Well I dont have object oriented experience
not sure how valuable that is in this case
ok I'll check that out
that's what this is about
Okay well I'll go ahead and do a course on it
File "main.py", line 484, in join
VoiceCl = discord.VoiceClient()
TypeError: init() missing 2 required positional arguments: 'client' and 'channel'
wut
...
Every time you run the warn command it gets reset to 0
You might want to store the warns somewhere else
Like a database
You can do that but it'll get reset to 0 when you restart the bot
Create a dict and bind it to your bot instance
The key will be user ID the value the number of warns they have
bot = commands.Bot(...)
bot.warns = {}
Then whenever you need to add a warn for a user:
bot.warns[123] += 1
Where 123 is the user ID
How can i add cooldown on_raw reaction_add evet?
@sick birch what host do you recommend
explain more clearly
I made tickets in discord and my and users spam emojie
Bot automaticly made multiples channels
But if user didnt spam
Its work fine
Hey, when I do !rijal mufaddal, i dont even get a traceback, no message sends
@fiqhbot.command()
async def rijal(ctx, gh):
gh = ["Mufaddal"]
message = ctx.message.content
if str(message) in ghulat:
await ctx.send("e")
make a debounce
add them to a list, wait 5 seconds and remove from list
are your intents enabled
Yep
make a global list, add their user id to the list when they react, wait 5 seconds, then remove from the list
Hmm
and check if they try to react again but their id is still in the list, it shouldn't let them
try doing the command in dms
Nope, nothing
how do i put 2 images in the embed?
cause when i do this it only sends the bottom image
โ ๏ธ Requires 2.0 to use without webhooks
URL = 'https://www.google.com/'
IMAGE_1 = 'https://cdn.discordapp.com/embed/avatars/1.png'
IMAGE_2 = 'https://cdn.discordapp.com/embed/avatars/2.png'
# embeds must have the same url
# works with more up to 4 images on desktop
# does not show more than 1 on mobile
embed1 = discord.Embed(
title='TITLE 1',
description='DESCRIPTION 1',
url=URL # <<< same url as other embeds
)
embed1.set_image(url=IMAGE_1)
embed2 = discord.Embed(
title='TITLE 2',
description='DESCRIPTION 2',
url=URL # <<< same url as other embeds
)
embed2.set_image(url=IMAGE_2)
await channel.send(embeds=[embed1, embed2])
```https://cdn.discordapp.com/attachments/559455534965850142/908123289904357386/unknown.png
is make music bot and then error vine boom
clientException: ffmpeg.exe was not found.
what do
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
So do you have ffmpeg?
wow thank you
i tried isnatllint with pip, npm, importing it, adding a blank ffmpeg.exe file, but as of right nwow, I use replit (imgetting hardware anyways for it so dont lecture) so not sure how
so me is how install
you put it where you want to timeout the member?
Idk probably find the executable and upload it to replit
where can i find it
mm I'm not gonna waste my time teaching basic python sorry
idk Google it
You do know that's already a built-in command right
Those already exist
They are built in to discord
If you can't make something super special or better, don't bother
cool
Does anyone know why I can't use special characters for the ign command. Example: !ign Chelรณna
This is strange.. new feature?
Does it basically "combine" the two embeds?
it's existed for ages
No idea, jankiest api thing I've seen yet
Agreed..
Especially with it only sometimes working
Anyone please?
line 425, in ign
elo_rating = get_elo_rating(tier_and_rank)
line 384, in get_elo_rating
tier, rank = tier_and_rank.split()
ValueError: not enough values to unpack (expected 2, got 1)
I think I found it: def rank_to_number(rank):
Print out tier_and_rank. That variable might be "Unranked" which would cause the error
You mean for that specific user?
I changed this part and it worked:
def get_elo_rating(tier_and_rank):
# Set the ELO rating based on the tier and rank
if tier_and_rank == 'Silver 3':
return 1300
else:
return 1300```
I'm still wondering why 'tier, rank = tier_and_rank.split()' is causing issues when using special characters
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ['string']
002 | ['string', '1']
For this example 'รณ'
What's the issue it's causing
who pinged me 
Not me but hello
shawn
my bad
@somber sky
ah no worries it happens
There's no error message
And you're getting a guild named Member
It doesn't work doesn't help people understand your question either โ
I'd use the built-in timeout feature if I were you, adding/removing certain roles is an outdated way of muting members and a hassle for server admins to set up correctly
plus adding/removing roles is worse since it removes all the roles from the users and would require a db to store them all and assigning them after unmuting would require a lot more api calls
overwrites just change all other permissions to default and changes the mentioned one to false. Is there any way to leave the other ones as they are and ONLY work with the one mentioned?
@client.event
async def on_ready():
print("Bot is online.")
synced = await client.tree.sync()
await client.sync(guild=discord.Object(id=1045668908536954911))
print("Slash CMD's Synced" + str(len(synced)) + "Commands")```
nothing gets printed..
this is the code in main.py
You should be getting an error
Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using Client/Bot.run. More about that in ?tag defaultlogging.
It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging
but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.
why does only the last part of my code work? the full thing worked before, idk why it doesnt work anymore, heres my code ```py
import discord
import random
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
Insults = []
Insults.append("I bet your parents change subject whenever their friends ask about you.")
Insults.append("You aren't the dumbest person in the world but you better hope they don't die.")
Insults.append("You are the human equivalent of participation trophy.")
Insults.append("I envy those who've never met you.")
Insults.append("You've got two brain cells, and they're are both fighting for third place.")
Insults.append("Trees are tirelessly producing oxygen so your ass can complain, I think you owe them an apology.")
Insults.append("You're the reason why shampoo has instructions.")
Insults.append("I don't care what others say, I think you're great.")
Insults.append("I wouldn't want to be your mirror.")
Insults.append("You're like the end pieces of a loaf of bread. Everyone touches you but nobody wants you.")
Insults.append("You're not cute enough to be this stupid.")
Insults.append("You seem like the type of guy to wash his hand after a shower.")
Insults.append("I had 0 expectations of you and somehow I was still let down.")
Insults.append("You're the best pro-abortion argument I've ever met.")
Insults.append("I bet you drop common loop when defeated.")
Insults.append("You're the reason the power ranger say their colors everytime.")
Insults.append("I thought about you the other day, reminded me of taking out my trash.")
Insults.append("Someday youโll go far. And I really hope you stay there.")
Insults.append("Youโre the reason God created the middle finger.")
Insults.append("Iโm busy right now, can I ignore you another time?")
Insults.append("I hope your wife brings a date to your funeral")
Insults.append("Mirrors can't talk, lucky for you, they can't laugh either.")
Insults.append("Itโs impossible to underestimate you.")
Insults.append("Your face makes onions cry.")
goodbye = []
goodbye.append("Bye")
goodbye.append("bye")
goodbye.append("Cya")
goodbye.append("cya")
goodbye.append("GoodBye")
goodbye.append("goodbye")
goodbye.append("Goodbye")
goodbye.append("Adios")
goodbye.append("adios")
Values = [1, 2, 3, 4, 5, 6]
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.id in [491212588768821281, 650415406955102228]:
insult = random.choice(Insults)
await message.channel.send(insult)
@client.event
async def on_message(message):
if message.author == client.user:
return
if any(goodbyes in message.content for goodbyes in goodbye):
await message.channel.send("Bye, I hope to see you never")
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == "!Random":
await message.channel.send(random.choice(Values))
client.run('my discord token')```
only the !Random command works now idk why
the last event is going to override the first two
why don't you just put them all in 1 event
and why are you using .append to add every single item instead of just declaring the list with those items
its too long when i do that
client = aclient()
tree = app_commands.CommandTree(client)
@client.event
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
# cut off the .py from the file name
await client.load_extension(f"cogs.{filename[:-3]}")```
'aclient' object has no attribute 'load_extension'
what is aclient?
insults = [
"I bet your parents change subject whenever their friends ask about you.",
"You aren't the dumbest person in the world but you better hope they don't die.",
"You are the human equivalent of participation trophy.",
"I envy those who've never met you.",
"You've got two brain cells, and they're are both fighting for third place.",
"Trees are tirelessly producing oxygen so your ass can complain, I think you owe them an apology.",
"You're the reason why shampoo has instructions.",
"I don't care what others say, I think you're great.",
"I wouldn't want to be your mirror.",
"You're like the end pieces of a loaf of bread. Everyone touches you but nobody wants you.",
"You're not cute enough to be this stupid.",
"You seem like the type of guy to wash his hand after a shower.",
"I had 0 expectations of you and somehow I was still let down.",
"You're the best pro-abortion argument I've ever met.",
"I bet you drop common loop when defeated.",
"You're the reason the power ranger say their colors everytime.",
"I thought about you the other day, reminded me of taking out my trash.",
"Someday youโll go far. And I really hope you stay there.",
"Youโre the reason God created the middle finger.",
"Iโm busy right now, can I ignore you another time?",
"I hope your wife brings a date to your funeral",
"Mirrors can't talk, lucky for you, they can't laugh either.",
"Itโs impossible to underestimate you.",
"Your face makes onions cry.",
]
class aclient(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
"""await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id=1045668908536954911))
self.synced = True"""
print(f"We have logged in as {self.user}."```
alright thanks ill do that next time
yeah, discord.Client doesn't have a load_extension method
that's part of the commands extension
so discord.ext.commands.Bot has it
oh
Thanks man i put them all in one event and it worked, i appreciate your help
welcome, have a good day
so how do i implement it?
discord.ext.commands.load_extension?
you subclass Bot instead of Client... or implement the logic yourself
that's not a thing... it's a method of Bot
oh
Extension 'cogs.fun' raised an error: TypeError: object.__init__() takes exactly one argument (the instance to initialize)
class Fun(commands.Cog):
def __init__(self, bot: commands.Bot):
super().__init__(intents=discord.Intents.default())
self.bot = bot
async def setup(client):
await client.add_cog(Fun(client), guilds=[discord.Object(id=1045668908536954911)])```
super().__init__(intents=discord.Intents.default()) why are you calling that?
oh my mistake
I suppose that's the Client _init_
ye
my bad
so I ran the file, and it succeded but the slash commands aren't showing
are you syncing the tree?
ye
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id=1045668908536954911))
self.synced = True
print(f"We have logged in as {self.user}.")```
also uhh
@commands.Cog.listener()
async def on_ready(self):
print('Giveaway Cog Loaded')``` this doesnt get printed
uhh i gtg i will be back in 40 mins
How would I make a command where, if the guild ID you invite the bot to is not in a list then leave the server
@client.event
async def on_join():
if guild.id not in f.whitelistedservers:
await guild.leave()```
thats what i have its probably not even close. `f.whitelistedservers` is a file, and its imported at the top `import whitelistedservers as f`
The event is on_guild_join iirc
@tasks.loop(minutes= 30)
async def statscounter(self):
for key in self.serverstats.keys():
guild = self.bot.get_guild(int(key))
try:
server_stats = self.serverstats[str(guild.id)]
except KeyError:
server_stats = {}
category = discord.utils.get(guild.categories, name="STATS")
botcount = 0
membercount = 0
members = guild.members
textchannelscount = len(guild.text_channels)
voicechannelscount = len(guild.voice_channels)
for member in members:
if member.bot == True:
botcount += 1
else:
membercount += 1
users_text = f"Users: {membercount}"
bots_text = f"Bots: {botcount}"
channels_text = f"Text Channels: {textchannelscount}"
channels_voice = f"Voice Channels: {voicechannelscount}"
tier = f"Premium Tier: Level {guild.premium_tier}"
uc = guild.get_channel(server_stats['member_count'])
bc = guild.get_channel(server_stats['bot_count'])
tc = guild.get_channel(server_stats['text_count'])
vc = guild.get_channel(server_stats['voice_count'])
pt = guild.get_channel(server_stats['tier'])```
if uc.name != users_text:
await asyncio.sleep(1)
await uc.edit(name=users_text, category=category)
if bc.name != bots_text:
await asyncio.sleep(1)
await bc.edit(name=bots_text, category=category)
if tc.name != channels_text:
await asyncio.sleep(1)
await tc.edit(name=channels_text, category=category)
if vc.name != channels_voice:
await asyncio.sleep(1)
await vc.edit(name=channels_voice, category=category)
if pt.name != tier:
await asyncio.sleep(1)
await pt.edit(name = tier, category=category)```
whats wrong , it doesnt update the channels
get_channel takes an int; looks like you're passing str
are you sure the if statements are running as expected and have you set up logging though?
^
class aclient(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id=1045668908536954911))
self.synced = True
print(f"We have logged in as {self.user}.")
intents = discord.Intents.default()
client = aclient()
tree = app_commands.CommandTree(client)
bot = commands.Bot(command_prefix="s!", intents=intents, application_id='1056541924556816494')
@client.event
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
# cut off the .py from the file name
await bot.load_extension(f"cogs.{filename[:-3]}")
async def main():
await load()
await client.start(credentials.TOKEN1)
@tree.command(name="ping", description="Gives the bot latency.", guild=discord.Object(id=1045668908536954911))
async def self(interaction: discord.Interaction):
await interaction.response.send_message(f"Pong!")
asyncio.run(main())```
this all works fine... but cogs aren't loading
class Fun(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('Fun Cog Loaded')
@app_commands.command(name="ping", description="Gives the bot latency.")
async def ping(self, interaction: discord.Interaction):
await interaction.response.send_message(f"Pong!")
@app_commands.command(name="8ball", description="Gives you an answer.")
@app_commands.describe(question="What do you want to ask the 8ball?")
async def eightball(self, interaction: discord.Interaction, question:str):
responses = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
"Donโt count on it.", "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no.", "My sources say no.",
"Outlook not so good.", "Outlook good.", "Reply hazy, try again.", "Signs point to yes.", "Very doubtful.", "Without a doubt.",
"Yes.", "Yes โ definitely.", "You may rely on it."]
await interaction.response.send_message(f"**Question: ** {question}\n**Answer: ** {random.choice(responses)}")
async def setup(client):
await client.add_cog(Fun(client), guilds=[discord.Object(id=1045668908536954911)])```
@commands.Cog.listener()
async def on_ready(self):
print('Fun Cog Loaded')```
when i run the code, this does not print
can someone help me in #1056860471061393418
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**.
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
!d discord.ext.commands.Context.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") referenced by this context.
For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
alias
future: <Task finished name='discord-ui-view-timeout-160f5a8f4ed3d684e890407cd770847d' coro=<admin_role_select_role_test.on_timeout() done, defined at c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_new_v2_00\view.py:113> exception=NotFound('404 Not Found (error code: 10008): Unknown Message')>
Traceback (most recent call last):
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_new_v2_00\view.py", line 116, in on_timeout
await self.message.edit(view=self)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 1150, in edit
message = await self._state._interaction.edit_original_message(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 434, in edit_original_message
data = await adapter.edit_original_interaction_response(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 182, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message```
I have no idea where the error comes from
nextcord eewww
Are you able to help?
i think you are editing original message before sending any response
show your on timeout code
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_new_v2_00\view.py", line 116, in on_timeout
await self.message.edit(view=self)
class admin_role_select_role_test(nextcord.ui.View):
def __init__(self, ctx_or_interaction, *, timeout=20):
super().__init__(timeout=timeout)
@nextcord.ui.role_select(placeholder="Please choose a role", max_values=1)
async def on_select(self, select: nextcord.ui.RoleSelect, inter: nextcord.Interaction):
roles = select.values.roles
for role in roles:
print(role.id)
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT id FROM setup WHERE id = ?', (inter.guild.id,))
data_a = await cursor.fetchone()
if data_a is None:
await cursor.execute('INSERT INTO setup (id, access_one) VALUES (?, ?)', (inter.guild.id, role.id,))
await db.commit()
if data_a is not None:
if inter.guild.id in data_a:
await cursor.execute("UPDATE setup SET access_one = ? WHERE id = ?", (role.id, inter.guild.id,))
await db.commit()
eb = self.children[0]
eb.disabled = True
eb.placeholder = f"You selected @{role.name}"
reply = nextcord.Embed(title="Admin role has been set", description=f"The Admin Role is now \n"f"{role.mention}\n `{role.id}`", colour=config.blurple)
await inter.response.edit_message(embed=reply, view=self)
await inter.delete_original_message(delay=7)
async def on_timeout(self):
eb = self.children[0]
eb.disabled = True
await self.message.edit(view=self)
await self.message.delete(delay=5) ```
@somber imp
from docs, View doesnt seem to have message attribute? ๐ค
https://docs.nextcord.dev/en/stable/api.html#nextcord.ui.View
you need to set the message yourself after you send the view
are you doing that?
if you are doing it, then are you sending the view in an interaction response?
Yeah
Oh then do self.message.edit_original_message
And for delete to self.message.delete_original_message
given that nextcord is just a fork of discord.py, that sounds untrue
but why does the timeout take effect after the code has already been completed
Oh huh
That's weird
cap
I find pycord the best
without d.py there wouldnt even be nextcord
ur weird
Fr
same for pycoed lmfao
Nah mate. It's actually good
I used pycord
Yea lol
Yeah it executes the on_select completely, but the on_timeout still takes effect
Although pycord as pre alpha V3 rn that's a full rewrite
so is nextcord
its not lmfao
they just changed namespaces and made stuff wrose
nah, they are actually doing a rewrite in a private repo.
It's public now
gonna suck then lol
No it's actually a full rewite
is it? i left the server a while ago so wasn't aware
With that attitude, yes
i think it would be better
if dpy wasn't garbage nextcord wouldn't exist either
those repos were created back when d.py was discontinued
Nextcord released because dpy had stopped development
what does it have to do with what i said