#discord-bots

1 messages Β· Page 1155 of 1

stiff fern
#

Theyre all set up the same way

paper sluice
#

seems like you didnt call the method

modern fiber
#

Not sure whats wrong..? It worked some time ago

robust fulcrum
stiff fern
#

Anyone know what the M stands for in file names?

robust fulcrum
paper sluice
modern fiber
#

and it worked

#

like month ago or smth

paper sluice
modern fiber
#

this same code worked

paper sluice
robust fulcrum
#

Actually I made my 2nd class

#

And not much experience

paper sluice
#

cool

slate swan
modern fiber
#

Should work right?

robust fulcrum
modern fiber
#

from @client.slash_command to @strange knoll_commands.command

slate swan
paper sluice
paper sluice
robust fulcrum
paper sluice
#

what does the function do?

#

and if it gives a keyerror, then the key that you are trying to access doesn't exist

modern fiber
#

Kind of new to slash commands and shit, sorry

paper sluice
paper sluice
modern fiber
paper sluice
paper sluice
robust fulcrum
#

I did a big mistake

#

I loaded the TOXICITY and printing PROFANITY

#

I am really sorry πŸ˜”

paper sluice
#

its alr

minor totem
minor totem
stiff fern
#

Which is weird because core should load first bc it’s first in the array but it doesn’t even load that

minor totem
#

Extensions are the files, cogs are the classes. I assume that you load the cog when you load an extension?

stiff fern
#

I was just doing load_extension(file name) for each one

#

In each file it has the class and run in there if that’s what ya mean

#

I’m not home rn so I won’t worry ab it too much but does the M matter? or how would I get rid of it

minor totem
#

It has to do with Git and version control

robust fulcrum
#

How to use a listener in cogs?

slate swan
robust fulcrum
#

How to fix this?

slate swan
#

Comment must be non-empty

'errorType': 'COMMENT_EMPTY'
#

Error says it all shrug

warm hamlet
#

c.execute("SELECT * FROM users")
sqlite3.OperationalError: no such table: users

#

@paper sluice

slate swan
cold tide
#

Anyone know how if i can make my bot reply to a user after executing a command for it make its missing a role?

#

would be appreciated

cold tide
blazing kettle
#

nevermind i fixed it

slate swan
#

go to the application's bot page on the dev portal

#

apply

#

read

#

and proceed

#

what

warm hamlet
#

c.execute("SELECT * FROM users")
sqlite3.OperationalError: no such table: users

thorny ferry
#

hey guys, do you know how to get the language of a user ?

vocal snow
warm hamlet
#

I'm asking for a fix

vocal snow
#

create a table users?

slow fog
warm hamlet
vocal snow
slate swan
warm hamlet
#

Like a full code example

#

I'm too dumb to know where that goes lol

vocal snow
#

examples there ^

#

although I would use aiosqlite instead

warm hamlet
#

So i need a cur.execute

#

can i delete a table

sick birch
#

DROP TABLE i believe

terse coyote
#

i'm trying to create role, but i have an error

    mute_role = await guild.create_role(name = "Mute", permissions = discord.Permissions(speak = False, send_messages = False), colour = discord.Colour.dark_gray)
  File "C:\Users\grama\AppData\Roaming\Python\Python310\site-packages\discord\guild.py", line 1894, in create_role
    fields['color'] = colour.value
AttributeError: 'function' object has no attribute 'value'```

code:
```python
mute_role = await guild.create_role(name = "Mute", permissions = discord.Permissions(speak = False, send_messages = False), colour = discord.Colour.dark_gray)
terse coyote
vale wing
#

Screw json as db

#

Take some speed sqlite tutorial

#

You don't need a really complicated db

#

For this project actually you need only a table with 2 columns

#

/marry list well if there are too many married persons they just won't fit in one message

slate swan
#

/marry "quit"
divorce :exit:

#

if i try to do /marry ill probably get a permissions error

slate swan
#

πŸ˜”

vale wing
#

After you learn about sqlite (all you need is CREATE TABLE, SELECT, INSERT and DELETE), read sqlite3 docs (that's python sqlite wrapper), after you get familiar with it switch to aiosqlite because you shouldn't use sqlite3 for discord bots

#

Mongo db is json-like iirc

#

Never used it myself

pliant gulch
#

They do

jovial dock
#

when i hit run, i get the second image in my terminal, y'all know what i'm doing wrong?

slate swan
#

Name it bot, or import http.client as some alias, or just remove it at all if you dont need it

slate swan
#

<whatever_you_named_your_commands.Bot_instance>.event

#

Also looks like intellisense is just being annoying, it imports those useless modules automatically when you hit enter without reading the source of the object

jovial dock
#

thanks, i had a feeling that the the import client thing was messing it up but didn't know what to do to fix it

slate swan
#

Many big companies including discord uses (actually discord used to) mongodb as their database.. I dont think any big company will use it if it's "bad". Though it also has it's potential disadvantages but for using it with a bot, it should be more than enough in most of the cases

slate swan
#

this is not active as it was long time ago?

terse coyote
slate swan
# terse coyote

Read the error:

TypeError: NoneType object is not subscriptable
The error also includes the line which is raising the error
data = self.cursor.fetchone()[0]
See what you're doing wrong in this line. If you don't know what "subscriptable" means (which I'm assuming you don't), you can google it... or basically it means an object which can contain other objects.
NoneType can't contain other objects in it, but you're still trying to parse it

#

How to fix it? Don't parse it if it's None. Use an isinstance or just an if-else condition to check that

keen wolf
#

Hello
I want to delete the default help command

#

and make my own

spring glade
#

im making a discord bot for the first time using https://realpython.com/how-to-make-a-discord-bot-python/#creating-a-discord-connection it says no module named discord help pls

In this step-by-step tutorial, you'll learn how to make a Discord bot in Python and interact with several APIs. You'll learn how to handle events, accept commands, validate and verify input, and all the basics that can help you create useful and exciting automations!

keen wolf
#

Nvm found it in the pins

slate swan
spring glade
#

ok

jovial dock
#

it's supposed to say the na,e of the role added but its just saying whats in the second image. i only have 57 lines in total so i dont get where its getting line 343 from either. top line is 43 and bottom is 53, i forgot to screenshot the numbers with it

slate swan
#

Again, it's just read the error.

NoneType object has no attribute display_avatar

On whatever attribute you're using display_avatar, it's None.

blazing kettle
#

how would i make it so i can click to go to a channel ex #rules

slate swan
#

!d discord.TextChannel.mention

unkempt canyonBOT
quaint epoch
#

😑

#

orrr, you could do f'<#{channel.id}>'

blazing kettle
#

lemme try that

slate swan
#

Think how would you. If it's None but you expect it shouldn't be, try to find what's causing your ctx.author to be None

blazing kettle
slate swan
#

attribute*

quaint epoch
quaint epoch
#

did you do ctx.channel.mention

blazing kettle
#

i tried

quaint epoch
#

send an image of what you see

wild spoke
#

Why it does not react to message?

quaint epoch
#

!d re.match

unkempt canyonBOT
#

re.match(pattern, string, flags=0)```
If zero or more characters at the beginning of *string* match the regular expression *pattern*, return a corresponding [match object](https://docs.python.org/3/library/re.html#match-objects). Return `None` if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in [`MULTILINE`](https://docs.python.org/3/library/re.html#re.MULTILINE "re.MULTILINE") mode, [`re.match()`](https://docs.python.org/3/library/re.html#re.match "re.match") will only match at the beginning of the string and not at the beginning of each line.

If you want to locate a match anywhere in *string*, use [`search()`](https://docs.python.org/3/library/re.html#re.search "re.search") instead (see also [search() vs. match()](https://docs.python.org/3/library/re.html#search-vs-match)).
quaint epoch
#

it returns a match object, not a boolean

#

you need to do re.match() is not None

wild spoke
#

how

quaint epoch
#

by typing it

blazing kettle
# quaint epoch send an image of what you see

no errors.

        errormsg.add_field(
            name=f"**Channel: {ctx.channel.mention}**",
            value=f"Error Raised: {error}"
        )
        await channel.send(embed=errormsg)``` this is my code, it sends the spacing may look werid
quaint epoch
quaint epoch
#

and you don't need ** **

slate swan
quaint epoch
#

since titles are always bold

blazing kettle
blazing kettle
wild spoke
#

man, python is hard

quaint epoch
#

it's really not

wild spoke
quaint epoch
#

you should be fluent in python before starting discord.py since their complexity is moderate to hard

slate swan
#

Lua is still an option if you find python hard πŸ™„

quaint epoch
slate swan
#

Also shouldn't just start using discord.py as a beginner project

wild spoke
#

I don't even know how to operate with @client @bot

wild spoke
quaint epoch
#

you should learn oop and decorators before starting dpy

slate swan
quaint epoch
wild spoke
#

im just making custom bot for server off a template found on github

slate swan
quaint epoch
#

lemme update your code

slate swan
cold tide
#

Can anyone please help me.

wild spoke
#

I know basics of basics of oop

quaint epoch
#

regex isn't necessary for this

cold tide
#

I need my bot to reply to the user who excutes a command whos missing roles to reply ("Your missing Roles !")

#

Can anyone help?

#

cant find any source at all

quaint epoch
#
@bot.event
async def on_message(message: discord.Message):
  emoji = ...
  if 'string' in message.content.lower():
    await message.add_reaction(emoji)
  await bot.process_command(message)```
slate swan
quaint epoch
#

btw, you used the client for the decorator

wild spoke
#

... = id?

quaint epoch
#

you need to use bot, not client

wild spoke
#

"..." = id or entire name:id?

quaint epoch
#

@bot.event
async def on_command_error(ctx, error):
  await ctx.send(error)
quaint epoch
cold tide
wild spoke
quaint epoch
quaint epoch
wild spoke
#

ok

slate swan
quaint epoch
#

just the final error

wild spoke
#

Not working

quaint epoch
#

well gotta hop in vc

#

goodbye

slate swan
#

Goodbye

wild spoke
#

and It's still not working for me.

#

cya mate

slate swan
#

What was the command to run code πŸ˜”

#

!e ```py
x = None

What you're doing. If x is None, which in your case I think it is, it just wont do anything

if x:
print(1)

Debug it like this, to see if this is the problem or not. Maybe the bot is just missing some permission

or smth like that, but who knows

if x:
print(1)
else:
print(2)

unkempt canyonBOT
#

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

2
slate swan
idle sparrow
#

What da

#

Hell is going on here

jovial dock
#

i keep getting this when i try to add a reaction role

idle sparrow
#

Okay first lets remove the error

#

Remove message.ide from the payload and just print it out

#

Then work from there whats going on

slate swan
#

Why no one tries to just read the error πŸ˜”
It's literally there, the line message_id = payload.message.id

idle sparrow
#

@slate swan ooooi ooooi ooooi

#

I was before you πŸ‘€

slate swan
#

I started typing before you tho

idle sparrow
#

No

#

Just no

jovial dock
slate swan
#

Remove the unused overwriting imports

jovial dock
idle sparrow
#

Wait wait wait

slate swan
#

email.message. The image you shared a few mins ago had that import, also unused

idle sparrow
#

Okay lets go slow here

#

That error there was cause because

#

Of the payload

#

Was never declared but was used

#

πŸ‘€

#

4th line

jovial dock
slate swan
#

@idle sparrow They have an import from email import message which is probably overwriting their original message instance

idle sparrow
#

message_id

#

Is not message.id

#

U might wanna start there and debug

#

But yes that is why it is greyed out

#

Because it was never used

jovial dock
idle sparrow
#

All i can say is do what u feel is right

slate swan
#

You typed message and hit enter without seeing the source, hence intellisense imported the wrong package for you. Remove it if you dont need it

idle sparrow
#

Combo of errors?

slate swan
#

Yes

idle sparrow
#

Oh what fun

#

Well I'll leave this one for you

#

Good luck πŸ˜… πŸ‘

slate swan
#

Thanks. It's the same issue they listed a few mins ago when you were not present that's why I know it lol

cold tide
#

Anyone know the statement on how to add roles to ctx.author?

idle sparrow
#

🀣

slate swan
unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
idle sparrow
#

Yeah hmmmmmm

cold tide
#

Thanks homie

idle sparrow
#

Ctx.guild.get_member
Will have to be used no?

#

Or something

#

If ur not mentioning the user that is

slate swan
#

ctx.author is already a member I guess (if context is of a guild)

idle sparrow
#

Hmmmm

#

No clue i have always used get member

#

To avoid errors

#

For incase

slate swan
#

ctx.guild.get_member(?? what's here) I just wonder

idle sparrow
#

Something like that

#

Not sure
I don't use d.py
I use pycord

idle sparrow
slate swan
#

Same things except for application commands

slate swan
idle sparrow
#

I haven't used it in a long while

#

So thats why i am unsure

#

These days i ise other systems that and i haven't worked on python in a long time

#

I use c++ these days

slate swan
#

Same, like a year ago. I just still remember most of the stuff

#

c here

idle sparrow
#

🀣

#

I don't have a memory like that

#

But ask me all the useless info

#

And i can help
Like
What is a good interface for building and verifying json data
Marshmellow

Whatsa fun way to work with json
Box

slate swan
#

Haha, yea same. Also let's not ot here before mods hit us with the mute hammer πŸ˜”

idle sparrow
#

Sure
Anyways its late
But have a good night

I amma go sleep i have a massive JavaScript project i need to do tomorrow πŸ‘

slate swan
#

I have a question. The discord snowflakes are made of current time + process_id + worker_id + random_bits. How do you get the process and worker id in python?

idle sparrow
#

I think the starting point is
A thread however i am not sure

slate swan
#

os.getpid returns some what they say a process id, but not sure if it's the same thing they use in snowflakes too

sick birch
#

also why do you want that? process and worker ID is meaningless outside of discord's internal infrastructure

#

the only useful part of the discord snowflakes are the creation time

slate swan
slate swan
sick birch
#

That's not public I don't believe (might have some info in one of the engineering blogs) but again, doesn't matter much to us users

#

It's only really implementable if you have a lot of nodes working at once, which you won't unless you have thousands of users

#

If you have a small app with not many users, your process_id and worker_id will always be the same, something like 0

slate swan
#

I found some implementations of twitter's snowflake (same what discord uses) and yes they had some weird bit shift stuff going on I just ignored it

sick birch
#

That's probably how they actually form the ID with the individual parts

unkempt canyonBOT
#

snowflake.py lines 11 to 19

worker_id_bits = 5L
data_center_id_bits = 5L
max_worker_id = -1L ^ (-1L << worker_id_bits)
max_data_center_id = -1L ^ (-1L << data_center_id_bits)
sequence_bits = 12L
worker_id_shift = sequence_bits
data_center_id_shift = sequence_bits + worker_id_bits
timestamp_left_shift = sequence_bits + worker_id_bits + data_center_id_bits
sequence_mask = -1L ^ (-1L << sequence_bits)```
cold tide
#

@bot.event async def on_command_error(ctx, error): error=discord.Embed() error=discord.Embed(title=f" πŸ€– ERROR 🚫 ",description=f"{ctx.author} seller/member role is needed to run this command try again !",color=0xffff00) await ctx.reply(embed=error)

#

Ive set my roles up for the cmd and it still doesnt show this error when ppl dont have the right roles

elfin moon
#

how do i get the session id of the bot in discord.py, is it the same as shard_id

elfin moon
whole sparrow
#

how do i send an empty value in embed discord

#

embed.add_field(name="asdasdsadasdsads", value="sd", inline=False) how do i send empty value

sick birch
pliant gulch
#

** **

sick birch
#

Yeah that works too I believe

terse coyote
#

how to except this raise
discord.ext.commands.errors.MemberNotFound: Member "sdsd" not found.

cold tide
#

@bot.event async def on_command_error(ctx, error): error=discord.Embed() error=discord.Embed(title=f" πŸ€– ERROR 🚫 ",description=f"{ctx.author} seller/member role is needed to run this command try again !",color=0xffff00) await ctx.reply(embed=error)

#

I have 2 @bot.event but for 2 differnet commands and they seem to be getting mixed up how do i fix them?

spring dome
spring dome
cold tide
#

@spring dome it would be much easier if you could join my server to asess the issue.

#

i hope i dont break any rules mentioning so.

terse coyote
spring dome
#

on_command_error is a global event processor. If I understand you correctly you might want to use a decorator to build an error handler for each command. something like ```py
@bot.command()
async def command_A(ctx):
...

@command_A.error()
async def command_A_error(ctx, error):
...

cold tide
spring dome
#

bot.event means global

cold tide
spring dome
#

what should be happening is that both commands should execute the last bot.event

cold tide
#

i havent expanded my further knowledge on discord.py just the basics so far

#

let me post the code.

spring dome
#

what you want to happen is that each command be assigned its own handler, as would happen with the decorators

cold tide
#

Here is premium

#
  if ctx.channel.id==998928038047780935:
        emb3=discord.Embed()
        emb3=discord.Embed(title=" πŸ€– Reaper Premium Succesfully Generated βœ…",description=f"Check your inbox {ctx.author} !",color=0xffff00)
        await ctx.reply(embed=emb3)
        embed=discord.Embed()
        embed=discord.Embed(title="Reaper Premium Gen !",description="Premium Generator πŸ’°",color=0xffff00)
        embed.add_field(name="Generated info:",value=random.choice(premium))
        await ctx.author.send(embed=embed)```
#

Non premium

#
@commands.has_role("Member",)
@commands.has_role("seller")
async def tiktok(ctx):
	if ctx.channel.id==998759012889809046:
		embed=discord.Embed()
		embed=discord.Embed(title="πŸ€– Reaper Gen",description="Non-Premium Gen !",color=0xffff00)
		embed.add_field(name="Generated Info:",value=random.choice(tiktokk),inline=True)
		embed.set_footer(text="Gen Command ! Dev - vd#7157")
		emb2=discord.Embed()
		emb2=discord.Embed(title=" Successfully Generated βœ…",description=f"Check your inbox {ctx.author} !",color=0xffff00)
		emb2.set_footer(text=f"Thankyou for using Reaper Gen πŸ€–")
		await ctx.reply(embed=emb2)
		await ctx.author.send(embed=embed)```
#

These 2 commands use 2 @bot.event commands but when running them they dont work correctly.

spring dome
#

that is because bot.event is called from a global standpoint. it is not specific to one command, it is all commands

#

what you need is to use the decorators like i demonstrated above to individually assign error handlers to your commands

cold tide
#

Okay.

#

How would i make a command that shows a error if a command is executed in the wrong channel?

spring dome
#

create a custom exception and raise it if the command executes in the wrong channel

cold tide
#

could you show me a example??

#

Still learning lol

slate swan
#

you dont need a custom exception, a simple conditional works

spring dome
#
class WrongChannelError(Exception):
  def __init__(self, channel):
    self.channel = channel
    self.reason = f'You must use this command in {channel}'

...

@bot.command()
async def command_A(ctx):
  if not ctx.channel.id == 1231231231231:
    raise WrongChannelError(123123123123)

@command_A.error()
async def command_A_error(ctx, error):
  if isinstance(error, WrongChannelError):
    await ctx.send(error.reason)
cold tide
#

Okay.

spring dome
#

since he wants to use the individual error handlers, the exception is the way to go as it is the only way you will get the problem outside the scope of the original function

cold tide
#

yes.

#

So @command_A is a variable??

#

beacuse of A?

spring dome
#

command_A is your function

cold tide
#

so i can make another statment called command_B

#

?

#

So if a error occurs it will show?? Like @bot.event

spring dome
#

your decorator @command_A.error assigns the underlying function as an error handler for anything that gets raised in command_a

cold tide
#

Okay.

#

Thankyou!

spring dome
#

if an error occurs in command_B, you will need another @command_B.error function to describe what to do

cold tide
#

Okay

robust fulcrum
#
    @commands.Cog.listener()
    async def on_message(self,message):
        tex = perspective(message.content)
        print(message.content)
        send = tex.toxicity()
        send2 = tex.profanity()
        if send > 0.7:
            await message.delete()
            embed = discord.Embed(title="warning", description="Please dont use bad words!",color=discord.Color.red())
            await message.channel.send(embed=embed)
        elif send2 > 0.7:
            await message.delete()
            embed = discord.Embed(title="warning", description="Please dont use bad words!",color=discord.Color.red())
            await message.channel.send(embed=embed)

Guys this event is not listening to any message even i tried printing the message it
Pls help

smoky cedar
#

RuntimeError: Timeout context manager should be used inside a task

Any idea yall?

smoky cedar
#

Sec... think this might be a python version compatibility issue with this spotify api wrapper I'm using

twin flower
#

my discord bot has become sentient, what od i do

dusky pine
hollow widget
#

Hello ! Can I please, delete this button ??

hybrid fjord
#

how do i set up specified options in slash commands?

#

also does d.py 2.0 have dropdowns?

#

no you cant

#

bruh honestly python is one of the worst languages to write discord bots in

pliant gulch
#

How so

hybrid fjord
pliant gulch
#

True

#

Mostly because the whole python wrapper space was dominated by discord.py, then it archived which stunted the growth of python wrappers sorta, then it came back πŸ˜…

#

A big mess

hybrid fjord
#

yea

slate swan
#

i would disagree on the statement, most people just turned to disnake at sticked with it while knowing that the development of the library wasnt going to stop, it confused many users but they werent scared or regretting changing back, especially the oldccommand stucture with decorators that make bot development easy with python compared to other languages e.g ruby.

smoky cedar
#

How to add a reaction to an interaction message?

sick birch
smoky cedar
#

after that I want to add reactions to it

sick birch
#

Because you can't add reaction to those I don't believe

#

If not, interaction.response.send_message returns the sent message, so you can add reaction to that:

message = await interaction.response.send_message(...)
await message.add_reaction('😎')
smoky cedar
#

Actually, it looks like send_message is returning None to me

#

Are you sure? @sick birch

#

And looking at the method it doesn't seem there is a return value

paper sluice
#

try

await interaction.response.send_message(...)
interaction.message.add_reactions('...')
smoky cedar
white aurora
#

async def

#

?

smoky cedar
slate swan
#

!d discord.Interaction.message

unkempt canyonBOT
smoky cedar
slate swan
#

weird it doesnt show why it can be optional i guess something else can invoke the command idk

smoky cedar
#

Atleast not in the traditional sense

slate swan
smoky cedar
slate swan
#

Im pretty sure that returns the message?

#

wait what it doesnt????

smoky cedar
#

Investigating

#

Yeah not that I can see

slate swan
#

πŸ₯΄

smoky cedar
#

I even looked at the method implementation and don't see any return statement

smoky cedar
slate swan
#

weird not even a partial obj is returned

shrewd apex
#

oki do u know any good tutorial for advanced use of decorators

#

or just decos in general

slate swan
# shrewd apex oki do u know any good tutorial for advanced use of decorators

In this Python tutorial, we will be learning about decorators. Decorators are a way to dynamically alter the functionality of your functions. So for example, if you wanted to log information when a function is run, you could use a decorator to add this functionality without modifying the source code of your original function. So let's take a loo...

β–Ά Play video
shrewd apex
#

is there one for passing args to decos as well?

shrewd apex
#

oh there is

sick birch
#

Give me a second, let me check out the docs again

hardy yoke
#

pretty sure it's the same in disnake

shrewd apex
#

thank u okiπŸ˜„

smoky cedar
slate swan
slate swan
sick birch
# smoky cedar Thanks

Ah yikes. Now I’m doubting if it’s even possible, I don’t see any way to get the sent message

hardy yoke
#

storing the message with inter.original_message() after your .send works in disnake

slate swan
#

he ment his response message not the one which invoked the interaction

sick birch
#

Maybe because interaction response messages aren’t regular messages?

smoky cedar
#

I was able to react to them with discord_slash

#

All I can think of now is to retrieve the latest message in that channel

#

But that's so sloppy

#

Github issue time?

sick birch
#

Hmm then it must be possible

#

Probably not.. must be possible, we’re just missing something

slate swan
sick birch
#

Mmm.. looks like you have to manually fetch the message object, but it doesn’t even return a message ID to do that

#

@smoky cedar have you tried interaction.original_message?

#

This seems to be what you want

#

!d discord.Interaction.original_message

unkempt canyonBOT
#

await original_message()```
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.
sick birch
#

Yeah, this gets the response message

#

See the little blob in the center

#

Terrible naming strategy and the important part is a tiny hidden blob but whatever we found it

slate swan
#

he wants to send a message and pass the reactions to that message he just sent and not the response one idk

sick birch
#

Yeah, and original_message is exactly what they want

smoky cedar
#

Man that is kind of a big meh though

sick birch
#

Yup, let me know how it goes

smoky cedar
#

await (await interaction.original_message()).add_reaction(FOLLOW_ROLE_EMOJI)

#

very ugly, let you know shortly

sick birch
#

You should probably split that up

slate swan
smoky cedar
#

yeah, I should haa

sick birch
#

Save the original message into a variable yeah

slate swan
#

wait it doesnt pithink

sick birch
hardy yoke
#

I take full credit for this revelation

sick birch
#

Lol props to you.. I remember you mentioned it but thought the same thing as Okimii

slate swan
#

method naming smhπŸ—Ώ

sick birch
#

Had to rack my brain on this one. Bad implementation on discord.py’s part if you ask me

smoky cedar
#

Success

slate swan
#

!d discord.Interaction.message

unkempt canyonBOT
sick birch
#

Whew, good to hear

smoky cedar
#

Thanks yall, and I completely agree @sick birch . Could save an entire line of code just returning the message object

slate swan
smoky cedar
#

And lots of confusion

sick birch
#

A slash command doesn’t have an original message that it originates from, similar to a button which is present inside of a existing message

#

Slash commands aren’t present in an existing message, they’re seperate, so someone thought it was a good idea to have .original_message() return the response

slate swan
smoky cedar
#

now... how to get the author who sent the slash command to add them a role

sick birch
#

Easy, interaction.user

#

I assume you know how to add roles to a regular member object

smoky cedar
#

Yup

#

Just migrating from the other library right now

sick birch
#

Actually.. if I’m correct interaction.user should be a discord.User object rather than a member object

#

Which throws another wrench in things

smoky cedar
#

damnit

sick birch
#

Man this whole interaction slash command thing is a pain isn’t it

slate swan
sick birch
#

Easiest solution that I can think of is to use interaction.guild.get_member(interaction.user.id)

slate swan
#

just checked and it returns User | Member

sick birch
#

As there’s a reason they’re a user instead of a member (no longer in guild)

#

So adding a role to them probably won’t work

smoky cedar
#

Gotcha... so this is basically an impossible scenario for me

#

Unless someone can leave within 1 second of sending the command

sick birch
#

No, fortunately. Just an extra line

slate swan
#

just use isinstance to check the type

sick birch
#

You can use isinstance to check if they’re a member or a user

shrewd apex
#
if isinstance(interaction.user, discord.Member):
    ...
sick birch
smoky cedar
shrewd apex
#

which is more handy using decorators with deco classes or just making a wrapper/ deco function

sick birch
#

Depends on the situation. What are you trying to do?

shrewd apex
#

just learning decos and it's uses

#

only places i used decos was in discord bots and commands checks but those are just simple case uses

sick birch
#

Well.. then it just depends on the use case. You won’t always use one over the other

shrewd apex
#

mhm true

sick birch
#

Anyway, @smoky cedar I’m off to bed for now. If you’ve got any more questions I’m sure the lovely folks in this channel would be more than happy to help you out. Cheers

shrewd apex
#

so for chaining decos we use nested functions so for chaining class decos do we subclass?

sick birch
shrewd apex
#

oh cool

sick birch
#

Just pretend as if your deco is the only one that’ll be used

shrewd apex
#

class gives a lot of access to dunder methods and stuff so i assume that is a perk of using class decos

vocal snow
#

Wow Robin called us lovely

paper sluice
paper sluice
#

bruh

slate swan
vocal snow
#

Okimii do you want to see cat

#

She fractured her left hind limb and is staying with me till it heals

slate swan
swift pumice
#

hi zeffo

vocal snow
#

πŸ‘‹

slate swan
#

beautiful catπŸ’“

vocal snow
#

They are called tortoiseshells (or torties)

slate swan
slate swan
jade fulcrum
#

Guys

#

I want this discord bot to reply to me when I say hello

#

But I want it to reply it with random words in the backets

vocal snow
#

Don't put a space between the decorator and function

jade fulcrum
#

How do I do that

jade fulcrum
slate swan
#

and you can use random.choice with a list

jade fulcrum
vocal snow
slate swan
#

whatπŸ›Œ

vocal snow
#

Good bye and good luck!

slate swan
paper sluice
# jade fulcrum

make a list of words, then use random.choice to get a random word from that list

light violet
#

!eval print([1]10001000)

slate swan
light violet
unkempt canyonBOT
#

@light violet :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | ModuleNotFoundError: No module named 'httpx'
slate swan
#

#bot-commands

light violet
#

Lol

#

Ok ok sorry

jolly basalt
#

so um

#

can anyone suggest a project that will take a long time to make

#

and will make me more familiar with python and discord.py

slate swan
jolly basalt
slate swan
#

it will take you a long time πŸ₯΄

jolly basalt
#

i mean

#

smth a bit easier

#

im really new to python

slate swan
# jolly basalt im really new to python

ahh, choose a random api and wrap it, the main features should be a sync client and an async client, cache implementation, ratelimiter if you need one and a Object Oriented wrapper

vocal snow
#

!kindling

unkempt canyonBOT
#

Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

vocal snow
#

there's also these

slate swan
#

πŸ™„

vocal snow
#

:D

jolly basalt
slate swan
#

πŸ₯΄

#
self.tree = discord.app_commands.CommandTree(self)
AttributeError: module 'discord' has no attribute 'app_commands'
vocal snow
#

@slate swan

jolly basalt
slate swan
slate swan
slate swan
#

You made the neko one right?

#

i havent made sync clients tho lmao

slate swan
#

Yes!!!

#

Love that one, how hard was it to make?

slate swan
# slate swan Love that one, how hard was it to make?

It wasnt hard, their api is quite basic, its just some endpoints with sub endpoints, it doesn't need objects either, i just added objects, its all in a db so its just an API that fetches data from a db so no ratelimit either iirc

#

you can always make your own apipithink

fluid zodiac
#
import nextcord, nextcord.ui, asyncio
from nextcord.ext import commands

class Bot(commands.Bot):
    def __init__(self, *args, **rwargs):
        super().__init__(*args, **rwargs)

    async def on_ready(self):
        print(f"bot online\n")

client = Bot(command_prefix="$", intents=nextcord.Intents().all())

@client.slash_command()
async def testcmd(interaction: nextcord.Interaction):
    eee = await interaction.send('eee')
    await asyncio.sleep(1)
    await eee.edit('test')

Error when im trying to change the message:

Ignoring exception in command testcmd:
Traceback (most recent call last):
  File "E:\Softwares\PyCharm\PyCharm 2021.3.3\pythonProject\venv\lib\site-packages\nextcord\application_command.py", line 1053, in _call_with_hooks
    await callback(*args)
  File "E:\Softwares\PyCharm\PyCharm 2021.3.3\pythonProject\venv\lib\site-packages\nextcord\application_command.py", line 1135, in call_invoke_slash
    await self.invoke_slash(interaction, **kwargs)
  File "E:\Softwares\PyCharm\PyCharm 2021.3.3\pythonProject\venv\lib\site-packages\nextcord\application_command.py", line 1228, in invoke_slash
    await self.callback(interaction, **kwargs)
  File "E:\Softwares\PyCharm\PyCharm 2021.3.3\pythonProject\DiscordBot\main2.py", line 134, in testcmd
    await eee.edit('test')
AttributeError: 'NoneType' object has no attribute 'edit'

The above exception was the direct cause of the following exception:

nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'edit'
slate swan
#

wrap the api then!!!!!

#

Soon 🀣

slate swan
#

It's a very simple api though, uses fastapi with some simple ratelimiting

paper sluice
slate swan
#

How do i change the description of an embed in another place i mean like:

em = discord.Embed(title=f"akinator:",color=discord.Color.blue())

# condition
em.change_description(description="something")

?

fluid zodiac
slate swan
paper sluice
#

yea

slate swan
#

Yeah I love fastapi

#

you wouldnt need fastapi either way

paper sluice
#

i guess its not 15 lines because i used an existing project i made earlier, but the api part is just 15 lol

slate swan
slate swan
fluid zodiac
slate swan
#

!d nextcord.Interaction.original_message

unkempt canyonBOT
#

await original_message()```
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 [`InteractionResponse.send_message()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.send_message "nextcord.InteractionResponse.send_message") then this would return the message that was sent using that response. Otherwise, this would return the message that triggered the interaction.

Repeated calls to this will return a cached value.
slate swan
#

I want to ask that, thanks

dreamy hamlet
#

guys how so i create a discord bot using python? What are the basics and which is the best way?

vocal snow
#

do you know python basics?

dreamy hamlet
vocal snow
#

you can start here then ^

dreamy hamlet
#

Alright

slate swan
#

!d discord.Interaction.original_message

unkempt canyonBOT
#

await original_message()```
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.
slate swan
#

nice

shrewd apex
#

top.gg lib has an on vote event

#

u can use that

#

to update the channel name

vocal snow
#

discord really hates channel counters

shrewd apex
#

to match number of votes

vocal snow
#

the channel edit ratelimit is significantly high... I would not recommend using it

slate swan
vocal snow
#

2 updates per 10 minutes :d

shrewd apex
#

i mean its fine if there are less votes per sec

shrewd apex
vocal snow
shrewd apex
#

rip

#

just do it every half an hour

#

make a task loop

#

to check number of votes

slate swan
#

Don't while loop work in async functions ?

#

you make a group, 'gtn' is the group while 'start' is a subcommand

placid skiff
slate swan
#

probably, dont know how pycord implements slash groups

slate swan
slate swan
#

except that loop

#

i do some interaction messages send and etc in while loop but it didn't work

#
while aki.progression <= 80:
  em.description = q
  await interaction.original_message.edit(embed=em)
  def check(reaction, user):
    return user == interaction.user

  reaction = await bot.wait_for("reaction_add", check=check)
  if reaction == "πŸ‘πŸΌ":
    q = aki.answer("yes")
  if reaction == "πŸ‘ŽπŸΌ":
    q = aki.answer("no")
  if reaction == "❓":
    q = aki.answer("idk")
slate swan
slate swan
#

Hello ?

#

you can just create a task or run the loop in run_in_executor

visual island
#

or just simply put an await asyncio.sleep() (in a while loop inside an async function)

slate swan
paper sluice
slate swan
visual island
#

without asyncio.sleep(), it would just block

slate swan
#

You mean normally any loop don't work without sleeping a short period of time to execute the next task ? Which is what "asyncio" all about ?

#

In that case should i put asyncio.sleep() for every command ?

#

or in the end of the current loop ?

#

like:

while condition:
  ...
  ...
  await asyncio.sleep()
visual island
#

at the end of your while loop (also await it)

slate swan
#

Thanks.

#

guild.owner is already a Member object
if you don't have member intents you can fetch the member from ctx.guild.fetch_member(ctx.guild.owner_id)

#

^it's a coro

slate swan
visual island
#

great!

slate swan
#

okay.

#

well, that is what slash commands are for

#

we

#

uwu

#

I love that logic

#

which lib

odd mango
#

is there any repo or lib yet which lets you use slash commands with just a decoration?

#

in dpy btw

slate swan
odd mango
#

dawn πŸ˜”

slate swan
#

mhm no idea then

slate swan
#

you don't need to get_user.

odd mango
slate swan
#

what

odd mango
#

also dawn is hikari iirc

slate swan
odd mango
#

tried to search

slate swan
#

Any way to add reactions to an interaction message ?

await interaction.original_message().add_reaction("πŸ‘πŸΌ")

AttributeError: 'coroutine' object has no attribute 'add_reaction'

?

slate swan
odd mango
#

she didnt last i saw

slate swan
slate swan
odd mango
#

peaceeee

slate swan
#

i should add them to a repo

odd mango
#

robo danny ducks

slate swan
magic zenith
#

How do I check if an item from a list is present in message content and print that item

odd mango
#

maybe im dumb

#

BUT dosent change the fact that robo danny ducks

slate swan
#

its called hybid commands

slate swan
odd mango
#

🚢

slate swan
odd mango
slate swan
#

dead on

#

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

oki bai

odd mango
#

πŸ‘‹

magic zenith
# slate swan !d any

I wanna be able to return that item in a print string function instead of boolean

magic zenith
#

Ah gotcha

odd mango
slate swan
#

!d discord.Guild.owner

unkempt canyonBOT
odd mango
#
from discord import app_commands```?
slate swan
#

why bot ?
and as i said its a coroutine

shrewd apex
odd mango
#

but i dont see slash commands

#

permission issue?

slate swan
magic zenith
#

Having trouble in putting it into code, can you help?

list = ["spider", "ant", "worm"]

@bot.event
async def on_message(ctx):
    #check if an item from list is in ctx.content:
        #print that item

Code example

slate swan
odd mango
#

yeah

slate swan
#

make sure to sync the commands

odd mango
#

hm?

slate swan
unkempt canyonBOT
#

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

['spider', 'ant']
slate swan
unkempt canyonBOT
#

await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Syncs the application commands to Discord.

This must be called for the application commands to show up.
slate swan
#

basically, bot.tree.sync()

shrewd apex
#
@bot.event
async def on_message(message):
  lst = ["spider", "ant", "worm"]
  if (x := list(filter(lambda i: if i in message.content, lst))):
     await message.channel.send('\n'.join(x))
shrewd apex
#

...

#

;-;

magic zenith
#

Lol

#

Ty to you too

shrewd apex
#

nvm sarths simpler for beginners

odd mango
vocal snow
slate swan
odd mango
#

i did

slate swan
#

move it into the setup_hook or something

odd mango
#

ok ok

slate swan
odd mango
slate swan
#

reload ur discord client

odd mango
#

ok

odd mango
#

await it

slate swan
#

its a coroutine

odd mango
#

yes

#

also the outer brackets are redundant

slate swan
odd mango
#

it is, havent updated teh repl

slate swan
#

invite the bot with application commands scope

odd mango
#

doing it in vsc, 2 mins

slate swan
#

How to remove a specific user's reaction in a message ?

#

!d discord.Message.remove_reaction

unkempt canyonBOT
#

await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Remove a reaction by the member from 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").

If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.

The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
slate swan
#

emoji, member

#

Thanks

#

!d discord.Guild.premium_tier

unkempt canyonBOT
#

The premium tier for this guild. Corresponds to β€œNitro Server” in the official UI. The number goes from 0 to 3 inclusive.

magic zenith
shrewd apex
#

lemme try

paper sluice
#

ternary if statements are like this out if condition else output

#

just remove the if

#

do i in message

shrewd apex
#

^^

magic zenith
#

Ah ok

shrewd apex
#

!e

lst = ["spider", "ant", "worm"]

message = "i saw an ant"

if (x := list(filter(lambda i: i in message, lst))):
    print(x)
    print('\n'.join(x))
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your eval job has completed with return code 0.

001 | ['ant']
002 | ant
magic zenith
#

Sweet, it worked

#

Now how do i print it like this?

print("I saw an {item} a moment ago")
slate swan
#

just replace the item with your join part

magic zenith
#
print("I saw an \n.join(x) a moment ago")
#

?

shrewd apex
#

print("I saw an {', '.join(x)} a moment ago")

magic zenith
#

Gotcha

slate swan
magic zenith
#

It worked

#

Nice

gilded gust
#

Hey, currently on a bot using py-cord, and have run into a bit of an issue. I need to disable all buttons in a view but I'm not sure how to do so, I could only find how to disable a single button, not every button. Please help.

shrewd apex
#

if pycord is similar to dpy then

for i in view.children:
  i.disabled = True
#edit the message with the new disabled view
magic zenith
#

How can I check if the first item from list is present in string using an if statement?

rain olive
#

index the list

#

if list[0] in string

magic zenith
#

Ah ok

rain olive
#

what lib

#

idk if guild.bans is a thing

robust fulcrum
#

I got no indentation error ;-;

rain olive
#

@slate swan can u try

print((await guild.bans())[0])
robust fulcrum
#
    @commands.Cog.listener()
    async def on_message(self,message):
        tex = perspective(message.content)
        print(message.content)
        send = tex.toxicity()
        send2 = tex.profanity()
        if send > 0.7:
            await message.delete()
            embed = discord.Embed(title="warning", description="Please dont use bad words!",color=discord.Color.red())
            await message.channel.send(embed=embed)
        elif send2 > 0.7:
            await message.delete()
            embed = discord.Embed(title="warning", description="Please dont use bad words!",color=discord.Color.red())
            await message.channel.send(embed=embed)

Guys this event is not listening to any message even i tried printing the message it
Pls help

slate swan
#

How do I use β€œFFFFFF” at ```py
(color=FFFFFF)

#

Says FFFFFF is not defined

gilded gust
#

or int('ffffff', 16)

#

but 0xffffff is shorter

slate swan
#

function on_message(message), how do i get the content of message ? it's a class.

gilded gust
#

message.content

slate swan
#

i tried message.content but it didn't work

gilded gust
#

share your code

slate swan
gilded gust
paper sluice
slate swan
paper sluice
#

version

slate swan
paper sluice
#

you need messge_content intent enabled

slate swan
# gilded gust share your code
@bot.event
async def on_message(message):
    print(message)
    if "$" in message.content:
        print(message.content, message.content[-1])
        if message.content[0] == "$" and message.content[-1] == "$":
            sympy.preview(message, viewer='file', filename='test.png', euler=False)
            file = discord.File("test.png", filename="test.png")
            await message.channel.send("attachment://test.png")
paper sluice
#

do

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(..., intents=intents)
gilded gust
slate swan
magic zenith
#

How do I make it so as long as a variable is true, the bot keeps sending a message in an specific channel after a certain amount of time?

gilded gust
#

you can use tasks

slate swan
#

im trying to make somthing that reacts with a emoji to everything in a channel

gilded gust
#
for message in channel.history(limit=200): # will look through the last 200 messages in the channel
  message.react('emoji')
slate swan
#

it returns an AsyncIterator
and it's message.add_reaction

vale wing
gilded gust
vale wing
#

Ok

robust fulcrum
slate swan
#

yeah, the kwarg was removed

#

yes

robust fulcrum
slate swan
#

i tried to make hug comand using event on message
but i dont know why is this dont work message.author.mention i cant ping mention user

#

its only ping me

#

ye

robust fulcrum
slate swan
#

no

vale wing
#

Is this replit

#

Where do these logs come from

#

What library do you have

slate swan
#

your bot is ratelimited, wait for some time

vale wing
#
await ctx.send(file=discord.File(...))```
#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
paper sluice
slate swan
#

more like bot.run() now does that by default

jade fulcrum
#

does anyone know

#

how to add more options to this?

vale wing
#

Erm are you trying to make a command

slate swan
eternal fox
slate swan
#

Client and Bot are two completely different things, though client and bot are just the instance name, it can be anything

eternal fox
#

Okokay

slate swan
#
def get(key):
    with open("./data/colors.json", "r") as raw:
        data = json.load(raw)
    color = int(data[key], 16)
    return color

color.get(error) does not work

{
  "error": "0xB91C32"
}```
=> `NameError: name 'error' is not defined`
#

I import it as a util

from utils import color

slate swan
#

{
"error": 0xB91C32
}

#

oh its a json vm

#

xD

slate swan
#

ok

#

makes sence

#

yeah its same as color["error"], but will return None of the key was not found

#

works

#

instead of raising an KeyError

#

thx :*

#

how to make a admin only channel with discordp

#

y

hazy oxide
#

Create a channel then set the permissions

#

Or role, idk

robust fulcrum
#

Holy man my bot got rate limited

#

When i used comand then it showed error otherwise it not showing

#

My bot is not being online even i run code!

slate swan
#

how unfortunate

robust fulcrum
paper sluice
robust fulcrum
#

Ahhahhh

robust fulcrum
paper sluice
#

you just said everything was working fine

robust fulcrum
#

Now it's not.

paper sluice
robust fulcrum
#

Ye

#

I have

paper sluice
#

remove that, have only one

robust fulcrum
#

Ok

robust fulcrum
#

Will it work?

paper sluice
#

your commands will work

slate swan
#

so will the listener

robust fulcrum
#

I still not able to understand what's difference between event and listener

slate swan
#

event is related to the bot directly py @bot.event async def on_message(): ... is same as bot.on_message = some function
listener on the other hand adds adds listeners to functions

#

you can have only one of an event, but multiple listeners for same event

#

Should just start a paid school, you volunteers would never need to work again lol

slate swan
#

that's the issue

robust fulcrum
# paper sluice your commands will work
@bot.listen("on_message")
async def on_message(message):
    userid = message.author.id
    connection = bot.connection
    cursor = await connection.cursor()
    await cursor.execute('SELECT * FROM afktable WHERE user_id=?',(userid,))
    check = await cursor.fetchone()
    if check == None:
        pass
    else:
        timess = await cursor.execute('SELECT time FROM afktable WHERE user_id=?',(userid,))
        timestamp = (await timess.fetchone())[0]
        await cursor.execute('DELETE  FROM afktable WHERE user_id=?',(userid,))
        await connection.commit()
        oldtime = datetime.datetime.fromtimestamp(timestamp)
        nowtime = datetime.datetime.now().replace(microsecond=0)
        pr = nowtime-oldtime
        pr = (f"{pr}")
        t = datetime.datetime.strptime(pr,"%H:%M:%S")
        delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
        ans = humanize.naturaldelta(delta)
        embed = discord.Embed(title=f"{message.author}\nAFk removed!", description=f"I have removed your AFK\n you were afk for **{ans}** ",color=discord.Color.green())
        embed.set_thumbnail(url=message.author.display_avatar.url)
        await message.channel.send(embed=embed)
    await bot.process_commands(message)

    async def on_messag(self,message):
        tex = perspective(message.content)
        send = tex.toxicity()
        send2 = tex.profanity()
        if send > 0.7:
            await message.delete()
            embed = discord.Embed(title="warning", description="Please dont use bad words!",color=discord.Color.red())
            await message.channel.send(embed=embed)
        elif send2 > 0.7:
            await message.delete()
            embed = discord.Embed(title="warning", description="Please dont use bad words!",color=discord.Color.red())
            await message.channel.send(embed=embed)
        await bot.process_commands(message)

Is it correct?

slate swan
#

Nah not really, the amount of people i see you helping here daily (helped me a few tiems too), its well worth looking at a paid lessons.

paper sluice
paper sluice
#

and you dont need bot.process_commands in a listener

slate swan
slate swan
#

you dont need to edit the view using interaction.response.edit...
and that does look fine, you shouldnt have a problem

#

what

paper sluice
slate swan
paper sluice
robust fulcrum
slate swan
robust fulcrum
slate swan
#

they shouldnt have the same name

robust fulcrum
slate swan
paper sluice
#

!paste please

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.

robust fulcrum
#

Ok

slate swan
#

you can't have two functions named on_message, only one of them will work

robust fulcrum
slate swan
#

show all of your code, and define not working, are there any errors?

robust fulcrum
pale turtle
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.

Changed in version 2.0: `message` parameter is now positional-only.
pale turtle
#

Add this to the end of your on_message

robust fulcrum
#

Bruh

slate swan
robust fulcrum
slate swan
robust fulcrum
pale turtle
#

Uh I forgot, haven't used python for like a year now

#

Sorry

slate swan
pale turtle
#

Happy now?

#

Or discord-bot coding or whatever

slate swan
#

i bet ash is happier than ever now

wild spoke
#

how can I make bot autoreact on message containing a specific emoji?

slate swan
#

β€’ Listen to on_message events
β€’ Check if the message.content contains the emoji concerned
β€’ Add the reaction to the message object with message.add_reaction(...)

wild spoke
#

(im really bad at python and ds.py)

#

do I need to make a cog for it?

slate swan
#

Not necessarily

wild spoke
#

I tried doing something in my commands cog but it only gave me a traceback

slate swan
wild spoke
#

"emoji here" is discord entire name:id of emoji?

slate swan
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

wild spoke
#

just because I really don't like pre-made public bots

slate swan
#

Still, learning Python is mandatory

wild spoke
#

yeah I know

#

university 1st course

#

I know basics of python

#

up to working with classes

livid hedge
#

tree = app_commands.CommandTree(bot)

#

discord.errors.ClientException: This client already has an associated command tree.

slate swan
livid hedge
#

ty

#

and now how can I fix this? discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

#
intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix=prefix, intents=intents)
slate swan
#

Bot probably can't create slash commands in the guild concerned

slate swan
winter gull
#

commands.BucketType.guild this set the cooldown for guild right? and not user specific.
like if the command is ran once the whole guild cannot run it until the cooldown ends

eternal fox
# wild spoke

Try:

@bot.event
async def on_message(message):
 if "theemoji" in message.content:
  await message.add_reaction("emojiyouwannareact")
slate swan
eternal fox
winter gull
eternal fox
slate swan
#

.listen is more convenient

eternal fox
#

Ooh

slate swan
#

And the code above works fine, if intents are enabled correctly

slate swan
eternal fox
#

Okioki my bad,im used to @bot.event

robust fulcrum
#

Guys my bot commands are not working even i don't shev many events
And it was working before 5 minutes

robust fulcrum
#

It's listener

#

On_message listener

slate swan
#

Yeah well without code or a more precise traceback/explanation we can't help

heavy swift
robust fulcrum
slate swan
heavy swift
#

🀨

slate swan
#

Unless it's at startup, which would simply require you to enable them in the developer portal. And I believe it's another error?

#

Raises discord.PrivilegedIntentsRequired and not discord.Forbidden

#

Or something close to that

#

!d discord.PrivilegedIntentsRequired

unkempt canyonBOT
#

exception discord.PrivilegedIntentsRequired(shard_id)```
Exception that’s raised when the gateway is requesting privileged intents but they’re not ticked in the developer page yet.

Go to <https://discord.com/developers/applications/> and enable the intents that are required. Currently these are as follows:

β€’ [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members")

β€’ [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences")

β€’ [`Intents.message_content`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.message_content "discord.Intents.message_content")
slate swan
#

yuh that is getting raised

livid hedge
#

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

slate swan