#Basic Pycord Help (Quick Questions Only)

1 messages · Page 85 of 1

zealous bear
#

i tried upgrading it to work in 3 different channels at once but now it is broken

#

just not posting at all

#

and i've tried debugging already

#

it has it stored in the DB just fine

#

but its not posting

versed fern
#

please give your tasks actual names

versed fern
#

very descriptive name actually better, but still

#

What exaclty isn't working?

zealous bear
#

but not posting in the channels

#

at all

#

how do you cross out something like that

versed fern
#

~~My Text~~

zealous bear
#

my text

versed fern
#

If the channel isn't in cache, bot.get_channel(channel_id) is going to return None

#

You should fetch the channel instead

#

channel = await utils.get_or_fetch() would be best since it doesn't make API calls if not necessary

#

.rtfm get_or_fetch

glossy forum
#

Is there a build-in class/function for the help command in form of a slash command?
Docs says it's recommended to use the build-in solution, but that class is build to be used as a classic/prefixed command, from what I see
Asking in case I can save myself from reinventing the wheel

zealous bear
#

which is why this is so weird haha

#

TypeError: get_or_fetch() missing 2 required positional arguments: 'attr' and 'id'

versed fern
#

Take a look at the example

zealous bear
#

.rtfm get_or_fetch

zealous bear
#

?

#

channel = await discord.utils.get_or_fetch(server, 'high-tier-items', HIGH_TIER_ID, default=None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/utils.py", line 614, in get_or_fetch
getter = getattr(obj, f"get_{attr}")(id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'get_high-tier-items'

#

nope

versed fern
#

you're trying to get/fetch a channel, not "low-tier-items"

zealous bear
versed fern
#

but pycord doesn't know this (not before getting the channel)

#

you have to specify the type of object you want to return

#

in your case, a channel

zealous bear
#

OH

#
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/tasks/__init__.py", line 169, in _loop
    await self.coro(*args, **kwargs)
  File "/Users/jef/Desktop/employee.py", line 712, in lowtask
    channel = await discord.utils.get_or_fetch(server, 'channel', LOW_TIER_ID, default=None)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/utils.py", line 614, in get_or_fetch
    getter = getattr(obj, f"get_{attr}")(id)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'get_channel'
zealous bear
versed fern
#

basically, what happens is this:
You set serveras the object here:

channel = await discord.utils.get_or_fetch(server, 'channel', LOW_TIER_ID, default=None)

Then, the library does the following:

channel = object.get_channel(channel_id)
if not channel:
  channel = await object.fetch_channel(channel_id)

Since server is a list of server_ids (Please name your variables accurately, sth like allowed_server_ids would be more fitting), but this list doesn't have the method get_channel, guilds do

zealous bear
versed fern
#

not an id

#

a guild

clear vault
#

What does that mean:
Cant Connect to Discord. Too many Files opened

versed fern
#

or a bot object

zealous bear
versed fern
#

Do you know what a method is?

young bone
zealous bear
versed fern
#

get functions won't work if it's not in the cache

#

talking to zerv

#

?tag lernpython

obtuse juncoBOT
#

dynoError No tag lernpython found.

zealous bear
versed fern
#

zerv, u know the tag?

#

?tag learnpython

obtuse juncoBOT
#

To be clear:

When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.

We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.

versed fern
#

let's just ignore my typo

zealous bear
#

i've only been programming overall for 3 weeks 😭

#

where can i learn about OOP (dont know what that is), and Async/Await

versed fern
#

It's really hard to help you without you knowing basic OOP

young bone
versed fern
#

my bad

#

OOP is object oriented programming

zealous bear
#

so i can fix it and then

#

go learn python

versed fern
#

but that won't help you in the long run

zealous bear
versed fern
#

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

clear vault
#

What does that mean:
Cant Connect to Discord. Too many Files opened

rare ice
#

When in doubt, Google it.

clear vault
#

Hmm okay. Nice help

rare ice
#

I mean, Google it more accurate.

zealous bear
#

That's a google question IMO

rare ice
#

Kind of like “ask 3 before me” but “ask the damn machine that does everything before me”

clear vault
#

So why does this section exist if you can google anyway? pog

versed fern
#
    thread_group = discord.SlashCommandGroup(
        name="thread",
        description="Group of thread commands!",
        default_member_permissions=discord.Permissions(administrator=True)
    )

    thread_directory_group = discord.SlashCommandGroup(
        name="directory",
        description="Group of thread directory commands!",
        parent=thread_group
    )

    @thread_directory_group.command(name="add", description="Adds the thread to the thread directory!")
    async def thread_directory_add(self, ctx: discord.ApplicationContext,
                                   thread: discord.Option(discord.Thread, "Please enter the thread!", required=False)):

Any ideas why /thread shows up but not /thread directory add?

young bone
#

Its even in the help rules Nr. 2 #help-rules

rare ice
versed fern
#

thx

rare ice
#

.rtfm discord.SlashCommandGroup.create_subgroup

winter condorBOT
zealous bear
#

how do i have a guild object without an ID

versed fern
#

guild objects do have an id, tho get_or_fetch requires a guild object and not guild.id

clear vault
#

@rare ice Is there a way to send async webhooks with pycord. I think that is the problem.

rare ice
winter condorBOT
zealous bear
#

what is a guild object

rare ice
clear vault
young bone
#

@clear vault maybe this one is helping?

clear vault
#

Thanks

drowsy hound
#

is it possible to respond with an ephemeral message on the "on_message" event?

silver moat
drowsy hound
#

thanks

zealous bear
zealous bear
#

should i fetch it instead?

full basin
#

I'm sure get_guild isn't a coro

spring hare
#

is Embed.from_dict save? (Do I need some json validation, if I get it from users)

zealous bear
#

What’s a coro?

full basin
zealous bear
#

I’m like 40%?

full basin
#

Asynchronous functions are called coroutines

spring hare
zealous bear
rare ice
#

"Try it and see"

spring hare
rare ice
#

wdym abuse it wtf

#

Try it and see

#

read that

#

try it

spring hare
rare ice
#

wtf are you talking about

spring hare
#

💀

#

Nevermind bruh

rare ice
#

SQL has nothing to do with that we're talking about

#

bruh is that your favorite word?

silver moat
#

deploy it and see if it breaks

rare ice
#

god damn children

silver moat
rare ice
#

^^^^^^^^^^^^^^^

#

people don't know how to read i swear

#

usually people under 13 :/

#

not gonna make out any names

tardy wind
#

~~pulling my hair out a little bit here.

message = output_character(codename, ch)
    try:
        await ctx.respond(message)
    except discord.errors.HTTPException as e:
        with open("message.txt","w") as file:
            file.write(message)
        await ctx.respond("The message is too long to send. Please view the attached file.",file=discord.File('message.txt'))
        os.remove('message.txt')
        log("Sent character sheet as file")

this is a snippet of code at the end of a slash command call. output_character assigns the raw string I want to send to the user to message. in this context, message can be quite long, sometimes exceeding 2000 chars. the idea here is for the bot to send the message content as a file instead of a message body if the initial ctx.respond fails.

the kicker is this:
i have 2 versions of my bot: one for testing, and one for actual member-facing use.

  • on my testing bot, this works fine. if message content exceeds 2000 chars, it's sent as a file instead, exactly as i want.
  • on my main bot (which is verified by discord), HTTPException: "Must be 2000 or fewer in length" is thrown and the command fails unconditionally if message has a length above 2000.~~
#

i have no idea what the issue is here. even when both bots are running the exact same code they perform differently.

#

i've also attempted to do this via checking len(message) > 2000 beforehand and got similar results

#

oh fucking hell. nevermind. git issue. i've been working on the wrong branch this entire time

silver moat
#

average git

tardy wind
#

"i dont need to delete the branch yet it'll be fine"
i would like to travel back in time about 1 hour and strangle that version of myself rq

silver moat
#

then that version of yourself will travel forward in time about 1 hour and strangle that version of yourself that tried to strangle that version of yourself

tardy wind
round rivet
round rivet
#

data loss

low dune
#

i need help using pycord with a tkinter gui

drowsy hound
#

What's the best way to warn users with a moderation bot? I mean, if the bot detects a bad word, how do you warn the user about his behaviour? Via private message?

silver moat
#
  1. Ping them in the channel that they were warned in
  2. DM them
  3. Log the warn
#

all three should be done

versed fern
waxen whale
fervent cradle
#

I have a command and I respond to the command like this:

msg = interaction.respond(embed=embed)

works fine. then I wait for a user Input. That works also fine. Now I want to edit the message. How can I do it?

with msg.edit(embed=emb)
?

waxen whale
#

read the docs KagamiSigh

fervent cradle
#

Yes yes

#

But sometimes this way is faster

proud mason
fervent cradle
#

Thanks

woven basin
#

For some reason I get an error: discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction , while trying to send an embed?

#
@bot.slash_command()
@option("by", description="Search from ISBN, Name, or Author", choices=["ISBN", "Title", "Author"])
@option("value", description="Enter the relevant term for your search")
async def search(
    ctx: discord.ApplicationContext, by: str, value: str,):
    url: str = f"https://openlibrary.org/search.json?{by}={value}".lower()
    response = requests.get(url)
    data = response.json()

    # Check if there are any documents in the response
    if "docs" in data:

        # Iterate over the documents
        for doc in data["docs"]:
            # Check if the document has a language field
            if "language" in doc and len(doc["language"]) == 1 and doc["language"][0] == "eng":
                # Check if the document has an ISBN
                if "isbn" in doc:
                    # Grab the ISBN and print it
                    isbn = doc["isbn"][0]
                    print("ISBN:", isbn)
                    embed = discord.Embed(title="Located Book", description=f"I found a book with the ISBN: {isbn}")
                    embed.set_author(name=f"Search by  for '{value}'")
                    await ctx.respond(embed=embed)
                    break  # Exit the loop since we found the desired document
        else:
            print("No English document found.")
    else:
        print("No documents found in the response.")
#

Works fine if there is no embed response, and if it is just printed

young bone
#

?tag requests

obtuse juncoBOT
#

Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.

This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.

Please look at using a HTTP library that has async support, such as aiohttp or httpx

woven basin
young bone
#

Yes

woven basin
#

sorry. haven't bot programmed in a while

young bone
#

If you use requests, its gonna block yout whole bot

maiden nexus
#

hey Zervyel could you look into my help thread? I have no clue what I'm doing wrong and have been stuck on this for a very long time #1121388195322540102

woven basin
#
@bot.slash_command()
@option(name="by", description="Search from ISBN, Name, or Author", choices=["ISBN", "Title", "Author"])
@option(name="value", description="Enter the relevant term for your search")
async def search(ctx: discord.ApplicationContext, by: str, value: str):
    url = f"https://openlibrary.org/search.json?{by}={value}".lower()

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            data = await response.json()

    if "docs" in data:
        for doc in data["docs"]:
            if "language" in doc and len(doc["language"]) == 1 and doc["language"][0] == "eng":
                if "isbn" in doc:
                    isbn = doc["isbn"][0]
                    embed = discord.Embed(title="Located Book", description=f"I found a book with the ISBN: {isbn}")
                    embed.set_author(name=f"Search by for '{value}'")
                    await ctx.respond(embed=embed)
                    
        else:
            print("No English document found.")
    else:
        print("No documents found in the response.")
young bone
#

defer it

woven basin
#

so bot is just slow

#

bummer... idek how to make this faster.

#

I am trying to make a book which has a folder of books, and user can pass a param like ISBN, title or author, and get info about the book, if there is an entry for it on my pc, I can even attach it in the message.

#

sadly, just the remote api takes too long

young bone
woven basin
#

yeah so, just querying the api alone takes 3 seconds.

young bone
#

So you already could send a respond after that edit or send a new message

woven basin
#

perhaps, is there a way to stop reading after some point, and not have to make a request just to pull all this unessecary data

#

Essentially I am grabbing the 0th book, so long as it is "eng"

fervent cradle
#

error:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Messageable.send() got an unexpected keyword argument 'ephemeral'

Code:

 await interaction.channel.send(embed=embed, ephemeral=True)
#

why?

fervent cradle
#

oh

#

and when the interaction got responded before it is interaction.followup.respond right?

young bone
#

Lemme check it

#

Just try it and maybe its gonna work @fervent cradle

fervent cradle
fervent cradle
#

yesterday i caused a war on the python server so ill do it here as well, indent using tabs or spaces?

fervent cradle
#

most ides use fake tabs so it just changes it to spaces

#

pretty sure spaces also let u do indentation like this ```py
foo(
bar, bar1)

true pewter
#

I would like to know how many bots my server has, the only way is as follows?

bots = [member for member in guild.members if member.bot]
full basin
#

Yes

drowsy hound
elfin dagger
#

something like @user don't use those types of words here!

drowsy hound
cyan quail
#

not possible on api

grim tangle
#

How do I do slash commands ?

young bone
grim tangle
#

Thank you :)

#

Can someone explain this to me:

Traceback (most recent call last):
  File "c:\Users\waike\Desktop\Discord Bot\main.py", line 7, in <module>
    bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
PS C:\Users\waike\Desktop\Discord Bot> 
young bone
#

Do you know basic Python?

grim tangle
#

I'm like a above average

young bone
#

Than why did you send a screenshots of what you imported and not the pip list?

grim tangle
#

Oh mb xd

true pewter
#

Is there any way to get information from the server, whether it is a partner, verified or tier premium?
something similar to this?

        guild = ctx.guild
        if guild.partnered:
            print(guild.partnered)
            print(f"{guild.name} is a Discord partner server.")
        if guild.verified:
            print(guild.verified)
            print(f"{guild.name} is a verified Discord server.")
        if guild.premium_tier:
            print(guild.premium_tier)
            print(f"{guild.name} has the level of reinforcement {guild.premium_tier} on Discord.")
young bone
grim tangle
#

ok

young bone
#

also uninstall and only reinstall py-cord 2.4.1

grim tangle
#

What do you mean?

young bone
#

and you have a old version installed

grim tangle
young bone
#

\o

river summit
#

is this a correct way of using perms in a slash command group?

    reaction = discord.SlashCommandGroup(
        name="reaction",
        description="Commands relating to reaction-roles within the guild",
        default_member_permissions=discord.Permissions.manage_guild = True
    )
zealous bear
#

I'm getting the
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
really often, and I don't know how to fix it

#

Is there anyone that will allow me to share my full code to them in DMs to help me out?

young bone
zealous bear
young bone
#

defer it

zealous bear
#

which is why i need to show someone my full code i think

young bone
#

Does it also happend to a basic slash command?

zealous bear
#

commands like that don't fail i dont think

young bone
#

Did you test it?

zealous bear
#

and it didn't fail

#

ill run a more complex command and see if the more complex one fails

young bone
#

And if you just send a respond and a message after that?

zealous bear
#

but usually if i don't use the bot for a while

#

the first command i use after that break will fail

#

and the next will succeed. it's like it has a startup time

young bone
#

How do you host the bot?

zealous bear
#

it's still in development

#

do you think that i should open up a seperate help post for this, as to not misuse this post?

proud mason
#

well host is the issue here. you either have a bad network, or the OS puts the bot to sleep

zealous bear
#

how do i prevent that?

proud mason
#

like you said, the 1st request will "warm-up" the network and process, so the following requests dont fail

zealous bear
#

Well i'm devving it on a mac

#

so 😂 that's probably the issue

proud mason
#

it doesnt do that for me shrug

zealous bear
#

so do you think that i should just host like the parts that are working fully

proud mason
#

try using a process manager. maybe pm2?

zealous bear
silver moat
#

does it say "This interaction failed, or The application did not respond"?

fervent cradle
zealous bear
#

Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

full error

proud mason
young bone
#

I also use PM2 for my Bots

proud mason
zealous bear
proud mason
#

not really. it doesnt need to do that

silver moat
#

as you said it is development, so this probably doesn't matter rn

fervent cradle
zealous bear
fervent cradle
#

is there any other way to get a channel object other than discord.utils.get

young bone
#

there are a few x3

proud mason
zealous bear
#

if its not keeping the bot awake

proud mason
#

it should keep it awake. although it wont hammer the cpu. (not sure about this)

zealous bear
#

i see

grim tangle
#

How to make arguments required (Instend of Optional) in slash commands?

young bone
#

;3

#

or just dont add it

grim tangle
young bone
#

At the Option

grim tangle
#

Okay

silver moat
#

if you are using discord.Option, put it in the constructor, if you are using @option, put it in there

fervent cradle
#

does TextChannel.clone clone the channel in the same category and basically replaces the channel?

cyan quail
#

it's not a replace, it's a new channel with the same attributes (+renaming), same as "Duplicate Channel" on the UI

#

it will be in the same category

fervent cradle
#

so if i clone it and then delete it its basically a replace, will it be in the same position as well?

cyan quail
#

it'll be at the bottom of the category

fervent cradle
#

right, so i still need to move it up

grim tangle
silver moat
cyan quail
#

required is already the default, if it's not then you've done something else wrong

fervent cradle
#

@young bone since u use pm2, how do u check logs? ive done pm2 monit once they were there, then exited and then pm2 monit again and logs are gone?

young bone
#

pm2 logs

grim tangle
# silver moat what is your current code?

I'm fairly new to Py Cord and Python in general so idk

@bot.command(description="Kicks the user from the guild")
@has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
        embed = discord.Embed(
            title="User Successfully Kicked",
            description=f":white_check_mark: {member.mention} has been kicked by {ctx.author.mention}",
            color=discord.Color.teal()
        )
        embed.set_thumbnail(url=ctx.author.avatar.url)
        embed.add_field(name="Username", value=f"`{member.name}`", inline=True)
        embed.add_field(name="User ID", value=f"`{member.id}`", inline=True)
        embed.add_field(name="Punished by", value=f"{ctx.author.mention}", inline=True)
        embed.add_field(name="Reason", value=f"{reason}", inline=False)
        embed.set_footer(text=f"Executed by: {ctx.author.username}")
        await member.kick(reason=reason)
        await ctx.respond(embed=embed)
cyan quail
#

isn't it literally just pm2 logs {process}

young bone
#

^

fervent cradle
#

oh

young bone
#

pm2 -help

fervent cradle
#

well thanks

silver moat
grim tangle
fervent cradle
#

i am free of tmux

silver moat
#

which option is not required rn?

grim tangle
silver moat
#

just remove the *,

grim tangle
#

okay...

young bone
#

Why do you have an * in a slash command?

grim tangle
#

it use to be normal prefixed commands but I changed over

silver moat
#

also, the =None should also be removed if you want it to be required

grim tangle
#

Now I'm getting this:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Member' object has no attribute 'username'

young bone
grim tangle
#

The lastest one (you told me to use)

grim tangle
young bone
#

use .name

grim tangle
#

ok

#

Uhh I don't have member.username anywhere in my code...

grim tangle
young bone
#

what?

fervent cradle
#

maybe show the full error

#

so u see what lines it on

grim tangle
#

It doesn't say

fervent cradle
#

then show the code for the command u ran

grim tangle
#

Okay I didn't really read it...
but it says this...

fervent cradle
#

yeah remove the .username

#

iirc its just ctx.author

grim tangle
#

now I got to remove .username to 20 other commands...... welp ok

fervent cradle
#

if u use vs code just replace it with nothing

#

ctrl shift h

grim tangle
#

hm

#

ty didn't know that

zealous bear
#

can someone help me with the correct way to defer an interaction

fervent cradle
#

.rtfm interaction.defer

winter condorBOT
#

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

zealous bear
fervent cradle
#

.rtfm ctx.defer

winter condorBOT
#

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

fervent cradle
#

bruh

zealous bear
#

.rtfm defer

fervent cradle
#

oh its interactionresponse

zealous bear
#

ill look at the docs

#

yeah my code looks correct based on the docs

proud mason
#

you can even swap out ctx.followup.send with ctx.respond as the library takes care of that for you

zealous bear
#

i made this code so long ago i'm sure its possible and i just was stupid at the time

zealous bear
elfin dagger
zealous bear
#

never heard of that, let me try it thank you!

#
await ctx.respond(content = f"{member.mention}\n", embed = tradeEmbed)
zealous bear
#

like a notification, yellow highlighted message type ping

neon lotus
#

help plz

elfin dagger
#

?

zealous bear
proud mason
#

try using use allowed_mentions

zealous bear
#

There's my name at the top there, but

#

its not a ping

neon lotus
# neon lotus help plz

return compile(tree, filename, "exec")
TypeError: arguments field "args" must be a list, not a NoneType
but there is no list argument wtf

zealous bear
elfin dagger
zealous bear
#

hmmm

#

maybe i move the ping to the bottom of the message

#

would look ugly though

elfin dagger
zealous bear
#

should that do it?

proud mason
#

it doesnt work like that lol

#

.rtfm allowed

proud mason
#

you need to pass the 2nd one

#

also, the parameter name is case sensitive

zealous bear
#

ah damn i was hoping i would finally correctly use the docs

zealous bear
proud mason
#
- AllowedMentions = ...
+ allowed_mentions = ...
zealous bear
#

hold on let me send it

#

bot = commands.Bot(allowed_mentions = discord.AllowedMentions.all, command_prefix = "!", intents=discord.Intents.all(), help_command=None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 124, in init
super().init(**options)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/commands/core.py", line 1225, in init
super().init(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 1132, in init
super().init(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 85, in init
super().init(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/cog.py", line 611, in init
super().init(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 244, in init
self._connection: ConnectionState = self._get_state(**options)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 263, in _get_state
return ConnectionState(
^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/state.py", line 194, in init
raise TypeError("allowed_mentions parameter must be AllowedMentions")
TypeError: allowed_mentions parameter must be AllowedMentions

#

big boy error

proud mason
#

()

zealous bear
#

ooooooh

#

thank you

zealous bear
#

is it because of the defer?

proud mason
#

hmm

#

try passing allowed mentions to ctx.respond

zealous bear
#

that's my code by the way

#

so that this is easier for you

proud mason
#

try this await ctx.respond..., allowed_mentions= discord.AllowedMentions.all())

zealous bear
#

unfortunately

#

no luck

#

maybe its a discord issue

#
await ctx.respond(content = f"{member.mention}\n", embed = tradeEmbed, allowed_mentions = discord.AllowedMentions.all())
proud mason
#

hmm

worldly schooner
#

Do I have to worry about sharding my bot at the start, when its only in like 10 servers? Or can I easily implement AutoSharding later when the amount of servers increases?

proud mason
#

Sharding is only need post 2k servers

#

and it wont even work before that

#

so using AutoShardedBot before that will only cause overheads

worldly schooner
#

alright, tysm!

drowsy hound
#

hello!
How do I make checks before a command kicks in?
I want to only restrict users usage to only users that have a certain role.
Is it also possible to hide it for users without that role?

solemn idol
# drowsy hound hello! How do I make checks before a command kicks in? I want to only restrict...

I would've said you could use discord permissions by using @discord.default_permissions which checks if the user has role permissions. But if its a personal bot you might directly just use discord's feature which allows you to select on your server who is allowed to use what commands (Under integrations tab; works for slash commands, see image)

But if those are definitely not the ways you want to go, you need to make a custom checker which for example checks if user is admin or smth like that.

(checks if the author has role xxx)

drowsy hound
zealous bear
naive remnant
#

How do I send text files

full basin
#

Just like any other file

weak violet
#

how i can get categories without ctx?

categ = discord.utils.get(ctx.guild.categories, id=1103752167095017513)

(is on on_ready)

cyan quail
weak violet
#

i found another way but thanks

cyan quail
#

In on_ready, you can also just use bot.get_channel

#

Oh fair

fervent cradle
#
@bot.slash_command(name = "profile", description = "See a user's Profile.")
async def profile(interaction: discord.Interaction, user: discord.Member = None,):

how do i add a description for the user context menu?

full basin
#

user: discord.Option(discord.Member, "My description", default=None)

somber pelican
#
    @su_group.command(name="db", description="Execute a SQL command (owner only)")
    @is_owner()
    @option(name="sql", type=str)
    async def sql(self, ctx: ApplicationContext, sql: str) -> None:
        result = await self.bot.db.run_raw_sql(sql)
        result_type = type(result)

        embed = await build_embed(
            self.bot.theme,
            "Database Query",
            f"""
**Result**
\`\`\`py
{result}
\`\`\`

**Type**
\`\`\`py
{result_type}
\`\`\`
        """,
        )

        return await ctx.respond(embed=embed)

with this code, i keep getting unknown interactions

#

here's how im using it

proud mason
somber pelican
#

it isnt taking 3s

proud mason
#

the error does indicate that 3s passed before you could respond

somber pelican
#

hm

#

ok thanks

naive remnant
#

How do I send files i used

await ctx.send(file=discord.File("file path"))

But didn't work

proud mason
#

.idw

winter condorBOT
#

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.

naive remnant
#

I mean mistakes

proud mason
#

nothing at first sight

#

what doesnt work?

#

any errors?

naive remnant
#

Wait I'll send the error message

solemn idol
#

Ok so for some reason, passing deug_guild id into my subclass of discord.Bot does not work... and I have no idea why.

"Does not work" --> It doesn't make my commands private.

  • How do I know it doesn't work.
    I have a checker which checks if commands are global or private, I even checked it to see if the Guild which's ID I provided has any private commands (and it has none so my bot's commands are global)

bot.py

import platform
import sys
from datetime import datetime

import colorama
import discord

from core.utils import Log, intents

colorama.init(autoreset=True)
sys.stdout = Log(open('./logs/console.log', 'w'))

class Beanie(discord.Bot):

    async def on_ready(self):
        base_url = discord.utils.oauth_url(self.user.id)
        permissions = discord.Permissions.administrator.flag
        link = f"{base_url}&permissions={permissions}"

        print(colorama.Fore.GREEN + f"\n     ---------")
        print(colorama.Fore.GREEN + f"System-OS : {platform.system()}")
        print(colorama.Fore.GREEN + f"OS-Version : {platform.version()}")
        print(colorama.Fore.GREEN + f"Discord-Tag : {self.user}")
        print(colorama.Fore.GREEN + f"Client-ID : {self.user.id}")
        print(colorama.Fore.GREEN + f"Conected-Guilds : {len(self.guilds)}")
        print(colorama.Fore.GREEN + f"Latency : {round(self.latency * 1000)}ms")
        print(colorama.Fore.GREEN + f"Time : {datetime.now().strftime('%d-%m-%Y %H:%M:%S')}")
        print(colorama.Fore.GREEN + f"Bot-Invite : {link}")

        # Write the list of intents to a file using the Log class
        sys.stdout.write_intents(intents)

        print(colorama.Fore.GREEN + f"     ---------\n")


debug_server = globals().get('debug_server', [])
bot = Beanie(intents=intents, debug_guilds=[1114959767715184730])

Any help is appreciated.

#

documentation even asks for a list with int's so... I am lost at this point.

#

And here's my regcheck.py file (which is run seperately) if you're wondering how I checked for them to be global / private

import requests, os
from dotenv import load_dotenv

load_dotenv()

bot_id = 1234567891011121314

# Replace these values with bot's information
BOT_TOKEN = os.getenv('token')
CLIENT_ID = bot_id

headers = {
    "Authorization": f"Bot {BOT_TOKEN}"
}
GUILD_ID = 1114959767715184730
response = requests.get(f"https://discord.com/api/v9/applications/{CLIENT_ID}/guilds/{GUILD_ID}/commands", headers=headers)

if response.status_code == 200:
    commands = response.json()
    if not commands:
        print("No commands found.")
    else:
        for command in commands:
            print(f"{command['name']}: {command['id']}")
else:
    print(f"An error occurred: {response.text}")

(@solemn idol me if you've got a solution)

naive remnant
proud mason
#

full error please 🙃

naive remnant
#

Okok

naive remnant
# proud mason full error please 🙃

Traceback (most recent call last):
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 184, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\thegi\Desktop\development\chatgpt bot\main.py", line 33, in check
await ctx.send(f"Total detected : {len(list_of_members)}", files=discord.File('log.txt'))
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\abc.py", line 1498, in send
if len(files) > 10:
TypeError: object of type 'File' has no len()

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

Traceback (most recent call last):
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 344, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 951, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thegi\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 193, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'File' has no len()

naive remnant
proud mason
#

files is for sending multiple files

#

it needs a list

somber pelican
#

hey, does ctx.guild.get_member fetch from cache?

proud mason
#

yes get_member will return from cache

somber pelican
#

thanks

proud mason
#

np

naive remnant
solemn idol
#

.tias

winter condorBOT
somber pelican
# proud mason np

so i can rely on the rule of thumb, being get_ for cache and fetch_ for api call?

naive remnant
#

Thanks @proud mason it works have a nice day

solemn idol
somber pelican
#

discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions does this mean i have no perms? or the bot?

#

because me and the bot are 1st and 2nd highest roles respectively, all with admin

#

and im editing a member who doesnt have admin and is the lowest role

#

although all other switches are turned off 🤔

#

that might be it

#

nope

#

any ideas? 😄

full basin
somber pelican
full basin
#

Show code

#

And full traceback

somber pelican
#

yeah one second

#

my code's pretty long

#
        try:
            user = await ctx.guild.fetch_member(int(id))
        except HTTPException:
            raise InvalidId

        if not user.get_role(int(role_data[0])):
            raise NotVerified

        [_, pss_name, __, ___] = await get_user_info_by_name(user.display_name, token)
        roles = []

        for role_id in role_data:
            if not role_id:
                raise NotConfigured

            role = get(ctx.guild.roles, id=int(role_id))

            if not role:
                raise NotConfigured

            roles.append(role)

        await ctx.user.edit(nick=None)
        await ctx.user.remove_roles(*roles)
        await self.bot.db.insert_data_into_table(
            ship_table, {"ships": dumps(ship_data)}
        )

        return await ctx.respond(embed=success_embed)

traceback:
https://sourceb.in/d6LFEzzkIT

full basin
#

You're doing ctx.user.edit

somber pelican
#

oh bruh

#

thanks so much

drowsy hound
#

how do I check if a message is a response to another message?

silver moat
#

as in reply?

drowsy hound
silver moat
drowsy hound
#

oh, that's the name. I couldn't find it. Thanks!

naive remnant
#

Can I make the bot check if someones dm is opened or closed

proud mason
#

You could send a message and handle the error in try-except

#

Or maybe use user.create_dm

#

.rtfm create_dm

drowsy hound
#

how can I read the content of a referenced message? I have the ID, can i get it by ID?

fervent cradle
#

in the on_message_edit even it takes a before and after message and to check if the author is a bot is it as simple as if before.author.bot

fervent cradle
#

so yes

full basin
#

Want me to send the tag again

fervent cradle
#

no just usually when u say it it means a yes

solemn idol
# fervent cradle no just usually when u say it it means a yes

its literally what it says;
Try it and see

If you try it and it works, then it works and the problem is resolved.
If you try it and it doesn't work then we can further assist you as problem solving is usually just trying something different which would make the most sense and then trying it out to see if it works.

fervent cradle
#

i know, it works

drowsy hound
#

Hello, I've been trying out the discord Guild Settings > Integrations feature, but I can't figure out how do "overrides" work. I mean this thing:
Can anyone help me?

solemn idol
#

and see

fervent cradle
#

i did and it works idk what problem there is

solemn idol
#

So there is none and your problem is solved.

In other words : You issue seems to be fixed?

fervent cradle
#

yeah

solemn idol
drowsy hound
#

How does that work? Am I disabling the command for that channel?

solemn idol
# drowsy hound How does that work? Am I disabling the command for that channel?

Yeah, you look;

You can disable the command either for entire channels or for roles

if you disable it for moderator role they cannot use it
but if you only enable it for them only they should be able to use it (unless your bot's code allows them to use the commands without the permission overrides)

The same for channel overrides.
You can either disable a command completely in a channel so it cannot be used by anyone in that channel or...
You enable it so that command can be used in that channel.

#

Now you can also make a mix of these permissions as you can make it so that in some channels the command cannot be used at all by anyone not even moderators

While in other channels you only allow it to be used by moderators.

drowsy hound
#

oh, so... if I disable it like that but I am admin... I still can use the command? I think that's my confusion

solemn idol
#

Oh right, I am not sure if admins can still use the commands but it would probably make sense that they can... so yeah, you can always preview your server from a specific role angle (theres an option in the role menu of your server which allows you to do that) so you can view your server with a specific role's permissions etc. as if you were to be that role.

#

brb

drowsy hound
#

Ok, I'll wait. Btw, that seems to be really useful, where can I find that option?

fervent cradle
#

can anyone please elaborate on the difference between has_permissions and default_permissions? which one is better for lets say moderation commands, they essentially seem to be the same thing?

silver moat
fervent cradle
#

okay, so if i use has_permissions will the commands still be visible to only those with the permissions

fervent cradle
#

and for my which would be better to use part?

silver moat
#

you're choice?

fervent cradle
#

well default permissions is a bit more flexible isnt it? i dont know which one to use whether or not to let moderators of guilds manage it or not

fervent cradle
#

nvm, i think its better to use default_permissions cus it is more flexible, and allows for the admins manage it better if they need to

cold ledge
#

hi, can you insert images in slash commands?

#

(in one of the arguments)

proud mason
#

yes

#

use discord.Attachment as the typehint/input_type

river summit
#

how do i mention a command in a slash command group?

grizzled sentinel
#

What do you mean "in a slash command group"? Like do you want the command mention?

river summit
#

like this

grizzled sentinel
#

</full name:ID>

#

I think that should still work for groups

proud mason
#

or

#

.rtfm command.mention

proud mason
#

5th one

river summit
#

i'll give it a go, cheers.

zealous bear
#

can someone link/explain how to make buttons in pycord

#

.rtfm buttons

zealous bear
#

i can link it myself

zealous bear
#

LOVE YOU

zealous bear
#

and then do something based on that action

proud mason
#

you can use the callbacks 👀

grizzled sentinel
clear vault
#

What does that mean

solemn idol
#

Is there a setting on the discord developer portal which messes something up?

grizzled sentinel
#

I dont think so. Does your bot have the create guild commands permission on that server?

solemn idol
#

It has admin permissions thus...

#

but it doesnt make my global commands private either

proud mason
#

one trick would be to change a command's description or smth. that would force sync the commands. maybe that could help

grizzled sentinel
clear vault
#

I guess it has smth to do with webhooks

solemn idol
#

Wait hold on...

clear vault
river summit
#

discord.EmojiNotFound is raised when the input is something like this: 👍
how can i work around it, i preferrably need the bot to recognise custom emojis as well as default ones?


@reaction.command(name='add', description='Add a reaction role to the active message')
@discord.option(type=discord.Emoji, name='emoji', description='Emoji to add to the active message', required=True)
@discord.option(type=discord.Role, name='role', description='Role to add once the reaction role is triggered', required=True)
async def add(
    self,
    ctx: discord.ApplicationContext,
    emoji: discord.Emoji,
    role: discord.Role
):
grizzled sentinel
# clear vault

Are you running any code when you get this? full traceback please

solemn idol
#

Maybe my cog is not made correctly because I am using Beanie instead of the default Discord.Bot class

class developer(discord.Cog, description = 'Bot developer commands.'):
    def __init__(self, bot):
        self.bot = bot

    @discord.slash_command(name = "test", description = "Test cmd.", debug_guilds=[1114959767715184730])
    async def test(self, ctx):
        await ctx.send('Approved!')
        print('Approved!')

def setup(bot):
    bot.add_cog(developer(bot))

?

clear vault
#

its a ahiottp error

#
        async with aiohttp.ClientSession() as session:
            try:
                commanduse = discord.Webhook.from_url```
grizzled sentinel
solemn idol
clear vault
grizzled sentinel
solemn idol
#

Let's try and see

solemn idol
#

why does it work now?

#

Aaaand now it stays private ;)

#

reverse problem

grizzled sentinel
#

I think your command was silently erroring due to the invalid argument or something. Then when you added a debug_guild it was not getting updated idk for sure though.

grizzled sentinel
solemn idol
#

I made it an empty list

#

completely removed it, still private

grizzled sentinel
#

That is weird. I can reproduce that on my bot to. I wonder if there are still bugs in command registration

zealous bear
#
class RoleConfirm(discord.ui.View):
    @discord.ui.button(label="Accept", row=0, style=discord.ButtonStyle.green) 
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("Role Creation Successfully created!")
        
        

    @discord.ui.button(label="Deny", row=1, style=discord.ButtonStyle.red) 
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("Role Creation Successfully denied!")
#

does anyone know why only the deny button is showing up

solemn idol
#

This is like really painful, its going to limit my amount of tests and the speed of tests, but what I find most confusing is why making debug_guilds in the Beanie (subclass) doesn't directly make them private

clear vault
grizzled sentinel
proud mason
zealous bear
#

and it did not work

proud mason
zealous bear
#

i do, they're accept and deny

proud mason
#

"function names"

#

not label

zealous bear
#

oh

proud mason
clear vault
#

Restartet the bot

#

It says too many files open

#

Cant connect to discord

solemn idol
# solemn idol 🥹

yk at this point I dont mind adding debug_guilds but they need to work as this is slowly starting to make me loose my mind... first cog loading / unloading and now the general command registration 🥹
And I still don't know why debug_guilds only works half, it used to work on my old bot using Discord.Bot but I am trying to organize stuff ab it more and this is going to ruin a lot

true panther
#

anyone has some example bot made with async sqlalchemy maybe?

zealous bear
#

like that?

proud mason
#

uh no

#

button_callback itself

#

you can do like
async def accept_button(...):
and
async def deny_button(...):

zealous bear
#

OH

#

im actually so stupid

proud mason
clear vault
#

@grizzled sentinel and i dont find anything on google

grizzled sentinel
solemn idol
grizzled sentinel
grizzled sentinel
clear vault
#

Bro why pycord have such issues

solemn idol
grizzled sentinel
grizzled sentinel
clear vault
grizzled sentinel
#

I mean what part of your code. Like on startup or on command. OR just randomly after time

grizzled sun
#

Im having issues with interactions atm, after using an interaction it suddenly no longer shows up

#

Currently this is the code

@bot.bridge_command(aliases=['tt','travel_time', 'travel'], description="Replies with the shortest route and the travel time in between the regions")
 async def traveltime(ctx, start: discord.Option(str, choices=[region for region in TravelTime.regions]), end: discord.Option(str, choices=[region for region in TravelTime.regions])):
     if end == None and start == None:
         await ctx.reply("Choose two regions!", view=Timeview(timeout=30))
         return
     await ctx.reply(await get_travel_time(start, end, TravelTime.Timegraph, "days"))```
proud mason
#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
grizzled sun
#

yea yea

proud mason
grizzled sun
#

Multiple Instances?

proud mason
#

yeah. like running the same bot (same token) actively more than once

grizzled sun
#

Only running one instance from Vscode on my laptop while im testing and working on the bot

proud mason
#

hmm try resetting the token

grizzled sentinel
#

Next time you get the erro please ping me with the ENTIRE traceback. I have never seen the issue before and am unsure what would cause it without more info.

clear vault
#

But if it shows again i'll ping you

grizzled sun
grizzled sentinel
#

That almost 100% means that you were accidentally running the bot multiple times. (IE in 2 different terminals on your PC) At least it works now!

solemn idol
zealous bear
#

hey is there a way to make it so that my slash command has a cooldown, and a different cooldown for 3 different roles

slate arrow
#

Does anyone have like a way only certain roles can use a slash command i cant find info on it anywhere

waxen whale
#

Slash permissions are handled via guild settings > Integrations
The old system from the bots side was removed long ago.

You can do custom checks tho.
Read the docs :)

winter condorBOT
#

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

silver moat
slate arrow
#

But like its only for that one command not all of the commands in my server

zealous bear
#
role_name = "Your Role Name"
    role = discord.utils.get(ctx.guild.roles, name=role_name)
    if role not in ctx.author.roles:
        await ctx.respond("You have to have <your role> to use this command.")
        return
#

@slate arrow

slate arrow
#

Thanks

zealous bear
zealous bear
#

will you let me tip you a coffee

#

at some point

silver moat
#

I don’t have that type of service set up.

zealous bear
silver moat
#

nah I’ll pass

waxen whale
#

Smh squid

zealous bear
#

bro could've gotten a tip

#

😭

#

you've helped me out so much i would want to show appreciation

silver moat
waxen whale
#

You want to turn them in like legend?

#

I mean sure. I see no reason why it shouldn't

zealous bear
#
if role = role:
        @discord.ext.commands.dynamic_cooldown(720, type=discord.Message)
#

something like that?

silver moat
silver moat
#

you’d like an example?

waxen whale
#

420 BaguetteMarch

zealous bear
#

give me a minute

#

oh do i need to put in the like function of my command

silver moat
#

no?

zealous bear
#
@discord.ext.commands.dynamic_cooldown(posttrade, type=discord.Message)
#

thats what i meant

waxen whale
#

You did not read the docs at all

zealous bear
#

i tried

#

i suck at reading the docs man

waxen whale
#

Then learn it lmfao

silver moat
#
def dynamic_cooldown_function(message: Union[discord.Message, discord.Interaction]) -> 
commands.Cooldown:

  if (insert condition here):
    return commands.Cooldown(1, 10)
  else:
    return commands.Cooldown(1, 5)

...

@commands.dynamic_cooldown(dynamic_cooldown_function, type = commands.BucketType.member)
...
zealous bear
silver moat
#

callable indicates a function

#

and it takes a message

#

and returns a cooldown

zealous bear
#

why is there an arrow

#

thats not part of the code right, thats just visual?

silver moat
#

uhh it's just type-hinting

zealous bear
#
def posttrade(message: Union[discord.Message, discord.Interaction])

  if (insert condition here):
    return commands.Cooldown(1, 10)
  else:
    return commands.Cooldown(1, 5)

...

@commands.dynamic_cooldown(posttrade, type = commands.BucketType.member)
#

?

silver moat
#

what?

zealous bear
#

is that incorrect usage

#

like where do i put my command name

#

and where do i leave it as dynamic cooldown

silver moat
#

the decorator goes above the command name. This function is just there

zealous bear
#
def posttrade(message: Union[discord.Message, discord.Interaction])

  if (<ctx.user has role>):
    return commands.Cooldown(1, 10)
  else:
    return commands.Cooldown(1, 5)


@commands.dynamic_cooldown(posttrade, type = commands.BucketType.member)
await interaction.something
#

this is correct? or am i just completely lost

waxen whale
#

the bucket type will be role

zealous bear
zealous bear
#
@bot.slash_command()
@commands.cooldown(
if role:
  1, 5, 
elif role:
 1, 10,
elif role:
1, 15,

commands.BucketType.user
)
async def posttrade(ctx: discord.ApplicationContext):
    await ctx.respond("You can use this command again in 5 seconds.")
#

so in that case, that is how i would make it work?

#

role give different cd

waxen whale
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or("!"), debug_guilds=[...], intents=intents
)

def my_cooldown(message):
    if message.author.get_role(929080208148017242):
        return commands.Cooldown(
            3, 10
        )
    elif message.author.get_role(929080208148017242):
        return commands.Cooldown(
            2, 5
        )
    else:
        return commands.Cooldown(
            1, 10
        )

@bot.slash_command()
@commands.dynamic_cooldown(my_cooldown, commands.BucketType.role)
async def dynamic(ctx: discord.ApplicationContext):
    await ctx.respond("You can use this command again soon.")

# bot.run("TOKEN")

something like that

#

dunno if its correct tho, i dont do python

rough roseBOT
#
Evaluation Result

Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/snekbox/user_base/lib/python3.11/site-packages/discord/init.py", line 22, in <module>
from ._version import *
File "/snekbox/user_base/lib/python3.11/site-packages/discord/_version.py", line 38, in <module>
from .utils import deprecated
File "/snekbox/user_base/lib/python3.11/site-packages/discord/utils.py", line 28, in <module>
import asyncio
File "/snekbox/user_base/lib/python3.11/site-packages/asyncio/init.py", line 21, in <module>
from .base_events import *
File "/snekbox/user_base/lib/python3.11/site-packages/asyncio/base_events.py", line 296
future = tasks.async(future, loop=self)
^^^^^
SyntaxError: invalid syntax

Return Code

1

waxen whale
#

eh

young bone
#

xd

waxen whale
#

fuck u eval

zealous bear
#

thats pretty cool

#

feature

waxen whale
#

guess what, its written in c# Troll

zealous bear
young bone
#

@waxen whale Kann man sich irgendwo den Code von dem @rough rose Bot anschauen?

zealous bear
waxen whale
#

i have enough jobs at pycord wheeze

zealous bear
young bone
waxen whale
#

not sure atm, i dont really wanna publish the code

zealous bear
#

okay thanks sexy

young bone
waxen whale
#

no

#

and stick to english here

young bone
#

alright

zealous bear
young bone
#

its in seconds

zealous bear
#

oh boy

waxen whale
#

how often / seconds

young bone
zealous bear
#

HEEH

#
def my_cooldown(message):
    if message.author.get_role(1121931624670580908):
        return commands.Cooldown(
            3, 18000
        )
    elif message.author.get_role(1121860931861893190):
        return commands.Cooldown(
            2, 14400
        )
    elif message.author.get_role(1121860948370673747):
        return commands.Cooldown(
            2, 10800
        )
    else:
        return commands.Cooldown(
            1, 6
        )
#

:wheeze:

#

aw

waxen whale
#

yeah like that in theory

zealous bear
#

as in it won't work?

waxen whale
#

idk if it works bcs i dont use python kek

halcyon gorge
#

is the username system updated for the 2.4.1 version of pycord?

waxen whale
#

no

#

it all depends on bob

zealous bear
#

its so sexy

#

it allows me to bypass the discord limitation of slowmode being based ONLY on channels and not at all on roles

zealous bear
#

when you defer

#

an interaction

#

it should look like this right?


@bot.slash_command(guild_id = server, name = "example", description = "this is for the py-cord help channel")
async def example(ctx):
  await ctx.defer()
  await ctx.respond("This is the example message that was deferred")
young bone
#

Yes

zealous bear
zealous bear
zealous bear
#

because i'm wondering if the way i'm deferring is causing interactions to fail

young bone
#

Ctx.edit is to edit the message

zealous bear
#

and then it was edited

#

so i was wondering if that is the better way to do it

young bone
#

If you want to do that

zealous bear
#

okay

#

well, thanks

trim condor
#

👋 quick question: if I’m in a cog, can I still use @discord.ui.mentionable_select()? seems like I need to modify it somehow because it’s not working for me (just getting an empty view). can post the 5 lines of code in its own thread if needed, but figured it might be a direct question

#

actually more generally I’m not quite sure what the different pre-made selects actually do. I may be misunderstanding; my hope is that it gives me a dropdown with a list of members in the channel where my slash command was invoked, but that seems a bit unlikely 😅

trim condor
#

turns out I was able to make it work via a view, instantiating the class, and setting the component type. I’ve noticed that I don’t always see the dropdown for some reason, I haven’t quite figured out why that is. I’ve also noticed some lag with slash command registration depending on which device I’m connected to discord with 🤔

signal sandal
#

how should i update my code to work with the new username system?

silver moat
#

if designed correctly, no changes are needed

signal sandal
#

well it shows with #0 and thats not so aplealing

#

everything works though

silver moat
#

next release should remove the #0 iirc.

signal sandal
#

cool

#

ty for the info

silver moat
#

For now you could just check discrim is 0

signal sandal
#

not really worth it

#

assuming the next update comes in the next few months

silver moat
#

should come within a few weeks

signal sandal
#

thanks!

clear vault
#

@grizzled sentinel So far I have not had the error but can it be that when I query something from a json I have to close it again?

rough roseBOT
#

You need to wrap the code into a code block.

bold notch
#

Is it possible to get a stream of individual people’s voice audio?

errant craneBOT
#

Here's the audio recording example.

bold notch
#

Cool I’ll look into it

slate arrow
#

Does Anyone Have A Way Of Getting A Voice Cannel And Then Chnaging The Name Of It?

#

I Cant Find Anything Online For It

bold notch
slate arrow
#

same thing

#

Actully Dont Worry ChatGPT Helped Me

fervent cradle
#

anyone know what happened to hyperlinks? the hyperlink markdown randomly stopped working about a month or so ago
Nvm, ig hyperlinks don't work anymore if the hyperlink text is a discord link, prob protection for phishing links or something

solemn idol
#

They didn't add those back

proud mason
#

Yep

#

Discord™️

fervent cradle
grizzled sentinel
grizzled sentinel
fervent cradle
grizzled sentinel
#

Ahh, ok. THats too bad.

fervent cradle
clear vault
grizzled sentinel
#

Im not sure. I would think it is fine, We will have to wait for the error to see the true problem.

clear vault
#

That is the „main error“

grizzled sentinel
#

Yeah, I want to see what bit of code it originates from like all the way at the top of the traceback.

clear vault
solemn idol
#

@grizzled sentinel Hmm yes look at that, now 1 command is both private and public at the same time

slate arrow
#

Again I Got A Problem Where channel.send('Hi') Is Not Working

#

This is where it gets it

#

channel = bot.get_channel(int('1122134576215633930'))

#

and this is where it sends it: channel.send("Hi")

somber pelican
#

.idw

winter condorBOT
#

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.

slate arrow
#

Pl Well Im Trying To Send A Command In a Channel After A User Presses A Button IN Their Dms

somber pelican
#

What's the error exactly?

slate arrow
solemn idol
#

try fetch_channel

river summit
#

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

message = ctx.interaction.original_response()
await message.add_reaction("👍") # type: ignore
await message.add_reaction("👎") # type: ignore
somber pelican
#

That's because get_channel fetches from the cache, which may or may not have your channel

slate arrow
#

ok

somber pelican
#

A method which is guaranteed to return a channel is fetch_channel

slate arrow
somber pelican
#

However, you should only use fetch_channel if get_channel returns none

#

Have you awaited fetch_channel?

slate arrow
#

no

solemn idol
#

Yeh you should do that 💀

slate arrow
#

File "main.py", line 51
await mod_channel = bot.fetch_channel('898223478136799285')
^^^^^^^^^^^^^^^^^
SyntaxError: cannot assign to await expression here. Maybe you meant '==' instead of '='?

solemn idol
slate arrow
#

Oh Yeah

slate arrow
solemn idol
#

Wait what exactly did you do now?

slate arrow
#

just awaited the send

somber pelican
#

???

slate arrow
#

await mod_channel.send(f'The User {userforbtn} Said The Service Today Was Good')

solemn idol
#

did you change get_channel to fetch_channel?

slate arrow
#

yes

solemn idol
#

also make sure the ID doesn't use ''

#

it needs to have an int not a string

slate arrow
#

It Doesnt

#

So This

somber pelican
#

have you awaited fetch_channel?

slate arrow
#

mod_channel = bot.fetch_channel(int('898223478136799285'))

somber pelican
#

okay that's where the error is coming from, you need to await both .send and .fetch_channel

slate arrow
#

Okay

somber pelican
#

since they're both async and return a coroutine

solemn idol
#

just... (make it simpler for you)

bot.fetch_channel(898223478136799285)

dont pass in a string to then convert it to a string just pass in the int directly ;_;

slate arrow
#

File "main.py", line 58
await mod_channel = bot.fetch_channel(int('898223478136799285'))
^^^^^^^^^^^^^^^^^
SyntaxError: cannot assign to await expression here. Maybe you meant '==' instead of '='?

solemn idol
#

no

somber pelican
slate arrow
#

Its Inside Where Awaits Can Happen

somber pelican
#

You're awaiting it the wrong way

solemn idol
#

look;

mod_channel = await bot.fetch_channel(898223478136799285)
slate arrow
#

og

solemn idol
somber pelican
#

damn that's some spoon-feeding right there

solemn idol
somber pelican
#

@slate arrow do you know python?

#

?tag learnpython

obtuse juncoBOT
#

To be clear:

When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.

We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.

slate arrow
#

I Just Havent Made A Bot For Ages

solemn idol
# slate arrow Yeah I Do

ok then do you know why we put the await before bot.fetch_channel?
and not before mod_channel?

slate arrow
#

because its awaiting for the varible to be set

#

and not waiting for the fetch

solemn idol
#

exactly, + it then only gets awaited when the variable is called.

slate arrow
#

Well Thats My Guess

#

Well Thank You It Works Now

solemn idol
#

Youre welcome Ig but... please (this is somewhat common sense in python 💀 )

#

also the docs are really helpful

river summit
#

how would i get a message object from this? i need to add reactions to the embed.

channel: discord.TextChannel = ctx.guild.get_channel(channel_id) #type: ignore
await channel.send(embed=suggestion_embed)
solemn idol
#

You could assign the result of the send method to a variable :P

river summit
solemn idol
fervent cradle
cyan quail
#

The #0 only appears when using str(User)

#

Because it would do f"{user.name}#{user.discriminator}"

fervent cradle
#

ah so it doesnt matter if u use str(User) or User.name it's essentially the same

cyan quail
#

No, user.name is only the username without discriminator

#

In the new version, str(User) does something like f"{user.name} ({user.global_name})"

#

Assuming they migrated

fervent cradle
#

ahh i do that manually right now

#

it doesnt really matter how u do it anyways essentially same thing

slate arrow
#

God Im Back Again, I Have 2 Buttons And I Want All Of Them To Be Disabled When One Pressed, I Copied The Docks Of:

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

But That Doesnt Work Is Anyone Able To Help?

#

i get this error: AttributeError: 'serviceView' object has no attribute 'disable_all_items'

zealous bear
#

yeah i seriously can't figure out why my interactions are failing

zealous bear
#
@tasks.loop(minutes=2)
async def check_live_status():
    guild_id = 953632089339727953
    guild = bot.get_guild(guild_id)
    live_role = guild.get_role(live_role_id)
    premium_role = guild.get_role(premium_role_id)

    if not premium_role:
        return

    for member in guild.members:
        if member.bot:
            return

        if member.activity and isinstance(member.activity, discord.Streaming):
            if live_role not in member.roles:
                await member.add_roles(live_role)
        else:

            if live_role in member.roles:
                await member.remove_roles(live_role)
#

that should be working right?

#

i see no reason why it would not be working

#

and yet its not working

#

oh yeah i called the task in on ready

#
check_live_status.start()
zealous bear
#

aw man i can't use /eval code

zealous bear
#

elp

cyan quail
zealous bear
cyan quail
#

also py for member in guild.members: if member.bot: return...this ends the task immediately if it finds a bot

cyan quail
#

you're looking for continue

zealous bear
#

yep

zealous bear
#

returns true and changed it to continue

#

but its still not working

cyan quail
#

is your premium_role None

#

not u

zealous bear
#

also i removed that part of the code and it didn't fix it

zealous bear
cyan quail
#

mf thought he had his selfbot on

#

anyway uhh

#

did you install the right lib

zealous bear
#

as in

cyan quail
#

not u

zealous bear
#

pycord?

#

oh sorry giggles

proud mason
#

can you show pip list

zealous bear
#

restart your code editor

cyan quail
#

what happens when u print len(guild.members)

zealous bear
#

i've gotten that error before and all i had to do was restart vs

cyan quail
#

i mean you can just debug this with prints and check where it breaks

#

because there's several places there the task could fail but we can't tell

proud mason
#

thats not the pip list...

#

run pip list in terminal and show output

zealous bear
#
@tasks.loop(minutes=2)
async def check_live_status():
    guild_id = 953632089339727953
    guild = bot.get_guild(guild_id)
    live_role = guild.get_role(live_role_id)
    premium_role = guild.get_role(premium_role_id)

    for member in guild.members:
        if member.bot:
            continue

        if member.activity and isinstance(member.activity, discord.Streaming):
            if live_role not in member.roles:
                await member.add_roles(live_role)
        else:

            if live_role in member.roles:
                await member.remove_roles(live_role)
#

current code SA_blob_cool

#

still broken SA_blob_cool

cyan quail
#

just

#

add prints

zealous bear
#

delete it

cyan quail
#

see where it stops printing

proud mason
#

||you could rather use events?||

zealous bear
#

oh yeah that works too

zealous bear
#

PIP LIST

proud mason
#

that doesnt have py-cord thonk

zealous bear
proud mason
#

wrong python version ig

#

which python version do you want to use?

#

3.11 ?

#

then do py -3.11 -m pip list

zealous bear
#
live_role_id = 1122209929659428916
premium_role_id = 1121860722054414397

@bot.listen()
async def on_member_update(before, after):
    guild = after.guild
    live_role = guild.get_role(live_role_id)
    premium_role = guild.get_role(premium_role_id)

    if premium_role not in after.roles:
        return

    if not live_role:
        return

    if after.activity and isinstance(after.activity, discord.Streaming):

        if live_role not in after.roles:
            await after.add_roles(live_role)
    else:

        if live_role in after.roles:
            await after.remove_roles(live_role)
#

thank you for telling me that i am stupid KermitSatisfiedStare

#

that's much better

proud mason
#

well, reinstall python and select the py launcher while installing

willow kiln
#

does anyone know how to fix this? it executes the desired function but still responds with this.

willow kiln
#

do i need to do ctx.respond or smth?

proud mason
#

yes

#

you need to send some response

full basin
#

Yes

#

Otherwise discord doesn't know lol

willow kiln
#

well i used ctx.send in another code that did the same shit, works with respond now tho, thx

#

btw can i somehow set that to be viewable by me only?

full basin
#

ephemeral=True

willow kiln
#

thanks!

river summit
#
 async def modal_response(message, interaction: discord.Interaction):
    doc = await self.collection.find_one({"guild_id": guild_id})

    if doc:
        await self.collection.update_one({"guild_id": doc["guild_id"]}, {"$set": {"message": message}})
        embed = embeds.success("The welcome message has been successfully changed.")
        await ctx.respond(embed=embed)
        await interaction.response.send_message("The welcome message has been successfully changed.", ephemeral=True)
        return


class Modal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.message_input = discord.ui.InputText(label="Message", style=discord.InputTextStyle.paragraph)

    async def callback(self, interaction: discord.Interaction):
        message = self.message_input.value
        await modal_response(message, interaction)


class MyView(discord.ui.View):
    @discord.ui.button(label="Change", style=discord.ButtonStyle.primary)
    async def button_callback(self, interaction: discord.Interaction):
        await interaction.response.send_modal(Modal(title="Set welcome message"))


await ctx.respond(embed=response_embed, view=MyView())

TypeError: WelcomeModule.message.<locals>.MyView.button_callback() takes 2 positional arguments but 3 were given

discord ui confused me before, but now im even more confused

clear vault
#

@grizzled sentinel

proud mason
river summit
proud mason
river summit
winter condorBOT
proud mason
#

you need to add the input text using that

willow kiln
#

can i check in an if statement whether or not the method was called by a command?

torpid perch
#

bot token redacted for privacy (?)

full basin
#

This is pycord

fervent cradle
#

also in ur command ur vulnerable to sql injection

torpid perch
#

a

#

omg...

torpid perch
willow kiln
#

is there an alternative to ctx.respond when using slash commands? in some cases it throws me 404s even though it works perfect in other methods

fervent cradle