#Basic Pycord Help (Quick Questions Only)

1 messages Β· Page 50 of 1

rare ice
#

Your .env file is wrong

#

Fix it

lament crown
#

i am going to make a new .env

rare ice
#

Ok

lament crown
#

it works i had it spelled with a i instead of a e

#

ty

rare ice
lament crown
#

ok sorry

fervent cradle
#

can i remove a command using a command?

proud mason
fervent cradle
#

slash

wintry cosmos
rare ice
#

.rtfm bot.remove_application_command

lament crown
#

does anyone know a way to make a drop down menu of a list of all members of the server?

silver moat
#

.rtfm member_select

winter condorBOT
#

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

silver moat
#

.rtfm user_select

winter condorBOT
viral hazel
#

Does anyone knows How to fix this problem I want to place that file into that url what should I do

embed.set_image(url=file=discord.File("text.png"))
silver moat
#

.localfile

lament crown
#

just a squid how can i set that a a varible?

rare ice
#

url=file=?? Syntax error?

silver moat
#

?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)```
viral hazel
rare ice
#

Basic python

viral hazel
#

I wanna place that file in

#

And I can use = like url=file=

lament crown
#

would i use user = discord.ui.user_select for it

viral hazel
#

so how can I just place that picture

viral hazel
lament crown
#

i got it to work where it is set as a varible but how do i make it a menu so u have to choose a user? bc i can't find it on the documentation

silver moat
lament crown
#

but how would the bot know the users?

#

would i have to define each one?

silver moat
viral hazel
#

@silver moat can you pls come to vc and help me out I am still having a lil problem can you pls guide me ?

#

I wont take much time

viral hazel
#

TYSM

young bone
#

Will it be faster with the new Version?

silver moat
young bone
#

the file image for an embed

tribal bough
#

how can i get a selected channel in a discord.ComponentType.channel_select

silver moat
tribal bough
#

code:```
async def dropdowncallback(self,interaction):
channel = self.values[0]
print(channel)
channel.send("This is a test")

#test command
@bot.command()
async def test(ctx:ctx):
guild=ctx.guild
dropdown = channelDropDown()
dropdown.callback = dropdowncallback
view = discord.ui.View(dropdown)
await ctx.send("This is a test", view=view)```
error:

Traceback (most recent call last):
  File "C:\Users\Fammy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
TypeError: dropdowncallback() missing 1 required positional argument: 'interaction'```
can anyone help???
proud mason
tribal bough
proud mason
tribal bough
grizzled sentinel
#

I suggest subclassing everytime you use a view. Imo it makes it much cleaner and easier to access things.

granite crypt
#

Is it possible to make an permissions override so that the bot owner can run every command?

winter condorBOT
knotty void
#

is there a way to get the server profile?

young bone
knotty void
young bone
lethal valve
#

How do I get the ID of the user who sent the slash command

knotty void
#

Why do i get an error message? embed.set_thumbnail(url=ctx.guild.icon.url)

limber urchin
knotty void
limber urchin
gleaming falcon
#

Not Pycord itself, but is anyone familiar enough with direct webhook posting. If I have a fields[] list and have a conditional second field, could I just pass an empty string? e.g.

fields = [
  {'name': 'ABC', 'value': '123'},
  {'name': 'DEF', 'value': '456'} if some_condition else ''
]

This would result in a list of

[
  {'name': 'ABC', 'value': '123'},
  ''
]

I'm guessing this won't work, but I'm trying to be lazy. Could change that to None if that might work

#

#tryitandsee says no 😦

fervent cradle
#

is there something that can fetch message search containing

knotty void
#

How can I delete multiple messages at once?

limber urchin
#

.rtfm TextChannel.purge

winter condorBOT
tall palm
#

Hi, I feel like I'm missing a leading ctx. before create_scheduled_event or something obvious, as my code is failing at that point

StartTime = datetime.strptime("2023-01-13 11:55", '%Y-%m-%d %H:%M')
EndTime = datetime.strptime("2023-01-13 14:00", '%Y-%m-%d %H:%M')
# I put in lots of print statements, and code fails here:
await create_scheduled_event(name="Test", description="test text", start_time=StartTime, end_time=EndTime, location="https://twitch.tv")```

(the bot does have permission to create/manage events, other commands are all working well)
silver moat
#

.rtfm create_scheduled_event

winter condorBOT
silver moat
#

ctx.guild.create_scheduled_event

tall palm
silver moat
#

yw

lament crown
#

when i make a dropdown menu is there a way to have the discord bot be able to see all users? or would i have to code each one in

winter condorBOT
lament crown
#

i did that but how do i input that into the code i set it as a varible that did not work it made u type the full name in and not show users

lament crown
# silver moat yw

sync def test(interaction: discord.Interaction, user = discord.ui.user_select ): i don't think this is right

proud mason
#

No that's not how you do it

#

.guide

winter condorBOT
proud mason
#

You have to subclass View and put the select menu there

#

And then send that view

lament crown
#

what part of the guide is it in?

#

would i have to make a class of options or is there a way for the bot to know the user names already?

proud mason
#

If you want to select a member in a Slash cmd, you have to typehint the parameter as member: discord.Member

#

Or use @option or the Option typehint

lament crown
#

would that make it so u could choose members in the server?

proud mason
#

Yes

#

But only 1 member btw

lament crown
#

ok

proud mason
#

If you want to be able to select more, you can use the user select menu

lament crown
#

tysm i am just going to work on it so i can cut off the # part of it

proud mason
#

πŸ‘πŸ‘

alpine kernel
#

am i using the extras cooldown right? doesnt seem to be working to not allow more then 3 per 30 seconds

from discord.ext import commands
...
@commands.slash_command(name='mention', extras={'cooldown':commands.Cooldown(3, 30)})```
silver moat
alpine kernel
#

oh, didnt know there was one, let me give it a go

#

cool that worked, but sometimes I have issues figuring out what the naming convention is on decorators because it's different in a cog... dunno guess something I'll keep fiddling around with and figuring it out

#

thanks!

lament crown
#

it nextcord there is a way to get the auther who sent a command is there a way in pycord to do that?

alpine kernel
#

ctx.author?

lament crown
#

tysm i was spelling author wrong i spelled it like auther

lament crown
#
@bot.command
async def wanted(ctx, user: discord.User = None):
    if user == None:
        user = ctx.author

    wanted = Image.open("wanted.jpg")

    data = BytesIO(await user.display_avatar.read())
    pfp = Image.open(data)

    pfp = pfp.resize((177, 177))

    wanted.paste(pfp, (120, 212))

    wanted.save("profile.jpg")

    await ctx.reply(file=discord.File("profile.jpg"))
```  File "c:\Users\\OneDrive\Desktop\Documents\bot\Main.py", line 27, in <module>
    async def wanted(ctx, user: discord.User = None):
TypeError: ApplicationCommandMixin.command() takes 1 positional argument but 2 were given idk what this error means
fringe socket
#

it means that you gave one too many arguments

#

if i'm not mistaken

fringe socket
#

also, if you are doing an error, I recommend opening a new thread

fringe socket
silver moat
fringe socket
#

that has nothing to do with it

#

i think im just half-awake lol

#

yep im typing in lowercase

#

definitely half-asleep

lament crown
#

ty did not see that

#

await ctx.reply(file=discord.File("profile.jpg")) when i run the command the new image does not get sent

#

ges\Python310\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'reply'

silver moat
#

ctx.respond

burnt fjord
#

when I get the error where I reached my max daily command limit (200) from restarting the bot too many times, what time does that refresh? like midnight utc?

opal warren
#

Can i use button and select menu
can anyone pls give a sample code

viral hazel
#

I want cat API for my discord bot I tried many of the cat API's but it didn't work

limber urchin
#

Dude, don't ping people to help you

#

And saying "didn't work" is completely useless, explain what's not working instead

viral hazel
#
@bot.command()
async def cat(ctx):
    r =  requests.get("https://api.thecatapi.com/v1/images/search")
    res = r.json()
    em = discord.Embed()
    em.set_image(url=res['message'])
    await ctx.send(embed=em)
``` can anyone tell me why this code's API is not working
limber urchin
#

...

#

** explain what's not working **

viral hazel
#

The API

limber urchin
viral hazel
#

I can't help with it

limber urchin
#

in what way is it "not working"?

viral hazel
#

Its not responding in discord

#

But I made a dog one and that's working fine

limber urchin
#

And you're not getting any errors?

viral hazel
#

No

limber urchin
#

First of all don't use the requests library in an async environment

viral hazel
#

then how will I make commands for bot ?

limber urchin
#

?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

viral hazel
limber urchin
#

???

viral hazel
#

okayy

limber urchin
#

what?

viral hazel
#

I mean how to do this one ?

limber urchin
#

Do what?

#

What is "this one"?

viral hazel
#

hmm so How can I use API's in discord ?

#

if not with requests

limber urchin
#

Bro..

#

did you even read the message?

#

It literally tells you what you can use

viral hazel
#

Yes i know

viral hazel
#

asiohttp or httpx ?

limber urchin
#

I still don't know what "this one" means

viral hazel
#

aiohttp

limber urchin
#

??????

viral hazel
#

Nothing leave it

#

You got more questions then I do

limber urchin
#

Because your questions don't make any sense

viral hazel
#

I am trying to but i am new got here for help

limber urchin
#

Okay?

viral hazel
#

Like without requests how can i use aiohttps or httpx that's my question for now

limber urchin
#

Use google and read the docs

viral hazel
#

thanks

limber urchin
#

You really needed me to tell you to use google? kek

limber urchin
#

The search feature of the docs is pretty bad tbh, so you have to click around until you find the right link

quartz thunder
#

Hey all, how can I make a custom function to authorize/unauthorize a commande ?
(I have a function inside my COG who returns a boolean based on the guildId and the memberId)

limber urchin
#

what? Where you use it doesn't matter, it's a method on a PartialMessage class

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.

flat merlin
#

Would it be possible to return the user's input on a modal dialog to the function calling said modal dialog? πŸ€”

proud mason
#

.rtfm modal.wait

winter condorBOT
flat merlin
#

πŸ€”

#

That's basically what I've been missing all this time.

proud mason
#

its cool

#

Although keep in mind

#

it also fires for timeout

#

so check that values are present before using them

flat merlin
#

I will take a note of that.

#

Thanks.

proud mason
#

no worries

north gorge
#

Can you access the auth'd Reddit username of a User?

limber urchin
#

No, bots can not see that info

north gorge
#

ah, damn. Ok, tyvm

coarse spire
#

why isn't this working?

from discord.ext import commands
import asyncio
import random
import json

class automod(commands.Cog): # create a class for our cog that inherits from commands.Cog
    # this class is used to create a cog, which is a module that can be added to the bot

    def __init__(self, bot): # this is a special method that is called when the cog is loaded
        self.bot = bot

    @discord.slash_command(description="Activate a premium subscription with a code")
    async def automod(self, ctx):
        authorr = ctx.author
        with open("automodguilds.json") as f:
            autmodguild = json.load(f)

        if guild.id not in automodguild:
            automodguild.append(self.guild.id)
            await ctx.respond("Enabled automod, saving settings...")
        elif guild.id in automodguild:
            automodguild.remove(self.guild.id)
            await ctx.respond("Disabled automod, saving settings...")

        with open("automodguilds.json", "w+") as f:
            json.dump(codes_list, f)

        await ctx.respond("Settings saved!")

def setup(bot): # this is called by Pycord to setup the cog
    bot.add_cog(automod(bot)) # add the cog to the bot```
#

It says guild isn't defined

limber urchin
#
  1. Don't use json as a database
  2. What is self.guild?
#

And why are you trying to do guild.id without defining guild?

coarse spire
limber urchin
#

Why can't you use ctx.guild?

#

You still didn't define guild

coarse spire
# limber urchin Why can't you use ctx.guild?

ok, I tried that and it worked, thanks. Now with this code;

from discord.ext import commands
import asyncio
import random
import json

class automod(commands.Cog): # create a class for our cog that inherits from commands.Cog
    # this class is used to create a cog, which is a module that can be added to the bot

    def __init__(self, bot): # this is a special method that is called when the cog is loaded
        self.bot = bot

    @discord.slash_command(description="Activate a premium subscription with a code")
    async def automod(self, ctx):
        authorr = ctx.author
        with open("automodguilds.json") as f:
            automodguild = json.load(f)

        if ctx.guild.id not in automodguild:
            automodguild.append(ctx.guild.id)
            await ctx.respond("Enabled automod, saving settings...")
        elif ctx.guild.id in automodguild:
            automodguild.remove(ctx.guild.id)
            await ctx.respond("Disabled automod, saving settings...")

        with open("automodguilds.json", "w+") as f:
            json.dump(automodguild, f)

        await ctx.respond("Settings saved!")

def setup(bot): # this is called by Pycord to setup the cog
    bot.add_cog(automod(bot)) # add the cog to the bot```

I get this error though; Application Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
limber urchin
coarse spire
#

I know, I am going to switch to sql soon, but I just want to get all the basic code working first

limber urchin
#

πŸ€·β€β™‚οΈ too bad, you probably corrupted your json file somehow and now your code can't read it

#

hence why you shouldn't use json as a database

coarse spire
#

oh wait

#

I found the error, thanks

north gorge
#

Do you guys have any idea why a user on android mobile (and seemingly only that platform) wouldn't be able to see a particular button? The only vaguely interesting/unusual thing about the button is it has an emoji and it's a timeout=None permanent one.

limber urchin
#

Are they using an old version of Discord?

north gorge
#

that could be the case

#

I'll tell them to update and post back just for posterity

#

Yup, that was it, thanks

fervent cradle
#

Hello i have a problem

thin terrace
#

Quick API question, what is the maximum number of overwrites a channel can have?

young bone
royal acorn
#

Hey, is there a way to send multiple attachments in the same reply to a command?

#

Also, how can i use set_image with an embed and an attachment image?

silver moat
royal acorn
silver moat
#

.localfile

#

?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)```
coarse spire
#

what am I doing wrong here?

                await message.delete()
                await message.channel.send("Please do not mass mention people :skull:")```
silver moat
#

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

coarse spire
#

I don't get any errors or anything from it

silver moat
#

what is the problem

coarse spire
#

well, I'm trying to make so that if you mention more than 5 people here, it will delete the message

#

but, it doesn't do anything

silver moat
#

is this in on_message?

coarse spire
#

yes

silver moat
#

do you have intents?

coarse spire
#

yeah, all intents. This is in a cog though

proud mason
#

And see till where code is being executed

coarse spire
#

ok

proud mason
#

Don't name the class and the Slash group the same. Use CamelCase for the class

proud mason
#

Also, you are trying to access a function of a different class from a different class

proud mason
coarse spire
proud mason
proud mason
coarse spire
# proud mason Alright that's progress. Full traceback?
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/automod.py", line 54, in on_message
    if message.raw_mentions > 5:
TypeError: '>' not supported between instances of 'list' and 'int'
silver moat
#

.rtfm discord.message.raw_mentions

winter condorBOT
proud mason
#

Define it outside both the classes?

silver moat
coarse spire
#

ah, so it returns an array...

#

Ok, now it works, thanks πŸ˜„

silver moat
#

yw

proud mason
#

Why not

silver moat
#

do you know basic python?

coarse spire
#

okay, so now when I try to add a timeout function as well await message.author.timeout_for(timedelta(minutes=15)) I get this error; discord.errors.ExtensionFailed: Extension 'cogs.automod' raised an error: ModuleNotFoundError: No module named 'timedelta'
I couldn't find much online on timing out members, am I doing something wrong?

silver moat
coarse spire
#

oh

#

I just typed import timedelta πŸ€¦β€β™‚οΈ

proud mason
#

what are you doing-

#

if you put functions out of the cog class then you cant use self

#

show what you are doing blobpain

loud holly
#

that's not what they meant

#

PascalCase for classes since that's the industrial practices I believe for classes itself, what you'd do in this case is

class emojiquiz():
  ...

to

class EmojiQuiz():
  ...
#

not rename the classes to literal Camel

#

for vars I believe you can make it so it's like

emoji_quiz = ...

Om confirm?

proud mason
#

since the func is outside a class, it cannot use self

you should rather accept a connection in random_emoji() and do this part async with self.bot.pool.acquire()as conn: at the places you want to use it

#

you can get the bot instance from interaction.client

loud holly
proud mason
#

so random_emoji should look like this
async def random_emoji(conn):

and wherever you want to use it, do

async with bot.pool.acquire() as conn:
    result = await random_emoji(conn)
full basin
#

You clearly don't know basic python

proud mason
limber urchin
viral hazel
#

Hello I am getting this error while using @client.group(name="help) :-
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
Even when I am not supposed to

full basin
#

There's already a help command built in

#

You must remove it or pass your command to the bot initialization

viral hazel
#

bot.remove_command('help') It's this simple

viral hazel
#

Can anyone tell me why my embeds are not working in groups ?

#
@bot.group(name="help", invoke_without_command=True)
async def help(ctx, member:discord.Member = None):
    if member == None:
        member = ctx.author
    embed = discord.Embed()
limber urchin
#

Because you're not even sending the embed?

viral hazel
#

no i am sending it its the top one

#

Now I am doing it with command and still not working

#
@bot.command()
async def help(ctx, member:discord.Member = None):
    if member == None:
        member = ctx.author

    name = member.display_name
    pfp = member.display_avatar

    embed = discord.Embed(title="Geniot Help", description="Here are commands for Geniot\nDon't forget to use prefix before command (g#)", color=discord.Color.blurple())
    embed.set_author(name=f"{name}", icon_url=ctx.author.avatar)
    embed.set_thumbnail(url=f"{pfp}")
    embed.add_field(name=f"dog", value=f"This command shows you cute pictures of dog")
    embed.add_field(name=f"8ball", value=f"You can ask a question from the bot", inline=False)
    embed.add_field(name=f"ping", value=f"This command shows you the response time of Geniot", inline=False)
    embed.add_field(name="**If you want more detail on a particular command, Type: **", inline=False)
    embed.set_footer(text=f"Requested by {name}")

    await ctx.reply(embed=embed)
limber urchin
#

Once again, "not working" is useless

viral hazel
#

No error Nothing

#

its just not replying on discord

#

and also I am using this command above to remove the initial help command:-
bot.remove_command('help')

#

will it effect ? on this command too ?

proud mason
proud mason
viral hazel
#

Yes I have tested this bot's command multiple times

smoky forge
#

Are webhooks currently broken?

proud mason
proud mason
#

are you having any issues?

viral hazel
#

@proud mason I found it idk why but issues are in add_field command

smoky forge
# proud mason are you having any issues?

i tried using dishook for an embed but the send button was greyed out, tried with another site and it didnt send. I suspect the same thing would happen if i used it with pycord

smoky forge
#

I'll try in a bit, but i'm not sure

young bone
#

also read #help-rules

proud mason
viral hazel
viral hazel
smoky forge
#

ok it does work

verbal marten
#

Are button cooldowns built-in or will I need to handle it myself?

silver moat
verbal marten
#

Great thanks :)

undone falcon
#

Is their a ways to deactivate certain commands while the bot is getting ready (before the on_ready event) ?

silver moat
undone falcon
#

if the bot is in a lots of servers, it take minutes before on_ready is called, and commands are not disabled in that time

silver moat
#

commands as in app commands or text-based?

undone falcon
#

slash commands

silver moat
#

and return if it is not.

#

if it is bot.process_application_commands

undone falcon
#

I see thanks you !

#

Do on_connect() is call when pycord reconnect to discord after for exemple a shortage of internet

silver moat
undone falcon
#

thanks !

lament crown
#

await message.edit(content="") this code is not working the message part is giving errors

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.

lament crown
#

there is no error it just refuses to load this part and message in yellow underneath

#

i can't rly describe what happens but it is fine if u can't bc the code is not rly needed but would make it so i don't need to right more

#

i am going to just delete it

worn void
#
@client.slash_command(name="gib")
async def gib(ctx):
     role = ctx.guild.get_role(1041224580968230922)
     print("trying to run loop")
     await ctx.respond("ok")
     for member in ctx.guild.members:
          print("checking " + member.name)
          if role in member.roles:
               pass
          else:
               try:
                    print("trying to add role to " + member.name)
                    await member.add_roles(role)
               except:
                    pass

This is only prints

trying to run loop
checking Test Bot
checking LegoScrap

and stops. and I can't figure out why. There are 200 other people in the server

young bone
#

you may get a rate limit

worn void
young bone
#

do you have intents?

worn void
#

yeah

young bone
#

which one?

worn void
#

all

#

just added a 2 second delay between requests and it still stops after checking me

silver moat
#

what is the value of ctx.guild.members?

worn void
#

was just about to check that

worn void
#

the bot has admin and should be able to see everyone

silver moat
#

how are your intents applied?

worn void
#

oh wait im dumb

#

this was a separate file for the bot, and I forgot to enable them before defining client

#

thanks

silver moat
#

ok

naive steppe
# winter condor

could someone tell me the name of the little "Select a result" bar? i need to search the docs for it

silver moat
#

.rtfm select_menu

winter condorBOT
#

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

silver moat
#

.rtfm select

naive steppe
#

thank you, you are a goat squid πŸ™

silver moat
#

yw

copper knot
#

none of my commands are syncing, and i have no idea what to do to fix it. can i have some ideas?

silver moat
#

.slashnoshow

winter condorBOT
#

Checklist for Application Commands Not Showing Up:
β€’ Does your bot have the application.commands scope?
β€’ Are you loading cogs before on_ready and on_connect?
β€’ Is on_connect not overridden?
β€’ Did you update to the newest version of py-cord (tag: install)?
β€’ Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
β€’ Did you share your code and errors?
β€’ Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

copper knot
#

thanks

#

turns out it was the on_connect override

dreamy mauve
#

I am in a discord server where the commands are being synced. But they don't appear anywhere. All the permissions, scopes are given. What's wrong with this?

There are 14 other bots that have slash commands in that server

olive acorn
#

Can anyone send me pycord api reference link

silver moat
#

.rtfm e

proud mason
vapid pumice
#

is there any way to access variables defined in initialization of a class?
I was under the impression that something like self.x or cls.x would work, but it returns undefined when trying to reference in @discord.ui.select

(Trying to randomize the order of my select menu options)

proud mason
#

You can create the select menu in the view init using the select class

#

And use self.add_item

full basin
#

You need to sync the commands. And slash commands use ctx.respond not ctx.send

ornate swan
#

how could i use a, old Select after restarting the bot?

ornate swan
#

ty

limber urchin
#

Do you have the presence intent enabled?

#

And how are you getting the member?

#

So I assume you also have member intents?

grizzled sun
#

Quick question: How do you get ctx.respond to be ethereal when using The Message Commands Context Menu?
As in only you're shown the message and you can dismiss it by pressing the small x

silver moat
#

ephemeral = True

grizzled sun
#

ephermeral that's it

#

Thought it was ethereal

atomic wolf
#

How do do I register all the cogs in a for loop? my folders ["commands", "economy"]

proud mason
#

Oh well

#

.rtfm load_extensions

proud mason
#

Use that. No need to use a for loop

#

Library handles that for you

astral mist
#
\programing\python\bot\viking bot\tom viking build\viking for tom.py", line 147, in <module>
    @bot.slash_command()
AttributeError: 'SlashCommand' object has no attribute 'slash_command'


``` trace back


https://pastebin.com/FrxvTiRT

codΓͺ^^^^^^
#

how do i send the code if its to big

#

.rtfm pastebin

winter condorBOT
#

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

coarse spire
#

this is a on_message event, what am I doing wrong here?

            return```

I get this error; 
```if message.guild.id not in automodguild:
AttributeError: 'NoneType' object has no attribute 'id'```
dapper flare
#

is it possible to send inline images in embed or normal text?

coarse spire
storm oyster
#

damn

#

Weird

#

Which pycord version?

coarse spire
#

2.3.2

storm oyster
#

Hm

coarse spire
#

and it's not all the times I send a message I get the error, only a few times

storm oyster
#

Ah that makes sense although idk why would that be happening either but ig you could make an error handler to it and prevent your console being flooded with that error

coarse spire
#

ok, thanks πŸ™‚

dapper flare
#

is it possible to send inline images in embed or normal text?

grizzled sun
#

Is it possible to when using The Message Commands Context Menu that you can show the message that you're using it on?

Like how you can click when replying to a message to go the orginal message

proud mason
proud mason
#

Full error?

#

Did you add less than 1 or more than 5 input texts?

fervent cradle
#

Is there a example that shows how to dynamically change the select menu,
My goal:
the command is: /settings Command: choice
when u choose, depending on choice the select menu in the follow response should have different results, how do i like use a variable or something to make the select menu change depending on that choice? is there already code for that or a example

#

yeah i mean not like the autocomplete but like
/settings command: u pick a choice, then the embed has a select menu and the options change based on the results

#

dankmemer has this on their settings so i assume it is possible

lyric parrot
fervent cradle
#

this helps thanks

grizzled sentinel
#

The autocomplete example on the github shows how to do that @fervent cradle @ancient summit
The function at the bottom

#

Can't get the bot to link to it rn

fervent cradle
#

autocomplete is different

#

thats for choices on a command, this is select menu

grizzled sentinel
#

Ohhh

grizzled sentinel
#

Sorry for this being much later.
My guess it they edit the message with a new select menu once the first one gets an input.

sweet wren
#

how would i add an emoji reaction to an embed I'm currently getting

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
    await self.callback(ctx, **kwargs)
  File "/home/container/beta-247-casino-bot.py", line 5367, in poll
    await msg.add_reaction("πŸ‘")
AttributeError: 'Interaction' object has no attribute 'add_reaction'```
#
        embed = discord.Embed(title="Poll", description=question, color=0x00ff00)
        embed.add_field(name="Question:", value=question)
        embed.set_author(name=ctx.author.name, icon_url=ctx.author.display_avatar)

        msg = await ctx.respond(embed=embed)
        await msg.add_reaction("πŸ‘")
neat field
#

Hi, I have a quick question about interactions, how can I edit both a button's contents and the interactions text contents at the same time? My code is as follows currently, I tried using the followup-thing but I do not fully understand it, as this is my first time using PyCord...

full basin
sweet wren
#

ooh

full basin
#

.rtfm interaction.followup

winter condorBOT
limber urchin
#

That while loop is extremely risky lol

neat field
#

The API sometimes times out and returns nothing (i.e times out with a 504), I know it’s bad practice to have such a loop but it’s just a POC for now

#

Will try figure out a better way to handle the problem

copper knot
#

is there a way to get a VoiceClient from a VoiceProtocol?

rare ice
#

How can I access permissions that are missing for the MissingPermissions exception?

copper knot
#

?

waxen whale
rare ice
#

Ah

rare ice
waxen whale
#

Idk what pycord does but the info isn’t given back via api. So Shrug

wicked forge
#

heya got a quick question- i have a simple command to verify a server member and it seems to work but it keeps giving me the error The application did not respond and I'm not quite sure why

#
@bot.slash_command(name ="verify", description="Mod command to verify new users.")
async def verify (ctx, user: discord.User):
    role = discord.utils.get(ctx.guild.roles, name="member")
    await user.add_roles(role)
    await user.send(
        f"Congratulations, you're now verified! Welcome to the server!"
    )
young bone
wicked forge
# young bone you have to respond and use discord.Member and not discord.User
@bot.slash_command(name ="verify", description="Mod command to verify new users.")
async def verify (ctx, member: discord.Member):
    role = discord.utils.get(ctx.guild.roles, name="member")
    await member.add_roles(role)
    await member.respond(
        f"Congratulations, you're now verified! Welcome to the server!"
    )

like this?

woeful spindle
#

member.respond isn’t a thing

wicked forge
#

I didn't think it was

woeful spindle
#

you were correct when using member.send, but you need to actually respond to the interaction

wicked forge
#

My goal is to dm them the message, not send it in server tbc

woeful spindle
young bone
wicked forge
#

alright

#

thanks for the help

#

does it count if I react to the message?

young bone
#

what?

woeful spindle
#

are you aware your using slash commands?

wicked forge
#

yes nevermind ignore that

woeful spindle
wicked forge
#

another question- is there a way to make a command that can be both slash and user command? i worded it terribly, but I'd like to create a command that can be accessed via slash command or the app directory and I can't figure out if there's a more efficient way than just copy pasting the code once for each

proud mason
#

That's the best way

wicked forge
#

thought so, thanks

vapid pumice
dapper flare
#
            btn1 = Button(label="Go Left", emoji=':left_arrow:')
            btn2 = Button(label="Go Right", emoji="πŸ”₯")
            async def btn1_callback(interaction: discord.Interaction):
                await interaction.edit_original_message("works")
            btn1.callback = btn1_callback
            view = View()
            view.add_item(btn1)
            em.set_footer(text="use !sell <skin_name> to sell your skins")
            msg = await ctx.send(embed=em, view=view)```
whats the problem?

```TypeError: Interaction.edit_original_message() takes 1 positional argument but 2 were given```
silver moat
#

content="works"

dapper flare
# silver moat content="works"

getting this if i try embed

await interaction.edit_original_message(embed=emm)```

```discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
silver moat
#

edit_original_message will edit the message that was responded with which doesn't exist.

#

you are looking for interaction.response.edit_message

dapper flare
#

oh

#

works thank u

silver moat
#

yw

gleaming falcon
#

Has anyone had any trouble running the pycharm debugger lately with pycord?

Just from a asyncio.sleep call, I get

Fatal Python error: PyFrame_BlockPop: block stack underflow
Python runtime state: initialized

thick pumice
proud mason
#

.rtfm channel.set_permissions

proud mason
#

I needs a channel object

#

Which you can get from bot.get_channel

#

Ah just saw your post.... Please don't crosspost

celest whale
#

How can I throw an error to a slash command user that only they can see?

kindred sail
#

use the ephemeral property on your respond

#
await ctx.respond("Only the user who used the command can see this!", ephemeral=True)```
celest whale
kindred sail
#
- like this?
thick pumice
#

How to make a button that's when pressed send another embed message also with button?

thick pumice
#

so it will add same buttons to that message

#

But problem is that I have class it witch there are all variables, channel ids, user ids and other.

#

(As I understand)

#

(I have some code)
I want to do that when user clicks 1 of 4 buttons, it creates channel (witch's name depends on witch button user pressed). When channel is created, for bot to send an embed that has button to delete the channel.

#

Yes

#

I'm doing it

#

I know it's stupid not to use existing bot, but I want to be able to modify it

#

What exactly you mean by "theme"

#

like. Button 1 creates channel named "role-[number]" (number thing I did my self). Button 2 creates "help-[number]", button 3 creates "bug-[number]" and etc.

#

Yes

#

Yes

#

ok thank you

copper magnet
#

Hello! I encountered an error on linux. no module named discord.ui. Here is a piece of code: from discord.ui import button, Button, View. Help me pls

#

(python version: 3.6.8)

young bone
copper magnet
#

okay, thanks

loud holly
#
class SuggestionButton(View):
    def __init__(self, choice: str, bot: commands.Bot, type_choice: str):
        super().__init__(timeout=6)
        self.choice: str = choice
        self.bot: commands.Bot = bot
        self.type_choice: dict[str, list[str]] = {
            "Suggestion": [ "Suggestion Button", ":Suggestion:"],
            "Review": ["Review Button", "⭐"]
        }
    
        Choice_Button = Button(label=self.type_choice[type_choice][0], style=discord.ButtonStyle.blurple, emoji=self.type_choice[type_choice][1])
        self.add_item(Choice_Button)

    async def blurple_button_callback(self, button: Button, interaction: discord.Interaction) -> None:
        button.disabled: bool = True

So I'm adding the callback for the Choice_Button since by adding the the button via self doesn't trigger the callback. Is there a bug or something that doesn't trigger the callback

proud mason
loud holly
#

even if I add callback to the function, it comes that I need discord.Interaction

proud mason
#

Not if you create the button using the Button class directly

loud holly
#
Choice_Button.callback = self.blurple_button_callback
proud mason
#

Hmm

loud holly
proud mason
loud holly
#

Hmmm that would be a problem since I'm using the self.choice. Here I thought I could reduce the classes needed πŸ˜”

thick pumice
#

Is it possible to host discord py bot on webserver (website)?

fervent cradle
#

can i send dm to every users that uses the bot? (i use commands from dms only)

#

and also would that cause a ratelimit or a ban?

proud mason
thick pumice
#

hmm

proud mason
proud mason
north gorge
#

somehow bot.get_guild(guild_number) is always returning None when I initialize my cog, yet the same exact code works in five other cogs

#

I am so confused pepehands

proud mason
north gorge
#

Yeah I just realized that lmao, looks like I have to fetch_guild in an on_ready block in the cog or something

#

Thanks Om

proud mason
#

Haha no worries

north gorge
#

can't do it in init because it's not async pepehands

proud mason
north gorge
#

ah true

north gorge
#

now I'm just leaving self.bot = bot in init and adding the other stuff to on_ready in that cog, gonna see if that makes it work as expected

proud mason
silver moat
#

just use asyncio?

proud mason
#

asyncio.create_task yes this works

silver moat
#

yeah

neat field
#

Are custom emojis not usable at all in slash commands?

silver moat
#

you just need the "Use External Emoji" permissions on the integration role itself.

grizzled sentinel
#

It depends it looks like it just does the :name: text

#

I'm not sure if it actually renders the emoji

neat field
#

and bot everyone role and my bot has use extermal emoji

#

yet, still

#

no format works

silver moat
#

is it animated?

neat field
#

nope

silver moat
#

does the integration role have that also checked?

reef ice
#

https://stackoverflow.com/questions/67862216/discord-py-how-can-get-attachment-in-message-content
I was trying to make a to-do-list channel, where i can archive messages once their task is done.
I found this post on stackoverflow which was pretty much what i wanted.
But the code doesn't seem to work right, and i have no clue why.

@bot.listen('on_raw_reaction_add')
async def todo(payload):
    todo_channel_id = ********
    guild = await bot.fetch_guild(int(os.getenv('SERVER')))

    if (payload.channel_id == todo_channel_id) and (payload.user_id != *********) and (str(payload.emoji) == "πŸ”³"):
        todo_channel = bot.get_channel(todo_channel_id)
        message = await todo_channel.fetch_message(payload.message_id)
        finisher = await guild.fetch_member(payload.user_id)
        attachments=[await f.to_file() for f in message.attachments]
        await message.clear_reaction("πŸ”³")
        await message.add_reaction("βœ…")
        await message.author.send(f"""{finisher.nick} Ha completato il tuo incarico\n> {message.content}""",files=attachments)
        #print(finisher.nick,message.author)
        await bot.get_channel(***********).send(f"> {finisher.nick} Ha segnato l'incarico come completato\n\n{message.content}",files=attachments)
        await message.delete(delay=3)

My bot correctly makes a new message in the archive channel, and adds to it any attachments present in the task message, but they are all 0 bytes. the file name is correct, but they are just empty.
Shouldn't ".to_file()" get me actually the file?

neat field
silver moat
silver moat
neat field
#

the discord server is literally the default setup Discord provides, as I am only using it to test the bot, so the permission was on "/"

silver moat
#

Does the bot have access to the server which the emoji is from?

neat field
#

It is in the server which owns the emoji (hence why my formatting of the emoji is as it is)

silver moat
#

is the emoji ID correct?

#

Copy ID on the client side would copy the message ID

neat field
#

I even tried via the bot:

#

(the code you see is no longer what I use, I just used this to find out if I was getting the IDs wrong)

#
    print(f'[{time.strftime("%X")}][INFO] {ctx.user} asks: {prompt}')
    await ctx.response.defer(ephemeral=True)
    response = await api.GPT3().get_response(prompt=prompt)
    await ctx.followup.send(content="@<dashyellow:1063491896720236604> <dashyellow:1063491896720236604> :dashyellow:", view=views.RetryButton(prompt))```
#

this is what I have

silver moat
#

oh, it's \:dashyellow:

#

oh i hate discord formatting

#

like this without the space

young bone
neat field
#

oh lmao

#

nope, pycord

young bone
#

I just ask because of ```py
ctx: discord.Interaction

silver moat
#

in pycord ctx would be discord.ApplicationContext

neat field
#

ah, alright, would I need to modify anything else if I change it (I am porting this from d.py)

silver moat
#

just use ctx.defer()?

#

but it isn't necessary, it's just a short hand for ctx.interaction.response.defer

neat field
silver moat
neat field
#

I reuploaded it

young bone
neat field
#

I'll try getting the ID again brb

#

Ah I guess I copied the ID wrong or smth, it worked. Thanks for the help and the other tips.

silver moat
#

you're welcome

thick pumice
#

Help me please. I'm dying...
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
Code:

import os
import time
import discord
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv("config.env")

bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())


async def on_ready():
    print(f'{bot.user} has connected to Discord!')
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="PAPAI"))


@bot.slash_command(name="cycle", description="saikl")
async def cycle(ctx):
    while True:
        time.sleep(10)
        print(ctx.guild.member_count)


bot.run(os.getenv('BILIETININKAS'))

py-cord version - 2.3.2

#

(For me slash commands don't work in any files, but for my friend (that has exactly same code) they work perfectly fine)

silver moat
#

pip list and send output thanks

north gorge
#

I'm not terribly familiar on how to make a decorator, but I wanted to make one to do a "can this command be run in this channel" check and another to do a "do you have roles x y and z" check. Are there any gotchas to adding such decorators to a slash command, any particular order you have to list the decorators in, etc?

#

I gave it a stab and nothing worked and I got frustrated and gave up so I have no code to show lmao

plain marlin
#

what does this do? discord.ComponentType.role_select

#

because it doesnt work for me

#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 997, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 359, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 127, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 1202, in _invoke
    await command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 359, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: type object 'ComponentType' has no attribute 'role_select'
plain marlin
#

?

#

whats that?

#

how do you upgrade pycord on pterodactyl

young bone
#

Idk what that is

plain marlin
#

ok

young bone
#

or terminal?

thick pumice
iron juniper
frank herald
#

Is there a way to load a cog after the bot is ready (I need the user id to already be loaded)

alpine kernel
alpine kernel
#

think this

should be
bot = discord.Bot(command_prefix=".", intents=discord.Intents.all())

young bone
obtuse juncoBOT
#

dynoError No tag clients found.

young bone
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
alpine kernel
#

o, never used it like that

thick pumice
#

Just a question

#

And

#

What do I do?
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)

#

Do I need to have discord package installed?

grizzled sentinel
#

No

grizzled sentinel
#

Completely uninstall all discord bot librarys and reinstall pycord.

young bone
#

uninstall py-cord and reinstall it

thick pumice
# young bone show the pip list

There is a problem with this... I just PyCharm program, and sometimes it installs packages to "python310/**" folder and sometimes to my project folder so how do I check pip list?

#

In terminal I can use pip list but it's not accurate.

frank herald
thick pumice
#

I selected Virtualenv

frank herald
thick pumice
#

But

frank herald
#

Im not 100% sure how you can use pip in venvs

thick pumice
#

It says that in here

#

But there is another button called Python Python Packages

frank herald
#

do pip uninstall py-cord and do pip install py-cord

thick pumice
#

I just did it but ok

#

And btw

frank herald
#

oh

thick pumice
#

I created new project

#

And installed only py-cord

#

It works... Sort of..

#

It just shows that it is online, but I have sat the status and on_ready message. And none of these things happen

#

It just being there online with no use

thick pumice
# frank herald oh

Maybe there is a location where pycharm creates logs or something like that?

thick pumice
frank herald
#

can you show the code rq

alpine kernel
#

slash commands sometimes take some time to register for me

#

so might wait 30s or so

thick pumice
# frank herald can you show the code rq
import os
import time

import discord
# from discord.ext import commands
import dotenv

dotenv.load_dotenv(".env")

# bot = discord.Bot()
bot = discord.Bot()


async def on_ready():
    print(f'{bot.user} has connected to Discord!')
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="something"))


@bot.slash_command(name="cycle", description="cycle command")
async def cycle(ctx):
    while True:
        time.sleep(10)
        print(ctx.guild.member_count)


bot.run(os.getenv('TICKET_TOKEN'))
frank herald
thick pumice
#

But

#

It doesnt say print(f'{bot.user} has connected to Discord!')

thick pumice
#

Okay...

frank herald
#

add that

thick pumice
#

OOooogh bru

frank herald
#

didnt notice at first lol

thick pumice
#
Traceback (most recent call last):
  File "E:\CodingProjects\TicketBot\main.py", line 13, in <module>
    @bot.event()
     ^^^^^^^^^^^
TypeError: Client.event() missing 1 required positional argument: 'coro'

Error

alpine kernel
#

yeah it's kinda hard working with discord apis stuff can be tricky how you use it

thick pumice
#

yeah..

young bone
#

remove the ()

thick pumice
#

Ok

alpine kernel
#

especially going from discordpy to pycord heh

thick pumice
#

Ogh πŸ˜„

frank herald
thick pumice
#

Ok it says start message

#

I'm stupid πŸ˜„

alpine kernel
#

eh so many minor details i just decided to start fresh on my simple bot

#

there's a lot of similarities but a lot of things are renamed I felt like

thick pumice
#

Yeah

alpine kernel
#

I do have a question though, I'm using
@commands.cooldown(1, 86400)
but i want it to respond with an ephemeral message, so i captured it with

  @_addcharacter.error
  async def on_application_command_error(self, ctx: discord.ApplicationContext, error: discord.DiscordException):
     await ctx.send_response(content=error, ephemeral = True)

but it still attempts to send the original error after the error is captured, am i doing something backwards?

#

(i know i should check the instance of the error, just trying to sort this out quick)

loud holly
alpine kernel
#

sorry if it was unclear, I do get my ephemeral message sent in the above on_application_command_error(), but after that in the terminal i get this:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: RuntimeError: Interaction was already issued a response. Try using ApplicationContext.send_followup() instead.

#

which I think it's throwing the error, doing my response, but then continuing to attempt it's own original message with the error, which I dont want to do

#

I guess i could try and capture that error as well, but kinda seems like I'm doing something wrong heh

#

oh i'm dumb, I had another error capturing function so that is what was trying to send the 2nd response

#

but shouldnt the "@functionname.error" only receive errors from the associated function?

#

ok nvm again, i think making that change required time to update as well >.<

hushed ledge
#

One message removed from a suspended account.

wind jay
#

what is more efficent or is there a more efficent way to get all user ids from a server?

way 1:

members = await guild.fetch_members()
user_ids = [member.id for member in members]

way2:

user_ids = [member.id for member in guild.members]
young bone
#

use the second one

loud holly
silver moat
#

the first one iff you don't have members intent

fallow hawk
#

is there any way to give an option a value?

rare ice
#

.rtfm discord.Option

rare ice
#

The answer is no.

#

Since what’s returned to you is the label of the option.

fallow hawk
#

oh oops im sorry i meant choice

#

these things

errant craneBOT
#

Here's the slash options example.

silver moat
#

@fallow hawk ^

fallow hawk
#

thank you

vapid pumice
#

Would someone be so kind to point me towards docs for "apps" - like the right-click message apps?

#

It's quite the difficult thing to search blobpain

#

Are these called MessageCommands?

silver moat
#

yeah

vapid pumice
#

Okay YAY tnx! Never used these before!! This should be fun ^-^

fervent cradle
#

how can I use multiple on_message events?

limber urchin
#

Why would you ever need more than one?

fervent cradle
#

I don't need more than one, but it's more simple since my first on_message event is for boost messages

fervent cradle
coarse spire
#

I'm getting the error "No module named discord", it has worked fine before now. I'm using V.2.1.0 of discord and 2.3.2 of pycord.

fervent cradle
#

is there a way to hide the command menu for users that are using the bot from dms?

narrow moss
#

how to disable a other button of the same class after click

iron juniper
#
Ignoring exception in command ticketas:
Traceback (most recent call last):
  File "C:\Users\Dreyon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\Dreyon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 980, in _invoke
    await self.callback(ctx, **kwargs)
  File "C:\Users\Dreyon\PycharmProjects\pythonProject\main.py", line 259, in ticketas
    await ctx.send(embed=embed, view=MyView())
  File "C:\Users\Dreyon\PycharmProjects\pythonProject\main.py", line 136, in __init__
    self.guild = ctx.message.guild
AttributeError: 'NoneType' object has no attribute 'guild'

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

Traceback (most recent call last):
  File "C:\Users\Dreyon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Dreyon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\Dreyon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'guild'
#

how do i fix it, i tried making all of the commands my friend @thick pumice made to slash commands and i keep getting this error

young bone
iron juniper
#

idk ask endas he made the code im just converting it cause hes struggling

#

i found out what pycord like 2 days ago

young bone
iron juniper
#

yeah ik

#

but there are like few diffrences i still need to learn

young bone
#

I really want to use the new version because it will be way faster and not anymore a fork of dpy

fervent cradle
#

Why after reloading bot can't get old messages?

limber urchin
#

Probably because you're getting the messages from the internal cache

#

which is cleared when the bot is restarted

fervent cradle
#

and what should i do?

limber urchin
#

πŸ€·β€β™‚οΈ you're not showing any code so I don't know

fervent cradle
#
    async def callback(self, interaction: discord.Interaction):
        suggestion = await models.SuggestionModel.get_or_none(message_id=self.message_id)
        message = interaction.client.get_message(self.message_id)


        if self.values[0] == "delete":
            await message.delete(reason=f"{interaction.user} (ID: {interaction.user.id}): Π£Π΄Π°Π»ΠΈΠ» ΠΏΡ€Π΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΠ΅ {suggestion.id}")
            await interaction.response.edit_message(content=f"πŸ—‘οΈ ΠŸΡ€Π΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΠ΅ **β„–{suggestion.id}** ΡƒΠ΄Π°Π»Π΅Π½ΠΎ!", embed=None, view=None)
            return await suggestion.delete()
        if self.values[0] == "thread":
            await message.create_thread(name=f"ΠžΠ±ΡΡƒΠΆΠ΄Π΅Π½ΠΈΠ΅ β„–{suggestion.id}", auto_archive_duration=1440)
            return await interaction.response.send_message("ΠžΠ±ΡΡƒΠΆΠ΄Π΅Π½ΠΈΠ΅ Π½Π°Ρ‡Π°Ρ‚ΠΎ!", ephemeral=True)
limber urchin
#

.rtfm fetch_message

proud mason
fervent cradle
proud mason
fervent cradle
#

yeah I do, but when having multiple, either both of them stop working or just one works

proud mason
#

Although I'm not sure if you can have multiple listeners of the same event in a single cog

fervent cradle
#

alright I'll just do some quick examples in here, both examples are in different files

#

Example 1

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

    @commands.Cog.listener()
    async def on_message(self, message):
        PubBoostChannel = self.bot.get_channel(1029177560401182790)
        if message.channel.id != 1040285655604924547:
            return
        embed = (
            discord.Embed(
                title="hi"
            )
        )
        await PubBoostChannel.send(content=message.author.mention, embed=embed)
#

Example 2

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

    @commands.Cog.listener()
    async def on_message(self, message):
        if "test" in message.content:
            await message.add_reaction(":grinning:")
proud mason
#

Yeah so that works

#

Does it work for you or no?

fervent cradle
#

it doesn't, I'll try again, but doubt I'll get a different output

proud mason
#

πŸ‘

#

If it doesn't work, show the output and stuff

fervent cradle
#

alright weirdly enough it works now. I'm gonna add more events and see if it bugs

proud mason
#

Lol

fervent cradle
#

it's so embarrassing every time I ask for help with something, and it just randomly starts working

astral mist
#

Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\Vibes\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 377, in _run_event     
    await coro(*args, **kwargs)
  File "C:\Users\Vibes\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1164, in on_connect       
    await self.sync_commands()
  File "C:\Users\Vibes\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 738, in sync_commands     
    app_cmds = await self.register_commands(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Vibes\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 531, in register_commands 
    prefetched_commands = await self._bot.http.get_guild_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Vibes\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 360, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
#

do i need intents for this to work

#

its a moderation command

#

that output this as traceback

young bone
obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord β€” whether it's a bot or a game or whatever your wildest imagination can come up with.

astral mist
young bone
#

yes

#

but does the bot has the permissions and intents at the website?

astral mist
#

sorry for ping

young bone
#

The ping is fine for me ^^

astral mist
thick pumice
#

Hello. Anyone have any idea how I can fix this?

full basin
#

You're missing arguments on your callback

full basin
#

Button is first.

thick pumice
#

Ok sec

full basin
#

Read the docs.

thick pumice
#

I know but like

#

I used to have that error when button was first, I swapped places with interaction and it was fixed, but now I have to swap again? ok I'll try

thick pumice
#

Ir works.

thick pumice
limber urchin
#

You can't just say "for this to work" without showing what you're trying to make work

thick pumice
#

Ok I have another problem.

astral mist
errant craneBOT
astral mist
#

my code dont fit

astral mist
limber urchin
#

Intents has nothing to do with permissions

#

You're probably trying to timeout the server owner or an administrator

#

Or the bot doesn't have permission to timeout

astral mist
#

its on run

limber urchin
#

???

astral mist
#

and the bot has admin perms

limber urchin
#

Why did you send the code for a timeout command then?

astral mist
#

i am running and getting the error

limber urchin
astral mist
#

i never ran the command

limber urchin
#

Why did you send the code for a timeout command then?

astral mist
#

i thought it had something to do with it

#

so i just sent it

limber urchin
#

Why would that have anything to do with it if you're not even running the command?

astral mist
limber urchin
#

Send the code that isn't working instead of sending random commands

astral mist
#

on the slash command list

astral mist
limber urchin
#

No, you just said your error appears when you run the bot

#

so why on earth would it not be the code that runs your bot?

astral mist
#

but the command isnt showing up

#

the bot is working but just that command isnt showing up

limber urchin
#

because you're getting an error when you're running your bot

astral mist
limber urchin
#

How

#

am

#

I

#

supposed

#

to

#

know

#

if you don't show the code that is causing the error?

astral mist
#

its that code cus when i remove it

limber urchin
#

the code that is causing the error

#

Bro you literally just said that it's not that code

astral mist
#

this is the most confusing talk i have ever had

limber urchin
astral mist
limber urchin
#

Okay so what is the servers variable then?

astral mist
limber urchin
#

And is the bot in both of those servers? With the application.commands scope?

astral mist
#

wait

astral mist
#

only 1 at the time

limber urchin
#

That's obviously not going to work, a bot can't register commands in a server that it isn't in.

astral mist
#

wow

fervent cradle
#

I keep experiencing this import error or some reason;

Traceback (most recent call last):
  File "c:\Users\syass\OneDrive\Desktop\Other Stuff\Python\Verasseti\src\main.py", line 37, in <module>
    from cogs.commands.user.Reminder import RemindMeCommand
ImportError: cannot import name 'RemindMeCommand' from 'cogs.commands.user.Reminder' (c:\Users\syass\OneDrive\Desktop\Other Stuff\Python\Verasseti\src\cogs\commands\user\Reminder.py)
#

I've imported the command as I normally would with other commands

limber urchin
#

Why are you doing it like that? Why not just loop over the files in the folder?

fervent cradle
#

what do you mean? how do I do that?

limber urchin
#

You can load an extension from the file path, as long as you replace / with ..
So if you have a folder called cogs with a bunch of Python files.

for f in os.listdir('cogs'):
    f = f.replace('.py', '') # Remove the file extension
    extension = f'cogs.{f}'
    bot.load_extension(extension)
fervent cradle
#

so all of these I can load just by doing that

limber urchin
#

yes

fervent cradle
#

alright ty, I'm experiencing errors with that too, but I'll figure it out later

proud mason
#

jk lol

proud mason
#

so it loads cogs from folders inside folders too

limber urchin
#

didn't even know that was a thing

proud mason
#

lmao

celest gulch
limber urchin
#

.rtfm walk_commands

limber urchin
#

.rtfm walk_application_commands

celest gulch
knotty surge
#

There anyway to have a user send a txt file and the bot to download and read it?

limber urchin
#

yes

knotty surge
#

How would I go about doing that?

limber urchin
#

Have the bot accept a file as an option to your command, and then read the file with Python

#

pretty simple

heady remnant
#

I keep getting this error : AttributeError: 'Client' object has no attribute 'slash_commands', how can I fix it?

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
heady remnant
#

I already tried to uninstall and reinstall pycord and discord but nothing

#

If I use discord.Bot it says discord has no attribute Bot

#

:'|

young bone
frank shale
#

You do not need discordpy to make the pycord working

heady remnant
#

there is pip list

#

i always did pip uninstall discord``````pip uninstall discord.py``````pip uninstall pycord``````pip install -U git+https://github.com/Pycord-Development/pycord but it won't fix

limber urchin
#

Then your python installation is broken or you're doing something wrong

#

You can't have any other library that uses discord as a namespace

#

and you have like 5

heady remnant
#

i am using replit, maybe is something wrong with it?

limber urchin
#

Oh ew

#

That's probably why everything is broken then

heady remnant
#

i had already fixed it but this time it won't fix

#

ps i fixed it on replit and then the bot works but this time nothing :'(

limber urchin
#

Just don't use replit

#

?tag norepl

obtuse juncoBOT
#

Why NOT to use Repl as a hosting platform

You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You'll need a web server alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.

IMPORTATNT

  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.

heady remnant
#

πŸ₯²

proud mason
#

even oracle has free vps

#

or railway.app is free too

silver moat
#

if you have a credit, a great free service is railway.app

heady remnant
#

so which is the best way(for free) to host my bot?

limber urchin
heady remnant
#

for me it takes a little bit to send the message πŸ˜…

silver moat
#

if you are a student, microsoft azure if also great.

proud mason
#

wait wrong reply. ignore the reply

limber urchin
#

tldr, replit is too beginner friendly, there are better options

silver moat
#

you mean wrong repl-y

proud mason
#

if you are a mad lad and still want to use replit, ?tag replit in #883236900171816970 for instructions. not tested if they work

silver moat
#

I should probably make the new instructions on a gist or something

limber urchin
#

If you're making a Discord bot, you're expected to already know how Python packages work, and learning a few basic linux commands takes 5 minutes. So setting up your own VPS should be a piece of cake.

heady remnant
#

i am now using visual studio code on my pc but the error isn't gone, what i need to do?

heady remnant
#

AttributeError: 'Client' object has no attribute 'slash_command'

silver moat
#

show code thanks

#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
heady remnant
#
import pycord
from pycord import *
import discord
from discord.ext import commands
from discord.ext.commands import bot
from discord_webhook import DiscordWebhook
import asyncio
import os
import random
import time
import tweepy
from tweepy import *

from keep_alive import keep_alive

intents = discord.Intents.default()
client = discord.Client(intents=intents)

###################
#twitter

# Twitter API keys
consumer_key = os.getenv("consumer_key")
consumer_secret = os.getenv("consumer_secret")
access_token = os.getenv("access_token")
access_token_secret = os.getenv("access_token_secret")

# Twitter account to track
twitter_username = ":D"

channel_id = "ID"

webhook_url = os.getenv("webhook_url")

#auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
#auth.set_access_token(access_token, access_token_secret)
#api = tweepy.API(auth)

tweets_list = []


async def check_tweets():
        tweets = api.user_timeline(screen_name='GenshinImpact', count=1)
        for tweet in tweets:
                if tweet.text not in tweets_list:
                        tweets_list.append(tweet.text)
                        with open("tweets.txt", "a") as f:
                                f.write(tweet.text + "\n")

                        channel = client.get_channel(channel_id)
                        await channel.send(tweet.text)

async def always():
    while True:
        await check_tweets()
        asyncio.sleep(300)
####################

@client.event
async def on_ready():
    print("We have logged in as {0.user}".format(client))

@client.slash_command(name="say", description="Says everything you write after the command")
async def say(ctx, text):
    await ctx.respond("{}".format(text))



@client.slash_command(name="botname", description="Send bot name (idk what to do)")
async def botname(ctx):
    await ctx.respond('Bot name: {0.user}'.format(client))


keep_alive()
client.run(os.getenv("TOKEN"))```
proud mason
#

Byw, there is no import pycord....

heady remnant
proud mason
#

Also, don't use discord_webhook. Pycord has webhook built in

heady remnant
#

pycord has everything :D

proud mason
#

Show your pip list too

heady remnant
proud mason
#

Also, don't use wildcard imports (the import *) it becomes difficult to debug

heady remnant
#

oke

proud mason
# heady remnant

Ok. Try to migrate discord webhook to py-cord so you can uninstall that too.

Also pycord is a different library than py-cord blobpain
So uninstall pycord too. It is some FFMpeg wrapper not related tk discord bots at all

heady remnant
#

do i need also to change import pycord to import py-cord?

heady remnant
limber urchin
heady remnant
#

File "c:\Users\Downloads\Obi-tests (1)\main.py", line 61, in <module>
@client.slash_command(name="say", description="Says everything you write after the command")
AttributeError: 'Client' object has no attribute 'slash_command'

#

:')

limber urchin
#

What's your code now?

heady remnant
#
import discord
from discord.ext import commands
from discord.ext.commands import bot
import asyncio
import os
import random
import time
import tweepy
from tweepy import *

from keep_alive import keep_alive

intents = discord.Intents.default()
client = discord.Client()

###################
#twitter

# Twitter API keys
consumer_key = os.getenv("consumer_key")
consumer_secret = os.getenv("consumer_secret")
access_token = os.getenv("access_token")
access_token_secret = os.getenv("access_token_secret")

# Twitter account to track
twitter_username = ":D"

channel_id = "ID"

webhook_url = os.getenv("webhook_url")

#auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
#auth.set_access_token(access_token, access_token_secret)
#api = tweepy.API(auth)

tweets_list = []

async def check_tweets():
        tweets = api.user_timeline(screen_name='GenshinImpact', count=1)
        for tweet in tweets:
                if tweet.text not in tweets_list:
                        tweets_list.append(tweet.text)
                        with open("tweets.txt", "a") as f:
                                f.write(tweet.text + "\n")
                        # Invia il messaggio in un canale specifico su Discord
                        channel = client.get_channel(channel_id)
                        await channel.send(tweet.text)

async def always():
    while True:
        await check_tweets()
        asyncio.sleep(300)
####################

@client.event
async def on_ready():
    print("We have logged in as {0.user}".format(client))

@client.slash_command(name="say", description="Says everything you write after the command")
async def say(ctx, text):
    await ctx.respond("{}".format(text))



@client.slash_command(name="botname", description="Send bot name (idk what to do)")
async def botname(ctx):
    await ctx.respond('Bot name: {0.user}'.format(client))

keep_alive()
client.run(os.getenv("TOKEN"))```
young bone
#

its still discord.Client

#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
limber urchin
limber urchin
#

I thought they stopped using Replit?

young bone
#

nope

#

@heady remnant Do you know the basicΒ΄s of Python?

heady remnant
#

Traceback (most recent call last):
File "c:\Users\Downloads\Obi-tests (1)\main.py", line 100, in <module>
client.run(os.getenv("TOKEN"))
File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run

  • Serving Flask app 'keep_alive' (lazy loading)

  • Environment: production
    return future.result()
    File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
    WARNING: This is a development server. Do not use it in a production deployment. await self.start(*args, **kwargs)
    File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
    await self.login(token)
    File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 508, in login
    raise TypeError(
    TypeError: token must be of type str, not NoneType

    Use a production WSGI server instead.

  • Debug mode: off

  • Running on all addresses.
    WARNING: This is a development server. Do not use it in a production deployment.

  • Running on http://192.168.1.52:8080/ (Press CTRL+C to quit)

heady remnant
heady remnant
#

but a little bit i know it

limber urchin
#

"a little bit" is not enough to be making a Discord bot

#

you're evidently just guessing and hoping to get it right instead of actually understanding the help we're trying to give you

young bone
#

I can see it really fast if someone knows the basicΒ΄s of Python

heady remnant
#

i have a friend who is studying python but lso him don't know how to resolve it :'|

limber urchin
#

Your friend must not be studying very well then, because these issues are easily solved by knowing the basics of OOP in Python and how a Python environment works

heady remnant
#

him is in 3rd grade of high school

#

ps we are not english

limber urchin
#

what difference does that make?

heady remnant
#

idk i was thinking from state to state it is different

limber urchin
#

I don't care if you're on your 5th year of university, if you don't know the basics of OOP and async-await in Python, you should not be making a bot

#

Python does not change depending on what country you are in

heady remnant
#

him also made a discord bot with chatgpt api i don't think him is that stupid

limber urchin
#

Then ask him for help, you're in the wrong place if you think we're just going to give you a solution. We've explained what you're doing wrong and you didn't understand it. Now follow #help-rules or leave.

heady remnant
#

*i was only asking for help ... πŸ₯² πŸ₯Ή *

limber urchin
#

And we provided it

#

You were given the help you're expected to get, if you don't understand it, that's on you. We don't spoonfeed here

#

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

zinc cloak
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/main.py", line 26, in on_connect
    bot.add_cog(moderation.warncommand(bot))
  File "/home/container/.local/lib/python3.11/site-packages/discord/cog.py", line 653, in add_cog
    raise discord.ClientException(f"Cog named {cog_name!r} already loaded")
discord.errors.ClientException: Cog named 'warncommand' already loaded```
Hey so I added cogs to my discord bot in my on_connect event function. However, when I run the bot for long periods of time, I get this error. It seems to be connecting a reconnecting and reregistering the command. Is there another place I'm supposed to register my cogs? Or should I just ignore this error?
Thanks!
limber urchin
#

You don't need to load your cogs in any event. Just run a function that loads them after your bot starts

zinc cloak
#

If it's not in an event

limber urchin
#

With ()? πŸ€”

#

You know how to call a function in Python right?

zinc cloak
#

Wait so even if it's not connected to discord...

zinc cloak
#

Wait so cogs are registered client side...?

#

Or is it put in queue

silver moat
zinc cloak
silver moat
#

yw

zinc cloak
#

Is there a way to reload all commands to be registered?

#

I tried to manually register some commands after they weren't showing up for a while (couple of days)

#

and it caused some issues with the other commands

#

Nvm, it's bot.sync_commands()

#

And it doesn't require any parameters which is grat

#

great*

fervent cradle
#

how do i create an error & pass the interaction to it

#

interaction: Interaction

silver moat
fervent cradle
#

an error class

#

wait actually i dont need i guess

#

just tell me how to create an error class that i can handle inside on_error

silver moat
fervent cradle
#

how do i create an error class then handle it in on_error when its raised

#

like what should i subclass

silver moat
#

Exception

fervent cradle
#

ah

#

i thought i need to subclass some specific discord thing

#

ty

silver moat
#

yw

verbal marten
#
class RequestView(discord.ui.View):
    def __init__(self, bot):
        super().__init__()
        self.bot = bot
        self.timeout = None
        self.cd_mapping = commands.CooldownMapping.from_cooldown(1, 7200, commands.BucketType.member)

    @discord.ui.button(label="Request a worker",custom_id="request:worker", emoji="🚜", style=discord.ButtonStyle.blurple)
    async def request(self, button, interaction):
        bucket =               self.cd_mapping.get_bucket(interaction.message)
        retry_after = bucket.update_rate_limit()
``` Can anyone see any issues with this code for a button cooldown? It seems to be setting the cooldown for every user, not on a per-user basis