#discord-bots
1 messages Β· Page 157 of 1
whelp. always the simple stuff
lol, we all make mistakes
discord.ext.commands has no attribute 'tree'
alright
instead of using commands try changing the variable to bot or anything else you'd like
i have bot set to commands.Bot
the function doesnt look like that its in a class, is it?
class Foo:
def in_a_class(self):
...
def not_in_a_class(self):
...
can i have hybrid commands and slash commands in the same bot? hadnt considered that might be an issue
i dont have anything in classes right now
oh yeah thats right as well
what is self doing there then
that was a result of me throwing stuff in trying to get something different to happen
@bot.event
async def on_ready():
await bot.tree.sync()
print('ready')
channel_id = 960040150765817907
number = [1]
@commands.hybrid_command()
async def question(ctx):
print('n')
bot.run(TOKEN)```
thats everything not commented out of the file right now except the token and imports
getting this error still
@bot.hybrid_command()
@bot.hybrid_command
rip
so why is that one bot but regular commands are still @commands and slash commands still @app_commands
works now though. thanks
np
they are different things, Basically the base decorator for creating coroutines to command objects
commands.command -> creates a command object
bot.command -> same as above but adds the command to the bot
app_commands.command -> creates a slash command
tree.command -> same as above but adds the command to the tree
same for tree commands
gets confusing sometimes
what's confusing about it
i guess i just havent looked at that part of the docs enough for the structure to make sense to me
mb
wait I just realized bots can't dm users who don't allow dms from users on a server unless they're friends...
that's the intention
to make it annoying?
some bots mass dm users for promotion malicious links
its just to prevent that
- dms from bots get annoying unless asked for
i join some servers and boom, 10 dms from bots in the same server
leaves instantly
alr ye thats true
Say what's the problem is or send with an exception
Anyways
The init in your lass isn't a magic method
So change it
you need to use an instance of commands.Context not the class itself
hmmm ok
what you trying to do with IPs, sus
@slate swan if my bot error handler was yr name then i don't think it will ever wake up from 0 second naps
thats' the future of tech
uhh no solution here is ```
@show_manager_channel.error # <- name of the command + .error
async def show_manager_channel_error(error, interaction):
if isinstance(error, commands.MissingRole):
await interaction.response.send_message(f"{ctx.author.mention} Sorry, create role << Channels Manager - Giveaways Manager >> has been can permission commands :rotating_light:",ephemeral=True)
# message = await interaction.original_response()
else:
raise error```
What's the problem
Can you send the actual error from the terminal or console or whatever
yes, nothing error console
is empty.
empty nothingg console error, but maybe problem there
Then you simply didn't respond to the interaction
Add this here:
else:
raise error
Ok
moment is last final?
?
edit example @maiden fable
maybe?
Indent
but confuse
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Mhm
There u go
ah yes but example no have rol and response error "Sorry create role..."
!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.
yeah but need example error response "sorry create role.."
no have rol think
In the else, can you add print(error) at the line above the raise error code
hmm ok
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.
error print: <discord.interactions.Interaction object at 0x7fd5abfd6a90>
Thought so
Your error and interaction params are interchanged
interaction should be the followed by error not the vice versa
async def show_manager_channel(interaction, error)
ahh
Instead of the other way around
error, interaction change is l(interaction, error)
Yes
You were trying to check if the Interaction is the error lol
Show the latest code
yeah..
but... missing messag error.
no is "error red" but only message error
hmm
@maiden fable yeah but my think.. other before "ctx" is okay work message error (not need red)
and differents response no is error message
example message error bot: Role 'Channels Manager' is required to run this command.
Of course, there's wouldn't be one
You're printing the error, not raising it
yeah..
hmmm think.
there is old yes. work.
but interaction no work why red message lol.
hmm
Okay
no problem idea thanks old better.
@naive briar oh i see but think no is "commands.MissingRole"?
maybe there interaction?
ahh
my stupid sigh!
solution maybe done ok
does anyone have an example implementation of a command that opens a modal?
how do you add users to a private discord thread?
There should be a menu at the top right which lets you invite them. I think mentioning them works too
!d discord.Interaction.response.send_modal
just interaction.response.send_modal will do
Thanks i did find an example, but I was specifically looking for how a slash command could open a modal. I think i have it now though
i mean in code lol
how do you invite users to a private thread?
i don't get errors in the terminal, it just pop up "This interaction failed"
maybe u r doing something big which is taking more than 3 seconds to complete
if doing such a thing before defering interaction it will always result in a fail
!e
print("checking")
oh bot alive
but, i'm just changing the button emoji in the meantime
code please.
wait
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
any help or fixes please?
!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.
show us full traceback
show us all exception
full error
we need see from which line u r getting this error
π
hey
error starts with
Traceback (most recent call last):
there is no code error its just that the command dont work @shrewd fjord
and idk how to make it do
something is wrong inside the command bro
u got a fix?
in which line u r getting troble?
i did a debug and everything is running fine and the bot is online but the only command not working is unban
button.emoji = 'βοΈ'
is what it says
then
await interaction.response.edit_message(view=self)
just gimme full trace back man
i doesn't want to send message
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discordβs API, this now returns a paginated iterator instead of a list.
Examples
Usage...
but than u can steal token spooky
huh?
the bot token
would it be somthing like then?
wait
@discord.ui.button(emoji='β', style=discord.ButtonStyle.grey, row=1)
async def my_button1(self, interaction:discord.Interaction, button:discord.ui.Button):
self.button.emoji = 'βοΈ'
no
how to do that?
button.emoji
or
@discord.ui.button(emoji='β', style=discord.ButtonStyle.grey, row=1)
async def my_button1(self, interaction:discord.Interaction, button:discord.ui.Button):
button.emoji = 'βοΈ'
check ur terminal man
thisz
then u must add edit_message
this?
and view will be self
why i need add edit_message?
or the button won't get updated
hmm
@discord.ui.button(emoji='β', style=discord.ButtonStyle.grey, row=1)
async def my_button1(self, interaction:discord.Interaction, button:discord.ui.Button):
button.emoji = 'βοΈ'
await interaction.response.edit_message(view=self)
like this?
yeeeeep
async for banned_users in ctx.guild.bans()
then do other stuffs here
what library u use
would it be like that?
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
see?
await interaction.response.edit_original_response()
π
spooky
not really
u r not sending any responsed message to do this
so no
need to use edit_message
@shrewd fjord u r getting any error?
@shrewd fjord
Thanks
wait
my ping was not working xddd
i'm testing now
xd
how do i send my code
Ohhhhh yeahhhhh it workedddd
async for ....................:
#then other codes will be send right here
nice
thanks a lootttt
np ;]
cool
you can use !code, or if itβs a lot !paste
ya
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
gl for mking tictactoe π
this is my first time using discordbots
damnnnn
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
haha
i love seeing people choose between code and paste
I know python, but discord.py is very different than pure python
haha
https://paste.pythondiscord.com/jujagaxini
@shrewd fjord
ofc
wait
are you getting an error? or what do you need help with
i don't speak english very well, so if i say something wrong, could you please correct me?
the unban command isn't working
its not that the lines are bad its just that it does not do the command and idk why
check what i edited
is it possible to detect messages from threads that is under a specific channel?
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discordβs API, this now returns a paginated iterator instead of a list.
Examples
Usage...
Reference ^
checking
go into your discord and type /bab
/bab
its a discord inbuilt feature lol
π
no need for another ban cmd
i never used async function, for example. This is a big adventure for me
why
if he wants it itβs his π€·πΌββοΈ
@shrewd fjord still not working
yeah but im trying to do it through a bot
what error u r getting
is it possible to log messages that are sent from a thread under a specific channel?
self should only be used inside classes
yes ofc
ye xd
same as last one
get the thread channel
and use get messages
what changes u did to the code?
what u gave me
how would that look like tho?
is it like a on event?
yes some kind of
u can use on_message event
pass their thread channel id
or u can use
channel. history
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
it will return a list
for disable a button, so we use button.disable(True) right?
almost got that but,
button.disabled=True
oh is it like a list of the messages only sent
what is the best way to (de)serialize a modal TextStyle.long to/from a db blob datatype?
in the specific thread?
ye
yep
Not is a function?
no
?
ok
!d discord.ui.Button.disabled
property disabled```
Whether the button is disabled or not.
because i have a variable with with create_thread() in it, should i just do like thread.read_message_history?
why not have a on_message event and check for the thread
thank you again, spooky :D
yeah how do i do that one
i mean i could not figure out how i could read messages from a specific thread from on message
u need to always update the code for that
if isinstance(channel, discord.Thread) and channel.id == your_id
if he uses history he can just wrap it with a command
like
.history #channel-name
here we can get the channel's history
the thing is that the threads are automatically created and gets deleted soon after so thats why i struggle find a way to log messages from those temporarily made threads
through on message
but for on_message event we always have to change the id
if we want some for diff threads too
oh nvm then
ohhh wait bruh
on_command_error doesnt takes arg
he's tryna log threads of a channel
bruh
nvm then
hmmmmmmmmmmm
any1 help?
wait
i think there is an event
named thread_delete
!d discord.TextChannel.threads
property threads```
Returns all the threads that you can see.
New in version 2.0.
unban command not working for me
just use
await ctx.send(error)
yea there is
yeah its a system that is for users to sell stuff in, and everything gets logged in it
yeaaaah then it's prettttyyyy easy
on_thread_delete
u can then check the history of channel and get the message and log it
kinda ez
the thread gets created automatically with an id in the name and gets deleted later on
oh okay
where is the async function
!d discord.on_thread_create
discord.on_thread_create(thread)```
Called whenever a thread is created.
Note that you can get the guild from [`Thread.guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.guild "discord.Thread.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
New in version 2.0.
nice
oh that seems much easier to use lol
yeah exactly
!d discord.on_thread_delete
discord.on_thread_delete(thread)```
Called whenever a thread is deleted. If the thread could not be found in the internal cache this event will not be called. Threads will not be in the cache if they are archived.
If you need this information use [`on_raw_thread_delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_thread_delete "discord.on_raw_thread_delete") instead.
Note that you can get the guild from [`Thread.guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.guild "discord.Thread.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
New in version 2.0.
better
yeah
ok
hmm okay thank you for the help, ill try to use this and see how it goes lmao
!d discord.Thread.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
ok a sec
xd
yes
u can use discord.User
its an unban command not an ban...
if the user is not in the server
then use discord.User
oh wait btw, for the on thread create function, how can i detect if the thread are created under specific channel?
a*
in this argument u gotta use either user's id or name or somehow mention him
thread.catgory
!d discord.Thread
class discord.Thread```
Represents a Discord thread.
x == y Checks if two threads are equal.
x != y Checks if two threads are not equal.
hash(x) Returns the threadβs hash.
str(x) Returns the threadβs name.
New in version 2.0.
list of attributes u can get here
oh okay
still not working
so it should be like like an id of some sort to check?
and im trynna unban him with a command
like the category id
can u try to pass his id?
a sec
u can get thread in on_thread_create event
oh okay thank you!
still not working @slate swan
wait lil correction,
thread.category_id
i gave up already xdddd
oh okay, once again thank you for the help haha
show code
we r always here to help tho xd
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I have question how to make something like
/setwelcomechannel for a welcome channel to make bot do the welcome on it (to be able to use the bot in more than 1 server)
@bot.command()
async def unban(ctx, user: discord.User):
await ctx.guild.unabn(user)
await ctx.send("your message")
@slate swan
database
unabn\
if u want to avoid it add cahnnel id manually
Yeah I know databases but is there any website or something saying how?
database are pretty hard
Since I am going to make the bot as public bot
but ig use sqlite3
atleast for me xddd
what to replace with this?
just replace your message
I already have sqlite3 database for warn and mute system alright
nothing else
the whole unban script?
then ez
How to do the set command then
bro just replace ur unban message bruuuuuuuh
slash command?
Yes
wut message
but u know ?
like how did u make ur poll command slash
Yeah
bot.event
async def on_command_error(ctx, error,):
if isinstance(error, commands.CommandNotFound):
CommandError=discord.Embed(title="π« ERROR !",description=f"{error}")
CommandError.set_footer(text="Deleting in 4 seconds...")
await ctx.reply(embed=CommandError)
time.sleep(3)
only part of this code enough btw
the things he told me to do did not fix it
I can't find any video or anything to show me how to /setchannel so what would I do @shrewd fjord
just make a slash command of setchannel
and use ur database skills?
I don't have database skills actually lol
Just learned a little bit for the warn
And probably forgot
@bot.event
async def on_command_error(ctx, error,):
CommandError=discord.Embed(title="π« ERROR !",description=f"{error}")
CommandError.set_footer(text="Deleting in 4 seconds...")
await ctx.reply(embed=CommandError)
time.sleep(3)
@slate swan
try this kind of easy
;-;
idk database professionally either
i can just give idea how to implement it
Alright no problem lemme see
Sure
like?
u can create a table named channel there will be 2 columns 1 for guild id one for channel id
then insert channel id value with guild id
ye so?
u can replace ur code by mine
if u want global slash handler
......what's ur new code?
show me or π«
After that if channel id in table and guild id :
Channel.send_message(")
Hmm
after that check in which guild the member joined and get the channel id from that table which matches guild id
no need to do
Lemme try
full @bot.event replace by this
@slate swan it will handleeeeeee allll sort of error
what's the diference about discord.ui.Button and discord.ui.button?
2nd one is decorator
and 1st one is for getting button object
;]
how do i make so only administrators or specific roles can use the commands and members no?
@commands.has_permissions(administrator=True)
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
but also for like specific commands
it's for specific commands only
put that beneath @bot.command()
no but like the script u gave me looks like it enables and disables bot commands for specific roles and im trynna do it so members can use bot commands but not all of them on the bot
and so as staff
can u tell the role name
so that if the staff has that role
he can use it
lets say member
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
@commands.has_role("member")
who have member role, that member can use this command
just put this line on those command which command u want only "member"role to use
ok and how do i do the opposite
?
wth
like to make them not be able to use the command
check if use has a role named "member"
if true then return it
ez as that
did not understand
like lets say a member can use !ban and i dont want that to happen how do i prevent that?
check if member has ban_members
@commands.has_permissions(ban_members=True)
!d discord.ext.commands.check
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
according to ur problem
You can check if the member has the role or not, if yes, just return false
There's example in that url
catgal don't talk or π«
@client.command()
@commands.has_permissions(ban_members=True)
...
jk
here is example
xd
where do i check that
π«‘
@slate swan
where do i put this?
and to put instead of true to false?
OH MY GOD KILL MEEEEEEE AAAAAAAAAAAAAAAAAAAAA
nope
put it in ur commanddddddddd
@client.command()
@commands.has_permissions(ban_members=True)
async def ban():
...
like that
make it to Trues so member can't use it
async def*
oh u edited, flash guy
hehe
gimme ur power or my water gun here to get u π«
btw the binary code in ur about me tells "Hello World"?
yes sir
cool
thanks
how do i do the same but for the unban command?
yep
no like how do i do it but for another command?
it's same for unban command too
π€·
@client.command()
@commands.has_permissions(ban_members=True)
async def ban():
...
@client.command()
@commands.has_permissions(ban_members=True)
async def unban():
...
oh
π«‘
did not work
wdym
@clever scaffold members cannot unban but the second i put this code: @commands.has_role("owner")
i gave uup btw π
all of the commands were open
if i would have used this command on staff staff would have access to use all of the commands
has_permissions(ban_members=True)
use it
i put that
then what
is this
meaning that when i put the role in the command @commands.has_role("")
that same role
can use all the commands of the bot
ownerID = [...]
@client.command()
async def ban(ctx):
if ctx.author.id in ownerID:
...
return
I have new idea
or use
nvm
leave it
indent return
it's outside of if statement π
it's like if else
"return" is not needed
oh ye makes sense altho xd
ima need to leave this codes out for now lemme check on yt or sum
Can you check dms @shrewd fjord
1 sec
use decorators
!d discord.Team Is recommended
class discord.Team```
Represents an application team for a bot provided by Discord.
!d discord.ext.commands.Bot.check
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
how to make custom command that when u write it it pings staff roles and it also pings the one who sent the command
@shrewd fjord
You can mention roles using <@&role_id> and the author using User.mention (ctx.author.mention)
await ctx.send(f"{mentions whatever} you can write your message content")
yeah but i want the message to be under
how to make a command that gives a role? @upbeat otter
and how to make one that removes a role
!d discord.Guild.add_role
No documentation found for the requested symbol.
L bot
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
Epic fail
!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.
u only add 1 role
?
I think (?) atomically means that they're added one-at-a-time as opposed to all at once. But I'm not certain.
are you asking what async is or?
inside the what
()
solution for this error ?
the arguments you need?
so probably the user and role?
send pls
Async means asynchronous. In the context of programming, it means your bot can carry out a longer task and still be able to do other things at the same time. Also, add_roles is a method of discord.Member so you need to put await member.add_roles(...).
where do i put that tho
im trynna put into the () in the desync line
hm
what do i write inside of the mouth or sum
bro the mouth? 
can i continue a task after a break of 1 hour ?
it looks like a mouth with eyes fr
well so what do i write inside
ima go eat write in my dms pls
your arguments...
How much Python do you know?
null
can a bot edit an ephemeral message
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
just @ works, no?
its correct, if you are in an embed, you are using a wrong area
< @ 1039974694033563658 >
what part of embed, only descriptions and field values work
I don't think you can mention users in the title and stuff of an embed
field value though?
yes.
im learning in school currently
i know very little python and discord.py is complicated for me
it raises an unknown webhook error
I've tried it already
That's okay, but it may be best to focus on just Python for a bit longer then.
Interaction.message.edit raises unkown Message
Was the ephemeral message sent by your own bot or another bot?
own bot
Send the code then
class LeaveButtonView(discord.ui.View):
def __init__(self, msg):
super().__init__()
self.value = None
self.msg = msg
@discord.ui.button(label="Leave Giveaway", style=discord.ButtonStyle.danger)
async def leave_buttony(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.msg.id in bot.messages:
if interaction.user.id in bot.messages[self.msg.id]["embed"][3]:
bot.messages[self.msg.id]["embed"][3].remove(interaction.user.id)
await interaction.message.edit(content="response 2")
else:
await interaction.response.send_message("response 1", ephemeral=True)
sent here
await interaction.followup.send("You have already entered this giveaway!", view=LeaveButtonView(msg), ephemeral=True)
does defering it help
nah
Because you haven't responded to the button click before trying interaction.message.edit. You should pass the original interaction into the view as something like self.interaction then edit that instead.
let me try
it's getting uglier
oh I got it in another way
view = LeaveButtonView(msg)
last_msg = await interaction.followup.send("You have already entered this giveaway!", view=view, ephemeral=True)
view.last_msg = last_msg
```editing self.last_msg
assuming self.last_msg is assigned before discord gets the message, the user gets the message from discord, the user clicks the button, which discord then tells the bot
Someone know where I can find a sports API key?
PS: ping me if you know 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.
https://github.com/public-apis/public-apis#sports--fitness here are some sports apis
Thanks!!
If you mean () they are parentheses
parenthesis?
Sorry I'm not one to remember names of python characters
how to make my bot list all its slash commands?
!d discord.app_commands.CommandTree.get_commands
get_commands(*, guild=None, type=None)```
Gets all application commands from the tree.
How do I keep my bots slash commands to only being used in a discord server and not in dms?
!d discord.app_commands.guild_only
@discord.app_commands.guild_only(func=None)```
A decorator that indicates this command can only be used in a guild context.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"), and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a private message.
This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples...
How can you send a private message NOT DM
what's a private message then?
You mean ephemeral?
Oh is that what it's called
Thank you
How can i import my comamnds from a different file? (#1053373188270215198)
like cogs?
I've not heard of that lmao
oh yeah this may work, i'll have a look on how it works
async def custom_cooldown(ctx):
time = await self.db.fetchval("SELECT time FROM users WHERE user_id = $1", ctx.author.id)
if time == 0:
print("one")
return commands.Cooldown(1, 200)
elif time == 1:
print("two")
return commands.Cooldown(1, 120)
@commands.command()
@commands.dynamic_cooldown(custom_cooldown, commands.BucketType.user)
async def test(self, ctx):
await ctx.send("ok")
the bot is not responding, there are no errors, what could be the problem?
No
no
Guys I need help I am planning to make a really good bot (already started on) and I am going to spend a lot of time working on it
But I want to know what I should really use discord.py or nextcord
Can someone suggest to me what to use?
I use nextcord
I'm gonna have to recommend discord.py personally
But it's entirely your decision
Can someone tell me what is the difference between both of them?
discord.py provides you more control on application command
nextcord provides you easier way of making application commands
thats basically it, other than that there's a bit of change in cogs extension loading etc
I don't mind easier or harder but I want it more professional and have the ability to do more features so which one is better for mr?
you get same features in both, in contrast nextcord has more features.
So if I got really professional at dpy and same as nextcord, if I am using nextcord it will give me more features to do?
features like voice recieve and some plugins yeah
help pls
what's the best way to save/load the text of a long-text modal field? edit: in a database nvm. you just use the .value of the textbox object which is a string that has the formatting.
So I have level system but idk how would I set the xp because it's kinda confusing so for now I have it to level up
5 = 63 messages
10 = 500 messages
15 = 1687 messages
20 = 4000 messages
25 = 7812 messages
30 = 13500 messages
35 = 21437 messages
40 = 32000 messages
Yall think this good ?
I'd just store each user's XP in a database then add a certain amount to that XP when they send a message. Then come up with some formula to convert between XP and level.
mh idk but people tend to send a lot of messages
that would be a lot of queries
you shoulf do some optimizing
So this is going to sound weird but basically I need to delete some channels but I dont want to loose the data, so can I use a discord bot to transfer all the data from day one to another channel in a different server?
True. How else could you go about it though? Just store stuff temporarily in the script and make a task loop to update the DB every so often?
that would be an option ig
you can dump all the channels
*messages
So like a for loop?
a while loop but yes
But how would I get every single message and would it include the images?
root@vmd104222:~/hi# python bruh.py
File "bruh.py", line 9
async def sync(ctx):
^
SyntaxError: invalid syntax
erm
check the documentation
can someone help?
there is .attachmentd
check line 8
what python version are you running?
Uhhh one last thing, what would it be under? Sorry im being a bit annoying
wtf python 2.7
well there u go
np
what library should i use to make a discord bot. I heard that discord.py was discontinued but i may be wrong
try using python3
it had been discontinued
but they brought it back
root@vmd104222:~/hi# sudo apt-get install python3
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
python3 is already the newest version (3.9.2-3).
python3 set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
root@vmd104222:~/hi# python --version
Python 2.7.18
root@vmd104222:~/hi# 0
bruh
just type "python3"
async def on_raw_reaction_add(payload):
if payload.channel_id == 1053432855847522434:
if payload.emoji.name == "π©":
guild = bot.get_guild(payload.guild_id)
overwrites = {
guild.me: discord.PermissionOverwrite(view_channel=True),
payload.member: discord.PermissionOverwrite(view_channel=True),
guild.default_role: discord.PermissionOverwrite(view_channel=False)
}
for role in guild.roles[1:4]:
overwrites[role] = discord.PermissionOverwrite(view_channel=True)
channel = await guild.create_text_channel(f"Ticket-{payload.member.display_name}", overwrites=overwrites)
sendticket = discord.Embed(title=f"Tickets on Pirates Developments", description=f"Thanks for contacting support, {ctx.author.name} here at **Pirates Developments**. Our amazing staff members will be with you shortly and hope to slove your issuses. If you have any information leave it below.")
sendticket.set_footer(text="Β© 2022 Pirates Developments. All rights reserved")
await channel.send(embed=sendticket)```
any who can help me
without errors bot dont work
Is it easy to make a music bot on nextcord?
Cuz it's been a really long time since I started trying to make a music bot on discord.dpy and still can't
Someone can send me the command to install Discord library?
We're not gonna help with music bots anymore as it usually violates the company's terms of service
Can you show us your error handler?
The error handler?
You're 100% sure?
What's it say in the console then?
In that case make sure the function itself is being called
Well you arenβt sending a string
But it would cause an error because it would call format on a set so if thereβs no error then make sure that the command itself is being called like robin said
Try adding a print statement at the top of the command and see if it prints
yeah that's why i wanted you to be 100% sure there's no error handler
we don't do that here
they're not supposed to be doing that
if you want code to be written for you there are platforms like fiverr where you can pay people to do that
then listen to us and fix it for free Β―_(γ)_/Β―
Hi, I was wondering if I can please get some help with this simple program game of rock paper scissor. Thank you
Paste your code & traceback and we'll take a look!
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
'''
import random
def start_game():
rock_paper_scissors = ['R','P','S']
#'R' = Rock
#'P' = Paper
#'S' = Scissors
print("""-------HOW TO PLAY--------
Type 'R' for Rock
Type 'P' for Paper
Type 'S' for Sissors
---------------------------""")
user = input("Rock Paper or Scissors?: ").upper()
while user != 'Q':
#if user input is not
if user not in rock_paper_scissors:
return 'Invaild Input!'
#opponent randomly selects a from list
opponent = random.choice(rock_paper_scissors)
#if the user and the opponent choose the same, then it is a tie.
if tie(user, opponent):
return 'It is a tie! Type "Q" to Quit'
#if the opponent chooses incorrectly, then the player wins the game.
elif player_wins(user, opponent):
return 'You win! Type "Q" to Quit'
#if the player choose correctly, then the oppoenent wins the game.
elif opp_wins(user,opponent):
return 'You Lose! Type "Q" to Quit'
#scissors > paper, rock > scissors, paper > rock
#Paper defeats Rock
#Rock Defeats Scissors
#Scissors Defeats Rock
def player_wins(player, your_opponent):
if (player == 'S' and your_opponent == 'P') or (player == 'R' and your_opponent == 'S') or (player == 'P' and your_opponent == 'R'):
return True
def opp_wins(player, your_opponent):
if (your_opponent == 'S' and player == 'P') or (your_opponent == 'R' and player == 'S') or (your_opponent == 'P' and player == 'R'):
return True
#When the player and the opponenet chose the same.
def tie(player, your_opponent):
if (player == your_opponent):
return True
start_game()'''
sorry!
There we go, Thanks
So, I am trying to allow the player (user) continue playing unless 'Q' is inputted. However, this seems to not work
Oh, doesn't look discord.py related.
Can you open a help post in #1035199133436354600 with the same code?
Okay!
Any who can help
Would I put this line of code into start_game()?
Its without errors but idk why it didnt work
Okay, I will give this a try
how do i get a users name and avatar url from channel.history?
I'm getting a syntax error with the key. But I think I can make it work
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
someone help ^^
!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.
You can get a list of messages in the channel's history with something like [message async for message in textchannel.history(...)]. This'll return a list of Message objects each of which have an author.
Thanks, got it.
Ran into another issue, how do i get images?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
Thats the thing, with channel.history it prints [<Attachment id=1053452869719822366 filename='.png' url='https://urlhere.com%27%3E]
what are you trying to do with it?
you can probably just add .url
you are getting the attachment object
so you gotta specify what you want from it
so Im using webhooks to get images but it just sends that instead of an actual image embedded
try .url
'list' object has no attribute 'url'
show code
messages = await channel.history(limit=100000000000).flatten()
try:
image = str(message.attachments.url)
await webhook.send(image, username=message.author.nick, avatar_url=message.author.avatar)
except Exception as e:
print(e)```
There morre but has webhook and channel id
oh- pretty sure because you are getting a bunch of images not just 1
No it just has 1 image url
Well attachments is a list so you can get the first element with attachments[0]
it also has %27%3E after .jpg or .png
oh?, try and just [0] it
oops
how did you add the [0]?
Forgot to delete .url hold on
message.attachments[0]?
It works tysm
One more thing lol, is there a way to send the images to a specific channel? (sending webhook to specific channel in other words)
get the channel and send the message
create a webhook
with the bot
webhooks are creating from channels
so whatever u send through a webhook will always be in that channel
any particular reason you are doing it through a webhook?
So basically my friends had a group chat for the club and the teacher is finally joining and some messages that are off topic cant be there, so I am using a bot to transfer it
Hello. I moved my bot from another hoster to another hoster but i have some issues
Task exception was never retrieved
future: <Task finished name='Task-58' coro=<ticket_response.on_component() done, defined at C:\Users\--\Desktop\Mirage DC Bot\ext\ticket_response.py:240> exception=FileNotFoundError(2, 'No such file or directory')>
Traceback (most recent call last):
File "C:\Users\--\Desktop\Mirage DC Bot\ext\ticket_response.py", line 243, in on_component
await self.close_ticket(ctx, reason = None)
File "C:\Users\--\Desktop\Mirage DC Bot\ext\ticket_response.py", line 288, in close_ticket
file = interactions.File(filename=f'./transcripts/{channel.name}.html')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\--\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions\api\models\misc.py", line 324, in __init__
self._fp = open(filename, "rb") if not fp or fp is MISSING else fp
^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: './transcripts/ticket-97.html'
cant close my tickets
directory on new host is probably different
if you dont have console access you can probably run a python file to get the cwd
i have full access but i cant find it...
i cant find the part to change the directory
wdym? youll just have to navigate to /transcripts/ assuming the folder and that file exists / are created
is created..
When i create a Ticket its everything fine, but when i want to close =
so then my next guess is its trying to open that html file it looks like, but cant find it
thanks found the fix
damn not fixxed. when i create a ticket it names: ticket-100 and i create in the folder ticket-100.html then it close
but i habe 5 different types of tickets and they get renamed randomly my firstnames
the ticket closes? and im assuming you are just randomizing/counting for the ticket-(number)
yes when i dont change the name it will be close. Example. You create a ticket. it will be named maybe ticket-120. My team must be rename it to duckv9
why dont you just name it as the name of the user who made the ticket?
same with the file
back then it worked but today i change it to another hoster
since then it dont worked
the host shouldnt effect the code though
i could see some directories being changed at the least
because when its be in editing it will be π‘duck
When the edit is finished then it will be π’duck
File "C:\Users\--\Desktop\Mirage DC Bot\ext\ticket_response.py", line 288, in close_ticket
file = interactions.File(filename=f'./transcripts/{channel.name}.html')
but you can change the contents of the file after its made without editing the file name, for example -
create channel with name ( i.e duckv9-ticket ) and a transcript file ( i.e duckv9-transcript(-datemaybe))
do whatever in ticket
when ticket is closed, transcript everything into the file and delete the channel or rename the channel to duckv9-ticket-closed
then you can close the file and upload it to the ticket (prior to closing it)
thats the code
log_channel = await interactions.get(self.client, interactions.Channel, object_id=1024695080080113764)
embed = interactions.Embed(fields=fields, author=author, thumbnail=thumbnail, color=color)
await ctx.send('Dieses Ticket wird in 10 Sekunden geschlossen')
os.system(f'dotnet DiscordChatExporter.CLI/DiscordChatExporter.Cli.dll export -t "BOT--TOKEN" -b -c "{channel.id}" "-o" "transcripts/{channel.name}.html"')
file = interactions.File(filename=f'./transcripts/{channel.name}.html')
await member.send(embeds=embed, files=file)
await log_channel.send(embeds=embed)
await asyncio.sleep(10)
await channel.delete()
collection.delete_one({'_id' : f'{channel.id}'})
with open('./utils/ticket_ids.json', 'r+') as f:
data = json.load(f)
list = data['ticket_channels']
list.remove(str(channel.id))
print(list)
data['ticket_channels'] = list
f.seek(0)
json.dump(data, f)
f.truncate()
ok I want my first button to send a second button when clicked but I'm stuck
can someone help me whenever i run the command it gives the application did not respond https://tinyurl.com/2p2ygmnt
interaction.response returns InteractionResponse, you don't call that. You have to use one of the various response methods that InteractionResponse offers
it also keeps saying this 404 Not Found (error code: 10062): Unknown interaction
you can just set the view to whatever the button is?
can you send the entire code?
is it synced?
which one would allow me to use the second class I just showed?
What
either send_message or edit_message
I do not know what that means
it is synced, otherwise they wouldn't be able to use it
slash commands take time to sync by default, so unless you sync it manually or give it a debug guild it might not work right away
It's been doing this for days
see ive been told that, then ive also seen people able to run it without any output, then after manually syncing it would work so
Β―_(γ)_/Β―
^
I'll send it in dms
dont wanna clog up the channel
!paste
defer before you send an HTTP request
if you ever defer, it's probably always best to do it at the start of the callback
also don't use requests
you were good using aiohttp - there's no point in spontaneously switching to requests
i just used the one request out putting the image to a file because of this
testing purposes basically
is there any reason why you're purposefully sleeping for 5 seconds after each defer?
thats what everywhere online said to do

internet is always right
hahahaha
no - sleeping serves no use
.bm
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
fav quote
now sometimes when i do the command it doesnt stop thinking
because you're not sending a followup
check your if status == 'available_later'
probably because you're using requests then?
i removed it
any errors?
hmmm, any error handlers that might be eating up yer errors?
one second
ok yea my log file is telling me something about the capes
ok so i called it again and it works perfectly the second time though
i didnt save it or anything
ok i put the capes one into its own seperate json file and that seemed to fix it
after defering a response, if u dont send further messages it will be thinking forever after 15 mins over
oh u fixed it xd
i see
yea thanks tho
nahhhhh, fixing something urself, is just great
is there a decorator to limit a slash command to admins only?
i think you want to use default_permissions
https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=default_perm#discord.app_commands.default_permissions
Yw
im trying to challenge god
will this work
What's with the $?
basically what a ? is in other python db libs
so confused rn