#Basic Pycord Help (Quick Questions Only)

1 messages · Page 46 of 1

swift pumice
#

It says 3.4 but with support of different aspects of updated version
Its a python interpreter for use with c#, since im trying to learn a bit of both and be able to implement features of other c# libraries to python bots

dim cape
#

How do i time out a command

#

await asyncio.sleep(5) os.unlink(f'{ctx.author.name}.png')

#

Would this time out rest of the code it gives 5 seconds for the rest of the code to rin

cyan quail
cyan quail
#

what are you trying to do?

dim cape
#

So it sends a capctha then u answer in a certain time if you dont it deletes the captcha files and ends the command

cyan quail
#

oh i see

cyan quail
dim cape
#

I need the command to end in a certain amount of time

marble obsidian
#

how can i get the og message object of a fourm thread

cyan quail
#

yes, so you use timeout=5 in wait_for

#

meaning if the 5 seconds have passed, it will raise asyncio.TimeoutError which you can catch

#

this is demonstrated in the second example py try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')

#

you can use the check function to verify that they did the captcha correctly, as seen in the first example ```py
def check(m):
return m.content == 'hello' and m.channel == channel

    msg = await client.wait_for('message', check=check)
    await channel.send(f'Hello {msg.author}!')```
cyan quail
marble obsidian
cyan quail
#

yeah caching with threads is pretty weird

#

and if that doesn't work either, one final method could be using thread.history with limit=1 and oldest_first=True

jaunty raft
#

hey guys is there any function that can be executed before a slash command function gets called?

#

is it also possible to cancel the function then

marble obsidian
jaunty raft
#

if how can I make some function that checks everytime when a slash command gets executed

#

wait

#

I can use commands.check() right?

#

rip wil still take some time to modify each command

marble obsidian
#

but its different for slash

jaunty raft
jaunty raft
#

@marble obsidian

#

but do I have to process the slash command ?

marble obsidian
marble obsidian
jaunty raft
marble obsidian
#

yes

jaunty raft
#

nevermind

#

how can I cancel then a slash command

#

like that it doesn't execute ping

marble obsidian
jaunty raft
#

but it will still execute the command ping

cyan quail
#

You have to include the process line

jaunty raft
#

?

marble obsidian
cyan quail
#

You override the on_application_command event, so you have to include process_application_commands

jaunty raft
cyan quail
#

Otherwise none of your commands will work

jaunty raft
#

but it will give me an error

marble obsidian
jaunty raft
#

okay

#

still

cyan quail
#

Oh wait my bad

jaunty raft
#

?

cyan quail
#

on_application_command can be overridden without process since that's handled somewhere else

jaunty raft
#

oh

#

so I can't block that

cyan quail
#

Are you trying to add permissions to your commands?

jaunty raft
#

kind of like:
if the user is in a database then:
the user is allowed to run the commmand
else:
alert

deep holly
#

Just an update on my errors I was trying to get help for - having Sparked wipe my server for me to start over worked. No issues lol

jaunty raft
#

but what if I have like alot of commands

cyan quail
#

It sounds like you'd be more interested in checks instead

#

You can add a bot check

jaunty raft
#

yeah that then I guess

#

so I have to modify each command now?

cyan quail
#

No, there's a way to add a check to all your commands which you can catch in your error handler

#

Just docs won't load for me...

jaunty raft
#

so that's the only thing what works?

cyan quail
#

There are several methods but a bot check is easiest

#

You can also have checks for each cog

jaunty raft
#

so there's no way to automate it

cyan quail
#

It's a single function

jaunty raft
#

ok I will do that then thanks

cyan quail
#

Bot check = global check for all commands

jaunty raft
#

bot check?

#

how do I do that

#

just @commands.check(check)?

#

or how do I make a global check

#

oh wait @cyan quail

cyan quail
#

Ah finally

#

Yep

jaunty raft
#

okay that's much better

jaunty raft
cyan quail
#

on_application_command_error

jaunty raft
#

can you give me an example?

cyan quail
#

And checks will raise discord.CheckFailure

#

Have you made a regular error handler before?

jaunty raft
#

oh not commands.ChecksFailure?

cyan quail
#

I think it was moved to discord

jaunty raft
#

oh I don't wanna update since I have to rename discord -> pycord

west quest
#

AttributeError: 'Bot' object has no attribute 'add_roles'

west quest
#

Whats wrong with that

cyan quail
west quest
#

👍

jaunty raft
cyan quail
#

You don't need to

west quest
cyan quail
#

v3 isn't for months

cyan quail
west quest
#

await user_added.add_roles(role)

#

correct right?

cyan quail
#

Yeah

jaunty raft
#

I'm not sure but:

@bot.on_error
async def on_err(ctx: commands.Context, error) -> None:
  if isinstance(error, commands.ChecksFailure):
    await ctx.send("oh no")
  else:
    raise error
cyan quail
jaunty raft
#

oh

cyan quail
#

Rather, you should use @bot.event with on_application_command_error and add your exceptions there

jaunty raft
#

bridge commands

jaunty raft
cyan quail
#

Well if it works then go for it

#

Yeah

#

Though it'd be discord.ApplicationContext instead

west quest
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'User' object has no attribute 'add_roles'

#

welp should it be add_role?

jaunty raft
cyan quail
#

No add_roles is correct, but you got a user instead of a member

west quest
#

now how do i fetch a member thonk

cyan quail
#

Can you show the command code?

jaunty raft
#

nope

west quest
#

user_added = self.bot.get_user(result["discord_id"])

jaunty raft
cyan quail
cyan quail
jaunty raft
#

oh does that also work

west quest
jaunty raft
cyan quail
#

Then use bot.get_guild

jaunty raft
#

now it works

cyan quail
#

And then guild.get_member

#

Nice

west quest
#

👍

#

also do i send message to user or member

jaunty raft
#

alright thanks

cyan quail
#

Either works

#

All good

west quest
#

whats the difference between user and member is what i dont get

cyan quail
#

User is a generic discord user

#

Member is tied to a specific guild

west quest
#

ah so user.mention should work right

cyan quail
#

So it'll have stuff like roles, nicknames etc

#

Yes

west quest
#

yep i've done this

#

is it a good idea to do it like this?

cyan quail
#

That's fine

west quest
#

or this better

cyan quail
#

discord.utils.get is certainly useful, but guild.get_role does the same and is shorter

west quest
#

lastly would i be able to dm a guild member something?

#

or do i need a user for that

cyan quail
#

It looks like you're transferring from 0.16.2 or something

cyan quail
#

Member inherits all the attributes of user

#

I'd recommend checking out the models section for other attributes and methods https://docs.pycord.dev/en/stable/api/models.html

cyan quail
#

Allgood

west quest
#

last thing, can someone tell me how i add multiple views to a message (multiple buttons to be precise)

proud mason
errant craneBOT
#

Here's the confirm example.

proud mason
#

See that

#

This is the most preferred way of doing multiple buttons in a view

west quest
#

👍

lapis raptor
#

Hey, how would I add a a channel select option to my slash command?
slash command:

@bot.slash_command(name = "announce", description = "Allows anyone with the administrator permission to send announcements")
@default_permissions(administrator=True)
#

also is there anyway to have it check if a user has a role or not compared to whether a user has a permission like above?

patent moth
#

can I record and play audio at the same time?

deep holly
#

what's the pycord equivalent of discord.py's timed_out_until ? Looking at the docs and am unsure

#

communication_disabled_until?

cyan quail
deep holly
proud mason
#

its the power of asynchronous programming

patent moth
#

but it is not working for me I get an error

proud mason
#

code? error?

patent moth
proud mason
#

👍

rare ice
#

Right now I’m trying to come up with an idea of a reaction roles system using buttons with each button giving a customizable role from the database. I was thinking of using on_interaction for this since I can handle all callbacks for a reaction role message (from a check) in one. Is there another way of doing this that’s more efficient? Since I don’t want to have to create persistent views over and over again every time the bot starts up.

proud mason
rare ice
#

on_interaction?

proud mason
rare ice
#

No

#

There are multiple buttons

#

That are able to be added by command

#

It’s a public bot so it has to be customizable

proud mason
#

oh then the number of buttons wont be fixed too right

rare ice
#

So I have to use on_interaction

proud mason
rare ice
#

But I’ve had trouble with on_interaction in the past if the button was sent before the bot restarts, probably wasn’t in the cache I think.

proud mason
proud mason
#

you wont have a button object in cache if you plan on doing it with on_interaction

rare ice
#

K

fervent cradle
#

How can i ask user that component life time expired

whole urchin
#

is there an ability to let users create custom commands?

ruby palm
# whole urchin is there an ability to let users create custom commands?

Creating non-slash commands shouldn't be a problem since you can just store the command name, the expected result and the guildID in for example a database.
Then you'd just have to check if the command with name x exists for guild y.

However, if you're talking about slash commands or a more complex form of the result than just text, I'm not certain how to do that.

whole urchin
fervent cradle
proud mason
fervent cradle
#

And i want to send user message that this button doesn't work

limber urchin
#

You can't make a button do something after it has timed out. In that case just disable the button or edit the message in on_timeout

fervent cradle
#

slash commands doens't show for me but for my friend it does

silver moat
fervent cradle
wind jay
#

404 Not Found (error code: 10062): Unknown interaction

when is this error triggered

full basin
#

When you usually take too long to respond

echo egret
#

is it normal that load/reload/unload_extension() doesn't affect commands ?

#

i have only one debug guild so when i restart my bot all changes are instantaneous, but when i use these methods new/removed commands aren't usable on discord

wind jay
#

how long?

full basin
wind jay
#

oh really?

#

so i have to use .defer() ?

full basin
#

Indeed

misty yew
#

How can I set cooldown for bridge commands?

young bone
wind jay
misty yew
#

How can I do CommandOnCooldown error for bridge command? If I use prefix, it send message in a chat. If I use slash_command, it send message in console

misty yew
#

And interaction didn't respond

young bone
marble obsidian
#

I'm trying to make my bot log avatar changes. This is what I've got but nothing happens. I've added loggers for nicknames using the same concept and it worked. How could I get this to work?

@bot.event
async def on_member_update(before, after):
    channel = bot.get_channel(channelid)
    if before.avatar != after.avatar and after.avatar is not None:
      embed = discord.Embed(description=f"**{after.mention} changed avatar **\n\n([before])[{before.avatar.url}] **->** ([after])[{after.avatar.url}]\n\nUser Id: {after.id}", color=0xe67e22)
      try:
        embed.set_author(name=after, icon_url=after.avatar.url)
      except:
        embed.set_author(name=after)
      await channel.send(embed=embed)
young bone
#

Wait

misty yew
#

Same problem

young bone
#

I know

#

I saw what the problem is now

#

You use on_command_error

#

But that is only for prefix commands

misty yew
young bone
#

Can you try .reply?

misty yew
cyan quail
dim cape
#

How can i edit a voice channels name?

rare ice
#

Is there a command check to see if a member is the guild owner?

#

Couldn’t find anything in the docs

silver moat
#

you could always make your own

rare ice
#

True

dim cape
#

Anyone know how i could fix this error and what does it mean

limber urchin
rare ice
#

Can a bot edit its own about me or can that only be done in the dev portal?

zinc cloak
#
In content: Must be 2000 or fewer in length.```
I got a function that works fine, but it gives this odd error when run
#

The line that it flags is

#
await ctx.channel.send(video)```
#

But the text isn't 2000 character long

#

Wait should I move this question to a thread

limber urchin
#

What is video?

rare ice
silver moat
#

the last choice

rare ice
#

Oh

light river
#

why doesn't on_disconnect call if you close the bot by pressing stop in ide

fervent cradle
#

Hi guys I have a question,
Currently I have a command that blocks a list of words that the user selects,
but my bot is not able to read the messages sent by weebhooks and other bots, Is it possible to achieve this?

light river
#

intents

fervent cradle
light river
#

message intents

fervent cradle
light river
#

message content intents

fervent cradle
#

I have message intents

light river
#

did you enable on dev portal?

silver moat
fervent cradle
#

Is that a different intent?

light river
#

i just use discord.Intents.all()

silver moat
silver moat
fervent cradle
#

O i didnt know that

#

Thanks Squid and Bigman appreciate itWumpusLove

fervent cradle
#

any help?

limber urchin
fervent cradle
#

and then?

#

pycord?

limber urchin
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

fervent cradle
#

?tag git

obtuse juncoBOT
#

dynoError No tag git found.

zinc cloak
#

In this call back to Season 10 of The Joy of Painting, learn how to create an almighty mountain, distant hills and trees, and a happy little path.

Follow along as certified instructor Nic Hankins guides us through the iconic Bob Ross wet-on-wet painting technique. From happy clouds to almighty mountains, these delicate instructions preserve ha...

▶ Play video
limber urchin
#

Could you show the code for the entire function?

proud mason
#

i suggest asking in #1047189308131508306

#

yes it is possible tho

fervent cradle
calm plume
#

i got this code

#
    vote_board = await ctx.response.send_message ( embed = vote_embed )
    emojis = ['1️⃣','2️⃣','3️⃣','4️⃣']
    await vote_board.message.add_reaction(emoji = emojis[0].encode("ascii", "namereplace"))
#

it says as a error discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'add_reaction'

#

which is weird bc vote_board.message exists

calm plume
#

but how is it nonetype when i sent it like some seconds ago

north gorge
#

is there some gotcha to using @tasks in a cog in a separate file that's loaded when the bot loads?

young bone
calm plume
#

well i don't want to

north gorge
#

I'm having an issue lmao, sorry wasn't responding

calm plume
#

here is my code tho for more detail

calm plume
#
@bot.command(name="voting_board", description="Pocket Calculator Here For Anything!")
async def _voting_board(ctx: discord.ApplicationContext,
                        title: str,
                        description: str,
                        timeout: str,
                        options: discord.Option(int, name = "options", description="The Amount Of Options", min_value = 2, max_value = 4)):
    server = bot.get_guild(665249741289947157)
    mod = server.get_role(953715870591496202)

    if ctx.author.top_role.position < mod.position:
        error_embed = discord.Embed ( title = "Uh Oh A Error!", description = f"It Seems That You Cannot Use The Command As You Need To Have A Moderator Role Or Higher, Please Use The Command Again When You Have The Moderator Role Or Higher", color = discord.Color.red ( ) )
        error_embed.set_thumbnail ( url = Logo )
        error_embed.set_footer ( text = "Below Moderator Role Power" )
        await ctx.response.send_message(embed = error_embed)
        return
    number = re.findall("\d+", timeout)
    time = timeout[len(number[0]):]
    seconds = float(number[0])
    if time == "m":
        seconds = float(number[0]) * 60
    elif time == "h":
        seconds = float(number[0]) * 3600
    elif time == "d":
        seconds = float(number[0]) * 86400
    vote_embed = discord.Embed ( title = title, description = description, color = discord.Color.dark_gray() )
    vote_embed.set_thumbnail ( url = Logo )
    vote_embed.set_footer ( text = "Voting Time, Cast Your Vote Now!" )
    vote_board = await ctx.response.send_message ( embed = vote_embed )
    emojis = ['1️⃣','2️⃣','3️⃣','4️⃣']
    await vote_board.message.add_reaction(emoji = emojis[0].encode("ascii", "namereplace"))
young bone
#

what returns a ctx.respond?

#

@calm plume

calm plume
#

wdym

young bone
#

Do you know basic python?

calm plume
#

ik

#

duh

#

i just don't understand why it returns none

north gorge
#

Aha, for the benefit of whoever is CTRL + F -ing in the future. Keywords: cog task has no attribute: when you're loading a cog with a task decorator you should do it in on_ready() not wherever you're doing it now

young bone
#

ctx.respond is not returning a message

calm plume
#

but then how imma gonna respond to the interaction

young bone
fervent cradle
#

is there a way to get all those arguments in commands.check ??

#

like i made a custom check and i want to check if the role which user pass in argument is above or not

dapper flare
#

how do i get a discord file input from a member

#
                                                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

TypeError: Invalid class <class 'discord.file.File'> used as an input type for an Option

i tried and got this

dapper flare
# proud mason `discord.Attachment`
@client.slash_command(name="ask", description="ask lol")
async def ask(ctx, gm:Option(str, "game master", required=False), gm_file:Option(discord.Attachment, "uplaod it in file format", required=False)):
    await ctx.defer()
    if gm_file:
        print("got here")
        with open(gm_file, "a+") as f: # stops here idk why
            print("gptt shere")
            gm = f.readlines() ```

i tried this and it didnt work and gave no error.
dapper flare
proud mason
#

with open(gm_file, "a+") as f: it doesnt work like that

dapper flare
#

then?

proud mason
#

.rtfm discord.Attachmet

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

proud mason
#

.rtfm discord.Attachment

dapper flare
#

oh okay

proud mason
#

1st one

#

yeah

verbal marten
#

In a custom cooldown function, how would I check if the command is currently on cooldown? I want to interact with my db if the command is on cooldown when the command is sent. I tried using is_on_cooldown() but I got a maximum recursion depth error.

proud mason
# verbal marten In a custom cooldown function, how would I check if the command is currently on ...

if you are implementing the cooldown with the decorator, CommandOnCooldown Exception would be raised in on_command_error https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.CommandOnCooldown

#

what is your custom cooldown function?

verbal marten
#
def my_cooldown(message):
        bot = message.bot
        record = bot.syncMongoDB[str(message.guild.id)].find_one({"user": message.author.id})
        if record:
            if bot.itemCheck(record["inventory"],"ancient scroll") and message.command.is_on_cooldown(message):
                bot.syncremoveItem(message.author.id, "ancient scroll")
                return None
            else:
                return commands.Cooldown(1, 7200)
        else:
            return commands.Cooldown(0, 7200)
#

@proud mason

#

oh i am stupid

#

i cant use is_on_cooldown within the cooldown function

#

ffs thats funny

#

A helper function would probably solve my problem here

#

Yeah i'm still struggling on how to implement this. I want it to reduce the cooldown if a database record has a certain value, but only if the command is currently on cooldown. So it is an 'item' a user can have to use a command again once instantly without a cooldown.

proud mason
#

i think you would need to maintain the cooldown checking yourselves. but im not sure

boreal dust
#

Code is in the error 💀

rare ice
#

By fetching a message, it returns discord.Message, how can I tell if this message is a discord.WebhookMessage object?

ruby palm
rare ice
ruby palm
#

Had to test that first as well.

rare ice
#

ah

chilly ermine
#

Hello! So i was trying to make a bot display a streaming status like when someone do a twitch stream (picture) however even tho i filled with name, game and all that stuff i can't manage to make it look like that, just the watch button appears.
Is it that a discord bot can only show that or maybe i coded it wrong?

dawn berry
#

bots are kinda restricted when it comes to stuff like that, so it could be just lack of permission

granite crypt
#

How can i add a persistant view in cog?

chilly ermine
full basin
granite crypt
dim cape
#

Is there a never ending loop

granite crypt
#

cogs are weird i hate cogs

granite crypt
dim cape
#

Wym where

granite crypt
#

Wym Is there a never ending loop

dim cape
#

Like is there a loop tht mever stops

granite crypt
#

No?

dawn berry
#

I can't get the cooldown in the Command class to work

tribal bough
#

where i can find all event list

ruby palm
proud mason
#

i dont think thats in the docs

proud mason
proud mason
#

see that

dim cape
#

Can i use em inside a async def

ruby palm
proud mason
proud mason
#

.rtfm discord.Message

dim cape
proud mason
proud mason
# dim cape Like here

oh yeah you can definitely use tasks.loop for this.. but i dont recommend editing a msg that often

proud mason
ruby palm
#

How the fuck did I oversee that

dim cape
#

And example or explanation on how i could do it

proud mason
dawn berry
#

How am I supposed to use the Cooldown class to set a cooldown for command usage? I don’t understand the docs

proud mason
dim cape
#

async def wtv():
@cedar depotsks.loop(seconds)
cod

proud mason
#

no

proud mason
#

it was working in the morning...

#

you use the decorator

#

and not the cooldown class

rare ice
#

RecursionError: maximum recursion depth exceeded in comparison what in the world is this error

proud mason
#

python has a limit

#

you can change it ofc

#

i hope you know what recursion is

#

(its a func calling itself)

rare ice
#

hm

#

i must have made an oopsie

proud mason
#

or if you intensionally want it, handle it with try except

ruby palm
#

I think you can increase the limit if needed

rare ice
#

how?

#

im also not having anything call itself

proud mason
dim cape
#
    async def btc_check():
      if a == await bitcoin():
        print("same")
      else:
          await a.edit(name = "BitCoin:" + str(await bitcoin()))```
proud mason
dim cape
rare ice
#

tbh ive never seen some of the errors im now getting before

dawn berry
proud mason
#

its not really a good idea to do that

limber urchin
#

Yeah no, don't do that

#

If you're reaching the limit you probably have an issue somewhere in your code

rare ice
#

i fixed it

proud mason
#

_raise_connection_failure(error)

rare ice
#

without having to do that

proud mason
#

smth with that?

proud mason
rare ice
#

i had a variable trying to do something with the variable that has the same name

#

duplicate names

proud mason
proud mason
proud mason
dim cape
#

@proud mason dms?

proud mason
#

i think that looks good

dim cape
#

How do i continue a task.loop

limber urchin
#

continue?

dim cape
errant craneBOT
dim cape
#

Anyone

proud mason
#

you might want to take the loop outside the command and then start it

proud mason
dim cape
#

loop.start(btc_check)

proud mason
#

you would need to pass a

#

im sensing you arent quite familiar with python?

#

is that so?

proud mason
dim cape
#

Ik some from w3school

limber urchin
#

Read rule 1 in #help-rules please

dim cape
#

ik most things but tasks.loop

limber urchin
#

If all you've learned is from w3schools, you are most definitely not ready for a Discord bot

fervent cradle
#

Hi, I was trying to work with set_permissions method (to create a lock command that removes send_messages permission from a selected channel), but I can't figure out how to pass a desired role to as target. I went through the docs but couldn't exactly find an answer.

fervent cradle
fervent cradle
proud mason
#

just pass the role object

#

to target

#

oh actually it might be a positional argument

proud mason
fervent cradle
# proud mason just pass the role object

Ok so I just tried something, and yeah passing the role object worked. I had to create an additional option that takes role input from the user inside a container (which is the parameter of the command func). I then passed that container/parameter as a target and it worked.

#

I was wondering if there was another way for it though. I wanted a role (say @everyone) to be the default value of that parameter or container.

#

Can I use a method to extract that desired role from the guild? Any idea if such a method exists?

winter condorBOT
proud mason
#

are you referring to this?

granite crypt
#

Is it possible to make the bot not say interaction failed without sending a response?

fervent cradle
proud mason
#

you can defer and forget a component, but not an app cmd

#

for app cmds, the best you can do is send an ephemeral response (only visible to the author), and if you want, delete it

fervent cradle
#

@proud mason Alright, it'll work (I haven't tested it yet since it's kinda late for me). Thank you for the help.

tough briar
#

i'm atm operationally blind 😅

How in the world do i use a local image in a embed for the image field?

proud mason
#

oh wow i found a tag for this

#

?tag localimage

obtuse juncoBOT
#

dynoError No tag localimage found.

proud mason
#

oops

#

?tag localfile

obtuse juncoBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
proud mason
#

yeah

proud mason
granite crypt
proud mason
#

no need to send a response

granite crypt
#

Can you drop an example please

dim cape
#

Yo how do i make space in between slash commands ive seen it somewhere

dim cape
#

Yi

errant craneBOT
#

Here's the slash groups example.

#

Here's the slash cog groups example.

graceful mortar
#

Hey, how can I send an error in Discord via embed, the error should look exactly like in the console, how do I do that? Because with on_error I find nothing suitable

thorny kindle
#

Hi, I do coding on my windows 7 laptop normally, But i have got a new host for my bot, How can i make the bot with the latest version of pycord and python online? Ive restarted so i dont have a current file.

thorny kindle
silver moat
#

also, Python dropped support for Windows 7, the latest version you can use is 3.8.16

#

you can install pycord with pip install py-cord

thorny kindle
#

Alright, cool, Ill try that now and just transfer the files over, Thanks!

jaunty raft
#

how many inputs can a modal have?

proud mason
jaunty raft
#

why the reaction

#

5 okay got it thanks

proud mason
jaunty raft
#

haha can happen

proud mason
#

You need that

#

It returns a sting

graceful mortar
#

ah thanks

young bone
jaunty raft
boreal dust
#

Can i make an api in the same file as bot? If yes, how?

#

ping me pls

young bone
obtuse juncoBOT
#

Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(http://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean)

discord.py uses aiohttp, so it should already be installed. An example of code using aiohttp and discord.py:

async with aiohttp.ClientSession() as cs:
    async with cs.get('https://httpbin.org/json%27') as r:
        res = await r.json()  # returns dict
        await ctx.send(res['slideshow']['author']) 

For more help, see aiohttp's documentation: <http://aiohttp.readthedocs.io/en/stable/>

young bone
#

is 1k the limit of a discord bot?

warm kindle
#

message.guild.members.find(lambda m: m.name == 'as'), whats the error?

warm kindle
young bone
#

?tag idw

obtuse juncoBOT
#

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

young bone
#

#help-rules

warm kindle
#

well, the code is just that, and i hope to find a member by his username

silver moat
#

.rtfm utils.find

winter condorBOT
silver moat
#

@warm kindle

thorny kindle
#

Hi, For some reason when i do a slash command whilst using my laptop as a host, It works but when i put the exact same code into the host i use this error shows, Does anyone know why?

#
  File "/home/container/main.py", line 14, in <module>
    @bot.slash_command(description="testing")
AttributeError: 'Bot' object has no attribute 'slash_command'
limber urchin
#

What host are you using?

thorny kindle
#

Cybrancee bot hosting

limber urchin
#

And are you sure you have pycord installed, and not discord.py?

thorny kindle
#

txt

limber urchin
#

why?

thorny kindle
#

oh wait

dawn berry
#

how do I put my errors in a cog and reference them when I make my commands?

#

my checks I mean

thorny kindle
#

I could not figure out how to put pycord in, so i thought pycord was already inside of the main.py built in

limber urchin
#

that is not how python works

thorny kindle
#

How can i add pycord too the requirements

limber urchin
#

just add py-cord to the requirements file?

thorny kindle
#

oh wait, its just py-cord?

limber urchin
#

yes? what else would it be?

thorny kindle
#

LOL

#

i spent 3 hours trying to get my bot to turn on as i was using the pip command to install it

#

thanks so much!

#

ah, it works now

thorny kindle
#

How would i make my bot dm a user before kicking them?

limber urchin
#

.rtfm discord.User.send

winter condorBOT
thorny kindle
#

Alright

#

How would i use this? Ive tried

await discord.User.send(f"u have been kicked for {reason}")

and that didnt dm

woeful spindle
#

you can call .send on a user object to send them DMs

thorny kindle
#

Ive just noticed that that discord.user.send was a link, I think i may have it now. Just gonna test

thorny kindle
silver moat
#

remove debug_guilds to register globally

woeful spindle
thorny kindle
#

No.

silver moat
#

?tag oop

obtuse juncoBOT
#

https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html

There's a difference between a class and an instance. Think of it like this:

  • A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
  • An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.

Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.

mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.

There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.

woeful spindle
#

@thorny kindle ^

thorny kindle
#

Alright.

woeful spindle
thorny kindle
#

Ah

#

i think i understand

#

so im only putting in half of what i need to do, i need to mention a user

#

but how do i put the user in?

woeful spindle
#

youre in a kick command right?

thorny kindle
#

Yea

woeful spindle
#

how are you kicking the user?

thorny kindle
#

with await member.kick()

woeful spindle
#

.rtfm discord.Member.kick

winter condorBOT
woeful spindle
#

so member is your instance of discord.Member

thorny kindle
#

Ok

woeful spindle
#

you can use discord.Member.send to send them a dm, but remember to use your instance

thorny kindle
#

Alright

#

Ahhh i think i see what i did then

#

So i used member as a placeholder for the user, But then i used a different placeholder for the dm so it could kick but not find who to dm.

#

oh. I changed it too:

  await discord.Member.send(f"You have been kicked for {reason}")

And

  await discord.Member.send(content=f"You have been kicked for {reason}")

but none worked

woeful spindle
#

you’re calling .kick on a member object, with the same member object, you can call .send to send a DM

thorny kindle
#

Im confused, Isnt that what i did in what i just sent with discord.Member.send?

woeful spindle
thorny kindle
#

Yea.

#

Wait, so it needs a instance and a class

#

but isnt the message the instance?

#

forget what i said. 2am reading dont work. Ill read it again and try and make more sence of it

#

So im missing something to make discord.Member a instance then

woeful spindle
# thorny kindle Yea.

right.. to kick a user in a guild, you need to have a discord.Member object which you clearly have, then you would call the following in your code:

await <discord.Member object>.kick()

if you compare the difference between the above code and your code, you should know what your member object is defined as (it replaces <discord.Member object>)

to send a DM to a user, you are able to call discord.Member.send as shown below:

await <discord.Member object>.send("Hey! This is a DM.")

as discord.Member is a class rather than an instance, you are required to replace it with the member object which you have

I can’t really put this any other way without spoon feeding (kinda already am)

thorny kindle
#

So does <discord.Member object> just mean the user i mention then. But the object has to be there otherwise its incomplete?

woeful spindle
#

define "the user i mention then"

#

the object which you call .kick one is the same object you call .send on

thorny kindle
#

So if i did /kick @thorny kindle, @thorny kindle would be discord.Member

#

But thats only a class. So the object completes it

woeful spindle
#

a user mention & user object are 2 completely different things

thorny kindle
#

oh

#

Im gonna go watch some videos on this before i go to bed, Hopefully by the morning ill understand what it all is, Sorry for any problems ive caused. Just gotta hope by morning i know what im doing.

Thank you so much for your help!

limber urchin
#

Read rule 1 in #help-rules

thorny kindle
#

Oops, sorry

young flint
#

was anything changed to commands.FlagConverter ?

#

mine doesnt work anymore

#

and im also getting TypeError: Flag.__init__() got an unexpected keyword argument 'name'

#
class StatsFlags(commands.FlagConverter, delimiter=" ", prefix="-"):
    d: Optional[str]  # Detailed
``` this is my code that's been working well for over a year, not sure what could have went on...
limber urchin
#

There's nothing about it in the changelogs NPCMechanicShrug maybe someone changed it without documenting

young flint
#

I read through both dpy and pycord changelongs just incase

limber urchin
#

But you didn't update? Or does it work with older versions?

young flint
#

and saw nothing

limber urchin
#

Hm, no clue tbh

young flint
#

same thing I said

#

i didnt even provide a "name"

#

idk what it's bugging at

young bone
#

For what is this btw?

#

It comes if you run pycord V3

young flint
# plain sail full error trace?
Traceback (most recent call last):
  File "C:\Users\Ghoul\Documents\TeamMai\Mai\mai.py", line 254, in cog_watcher_task
    self.load_extension(extension_name)
  File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 910, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 777, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.Osu.Osu' raised an error: TypeError: Flag.__init__() got an unexpected keyword argument 'name'
Traceback (most recent call last):
  File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 774, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Ghoul\Documents\TeamMai\Mai\cogs\Osu\Osu.py", line 50, in <module>
    class StatsFlags(commands.FlagConverter, delimiter=" ", prefix="-"):
  File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\flags.py", line 335, in __new__
    for flag_name, flag in get_flags(attrs, global_ns, local_ns).items():
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\flags.py", line 168, in get_flags
    flag = Flag(name=name, annotation=annotation, default=flag)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Flag.__init__() got an unexpected keyword argument 'name'

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

Traceback (most recent call last):
  File "C:\Users\Ghoul\Documents\TeamMai\Mai\mai.py", line 254, in cog_watcher_task
    self.load_extension(extension_name)
  File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 910, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 777, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.Osu.Osu' raised an error: TypeError: Flag.__init__() got an unexpected keyword argument 'name'
plain sail
#

hm

#

could very well be a bug

limber urchin
# young bone For what is this btw?

Clients are limited to 1000 IDENTIFY calls to the websocket in a 24-hour period. This limit is global and across all shards, but does not include RESUME calls. Upon hitting this limit, all active sessions for the app will be terminated, the bot token will be reset, and the owner will receive an email notification.
Might be this

plain sail
#

could try doing a git bisect if you really wanna find out

young flint
#

lol

#

that's probably not needed

#

but from what im seeing

#

I think this was updated

#

but not documented

#

i think you're supposed to actually use discord.ext.commads.flag

#

but im not sure how...i dont see any args for delimiters or prefixes

#

so probably not that actually

silver moat
#

.rtfm slashcommand.mention

winter condorBOT
silver moat
#

.rtfm applicationcontext.command

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

silver moat
final fractal
#

.rtfm status

limber urchin
#

"not working" doesn't say anything. Explain what is wrong

#

Yeah, it's not a coroutine

#

You have already been told how to

#

Because your code is wrong

#

get_application_command is not a coroutine

dreamy mauve
#

interaction.response.send_message() returns nothing. Is there a way to get the interaction message?

proud mason
#

.rtfm interaction.original_response

winter condorBOT
obtuse cairn
#

Hi, I'm trying to create a Slash Command that allows users to set a role icon by uploading an image attachment in the command
The issue is that the icon appears to be low resolution, and also lacks a transparent background

@discord.slash_command(description="Create and adjust a custom role")
    async def custom_role(self, ctx, icon: Option(discord.Attachment, required=False)):
      role = await guild.create_role(name="Test")
      await role.edit(icon=await icon.read())
#

I tried to write the bytes object to file by using the following code

with open("icon.png", "wb") as binary_file:
            binary_file.write(icon_byte)

and got the following result

limber urchin
#

You should probably use an image processing library for that, like PIL.

obtuse cairn
limber urchin
#

I mean to create the file that gets uploaded, instead of just writing raw binary

obtuse cairn
#

I thought that the role icon needs to be a bytes object

#

Never mind, it might be an issue with the image

glossy sand
#

Do you need presence intent to get a user object from id?

await bot.get_user(id)

returns None when I disable it

limber urchin
#

get_user is not a coroutine, and it only gets from the bots cache

#

.rtfm discord.Bot.get_or_fetch_user

boreal dust
#

i want to create a database

boreal dust
limber urchin
boreal dust
#

i have a website

#

I eant to use php to fetch user, server … count

limber urchin
boreal dust
#

in the same file?

limber urchin
#

Yes?

#

Which files you use doesn't make a difference at all

boreal dust
#

i mean

#

can i make a loop?

limber urchin
#

make a loop?

boreal dust
#

Ext.loop

limber urchin
#

I don't see a reason to, but sure

boreal dust
#

so it is updated every 10 minutes

#

wait

#

it gets values on web load?

limber urchin
#

That entirely depends on how you set up the API

boreal dust
#

bryh that males sende

#

thanks

#

i used Quart before

#

and i wasnt abkw to start both

limber urchin
#

You can get the bot's event loop through discord.Bot.loop
And then just do something like

my_web_server = MyWebServer()
bot.loop.create_task(my_web_server.start())
boreal dust
#

👍 ❤️

west quest
#

Hi, can someone tell me how I can start a task after the bot comes online?

#

i have a expire_invite.start() over here

boreal dust
#

Await task.start()

west quest
#

but I need to fetfch a guild

#

👍

boreal dust
#

Cant you just pass args?

west quest
#

I would need to wait for the bot to start up

#
        self.expire_invite.start()
        self.check_invite.start()

    # Does for manual invites too, so not removing it
    @tasks.loop(hours=12)
    async def expire_invite(self):
        guild = self.bot.get_guild(self.bot.config["guild_id"])
        member_alerts_channel = discord.utils.get(guild.channels, id=self.bot.config["member_alerts"])```
#

this is a snippet of what im tryna do

limber urchin
#

.rtfm discord.Bot.wait_until_ready

limber urchin
#

Maybe this is useful?

proud mason
west quest
#

yep thanks!

static juniper
#

how to make a sub command inside a command with same arguments

static juniper
errant craneBOT
#

Here's the slash groups example.

#

Here's the slash cog groups example.

static juniper
#

ty

proud mason
#

Examples for both, cogs and normal ^

proud mason
fringe socket
#

Anybody know how to make an emoji message jump link?

#

There's one in #server-announcements message

proud mason
#

but im not sure

#

it might be this [emoji](link)

#

but i thought that only works inside embeds

errant craneBOT
#

src/main/java/com/jagrosh/giveawaybot/commands/RerollMessageCmd.java line 102

+ " [\u2197](" + String.format(JUMP_LINK, interaction.getGuildId(), interaction.getChannelId(), msg.getIdLong()) + ")") // ↗```
proud mason
#

but i recently came to know messages sent via webhooks or interactions allow it too

#

cool

#

how do i get the try_after in HTTPException ?

static juniper
#

when i try it throw me an error

limber urchin
#

show your code

static juniper
#

and bot.add_application_command(blacklist) at the bottom

limber urchin
#

You're using the create_group method completely wrong

#

.rtfm discord.Bot.create_group

lost lodge
#

Heyyy, how can I make a select menu so that when you select an option it automatically becomes unselected?

static juniper
limber urchin
#

Look at the examples and read the docs

static juniper
limber urchin
static juniper
#

oh

limber urchin
#

Read the docs

static juniper
#

ty i just know how to do now

upper echo
#

what should i set the guild value to be such that by default given a guild id it will be automaticaly only showing that and if the user does not have access thay should not be able to add the bot

verbal marten
polar plume
#

Anyone got a scalable file structure template?

cyan quail
lost lodge
cyan quail
upper echo
#

also im by default the bot is not part of the server

cyan quail
#

you can use bot.get_guild(id)

#

though note that you technically don't need a guild object; you can create an arbitrary discord.Object with id=... and pass it in

cyan quail
#

well just call it exactly like that

#

discord.Object(id=...)

proud mason
#

discord.Object(id) was the sexiest thing man had seen

cyan quail
#

ah i forgot it's positional

#

fair enough

upper echo
#

thx Om & Nelo it works

modest turtle
#

hello, how to use pycord with aiomultiprocess to like avoid API limitation

import aiomultiprocess as amp, os

@client.event
async def on_ready():
    guild = client.get_guild(guild_id)
    legend_role = guild.get_role(role_id)

    async with amp.Pool(os.cpu_count()) as pool:
        async for color in asyncgen_color_seq
            await pool.apply(legend_role.edit, kwds={"colour": color})

# this code should call cores asynchonly i.e. when first core is processing the request you call second one

#

oops

full basin
#

Why would you want to avoid api ratelimits

modest turtle
full basin
#

Ratelimits exist for a reason

modest turtle
#

but when I do it in common way feels like 10fps

full basin
#

You're not meant to avoid them

modest turtle
#

no, it's not like ratelimits I guess

#

pycord made that way to interact with discord with async/await

#

but you know when I send request (to change the role for instance) not the bot, but my PC proceeds it and takes some runtime so using threading makes no sense

#

multiprocessing should help me to short the latency

#

(aiomultiprocess, not the synchronous one)

#

:(

polar plume
#

Hello, I'm getting this error;

AttributeError: 'Bot' object has no attribute '_CogMixin__extensions'
#

I'm trying to use load_extension method of bot

full basin
#

Can't help with no code.

modest turtle
polar plume
# full basin Can't help with no code.
import os
from dotenv import load_dotenv
load_dotenv()

from src import Bot

bot = Bot()

cogs_list = [
    'greetings',
    'owner',
    'errors'
]

for cog in cogs_list:
    bot.load_extension(f'src.cogs.{cog}')

bot.run(os.environ('TOKEN'), reconnect=True)
#

and my Bot class;

import discord

class Bot(discord.Bot):
    def __init__(self):
        self.Version = "0.1.0"
        
    async def on_ready(self):
        await print(f"{self.user} is online.")
full basin
#

You didn't super().init

modest turtle
#

you forgot the dot

#

.src.cogs

full basin
#

That's not even the issue lol

modest turtle
#

without it you just load /src/cog instead of {filepath}/src/cog

#

as I see

full basin
#

But that's not the issue as I said

modest turtle
#

try to reinstall pycord from github

full basin
modest turtle
#

maybe something went wrong or I don't have any ideas

#

sooooooooooooooooo, who can help me pls?

#

question is above

hushed jasper
#

As im learning python, i have some issues. How can i fix this issue

full basin
#

Congrats you leaked your token

#

Reset it

#

And show your pip list

polar plume
#

dude a new error spawned after i added the super part

#

discord.errors.ExtensionFailed: Extension 'src.cogs.greetings' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'

full basin
#

Show your code dude

hushed jasper
hushed jasper
full basin
#

Your token

polar plume
# full basin Show your code dude
import discord

class Bot(discord.Bot):
    def __init__(self):
        self.Version = "0.1.0"
        super().__init__()
        
    async def on_ready(self):
        await print(f"{self.user} is online.")
full basin
hushed jasper
#

alr i did that

full basin
full basin
polar plume
#

latest prob, installed it today

hushed jasper
full basin
polar plume
#
import discord
from discord.ext import commands

class Greetings(commands.Cog):
    
    def __init__(self, bot): 
        self.bot = bot

    @commands.command() # creates a prefixed command
    async def hello(self, ctx): # all methods now must have both self and ctx parameters
        await ctx.send('Hello!')

    @discord.slash_command() # we can also add application commands
    async def goodbye(self, ctx):
        await ctx.respond('Goodbye!')

    @discord.user_command()
    async def greet(self, ctx, member: discord.Member):
        await ctx.respond(f'{ctx.author.mention} says hello to {member.mention}!')

    @commands.Cog.listener() # we can add event listeners to our cog
    async def on_member_join(self, member): # this is called when a member joins the server
    # you must enable the proper intents
    # to access this event.
    # See the Popular-Topics/Intents page for more info
        await member.send('Welcome to the server!')

def setup(bot): # this is called by Pycord to setup the cog
    bot.add_cog(Greetings(bot)) # add the cog to the bot
full basin
#

#help-rules 1

hushed jasper
polar plume
#

i mean i iinstalled it today, so it should be latest right?

hushed jasper
#

yeah

full basin
hushed jasper
full basin
full basin
hushed jasper
full basin
#

Indeed, don't expect help.

hushed jasper
#

alr, wish me luck

#

i'll need it

polar plume
full basin
#

Then you use a commands.Bot instance

polar plume
#

okay Sir, thanks for your help < 3

polar plume
proud mason
dapper flare
#
    try:
        await ctx.respond(f'{ctx.author.mention} {response}')
    except:
        with open("tempfile.txt", "r+") as tf:
            tf.write(response)
            await ctx.respond("here is your answer: ", file=discord.File(tf))
        os.remove("tempfile.txt")```

anyone know what's wrong here, i am trying to create a temp text file if the discord bot is unable to send it, so it can send the text in the file
cinder pilot
#

hi so I was wondering how to make a slash command without the sub command
Like I want to have a command /parent and command /parent command1 but I don't see how I am able to make these

#

In the example they used discord.SlashCommandGroup("math","Commands related to math.")
and makes a command /math add

#

but how would I make a command /math along with it (to maybe give like an info about the command)

thorny kindle
#

How can i figure out what the "object" should be on this:


 await <discord.Member object>.send(f"You have been kicked for {reason}")
ruby palm
proud mason
proud mason
#

if that doesnt work, then you best bet is doing math help or smth

cinder pilot
#

shows error

#

guess it's not possible

ruby palm
#

What error do you get?

Because when I use this:

@bot.command(name="math", guild_ids=[...])
@option(
    name="operation",
    choices=[
        "add",
        "subtract"
    ],
    required=False
)
async def math(ctx: discord.ApplicationContext, operation):
    if not operation:
        await ctx.respond("This explains the command")
    else:
        await ctx.respond(f"You chose: {operation}")

It works perfectly fine.

dim cape
fervent cradle
#

Hi, I wanted to know if there's a method to check a role's permission for a specific text channel. In other words, if there's a method to know whether a particular role has a certain permission in a specific text channel.

loud holly
dim cape
#

.rtfm get_role

winter condorBOT
fervent cradle
fleet phoenix
#
    @commands.slash_command(guild_ids=[guild_id])
    @commands.guild_only()
    @commands.has_permissions(ban_members=True)
    async def poll(self, ctx, intrebare, optiune1, optiune2):
        await ctx.respond("✅", ephemral = True)

Isn't this how you give hidden replies back ?

TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'ephemral'
loud holly
#

ephemeral

fleet phoenix
#

fu** i'm stupid. thanks

loud holly
#

yes literally what i have pointed out

#

use if statements to get the perms u r finding

fervent cradle
#

Ah right. Was a bit confused. Thanks.

#

I was thinking if there was a way to do it without an if statement (if I could pass the perm I'm looking for as a parameter maybe?), lol.

rare ice
#

When editing ClientUser using bot.user.edit, avatar requires a bytes-like object. I have a slash command with a discord.Attachment option, how would I make that discord.Attachment a bytes-like object?

proud mason
#

.rtfm attachment.read

winter condorBOT
proud mason
rare ice
#

o

warm kindle
#

how can i find a user that is not cached by id or username?

silver moat
full basin
#

.rtfm fetch_user

warm kindle
silver moat
#

if you are trying to find the user, what do you know about the user?

warm kindle
#

anything

fervent cradle
#

They mean to ask that if you don't know the user's ID or username, is there anything else at all that you know about the user?

warm kindle
#

no i am trying to make a simple avatar command. i want to show avatar by user id, name or nickname

silver moat
#

Does your command take any parameters?

warm kindle
silver moat
#

Do you know which user's attributes you want to access?

warm kindle
silver moat
#

Are you looking for the command's author or is that provided by the author?

warm kindle
cinder pilot
silver moat
#

simply, user.avatar.url

cinder pilot
warm kindle
#

i want to return the avatar of a user that may not be in the cache

cyan quail
warm kindle
#

i think no

cyan quail
#

i mean it is... only with ID though

warm kindle
#

i want it to be possible by username too

silver moat
#

aren't they always cached?

cyan quail
#

you can't request any user just from username alone

cyan quail
proud mason
proud mason
#

Iirc

warm kindle
#

so is it not possible to find a user that is not cached by username?

cyan quail
#

you can

#

you can fetch any user on discord by ID

cinder pilot
warm kindle
#

bad

proud mason
cyan quail
proven canopy
#

Is it possible to mention slash commands with pre-filled arguments?

proven canopy
#

thanks

echo egret
#

how do I convert a datetime object into something like this <t:1672350806:D>

limber urchin
#

Parse the datetime object to an int and add it between <t: and :D>

full basin
#

Don't you have to .timestamp() it

warm kindle
#

how can i return bot invite url?

echo egret
silver moat
#

.rtfm utils.oauth

winter condorBOT
silver moat
warm kindle
#

thx little squid

silver moat
#

np

warm kindle
#

how can i do allowed mentions (user)

full basin
#

Have you tried reading the docs

#

There's usually plenty of info about the library there

warm kindle
full basin
#

.rtfm AllowedMentions

full basin
#

You sure bout that?

warm kindle
#

yes

astral mist
#

how should i deal with this

#

because if i set everything on a new line

#

it will not end up good

young bone
#

py```
"""
Text

"""

#

@astral mist

astral mist
#

welp

#

some things u cant have in life ig

young bone
#

oof

young bone
astral mist
proud mason
warm kindle
#

.rtfm permissions

astral mist
warm kindle
#

How can I return a list of user permissions? (I tried discord.abc.GuildChannel.permissions_for(message.author.id)) and it wasn't

silver moat
#

.tag oop

winter condorBOT
#

https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html

There's a difference between a class and an instance. Think of it like this:

  • A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
  • An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.

Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.

mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.

There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.

upper echo
#

could someone pls explain how i can make a bot to use oath2 code grant?

limber urchin
#

For what purpose?

upper echo
west vault
#

??

narrow nexus
#

how would i make a basic word blacklist? I tried using on_message but that doesn't detect the word

fervent cradle
#

How can i send a modal in a normal select view

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(
            discord.ui.InputText(
                label=config.QUESTION_ONE,
                placeholder="Please put your discord ID",
            ),
            discord.ui.InputText(
                label=config.QUESTION_TWO,
                placeholder="Please put your age!",
            ),
            discord.ui.InputText(
                label=config.QUESTION_THREE,
                placeholder="Please put your Country & Time Zone",
            ),
            discord.ui.InputText(
                label=config.QUESTION_FOUR,
                placeholder="Please put your job or education",
            ),
            discord.ui.InputText(
                label=config.QUESTION_FIVE,
                placeholder="Please fill this out fully!",
                style=discord.InputTextStyle.long,
            ),
            *args,
            **kwargs,
        )

    async def callback(self, interaction: discord.Interaction):
        channel = bot.get_channel(STAFF_APP_LOGS)
        embed2 = discord.Embed(
            title=f"Your Staff Application --> {ticket.mention}",
            fields=[
                discord.EmbedField(
                    name=config.EMBED_ONE, value=self.children[0].value, inline=False
                ),
                discord.EmbedField(
                    name=config.EMBED_TWO, value=self.children[1].value, inline=False
                ),
                discord.EmbedField(
                    name=config.EMBED_THREE, value=self.children[2].value, inline=False
                ),
                discord.EmbedField(
                    name=config.EMBED_FOUR, value=self.children[3].value, inline=False
                ),
                discord.EmbedField(
                    name=config.EMBED_FIVE, value=self.children[4].value, inline=False
                ),
            ],
            color=discord.Color.random(),
        )
        await channel.send(embed=embed2)
        embed = discord.Embed(description=f'📬 Ticket was Created!', color=0xe800ff)
        await interaction.response.send_message(embed=embed, ephemeral=True)```**MODAL**
#
    async def fifth_button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
        if "support5" in interaction.data['custom_id']:
            if interaction.channel.id == TICKET_CHANNEL:
                guild = bot.get_guild(GUILD_ID)
                ticket_owner = interaction.user
                for ticket in guild.channels:
                    if str(interaction.user.id) in ticket.name:
                        embed = discord.Embed(title=f"You can only open one Ticket", description=f"Here is your opened Ticket --> {ticket.mention}", color=0xff0000)
                        await interaction.response.send_message(embed=embed, ephemeral=True)
                        return

                modal = MyStaff(title="Staff Application")
                await interaction.response.send_modal(modal)

                open_ticket = bot.get_channel(LOG_CHANNEL)

                category = bot.get_channel(CATEGORY_ID4)
                ticket_channel = await guild.create_text_channel(f"ticket-staff-application-{ticket_owner}", category=category,
                                                                    topic=f"Ticket from {interaction.user} \nUser-ID: {interaction.user.id}")
                await ticket_channel.set_permissions(guild.get_role(STAFF_APP_TEAM), send_messages=True, read_messages=True, add_reactions=False,
                                                        embed_links=True, attach_files=True, read_message_history=True,
                                                        external_emojis=True)
                await ticket_channel.set_permissions(interaction.user, send_messages=True, read_messages=True, add_reactions=False,
                                                        embed_links=True, attach_files=True, read_message_history=True,
                                                        external_emojis=True)
                await ticket_channel.set_permissions(guild.default_role, send_messages=False, read_messages=False, view_channel=False)
                embed = discord.Embed(description=f'Welcome {interaction.user.mention}!\n'
                                                   'Please wait while we review your answers!',
                                                    color=config.EMBED_COLOR)
                embed2 = discord.Embed(description=f'We have received your staff application answers.\n'
                                                   'Please wait, we will get back to you shortly',
                                                   color=config.EMBED_COLOR)
                await ticket_channel.send(embed=embed2)

                await ticket_channel.send(embed=embed, view=TicketClose())
                embed3 = discord.Embed(title='**Ticket Opened**', description=f"{ticket.mention} Was created!", color=config.EMBED_COLOR)
                await open_ticket.send(embed=embed3)
                return``` **TICKET**
winter condorBOT
spare juniper
proud mason
#

You can do if any((word in msg.content for word in ban_words_list))

#

Else you can straight up use regex and it will be the fastest and most efficient

limber urchin
#

Typically speaking, regex will be slower. But it requires a lot less code, and the speed difference usually isn't that vital unless you're checking thousands of messages every second.

proud mason
#

I thought regex will be faster if you have a compiled search pattern, considering that you are checking a whole list of words

limber urchin
#

Yeah, it of course depends on what you're checking. But from what I've seen regex is usually slower, but more suited for complex pattern checks that would be too tedious to code with regular checks. And it's a matter of milliseconds anyways, so you should just use whatever suits the situation better.

proud mason
#

Hmm true doggokek

vapid pumice
#

Do discord model buttons follow different parameters than normal buttons?
I'm trying to disable one on button click using

button.disabled = True
await interaction.followup.edit_original_message(view = self)

but I'm getting AttributeError: 'Webhook' object has no attribute 'edit_original_message'

silver moat
vapid pumice
polar plume
#

Hello, How do i set activity of my bot?

silver moat
#

.rtfm bot.activity

silver moat
#

yes

#

you can mention slash command

#

.rtfm slashcommand.mention

winter condorBOT
undone falcon
#

thanks !

polar plume
silver moat
polar plume
#

I did try something like that but doesn't show any activity to my bot

#
activity = Activity(name='Anime', type=ActivityType.watching)
bot = Bot(activity= activity)

Bot Class

class Bot(discord.Bot):
    def __init__(self, *args, **kwargs):
        self.Version = "0.1.0"
        super().__init__(args=args, kwargs=kwargs)
silver moat