#discord-bots

1 messages · Page 178 of 1

vocal snow
#

yes you do, in the list comp

manic knoll
vocal snow
#

ctrl+f is a great tool

manic knoll
manic knoll
# vocal snow

thanks so much it worked. But the only problem i have left is i have “role: discord.Role” and when i use it the bot doesn’t give the role to the members and it has permission

vocal snow
#

role: discord.Role just converts the argument to a discord.Role instance

#

it doesn't give anyone any roles

manic knoll
#

ohhh

vocal snow
#

!d discord.Member.add_roles

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 [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
vocal snow
#

you can add roles with this method

#

you have member which is an instance of discord.Member, so you can use member.add_roles

manic knoll
#

ok so where would that code go into the coding ```@client.tree.command(name="sign", description="Where athletic directors & head coaches sign players")
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role) -> None:
msg = f"{member.mention} has been signed by {interaction.user.mention}!"

if 854573259030921256 not in [role.id for role in member.roles]:
    msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
    msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
    msg = f"Hey {member.mention}! You cannot sign yourself."

await interaction.response.send_message(msg)```
#

didnt mean to ping robin

#

so would i do

vocal snow
#

where you want to add the role

manic knoll
#

“role: discord.Role, discord.Member.Add_Roles”

#

or something else

#

@vocal snow

vocal snow
#

just call the method wherever you want to add the roles

manic knoll
#

hmm. So the best place to do that would be after the argument right?

vocal snow
#

it has to be after the argument otherwise you wouldn't know which role to add

manic knoll
#

ok so that part is what im stuck on

#

so would i just do discord.Member.Add_roles?

#

@vocal snow

manic knoll
#

ohhh

#

async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role, member.add_roles ) -> None:

#

thats the whole line

#

@vocal snow

vocal snow
#

what

#

why is that in the function siugnature

manic knoll
#

im so confused on where it should be right now

vocal snow
#

id recommend looking at how to use functions in python

manic knoll
#

yep

#

im still stuck but i just noticed it shouldnt be in the same line as the other code

vocal snow
#

i mean you put it where you want to actually add the roles

#

do you want to add them as soon as the command is called

#

or after you do all the checks with the if statements

manic knoll
manic knoll
vocal snow
#

so then just use an else statement and do it there

manic knoll
vocal snow
#

you know how if statements work right

manic knoll
#

a little

#

but im gonna need a lot of help with it

vocal snow
#

Learning a bit more python before making a discord bot would be good

manic knoll
#

true

#

but this is the only problem im having so far

slate swan
manic knoll
#

okay

#

so uh im going to need help on the if statement though

slate swan
#

Im not sure what the context is so I might be wrong

slate swan
manic knoll
#

so this is about a argument in a tree command where the author runs a command to role someone but right now i guess i didnt add a if statement thats why the bot isnt roling the member

#

@slate swan

slate swan
#

Where’s the command code

manic knoll
#
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role) -> None:
    msg = f"{member.mention} has been signed by {interaction.user.mention}!"

    if 854573259030921256 not in [role.id for role in interaction.user.roles]:
        msg = f"Sorry, but you don't have the head coach role to perform this command."
    elif member.bot:
        msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
    elif interaction.user.id == member.id:
        msg = f"Hey {member.mention}! You cannot sign yourself."```
slate swan
#

So what do you want to do ?

manic knoll
#

make the bot role the person after the argument in the command

#

@slate swan

slate swan
#

Okay, what’s it doing now

manic knoll
#

nothing

slate swan
#

Is it not giving them the role

manic knoll
#

yep

slate swan
#

Or sending any messages

manic knoll
#

its sending messages and doing everything fine just not giving the person the role

slate swan
manic knoll
#

i know thats the thing im stuck on

#

here let me show you

manic knoll
#

im guessing i just need a code to actually make the bot able to make the role

slate swan
#

memberobject.add_role(role)

manic knoll
#

the thing is where in the code tho

slate swan
#

So it should be member.add_role(role)

manic knoll
#
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role) -> None:
    msg = f"{member.mention} has been signed by {interaction.user.mention}!"

    if 854573259030921256 not in [role.id for role in interaction.user.roles]:
        msg = f"Sorry, but you don't have the head coach role to perform this command."
    elif member.bot:
        msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
    elif interaction.user.id == member.id:
        msg = f"Hey {member.mention}! You cannot sign yourself."```
slate swan
#

Well In what clauses do you want it to add the roles

manic knoll
slate swan
#

So you need to move that first msg variable into an if statement or else it’ll just be sending that no matter what

manic knoll
slate swan
#

What code are you using to send the message

manic knoll
#

for which one the sucessful one

#

msg = f"{member.mention} has been signed by {interaction.user.mention}!"

slate swan
#

I don’t really get what the problem is here

manic knoll
#

the bot isnt rolling the person that has been signed

slate swan
#

So move the add role and response inside one of the conditions

manic knoll
naive briar
slate swan
#

!e ```py
msg = 1
if "a"=="a":
msg = 2
print(msg)

unkempt canyonBOT
#

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

2
manic knoll
#

sigh

#

im just gonna gts

slate swan
#

how do i make a role be able to see the channel aswell

#

read_messages is "see channel"

slate swan
cloud dawn
slate swan
#

I always use ow

cloud dawn
slate swan
#

!e

unkempt canyonBOT
#
Missing required argument

code

slate swan
cloud dawn
lapis light
#

yo
Hey , is it possible to code an python bot as selfbot for an user in discord?

cloud dawn
#

That's not allowed.

lapis light
#

ETC , I want to code an selfbot to search all of members in all of servers my user is , and then , if example word was in any of members bio , take that member id

lapis light
cloud dawn
lapis light
#

thanks 🌹

upbeat otter
#

but it's gonna be complicated af pepe_exit

cloud dawn
#

And besides don't suggest loopholes.

upbeat otter
#

lmao fine

shrewd apex
# upbeat otter ,

pretty sure reply triggers ping and is visible in notifications so no use editing

shrewd apex
#

idk just saying

cloud dawn
#

If you get a message on phone but the person removed the message you can still read it even.

shrewd apex
#

pc too if u enabled notifs atleast on my windows idk others

cunning moss
#

I'm not sure if I should ask this here or in the get help channel, but how do I make it so that I can see which commands a certain user performed in the console?
this is wht i have currently
print(f"> {interaction.user} used the command.") -

is {interaction.command} an actual command tht i can use?

unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.

New in version 2.0.
cloud dawn
#

interaction.command is optional remember that. Pushing buttons sending models etc are also valid interactions.

cunning moss
#

tysm

naive briar
#

Imagine

shrewd apex
#

rip

#

disnake better handles the interactions

slate swan
#

I'd just use the tree's check

shrewd apex
#

tru

upbeat otter
shrewd apex
cloud dawn
#

discord.js 4377_peepoSantaHappy

slate swan
#

ew

sick birch
#

W crate

umbral mesa
#

How do I send a message in a Pacific channel with a discord bot

manic knoll
#

yes

cloud dawn
shell wing
#

Does anyone have a example for sticky message ? (message stays at the end of the channel and old msg gets deleted)

slate swan
#
sticky_msg_mapping: dict[int, discord.Message] = {}

@listen()
async def on_message(message: discord.Message) -> None:
    if (msg:=sticky_msg_mapping.get(message.channel.id)):
        await msg.delete()
    new_msg = await message.channel.send("sticky message")
    sticky_msg_mapping[message.channel.id] = new_msg
``` this should be pretty much it but you'll be better off using a database instead of the dictionary
cloud dawn
#

May ratelimit rest in peace.

slate swan
#

could implement a on_message cooldown

#

!tag custom-cooldown

unkempt canyonBOT
#

Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

cloud dawn
manic knoll
#

ok so i have this problem my bot isn’t rolling the member after we use the role member argument command

cloud dawn
#

"rolling the member"?

manic knoll
#

here let me

#

ok so you see the role part? that part is meant for the head coach to role who the member the picked on “member”

#

@cloud dawn

cloud dawn
#

So assign roles to users?

manic knoll
#

yea

manic knoll
#

its the same one

cloud dawn
#

Well the role typehint works right?

manic knoll
#

yep

#
async def sign(interaction: discord.Interaction, member: discord.Member, team: discord.Role) -> None:
    msg = f"{member.mention} has been signed by {interaction.user.mention}!"

    if 854573259030921256 not in [role.id for role in interaction.user.roles]:
        msg = f"Sorry, but you don't have the head coach role to perform this command."
    elif member.bot:
        msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
    elif interaction.user.id == member.id:
        msg = f"Hey {member.mention}! You cannot sign yourself."
    

    
    await interaction.response.send_message(msg)```
#

@cloud dawn

cloud dawn
#

What have you tried so far?

manic knoll
#

discord.Member.Add_roles

#

but idk where to put it in the coding

cloud dawn
#

!d discord.Member.add_roles

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 [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
cloud dawn
#

Assigned to a member.

manic knoll
#

so basically with the await?

#

@cloud dawn

cloud dawn
#

Yes and you need some checks.

#

Like a member cannot add a role equal or higher than the highest role he/she has. And same goes for the bot. If the bot's role that it's going to give is equal or higher it cannot be assigned.

manic knoll
#

yes

#

thats very smart

#

wait is it possible to make it so specific roles show up in the argument

cloud dawn
#

You could with choices.

manic knoll
#

bet could you please help with the code

cloud dawn
#

Erm.

#

I like to help but I don't want to provide you the code. I know I can do it, but if I will just do it for you; then you won't learn how to do research.

shrewd apex
manic knoll
cloud dawn
#

Besides that the docs also has some small examples. And anyone here is more than willing to explain how to use a certain function in a context.

manic knoll
#

ok so would it just be "await discord.Member.Add_roles"?

cloud dawn
#

You are using the derived method.

shrewd apex
#

await inter.user.add_roles

upbeat otter
shrewd apex
#

also add a guild only command check

manic knoll
cloud dawn
#

discord.Member.add_roles is the full path of the method you are going to use. But this class needs context, it has to exists. Therefore we look at what interaction passes if we want to give a role to the author, we can also create a Member object by fetching or getting it.

shrewd apex
#

yeah

cloud dawn
#

Avarage Disnake coder :p

upbeat otter
#

lmao

manic knoll
upbeat otter
#

hikari-lightbulb pepeShy

manic knoll
#

this is what i have rn

cloud dawn
#

add_roles is a function.

manic knoll
cloud dawn
#

Well you have to call it.

manic knoll
#

"add_roles(role)"

#

right?

#

await interaction.user.add_roles(roles=)

cloud dawn
#

Debug it.

#

Test it out, play around.

manic knoll
#

but wouldnt the "roles=" need a certain role after that

cloud dawn
#

Is roles an argument or a keyword-argument?

mental hollow
#

I’m currently using mongodb for my bot & I’m considering changing to asyncpg, are there any benefits to changing?

manic knoll
#

@cloud dawn

cloud dawn
#

Other than that no I'd say.

mental hollow
#

is it not faster or anything?

cloud dawn
#

Unless your bot is as big as mee6 you'd likely not notice.

manic knoll
mental hollow
mental hollow
#

just pass your role object into the function

manic knoll
mental hollow
#

you haven’t passed any role objects

cloud dawn
slate swan
# mental hollow is it not faster or anything?

for the starters, asyncpg has much better design that mongodb/pymongo
and when it comes to the database postgres is much more scalable than mongodb, mongo isnt a great database anyways

mental hollow
cloud dawn
#

Design due to Mongo not needing it.

mental hollow
cloud dawn
slate swan
manic knoll
slate swan
manic knoll
slate swan
#

well you're telling it to add roles but not telling to add what roles...

#

other than that it's fine

shrewd apex
#

that was so casual

manic knoll
#

its for the argument the author picks the role @slate swan

shrewd apex
#

add the role param in the ()

cloud dawn
manic knoll
shrewd apex
#

detailed

shrewd apex
slate swan
#

*untyped dictionaries

shrewd apex
#

tru

cloud dawn
shrewd apex
manic knoll
cloud dawn
slate swan
manic knoll
slate swan
#

yes

#

i forgot that i installed surrealdb but never tried it

manic knoll
#

ohhh

#

ok so

cloud dawn
manic knoll
#

oof

#

so could i do interaction.member.roles?

cloud dawn
#

member isn't an attribute of interaction.

manic knoll
#

remember this code

cloud dawn
#

Yes.

manic knoll
#

so it should be like that instead of inter.user?

#

@cloud dawn

cloud dawn
#

just member

#

i gtg

shrewd apex
primal token
#

Just use a matrix lmao

maiden fable
#

JSON

potent light
#

Does int have a limit in Python? what's the best way to pass an argument in a function like:

@app_commands.command()
async def test(self, interaction: discord.Interaction, message_id: int)```
potent light
slate swan
#

!d discord.ext.commands.Range

unkempt canyonBOT
#

class discord.ext.commands.Range```
A special converter that can be applied to a parameter to require a numeric or string type to fit within the range provided.

During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated "(in Python v3.11)") so type checkers understand the intent of the code.

Some example ranges...
slate swan
#

but discord doesn't take integers of a Message ID length in an integer type argument

potent light
slate swan
#

yessir

hushed galleon
potent light
slate swan
#

they do, there's a integer option type in the api

#

they just don't accept BIGINTs as value

potent spear
#

Incredibly useful, I’ll remember that

slate swan
#

or any value out of the range thegamecracks mentioned

potent spear
#

Remembered someone using string int() conversion earlier 😅

hushed galleon
#

for referencing a message, i would probably make a transformer that uses the same mechanism as MessageConverter

#

discord doesnt have a native option type for messages apparently

slate swan
#

one can use an app_commands.Transformer to make a custom one yeah

#

the data type shouldn't matter if it's a fetch request

hushed galleon
#

oh right there's context menu commands

slate swan
#

thats the best choice lol

#

almost same steps as it would take to copy the msg id

#

How can I see all the perms my bot has in a server

unkempt canyonBOT
#

property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
slate swan
#

!d discord.Member.guild_permissions gives you the server-level permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.
slate swan
#

appreciate it

#

another question how would I setup the arguments if I wanted a command like this

.a @slate swan
or
.a bot.on_error=lambda *_:sleep(0)

#

actually instead of name an id

spiral kiln
#

how can i except discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embeds.0.image.url: Scheme "hello" is not supported. Scheme must be one of ('http', 'https').

slate swan
spiral kiln
outer flint
#

how would I go to replicate this?

slate swan
#

use an image manipulation tool like pillow

#

!pip pillow

unkempt canyonBOT
outer flint
#

do I need to store the images locally or? thonkhmm

slate swan
#

nope you create the image in memory get the bytes and send it directly using discord.File

#

!d discord.File the fp can be any bufferable

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

which means you can pass an io.BytesIO in there

outer flint
#

I suppose the same if using disnake? thonkhmm [we switched to it]

vocal ruin
#

Hello, I'm trying to make a discord bot but I have no idea how to start, I would like the discord bot to use the search bar at the top right, how would I use the search bar with a bot?

slate swan
vocal ruin
#

Is the search bar function maybe not the right way of doing it ?

#

Maybe reading message contents or sumn idk

slate swan
#

!d discord.abc.Messageable.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.

Examples

Usage...
slate swan
#

you can check history per-channel

vocal ruin
#

And does messagebale history work per server?

sick birch
#

We don't help with selfbots here so we won't be answering that question, sorry 🙂

vocal ruin
#

my bad

potent spear
#

this is called ephemeral, now try the docs with that word in mind

#

Try and see

#

slash commands have a different syntax than "text commands" tho

hazy vault
#

guys i have a question

#

Learning from the phone rather than from the computer will make a difference

#

Meaning, is there a difference in the Python language between the phone and the computer?

potent spear
#

learning on a phone is quite a small screen though, you'll have lots of issuesdiscomfort with "scrolling through classes and functions" etc

shrewd apex
#

indentation also ide support in short u will be in for a bumpy ride

outer flint
#

question... why it says it is undefined?

fading marlin
#

that's not how you reference a method, you're missing a self parameter there too

outer flint
#

ah self.create_welcome_image(member)?

slate swan
#

right

#

but also, add self as the first argument to the create_welcome_image function
or make it a staticmethod

outer flint
#

noted! I just need to thinker the create_welcome_image function then, thank ya ^^

velvet sierra
#

since i changed my bot to use discord slash commands sometimes it don't respond to commands, someone reasons for this happen?

pine bobcat
#

Hi, anyone is familiar with free hosting for bots? I used heroku but they closed the free tier

slate swan
#

there's no good free hosts

#

https://railway.app this one's nice and free but has usage limitations similar to heroku ( 20-25 days/ month )

Railway

Railway is an infrastructure platform where you can provision infrastructure, develop with that infrastructure locally, and then deploy to the cloud.

shrewd apex
#

500hrs and 5$

slate swan
#

!e print(500/24)

unkempt canyonBOT
#

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

20.833333333333332
slate swan
#

🤷‍♂️

loud junco
#

my man is working on anya

vocal ruin
#

When I try to print mutual guilds of a user it gives back [], I want to print the mutual guilds id

#

print(user.mutual_guilds)
|
I'm pretty sure I need to add something else here

#

bonus would be printing how many there in aswell as id and name

loud junco
#

check the docs there should be some attribute mentioned there

vocal ruin
sick birch
#

Okay, but what intents do you have?

vocal ruin
sick birch
#

No.. your gateway intents

vocal ruin
#

None

sick birch
#

Lol. Miscommunication 😅 my apologies

vocal ruin
#

I haven't put any on

sick birch
#

That's probably why then

#

IIRC your bot needs a special intent to be able to see guilds

vocal ruin
#

Alright

#

Ok thanks

sick birch
#

Give me a sec to find out which one that was for you

vocal ruin
sick birch
#

To start off you can just use all intents:

intents = discord.Intents.all() # enable all intents
client = commands.Bot(command_prefix="!", intents=intents)

# commands and other logic here

client.run("token here")
#

Make sure you enable all 3 intents in your developer dashboard or this will spit out an error

vocal ruin
#

even with intents off

sick birch
#

these 3

sick birch
#

If you'll notice this note here:

sick birch
#

It only considers the local cache

vocal ruin
#

OH

feral timber
vocal ruin
#

I think I got it lemme test'

sick birch
#

Your cache should not be out of date

feral timber
sick birch
#

Have you had a similar issue?

feral timber
#

no

#

I'm just listening and learning

sick birch
#

Heh, lol. Thought you had an issue like that before. The cache will always be up to date

vocal ruin
#

man

#

@sick birch Can I dm you?

sick birch
#

I'd prefer that we keep things here

#

If it's related to Python, of course

vocal ruin
vocal ruin
sick birch
#

if you're not breaking any rules nobody will judge 🙂

sick birch
#

... and if it does i'm going to get in trouble for helping lol

vocal ruin
#

damn where do I go for help on this kinda stuff bruh

sick birch
#

Most servers won't help as it breaks discord's terms of service

#

And they'd be putting themselves at risk of termination

vocal ruin
#

xx

slate swan
#

Can someone give me that link to the stackoverflow question that explains why on_message stops your commands?

golden portal
vale wing
#

Very simple

spiral crypt
#

hey question, i have a file that uses memberid as a key, how would i search upthat key using ctx, is it like ctx.author.id?

vocal snow
#

yes

winged cloud
#

how can i fix this

slate swan
#

!tag 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. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

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

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

winged cloud
#

thanks

tough fern
#

"\n" doesn't work
expected output:

..
...

ahem...
test
Hello there!
Welcome to BitWorld, this is the very first ever book in BitWorld, if you reading this, i'm betting that you already encounter at least an enemy
Well, that's all in this book

Have a nice day!
rbbit```
what it actually does:
```.\n..\n...\n\nahem...\ntest\nHello there!\nWelcome to BitWorld, this is the very first ever book in BitWorld, if you reading this, i'm betting that you already encounter at least an enemy\nWell, that's all in this book\n\nHave a nice day!\nrbbit```
code:
```py
bookEmbed = discord.Embed(title=book, description=str(connDB.getBook(book)[0]["content"]))```
```py
def getBook(title):
    k = []
    for x in b.find({"title": title}, {}):
        k.append(x)
    return k``` i also use mongoDB btw
winged cloud
# tough fern "\n" doesn't work expected output: ```. .. ... ahem... test Hello there! Welcom...

write ```..
...

ahem...
test
Hello there!
Welcome to BitWorld, this is the very first ever book in BitWorld, if you reading this, i'm betting that you already encounter at least an enemy
Well, that's all in this book

Have a nice day!
rbbitinstead of.\n..\n...\n\nahem...\ntest\nHello there!\nWelcome to BitWorld, this is the very first ever book in BitWorld, if you reading this, i'm betting that you already encounter at least an enemy\nWell, that's all in this book\n\nHave a nice day!\nrbbit```

#

it'll work, hopefully 🙂

tough fern
#

ok, tysm

slate swan
#

if you're using a listener for on_presence_update(self, before, after): to send an embed, what's the format for the user avatar? i'm trying these and it doesn't grab the avatar. any suggestions?

           avatar = before.avatar(size=128)
           embed.set_thumbnail(url=avatar)
           embed.set_author(name=before.name, icon_url=avatar)


            avatar = before.display_avatar.url
            embed.set_author(name=str(before), url=avatar)


            embed.set_thumbnail(url=before.avatar_url)
            embed.set_thumbnail(url=before.avatar_url_as(size=128))
naive briar
slate swan
#

so prolly after?

naive briar
#

I've never seen that word in my life

slate swan
#

i'm using it for discord.ActivityType.streaming
if before.activity != after.activity
if after.activity.type == discord.ActivityType.streaming:
then it sends the embed.

mild token
#

how can i lock slash command to specific channel

vale wing
mild token
vale wing
#

Wut

mild token
#

i mean i am trying to make bot autosetup

vale wing
#

Ah

#

But like all servers are different, how can you automatically detect the channel you need? By checking names?

mild token
#

i am searching docs but not able to find anything 😅

mild token
#

and then in that channel all commands will be executed

vale wing
#

What's the point of that command if user can go to server settings and just put a checkmark on

mild token
#

all cant 😅 , only people with perms

slate swan
mild token
naive briar
#

That's why you should sync the commands manually

mild token
#

d.py register everytime when u reload the bot

#

so it goes to global scope

naive briar
#

What

#

Are you talking about app commands here

mild token
#

yes

naive briar
#

It only sync the command when you call CommandTree.sync

#

!d discord.app_commands.CommandTree.sync

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 also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
vale wing
#

Only if you authorise the user and do that via bearer token

slate swan
mild token
#
class MyClient(discord.Client):
    def __init__(self) -> None:

        intents = discord.Intents.default()
        super().__init__(intents=intents)

        self.tree = app_commands.CommandTree(self)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')

    async def setup_hook(self) -> None:

        await self.tree.sync(guild=TEST_GUILD)
        self.add_view(PersistentView())

this is how its in my bot

#

so when i turn on bot self.tree.sync is called everytime

vale wing
naive briar
#

I just said that's why you should sync the command manually

#

With a prefix command or something

vale wing
#

I don't really know does that thing utilize authorization

slate swan
vale wing
#

?

slate swan
#

nvm

#

I need to learn how to use requests module

vale wing
#

Yeah just don't use it in async app

mild token
naive briar
#

Just make it

vale wing
#

Once you learn requests generally, move to aiohttp to use in async context

slate swan
naive briar
#

It's not any harder than learning + operator

slate swan
#

I learned how to use requests a one point

#

I just don't understand how to read docs

#

like I don't understand what I'm sending a get to it shows this /imagegen{?type}

vale wing
#

Type is an URL param or whatever it's called

#

Like https://api.cool-site.com/imagegen?type=raw will send raw image bytes in response body

slate swan
#

so like

vale wing
#

?type=url will return a json with url probably

#

You need to test

slate swan
vale wing
#

If that's their base API url then yeah

#

Their base is actually https://nekobot.xyz/api/

#

Do they not require authorisation wtf

mild token
#

@vale wing still i am able to use command in other channel

loud junco
#

will it take damage as a negative number

upbeat otter
#

bot.command not add_command

upbeat gust
#

Where did you get this code from

upbeat otter
#

and nice slash commands pepe_exit

upbeat gust
#

What library are you using?

upbeat gust
upbeat otter
upbeat gust
#

Yes it is, read the question and code before answering

quick gust
upbeat gust
#

ah ok well that's very wrong but I'm not familiar with pycord, you might have better luck asking in their server

upbeat gust
upbeat otter
#

it is

upbeat gust
#

sure-

#

I'm not familiar with pycord

#

Are you sure you're actually using pycord though?

#

pip list

quick gust
#

that's not stack overflow

upbeat gust
quick gust
#

I thought you were talking about the link chrispy sent

#

Yeah okay

upbeat gust
#

yeah use only discord.py or pycord, they'll conflict and make weird shit happen if you have both

#

sure, also do pip install discord.py --force-reinstall while you're at it

feral cradle
#

I have a question, I'm getting a error about exceeding rate limits, it's 429 but how do I prevent this from happening next time?

upbeat gust
#

Slow down

feral cradle
#

Wdym?

upbeat gust
#

A ratelimit means you're doing something too fast, slow down

feral cradle
#

It's a AI chatbot that I'm letting idle mostly

upbeat gust
#

Do you have logging enabled?

feral cradle
#

No Waaa

upbeat gust
#

You should see warnings about ratelimits being handled before the 429

upbeat gust
# feral cradle No <:Waaa:805212826125205515>

Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using Client/Bot.run. More about that in ?tag defaultlogging.

It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging

but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.

feral cradle
#

Ah thanks

slate swan
#

question. so for games to have that icon in the bottom left above ur avatar, is there a way I can get the url that discord uses to load it? like maybe the application_id?
trying to see if I can have a script grab it for a bunch of games I put in a db. here's an example of one for valorant.

<Activity type=<ActivityType.playing: 0> name='VALORANT' url=None details=None application_id=700136079562375258 session_id=None emoji=None>
i tried an if statement setup like this, but it didn't grab the icon :/

            if before.activity != after.activity:
                if after.activity:
                    application = await self.bot.application_info(after.activity.application_id)
                    avatar = application.avatar
slate swan
#

the thumbnail that discord has for game activities. so like, the data discord has for this. how can a bot obtain it? I got the name via after.application_name, but i'm trying to see if I can grab the thumbnail too.

naive briar
#

!d discord.Activity.large_image_url

unkempt canyonBOT
naive briar
#

!d discord.Member.activity

unkempt canyonBOT
#

property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activities "discord.Member.activities").
slate swan
#

thank you!

#

fuk of biches

feral cradle
loud junco
#

is this how u import itemlist?

naive briar
#

What

loud junco
#
for mobdrop in itemlist.mobdrop_list:
naive briar
#

Is that list inside the itemlist file

loud junco
loud junco
naive briar
#

Then it should be good

vale wing
vale wing
loud junco
#

wtf language are u talking in

vale wing
#

Idk

robust fulcrum
#

Guys i am trying to make a docs command like @unkempt canyon and i have the objects.inv file
How can I use that file to get docs on a symbol?

vocal snow
#

set ephemeral=True in send_message

spiral kiln
#

how can you check if you deselected an item in a dropdown?

#

like only you can see that message

vocal snow
#

in english ephemeral means something that exists temporarily

vocal snow
#

nope, only for interaction responses

spiral kiln
#

how can you check if you deselected an item in a dropdown?

timid pawn
#

Hi, if there's anyone who has used telethon's api library for telegram before, do you know if its possible to remove a user from a group with a bot using the api?. Have tried it with the available methods but it only seems to work for channels.

vocal snow
heady verge
#

i get no error but its bothering me

timid pawn
vocal snow
#

ah, fair enough

vocal snow
heady verge
#

oh, ty

#

how to import Option then

vocal snow
#

which library are you using?

heady verge
#

pycord

vocal snow
#

oh

#

there might be a discord.commands then, I'm not sure about pycord

#

I think you can import Option directly from discord though

heady verge
#

oh okay

#

ty

slate swan
#

What i am trying to accomplish
I am trying to make a command that when i do "/add 123" it will add 123 to a txt file on github. My bot is hosted by myself using Visual Studio Code.

scarlet sorrel
#

why does this not work?


from threading import Thread

import discord


def master_thread():
    intents = discord.Intents.default()
    intents.messages = True
    client = discord.Client(intents=intents)

    @client.event
    async def on_ready():
        print('Logged in as')
        print(client.user.name)
        print(client.user.id)
        print('------')

    @client.event
    async def on_message(message):
        print(message.content)

    client.run('blahblahblah')

Thread(target=master_thread, args=()).start()

It says RuntimeError: There is no current event loop in thread 'Thread-1 (master_thread)'.

naive briar
#

It means exactly what it says

#

There's no event loop in that thread

#

!e

import threading
import asyncio


def main():
    async def inner():
        print("meow")

    loop = asyncio.get_event_loop()
    loop.run_until_complete(inner())

thread = threading.Thread(target=main)
thread.start()
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Exception in thread Thread-1 (main):
002 | Traceback (most recent call last):
003 |   File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
004 |     self.run()
005 |   File "/usr/local/lib/python3.11/threading.py", line 975, in run
006 |     self._target(*self._args, **self._kwargs)
007 |   File "<string>", line 9, in main
008 |   File "/usr/local/lib/python3.11/asyncio/events.py", line 692, in get_event_loop
009 |     raise RuntimeError('There is no current event loop in thread %r.'
010 | RuntimeError: There is no current event loop in thread 'Thread-1 (main)'.
naive briar
#

Just create a new loop and set it

#

Also why do you need threading anyway

slate swan
#

whats more valuable Java or Python

naive briar
#

Depends on what you're comparing those two on

slate swan
#

Hey guys, I used to make discord bots when the discord library died and then I shifted to disnake but soon I stopped making bots. So now again I am going to make bot, so what discord library most of you using?

slate swan
#

how fast it can analyze and execute

naive briar
#

Java is a compiled language, so of course it's faster than Python

slate swan
#

okay so discord library came back

slate swan
unkempt canyonBOT
slate swan
#

I am asking because i am trying to make my bot fast enough to compile data and store it {every 6 seconds it stores it in python currently} but also be able to run commands that people may use {Without timing out}

naive briar
#

Then asynchronous programming is enough

slate swan
#

language?

naive briar
#

Python

slate swan
#

copy that thank you

upbeat otter
slate swan
#

okay thx

upbeat otter
#

those are the docs only for their API

slate swan
#

no I mean IK

#

just asking if discord.py have the latest features rolled out by discord,com

upbeat otter
#

well yeah

#

those are mostly on their github repo

slate swan
#

Ye

upbeat otter
#

"really new ones"

slate swan
#

Because the last time I used discord.py, it was dead

#

It was when I started using disnake, which was updated

upbeat otter
#

that was 2 years (or maybe 1) ago

slate swan
#

I don't think it was this long, but maybe time went really fast

upbeat otter
spiral kiln
#

yo so i see other bots like save the options you have chosen before in a select. How do i do this?

slate swan
#

use json

#

or db, but json is easy

spiral kiln
#

but like how does the dropdown automatically like save those selects

#

can i show u an example in dms?

slate swan
spiral kiln
#

o

#

alr

upbeat otter
#

as a db

naive briar
#

Found out the hard way

upbeat otter
slate swan
naive briar
#

As your JSON file gets bigger, the more data it needs to load into the memory to use

slate swan
#

oh ye

upbeat otter
#

and if your bot goes down while your bot is writing into the file, your data may get corrupted or in the worst case scenario, completely lost

spiral kiln
naive briar
slate swan
#

you guys use replit?

#

(free users only)

regal cove
#

how can you disable a button on disnake after it being pressed?

vale wing
#

I don't understand purpose of it at all

#

Why not just use local IDE

severe nacelle
#

Hi

slate swan
unkempt canyonBOT
slate swan
vale wing
#

For hosting it's unisuitable

spiral kiln
slate swan
#

!d discord.ui.Select

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 with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
slate swan
#

there was some defaut kwarg somewhere

unkempt canyonBOT
#
Not gonna happen.

No documentation found for the requested symbol.

slate swan
#

!d discord.SelectOption

unkempt canyonBOT
#

class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.

These can be created by users.

New in version 2.0.
slate swan
#

right, set it to True in the option's default kwarg

spiral kiln
#

finnaly

#

ty

slate swan
#

hello i want to send this embed with a discord bot command. exactly the same. what should i use. (add.field) or something else?

#

how to send a body content in an embed

#

is itembed.set_body(title="title", description="description")?

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

\2063 isn't an invisible char?

#

i want invisible char because when I write title="" it does that

elder bison
#

hello

#

wat does exactlly mean by >For your app to be considered active, it will need to have executed an application command in th

#

application commands

#

does that i mean i have to use / slash in the start of my bot command like

if message.content.startswith("/"):```
sick birch
elder bison
#

so the bot should have that particularly

sick birch
#

Colloquially we refer to them as "slash commands"

elder bison
#

@sick birch

#

code looks this way isnt it

sick birch
elder bison
sick birch
#

So what's the problem?

elder bison
timid spade
#

am i doing something wrong here?

#

i am still getting the error

torn sail
timid spade
#

thanks 🤝

#

also there was on_error in logs too
whats that used for then

torn sail
unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.11)").

Note

`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").

It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").

Changed in version 2.0: The traceback is now logged rather than printed.
torn sail
#

based on what this says i think you can override it to change how the error is dispalyed

#

for example writing the error to a file instead of stderr

timid spade
#

oh okay

#

thanks

slate swan
#

Is it impossible to print variables in embed's description?

upbeat otter
slate swan
#

how?

upbeat otter
#

you're trying to use an f-string ig

cloud dawn
#

!f-string

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

upbeat otter
#

ok I am lagging so bad

#

wtf

cloud dawn
#

lol

slate swan
#

oh i forgot it

#

thank you

pearl vault
#

Why the server doesn't have channel for telegram bots?

#

they are quite popular

cloud dawn
#

I've not seen many question about telegram bots.

ionic garden
#

in a user db for my bot, should the primary key be 1, 2, 3, 4... or the discord user id?

cloud dawn
ionic garden
#

see here's the thing

#

w/o a PK intellij won't let me update the db for some reason lol

cloud dawn
#

That's weird

sick birch
young dagger
#

Why does it send the message when someone in the voice channel is muting or unmuting themself?

@client.event
async def on_voice_state_update(member, before, after):
    # Check if the user is joining the voice channel 712072729406472374
    if after.channel and after.channel.id == 712072729406472374:
        # Check if the user is in the database
        if collection.find_one({"discord_id": member.id}) is None:
            channel = client.get_channel(712074759453671494)
            if member.voice:
                await channel.send(f"{member.mention}")
                # Create an Embed object
                embed = discord.Embed(title="Verification Required", description="To ensure fair gameplay, we are using an Elo system to generate the teams. In order to participate in our custom games, you must first verify your League of Legends account. Please use the `!setup YOUR SUMMONER_NAME` command and follow the instructions provided.", timestamp=datetime.datetime.now(), color=discord.Color.red())
                await channel.send(embed=embed)```
sick birch
young dagger
sick birch
#

What are you looking for your code to get triggered on? When a user joins a voice channel?

shrewd apex
#

u want voice channel joins?

young dagger
shrewd apex
#

iirc there is an event for that too

vale wing
young dagger
#

And not when they are muting/unmuting or deafen/undeafen themself.

shrewd apex
vale wing
#

Telegram bots are just scripts that make requests API what's so special about them

#

discord bots aren't much more complicated but at least there's websocket

shrewd apex
vale wing
#

No

#

I already tried to do that in java and lost 69% of my braincells

shrewd apex
vale wing
#

But at least I managed to establish ws connection 🤓

vale wing
#

I'd probably better fork JDA and make it more user-friendly

sick birch
young dagger
# sick birch You'd check if `before.channel is None and after.channel is not None`

Like this?

@client.event
async def on_voice_state_update(member, before, after):
    # Check if the user is joining the voice channel 712072729406472374
    if after.channel and after.channel.id == 712072729406472374:
        if before.channel is None and after.channel is not None:
            # Check if the user is in the database
            if collection.find_one({"discord_id": member.id}) is None:
.......................```
sick birch
#

Or you can leave it as is

slate swan
#

It's saying user has no attribute banner what would be the proper way of doing it

@bot.command()
async def banner(ctx, user:discord.Member):
    user = await bot.fetch_user(user.id)
    banner_url = user.banner.url
    await ctx.send("{}".format(banner_url))```
young dagger
vocal snow
#

what version of dpy are you using? @slate swan

slate swan
#

forgot how do I check

sick birch
shrewd apex
sick birch
#

Which is why I generally advise people to print discord.__version__

junior terrace
#

hey i'm freaking out

#

i am using this code

@client.event
async def on_member_update(after):
    target_guild = client.get_guild(816442399039422476)
    blender_role = discord.utils.get(target_guild.roles, id=830836844950192209)

    for activity in after.activities:
        if activity.name == "Blender":
            await after.add_roles(blender_role)
            break
    else:
        await after.remove_roles(blender_role)```
#

it checks if a user is playing blender and if yes gives the role "blender"

#

pretty easy

#

BUT

#

i get "unknown role" as error

#

the role in the list is above everything and the command do what it should do

pliant gulch
#

Doesn't on_member_update give two parameters?

#

!d discord.on_member_update

unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.

This is called when one or more of the following things change...
junior terrace
#

yeah i had before, it was an unused parameter so i removed it

#

nothing changed

#

i still get the error even tho everything works fine

#

as you can see it is unused @pliant gulch

pliant gulch
#

Yes, but I wouldn't remove it completely cause that'll either error right away or give an undefined behaviour

#

I would just prefix it like _before which is the convention iirc

#

None the less, make sure target_guild is not None and that blender_role is also not None

junior terrace
#

they are not trust me

#

they are actually my guild and my role id

pliant gulch
#

Okay, then make sure that the person who has Blender in their activity a member of the guild you have the role in

#

Those are the only places I can see this going wrong, other than that it looks fine

junior terrace
#

hey @pliant gulch

#

little update

#

i've used _before

#

and now no error pops up, could you tell me what is the convention iirc?

#

ah nevermind, my bot was getting rate limited.... al the errors popped up rn

shrewd apex
slate swan
#

someone knows why I can't Import option from discord

shrewd apex
#

also thats not how it's used

#

ok that looks like pycord

slate swan
#

yes it's pycord

shrewd apex
#

and pycord dosent take intents? susge idk never used it but the code looks awfully wrong

shrewd apex
#

chatgpt moment i would guess

slate swan
#

no lol i did it

shrewd apex
#

only slash command

slate swan
#

whym

#

wdym*

rare echo
shrewd apex
#

like prefix command

#

dont have option only / commands

rare echo
#

no option just argument ;)

shrewd apex
#

bot.command is for prefix command

slate swan
#

it still doesn't work

shrewd apex
#

it won't work with just that the code has a ton of bugs

#

i suggest u debug it in a ide

slate swan
#

it works

#

i don't have my pc

shrewd apex
#

!pypi pycord

unkempt canyonBOT
rare echo
#

!pypi py-cord

unkempt canyonBOT
shrewd apex
#

yeah he has the former

rare echo
#

ahhhhh

shrewd apex
#

in his cide

#

look at the installation logs

livid hedge
#

what is the package name of the official discord library?

#

I know there is one named Rapptz but it doesn't look official

rare echo
#

it is

shrewd apex
#

no official but famous ones are discord.py disnake hikari nextcord

slate swan
#

so u can't help me ?

#

I don't understand why I can't Import option

shrewd apex
#

without a ide for u to code in no

#

unless someone rewrites the code for u

slate swan
#

what's wrong with the code

shrewd apex
#

for starters the requirements

#

then the bot declaration

#

a bunch of stuff they will be highlighted once u code in an ide

livid hedge
#

i want the official one

shrewd apex
#

plus u are using ffmpeg pretty sure something related to ytdl so thats a risk too

shrewd apex
shrewd apex
#

its all supported by enthusiastic devs

livid hedge
#

hm

shrewd apex
#

so i would suggest that

#

also dont watch old video tuts those are outdated

pliant gulch
#

Hikari is clean as fuck

#

I don't think it would be torture

#

You must've gotten it mixed with Hata

rare echo
#

its torture if youre learning haha

livid hedge
shrewd apex
#

my answer was from the learning curve expected perspective

vocal plover
#

hikari is a pretty big learning curve tbf

sick birch
#

Serenity >>>

pliant gulch
#

I just remembered that for Hata Huyane rewrote asyncio apparently

#

Or at least that's what one of my friends told me

shrewd apex
#

...

#

damn

#

i should rethink my prospectives in coding ;-;

pliant gulch
#

No hata is a special case

shrewd apex
#

lemme Google him up

young dagger
#

So I want it to execute the code regardless of whether the user was in a voice channel before or not

sick birch
young dagger
sick birch
young dagger
sick birch
#

Ah: if (before.channel is None or before.channel.id != 712072729406472374) and (after.channel and after.channel.id == 712072729406472374)

young dagger
sick birch
young dagger
sick birch
#

If a user went from being in a voice channel to not being in a voice channel, that means after.channel is None

#

And then you're basically doing None.id which, of course, errors

young dagger
#

Do you know why this is considered error logs?

0|blitzcra | [2023-01-14 23:51:51] [INFO    ] discord.client: logging in using static token
0|blitzcra | [2023-01-14 23:51:55] [INFO    ] discord.gateway: Shard ID None has     connected to Gateway (Session ID: 97d1d9df36701e8be3ca47d36586aa16).```
pliant gulch
#

It's prefixed with INFO

#

You can ignore them unless you need to debug that deeply

upbeat gust
young dagger
hushed galleon
#

its probably shown in the error log because python's StreamHandler (what discord.utils.setup_logging() uses) defaults to stderr instead of stdout

smoky stone
#

im trying to make a discord bot but I keep getting the error "Traceback (most recent call last):
File "main.py", line 4, in <module>
bot = commands.Bot(command_prefix='!')
TypeError: init() missing 1 required keyword-only argument: 'intents'
".

my line 4 is py bot = commands.Bot(command_prefix='!')

#

whats the issue and how can i fix it?

golden portal
#

!intent issue is intents is a required keyword argument you need to specify

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

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

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

heavy swift
#

does get_guild actually work for anyone here

naive briar
#

Why wouldn't it

heavy swift
#

Because fetch seems to be the only thing that works for me lol

#

Whenever I replace a get command with fetch it just works

naive briar
#

Where do you call it then

heavy swift
#

I'll provide you with an example hang on

#

Before Fetch (Nonetype error)

    async def msg(self, ctx, channel_id=None, server_id = None,  *, txt=None):
        if server_id == None:
            server_id = ctx.guild.id


        if channel_id == None:
            return await ctx.send("You forgot to specify the channel.")

        
        server = self.bot.get_guild(server_id)
        channel = server.get_channel(channel_id)
        await channel.send(txt)

After Fetch (works)

    async def msg(self, ctx, channel_id=None, server_id = None,  *, txt=None):
        if server_id == None:
            server_id = ctx.guild.id


        if channel_id == None:
            return await ctx.send("You forgot to specify the channel.")

        
        server = await self.bot.fetch_guild(server_id)
        channel = await server.fetch_channel(channel_id)
        await channel.send(txt)

user input: .msg channel_id server_id hiya

#

same input, different result

#

The error to be precise:

channel = server.get_channel(channel_id)
AttributeError: 'NoneType' object has no attribute 'get_channel'

The above exception was the direct cause of the following exception:
golden portal
#

also, you might as well use the channel converter instead of explicitly do get_x

sick birch
#

Is all you need. Let discord.py handle the parsing for you

hushed galleon
hushed galleon
#

oh right i missed flowerpad's comment

smoky stone
#

but now its saying "NameError: name 'discord' is not defined"

naive briar
#

Import it then

dapper breach
#

need help

#

how do i make it check the mongodb every 2 secs if something changed then edit the original embed, if nothing changed it wont update or edit it until something gets changed

#

using pymongo

pliant gulch
#

Usually, I'd avoid checking over something and then doing something, it's quite demanding imo. How does the data get changed? Like via a command or

#

Because if it's a command or any other thing that takes in user input that you control, you can just update the embed on demand

dapper breach
#

if u need a example code then i can give u it

pliant gulch
#

Well, I'm assuming parts of other commands/events update the database correct?

dapper breach
#

would you like to see the code?

pliant gulch
#

So rather than having your code continuously check which is heavy, you could tell the bot that the embed needs to be updated

#

Lets take this as an example, ```py
some_code_that_updates_database() # we call this, E.g the command in this case
update_embed() # we call this because the database was updated and we know it is, because of above

#

Rather than having ```py
while True:
if database_updated:
update_embed()

some_code_that_updates_database()
database_updated = True

#

Note it's just pseudo-code so this doesn't work but, I think you can see what I'm getting at here

unkempt canyonBOT
#

Hey @dapper breach!

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

dapper breach
#

i have it like this

#

if u can help me with it i would love the help

naive briar
dapper breach
#

blocking what?

naive briar
#

!blocking

unkempt canyonBOT
#

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

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

import discord

# Bunch of bot code

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

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

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

dapper breach
#

the problem is it updates every 2 seconds with out me updating anything

naive briar
#

I'm just saying that it's blocking

#

Querying the database every 2 seconds with pymongo in asynchronous app like discord.py isn't a very smart idea

potent spear
#

especially when loads of people are simultaneously trying to access your db

#

also, not sure why you used mongodb as a db, as I suppose most objects in dpy are relational, so an object-relational db would be more fitting

#

the most common answer to that is "I made another project where I used that db, so I kept going with it"

dapper breach
#

but can anyone help or not?

slate swan
dapper breach
#

can anyone help me with the code?

solemn bramble
slate swan
quick gust
robust fulcrum
#

Guys i am trying to make a docs command like @unkempt canyon and i have the objects.inv file
How can I use that file to get docs on a symbol?

hushed galleon
# robust fulcrum Guys i am trying to make a docs command like <@409107086526644234> and i have th...

it seems you've tried using sphobjinv before, you should look into their api documentation and its source code to learn how to use it
https://sphobjinv.readthedocs.io/en/stable/api_usage.html
https://github.com/bskinn/sphobjinv/blob/stable/src/sphobjinv/inventory.py
or if you want to write your own parser, you can follow their unofficial specification of the v2 format and read the source code of the python bot
https://sphobjinv.readthedocs.io/en/stable/syntax.html
https://github.com/python-discord/bot/blob/main/bot/exts/info/doc/_inventory_parser.py

robust fulcrum
#

I tried encoding it and got a huge dictionary type thing

hushed galleon
#

the parser itself seems to be relatively simple compared to the rest, i would focus on that first and turn the file into a useful data structure

robust fulcrum
unkempt canyonBOT
#

src/sphobjinv/inventory.py lines 430 to 431

def suggest(self, name, *, thresh=50, with_index=False, with_score=False):
    r"""Suggest objects in the inventory to match a name.```
worthy wagon
#

Code works, everything is fine, it just won't add the user's data into the DB. ```py
if difference <= timedelta(seconds=3600):
query = 'INSERT OR REPLACE INTO Robbed (Timestamp, Placeholder, UserID) VALUES (?, ?, ?, ?)'
await cursor.execute(query, (int(time.time()), 0, member.id))
await cursor.close()
await db.close()
return await ctx.send(f"{member.mention} has already been robbed recently, please choose a different user.")
else:
query = 'INSERT OR REPLACE INTO Robbed (Timestamp, Placeholder, UserID) VALUES (?, ?, ?, ?)'
await cursor.execute(query, (int(time.time()), 0, member.id))
try:
await db.commit()
except Exception as e:
print(e)

        if wallet - rob_amount < 0:
            rob_amount = wallet

        await cursor.execute(f"UPDATE Economy SET Wallet = Wallet - {rob_amount} WHERE UserID = {member.id}")
        await cursor.execute(f"UPDATE Economy SET Wallet = Wallet + {rob_amount} WHERE UserID = {ctx.author.id}")
        await db.commit()
        await cursor.close()
        await db.close()
        return await ctx.send(f"{ctx.message.author.mention}, You've successfully robbed {member.mention} for $``{rob_amount}``.\n``Your Previous Wallet Balance``: ${wallet}.\n``Your Current Wallet Balance``: ${wallet + rob_amount}.", delete_after=5)
robust fulcrum
naive briar
#

!d sqlite3.Connection.commit

unkempt canyonBOT
#

commit()```
Commit any pending transaction to the database. If there is no open transaction, this method is a no-op.
naive briar
#

And the placeholders amount is incorrect

worthy wagon
#

I am.

#

Do you need to commit them in that specific code block? Because it didn't work the last time.

worthy wagon
naive briar
worthy wagon
#

Just rewrote some parts, and even made a line for it to create the table, and yet it still won't insert the changes.

naive briar
#

Just commit the changes then

worthy wagon
#

??

#

Bro, what?

shrewd fjord
#

Before closing the database and cursor

#

U need to commit/save the changes u made to the database

#

Like
-Creating table
-Updating stuff on table
-Inserting stuff on table
-Altering stuffs on table

#

And so on

#

Also as catglal said, the placeholder amount is fr i correct, u r trying to change the value of 3 diff datas, but u inserting the value of 4 datas

#

💀

spiral crypt
#

heyo!

import discord
  from discord.ext import commands
  from Rankcard import Main
  
  class Rank(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.rankcard = Main.RANKCARD()
      
    @commands.command()
    async def rank(self, ctx):
        card = self.rankcard.rank_card(
                    username=ctx.author.name, # user name
                    avatar= ctx.author.avatar_url, 
                    level=1, # user level
                    rank=1, # user rank
                    current_xp=0, # user xp
                    custom_background= "#000000", # background colour
                    xp_color="#FF7A7A", # Foreground colour
                    next_level_xp=100) # Next level xp
        file = discord.File(card)
        await ctx.send(file=file)
        
  def setup(bot):
        bot.add_cog(Rank(bot))

I found this online but I dont quite understand, its giving me a bunch of errors like an attribute error with ctx and rankcard, does anyone know a better library for a rankcard?

drifting arrow
#

Is it possible to make it so that when I send a link using the webhooks, that it doesn't show the preview or "unfurl"?

slate swan
#

or you can use supress_embeds=True in your send

slate swan
#

what's the best way to do slash command?

#

app_command, tree command, pycord, slash_command?

slate swan
#

why my command say isn't synced?

naive briar
#

bot.tree.command is a decorator

#

app_commands.describe also

#

Put @ infront of them

#

Also sync your commands in setup_hook

slate swan
#

Tryna get me code to check if a message has a word in a json called narrators, and if it has the value "weak" it should add it to a list and send the keys present, but its not working, theres no traceback.

    async def rijal(self,ctx,*,message):

        narrators = message.content.split()


        found_keys = []


        for message in narrators:

            for key in narrators.keys():

                if narrators == key and narrators[key] == "weak":

                    found_keys.append(key)


        if found_keys:
            await message.channel.send("Weak keys found in the message: " + ', '.join(found_keys))```
#

heres the json

{"aban": "weak"}

robust fulcrum
#

Guys i am trying to make a docs command like @unkempt canyon and i have the objects.inv file
How can I use that file to get docs on a symbol?

naive briar
#

How many times have you said this already

robust fulcrum
#

I not got help so I asked again

naive briar
#

Someone already told you how to read the inventory file

loud junco
vocal snow
loud junco
loud junco
naive briar
#

You should just take those as arguments

vocal snow
#

also, _init_ cannot be async like that

vocal snow
#

or alternatively, do the fetching lazily

robust fulcrum
flat marsh
#

hello, how can i mention a user and the bot, in this type of function:

async def test_command(interaction:Interaction, question:str):```
loud junco
#

i have no idea on how to fix this

loud junco
spiral kiln
#

yo so cos autocomplete only takes 25 values how can i make it so it displays 25 but i can search for more

loud junco
#

this is working

#

but once i add async its not working
are there any other way other than async def init thats not going to work

naive briar
#

__init__ can't be async

naive briar
#

Just take them as variable or make a classmethod to construct the insurance

naive briar
#

!e

import asyncio


class J:
    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2

        print(self.var1, self.var2, sep="\n")

    @classmethod
    async def new(cls):
        # do some async things
        var1 = await asyncio.sleep(0, result="Variable 1: Cat")
        var2 = await asyncio.sleep(0, result="Variable 2: Meow")

        return cls(var1=var1, var2=var2)

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

ins = loop.run_until_complete(J.new())
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Variable 1: Cat
002 | Variable 2: Meow
naive briar
#

Basic OOP

#

Discord.py can't convert your argument to member object

#

How did you call the command

spiral kiln
#

yo so cos autocomplete only takes 25 values how can i make it so it displays 25 but i can search for more