#discord-bots
1 messages · Page 289 of 1
ok
i just do pip install discord
discord is a mirror package
i did discord and discord.py
Use discord.py instead
idk man i do it that way and it works
Hello, I'm OpenAI's AI. How can I assist you today?

is a concept that encourages the use of creative and innovative thinking to come up with new ideas and solutions. It is based on the idea that when we combine different perspectives and approaches, we can come up with creative solutions to problems.
!ban 1143114332230664252 selfbot
:incoming_envelope: :ok_hand: applied ban to @rose frost permanently.
XD
lmao
manual boarding and a bot msged
Would have been scary if it filled the boarding itself
fr
It would be more scary if he was not actually using ai to answer
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
New in version 1.5.
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable) ABC.
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
Why does the same code show 2 diffrent answer, down
i run it in vsc - incorrect
i run it in sublime text - correct
win 10
guys in nuking, do the bots have like perms to delete a server?
no nobody has except the owner
ok great
you need a code to delete the discord if you're the owner
what server are you nuking
no Im not nuking, just making a bot to counter nuke bots
nuking have a different meaning, but ok
is it somewhat similar to raiding? or Im mis-using it xd
i think the second lol
nuking is what nuke bot do
cause somewhat people use that word to like delete all of the things and spam messages
that's nuking ig
but anyways, most nuke bots cant delete sa server but they can make your discord/server lag wherein you cant make any changes into it
but is making a bot trigger a command in the console illegal?
the bot can change everything in a server, but can't delete it
if you're going against the discord rules, yes
is this considered self botting
ahh ok ok
If you mean you make bot do something from terminal it's perfectly fine
Selfbotting is automating non-bot account
wait i can't invite a bot without having admin in the server, right?
ok ok thank you
Manage server perm to be precise
i only need that?
Yeah
alr
I'm trying to get a reaction from the Button to make the bot send a message in a different channel. The code i have rn:
class Confirm(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, custom_id="click_test")
async def click(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('you clicked me!', ephemeral=True)
@bot.command()
async def test(ctx):
view = Confirm()
embed = discord.Embed(
title = "Test",
description = f"{bardata[0]}",
color = discord.Color.red()
)
await ctx.send(embed=embed, view=view)
await view.wait()
if view.value is None:
await ctx.send("ciao")
Don't really know how can i get the interaction from the Button to make send a message in a specific Channel.
which of the reaction command should be used for the reaction roles
@client.event
async def on_member_join(member):
channel = client.get_channel(1142743219860418569)
await channel.send("Welcome to the server")
that doesnt do
help me fix it pls
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
who?me?
yea
try client.listen
First, you should send codes as text. Second, you need the members intent to receive the on_member_join events
how?
!d discord.on_member_join
oh yea
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
Enable the members intent? 🤷
just type intents.member = True
With s
@naive briar what command of reaction role can be used for the reaction roles
What?
I just said members twice
there are a few on_reaction commands what is the one used for reaction roles
3*
Did you mean events?
And it's pretty obvious which will be used
there are raw and normal
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
Just check the message property of the reaction 🤷
an erorr message after if user is None is supposed to send when a incorrect username/id is provided. any ideas why it doesnt?
def check_message(m):
return m.author == interaction.user and m.channel == channel
reply = await interaction.client.wait_for("message", check=check_message)
id = reply.content
if id.isdigit():
user = interaction.guild.get_member(int(id))
else:
user = discord.utils.get(interaction.guild.members, name=f"{reply.content}")
if user is None:```
What error
an embed is supposed to send saying "incorrect user etc etc" but i get no errors in my console
Can you show your full code for this?
@client.command()
@has_permissions(kick_members = True)
async def kick(ctx,member: discord.member,*,reason=None)
await member.kick(reason = reason)
await ctx.send(f"{member} kicked!")
invalid suntax
embed = discord.Embed(title="New Ticket", description=f"Below please provide your traders **ID** or **username**", color=discord.Color.orange())
embed.set_thumbnail(url=interaction.user.display_avatar)
a = await channel.send(interaction.user.mention, embed=embed)
await interaction.response.send_message(content=f"Ticket **created** -> <#{channel.id}>", ephemeral=True)
def check_message(m):
return m.author == interaction.user and m.channel == channel
reply = await interaction.client.wait_for("message", check=check_message)
id = reply.content
if id.isdigit():
user = interaction.guild.get_member(int(id))
else:
user = discord.utils.get(interaction.guild.members, name=f"{reply.content}")
if user is None:
error_em = discord.Embed(title=f"Error", description=f"The user **ID**/**username** is invalie! Please **check** the user again", color=discord.Color.red())
error_em.set_thumbnail(url="https://cdn.discordapp.com/emojis/1125508039651381369.webp?size=240&quality=lossless")
error = await interaction.channel.send(embed=error_em)
await asyncio.sleep(2)
await error.delete()```
Can you print out user before the if user is None check
if i input an incorrect user it prints None
oh wait i fixed it now
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
How I can make the bot detect if. Channel created in a specific catagory?
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild).
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
check if the channel.category is the cateogry you want
down
@client.command()
@has_permissions(kick_members = True)
async def kick(ctx,member: discord.member,*,reason=None)
await member.kick(reason = reason)
await ctx.send(f"{member} kicked!")
ive made it so when an incorrect user is added, it deletes the users message, sends an erorr message and deletes afer 2 seconds. but if i then re-enter a correct username it doesnt do anything. how can i make not do this?
what about it?
invalid syntax
the third line
How I get the catagory?
Guild.get_catagory?
Like when
channel.catagory == ?
send the traceback
what the hell is a traceback
you can check by id
Ok
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
how rhen?
since you are getting SyntaxError you have a traceback
OOHHHH
File "C:\Users\urf\Desktop\discord bots\discordbot.py", line 37
async def kick(ctx,member: discord.member, * , reason = None)
^
SyntaxError: invalid syntax
[Finished in 193ms]
this?
U forgot a colon at the end of line
oh
also its discord.Member
not like its me telling you third time python is case sensitive
This too
You probably want to use a while-loop to keep asking for a correct user, then break after getting one. Like
while True:
message = await bot.wait_for("message")
# do some stuff
if user is None:
await interaction.channel.send(content="Please enter a valid user")
continue
else:
break # break the loop
# do something with the user
ok ty
I didn't understand the question /
i am making reaction role but if i just do on_reaction it will take all reaction on server but i only want it to be a specific message to run the command if a reaction is added to that message
There is not something like this built-in i believe
Just run that function from the event
wdym by that
Button roles
hmm how do i make that
Which lib are you using?
But to actually make those u need info regarding oop
i know a little bit of oop
Welp this here is an example on creating buttons
And this here is how to make them persistent views
the first one dont work
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/requests/models.py", line 971, in json
return complexjson.loads(self.text, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/disnake/ext/commands/slash_core.py", line 728, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
File "/home/container/.local/lib/python3.11/site-packages/disnake/ext/commands/params.py", line 1083, in call_param_func
return await maybe_coroutine(safe_call, function, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return await value
^^^^^^^^^^^
File "/home/container/bot.py", line 207, in crash
one = crashPoint(0)
^^^^^^^^^^^^^
File "/home/container/bot.py", line 198, in crashPoint
info = s.get('https://api.bloxflip.com/games/crash').json()['history'][num]['crashPoint']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/requests/models.py", line 975, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1378, in process_application_commands
await app_command.invoke(interaction)
File "/home/container/.local/lib/python3.11/site-packages/disnake/ext/commands/slash_core.py", line 737, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
What error ? anyone can help me ty
Wdym didn't work?
can you help me?
Seems like you getting an error while reading a json file
class Verify(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Verify', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.user.remove_roles(872417159748386848)
await interaction.user.add_roles(872414113870008320)
await interaction.user.send("You Have Been Verified\n"
"On The FedxD Server")
self.value = True
self.stop()
bot = Bot()
@bot.hybrid_command(name="verify", description="Verify a member")
@commands.has_role(FedxD_id)
async def verify(ctx):
verify = Verify()
await ctx.channel.send(embed=discord.Embed(title="Verify",
description="To Verify You Need To Subscribe to our channel FedxD"),verify=verify)
Don't know much
Hybrid command raised an error: Command 'verify' raised an exception: TypeError: Messageable.send() got an unexpected keyword argument 'verify'
how to fix?
Yeah it should be view=Verify()
its just a variable
Instead of verify=verify
Sry idk can't help
oh
Hybrid command raised an error: Command 'verify' raised an exception: NameError: name 'view' is not defined
I need help
Is it possible to use the Google colab GPU in our own python script (like an API) ,like to make my own app that uses colab GPU
Anyone pls help
Can you show me what u did?
@bot.hybrid_command(name="verify", description="Verify a member")
@commands.has_role(FedxD_id)
async def verify(ctx):
veiw = Verify()
await ctx.channel.send(embed=discord.Embed(title="Verify",
description="To Verify You Need To Subscribe to our channel FedxD"),view=view)
Zzzz
Check spelling of your veiw variable and where u sending it
File "D:\Coding Projects\Python\FedxD Manager Bot\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "d:\Coding Projects\Python\FedxD Manager Bot\main.py", line 54, in confirm
await interaction.user.remove_roles(872417159748386848)
File "D:\Coding Projects\Python\FedxD Manager Bot\venv\Lib\site-packages\discord\member.py", line 1096, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
^^^^^^^
AttributeError: 'int' object has no attribute 'id'
remove_roles takes objects, not integers
huh
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s from this member.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
can someone help here #1143165654023811082
how do i check that 2 set users have interacted with a button? i want it to proceed when both users have reacted
so i should write 1:*
First you need to get the role you are trying to remove
no
then?
how
!d discord.Member.get_role
get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.
New in version 2.0.
discord.Object(id) is enough tho
Yeah but i like the above approach
you can use Object
so i should write interation.user.get_role(id?)
Try and see
?
can you help me?
Man can you help me?
^
!json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
still same error @turbid condor
how to fix?
Read the embed
did you even bother to read the embed?
The
Wdym still the same?
What did you do?
where?
I already answered it
await interaction.user.remove_roles(interaction.user.get_role(872417159748386848))
i do not have create json file i use host
in visal studio no error why?
@turbid condor
And the error?
same
this one
you can use discord.Object and pass id to it
me?
ok lemme try that
.remove_roles(discord.Object(...))
help me
ile "D:\Coding Projects\Python\FedxD Manager Bot\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "d:\Coding Projects\Python\FedxD Manager Bot\main.py", line 55, in confirm
await interaction.user.add_roles(872414113870008320)
File "D:\Coding Projects\Python\FedxD Manager Bot\venv\Lib\site-packages\discord\member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
^^^^^^^
yes
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
For example by me that api returns 403 code, which is an error (forbidden)
>>> requests.get("https://api.bloxflip.com/games/crash")
<Response [403]>
you never provided code so im guessing you are fetching some api that you expect to return json but it does not
hence you try to parse empty string to json
you mean create json file?
no.
how do i check that 2 set users have interacted with a button? i want it to proceed when both users have reacted
issue is resolved but there is some things that is wonky that i can only use the interaction one time and it dont add the role
?
you never provided code so im guessing you are fetching some api that you expect to return json but it does not
hence you try to parse empty string to json
def crashPoint(num):
info = s.get('https://api.bloxflip.com/games/crash').json()['history'][num]['crashPoint']
return info```
what if this api does not return json?
you still will do .json() which will raise exception
you mean remove return info?
as Vitness already provided same for me : ```py
requests.get("https://api.bloxflip.com/games/crash")
<Response [403]>```
?
>>> _.text
'<!DOCTYPE html><html lang="en-US"><head> ...
its html you cant parse that to json
Htnl bruh?
you need to check it it actually returned json correctly
s = cloudscraper.create_scraper()
def crashPoint(num):
info = s.get('https://api.bloxflip.com/games/crash').json()['history'][num]['crashPoint']
Fixed Like this?
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
is that?
Cloudscraper is a library to bypass Cloudflare's anti-bot measures
oh good to know
....
well problem solved itself 🤫
Sure
the button works but it only work one time and it is not adding the role
#1143172042561179658 help please
BROO
how does the scope guild.join work, if i authorized my bot to join servers for me how will i do that?
you need redirect url and a web server to do that
yeah you need oauth
Average bobux outage
😳
Hello do someone know a way to make a anti spam system ?
Yes, do you have a more specific question?
no like
do someone know a tutorial or sum
or a github rep
wdym by "not actual token" ?
my bot tokem
put your bot's token in client.run(..)?
client.run('MTE0MjUwMDc5NDg3NzM1NDAwNg') I DONT WANT THAT
oh you want to make the token secret?
yes
then load the env in the code
then u can simply do
BOTTOKEN = os.environ.get('TOKEN')
pip install python-dotenv
BOTTOKEN = os.environ.get('TOKEN') in the emv?
nop
create .env file
then put there,
TOKEN = 'your bot's actual token'
then go to your main script and you have to import load_dotenv from dotenv and import os and load the env var
cuz the tut i watched the guy made a apisecrets.py
.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.
In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv()
load_dotenv(".env")
The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.
yep
its too complicated😭
it isnt...
whats so complicated about it?
It's pretty simple
yeah? what does that change
If you want
fun fact this tag has a syntax error
bro yall have 3yrs experience i started yesterday cuh
.. import load_dotenv() 💀
get them fired
!dotenv
lol
.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.
In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv()
load_dotenv(".env")
The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.
ok its this
bot#2728

what?
nothing
BOTTOKEN = getenv("token")
getenv isn't defined

from os import getenv
?
....
its too long (daddy)
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
issue
😭
yup
client.run('BOTTOKEN') you just pass string not actual varriable containing your token
client.run(BOTTOKEN) is the correct one
nah bro be spoonfeeding

try
try and see
error

how about you show us?
no, we are supposed to guess it

ah thats a game
screenshare?
no thanks
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
!paste but you can paste it
L
Guess what my name means
that you love dogs
you love cats ig
so obvious
you hate dogs*
@client.command
async def message(ctx,user:discord.member,*,message = None):
message = "Welcome to the server"
user.send(message=message_content)
``` there are a few things wrong here
that was difficult
Damn right
main one being naming instance of Member user
but as I already said I'm good at guessing
gonna remove it
that is a respectable choice
lmao
i spotted 4 errors here besides naming
bro
...
how tf do i fix my code
Traceback (most recent call last):
File "C:\Users\urf\Desktop\discord bots\discordbot.py", line 65, in <module>
client.run(BOTTOKEN)
File "C:\Users\urf\AppData\Local\Programs\Python\Python38-32\DLLs\lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\urf\AppData\Local\Programs\Python\Python38-32\Lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\Users\urf\AppData\Local\Programs\Python\Python38-32\Lib\asyncio\base_events.py", line 608, in run_until_complete
return future.result()
File "C:\Users\urf\AppData\Local\Programs\Python\Python38-32\DLLs\lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\urf\AppData\Local\Programs\Python\Python38-32\DLLs\lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\urf\AppData\Local\Programs\Python\Python38-32\DLLs\lib\site-packages\discord\client.py", line 609, in login
raise TypeError(f'expected token to be a str, received {token.class.name} instead')
TypeError: expected token to be a str, received NoneType instead
[Finished in 2.3s with exit code 1]
[cmd: ['py', '-u', 'C:\Users\urf\Desktop\discord bots\discordbot.py']]
[dir: C:\Users\urf\Desktop\discord bots]
[path: C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Users\urf\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\urf\AppData\Local\Programs\Python\Python38-32;C:\Users\urf\AppData\Local\Programs\Python\Python35-32\Scripts;C:\Users\urf\AppData\Local\Programs\Python\Python35-32;C:\Program Files\pycharm\bin;;C:\Program Files\Visual Studio Code\bin]
TypeError: expected token to be a str, received NoneType instead
whats wrong here:
- the
.commanddecorator needs to be called - there is no such thing as
discord.memberyou are actually looking fordiscord.Member .sendmethod is awaitable.senddoes not takemessageargument, itscontent
that means you passed None as the token instead of a string
i missed the 4th one. good catch
what do i type then??

sigh
print out to console BOTTOKEN and see if its actually your token
bro wants to be spoonfeeded
if not the .env file is not parsed correctly
Aren't we all
😭
It's easier and less things to actually learn to solve the problems ourselves 👍
i wish i understood how bad spoonfeeding was back in the days 
!dotenv
.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.
In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv()
load_dotenv(".env")
The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.
whats wrong with spoonfeeding anyways its not like anyone here actually wnts to learn
might as well give them answers directly
could be easily misunderstood
🤨
I can explain
you cant
am i the only one who noticed the one space indentation
I think it is worth differentiating when you are helping someone
If someone just wants the solution and is not really interested in learning that is their call and we can probably just give it to them
My take on that, anyway
i just want money
yes 'cause I didn't even open it 
i had to cause i asked for it 
mh you should call load_dotenv before trying to get the token using getenv, that's why you get that error

actually looking at that now and seeing even more message_content is nowhere defined and message is being overrided in the function body so why even accept it
did he ever call the load_dotenv though
no, that was the point of my message

down reading bug ig
snipy down bad rn
thought you meant he called it afterwards 😵💫

I don't know a shit about workflows
how did i
lmao
oh this was just merging flags
but this workflow looks very simmilar to one i wrote myself for my bot
suspicious
problem is that repo is private so cant accuse panda
SUSpicius
you leaked your own workflow
lmao
nah not so simmilar
you know why I never really cared about workflows
it's a sad story
never got a bot to deploy
but I contribute to disnake 
does that mean you contribute to every bot made with disnake?
In what way?
in the latest pr i shifted the listener system to disnake.Client so now Clients can have listeners 🥶🥶🥶
😳
A question
Two questions
shit i forgot what i would ask
now i remember
how do i send parameter by ""
like "parameter1" something else
?
something like how tupperbox do
i have no idea what tupperbox is
like
tul!register "Sherlock Holmes" Sherlock: text
i want to my bot not receives Sherlock and Holmes separatedly
but togeter
anything inside ""being together
oh so it goes naturally
if you dont want to put it in "" quotes you need to place * in the args
look at the example ```py
@bot.command()
async def echo(ctx, *, message: str):
await ctx.send(message)
sure just telling you
okay so, i sync slash commands
but the slash commands didn't updated
this is what should had added:
maybe it just dont appear and you need to write it all?
in discord just write the full name of command
i tested it and it don't work
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1089, in wrapper
await self._call(interaction)
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1221, in _call
command, options = self._get_app_command_options(data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1140, in _get_app_command_options
raise CommandNotFound(name, parents)
discord.app_commands.errors.CommandNotFound: Application command 'edit' not found
let me test in another way
yep, not registered still:
you named it edit_name_...
yep
it should appears as "/character default edit name"
okay soo
help me understand better this error:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\User\Documents\GitHub\RP-Utilities\cogs\CharactersCog.py", line 146, in _character_default_edit_name
for data in result:
TypeError: 'coroutine' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\hybrid.py", line 438, in _invoke_with_namespace
value = await self._do_call(ctx, ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'edit_name' raised an exception: TypeError: 'coroutine' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\hybrid.py", line 438, in _invoke_with_namespace
value = await self._do_call(ctx, ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'edit_name' raised an exception: TypeError: 'coroutine' object is not iterable
this error is kinda confuse for me
you are iterating over coro
Looks like your function is async
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | /home/main.py:5: RuntimeWarning: coroutine 'f' was never awaited
002 | for _ in f():
003 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
004 | Traceback (most recent call last):
005 | File "/home/main.py", line 5, in <module>
006 | for _ in f():
007 | TypeError: 'coroutine' object is not iterable
^
you didnt await the async function so it did not return what you are trying to iterate over
i see
it's the awaitin' thing then
ERROR discord.ext.commands.bot Ignoring exception in command character default edit_name
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\User\Documents\GitHub\RP-Utilities\cogs\CharactersCog.py", line 133, in _character_default_edit_name
result = await ctx.bot.database.update_default_character(user_id = user, old_name = old_name, new_name=new_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\User\Documents\GitHub\RP-Utilities\rpu_database.py", line 151, in update_default_character
await self.db.characters.update_one({
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Collection.update_one() missing 1 required positional argument: 'update'
okay this one is strange too
Collection.update_one()
i believe i should ask this in #databases ?
PARAMETERS:
filter: A query that matches the document to update.
update: The modifications to apply.
You are giving only one
pymongo 
hello i am using pycord to make a bot and for a music command, i need to edit a message in a non-async function. how would i be able to do this? i am using cogs and the commands.Bot instead of discord.Client (and i cant find any help online for commands.Bot)
Why does your function need to be non-async?
when the music finishes, it will stop and then run a "replay" function which will play the next song in the playlist, and id like it to edit the original message to show the new song that will play
But that doesn't answer why your function needs to be specifically non-async. Why not simply make your function async and then await it whenever you call it?
i could try this but i am not completely sure it will work
i am using the VoiceClient.play() function with an after= parameter, using it like the following:
music.play(audio,after=lambda check: replay())
asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name).
An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) for the *coro* to run in. The current context copy is created when no *context* is provided.
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) is raised if there is no running loop in current thread.
Note
[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task) is a newer alternative that allows for convenient waiting for a group of related tasks.
so within my replay function, i could use asyncio.create_task(msg.edit(content="name of song and everything"))?
i will try this
got an error
loop = asyncio.get_running_loop()
^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop
Change asyncio.create_task to asyncio.run
I think there’s a better way but this should work
@granite citrus
fut = asyncio.run_coroutine_threadsafe(coro, client.loop)
yeah, i see this working with using discord.Client() but i am using discord.Bot, im not sure how to get the loop object for that
bot.loop
your bot always have the loop attr
Or in a cog self.bot.loop
Bot is a subclass of Client so Bot will have all the same stuff as client
Oh yep that’s what I forgot about
I wonder if asyncio.run works tho
no, asyncio.run spawns another event loop, iirc, you can't run a coroutine from another event loop
besides, its also in another thread, its not thread safe either
Yeah
How come?
you shouldn't do this, asyncio.run is only meant to run your top-level coroutine, inside of which everything else happens, as I understand it
it has worked
msg.edit has the bot attached and uses aiohttp client that was spawn in another event loop, so it would raise an error if you would've used it
Yeah I was just wondering if it worked even if I shouldn’t do it
it throws an error when i include the view argument in the edit coroutine though
Oh I see thanks
That makes sense
What’s the error?
this one
show code
def replay(pre_index,file,msg): # get previouis index so we can tell if we screwed with the indexes using queue control
. . .
edit_coro = msg.edit(content=f"playing {stream.title}",view=self.MusicControl(outer=self))
asyncio.run_coroutine_threadsafe(edit_coro, self.bot.loop)
music.play(source,after=lambda bruh: replay(nindex,destiny,msg))
music.source = discord.PCMVolumeTransformer(music.source,volume=self.volumes.get(ctx.guild.id,float(self.config["MUSIC"]["volume"])))
msg = await ctx.send(f"playing {stream.title}",view=self.MusicControl(outer=self))
music.play(audio,after=lambda check: replay(index,destiny,msg))
music control is a ui.View class, the replay parameters (besides msg) are irrelevant
@golden portal
but i dont think id need to include it anyways, since editing the message doesnt affect the UI view of the message
If the view is already in the message you don’t need to edit it in
yes
Could you also maybe give the full traceback?
i see, next time you would also need to instantiate the view inside the coroutine, it's required, it creates a Future which uses the event loop
def replay(pre_index,file,msg): # get previouis index so we can tell if we screwed with the indexes using queue control
. . .
edit_coro = msg.edit(content=f"playing {stream.title}",view=self.MusicControl(outer=self))
asyncio.run_coroutine_threadsafe(edit_coro, self.bot.loop)
music.play(source,after=lambda bruh: replay(nindex,destiny,msg))
music.source = discord.PCMVolumeTransformer(music.source,volume=self.volumes.get(ctx.guild.id,float(self.config["MUSIC"]["volume"])))
view = self.MusicControl(outer=self) # <--- added line
msg = await ctx.send(f"playing {stream.title}",view=view)
music.play(audio,after=lambda check: replay(index,destiny,msg))
like this?
no, like this ```py
def replay(pre_index,file,msg):
...
async def edit():
await msg.edit(content=f"playing {stream.title}",view=self.MusicControl(outer=self))
asyncio.run_coroutine_threadsafe(edit(), self.bot.loop)
yes, as long as they are encapsulated within that async function
🙏 thank you
!rule 9
oops mb
from discord.ext import commands
from discord import app_commands, Interaction
class UserStats(commands.GroupCog)
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="balance")
async def balance(self, interaction: Interaction):
# fetch balance from database
user-stats why i am getting this when i do / how do i rename the cog??
Have you checked the documentation for GroupCog?
Or it's parent class (app_commands.Group)
!d discord.ext.commands.GroupCog
class discord.ext.commands.GroupCog(*args, **kwargs)```
Represents a cog that also doubles as a parent [`discord.app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group) for the application commands defined within it.
This inherits from [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog) and the options in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta) also apply to this. See the [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog) documentation for methods.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of the cog.
Hybrid commands will also be added to the Group, giving the ability to categorize slash commands into groups, while keeping the prefix-style command as a root-level command.
For example...
will take a look at it
class MyClass(commands.GroupCog, name="name of the parent"):
thanks D:
class buyig(discord.ui.View):
def __init__(self):
super().__init__()
self.Value = None
@discord.ui.button(label="إدخال المعلومات", style=discord.ButtonStyle.blurple)
aysnc def menu1(self, button : discord.ui.Button, interaction : discord.Interaction):
await interaction.response.send_message("hello")
How is that Invaild syntax
aysnc
you have swapped arguments
interaction comes before button
Only replace the places?
@app_commands.command(name="bon", description="bon user!")
async def bon(self, interaction: Interaction, member: Optional[discord.Memer]=None, id:Optional[int]=None):
if (member is None ) and (id is None):
# provide id
# other code
But when i enter the users id its says input a valid integer
yeah discord user id is larger than its integer value its able to accept
id is too big for int
discord dosent have infinity level integers like python
iirc limit is like 2 to power 64
so i cannot input id
input it as string
you can accept is as string
hmm
cast it in code
alr, trying
either ways discord snowflake is bigger than the limit
INTEGER 4 Any integer between -2^53 and 2^53
!e print(628951875147923476 < 2**53)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
!sf 628951875147923476
You are not allowed to use that command here. Please use the #bot-commands channel instead.
!src sf
Get Discord snowflake creation time.
bot/converters.py line 185
class Snowflake(IDConverter):```
bot/converters.py line 196
async def convert(self, ctx: Context, arg: str) -> int:```
bot/converters.py line 207
snowflake = int(arg)```
and they just cast it 😃
how is that related to discord bots
you need to find pokemon api yourself
does pokemon go have an api for that?
How I can make modal Textinput should be a intger?
Like if it's not intger, something happens like when max_len reached
u have to create a check in the callback
no other way
!d str.isdigit
str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e
print(int("¹"))
@buoyant quail :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(int("¹"))
004 | ^^^^^^^^
005 | ValueError: invalid literal for int() with base 10: '¹'
try-except would be better ig
(or checking that with your set of values - only from 0 to 9, not with str.isdigit)
try again 
i will convert you to int until you won't become an int

who called
Why something wrong?
while not isinstance(down, int):
try:
down = int(down)
except ValueError:
continue
Sisyphus reference
😵💫
.
class insert(discord.ui.Modal, title="SwesRa Host"):
server_id = discord.ui.TextInput(label="ضع ايدي سيرفرك هنا", placeholder="مثال: 1130898038639054940", required=True, min_length=15, max_length=25)
where the callback at
And where's on_submit method
How would you expect your modal to do anything then lol
Only should make it make something?
?
Of course, otherwise what's its use
That's an example how you should do them
Im trying to make managable private voices
How can i check if user own a channel and get id of that channel?(wanna change name of channel)
https://paste.pythondiscord.com/QYUA
Either map owner ids to channels in db or just list through vcs and check permissions
async def lock(self,interaction:discord.Interaction,button:discord.ui.Button):
conn = sqlite3.connect('voice.db')
c = conn.cursor()
id = interaction.user.id
c.execute("SELECT voiceID FROM voices WHERE user = ?", (id,))
voice = c.fetchall()
if voice is None:
await interaction.response.send_message('у тебя нет войса')
else:
channelID = voice[0]
role = interaction.guild.default_role
channel = self.bot.get_channel(channelID)
await channel.set_permissions(role,connect = False)
await interaction.followup.send('Locked')
conn.commit()
conn.close ```
look , when i create channel and trying to lock it
bot says that i dont have a channel
Whats the problem?
How I can detect when the bot join to a new server and get thing like server link & name
You sure the records exist in db?
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
@bot.event
async def on_voice_state_update(member, before, after,):
db = sqlite3.connect('voice.db')
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS voices(user INETGER,voiceID INTEGER,guild INTEGER)")
if after:
if after.channel:
if after.channel.id == 1121024522368327690:
for guild in bot.guilds:
maincategory = discord.utils.get(guild.categories, id = 1121024521894363239)
channel_p = await guild.create_voice_channel (name= f'Канал {member.display_name }', category= maincategory)
await channel_p.set_permissions( member, connect = True, mute_members = True, move_members = True, manage_channels = True )
await member.move_to(channel_p)
cursor.execute("INSERT INTO voices(user,voiceID,guild) VALUES(?,?,?)",(member.id,channel_p.id,member.guild.id,))
def check(x,y,z):
return len(channel_p.members ) == 0
await bot.wait_for(f'voice_state_update', check= check)
await channel_p.delete()
cursor.execute('SELECT voiceID FROM voices WHERE user = ? AND guild = ? ', (member.id, member.guild.id))
data = cursor.fetchone()
if data:
cursor.execute('DELETE FROM voices WHERE user = ? AND guild = ?', (member.id, member.guild.id))
db.commit()```
ig i make it right
aint reading allat
That triple if already makes me not
And yeah you have a typo: INETGER
What kind of tutorial were you following
And how to get link?
github repository
You'd have to either fetch one from already existing ones if you got access, or create new one
Gotta tell you if that code is from some repo that repo is complete trash
Can you explain
Can say just by triple if cond and way of managing connections
its my code and if ill write ```py
if after.channel.id == 1121024522368327690:
Then ill get a error
Only with triple if
No errors
No offense to whoever wrote that code but have you heard of and

How I can get server link??
What kind of explanations do you need
whatever server link is
If you need spoonfeed ask chatgpt
When the bot joins a server
Vanity url?
I want it to send me the link
Or any server invite?
.gg/
its called invite
These are the ways
!d discord.Guild.invites
await invites()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns a list of all active instant invites from the guild.
You must have [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild) to get this information.
!d discord.abc.GuildChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite) to do this.
Forgot it's for channels
yeah invite is per channel
!d discord.Guild.vanity_invite but if guild has vanity url you can use this
await vanity_invite()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the guild’s special vanity invite.
The guild must have `VANITY_URL` in [`features`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.features).
You must have [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild) to do this.as well.
no idea why its coro
Create invite is this
OK HERE WE GO
invite = await guild.text_channels[0].create_invite(whatever=whatever)
print(invite.url)
Gotta handle situations where you aren't allowed to create invites or where there are no text channels
blud spoonfeeding
Eat dat spoon
gonna eat you too 😏
It works ☺️
can I use the same logic dad
Why its telling me that?
class insert(discord.ui.Modal, title="SwesRa Host"):
server_id = discord.ui.TextInput(label="يرجى إدخال ايدي سيرفرك", placeholder="مثال: 1130898038639054940", required=True, min_length=15, max_length=25)
count = discord.ui.TextInput(label="يرجى إدخال كمية الاعضاء المراد شرائها", placeholder="مثال: 100", required=True, min_length=1, max_length=4)
async def on_submit(self, interaction: discord.Interaction):
b_guild = bot.get_guild(server_id)
chennel = bot.get_channel(log_channel_id)
await channel.send(f"تم شراء : {self.count}\n المشتري: {interaction.user.mention}\n ايدي السيرفر: {self.server_id}")
??
Look at the first var
Wdym
you know what self is?
Yup
doesnt look like
@vale wing thanks for free PR on Rapptz/discord.py#9531
await channel.send(f"...{self.count}...") ``` you already did that with count varriable
which is defined same way as server_id
!E ```py
class A:
varriable = 1
def something(self):
print(self.varriable)
A().something()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
see difference?
....
- You must have :attr:`~Permissions.manage_guild` to do this.as well.
+ You must have :attr:`~Permissions.manage_guild` to do this as well.
lol
hard fix
insert().server_id()?
...
Can anyone help me?
okay for some reason my command is not appearing
i tried typing /_char but nothing appears
You’re calling server_id within a class without declaring self first.
Exactly what your error is saying. And exactly what the other guy started with
difficult to update my slash commands
Ah in guild = ...
!e ```py
class A:
class self:
var = 1
print(A.self.var)
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
Your welcome
Generally speaking you have to appropriately sync your commands to the server.
But without context and code examples it could literally be anything
well i have synced the commands, but those new ones aren't syncing
?paste
as you can see here
It's doing the action of on_submit function + no errors in project
Why its telling something is wrong
Well you shouldnt sync in a cog
And you are syncing them globally, that will take up to an hour
where and how should i sync?
cus in bot i couldn't
Setup hook is fine
but in cog i could
class insert(discord.ui.Modal, title="SwesRa Host"):
server_id = discord.ui.TextInput(label="يرجى إدخال ايدي سيرفرك", placeholder="مثال: 1130898038639054940", required=True, min_length=15, max_length=25)
count = discord.ui.TextInput(label="يرجى إدخال كمية الاعضاء المراد شرائها", placeholder="مثال: 100", required=True, min_length=1, max_length=4)
async def on_submit(self, interaction: discord.Interaction):
b_guild = bot.get_guild(self.server_id)
channel = bot.get_channel(log_channel_id)
await channel.send(f"تم شراء : {self.count}\n المشتري: {interaction.user.mention}\n ايدي السيرفر: {self.server_id}")
oh setup hook
Copy global to guild and pass a guild snowflake to the sync and copy
copy global?
Respond to the interaction 🤷
!d discord.app_commands.CommandTree.copy_global_to
copy_global_to(*, guild)```
Copies all global commands to the specified guild.
This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.
Note that this method will *override* pre-existing guild commands that would conflict.
Can you explain?
Make sure the specify both the guild in the copy and global using a snowflake
i need an example on how i will do it
!d discord.Object
class discord.Object(id, *, type=...)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
Explain what
Why it's telling something went wrong when no errors?
You need to place them after eachother in the setup hook. Not much to show.
Because you didn't respond to the interaction
Is that required?
Yes interactions always require a response.
You can defer the response and not do anything with it.
Ok thx for help
Well you need to have copy and set the guild
copy and set the guild uhmm...
i have no idea how i use this
I mean, it's just a function that takes a guild argument
then i type .sync?
Damn boy you need to learn oop
how do i set it as for all guilds it enters?
Just sync globally at that point
sync globally uhmm
like .tree.sync()?
@bot.event
async def on_guild_channel_create(channel):
if channel.category == 1143506203549384836:
print("vhanel")
else:
print("not")
Why is not working
When I make the channel in the category it's printing not
!d discord.abc.GuildChannel.category
property category```
The category this channel belongs to.
If there is no category then this is `None`.
it's a CategoryChannel object, not an int, thats why
Someone here told me that I can check with ID only
flowery will say they are wrong
just do getattr(channel.category, 'id', None) == 1143506203549384836 or somethin
Cause you can
Just do category.id bruh?
category can be None
It's optional so
Me when if category
That should return an ID
So like I put in my code
(but third argument is None by default)
if you dont put the third arg, it will raise attr error
hmm, really?
!d getattr
getattr(object, name)``````py
getattr(object, name, default)```
Return the value of the named attribute of *object*. *name* must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, `getattr(x, 'foobar')` is equivalent to `x.foobar`. If the named attribute does not exist, *default* is returned if provided, otherwise [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError) is raised. *name* need not be a Python identifier (see [`setattr()`](https://docs.python.org/3/library/functions.html#setattr)).
Note
Since [private name mangling](https://docs.python.org/3/reference/expressions.html#private-name-mangling) happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with [`getattr()`](https://docs.python.org/3/library/functions.html#getattr).
!e
print(getattr(None, "idk"))
@buoyant quail :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(getattr(None, "idk"))
004 | ^^^^^^^^^^^^^^^^^^^^
005 | AttributeError: 'NoneType' object has no attribute 'idk'
ok
Doesn't it?
Oh u mean some_number == member?
yes
Yea..... well wouldn't that be weird tho lol?
We all are just numbers
it's one of the most common things to do tbh
Well u can implement it yourself
nyo
How I can multiple a number in TextInput?
Take out data from there, convert to int and multiply
Wdym Take data out from there
How to get it?
Link pls

Didn't find anything
What did you search
Get data from TextInput
Nah, it's not google
Search TextInput, choose discord.TextInput and look what attributes and methods it has
Ok
okay... first time getting this error:
ERROR discord.app_commands.tree Ignoring exception in command 'image_set'
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 841, in _do_call
raise CommandSignatureMismatch(self) from None
discord.app_commands.errors.CommandSignatureMismatch: The signature for command 'image_set' is different from the one provided by Discord. This can happen because either your code is out of date or you have not synced the commands with Discord, causing the mismatch in data. It is recommended to sync the command tree to fix this issue.
You need to sync your commands ¯_(ツ)_/¯
Error says they aren't
i don't know why it says it's not synced
close and open?
they are synced, but don't work?
there was a command alt + r or control + r
i restart bot
restart discord, and the same thing still keeps up
ERROR discord.app_commands.tree Ignoring exception in command 'image_set'
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 841, in _do_call
raise CommandSignatureMismatch(self) from None
discord.app_commands.errors.CommandSignatureMismatch: The signature for command 'image_set' is different from the one provided by Discord. This can happen because either your code is out of date or you have not synced the commands with Discord, causing the mismatch in data. It is recommended to sync the command tree to fix this issue.
what else i need to do?
kill a god?
commands = await self.tree.sync()
print(commands)
run and check if you get that command in output
(there will be a list like [<AppCommand id=1143115911985901579 name='foo' type=<AppCommandType.chat_input: 1>>])
[<AppCommand id=1143283798516179055 name='prefix' type=<AppCommandType.chat_input: 1>>, <AppCommand id=1141375427185746041 name='character' type=<AppCommandType.chat_input: 1>>]
that's what print
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/6DLA#1L247-L247
command name cannot have spaces
I am not sure bcs i don't know groups in dpy good enough, but that confuses me
@commands.hybrid_group(name = "character", fallback="help", invoke_without_command = True, aliases = ["char"])
async def _character(self, ctx):
await ctx.send("character related commands, use default if you are a starter.")
@_character.group(name = "default", fallback="help", invoke_without_command = True, aliases = ["def"])
async def _character_default(self, ctx):
@_character_default.command(name="set image", aliases=["img_set", "pfp_set", "profile_set"], with_app_command = False)
async def _character_default_image_set(self, ctx, name: str, image: str):
@_character_default.app_command.command(name = "image_set",)
async def _character_default_image_set_slash(self, ctx: discord.Interaction, name: str, image1: discord.Attachment | None, image2: str | None):
becausei checked, it works, okHybridGroupdoesn't haveapp_commanddocumented, onlycommand- because it's hybrid but you are setting two different commands for prefix and slash, not one (i see that you are doing with_app_command = False but still)
If it was the same and did work before then ok
it's because of comptiblity
*campatibility
like, prefix command don't support attatchment
so i had to split in two to make it work
It does?
@bot.command()
async def foo(ctx, arg: discord.Attachment):
await ctx.send(arg)
not documentation
pretty sure its documented
A hands-on guide to Discord.py
okay... that's curious
?
It seems correct
its not, it doesn't raise MissingRequiredArgument, that one is for consume rest where *, a, b, b raises MissingRequiredArgument, but Greedy doesn't consume that way, it would raise ArgumentParsingError
Run it and see
i did
Traceback (most recent call last):
File "C:\Users\Vital\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Vital\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 1021, in invoke
await self.prepare(ctx)
File "C:\Users\Vital\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 938, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Vital\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 845, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "C:\Users\Vital\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 697, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: argument2 is a required argument that is missing.
Its open source you can make an issue if you want :)
hmmm
yeah i tested it
also it might be even stated on the official docs, not sure
I see, i guess i misread what the warning actually meant, i was expecting it meant 1 2 3 a so it would raise parsing error
not the latter
If only I can respond one time for interaction so how to send messages in same channel?
use followup
There are interaction.followup and interaction.channel
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
Ok
idk why discord is returning 404 but you can delete the message without the needs to fetch a full message object (eg. using the old message object)
Why don't you just use the msg variable you already have anyway? 
you can pass delete_after kwarg when sending
but you have no 100% chance it will be deleted
you can transfer Message object anyways
What is this
View representation string
!e ```py
class View:
def repr(self):
return "<View timeout=None children=2>"
print(View())
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
<View timeout=None children=2>
I want to send an embed with a thumbnail of a specific image url. I need to put cookies data to access the image url. What should I do? Downloading to the local directory or sending the discord.File object to a certain channel and getting the download url seems a lot of work.
class VCname(discord.ui.Modal, title="Верификация"):
def __init__(self, channel,*args,**kwargs):
super().__init__(*args,**kwargs)
self.add_item(discord.ui.TextInput(
label='Проверка 93457',
style=discord.TextStyle.short,
placeholder=f"Input number",
required=True,
max_length=32,
min_length=1,
)
)
async def on_submit(self, interaction:discord.Interaction):
if self.children[0].value == 93547:
await interaction.user.add_roles(interaction.guild.get_role(1124323679703158816))
await interaction.response.send_message('Passed',ephemeral=True)```
Can someone help? I wanna male simple Verification bot
i need give role to user if he input right number in modal
But its not working
I didn't understand this error
- did you check if the
if ...:is being invoked? - you dont need to get actual Role object,
.add_rolestakes snowflakes meaning if you have id you can do.add_roles(discord.Object(ID_HERE))
@exotic island ^
!E 1 in ""
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | 1 in ""
004 | TypeError: 'in <string>' requires string as left operand, not int
!e
1 in ""
🧐
Ok ok
It's written in plain English
same example shush
English it's not my main language 
google translate: 
can you rephrase it?
do you want to send image from channel1 to channel2 without saving it to local storage?
python file.py

You might have another instance running
This bot aggravates me
what?
Anyways, if you stop running the code the bot should go offline. You can also use Bot.close() to disconnect the bot from discord. https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.close
There’s a chance you have an instance of your bot running somewhere, maybe restart your pc
i dont want to restart my PC just to stop the bot
Then try to find where the instance is running, what IDE are you using?
im gonna import time and it will only run for 30minutes
sublime text
Well, as I said, there must be an instance running somewhere if the bot is online
what os
7
7 what?
windows 7







