#discord-bots
1 messages ยท Page 217 of 1
Oh
well with fetch how could I add reactions?
fetch will return you the full message object
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
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. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
So like this?
Because I read the document and it had nothing to do with reactions and etc
No, message is still PartialInteractionMessage. message.fetch() returns InteractionMessage. Use the returned value to add the reaction
and how could we get the returned value? what by doing an if statement?
disregard the other message
def foo():
return 1
foo returns a value of type int. In this case, 1. You can get the value by pointing a variable to it
def foo():
return 1
value = foo()
value now has the value of the returned value of foo (so 1)
!e print(4194432 << 16)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
274886295552
@fading marlin Something like this?
In the example I showed you, foo acts like message.fetch
the function was just an example
what would return 1 even do here
y = x.function()
y.do_something()
this is what you need
Hi guys, quick question
Using disnake:
ApplicationCommandInteraction.bot
I wanna know if this parameter returns an instance of the actual bot/client running or the bot object from discord, because i've added some extra parameters in my bot and i wanna know if I can join them with the command interaction
@fading marlin ???
fetch is a coroutine, and doesn't need any parameters
The former
you have to save the return value of fetch to a variable and then use it
and how would I use the value?
why are you doing def fetch
I'm following his example
this is what I have
yeah the example was just an example
fetch is defined by discord.py
you don't define it yourself
It's an example. You don't have to literally create a new function. foo just represents fetch, nothing else
Now I am confused on how to fetch the message
return to this and assign the return value of fetch to a variable
then use add_reaction on that variable
I did this
msg = await interaction.send(embed=embed)
msg.fetch
return await msg.add_reaction("โ
")
what do you expect msg.fetch to do here
!e ```py
def example_fetch_function():
pass
print(example_fetch_function)
@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.
<function example_fetch_function at 0x7f5e31fb8680>
this is what you're doing right now
you're not calling the function, not awaiting it, and not assigning the return value to anything
So then what am I gonna do?
all of these
You said I'm not gonna call the function
no, you aren't calling it right now
what's incorrect then if I am not calling it right?
wdym?
Bro this is basic. to call function you just basically do
foo()
Put parentheses in end of function to call it
Btw this function is coroutine and you need to await coroutine
await fetch()```
any ppl from hikari here?
me
?
this parameter returns an instance of the actual bot/client running
but this way, its not going to delete the bots messages am I right?
it is, unless you filter them
await StageChannel.purge(check=lambda m: m.author != bot.user)
just loop over the roles and use continue when you encounter it
?
Yea that should work too
but this is still not going to delete the bot's messages right?
purge without any arguments will
this won't because there's a check
but then, its gonna prompt an error
wait ill send it here
this error
thats what I was willing to fix
tried to catch it but it didn't work
hi can someone help me im getting this error when i run the command on my linux server it just started happening the command used to work
the error 404 Not Found (error code: 10062): Unknown interaction
print the message that it's deleting first maybe to find out what it is
Im looking to check if any of the users roles is in a SQL row, can anyone help?
this is what i got but its not working at all
what do u mean
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
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 **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, 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 [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") 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")
Why you just don't use this decorator?
what library are you using right now
discord-py-slash-command
because he's looping over the roles
ok that library is also really outdated but i meant for your database
can I have an example?
just print(message.author) and print(message.content) before you delete it
sqlite3
yeah so you would use discord.py 2.0 and aiosqlite3
on the check= right?
.
why#
Well , i thought he's trying to only allow users that has specific role(s) to use command
how can I add reaction to a interaction message?
I tried this but it didn't work:
await original_message.add_reaction('โ')```
What is original_message
original_message = await interaction.original_response()```
and the interaction is defer
- discord-py-slash-command is extremely outdated
- sqlite3 is blocking
!blocking
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
?
thats what I did
or InteractionResponse.defer(), where thinking is True)
thinking is true by default
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
bruh what they already did that
someone please ๐ญ
you are probably responding twice
in the case of hybrid commands though
i'm not sure
is there a way that a command can execute other commands in order?
which type of command?
interactions
I only respond once
for interactions probably no as there has to be an interaction to respond to but you could split the logic off into its own function
sorry i meant to ping joshua
i see, thanks
he said you may be responding more than one time
that's usually the only time "unknown interaction" errors happen
hmm
if I remember, it happened to me when I forgot to defer my interaction, but it may not relate to this case
yeah or if you take too long to respond
yes
ig doesnt hurt to try
yas
i think you can use Context.typing to handle that?? i don't remember
do you know how can I solve
#discord-bots message
why would it not work
can i see the code?
wait ill send it
defering fixed it, thanks
is there a interaction.autor.role ?
nice
how did you defer in a hybrid command ๐ค
not sure on what you are refering to what do you mean by interaction.autor.role?
bruh im so clueless
interaction.user returns Union[User, Member]
is that not a thing u can do?
idk that's why i asked
thats the reason I didn't come up saying about deferring, I saw its not a slash command
i thought hybrid commands took in context
then what code did you use
i sent it
to defer
wait wtf
await ctx.defer()
bruh discord.py interaction code is so useless it's like a whole seperate library
? thats a thing
i want to get what roles does the user that interacted has
it doesn't even make sense to defer a context
no reason to anyways its useless
yes there is in an app command
welp it doesn't make sense to defer context really
hmm, it seems to be working for some reason, https://cdn.agamsol.xyz/media/DiscordCanary_gYNz2Ohycs.png
ok, my next thing is to listen if the user adds a reaction, how can I do that?
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
it works on interactions?
!d discord.Member.roles
No documentation found for the requested symbol.
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ@everyone](mailto:'%40everyone)โ role.
These roles are sorted by their position in the role hierarchy.
how is it finding something when its not even there
r comes back with a row
it works for any event
why are you doing SELECT value
it's SELECT <x> where <x> is the column name
how do i put everything i selected in a dic?
dictionary*
array
dic = [] and i wanna put each value selected from the table seperate in the dictionary
that syntax creates a list, not a dictionary
have you tried dict(record)?
ok im given this dict
and i want to search for a role ID in it
how do i do so?
this didnt work
i think its cuz its
"x": ROLEIDVAL,
and not just ROLEIDVAL, ROLEIDVAL, ROLEIDVAL
also why do you keep calling them dic that's kind of concerning
its kinda complicated
so when the else block of the try-except block is gonna be triggered, it means that the reaction was done, in time?
yeah if you are referring to TimeoutError
it is only 5 pm but thanks
The fields are
guild_id | group_id | 0 | 1 | skip a few | 255
yes
i think you need to rework your schema
whats wrong with it
also in a normal table how many rows can it store? @smoky sinew
that may let me change my schema
many millions
it's about 2^64 i believe
but on sqlite it's probably less
thats quite a few
ok i got an idea to change my schema
I have no errors with my bot but more of an import question, I looked up jus good things to save data: I found pickle its eh. I was wondering whats the best way to log user data just like a integers such as amount they used certain command.
I personally use sqlite3/db browser which is pretty straight forward to use for basic tables like that
just use sqlite with aiosqlite3
I'd look into learning SQL, it's a programming language (albeit very English and easy to learn) that allows you to read & write to database files. There's a few Python libraries such as asqlite that allow you to do that quite easily in your code.
I'd also recommend checking out #databases for further help with SQL-related stuff.
is there a big difference from sqlite to mongo?
Yes
Sqlite is a serverless, zero-conf, relational database
Mongo is a NoSQL database
I remember creating pickle "database" ๐
-0?"+______________________{[[[[[[[ujmkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk /
@commands.command()
@commands.has_role(876359978376642570)
async def status(self, ctx):
channel = bot.get_channel(1086790739582791710)
message = await channel.fetch_message(1086790739582791710-1087558681132011521)
await message.edit(content="eee")```
my code wont change the message and gives error:
```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'fetch_message'```
so the get_channel call returned None
are you sure that channel id is valid?
yes
and what intents do you have enabled?
all
are you sure the bot is properly logged in before you use the command?
yes, i have the on start thingy to say it is
try using fetch_channel instead
!d discord.Client.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_channel "discord.Client.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
what
how is bot defined here?
is that command in a cog, and in an extension file?
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
its the same thing ive been using for all my bots ever, not ever caused a bug
cog, same directory/file
do you have this line multiple times?
its in the cog and main.py because otherwise the cog file cant know what bot is
async def setup(bot):
await bot.add_cog(Cog(bot))
you should not be making a new bot instance
where does this go?
in the extension file
are you not using extensions?
how are you adding the cog currently?
what is exentsion?
i dont think i am using that
how are you adding the cog currently?
and where is this line?
@bot.event
async def on_ready():
print('Bot is ready.')
await bot.add_cog(Commands(bot))
await bot.change_presence(activity=discord.Game(name="FuzedHosting.com"))```
self.bot = bot
so use self.bot to access the bot instance in the class
why make another bot instance
red signal on which line
top corner saying bruh u fucked up smthn in code
oh u mean...
nvm lol
it fucks up the line
which line
channel = bot.get_channel(1086790739582791710)```
self.bot ^^
thanks, works
hello I need help can someone help
Drop ur problem or questions
how do i remove a category from the built-in help command? i made a new class for commands, but they are admin commands, and i dont want em public to see
Idk if you can apply this to categories, but you certainly can apply a hidden=True kwarg to each of these commands in your category
well, i asked chatgpt for help, and it said to do that for class, but it didnt work for class
so il try for individual commands
It only works for command
alr
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
you can apply the hidden=True to each command via the Cog's command_attrs
Idk about cog class tho
is there any way to make the class not appear?
wait
i found out how
if there are no commands visible in the class, the class just does not appear on the help. nice
Applying hidden to all commands will make it disappear too iirc
ye thx
[2023-03-21 12:16:47] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: *********************).
is it possible to hide this stuff when the but is starting to run?
(at least the INFO prefixed ones)
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
or if you can log only warnings and higher
log_level=logging.WARNING
or this
working
its 30 but you can just say logging.WARNING
๐
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/runner/MathBot-1/cogs/userinput.py", line 47, in respond
data = (await collection.find_one({ "_id" : interaction.message.id }))[ "already_voted" ]
RuntimeError: Task <Task pending name='discord-ui-view-dispatch-9049f46c6d54b21fae2271a7d5092095' coro=<View._scheduled_task() running at /opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py:427>> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib/python3.8/asyncio/futures.py:360]> attached to a different loop
```guys what does this mean ๐
!e
import asyncio
loop = asyncio.new_event_loop()
fut = loop.create_future()
async def main():
await fut
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 12, in <module>
003 | loop.run_until_complete(main())
004 | File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
005 | return future.result()
006 | ^^^^^^^^^^^^^^^
007 | File "/home/main.py", line 7, in main
008 | await fut
009 | RuntimeError: Task <Task pending name='Task-1' coro=<main() running at /home/main.py:7> cb=[_run_until_complete_cb() at /usr/local/lib/python3.11/asyncio/base_events.py:180]> got Future <Future pending> attached to a different loop
It means exactly what it says
thats the point, i dont understand what it says
How can I make my bot display a custom activity?
I wanna do it when the bot starts up
I have the following code but it throws an error:
bot_activity = discord.CustomActivity('Waiting for users to connect to clients', emoji=discord.partial_emoji('skull'))
await client.change_presence(status=discord.Status.idle, activity=bot_activity)
Traceback (most recent call last):
File "C:\Users\Agam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "D:\Windows\Users\Agam\Desktop\Programs\Python\Audio-RC-Python\Audio-RC\discord-bot.py", line 169, in on_ready
bot_activity = discord.CustomActivity('Waiting for users to connect to clients', emoji=discord.partial_emoji('skull'))
TypeError: 'module' object is not callable```
and also how can i fix it?
async def respond(self, interaction: discord.Interaction, button: discord.ui.Button):
data = (await collection.find_one({ "_id" : interaction.message.id }))[ "already_voted" ]
if interaction.user.id in data:
await interaction.response.send_message("You have already responded.", ephemeral=True)
else:
await interaction.response.send_modal(VoteModal())
can anyone tell me why this doent work as a loop?
import asyncio
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$pingloop'):
while True:
await message.channel.send(f'My ping {round(client.latency * 1000)}ms!')
await asyncio.sleep(60) # wait for 60 seconds before sending the next ping
Hey
async def on_message(self, message):
if message.author.id == self.user.id:
return
if message.content('Fuck', "Shut up", "Fuck you"):
await message.delete(message.reply("Hey you can't say that!"))``` Whenever I say "Fuck" or "Fuck you" my bot doesnt delete it and respond to it. Im not sure why
At first I did message.content.startswith but Idk if that would be correct
No offense, but python beginners be like
Check pins
Wait so whats wrong with the code??
Check discord.py commands framework documentation and discord.ext.tasks.loop
I suspect you have no knowledge about functions
I do
and what I'm seeing right now is that the return keyword is returning nothing
So Idk what it's supposed to return
Then uh how can you explain calling message.content
I made it message.content.startswith
async def on_message(self, message):
if message.author.id == self.user.id:
return
if message.content.startswith('Fuck', "Shut up", "Fuck you"):
await message.delete(message.reply("Hey you can't say that!"))```
It returns a boolean
No it doesnt return anything
I say "Fuck" in the discord server and nothing happens
!d str.startswith
str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
Wait so I need prefix for that??
And look into arguments
No one is gonna say ?Fuck
how are we supposed to handle check failure exceptions ?
Arguments are what inside of the brackets right?
Ok so these discord bot github examples are useless
is that last line even possible
Separate await message.delete() and await message.reply()
like calling two asynchronous methods with just one await
No
And they probably meant to delete the message with the swear word
Not the one replying about it
See it isn't doing anything this bot fr dooky
Two different lines
await message.delete
message.reply("Hey you can't say that!")```
The message that is to be deleted is message, not the bot's reply
Ohhh I get it now
ahh yeah just realized that mb
You should reply before deleting the message
async def on_message(self, message):
if message.author.id == self.user.id:
return
if message.content.startswith('Fuck', "Shut up", "Fuck you"):
await message.delete
await message.reply("Hey you can't say that!")```
Oh so flip it around?
async def on_message(self, message):
if message.author.id == self.user.id:
return
if message.content.startswith('Fuck', "Shut up", "Fuck you"):
await message.reply("Hey you can't say that!")
await message.delete```
Alright I did that
Still didn't call message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleโs messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").
Changed in version 1.1: Added the new `delay` keyword-only parameter.
no you just have to do
msg.delete() instead of just msg.delete
await message.delete()``` Like this?
yeah
How else would any Discord member delete other members' messages?
Ok so manage_messages is a seperate function right??
can someone help me fix this error```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/runner/MathBot-1/cogs/userinput.py", line 45, in respond
data = (await interaction.client.database.find_one({ "_id" : interaction.message.id }))[ "already_voted" ]
RuntimeError: Task <Task pending name='discord-ui-view-dispatch-d2e5a57124186e2aaec5ef6217792cbe' coro=<View._scheduled_task() running at /opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py:427>> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib/python3.8/asyncio/futures.py:360]> attached to a different loop
Or does it fall under on_message
Yea I say Fuck and the bot doesnt reply to it damn it
Just like you need to give this permission to Discord members for them to be able to delete other members' messages, the bot member needs it
Wait but isn't the permissions in the Discord bot developer portal?
You just give it administrator?
No those are privileged intents that don't matter here
You're supplying multiple string arguments to startswith, it only takes one string argument
I knew it
So the commas dont seperate the phrases there's only 1 phrase I can put in right?
async def on_message(self, message):
if message.author.id == self.user.id:
return
if message.content.startswith('Fuck'):
await message.reply("Hey you can't say that!")
await message.delete()``` So is this code good??
the return is still making me ponder ๐ค
discord limits button ui interations to two per 10 minutes?
responded with 429. Retrying in 575.73 seconds.```
The if with the return is just there to stop handling a message when the author of the message is the bot (compares IDs)
Correct
Ohhhh
is it possible to have an argument (application_commands) that contains a list of all the server members who are having a certain role? exactly like discord.member, just presents only those who have a certain role
Wait so now I gotta make a seperate function manage_messages to let my bot delete messages?
No
manage_messages is the name of the permission in discord.py. If your bot cannot delete your message because it's lacking Manage Messages, you need to permit it in the Discord server's settings like you do for roles (do it for the bot's role). Nobody can touch server owners, so maybe not even that permission can permit your bot to delete your message if you are the server owner
The gist link doesnโt work
You don't really need it, everything's is written in the message. Isn't it?
!d discord.Role.members sure
property members```
Returns all the members with this role.
UI interactions aren't really limited since they are gateway events and are initiated by discord
Although responses are done not via gateway
What exactly the endpoint is
if we talk about the same message, then yes, but it doesn't seem like that
#discord-bots message
I actually meant this one #discord-bots message
I mean, want it to be custom
just like users do
with an emoji and all that
it doesn't seem to be listed
Not possible
!d or
6.11. Boolean operations
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a `__bool__()` method.
The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
you should wither use any() or or
then use
if .... in message.content:
Then do stuff
!d any
any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:
```py
def any(iterable):
for element in iterable:
if element:
return True
return False
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a โsecretโ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
category (Optional[CategoryChannel]) โ The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.
so you'll need to get the CategoryChannel with interaction.guild.get_channel first, and then pass that
Collaborate on what?
how can I add a permission to a specific member and channel channel?
view_channel
Do you mean adding a channel-specific permission overwrite?
I mean, I want to add a permission, for a user, in a specific channel
without roles
like this in specific channel
!d discord.abc.GuildChannel.set_permissions Check this out from the discord.py docs
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
You can specify target to be a guild member or a role
Also remember, it should be a Member object
is this acceptable?
member = discord.Member()
member.id = interaction.user.id
I want to add the permission to a specific user
Yea it's a member. You can use interaction.user
no need .id?
Permissions to role or in channel?
in channel, specific member
The user or member that sent the interaction.
You should not be creating your own instance of Member, use something like guild.get_member to retrieve a Member of the given guild, or as Random Being said, interaction.user returns the author's Member object if the interaction takes place within a guild.
Do not use get_member, just interaction.user
I am kinda confused now xd
Discord bots become a hassle when they get big
Just interaction.user
the object right?
Yes
Sorry wrong reply but refering to your question.
Interaction.user returns discord.User, discord.Member object
so I dont need discord.Member right?
No. That's a class, not an instance
You are new in python right?
https://discordpy.readthedocs.io/en/latest/index.html
When you write the bot, if you don't know some things, it would be good to look it up in the docs.
Everything about discord.py is on docs
yeah, I know, I just still need some guiding through it
Well you can search it docs about interaction.user
And you can see what returns, type etc.
i'm trying to code a quick admin bot for my server (still learning python, and coding in general)
and i feel i'm doing smth wrong bc i try to use pip3 install -r requirements.txt to install discord.py latest version and it says that's not installed
when i run that command, it says pip3 is not recognised
Just run pip install discord.py
not working 
Error?
The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
Add python to path
discord bot
@slate swan man
hey, i want to remove my program from my vps background
how i can process ?
you need to find PID of process you want to stop
how ? ^^
you can find out using ps or top command
not sure about top actually
and then when you have the PID you do kill -9 {your_pid_here}
htop supremacy
wdym
I'm just joking around. I much like htop
how can i know it's the process i want ?
When Discord starts acting funky I can
it
hmm
help pls
should be something called python
or sum
a
@slate swan and how can i reset my vps ?
๐

@slate swan sorry for disturbing again, i want to start my script on my vps but i receive error, could you help me ?
your token was invalid
yeah i saw ^^
I've been experimenting with slash commands, since that means I don't need the message intent. I've been syncing my slash command tree in on_ready. However, I've been told that that's not a good idea due to rate limiting, and that I should use an admin-only message command instead to sync the slash commands. This would require the message intent, which, to me, would seem to negate one of the advantages of slash commands.
TL;DR: is there a way of syncing the slash command tree which does not involve on_ready and does not require the message intent?
can you post a screenshot of the full traceback
also what is your discord.py version
well how did you install it
so run pip3 list
also you should in future run pip3 install discord.py
discord is a mirror package
but at the moment those are on the same version so it doesn't matter
hmmm
that's odd
I had this same problem easy fix
how are you running your bot
change:
intents = discord.Intents.default()
to:
intents = discord.Intents.all()
that's not going to help
and go to your bot settings in discord dev portal
no....
do not do that
stop
@little narwhal this is unrelated to his issue
that will not fix it
he doesn't have the intents attribute in his discord library
calling a different subattribute of a parent attriobute which doesn't exist isn't going to magically add the parent attribute
well, you could try that
but 2.1.1 should be new enough
@slate swan how are you running your bot bruh
intents has been in there since 1.5
oh
run it from the terminal
is python.org a good app to use python in or do i stick tot replit
your interpreter is probably different
sometimes it gets mixed up with virtual environments
python.org is not an app, it is just a website to download python
ye mb
which one is better?
depends on your needs
they are not comparable really
uninstall the microsoft store version and install it from python.org
Hey you may remember me from yesterday, ive changed my schema but im not sure if this is the correct syntax, can you maybe help correct it?
what's wrong with it
add or remove programs
x64 x86_64 and amd64 are all the same
How can i select data from 2 tables if possible in one execution? e.g:
well based on this traceback, i wouldnt have assumed it was an issue with microsoft store python, my two guesses for the cause would be having a file named discord.py or having installed multiple conflicting packages that corrupted dpy
usually its in your local appdata folder but you dont normally need to know the exact location
does running py in the terminal work?
after installing you usually want to restart your terminal/editor to make sure it updates with any changes to PATH
huh, never seen py explicitly ask that
btw can you show what your project structure looks like?
before you go reinstall discord.py
ive now got this btw
what files are in your project folder? what are they named?
yeah that's likely the real cause of your last error
did you install discord.py?
using pip
how many python installations do you have now? is it just one
its fairly easy to mix them up when you use their commands directly so id suggest running stuff through py instead, e.g. py -m pip install discord.py
!windows-path
If you have installed Python but forgot to check the Add Python to PATH option during the installation, you may still be able to access your installation with ease.
If you did not uncheck the option to install the py launcher, then you'll instead have a py command which can be used in the same way. If you want to be able to access your Python installation via the python command, then your best option is to re-install Python (remembering to tick the Add Python to PATH checkbox).
You can pass any options to the Python interpreter, e.g. to install the [numpy](https://pypi.org/project/numpy/) module from PyPI you can run py -3 -m pip install numpy or python -m pip install numpy.
You can also access different versions of Python using the version flag of the py command, like so:
C:\Users\Username> py -3.7
... Python 3.7 starts ...
C:\Users\Username> py -3.6
... Python 3.6 starts ...
C:\Users\Username> py -2
... Python 2 (any version installed) starts ...
ah whatever install discord.py however you want and if it still cant find discord, then you're mixing up your installations
type where pip, if it doesnt match the version you have selected in your editor then you've installed discord.py to a different python installation
im on the python app and when i try press enter, it shows my code instead of going down
anyone know how i can go a line down?
Can you send a screenshot of your screen?
i found it ๐ i had to just go into file and press new
i was on the shell
discord_slash for 2.2 just wont work
I import but it just says I haven't imported
idk why, I have imported correctly and it is on correct path to work in environment but it just doesn't think I have it
why would you need to use discord_slash with discord.py 2.0
what should I use
the built-in discord.py slash command system
send documentation
ty
hello, how can I get a channel's id with interactions?
is it something like interaction.message.channel.id?
interactions will not always have a message
ids are not strings
and also use the in operator for that
with a tuple
like if message.author.id in (1, 2, 3):
yes use a list comprehension
with any
if any([r in member.roles for r in (1, 2, 3)]):
*member._roles
why so?
would be nice if dpy exposed a proxy to that mapping, but i guess you dont usually have enough roles for that optimization to be worth it
oh wait thats just a sorted list
discord/member.py line 351
self._roles: utils.SnowflakeList = utils.SnowflakeList(map(int, data['roles']))```
`discord/utils.py` lines 783 to 793
```py
class SnowflakeList(_SnowflakeListBase):
"""Internal data storage class to efficiently store a list of snowflakes.
This should have the following characteristics:
- Low memory usage
- O(n) iteration (obviously)
- O(n log n) initial creation if data is unsorted
- O(log n) search and indexing
- O(n) insertion
"""```
the difference is negligible
theres also the fact that an integer wont exist in a list of Roles
yes that's what the list comprehension is useful for
but your example is trying to test if an integer exists in a list of roles
lol
.roles: list[Role]
._roles: list[int]
and you're doing py int in list[Role]
yes i'm aware
oh i didn't see recent message sorry:p
just use _roles as sarth pointed out
it does?
what error
if any([role in member.roles for role in (
guild.get_role(1),
guild.get_role(2),
guild.get_role(3)
)]):
you could use this instead i guess
@slate swan python is case sensitive
does anyone have/know of a discord bot example github repo I can view (or a sample code for a slash command?)
There are examples in official discord.py repo
oh neat
Hey there, recently I had made an image generation bot that used OpenAi API, it worked perfectly fine, then U thought of moving to slash cmds and replaced discord.py with pycord, it stopped working. I googled, asked chatgpt and did everything i could still the bot didn't work. I uninstalled Pycord and installed discord.py 3 times, the bot runs without any error, but doesnt listen to any of my command. It shows online, but doesnt follow any command, even though it's online and doesn't give any error
discord.py supports slash commands since version 2 came out
No need to switch wrapper libraries or a third party library
guys how to make cogs in discord.py
who knows to make cogs? if u know how to make cogs, then DM me
guys how to make cogs in discord.py
who knows to make cogs? if u know how to make cogs, then DM me
guys how to make cogs in discord.py
who knows to make cogs? if u know how to make cogs, then DM me
Cog is just a class inheriting from commands.Cog. They are typically placed into extensions - simple python modules with setup() function defined. That function accepts bot as argument and adds cogs to it. You can load extension with bot.load_extension(). For further explanations see docs
And yeah no need to send your message 3 times
In a fricking row
docs?
documentation
discord.py documentation?
yes
k
whys it saying local variable embed rerefferensed before assignment py @commands.command() async def roles(self, ctx): i=0 k=1 l=0 mes = "" number = [] messages = [] for role in ctx.guild.roles: mes = f"{mes}`{k}` {role.mention} - <t:{int(role.created_at.timestamp())}:R>\n" k+=1 l+=1 if l == 10: messages.append(mes) number.append(discord.Embed(color=ctx.author.color, title=f"List of roles", description=messages[i])) i+=1 mes = "" l=0 messages.append(mes) embed = discord.Embed(color=ctx.author.color, title=f"List of roles", description=messages[i]) number.append(embed) if len(number) > 1: paginator = pg.Paginator(self.bot, number, ctx, invoker=ctx.author.id) paginator.add_button('prev', style = discord.ButtonStyle.blurple, emoji=':left:') paginator.add_button('next', style = discord.ButtonStyle.blurple, emoji=':right:') #paginator.add_button('goto', style = discord.ButtonStyle.grey, emoji=':skipto:') paginator.add_button('delete', style = discord.ButtonStyle.danger, emoji=':cancel:') await paginator.start() else: await ctx.reply(embed=embed, mention_author=False)
Yeah i came to know that, but now the code doesn't work.
can you help me above? i dont see the error anywhere
lemme see
u tried asking chatgpt
not really no
i dont use that
show full traceback
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'embed' referenced before assignment```
Traceback (most recent call last):
File "C:\Users\MickensTraevon\Desktop\bleed\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\MickensTraevon\Desktop\bleed\cogs\moderation.py", line 41, in roles
await message(self, ctx, None, embed, None, None, None)
UnboundLocalError: local variable 'embed' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\MickensTraevon\Desktop\bleed\jishaku\features\invocation.py", line 168, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "C:\Users\MickensTraevon\Desktop\bleed\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\MickensTraevon\Desktop\bleed\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'embed' referenced before assignment```
the code you have provided does not seem to error
are you using a message coro anywhere?
async def message(self, ctx, content, embed, view, file, allowed_mentions):
try: await ctx.reply(content=content, embed=embed, view=view, file=file, allowed_mentions=allowed_mentions, mention_author=False)
except: await ctx.send(content=content, embed=embed, view=view, file=file, allowed_mentions=allowed_mentions)
@commands.command()
async def roles(self, ctx):
i=0
k=1
l=0
mes = ""
number = []
messages = []
for role in ctx.guild.roles:
mes = f"{mes}`{k}` {role.mention} - <t:{int(role.created_at.timestamp())}:R>\n"
k+=1
l+=1
if l == 10:
messages.append(mes)
number.append(discord.Embed(color=ctx.author.color, title=f"List of roles", description=messages[i]))
i+=1
mes = ""
l=0
messages.append(mes)
embed = discord.Embed(color=ctx.author.color, title=f"List of roles", description=messages[i])
number.append(embed)
if len(number) > 1:
paginator = pg.Paginator(self.bot, number, ctx, invoker=ctx.author.id)
paginator.add_button('prev', style = discord.ButtonStyle.blurple, emoji=':left:')
paginator.add_button('next', style = discord.ButtonStyle.blurple, emoji=':right:')
#paginator.add_button('goto', style = discord.ButtonStyle.grey, emoji=':skipto:')
paginator.add_button('delete', style = discord.ButtonStyle.danger, emoji=':cancel:')
await paginator.start()
else:
await ctx.reply(embed=embed, mention_author=False)
``` i did this and it still errored
it's causing the error because you did something like
#no definition of embed here
await message(ctx, message, embed)
embed = discord.Embed()
well, what's the error in that case?
Traceback (most recent call last):
File "C:\Users\MickensTraevon\Desktop\bleed\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\MickensTraevon\Desktop\bleed\cogs\moderation.py", line 40, in roles
await ctx.reply(embed=embed, mention_author=False)
UnboundLocalError: local variable 'embed' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\MickensTraevon\Desktop\bleed\jishaku\features\invocation.py", line 168, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "C:\Users\MickensTraevon\Desktop\bleed\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\MickensTraevon\Desktop\bleed\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'embed' referenced before assignment```
ah
You see how the if mayy not be triggered and no embed variabled would be created
that's causing the error
if that if statement does not run and straight away the else statement runs
there is no embed variable, and hence no discord.Embed object for it to send
you have to create a new embed inside the else in this case
or create a single embed and update its attributes in any of the above case
how would i do that?
embed = discord.Embed(title="", description="", color=ctx.author.colour)
if something.happens:
embed.title = "You are UwU"
await ctx.send(embed=embed)
await paginator.start()
else:
embed.title = "You are not UwU"
await ctx.send()
something like this
ah
i believe something is blocking it still, and im not understanding what it is since it keeps messing with my brain
@upbeat otter
ah, i got it, i know what is was
ah, i dont, i thought it was fixed, the pagination seems to not be updating and its over 10 roles in the guild, and the py
else statement from if l == 10: isn't working still, i believe something is still blocking it but im not sure why.. @upbeat otter
can anyone help?
why doesnt this work as a loop?
import asyncio
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$pingloop'):
while True:
await message.channel.send(f'My ping {round(client.latency * 1000)}ms!')
await asyncio.sleep(0,1)
@midnight oyster
Hey, sorry for the late reply. I think it should work normally but there should be a way for you to exit the while loop.
Also this asyncio.sleep(1) is the correct one, that asyncio.sleep(0,1)means it should sleep for 0 seconds and return 1
i think he meant 0.1
Didn't I explain it to you yesterday
Anyone wanna contribute on a discord bot
@client.command()
AttributeError: 'Client' object has no attribute 'command' help me
.py?
Use discord.ext.commands.Bot if you want that decorator, not discord.Client
tht client =?
You might as well name it bot because it's an instance of a class that is called Bot
ok
bot = discord.ext.commands.Bot?
You have to import commands from discord.ext somehow, so just do as I did
i did it now?
Yeah but like here I showed you the import and the instantiation lines
So i have to copy paste it?
You can't instantiate by calling discord.ext.commands.Bot, it will tell you that you can't import commands from discord.ext. You have to import it separately
yes but it wouldnโt work
async def on_ready():
TypeError: Client.event() missing 1 required positional argument: 'coro'
Remove the parentheses after .event
still the same error
async def on_ready():
TypeError: Client.event() missing 1 required positional argument: 'coro'
What he said. @bot.event, not @bot.event()
i understood
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.
You need to instantiate the bot with
bot = commands.Bot("!", intents=intents)
Create a variable named intents which will be the intents you need for your bot
Then intents = discord.Intents.default()
Thanks a lot mate
It doesn't include the message privileged intent though so your bot will not be able to see messages and therefore not be able to respond to any command
Oh lol, how do I enable it?
You need to enable privileged intents both in the developer portal and in the variable
Look up the names of the privileged intents on the library side, enable those on the developer portal
it joined the VC but didnt speak
it isnt speaking'
Oh ok
@client.event
async def on_member_remove(member):
user = discord.utils.get(client.get_all_members(), name=member)
print(user.id)
How can I get the member's object who left?
the member parameter is not a user object
which is what Id like to get
You get the member in the parameter, so member.id
but its not the object
It is
wait wa
That's the point of it
The library gives you the member in the parameter
but when I print the member
It's like this with other kinds of events
it shows the name and discrim, instead of showing its an boject
Printing an instance of discord.User (or a subclass, which discord.Member is) first tries to convert the object into a string, just like any other object. discord.User implements __str__ in such a way that you get a string in the format: username#discriminator
Print str(member), you get the same
I think discord.Role and discord.GuildChannel implement something like this too
Maybe not
But all these do have a mention attribute which is a string that serves a mention to these objects
So like [#discord-bots](/guild/267624335836053506/channel/343944376055103488/) for #discord-bots for example
thanks a lot!
Yes
havent coded for a long time, so I have alot of questions:
- do all discord bots need to be all slash commands to work?
- if so, then anyone have any saved docs on how to do the slash commands, is it similar to what we do for example:
@client.command?
no you can still make prefixed commands you just need message_content intent enabled
ahhh, anyone here use replit?
and this is example of such command
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
in discord.py
thank you thank you
from music_cog import music_cog
from tictactoe_cog import tictactoe
intents = discord.Intents.all()
client = commands.Bot(command_prefix=",", intents=intents)
client.add_cog(music_cog(client))
client.add_cog(tictactoe(client))
can someone help me, this seems to not add my cogs, I have all the files in place though
import discord
from discord.ext import commands
from discord.utils import get
import random
player1 = ""
player2 = ""
turn = ""
gameOver = True
board = []
winningConditions = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7],
[2, 5, 8], [0, 4, 8], [2, 4, 6]]
class tictactoe(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def tictactoe(self, ctx, p1: discord.Member, p2: discord.Member):
global count
...
``` this is what the tictactoe_cog file contains
add_cog is a coroutine now
heh? which version did it start?
since discord.py 2.0
so I have to put await?
for example? xd
@client.event
async def setup_hook():
# load cogs
ahh it worked, thank you so much
?
Hi, i can't import tasks from discord.ext. Any idea why?
a simple reinstall seems to do the job
Hi. Idk why, but after some runtime of my bot, the postgres server randomly disconnects. All dB related commands get stuck in "{bot name} is thinking.." with no error whatsoever.
are you using asyncpg?
Does the pg server itself function
Hmm lemme check it on vps
Yep it works when used directly
It doesn't even work when I try an eval command on the bot.
But works when I restart the bot.
Hey @half wind check ur DM
heyo, in terms of locally hosting my bot, what should I do if my PC restarts?
I currently have a windows task scheduled to run monthly to start the bot just as a backup, and I have reconnect on so that wifi wont be an issue, but the only issue I'm running in to is if my computer restarts for some reason, then I have to remote back into it to start the bot again
You use connection pool right?
You can run the bot with docker and setup docker to run on startup
interesting. I tried looking into docker when I was less learned, but I'll try again now
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
Docker part is same for all OS, you will only need to setup docker in a different way rather than for ubuntu
You just download docker desktop and follow instructions
Got it, thanks
if anyone knows how to use cogs would you please help me out in #1088120405887299614? Thank you!! :D
why it sends the message 2x?
async def on_member_update(before, after):
if after.display_name.endswith('แดดแถป'):
guild = client.get_guild(guild_id)
role = discord.utils.get(guild.roles, name='Official Member')
channel = client.get_channel(channel_id)
await channel.send(f'Added roles {role} to {after.display_name}')
await after.add_roles(role)
Anyone plays Minecraft

DM me
Can we keep it here?
I play on a server
I assumed the question was somehow related to discord bots
K
But we already have one of those for staff, so I'm good thanks ๐
There might be 2 instances of ur bot
can somebody help me with implementing a discord bot, i have the codes done. its an ecg(heart monitoring) bot that asks users to correctly guess the problem of heart
what do you need help with exactly?
You might have 2 instances of the bot running
i have another one on_member_update, is that the problem?
you're not checking if a role was added
you're just simply sending "added role" message for every update....
#1088159002250191001
https://paste.pythondiscord.com/ikunanexen
main bot file, known as bot.py
https://paste.pythondiscord.com/afonixequb
cog file, known as ping.py
would anyone possibly know why the slash command coming from the cog isn't working?
add_cog() is asynchronous so you'll need to await it, and usually a warning shows in the terminal when you forget to await a function
yeah, my terminal is terrible and after the on_ready() in the main bot.py, nothing prints after the last '-'
The botโs command tree is only synced on itโs setup hook, which iirc runs before your on_ready command, which runs when the bot connects to the websocket
oh yea true
and on_ready() can be called multiple times which makes it a poor place to set up anything there
Load your cogs in your setup hook, before you sync your command tree
I do have that already I believe
I have await self.add_cog(MPing(self)) currently before the sync
Are you running your main bot file, or your ping.py file?
You have two seperate bot classes?
I'm running the main
Then whatevwr changes you make to that bot class youโre making in ping.py wonโt do anything
You need to make those changes to the class youโre actually using
yeah, I used that for troubleshooting a while ago I should probably fix that
setup_hook included?
Yeah
I see...
would I include await self.add_cog(MyClient(self)) under the main then? or keep that seperate by itself under a function under the cog file?
doesn't return any errors, but on the second hand I also can't see any errors due to my great terminal not wanting to output anything besides what's in on_ready()
new main file: (still not working however,) https://paste.pythondiscord.com/kijumuzido
new ping.py file: (a piece of the problem,) https://paste.pythondiscord.com/safepotebe
your bottom setup_hook is just a random function that wont get called, as per AM2 you should call load_extension() in the setup_hook you wrote for MyClient
is there any way to do @commands.has_role() with interactions?
!d discord.app_commands.checks.has_role (assuming you mean in discord.py)
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_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.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
thanks
I'm confused by what you mean call load_extension() in the setup_hook you wrote for MyClient
how would I do that
would I just throw it under the class?
Ah nvm I understand now ๐คฃ
my brain stopped working for a second
OK
I got the slash commands to show on discord... however every time I use the (one) command I setup (/ping,) it responds with "the application did not respond."
does it show an error in your terminal? self.latency is probably what caused it to fail
yep
would client.latency work (im trying it either way) (it did not work)
interaction.client or self.bot would be two ways to access your bot instance
it worked!
thats why its common to have self.bot = bot in the cog's init method, for easy access to the bot instance
yeah
thank you very much for your help!
Yo!
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
https://paste.pythondiscord.com/ifacosekec
This bot refuses to create a new channel on the new creation of Journa, the embed in that new channel, "react-to-gain-access". When the user reacts with the โ to the embed in line 14 it refuses to do ANYTHING, literally freezes & doesn't even remove his reaction or adds the channel. I don't know where in the code the issue is & I really need help. Thanks!
(basically when the user reacts, it refuses to create a channel under his name bruhh)
on_reaction_add/on_reaction_remove requires whatever message that was reacted to be in the cache, or in other words be a message recently sent while your bot was online, so if your bot restarted afterwards your event handlers will probably never get triggered
the on_raw_reaction_* events would be more suitable for your purpose
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
gahh I fucked up so hard
it doesnt look right
@hushed galleon Could you rewrite the whole script for me fr fr
๐คจ
It suddenly wont work
Now it wont even react with a checkmark at all
!e discord.ext.commands.Bot
@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 | discord.ext.commands.Bot
004 | ^^^^^^^
005 | NameError: name 'discord' is not defined
can you get your event handler to work with the bare minimum code? e.g. py @bot.event async def on_raw_reaction_add(payload): if payload.emoji.name == "โ
": print("saw a checkmark")
try putting more print statements to figure out if your event handler fires, how far it gets in your handler, and what your conditions are evaluating to
@discord.app_commands.checks.has_any_role('admin')
async def remover(self, interaction, user_id: str, tag: str):
if isinstance(error, discord.app_commands.MissingAnyRole('admin')):
await interaction.response.send_message('You do not have the required role to use this command.')```
I know im probably missing something or not used something correctly, but the admin check does not pass
you cant exactly handle a check error inside your command, but regardless have you double checked that the role name exactly matches admin? its usually a better idea to compare the role ID instead so you wont have to worry about it getting renamed or something
- casing matters
yep, its admin. The command works if i have admin and doesnt if i do not have it, but i want to send the message that message if the person does not have the admin role
Yes. That's the "can't handle error inside the callback itself" thegamecracks mentioned
i see
You need a separate function decorated with @inland glacierremover and accepts a ctx and error
^ or alternatively you can write a global error handler to handle the missing role exception from any command
Sorry about the ping, am on mobile lol
e.g. ```py
bot = commands.Bot(...)
@bot.tree.error
async def on_app_error(interaction, error):
if isinstance(error, app_commands.MissingAnyRole):
await interaction...
else:
raise error```
thanks for the help
and for example, if i want it to handle every error to at print something on the console?
raising the error like above is a pretty easy way to get something printed to your console, and especially important for error handlers because you wont know if an error occurred otherwise
hello, I tried to make music bot using "youtube_dl", but I have an error when I type my "!play" command.
The bot is successfully connecting the vocal channel but then I have this error:
discord.errors.ClientException: Not connected to voice.
you can see here that the bot connected to the voice channel
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโs robots.txt file; (b) with YouTubeโs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Getting amount of messages in a channel?
afaik discord's api doesnt have a good way to do that, you have to fetch every message using channel.history() (up to 100 messages per API call) which can get held back by rate limits
Oh
How can I delete all messages in a channel with a purge all command and have it say the exact amount of messages deleted
oh in the case of purge() it already has to fetch messages, and afterwards it returns a list of messages which you can get the length of
how to i just get to where i can write code for a bot
If you donโt know that, you probably should not be making a discord bot
can you just tell me
please
This does not work
did you get an error? what didnt work?
One sec
Can you help me please
generally you want to learn python fundamentals, object oriented programming, and at least a basic understanding of concurrency
https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b
https://realpython.com/python3-object-oriented-programming/
https://realpython.com/python-concurrency/
Learning discord.py. GitHub Gist: instantly share code, notes, and snippets.
https://code.visualstudio.com/docs/languages/python
they're using vscode, but when you install python it comes with the IDLE editor which is good enough for initial learning
Ok thank you
Is if not verification_completed: the same as verification_completed: False?
== false is redundant but mostly yes
Why do I get:
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.cog' raised an error: ImportError: cannot import name 'ui' from 'discord.ui' (/home/fate/.local/lib/python3.10/site-packages/discord/ui/__init__.py)
``` ?
hello guys im new to discord.py what interprenter shall i use
?
the python interpreter
Did you do from discord.ui import ui?
ive downloaded it but i get this
yep
It's just from discord import ui
you need to install the lib with pip
i see, thanks
pip install discord.py
correct
Is this pycharm?
yes
You need to install it from the Pycharm package manager IIRC
Since pycharm sets up a venv for you by default
double shift > packages
i mean what package it is
i deleted sorry
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.
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal.
last line sorry
it tells you what to do
go to the developer portal and enable the privileged intents
i now saw it too
can i make a command like if a message send in a specific channel, then ...
that wouldn't be a command though, it would just be an event listener
you can use on_message
thanks
im tryna do an embed and i want the author of the message to be the author of the embed, but i only get the id
The author field does not support markdown or things like mentions iirc
you can't mention people in an author field
neither can you mention people in a footer, title, field name, etc
๐
?
?
just a commandnotfound error
for any of my commands for some reason
what is your code