#discord-bots

1 messages Β· Page 41 of 1

sick birch
#

No, in the code

#

!d discord.Intents.presences

unkempt canyonBOT
#

Whether guild presence related events are enabled.

This corresponds to the following events:

β€’ on_presence_update()

This also corresponds to the following attributes and classes in terms of cache...

sick birch
#

You can just try discord.Intents.all() for testing purposes

slate swan
#

ok

#

so the activity worked

#

but it wasnt activity lol it was my

#

the status still says offline

#

Started this at 6pm yesterday, it's now 8am.
My code is now fully adapted for cogs and completely error free.
Thank you so much @sick birch @primal token.

I'm going to bed lol

slate swan
#

i fixed it

#

dw its because i had mobile_status instead of raw_status

#

ok sorry for being annoying but last thing

#

is it possible to change .created_at and .joined_at to a timespam

#

like instead of

#

created 2 years ago

#

joined a month ago etc

#

please ping me if anyone replys because im coming of my pc now

glad cradle
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
glad cradle
#

@slate swan

slate swan
glad cradle
slate swan
#

not really sure how to put it how you want it tho

#

that's just the formatting

glad cradle
hidden haven
#

How can I send a message to any user who reacts to my bot's message? I know how to check for the user being the same person that initiated the bot user == message.author, but how do i define the user as any person on the server?

slate swan
hidden haven
#

DM

slate swan
#

@client.event
async def on_reaction_add(reaction, user):
    ChannelID = id
    if reaction.message != ChannelID:
        return
    if user.reaction.emoji == ":thumbsup:":
        await user.send('message')```
#

try that, I'm not well versed with discord.py, but I imagine that'd work based on how I've used reactions before

#

as an event sorry, my bad

sick birch
hidden haven
sick birch
#

In that case, you're looking for discord.Client.wait_for

#

!d discord.Client.wait_for here's the relevant documentation

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.10)"). 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.10)") 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.10)") 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**...
hidden haven
#

How do I allow any user to react and get the information? Wouldn't user==message.author limit to just the initiator?

sick birch
hidden haven
sick birch
#

You have to check the message, that's about it

hidden haven
#

yes but don't i need the user information to DM them

sick birch
#
reaction, user = await client.wait_for(...)

is how you get the user

mossy jacinth
#

please someone help me 😭

radiant junco
#
await ctx.send('>>> ``'+'\n'.join(list(map(lambda id: await self.client.fetch_user(id),db["mock"])))+'``')

Trying to use await in lambda which doesn't work but is there another way to do this?
I can't use asyncio.run since i'm mapping the values so I can't include self.client in parameters

#

nvm

limber bison
#

MySQL is completed wrt mongo db

#

Switching becomeing hard 😳

rugged shadow
limber bison
limber bison
# sick birch Try `get_user`

Is there any function with return owner as user ? , I want i someone type !bug the bot dm me , even if i am not in guild

#

Members.send , but how can I get owner as members!

rugged shadow
limber bison
#

Form mongodb

rugged shadow
#

nice

limber bison
#

But me mongo is easy

rugged shadow
#

mongo is a pain πŸ˜”

limber bison
#

Slow ?

unkempt canyonBOT
limber bison
heavy swift
#

I'm not sure how it would work for team applications, so I usually just use a check function

#

but if it's just you, that'd work

drifting arrow
#

Hey, with Modals, is it possible to send multiple modals? Like, after 1 is submitted, the bot sends a 2nd one? Sorta like a page system

#

Not everything I want on the modal fits on it 😦

winged dock
#

Can someone show me how you can make a discord command that prints what you say?

limber bison
#

how can i unhide this in vc code ?

winged dock
#
@bot.command()
async def check(ctx,  arg):
    await ctx.send(arg)
#

this isnt sending why??

limber bison
#

should be working i think

winged dock
#

idk why

limber bison
#

check you other stuff

winged dock
#
@bot.command()
async def check(ctx, arg):
    await ctx.send("test",arg)
#

doesnt send

#

@limber bison

limber bison
#

did u import commands ?

#

oh u r on client

#

nvm

#

whats your client/bot instance ?

winged dock
#

wym?

limber bison
winged dock
#

It worked dw.

#

thankyou so much.

limber bison
winged dock
#

The code

limber bison
#

what thing u change ?

buoyant quail
#

How to put timestamp in embed field value?

heavy swift
buoyant quail
#

thx

heavy swift
#

βœ…

limber bison
#
    @realfight.error
    async def additem_error(self,ctx , error):
        await client.application.owner.send(f'{error}') 

how can get the complete callback ???????????????/

#

its only sending the last error!

austere prairie
#

What d.py alternatives are there with buttons/slash commands/etc. support?

slate swan
#

hikari, forks like disnake, pycord etc....
discord.py has buttons & slash commands support in the master version too

rugged shadow
#

sarth is recommending pycord

#

real?

austere prairie
austere prairie
#

ty

slate swan
slate swan
torn sail
#

Yep

drifting arrow
#

So uhh. When I do print(interaction.channel.type I get public_thread, but when I print the type, I get it as a class.. how can I just get public_thread?

#
print(interaction.channel.type)
        print(type(interaction.channel.type))
        if interaction.channel.type == 'public_thread':
```The if statement doesnt work is what I am trying to say.
#

Can someone help me please

torn sail
drifting arrow
#

alright I believe that worked

#

now to figure out the rest lol

#

Can modals only be sent as a response to a slash command?

#

Or can I use regular commands like !newmodal?

#

Coz it'd be nice to have multiple modals sent in a row so I can get more than like 5 questions on my application form xD

vale wing
#

They include components interactions

drifting arrow
#

Do you know how to send a 2nd modal after the first is submitted?

torn sail
austere vale
#
class LevelCog(commands.Cog, name='Leveling'):
  '''rank, add, subtract'''
  def __init__(self, bot):
    self.bot = bot
  #create leveling database
  @commands.Cog.listener()
  async def on_ready(self):
    setattr(self,'db',await aiosqlite.connect('level.db'))
    await asyncio.sleep(3)
    async with self.db.cursor() as cursor:
      await cursor.execute('CREATE TABLE IF NOT EXISTS levels (guild INTEGER, user INTEGER, level INTEGER, xp INTEGER, ssc INTEGER)')

what would i put instead of self.db.cursor() to make it work inside a cog?

shrewd apex
#

add it to the bot

#

so u can do self.bot.db.cursor

silk fulcrum
#

everytime I click the button on my game it says "This interaction failed" (screenshot 1) and if I add defer here py await self.view.message.edit(view=self.view) await ctx.defer() this error happens (screenshot 2)

silk fulcrum
silk fulcrum
torn sail
#

yeah

silk fulcrum
#

i just accidentally pressed enter;(

torn sail
#
  1. you can only defer once because it is an interaction response
  2. you need to defer the new interaction to make the "interaction failed" go away
#

how come ur using ctx.defer?

silk fulcrum
#

oh bruh ctx

#

forgot

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.

vale wing
#

Your modal is empty

drifting arrow
#

Why is it when I create a new thread using my bot, it doesnt automatically appear under the channel? I have to speak in it to make it appear..

silk fulcrum
pulsar abyss
#

how would I make my bot DM a user after sending a certain message?

silk fulcrum
unkempt canyonBOT
#
Huh? No.

No documentation found for the requested symbol.

silk fulcrum
#

!d discord.User.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
silk fulcrum
#

abc.User doesn't have send for some reason pithink

#

because there is a ClientUser 😫

#

@pulsar abyss

pulsar abyss
#

i wish i knew what any of this meant!

silk fulcrum
#

await my_user.send("Beautiful message"), ig this is all you need

#

it'll DM my_user

pulsar abyss
#

wait it got messed up

silk fulcrum
#

?

pulsar abyss
#

would something like this work? (i literally have no idea what im doing and have never coded)

async def on_message(message):
    if message.author == client.user:
        return
    
    if message.content.startswith('43725'):
        await my_user.send("Beautiful message")```
silk fulcrum
#

no it won't

#

my_user is not defined

#

my_user should be the user you want to dm

#

i guess it's message.author for you

pulsar abyss
#

THANK YOU

#

πŸ™ it works

silk fulcrum
#

ofc

pulsar abyss
#

man i wasted so much time googling stuff and i could have just asked here this whole time 😭

silk fulcrum
#

lmao

#

shit happens

primal token
#

pretty sure abc is just the folder for abstract base classes e.g User lol

silk fulcrum
#

ye

primal token
#

so no need really to provide the folder either as the namespace has already been initiated

limber bison
#

await cur.execute(f"INSERT INTO music_style VALUES({ctx.authour.id},'heavy metal')")

Will this work ?

#

Or not ?

silk fulcrum
limber bison
#

How can I insert then ?

#

Nvm not why question

silk fulcrum
#

because your insert VALUES into music_style, but you dont give columns

limber bison
#

It only have 3 columns

silk fulcrum
#

INSERT INTO table_name (column1, column2) VALUES (value_for_lumn1, value_for_column2)

#

that is how it works

limber bison
#

Will work ?

silk fulcrum
#

no, it's author, not authour

sick junco
#

can anybody help me? I'm trying to install chatterbot but it gives me an error when I run pip install -U chatterbot, here is the error.

ERROR: Could not build wheels for srsly, which is required to install pyproject.toml-based project```
limber bison
primal token
silk fulcrum
limber bison
primal token
#

sqlites syntax is query, (values,)

limber bison
#

F string ?

primal token
silk fulcrum
limber bison
silk fulcrum
silk fulcrum
sick junco
silk fulcrum
limber bison
sick junco
silk fulcrum
#

so %s's will be replaced with value1, 2 and 3

limber bison
#

Hmm it inc. code !

#

Let me try f strings

silk fulcrum
#

if you do fstring, some user with name yes'; DROP TABLE users; could break your sql

drifting arrow
#

Is it possible to set a thread to delete after an hour after it has been spoken in?

drifting arrow
#

Sure. Whatever works. I just want it to remove itself after someone has spoken in it, but not right away, after an hour

limber bison
silk fulcrum
unkempt canyonBOT
limber bison
#

So what ever the input it will take it as value

#

Creating it ?

#

It you r creating bot host it on you pc to understand things

#

After complet u can host

#

Ohh

#

Sory

#

Is your setup function async ?

#

πŸ€”

#

Share you code

silk fulcrum
# limber bison I don't think it will be in VALUES section ,

lemme show you, you do:

cursor.execute(f"INSERT INTO beautiful_table (guild_id, user_name, score, level) VALUES ({ctx.guild.id}, '{ctx.author.name}', score+10, level+1)")
``` and if a user has the above nick, this will hapen:
```sql
Executing query: INSERT INTO beautiful_table (guild_id, user_name, score, level) VALUES (8123059703147203, 'yes'); DROP TABLE beautiful_table;', score+10, level+1)
```SQL query is executing step by step, and when it sees `;` it counts everything after it as a new query, so first some data will be inserted and then your table will be deleted, and then code `', score+10, level+1)` will not work
#

that's why you use place holders

#

to prevent this shit from happening

#

any error?

#

what is code?

#

of your cog

#

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

hard beacon
#

So, I’m about to start this new job and they use discord and M336 as a bot to receive all of there jobs that they need to input for the day or the next day. They are always coming in and I know there is a better way to automate a bot of some sort to take the info from discord and input it into the website that they use to import all the data. I know it won’t be perfect bc sometimes you have to use brain power to decide on situations or if someone doesn’t import the job the correct way. I was just hoping someone could get me started on the right track and I would definitely pay you well. Let me know if this is in your wheelhouse and if so, hit me up!

limber bison
silk fulcrum
#

M336 πŸ’€

drifting arrow
#

aahh.
Im using the command in a thread.. What am I doing wrong? await interaction.thread(auto_archive_duration=60)?
should it be await interaction.channel.thread(auto_archive_duration=60)?

limber bison
#

Else I can user this method

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

hard beacon
#

oh snap, my bad...is there a channel in here that u can? I've been apart of this server for years now

silk fulcrum
hard beacon
#

can someone help me in general then?

drifting arrow
silk fulcrum
#

Ctrl + Z?

hard beacon
limber bison
#

@silk fulcrum sirrrr
await conn.execute(
table.insert(),
{"id":1, "value":"v1"}
)

What about this method ?

#

Same as Mongodb !!!

silk fulcrum
#

not for mysql

#

mysql only allows sql queries

limber bison
slate swan
limber bison
#

SQLAlchemy support

silk fulcrum
limber bison
slate swan
#

bro on 9 percent

primal token
silk fulcrum
primal token
#

either way it would depend on drivers lol

limber bison
#

What ?

#

await conn.execute(
table.insert(),
{"id":1, "value":"v1"}
)
This will work with SQLAlchemy right ?

silk fulcrum
#

what commands dont work?

primal token
#

Just learned CPython isnt JIT compiled only other implementations are, i hope it gets one

silk fulcrum
#

indentation just completely broke

primal token
#

looks like it were nested lol

silk fulcrum
#

bruh command inside command inside command

#

fix indentation and everything be good

#

well then do it on pc

vale wing
#

Very sus

maiden fable
#

At last people can stop using the GitHub link to install discord.py v2.0

limber bison
#

Roulette game git code ?

robust fulcrum
silk fulcrum
robust fulcrum
silk fulcrum
#

showmepls

robust fulcrum
slate swan
#

am I your embed visualizer or what

limber bison
#

Vai

robust fulcrum
#

Love day?

silk fulcrum
#

well, it's a package with speed up

limber bison
#

Uff

robust fulcrum
silk fulcrum
#

more speed ig pithink

limber bison
#

Good guess ig

vale wing
shrewd apex
vocal snow
shrewd apex
#

value is required if u are doing embed.add_field

night crater
#

you can use \u200b which is a zero width space

rugged shadow
#

I don't get why you're doing that fields thing

#

It's only one field

shrewd apex
#

"\u200b"

junior verge
#

Why does my on_guild_join not always does what it needs to do and send the message where it's supposed to send

slate swan
#
async def register(ctx):
    con = sqlite3.connect('userinfo.db')

    cur = con.cursor()
    
    cur.execute("""INSERT INTO userinfo (userid, balance)
                VALUES(ctx.message.author.id, 0)
                """)```

sqlite3 table has already created, but why my code no work?
robust fulcrum
#
    async def get_prefix(self,message):
        id = message.guild.id
        self.cursor = await self.connection.cursor()
        await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
        prefix = await self.cursor.fetchone()
        await self.connection.commit()
        return prefix or '>'

Guys i have this function to get prefix
I want that when someone mention my bot it sends the bot prefix
How to do that?

#

Yep

slate swan
#

how to fix?

slate swan
lone lichen
#

Does the message send?

silk fulcrum
#

ctx.author.id

#

wtf is ctx.message.user.id

slate swan
slate swan
silk fulcrum
#

lmao

#

!d discord.ext.commands.Context.author

unkempt canyonBOT
slate swan
#
async def register(ctx):
    con = sqlite3.connect('userinfo.db')

    cur = con.cursor()
    
    cur.execute(f"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id}, 0)")

    
    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

updated the code, but still not working :/
lone lichen
slate swan
lone lichen
silk fulcrum
#

it returns cursor

#

btw you can use con.execute

shrewd apex
#

intents enabled? u have on_message anywhere?

lone lichen
shrewd apex
#

!d sqlite3.connect

unkempt canyonBOT
#

sqlite3.connect(database, timeout=5.0, detect_types=0, isolation_level='DEFERRED', check_same_thread=True, factory=sqlite3.Connection, cached_statements=128, uri=False)```
Open a connection to an SQLite database.
shrewd apex
#

and get urself an error handler

slate swan
#

so how do i fix it?

lone lichen
slate swan
#

so it isnt the problem

lone lichen
slate swan
#

alr

leaden cosmos
#

hello

lone lichen
slate swan
lone lichen
leaden cosmos
lone lichen
leaden cosmos
#

i'm a starter

slate swan
#
async def register(ctx):
    con = sqlite3.connect('userinfo.db')

    cur = con.cursor()
    
    cur.execute(f"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id},0)")

    con.commit()
    cur.close()

    
    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

still no work
lone lichen
leaden cosmos
lone lichen
leaden cosmos
slate swan
#
@bot.command(name="register")
async def register(ctx):
    print("Connecting...")
    con = sqlite3.connect('userinfo.db')

    cur = con.cursor()
    
    cur.execute(f"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id},0)")

    con.commit()
    cur.close()

    
    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

it did print connecting... but database still not work
lone lichen
leaden cosmos
lone lichen
#

!resource python

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.

lone lichen
#

Ty πŸ˜‚

lone lichen
leaden cosmos
lone lichen
leaden cosmos
lone lichen
leaden cosmos
#

just some small codes

lone lichen
lone lichen
leaden cosmos
lone lichen
leaden cosmos
lone lichen
#

Okay

slate swan
#

it stopped working starting from this command
con = sqlite3.connect('userinfo.db')

#

@lone lichen

lone lichen
#

!d sqlite3.connect

unkempt canyonBOT
#

sqlite3.connect(database, timeout=5.0, detect_types=0, isolation_level='DEFERRED', check_same_thread=True, factory=sqlite3.Connection, cached_statements=128, uri=False)```
Open a connection to an SQLite database.
slate swan
#

?

lone lichen
slate swan
#

ok

lone lichen
#

And u dont get an exception?

slate swan
#

no

lone lichen
slate swan
#

ok

#

it still doesnt work @lone lichen

#
async def register(ctx):
    print("Connecting...")
    db = sqlite3.connect('/Users/bai/Documents/Personal Things/PythonDiscord/UserInfo/userinfo.db')
    cur = con.cursor()
    cur.execute(f"INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id},0)")
    con.commit()
    cur.close()

    
    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```
lone lichen
#

And see if it inserts into db

lone lichen
slate swan
#

ok

lone lichen
#

Leave everything here as it is

#

Just copy paste that part

slate swan
#

nope it didnt work

lone lichen
slate swan
#

...

vocal snow
#

maybe it wasn't feeling well

lone lichen
lone lichen
slate swan
#
async def register(ctx):
    db = sqlite3.connect("userinfo.db")
    
    cur = con.cursor()

    await cur.execute(
        "INSERT INTO userinfo (userid, balance) VALUES({ctx.author.id},0)",
        (
            ctx.author.id
        ),
    )
    con.commit()
    cur.close()
    
    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

i changed the code, but still no work! :/
glad thicket
unkempt canyonBOT
vale wing
#

Gg

#

Ima learn it prob

#

Although I prefer disnake shortcuts

vale wing
lone lichen
vale wing
#

Yeah

lone lichen
#

I usually just use an orm

slate swan
#
async def register(ctx):
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()
    cursor.execute(f"INSERT INTO userinfo (userid, balance) VALUES ({ctx.author.id}, {0})")
    db.commit()
    cursor.close()
    
    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

How to get this thing working? database was already created but it just cant connect or insert?? this already wasted so much of my time :/
shrewd apex
#

is the table created pithink

slate swan
ionic edge
#
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Unclosed connector```
#

i am getting this error

maiden fable
#

Probably the wrong bot application?

ionic edge
#

naah its the same

maiden fable
#

Other than that, there's no explanation for that error

maiden fable
#

(According to me)

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.

bitter island
#

Traceback (most recent call last):
File "main.py", line 7, in <module>
bot = commands.Bot(command_prefix='$')
TypeError: init() missing 1 required keyword-only argument: 'intents
i need help

maiden fable
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

honest quartz
#

!e

mport random
import string

def keygen(length): #function
    output = "".join((random.choice(string.ascii_letters + string.digits)) for x in range(length))
    print("your key: ", output)
    
keygen(20)
unkempt canyonBOT
#

@honest quartz :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     mport random
003 |           ^^^^^^
004 | SyntaxError: invalid syntax
honest quartz
#

sorry couldnt find bot commands

slate swan
#
async def register(ctx):
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()
    await cursor.execute(
        "INSERT INTO userinfo (userid, balance) VALUES (?, 0)",
        (ctx.author.id),
    )
    db.commit()
    cursor.close()
    
    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

is it like this? not working
silk fulcrum
#

its not aiosqlite to await

slate swan
#

ok fixed

#
async def register(ctx):
    db = sqlite3.connect("userinfo.db")
    cursor = db.cursor()
    cursor.execute(
        "INSERT INTO userinfo (userid, balance) VALUES (?, 0)",
        (ctx.author.id),
    )
    db.commit()
    cursor.close()
    
    em=discord.Embed(title=f"You've successfully registered!", description=f"Now you can use currency commands :)")
    await ctx.send(embed=em)```

is it like this? not working
#

still not work

shrewd apex
#

send ur whole code

#

!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
shrewd apex
#

thats ur whole code πŸ—Ώ

#

so u just have that one function in the file u are running? pithink

flat swallow
#

How do I convert if ladder code to ctx code?

flat swallow
shrewd apex
flat swallow
#

to smth like this:

silk fulcrum
#

hybrid**_**command

shrewd apex
# flat swallow

these aren't even commands just some random message on sending some stuff

flat swallow
#

But these are the only things working

#

the rest isnt

shrewd apex
#

better do that in on_message only when u have decent command make a command function

flat swallow
#

But the actual commands aren't working

shrewd apex
shrewd apex
#

in on_message

flat swallow
flat swallow
#

What does that do

shrewd apex
#

that the reason why

shrewd apex
flat swallow
#

Where should process_commands be

shrewd apex
#

last line of on_message

#

no one gonna comb thru ur ss and find out where error is there u have debug all this by urself

flat swallow
#

its so small my glasses cant read bro

primal token
#

string concatenation πŸ˜”

flat swallow
shrewd apex
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.

flat swallow
#

do u have the intents and perms?

#

how do u run all this without any imports...?

primal token
flat swallow
#

ok

#

Why am I stuck here now

#

Honestly, I don't know enough about Discord.py to help you :(

#

Most I can do is say try the documentation πŸ˜…

#

Also can someone explain how to use aiohttp

vale wing
#

Just check their docs

vale wing
shrewd apex
flat swallow
vale wing
#

Use @bot.listen() instead of @bot.event

flat swallow
#

bro what is that intents for

#

why is it giving that error

vale wing
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

flat swallow
#

how

#

thnx

vale wing
#

Pass does nothing it can't cause any exceptions

flat swallow
#

I didn't make that part

#

tbh I just blindly copied from google that part

#

its so that the bot doesn't run multiple instances apparently

vale wing
#

🧐

flat swallow
#

very dumb on my part i know

vale wing
#

How does try: pass help with that lmoa

flat swallow
#

idek

#

but if i remove it

vale wing
#

Literally nothing will change

flat swallow
#

it throws an error which is annoying so i dont disturb it much

vale wing
#

Probably runtime error and you definitely don't handle it like this

flat swallow
#

oh

#

it worked so i was happy but is there a better way

vale wing
#

I honestly never had a need to handle it because I do graceful shutdowns

#

It often occurs because of bad shutdown

flat swallow
vale wing
#

Cringe

flat swallow
#

ye

#

I hate python

#

Why aren't my commands working

vale wing
#

I hate replit

#

That's why your commands aren't working

flat swallow
#

There isn't even an error 😭

vale wing
#

Jk

flat swallow
#

lmao

#

!pastecommands

#

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

vale wing
#

How do you make commands anyway

#

@bot.command or everything in the event

flat swallow
#

enjoy this mess

flat swallow
#

I originally used everything in event

#

but now i am using bot.command

#

but since i switch to bot.command, it hasnt been working

vale wing
#

Have you tried changing @bot.event to @bot.listen()

valid hatch
#

I have a question. Now that discord.py 2.0 has been released, which one do you recomment for slash command bots:
discord.py ou discord-interactions?

vale wing
#

discord-interactions was created to add support for interactions to dpy because it didn't have them, now it does so why not use the main lib

flat swallow
#

Nope

ionic edge
#
  client.load_extension(f'cogs.{filename[:-3]}')```
flat swallow
#

still nothing
code it DEAD

ionic edge
#

i am new tod discord2.0

ionic edge
# flat swallow send code
intent = discord.Intents.all()
client = commands.Bot(command_prefix=commands.when_mentioned_or('$'),
                      intents=intent)
client.remove_command('help')      

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            client.load_extension(f'cogs.{filename[:-3]}')

asyncio.run(load())```
flat swallow
#

wtf is commands.when_mentioned_or

#

why don't u directly make it a string

#

command_prefix='$'

ionic edge
sage otter
ionic edge
flat swallow
#

it should be await

#

ye like he said

sage otter
flat swallow
#

:o

ionic edge
#

new error

flat swallow
#

Is it a string value?

flat swallow
ionic edge
flat swallow
#

My code still dead :/

jovial spear
#
discord.ext.commands.errors.CommandNotFound: Command "test" is not found```


Can someone explain why this happens? Code seems to be perfect πŸ˜•
sage otter
sage otter
jovial spear
#

yep

#

on_ready works

flat swallow
#

Can anyone help me with my code

ionic edge
#
iscord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ping' raised an error: TypeError: object NoneType can't be used in 'await' expression```
ionic edge
#

uff

robust fulcrum
#
    async def get_prefix(self,message):
        id = message.guild.id
        self.cursor = await self.connection.cursor()
        await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
        prefix = await self.cursor.fetchone()
        await self.connection.commit()
        return prefix or '>'

Guys i have this function to get prefix
I want that when someone mention my bot it sends the bot prefix
How to do that?

mossy jacinth
#

hi i want to send the answers the user put into a modal to be sent into a channel but i get this?

pale turtle
robust fulcrum
ionic edge
pale turtle
#

Don't start with a fetch, try to get the channel from the bot's cache

ionic edge
robust fulcrum
robust fulcrum
#

That's event

pale turtle
#

Do message.channel.send ig

potent spear
#

also, on_message only takes a message arg

robust fulcrum
slate swan
#

How can I disable select menu after it's been used?

robust fulcrum
#

Guys why i am getting this error?

mossy jacinth
#

already got it πŸ’€ forgot to add () after view=back

glad cradle
#

what are the best databases to use for a Discord Bot? (ex MySQL, SQLite etc)

night crater
#

Sqlite for small bots, postgres for bigger bots tends to be what alot of people use

lone lichen
lone lichen
lone lichen
shrewd apex
#

why use sqlite ain't that sync

robust fulcrum
shrewd apex
#

atleast use aiosqlite

robust fulcrum
#

Me?

lone lichen
lone lichen
shrewd apex
robust fulcrum
robust fulcrum
shrewd apex
#

u are prolly using something which uses asyncio.run

lone lichen
robust fulcrum
#

I never used asyncio.run in my life

shrewd apex
#

do as enslo says then

glad cradle
robust fulcrum
lone lichen
#

as long as its free

lone lichen
#

this may be helpful for future

robust fulcrum
#

Or 8080?

shrewd apex
robust fulcrum
#

Do it work same as 8080?

shrewd apex
#

it's just a numberpithink

#

pick one

lone lichen
lone lichen
#

also show whats inside of events cog as Asher said

glad cradle
robust fulcrum
lone lichen
robust fulcrum
lone lichen
robust fulcrum
#

Ok

robust fulcrum
# lone lichen show code for flask app and events cog
from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def home():
    return "I'm alive"

def run():
  app.run(host='0.0.0.0',port=2056)



def keep_alive():
    t = Thread(target=run)
    t.start()
#

😒

lone lichen
#

press ctrl+shift+s and put in kill 1

#

also send code of events cog

sick birch
#

Looks like discord.py v2.0 is officially out, can someone confirm?

glad cradle
#

finally pip install shit

sick birch
#

Awesome. Now I won’t have to tell people how to manually install 2.0 lol

glad cradle
glad cradle
#

just use the port 8080

lone lichen
cerulean shale
#

yo, i recently changed to dpy2.0 and since then my bot is coming online but it aint taking any commands

#

pls help ;-;

#

it is not even giving any errors

glad cradle
#

it is usually not occupied

lone lichen
cerulean shale
#

ight ;-;

cerulean shale
glad cradle
#

yes

lone lichen
lone lichen
cerulean shale
#

thats it right? is it worth it tho?

glad cradle
#

Read the new added things #381965829857738772 message

also discord have implemented breaking changes, if you'll not migrate to a recent version of the library your Bot could broke

cerulean shale
#

oh

cerulean shale
glad cradle
cerulean shale
#

oh

slate swan
#

I don't think "interactions" sum up all of the features

lone lichen
glad cradle
#

there are 800 changes and 1700 commits

#

😐

cerulean shale
#

yo completely new to cogs. Pls tell me the mistakes I have in this cog ;-;

unkempt canyonBOT
#

Hey @cerulean shale!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

cerulean shale
#

pls help ;-;

glad cradle
#

it's self.bot to use the bot object, not bot

cerulean shale
glad cradle
#

also don't make Api call inside on_ready event

glad cradle
cerulean shale
#

oooooooooooh

glad cradle
#

!d discord.on_ready also

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
glad cradle
#

Read the warning

cerulean shale
#

ight

#

so in here instead of just bot.change_presence, i should use self.bot.change_presence?

cerulean shale
glad cradle
#

Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.

Instead set the activity and status kwargs in the constructor of these Classes.

bot = commands.Bot(command_prefix="!", activity=..., status=...)

As noted in the docs, on_ready is also triggered multiple times, not just once.

Basically: don't πŸ‘ do πŸ‘ shit πŸ‘ in πŸ‘ on_ready.

cerulean shale
#

cant i just define self.bot=bot tho?

glad cradle
digital forge
#

how to ping the message to which you are replying??

glad cradle
slate swan
unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

glad cradle
#

!resources

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.

digital forge
robust fulcrum
slate swan
robust fulcrum
#

Wait wat

#

I just did
from main import get_prefiz
And i got a port error
How is this connected?

glad cradle
robust fulcrum
#

@lone lichen when i removed from main import get_prefix my code started working and i not got port error
Do you know why was i getting it?

digital forge
#

im extremely dumb , please forgive my low iq , what i was searching for was message.reply()

glad cradle
#

ok

worn onyx
#

could anyone plz help me?

glad cradle
slate swan
slate swan
#

that emojis gives me the creeps, jeez

glad cradle
worn onyx
#

any solution?

vocal snow
#

replit moment

glad cradle
#

I mean the shell not the console

worn onyx
glad cradle
#

do cntrl + shift + r

#

if this does not work delete your repl and create a new one

lone lichen
#

so if you have keep_alive() in there outside if __name__ == '__main__', it will get executed when u run the main file and when u import it, meaning, you will have 2 flask servers running on the same port

glad cradle
#

__name__

lone lichen
shrewd apex
# vocal snow replit moment

just reminded me all those old 1.7.3 users on replit replit gonna update them all to 2.0 and then bot gonna crash for thempithink

#

poetry auto update πŸ™

glad cradle
#

ahah

vocal snow
#

Lmaoo going to be fun

glad cradle
#

not really fun

glad cradle
lone lichen
# vocal snow replit moment

replit has many great features like shared ip, underpowered machines, shit code editor and more random issues

vocal snow
#

As if they will read it

lone lichen
robust fulcrum
robust fulcrum
#
    async def get_prefix(self,message):
        id = message.guild.id
        self.cursor = await self.connection.cursor()
        await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
        prefix = await self.cursor.fetchone()
        await self.connection.commit()
        return prefix or '>'

Guys i have this func in my bot class
How can I use it in cogs?

lone lichen
# vocal snow πŸ˜‚ πŸ’€

and if you have a friend, you can take advantage of their collaboration feature and constantly delete each others code while trying to code at the same time

robust fulcrum
#

Lol

vocal snow
robust fulcrum
#

I not able to understand what you mean

vocal snow
#

it's a yes or no question

#

do you have access to a bot object

robust fulcrum
#

Ye

#

this self.bot = bot?

vocal snow
#

ok, so just use bot.get_prefix then

robust fulcrum
vocal snow
#

you need to give more details

robust fulcrum
vocal snow
#

error is pretty self explanatory

robust fulcrum
#

Oh me dumb

#

How would I add a other datatype to str lmao

vocal snow
#

read the whole error

#

carefully

#

from the very start

robust fulcrum
vocal snow
#

what error

robust fulcrum
vocal snow
#

ok, you read the first sentence of it?

robust fulcrum
#

It says not awaited

robust fulcrum
vocal snow
#

I think you can figure this out without help

robust fulcrum
#

Hmmm?

robust fulcrum
#

Thanks for help tho

slate swan
#

is there a way to disable select menu after its been used?

#
            for item in self.children:
                if isinstance(item, discord.ui.Select):
                    item.disabled=True
            await interaction.message.edit(view=self)``` i have this code right here but i get error that `self` doesnt have attribute `children`
#

since self is in my parameters

vocal snow
#

what is self here

#

ui.View obj?

slate swan
#

discord.ui.Select class

#

why ? @vocal snow

vocal snow
unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.

This is usually represented as a drop down menu.

In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Select.values "discord.ui.Select.values").

New in version 2.0.
vocal snow
#

it doesn't have a children attribute

#

which makes sense because children is supposed to be the components of a View

#

you can use self.view.children there

cold sonnet
vocal snow
#

what?

cold sonnet
#

set self.disabled to True

vocal snow
#

self.view.children would be all components of the view

#

not just the select menu

slate swan
#

i want to be disabled after its been used

cold sonnet
#

probabilities that the View only has the select menu are high, but not sure so sorry
he checks with an if if the children is a selectmenu

slate swan
#

the code i sent is working for buttons but i try to convert it for select menu

cold sonnet
#

so he's looking for self

vocal snow
#

go to the doc

#

check it's attributes

vocal snow
slate swan
#

but i want to disable only the select menu πŸ˜‚

cold sonnet
#

I don't know, it's got nothing to do with the question either

vocal snow
slate swan
#

cause i didnt know that ui.Select hadn't attribute children

vocal snow
#

that makes no sense at all but ok

slate swan
#

nvm

cold sonnet
#

so if you wanna disable the select menu that was clicked you do
self.disabled = True

#

and edit the message

#

if you wanna disable something else this advice is useless

slate swan
#

so await interaction.response.edit_message(view=self)

#

or await interaction.message.edit(view=self)

vocal snow
#

Maybe the deleted message has no content

golden tapir
#

i am following a tutorial on slash commands they tell me to install this and i do it then they tell me to import slash commands i do all of that but i get error saying discord_slash does not exist

#

idk what i am missing

sick birch
cloud dawn
#
    @command(name="mute", description="Mute a certain member.")
    @describe(
        member="The member that is going to be muted.",
        length="Amount of time to mute the member.",
        unit="Unit of time.",
        reason="Why this member is getting muted."
    )
    @choices(unit=[
        Choice(name="Days", value=86400),
        Choice(name="Hours", value=3600),
        Choice(name="Minutes", value=60),
        Choice(name="Seconds", value=1)
    ])
    async def moderation_mute(
            self, interaction: Interaction,
            member: Member,
            length: Range[int, 1, 2419200],
            unit: Choice[int],
            reason: str = "No reason specified"
    ) -> None:
        second_amount = sec if (sec := length*unit.value) < 2419200 else 2419200
        dt = datetime.now().astimezone() + timedelta(seconds=second_amount)

        await member.timeout(dt, reason=reason)
        await interaction.response.send_message(
            f":ok_hand: Muted {member.mention} for `{reason}` until <t:{int(dt.timestamp())}:F>"
        )
``` any ideas of improvement.
#

And yes the length/unit time is on purpose.

final walrus
#

Would you guys use a database to store data such as user info, or user stats specifically for your bot.. Like let's say your bot gives each user a balance, would you guys store that in a database?

cloud dawn
final walrus
#

oroight

ionic edge
#
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'url'
cold sonnet
ionic edge
#

@client.command()
async def jod(ctx):
    await ctx.message.delete()
    res = requests.get(link).json()
    em = discord.Embed()
    em.set_image(url=res["url"])
    await ctx.send(embed=em)```
cold sonnet
#

res has no url key

ionic edge
#

i am new to discord 2.0

golden tapir
cold sonnet
#

print(res)
I suggest seeing what it is

#

and switching to aiohttp

#

but it doesn't matter rn

ionic edge
#

{'msg': '404'}

#

@cold sonnet

cold sonnet
#

uh that's not much

ionic edge
cold sonnet
ionic edge
#

@cold sonnet

#

can u help me with the slash commands

#
import discord
from discord.ext import commands
from discord import app_commands
import interactions

class ping(commands.Cog):
    def __init__(self, client : commands.Bot):    
        self.client = client
        

    @app_commands.command(name='test' , description='Pong!')
    async def test(self , ctx: interactions.CommandContext):
        await ctx.send('Pong!')


async def setup(client):
    await client.add_cog(ping(client))
cold sonnet
#

you're doing too much in on_ready

ionic edge
cold sonnet
#

you made a global slash command and didn't copy it to a guild

#

that'll take much time to sync

#

an hour or more

ionic edge
#

what can i do then?

cold sonnet
#

oh you didn't sync at all

ionic edge
#

what is the use of

cold sonnet
#

read the gist I sent

ionic edge
#

setup.hook??

cold sonnet
#

only called once

#

unlike on ready

ionic edge
#

i didnt setup that

#

@cold sonnet CAN U HELP ME WITH A TEMPELATE FILE

#

with cogs

cold sonnet
#

what's that

lone lichen
#

i just made this πŸ˜‚

[await channel.delete() for channel in [ctx.guild.get_channel(channel_id) for channel_id in [order.channel_id for order in await self.bot.orders_dao.get_all()]]]
maiden fable
#

Nice, but uh

#

Nice

vale wing
#

Wut is orders_dao

#

Custom attr or smth

elder storm
#

Hey Guys I need help

silk fulcrum
#

just send problem

sick birch
#

Reset your token

elder storm
#

idk y line 6 has an error

silk fulcrum
#

2.0 is now on PyPI so everyone will have problems with that

sick birch
#

MTAw0TgOOTc1Nzc4NDYwODc50A.G2j0II.ltp21k-NZbHHiRT44E4Poosolt3493rjOvW4Og

#

should invalidate it

lone lichen
sick birch
#

Anyway, intents are required in 2.0

elder storm
lone lichen
silk fulcrum
lone lichen
vale wing
silk fulcrum
#

@elder storm reset your token please

sick birch
#

idk blame the OCR

lone lichen
silk fulcrum
#

you should not reveal it here

vale wing
#

What's that

silk fulcrum
#

it can be used in bad way

lone lichen
elder storm
sick birch
#

I'm just trying to get discord to force reset it

elder storm
vale wing
#

Understandable

silk fulcrum
vale wing
#

I am android user since my very first phone so idk about iphones

lone lichen
sick birch
lone lichen
silk fulcrum
#

@unkempt canyon does it, no?

sick birch
#

Β―_(ツ)_/Β―

#

Also as for the OCR, I'm doing it on my macbook

slate swan
#

πŸ—Ώ2.0 is out on pypi hmm

sick birch
#

I can open it in the preview app and highlight and select and open links and whatnot from images

silk fulcrum
slate swan
#

would be funny watching people getting missing kwargs error for intents

sick birch
slate swan
silk fulcrum
#

right now

ionic edge
shrewd apex
#

how to raise a custom exception using the error handling event

silk fulcrum
shrewd apex
#

i did that in my code but it's only being caught locally with a try except when i am adding isinstance in error handler it's not being raised

quaint epoch
shrewd apex
#

yeah that's not working

quaint epoch
#

it has to inherit from another exception

shrewd apex
#

if i use try except i can print it i can see but the error handler is not raising it

maiden fable
#

What are you subclassing?

shrewd apex
slate swan
#

it should be an instance, not the class

maiden fable
#

Ah yes

shrewd apex
#
class InvalidFlag(Exception):
    pass
raise InvalidFlag(message)
# in error handler
elif isinstance (error, InvalidFlag):
   ...
slate swan
#

is that error raised inside a command?

shrewd apex
#

no

maiden fable
#

Then how tf do u expect the handler to catch it 😐

shrewd apex
#

in another function for a custom convertor

maiden fable
#

The error handler only catches errors while invoking a command

shrewd apex
#

it's in a custom convertor tho the ones which u typehint

#

hmm ok i see

maiden fable
#

So u have subclassed ext.Converter?

#

(I forgot the exact class name)

shrewd apex
#

commands.Convertor

#

but yes i did

sick birch
#

Can converters return a type other than themselves? How would that work with typehinting 🀨

sick birch
#

What type should a custom converter return?

shrewd apex
#

u can create custom convertor like discord.py does when u typehint with discord.Member

shrewd apex
#

depending on a few cases

sick birch
#

Seems cursed

shrewd apex
slate swan
#

the typehint stuff actually works this way ->

async def foo(ctx, arg: Converter):
   ...
``` `Converter` here needs to be an instance of commands.Converter with a `convert` method which returns the result, the raw argument is passed in the convert method...
sick birch
#

Yeah I can’t imagine that playing well with typecheckers

brazen raft
#

Actually, is it a class method or a static method

sick birch
shrewd apex
#

but not the elif πŸ˜”

elder storm
#

Guys help plz

M tryna make a Discord bot tht replies back but this bot isnt responding in my server even tho its online

slate swan
silk fulcrum
#

i dont think you've really hidden the token but ok whatever

elder storm
silk fulcrum
slate swan
#

check it using pip show discord.py , if its 2.0 add message_content intents

silk fulcrum
#

@elder storm i thought you did discord.Intents.all() as i told you but ok sure

elder storm
slate swan
#

you can do something like ```py
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

silk fulcrum
#

what error

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

read the dev portal part

elder storm
silk fulcrum
#

bruh

slate swan
#

weird though, message_content is not a previlaged intent yet

silk fulcrum
#

vilaged

silk fulcrum
#

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

slate swan
silk fulcrum
#

what is this and how do I fix it? (did python3.10 -m pip install -U discord.py[speed])

torn sail
unkempt canyonBOT
#

setup.py line 48

'cchardet==2.1.7; python_version < "3.10"',```
slate swan
#

because you have 3.10

silk fulcrum
#

sed

slate swan
torn sail
#

yeah will come in 2.0.1

slate swan
#

well then they can use the github version

silk fulcrum
#

its 2.1 in github btw lmao

#

if not changed yet

slate swan
#
$ git clone https://github.com/Rapptz/discord.py
$ cd discord.py
$ python3 -m pip install -U .[speed]
#

can use this

silk fulcrum
#

how do I implement this into requirements.txt?

slate swan
#

dk if the speed version can be installed with pip directly or not

torn sail
silk fulcrum
#

i have to downgrade my python version?

torn sail
#

no it means only install if py version < 3.10

unkempt canyonBOT
#

setup.py line 48

'cchardet==2.1.7; python_version < "3.10"',```
silk fulcrum
#

okay, I guess I'll just wait until cchardet is supported in 3.10

shrewd apex
#

what u need chardet for?pithink

#

!pypi chardet

unkempt canyonBOT
silk fulcrum
#

discord.py[speed]

slate swan
#

just install the speed version dependencies conditionally instead of installation discord.py[speed]

shrewd apex
#

!pypi cchardet

unkempt canyonBOT
shrewd apex
#

hmm written in c

slate swan
#

if you really want some speed boost and you're on a Unix bases system you can use uvloop

#

it replaces the default asyncio event loop and provides better performance

#

!pip uvloop

unkempt canyonBOT
shrewd apex
#

just use third party compilers to compile the code before then runpithink

slate swan
#

that needs strict type checking, else it will be of no use

shrewd apex
#

tru

shrewd apex