#discord-bots

1 messages ยท Page 217 of 1

fading marlin
#

You have to fetch the message, not the interaction

graceful ermine
#

Oh

graceful ermine
fading marlin
#

fetch will return you the full message object

smoky sinew
unkempt canyonBOT
#

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`.
graceful ermine
#

Because I read the document and it had nothing to do with reactions and etc

fading marlin
#

No, message is still PartialInteractionMessage. message.fetch() returns InteractionMessage. Use the returned value to add the reaction

graceful ermine
#

and how could we get the returned value? what by doing an if statement?

#

disregard the other message

fading marlin
#
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)

slate swan
#

!e print(4194432 << 16)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

274886295552
graceful ermine
#

@fading marlin Something like this?

fading marlin
#

In the example I showed you, foo acts like message.fetch

smoky sinew
#

what would return 1 even do here

#
y = x.function()
y.do_something()
#

this is what you need

graceful ermine
#

will this help?

#

by fetching the message id of the interaction?

placid skiff
#

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

graceful ermine
fading marlin
#

fetch is a coroutine, and doesn't need any parameters

smoky sinew
graceful ermine
smoky sinew
#

why are you doing def fetch

graceful ermine
#

this is what I have

smoky sinew
#

you don't define it yourself

fading marlin
#

It's an example. You don't have to literally create a new function. foo just represents fetch, nothing else

graceful ermine
#

Now I am confused on how to fetch the message

smoky sinew
#

then use add_reaction on that variable

graceful ermine
#

I did this

#
    msg = await interaction.send(embed=embed)

    msg.fetch
    return await msg.add_reaction("โœ…")
smoky sinew
#

what do you expect msg.fetch to do here

#

!e ```py
def example_fetch_function():
pass

print(example_fetch_function)

unkempt canyonBOT
#

@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.

<function example_fetch_function at 0x7f5e31fb8680>
smoky sinew
#

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

graceful ermine
#

So then what am I gonna do?

graceful ermine
smoky sinew
#

no, you aren't calling it right now

graceful ermine
smoky sinew
#

wdym?

tired pollen
#

Btw this function is coroutine and you need to await coroutine

#
await fetch()```
dusty tree
#

any ppl from hikari here?

smoky sinew
#

me

placid skiff
smoky sinew
# placid skiff ?

this parameter returns an instance of the actual bot/client running

worthy heart
#

but this way, its not going to delete the bots messages am I right?

smoky sinew
#

await StageChannel.purge(check=lambda m: m.author != bot.user)

exotic maple
#

when i search through user.roles,
how do i ignore the @ everyone role

#

?

smoky sinew
tired pollen
#

or loop through user.roles[1:]

#

Bc first index is always everyone role

exotic maple
tired pollen
worthy heart
smoky sinew
#

this won't because there's a check

worthy heart
#

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

torpid hare
#

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

my code https://paste.pythondiscord.com/jewedajuke

smoky sinew
exotic maple
#

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

smoky sinew
#

what do you mean "it's not working"

#

also you shouldn't use a sync database library

exotic maple
tired pollen
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@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")
tired pollen
#

Why you just don't use this decorator?

smoky sinew
exotic maple
#

discord-py-slash-command

smoky sinew
smoky sinew
worthy heart
smoky sinew
smoky sinew
tired pollen
worthy heart
#

how can I add reaction to a interaction message?

#

I tried this but it didn't work:

await original_message.add_reaction('โŒ')```
worthy heart
#

and the interaction is defer

smoky sinew
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

tired pollen
unkempt canyonBOT
#

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.
smoky sinew
worthy heart
tired pollen
worthy heart
#

thinking is true by default

tired pollen
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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...
smoky sinew
#

bruh what they already did that

smoky sinew
#

in the case of hybrid commands though

#

i'm not sure

stone gate
#

is there a way that a command can execute other commands in order?

smoky sinew
stone gate
#

interactions

worthy heart
smoky sinew
# stone gate interactions

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

smoky sinew
torpid hare
#

which one

#

u said alot

worthy heart
smoky sinew
#

that's usually the only time "unknown interaction" errors happen

torpid hare
#

hmm

worthy heart
#

if I remember, it happened to me when I forgot to defer my interaction, but it may not relate to this case

smoky sinew
#

yeah or if you take too long to respond

worthy heart
#

yes

torpid hare
#

ig doesnt hurt to try

worthy heart
#

yas

smoky sinew
#

i think you can use Context.typing to handle that?? i don't remember

smoky sinew
#

why would it not work

worthy heart
#

its within an interaction

#

it throws an error

worthy heart
#

wait ill send it

torpid hare
#

defering fixed it, thanks

stone gate
#

is there a interaction.autor.role ?

worthy heart
smoky sinew
slate swan
smoky sinew
#

bruh im so clueless

smoky sinew
torpid hare
smoky sinew
#

idk that's why i asked

worthy heart
smoky sinew
#

i thought hybrid commands took in context

torpid hare
#

ive been doing it for a while now

#

yea

smoky sinew
#

then what code did you use

torpid hare
#

i sent it

worthy heart
smoky sinew
#

wait wtf

torpid hare
#

await ctx.defer()

smoky sinew
#

bruh discord.py interaction code is so useless it's like a whole seperate library

slate swan
stone gate
smoky sinew
#

it doesn't even make sense to defer a context

slate swan
smoky sinew
#

there could have just been a HybridInteraction type

#

or something like that

smoky sinew
slate swan
worthy heart
#

ok, my next thing is to listen if the user adds a reaction, how can I do that?

smoky sinew
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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**...
worthy heart
#

it works on interactions?

slate swan
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

slate swan
#

!d discord.Member.roles

unkempt canyonBOT
#

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.
exotic maple
#

r comes back with a row

smoky sinew
smoky sinew
#

it's SELECT <x> where <x> is the column name

exotic maple
#

nvm

#

thx

#

its midnight and my brain is shutting down

exotic maple
smoky sinew
#

why?

#

what is a dic

exotic maple
#

array

#

dic = [] and i wanna put each value selected from the table seperate in the dictionary

smoky sinew
#

have you tried dict(record)?

exotic maple
#

this didnt work

#

i think its cuz its

"x": ROLEIDVAL,

#

and not just ROLEIDVAL, ROLEIDVAL, ROLEIDVAL

smoky sinew
#

also why do you keep calling them dic that's kind of concerning

smoky sinew
#

wdym by role id by the way

#

why is your table schema like that

exotic maple
#

im lost

exotic maple
smoky sinew
#

that also wasn't the code i sent

worthy heart
smoky sinew
worthy heart
#

Thanks!

#

have a good night (if its night for you)

smoky sinew
#

it is only 5 pm but thanks

exotic maple
smoky sinew
#

what...

#

you have 255 different columns for each number

exotic maple
#

yes

smoky sinew
#

i think you need to rework your schema

exotic maple
#

whats wrong with it

#

also in a normal table how many rows can it store? @smoky sinew

#

that may let me change my schema

smoky sinew
#

it's about 2^64 i believe

#

but on sqlite it's probably less

exotic maple
#

ok i got an idea to change my schema

slate swan
#

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.

exotic maple
smoky sinew
slate swan
swift heron
#

is there a big difference from sqlite to mongo?

vocal snow
#

Sqlite is a serverless, zero-conf, relational database

#

Mongo is a NoSQL database

vale wing
#

I remember creating pickle "database" ๐Ÿ’€

swift heron
#

-0?"+______________________{[[[[[[[ujmkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk /

keen niche
#
    @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'```
vocal snow
#

are you sure that channel id is valid?

keen niche
#

yes

vocal snow
#

and what intents do you have enabled?

keen niche
#

all

vocal snow
#

are you sure the bot is properly logged in before you use the command?

keen niche
#

yes, i have the on start thingy to say it is

vocal snow
#

!d discord.Client.fetch_channel

unkempt canyonBOT
#

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.
keen niche
#

um

#

fetch_channel doesnt exist for me

vocal snow
#

what

vocal snow
#

is that command in a cog, and in an extension file?

keen niche
#
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

keen niche
vocal snow
keen niche
vocal snow
#

yes it can

#

the setup function in the extension gives you the bot instance

keen niche
#

well when i delete that bit

#

i get errors

vocal snow
#

async def setup(bot):
    await bot.add_cog(Cog(bot))
#

you should not be making a new bot instance

keen niche
vocal snow
#

in the extension file

#

are you not using extensions?

#

how are you adding the cog currently?

keen niche
#

what is exentsion?

keen niche
#

i dont think i am using that

vocal snow
keen niche
#

wym

#

wait nvm

#
await bot.add_cog(Commands(bot))```
vocal snow
#

and where is this line?

keen niche
#
@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"))```
vocal snow
#

so you're passing the bot instance to the cog

#

what's in the cog _init_?

keen niche
#

self.bot = bot

vocal snow
#

so use self.bot to access the bot instance in the class

#

why make another bot instance

keen niche
#

because if i delete the 2nd instance

#

the IDE gives me the red signal

vocal snow
#

red signal on which line

keen niche
#

top corner saying bruh u fucked up smthn in code

#

oh u mean...
nvm lol

#

it fucks up the line

vocal snow
#

which line

keen niche
#
channel = bot.get_channel(1086790739582791710)```
vocal snow
keen niche
#

thanks, works

slate swan
#

hello I need help can someone help

shrewd fjord
keen niche
#

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

silk fulcrum
keen niche
#

well, i asked chatgpt for help, and it said to do that for class, but it didnt work for class

keen niche
#

so il try for individual commands

keen niche
#

alr

shrewd fjord
#

!d discord.ext.commands.command

unkempt canyonBOT
#

@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.
vocal snow
shrewd fjord
#

Idk about cog class tho

keen niche
#

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

silk fulcrum
keen niche
#

ye thx

worthy heart
#
[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)

slate swan
#

when using bot.run() add log_handler=None

#

!d discord.ext.commands.Bot.run

unkempt canyonBOT
#

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.
slate swan
#

or if you can log only warnings and higher

worthy heart
#

log_level?

slate swan
#

set log_level to level

#

you want to

#

for warnings its 3 i belive

worthy heart
#
log_level=logging.WARNING

slate swan
#

or this

worthy heart
#

lets see

#

wa

slate swan
#

nothin

#
>>> import logging
>>> logging.WARNING
30


worthy heart
#

working

slate swan
#

its 30 but you can just say logging.WARNING

worthy heart
#

yes ill keep it like that

#

thanks!

slate swan
#

๐Ÿ‘

stone palm
#
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 ๐Ÿ’€
naive briar
unkempt canyonBOT
#

@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
naive briar
#

It means exactly what it says

stone palm
#

thats the point, i dont understand what it says

worthy heart
#

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```
stone palm
#

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())
zenith thicket
#

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
gilded harness
#

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

vale wing
#

No offense, but python beginners be like

gilded harness
#

Wait so whats wrong with the code??

vale wing
vale wing
gilded harness
#

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

vale wing
#

Then uh how can you explain calling message.content

gilded harness
#

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!"))```
vale wing
#

It returns a boolean

gilded harness
#

No it doesnt return anything

#

I say "Fuck" in the discord server and nothing happens

vale wing
#

!d str.startswith

unkempt canyonBOT
#

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.
gilded harness
#

Wait so I need prefix for that??

vale wing
#

And look into arguments

gilded harness
#

No one is gonna say ?Fuck

desert cosmos
#

how are we supposed to handle check failure exceptions ?

gilded harness
#

Ok so these discord bot github examples are useless

desert cosmos
brazen raft
desert cosmos
#

like calling two asynchronous methods with just one await

brazen raft
#

No

gilded harness
#
        await message.delete and message.reply("Hey you can't say that!")```
#

Like this?

brazen raft
#

And they probably meant to delete the message with the swear word

#

Not the one replying about it

gilded harness
#

See it isn't doing anything this bot fr dooky

gilded harness
#
   await message.delete
        message.reply("Hey you can't say that!")```
brazen raft
#

The message that is to be deleted is message, not the bot's reply

gilded harness
#

Ohhh I get it now

desert cosmos
brazen raft
#

You should reply before deleting the message

gilded harness
#
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?

brazen raft
#

Almost

#

Flip it and make sure you actually call message.delete

gilded harness
#
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

brazen raft
#

Still didn't call message.delete

gilded harness
#

But message.delete isn't a function I cant call it

#

on_message is the function

brazen raft
#

Are you sure it isn't?

#

!d discord.Message.delete

unkempt canyonBOT
#

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.
gilded harness
#

So I gotta have manage_messages?

#

Man they make this so complex

desert cosmos
gilded harness
#
 await message.delete()``` Like this?
desert cosmos
#

yeah

brazen raft
gilded harness
#

Ok so manage_messages is a seperate function right??

stone palm
#

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

gilded harness
#

Or does it fall under on_message

brazen raft
#

It's totally a Discord thing

#

Not your bot's program

gilded harness
#

Yea I say Fuck and the bot doesnt reply to it damn it

brazen raft
#

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

gilded harness
#

Wait but isn't the permissions in the Discord bot developer portal?

#

You just give it administrator?

brazen raft
brazen raft
gilded harness
#

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 ๐Ÿค”

slate swan
#

discord limits button ui interations to two per 10 minutes?

 responded with 429. Retrying in 575.73 seconds.```
brazen raft
uneven hearth
#

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

gilded harness
# brazen raft Correct

Wait so now I gotta make a seperate function manage_messages to let my bot delete messages?

brazen raft
#

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

worthy heart
vale wing
unkempt canyonBOT
vale wing
#

Although responses are done not via gateway

#

What exactly the endpoint is

worthy heart
worthy heart
#

with an emoji and all that

#

it doesn't seem to be listed

vale wing
unkempt canyonBOT
#
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.
shrewd fjord
#

you should wither use any() or or

#

then use
if .... in message.content:

#

Then do stuff

#

!d any

unkempt canyonBOT
#
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
worthy heart
#

for the category should I specify the ID of it or the name?

vocal snow
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#
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...
vocal snow
#

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

sinful thistle
#

anyone wanna collaborate

#

guys

slate swan
#

Collaborate on what?

worthy heart
#

how can I add a permission to a specific member and channel channel?

view_channel

slate swan
#

Do you mean adding a channel-specific permission overwrite?

worthy heart
#

like this in specific channel

slate swan
#

!d discord.abc.GuildChannel.set_permissions Check this out from the discord.py docs

unkempt canyonBOT
#

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...
slate swan
#

You can specify target to be a guild member or a role

tough lance
#

Also remember, it should be a Member object

worthy heart
#

is this acceptable?

member = discord.Member()
member.id = interaction.user.id
tough lance
#

No

#

Interaction.user is a member if it's a guild.

#

Wait

#

Lemme confirm

worthy heart
#

I want to add the permission to a specific user

tough lance
#

Yea it's a member. You can use interaction.user

worthy heart
#

no need .id?

bright wedge
worthy heart
bright wedge
#

just use interaction.user

#

!d discord.Interaction.user

unkempt canyonBOT
slate swan
bright wedge
worthy heart
#

I am kinda confused now xd

tough lance
#

Discord bots become a hassle when they get big

bright wedge
#

Just interaction.user

worthy heart
#

the object right?

tough lance
#

Sorry wrong reply but refering to your question.

bright wedge
worthy heart
#

so I dont need discord.Member right?

tough lance
#

No. That's a class, not an instance

bright wedge
worthy heart
#

yes

#

I mean, discord.py is the most complicated I've ever done in python

bright wedge
worthy heart
bright wedge
#

Well you can search it docs about interaction.user

#

And you can see what returns, type etc.

worthy heart
#

one day things would be clear

#

still working on it

flint vortex
#

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

bright wedge
flint vortex
#

not working Cry

bright wedge
flint vortex
#

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.

bright wedge
#

Add python to path

sinful thistle
slate swan
#

@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

slate swan
#

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}

sick birch
#

htop supremacy

slate swan
sick birch
#

I'm just joking around. I much like htop

slate swan
sick birch
#

When Discord starts acting funky I can bonked it

slate swan
#

@slate swan check that

slate swan
slate swan
#

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

slate swan
wary moat
#

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

#

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

little narwhal
#

I had this same problem easy fix

smoky sinew
#

how are you running your bot

little narwhal
#

change:
intents = discord.Intents.default()
to:
intents = discord.Intents.all()

little narwhal
#

and go to your bot settings in discord dev portal

little narwhal
smoky sinew
#

stop

little narwhal
#

turn these on

#

that worked for me I had the same issue earlier

wary moat
#

@little narwhal this is unrelated to his issue

smoky sinew
#

that will not fix it

wary moat
#

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

smoky sinew
#

@slate swan how are you running your bot bruh

wary moat
#

intents has been in there since 1.5

smoky sinew
#

how are you running it

#

that's your issue then

wary moat
#

oh

smoky sinew
#

run it from the terminal

wary moat
#

try running it from a command line

#

same place you installed the dependency

brisk relic
#

is python.org a good app to use python in or do i stick tot replit

smoky sinew
#

your interpreter is probably different

wary moat
#

sometimes it gets mixed up with virtual environments

smoky sinew
brisk relic
#

which one is better?

wary moat
#

depends on your needs

smoky sinew
#

uninstall the microsoft store version and install it from python.org

exotic maple
smoky sinew
#

add or remove programs

wary moat
#

I think you can uninstall it from settings or smth

#

oh, ok

#

yes

smoky sinew
#

x64 x86_64 and amd64 are all the same

exotic maple
hushed galleon
#

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

hushed galleon
#

before you go reinstall discord.py

hushed galleon
#

what files are in your project folder? what are they named?

#

yeah that's likely the real cause of your last error

#

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

unkempt canyonBOT
#
PATH on Windows

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 ...
hushed galleon
#

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

brisk relic
#

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?

sick birch
brisk relic
#

i was on the shell

scarlet aurora
#

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

smoky sinew
#

why would you need to use discord_slash with discord.py 2.0

scarlet aurora
#

what should I use

smoky sinew
scarlet aurora
#

send documentation

scarlet aurora
#

ty

balmy bobcat
#

hello, how can I get a channel's id with interactions?

#

is it something like interaction.message.channel.id?

smoky sinew
#

interactions will not always have a message

balmy bobcat
#

oh, okay

#

I'm not used to interactions yet

smoky sinew
#

ids are not strings

#

and also use the in operator for that

#

with a tuple

#

like if message.author.id in (1, 2, 3):

smoky sinew
#

yes use a list comprehension

#

with any

#

if any([r in member.roles for r in (1, 2, 3)]):

slate swan
#

*member._roles

smoky sinew
hushed galleon
#

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

unkempt canyonBOT
#

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
    """```
smoky sinew
#

the difference is negligible

hushed galleon
#

theres also the fact that an integer wont exist in a list of Roles

smoky sinew
#

yes that's what the list comprehension is useful for

hushed galleon
#

but your example is trying to test if an integer exists in a list of roles

smoky sinew
#

ah

#

my bad

#

i forgot to change that

hushed galleon
#

lol

slate swan
slate swan
#

oh i didn't see recent message sorry:p

smoky sinew
#

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

smoky sinew
#

@slate swan python is case sensitive

slate swan
#

does anyone have/know of a discord bot example github repo I can view (or a sample code for a slash command?)

tough lance
slate swan
slate swan
#

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

brazen raft
#

discord.py supports slash commands since version 2 came out

#

No need to switch wrapper libraries or a third party library

warm apex
#

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

vale wing
#

And yeah no need to send your message 3 times

#

In a fricking row

warm apex
#

docs?

glad cradle
#

documentation

warm apex
glad cradle
#

yes

warm apex
#

k

slate swan
#

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)

slate swan
slate swan
#

lemme see

#

u tried asking chatgpt

#

not really no

#

i dont use that

slate swan
#
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'embed' referenced before assignment```
upbeat otter
#

full

#

everything in the terminal

slate swan
#
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```
upbeat otter
slate swan
upbeat otter
#

not this

#

where you're using it

slate swan
#
    @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
upbeat otter
#

it's causing the error because you did something like


#no definition of embed here
await message(ctx, message, embed)
embed = discord.Embed()
upbeat otter
slate swan
#
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```
upbeat otter
#

ah

upbeat otter
#

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

slate swan
#

how would i do that?

upbeat otter
#
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

slate swan
#

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

zenith thicket
#

can anyone help?

noble thorn
#

Hi

#

sure

zenith thicket
# noble thorn sure

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)
warm apex
#

@midnight oyster

noble thorn
#

Also this asyncio.sleep(1) is the correct one, that asyncio.sleep(0,1)means it should sleep for 0 seconds and return 1

slate swan
#

i think he meant 0.1

vale wing
sinful thistle
#

Anyone wanna contribute on a discord bot

slate swan
#

@client.command()
AttributeError: 'Client' object has no attribute 'command' help me

slate swan
brazen raft
brazen raft
#

You might as well name it bot because it's an instance of a class that is called Bot

slate swan
#

ok

brazen raft
#
from discord.ext import commands
...
bot = commands.Bot(...)
#

Then @bot.command()

slate swan
#

bot = discord.ext.commands.Bot?

brazen raft
#

You have to import commands from discord.ext somehow, so just do as I did

brazen raft
slate swan
#

So i have to copy paste it?

brazen raft
#

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

slate swan
#

yeah imported it separately

#

now what?

brazen raft
#

Try it

#

You have to give the constructor a command prefix and intents

zenith thicket
slate swan
#

async def on_ready():
TypeError: Client.event() missing 1 required positional argument: 'coro'

naive briar
#

Remove the parentheses after .event

slate swan
#

still the same error

#

async def on_ready():
TypeError: Client.event() missing 1 required positional argument: 'coro'

brazen raft
#

What he said. @bot.event, not @bot.event()

slate swan
#

i understood

brazen raft
#

Can you paste your code in like

#

!paste

unkempt canyonBOT
#
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.

slate swan
#

ok

brazen raft
#

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

slate swan
#

Oh ok

#

i need default intents

#

can u make var nd send

brazen raft
#

Then intents = discord.Intents.default()

slate swan
#

Thanks a lot mate

brazen raft
#

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

slate swan
#

Oh lol, how do I enable it?

brazen raft
#

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

slate swan
#

it joined the VC but didnt speak

brazen raft
#

I haven't learned the voice part of the library at all

#

Can't help with that

slate swan
#

Oh ok

worthy heart
#
@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

brazen raft
#

You get the member in the parameter, so member.id

worthy heart
#

but its not the object

brazen raft
#

It is

worthy heart
#

wait wa

brazen raft
#

That's the point of it

worthy heart
#

when I print it it prints the user#tag

#

sec

#

wtf

#

how in the world

brazen raft
#

The library gives you the member in the parameter

worthy heart
#

but when I print the member

brazen raft
worthy heart
#

it shows the name and discrim, instead of showing its an boject

brazen raft
# worthy heart but when I print the member

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

worthy heart
#

damn

#

so thats the default for discord.Member() object?

brazen raft
#

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

worthy heart
#

thanks a lot!

sinful thistle
copper gulch
#

havent coded for a long time, so I have alot of questions:

  1. do all discord bots need to be all slash commands to work?
  2. 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?
slate swan
copper gulch
#

ahhh, anyone here use replit?

copper gulch
#

thank you thank you

copper gulch
#
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
vocal snow
#

add_cog is a coroutine now

copper gulch
vocal snow
copper gulch
#

so I have to put await?

vocal snow
#

yes

#

you can use the setup_hook to load your cogs

copper gulch
vocal snow
#
@client.event
async def setup_hook():
    # load cogs

copper gulch
midnight oyster
junior drum
#

Hi, i can't import tasks from discord.ext. Any idea why?

#

a simple reinstall seems to do the job

tough lance
#

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.

tough lance
#

Yes

#

It wasn't a problem until now.

vale wing
tough lance
#

Hmm lemme check it on vps

tough lance
#

It doesn't even work when I try an eval command on the bot.

#

But works when I restart the bot.

warm apex
abstract kindle
#

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

vale wing
vale wing
abstract kindle
vale wing
#

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

abstract kindle
#

Got it, thanks

slate swan
karmic nimbus
#

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)
sinful thistle
#

Anyone plays Minecraft

sick birch
sinful thistle
#

DM me

sick birch
sinful thistle
#

I play on a server

sick birch
#

I assumed the question was somehow related to discord bots

sinful thistle
#

K

sick birch
sinful thistle
#

There might be 2 instances of ur bot

graceful pine
#

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

vocal snow
graceful pine
#

can i dm you

#

i send you the code also

#

unable to invite it to my server

slate swan
karmic nimbus
#

i have another one on_member_update, is that the problem?

slate swan
slate swan
hushed galleon
slate swan
wicked atlas
#

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

hushed galleon
#

oh yea true

#

and on_ready() can be called multiple times which makes it a poor place to set up anything there

wicked atlas
#

Load your cogs in your setup hook, before you sync your command tree

slate swan
#

I have await self.add_cog(MPing(self)) currently before the sync

wicked atlas
#

Are you running your main bot file, or your ping.py file?

#

You have two seperate bot classes?

slate swan
wicked atlas
#

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

slate swan
wicked atlas
#

Yeah

slate swan
#

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()

slate swan
hushed galleon
stone gate
#

is there any way to do @commands.has_role() with interactions?

hushed galleon
#

!d discord.app_commands.checks.has_role (assuming you mean in discord.py)

unkempt canyonBOT
#

@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...
stone gate
#

thanks

slate swan
#

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."

hushed galleon
#

does it show an error in your terminal? self.latency is probably what caused it to fail

slate swan
#

sure enough

#

an error did go through (I did not think any would up till this point)

slate swan
#

would client.latency work (im trying it either way) (it did not work)

hushed galleon
#

interaction.client or self.bot would be two ways to access your bot instance

slate swan
#

it worked!

hushed galleon
#

thats why its common to have self.bot = bot in the cog's init method, for easy access to the bot instance

slate swan
#

thank you very much for your help!

#

Yo!

unkempt canyonBOT
slate swan
#

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)

hushed galleon
#

the on_raw_reaction_* events would be more suitable for your purpose

#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

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.
slate swan
#

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

unkempt canyonBOT
#

@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
hushed galleon
#

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

stone gate
#
    @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
hushed galleon
#

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

sick birch
#
  • casing matters
stone gate
#

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

sick birch
#

Yes. That's the "can't handle error inside the callback itself" thegamecracks mentioned

stone gate
#

i see

sick birch
#

You need a separate function decorated with @inland glacierremover and accepts a ctx and error

hushed galleon
#

^ or alternatively you can write a global error handler to handle the missing role exception from any command

sick birch
#

Sorry about the ping, am on mobile lol

hushed galleon
#

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```

stone gate
#

thanks for the help

#

and for example, if i want it to handle every error to at print something on the console?

hushed galleon
#

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

left jungle
#

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

slate swan
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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)
blazing flint
#

Getting amount of messages in a channel?

hushed galleon
#

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

blazing flint
#

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

hushed galleon
#

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

blazing flint
#

Oh ok

#

So if limit is None then it will purge as many messages as possible?

jade needle
#

how to i just get to where i can write code for a bot

blazing flint
jade needle
#

can you just tell me

hushed galleon
#

did you get an error? what didnt work?

blazing flint
#

One sec

jade needle
hushed galleon
jade needle
#

Ok but where do I actually type the code

#

Like this where I can actually code

hushed galleon
jade needle
#

Ok thank you

young dagger
#

Is if not verification_completed: the same as verification_completed: False?

smoky sinew
#

== false is redundant but mostly yes

tulip frigate
#

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)
``` ?
hasty bison
#

hello guys im new to discord.py what interprenter shall i use

smoky sinew
#

the python interpreter

sick birch
hasty bison
#

ive downloaded it but i get this

tulip frigate
#

yep

sick birch
#

It's just from discord import ui

tulip frigate
tulip frigate
hasty bison
#

pip install discord.py

tulip frigate
#

correct

hasty bison
#

ive already done this

#

but i get this

sick birch
hasty bison
#

yes

sick birch
#

You need to install it from the Pycharm package manager IIRC

#

Since pycharm sets up a venv for you by default

hasty bison
#

ok thanks

#

how is it called

smoky sinew
hasty bison
#

i mean what package it is

smoky sinew
#

what is the full error

hasty bison
smoky sinew
#

that's still not the full error

#

!traceback

unkempt canyonBOT
#
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.

hasty bison
#

discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal.

#

last line sorry

smoky sinew
#

it tells you what to do

#

go to the developer portal and enable the privileged intents

hasty bison
#

i now saw it too

hasty bison
#

can i make a command like if a message send in a specific channel, then ...

smoky sinew
#

you can use on_message

hasty bison
#

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

wicked atlas
#

The author field does not support markdown or things like mentions iirc

smoky sinew
#

you can't mention people in an author field

#

neither can you mention people in a footer, title, field name, etc

hasty bison
#

๐Ÿ‘

scarlet aurora
#

changed to 2.2.2 and now my hoster wont run the cogs

#

commandnotfound error

smoky sinew
scarlet aurora
#

?

scarlet aurora
#

for any of my commands for some reason

smoky sinew
#

what is your code

scarlet aurora
#

it works

#

when I run locally

#

but when I run on my host it just does commandnotfind ignoring exception in None