#Basic Pycord Help (Quick Questions Only)

1 messages · Page 6 of 1

cyan quail
#

if there's any changes in particular you want to ask about then go ahead, but yeah most of these changes probably don't affect you

drifting current
#

is this just a name change?

cyan quail
#

you now check permissions from the channel instead of the member

#

so if before you were doing ctx.author.permissions_in(ctx.channel), it would become ctx.channel.permissions_for(ctx.author)

#

as one example

drifting current
#

I see

cyan quail
#

this is more inline with how discord shows permissions to the user (i.e. opening a channel's edit menu to see all user and role permissions)

drifting current
#

yeah its a pain to change it everywhere wowcry

#

definitely cool for new coders but migrating is e.e

cyan quail
#

if it wasn't now, you're more or less guaranteed to run into breaking changes somewhere along the line

#

ultimately just a part of development

drifting current
#

yep

celest lichen
#

hi guys, trying to set up a venv for my bot repo and it is an absolute nightmare lmao

#

i'm using vscode as my ide

#

when i made the venv it automatically detected it and asked if i wanted to switch to it, i said yeah

#

all good so far. but when i install stuff with pip, it installs to my global packages, not to my venv

#

and when i run where python i get my global installation in program files or whatever

silver moat
#

you need to activate your venv

#

and you see a (env) next to the cmd line prompt

cyan quail
#

pretty sure vscode also has a ui interface for package management for your venv

celest lichen
#

oh really ???

#

shouldnt this be working ??

#

this is using normal cmd prompt, when i try to activate the venv in the default vscode bash terminal it doesn't even recognise the command

cyan quail
#

python -m pip

celest lichen
#

ughhhh yep that was it lmaoo

cyan quail
#

ah i see

#

pycharm supremacy

celest lichen
#

installing that now, thank you

#

does pycharm have source control tools? might install it

celest lichen
#

yeah sorry

fervent cradle
#

What would be the best way to repeat a command? I’m sending a request and if the return containers a certain word I want it to just retry instead of them manually retrying the command.

cyan quail
#

pycharm's awesome but do note it's fairly different to vscode so if you're comfortable with vs then you might not enjoy the switch

fervent cradle
#

Yes

cyan quail
#

or prefix

#

hmmmm

silver moat
#

use a command mention

celest lichen
#

i've used vscode for quite a while - if it'd be a rly steep learning curve then i might stick with it

silver moat
#

so they click and enter

cyan quail
#

^ either print a mention, or if you want it to be "automatic" then you'd need to give them some sort of component to reinvoke it with a new interaction token

fervent cradle
#

I see

#

Thanks for the help guys

cyan quail
#

all good

silver moat
#

you're welcome

fervent cradle
#

I’m currently using ctx.invoke which works but when the command is invoked ctx.respond doesn’t work. So it sends the request but there’s no user feedback because it can’t respond. Would there be anything I could do with that?

cyan quail
#

e.g. send a button, and in the callback py ctx.interaction = interaction await ctx.invoke(...)

fervent cradle
#

Alright ty

fiery tiger
#

https://hastebin.com/yerafaciri.rust - error

whitelisted = fields.ManyToManyField("Bot.UserModel", on_delete=fields.SET_NULL, null=True, related_name="whitelisted")
vanity_whitelisted = fields.ManyToManyField("Bot.UserModel", on_delete=fields.SET_NULL, null=True, related_name="vanity_whitelisted")

That error is coming from those 2 lines...

#

why is the value empty?

warm kindle
#

Hello, peoples. what is this error ?

silver moat
meager heron
#

How long should I expect Bot.wait_until_ready() to take on a bot in a few hundred servers?

rare ice
#

Maybe a few seconds -10 seconds depending on your host and latency?

royal spindle
#

what was the class in which pycord auto converted normal commands to slash commands, was that on a seperate branch altogether?

silver moat
#

@royal spindle

royal spindle
#

so will ctx.send be converted to the ephemeral type in the slash command version of the same?

royal spindle
#

so will the followup be automatically implemented?

silver moat
#

text-based will be a reply

royal spindle
#

if i use ctx.respond 2 times

silver moat
#

yeah

#

ctx.respond already does that afaik

royal spindle
#

it does?

#

so if i disable the normal counterpart by doing client.get_command
will the slash version also get disabled?

#

I was actually looking for this class for this reason

#

the normal command has a boolean .enabled

fervent cradle
#

yo

#

how can i create a forum channel using the api

#

or pycord

silver moat
#

you can’t if the server doesn’t have access to them in the first place

fervent cradle
#

How can i get category id

tiny wagon
#

whats the pblm here:

type_: Option(str, 'Choose Global or server leaderboard', choices=['Global', 'Server'], default='Global'),

order: Option(str, 'Order of Leaderboard', choices=['Ascending', 'Descending'], default='Descending')```
docs say providing default sets required to False, but still discord shows it as required argument while testing
quasi swan
#

how can i see in what servers my bot is

cyan quail
cyan quail
quasi swan
cyan quail
#

what

#

that's literally the answer

mortal cairn
#

how do i properly add a function to be executed before the main command invocation in a slash command? like before_invoke() but i couldn't get it to work with slash commands

tiny wagon
#

should show | +2 optional

#

also cant send command leaving blank, so required not working in this case

verbal gulch
#

Hi, so i have a question, i can make buttons, directly in the command? After @bot.slash_command, because i only need that button in one command, and it need a parameter of the command.

strange wagon
#

i've seen bots where it's possible to upload files with slash commands - how do I do that with pycord?

full basin
full basin
strange wagon
full basin
#
async def cmd_callback(ctx, attachment: discord.Attachment)```
strange wagon
#

ahhh

#

thanks

full basin
#

Or you can also use Option

#
async def cmd_callback(ctx, attachment: discord.Option(discord.Attachment, "Drop a file"))```
strange wagon
cyan quail
#

apparently there's a bug where options don't refresh without removing the command and adding it back

strange wagon
full basin
strange wagon
#
import discord
from discord.ext import commands
from discord.commands import slash_command
from discord.commands import Option  #Importing the packages
import datetime
import json
config = json.load(open("config.json"))


class balls(commands.Cog):
    def __init__(self, bot):#to Initialise
        self.bot = bot

    @slash_command()

    async def cmd_callback(ctx, attachment: discord.Option(discord.Attachment, "Drop a file")):
        await ctx.respond("Okay")
            
def setup(bot):
    bot.add_cog(balls(bot))```
verbal gulch
full basin
cyan quail
strange wagon
#

unless that's part of the problem in the github issue

fervent cradle
#

how do i make a slash command that is only visible and usable by the bot owner

strange wagon
fervent cradle
#

ah, alright

rotund berry
#

Can we help?

young bone
tranquil pivot
#

Hey guys, I have 3 dropdowns and I’m trying to use all 3 selections for a query. Is there an easy way to pull all 3 values? Right now each one is a local variable within the callback

rotund berry
tranquil pivot
tranquil pivot
#

just open cmd and type "pip list"

rotund berry
#

here

young bone
#

Oh

#

you have discord.bot but it need upper case "discord.Bot()"

rotund berry
#

Thx you

fading granite
#

Is it possible to send a message through timeout

wet leaf
#

I made a button with a callback function and id like to add a timeout to that, how would one?

pallid trench
#

the view

rare ice
dire spadeBOT
silent kite
#

Is there any way I can host the docs page locally? I'm currently on holidays and don't have decent internet so loading the docs takes a while longer than I would like.

silent kite
#

I've downloaded the 'docs' folder from the github page, but don't know how to run it.

wet leaf
#

I only want it to respond to one user

#

But the whole server tho be able to interact with it

rare ice
#

you said a timeout

wet leaf
#

Yeah? What else would you call it

#

To timeout if the user does not interact within x seconds

rare ice
#

yes thats a view timeout

wet leaf
#

Yeah tho that wont really work in my case as everyone can see the button

#

But it only responds to one person

#

Does waitfor work for buttons?

rare ice
#

then you're looking for an interaction check to check that the interaction.user is the person who ran the command

wet leaf
#

Im pretty sure you could do it using that

rare ice
#

b!rtfm pyc discord.ui.View.interaction_check

dire spadeBOT
fervent cradle
#

hey guys so i use this code for a command, but i just noticed that the response is really slow, is there anyway i can speed up the response

    @commands.slash_command(name="clown", description="make someone a clown")
    async def clown(self, ctx, *, clown_guy: Option(discord.Member, "who's the clown out here big man?", required=True)):
        await ctx.defer()
        try:
            clown_payload = {'image': clown_guy.display_avatar.url}
            clown_src = requests.get('https://luminabot.xyz/api/image/clown', params=clown_payload)
            clown_upload = imagekit.upload(file=clown_src.url, file_name="clown.jpg", options={})
            clown_embed = discord.Embed(title="New clown for the circus!")
            clown_img = clown_upload['response']['url']
            clown_embed.set_image(url=clown_img)
            await ctx.respond(embed=clown_embed)
        except Exception as clown_err:
            await ctx.respond(information.error_message)
            print(f"Something went wrong with the clown command: {clown_err}")
#

How can i get category id

rare ice
fervent cradle
fervent cradle
#

ok

silver moat
rare ice
#

should the image be deleted

silver moat
#

preferably

worldly schooner
#

whats the error raised when trying to build a member from non existing id?

copper dew
tiny wagon
#

whats up with this error, whenever i try to restart/stop script, it reloads cogs again and throws this err

copper dew
tiny wagon
tiny wagon
#

#1004777736222539826

copper dew
tiny wagon
#

this is the part of loading of cogs, it has no issues since 2 months

#

when i stop the script, bot adds cogs again which results in an error, then script finally goes off

dull mesa
#

Do messages ignore the delete_after parameter if the message is also ephemeral? I can't get mine to timeout at all

silver moat
warm kindle
#

mention me when reply a message from me

hushed ledge
#

One message removed from a suspended account.

#

One message removed from a suspended account.

rotund berry
#

Can me Help Me?

young bone
#

and you need at the end a :

abstract yew
#

add a ) at the end of the line

young bone
#

basic python?

abstract yew
#

yep

rotund berry
young bone
#

botinfo ()
^

abstract yew
#

you opened two ( but only closed one of them

abstract yew
young bone
#

k

#

you need a )):
at the end

rotund berry
young bone
rotund berry
abstract yew
#

yep

#

just add some code to the command and it will work

rotund berry
young bone
#

only videos?

rotund berry
rotund berry
young bone
#

pls learn basic python first

abstract yew
rotund berry
rotund berry
young bone
#

Könntest du bitte erst basic python lernen?

abstract yew
young bone
#

sonst wirst du viele probleme dabei haben

rotund berry
abstract yew
young bone
#

eigentlich nein

rotund berry
rotund berry
young bone
#

also nicht in diesem channel

abstract yew
#

if imma be honest, i actually learnt python from making a discord bot in discord.py

rotund berry
prisma flicker
#

how can I get the view from an interaction object?

young bone
prisma flicker
#

View.from_message(interaction.message)?

abstract yew
naive remnant
#

How do I send a message to a specificied channel

abstract yew
naive remnant
fervent cradle
abstract yew
#

guild.get_channel(id)

fervent cradle
#

or channel = guild.get_channel()

fervent cradle
abstract yew
young bone
#

if you use fetch_channel you need await if you use get_channel not

abstract yew
#

i forgor

young bone
#

or fetch_guild

abstract yew
#

My bot for some reason returns an empty string instead of the message.content. Anyone know the reason?

grizzled sentinel
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html

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)
grizzled sentinel
#

you need the message content intent

abstract yew
#

oh, i used to only use intents.messages. Thanks

#

was it split up?

grizzled sentinel
#

it kinda new. discord only started enforcing it in API version 10 and will start enforcing it in all version at the end of this month i think.

copper dew
grizzled sentinel
abstract yew
#

ok thanks, my bot works again

fervent cradle
#

Hello 🙂 How can i get all these bans? Will guild.bans(limit=999999) work? Thanks

grizzled sentinel
prisma flicker
#

would limit=0 work?

fervent cradle
#

Thank you, I will check by trial and error 🙂

fiery tiger
#

https://hastebin.com/yerafaciri.rust - error

whitelisted = fields.ManyToManyField("Bot.UserModel", on_delete=fields.SET_NULL, null=True, related_name="whitelisted")
vanity_whitelisted = fields.ManyToManyField("Bot.UserModel", on_delete=fields.SET_NULL, null=True, related_name="vanity_whitelisted")

That error is coming from those 2 lines...

#

@grizzled sentinel Do u mind checking this issue?

grizzled sentinel
#

Im not sure, its an issue with whatever lib you are using for your database. To me it looks like a lib error and not an user error. I would check there github for a similar error or contact there support

grizzled sentinel
# fiery tiger https://hastebin.com/yerafaciri.rust - error ```py whitelisted = fields.ManyToM...
wooden bone
#

I'm having trouble adding multiple select dropdowns to a message. I assume it's possible but can't get it to work. I figured this would work but it's not: class TemplateSelection(discord.ui.View): @discord.ui.select( placeholder = "Choose X", options = options_list ) @discord.ui.select( placeholder = "Choose Y", options = options_list )

cyan quail
#

i.e. ```py
@discord.ui.select(...)
async def callback_a(self, select, interaction):
...

@discord.ui.select(...)
async def callback_b(self, select, interaction):
...```

wooden bone
#

Gotcha. How would I do it without decorators? I'm pretty new to the library

cyan quail
#

if you want it without decorators, you can construct them and assign the callbacks separately ```py

Notice capitalization

select_a = discord.ui.Select(...)

async def callback(self, interaction):
...

select_a.callback = callback```

#

this would make it easy to assign the same callback to multiple components, but you should ensure to use custom_id in the select menu to properly validate the input

wooden bone
#

Okay, I think I see how that goes together.

#

As for the message itself, how would I get both of them to show at the same time?

cyan quail
#

(also those code samples were written with the assumption you're doing them inside your view class)

#

if you're subclassing discord.ui.View:

  • if you're using decorators, it'll be assigned to the view automatically
  • if you're not, you should do self.add_item(...)
#

then when sending the message, you just pass in view=... as a kwarg

wooden bone
#

Okay, got it. I'll fiddle around with this and see how it goes. Still getting used to Python object stuff

#

Thanks!

cyan quail
#

all good

fiery tiger
#

some value is empty

#

its similar tho i don't see a fix for it tho

fervent cradle
# cyan quail all good

do you know how to send the data of modal interaction response to a specific channel I have tried everything and it won't work

cold eagle
#

how do you check if someone has an avatar or not? this will make the bot send an error if the user has the default i'm pretty sure

full basin
#

.display_avatar.url

fiery tiger
#
class DiscordColorField(fields.IntField):
    def __init__(self, default=settings.colors.embeds, **kwargs):
        super().__init__(default=default, **kwargs)
        self.validators.extend([MinValueValidator(0x000000), MaxValueValidator(0xFFFFFF)])  

    def to_python_value(self, value: int) -> discord.Colour:
        return value
#
            Option(
                ColourNameConverter,
                name="color",
                description="Color of the Welcomer embed if in embed mode",
                autocomplete=color_autocomplete)
#
NAME_HEX_MAP: Final[Mapping[str, int]] = {color['name']: int(color['hex'][1:], base=16) for color in RAW_COLOR_MAP.values()}
COLOUR_NAMES: Final[list[str]] = list(NAME_HEX_MAP.keys())


def color_autocomplete(ctx: discord.AutocompleteContext):
    return sorted(color for color in COLOUR_NAMES if color.lower().startswith(ctx.value.lower()))[:25]


class ColourNameConverter(Converter[discord.Colour]):
    async def convert(self, ctx: Context, argument: str) -> discord.Colour:
        try:
            return discord.Color(value=NAME_HEX_MAP[argument])
        except KeyError:
            raise BadColourArgument(argument)
#

example of color

#

why is the keyerror rising?

fervent cradle
#

Do cogs increase performance?

silver moat
fervent cradle
#

paginator doesnt seem to work

#
class fun(commands.Cog):
    def __init__(self,bot):
        self.bot = bot
        self.pages = [
            "Page 1",
            [
                discord.Embed(title="Page 2, Embed 1"),
                discord.Embed(title="Page 2, Embed 2"),
            ],
            "Page Three",
            discord.Embed(title="Page Four"),
            discord.Embed(
                title="Page Five",
                fields=[
                    discord.EmbedField(name="Example Field", value="Example Value", inline=False),
                ],
            ),
            [
                discord.Embed(title="Page Six, Embed 1"),
                discord.Embed(title="Page Seven, Embed 2"),
            ],
        ]
        self.pages[3].set_image(url="https://c.tenor.com/pPKOYQpTO8AAAAAM/monkey-developer.gif")
        self.pages[4].add_field(name="Another Example Field", value="Another Example Value", inline=False)

    
    @commands.Cog.listener()
    async def on_ready(self):
        print('fun cog ready')
    @commands.slash_command(name="meme", description="Generates a random meme")
    async def meme(self, ctx):
        paginator = pages.Paginator(pages=self.get_pages())
        await paginator.respond(ctx.interaction, ephemeral=False)
``` what am i doing worong??
#

oh im dumb

#

im trying to do a discord.ui response that when you click the button it responds with an embed with two more buttons

rare ice
fervent cradle
#

i did

#
@bot.command()
async def ticket(ctx):
    button = Button(
        label="Create A Ticket",
        style=discord.ButtonStyle.green,
    )
    Option1 = Button(label="Request a Material Offer to Venerable",
                     style=discord.ButtonStyle.green)
    Option2 = Button(label="Make a Purchase Order",
                     style=discord.ButtonStyle.danger)

    async def button_callback(interaction):
        await interaction.response.send_message(
            "What Would you like to create a ticket about?", view1=view1)

    button.callback = button_callback

    view1 = View()
    view1.add_item(Option1)
    view1.add_item(Option2)
    view = View()
    view.add_item(button)

    await ctx.send("Hi!", view=view)
#

what am i doing wrong

rare ice
#

You should try subclassing, easier

#

@fervent cradle

fervent cradle
rare ice
#

Yes

fervent cradle
#

where is that

#

i cant figure that out

fervent cradle
rugged lantern
#

perhaps learn english sometime then

fervent cradle
#

dude

tiny wagon
#

whats the best alternative to restart while testing bot

rare ice
rare ice
tiny wagon
#

so better alternatives to restart

rugged lantern
#

you linked a website. that website clearly explains and answers the question. they're not doing anything to help themselves- so why do i owe them any kind of respect

rare ice
#

It’s a help channel for a reason, for people to get help with Pycord, Python and more.

fervent cradle
#
class MyView(discord.ui.View):
    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "Choose a Ticket Type", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Request a Material Offer to Venerable",
                description="Employee Only!"
            ),
            discord.SelectOption(
                label="Make a Purchase Order",
                description="Purchase Something from Venerable!"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message(f"I'm Creating a Ticket for you...")
cold eagle
#

i want to make it so if the user doesn't give a member, it'll just give information for themselves. how can i do that?

fervent cradle
#

what am i doing wrong?

young bone
#

And add "required=False

cold eagle
#

i'll try that

fervent cradle
#

i figured the response out

#

im trying to now have the bot create a text channel based on the name of the option

#
class MyView(discord.ui.View):
    
    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        
        placeholder = "Choose a Ticket Type", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Request a Material Offer to Venerable",
                description="Employee Only!"
            ),
            discord.SelectOption(
                label="Make a Purchase Order",
                description="Purchase Something from Venerable!"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        channel = guild.create_text_channel(f"{select.values[0]} Ticket")
        await select.response.send_message(f"I'm Creating a Ticket for you...", channel)
#

this doesnt work

cold eagle
#

i'm not sure what's going wrong

rare ice
fervent cradle
#

wouldnt it be select?

rare ice
rare ice
#

b!rtfm pyc discord.Interaction

fervent cradle
#

yes but its not an interaction

cold eagle
#
Ignoring exception in command rank:
Traceback (most recent call last):
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped
    ret = await coro(arg)
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 877, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "c:\Users\CENSOR\Documents\Github\file-storage\Robot Maxx\cogs\levels.py", line 38, in rank
    data = await self.lvl.get_data_for(member)
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discordLevelingSystem\decorators.py", line 62, in wrapper
    return await func(*args, **kwargs)
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discordLevelingSystem\decorators.py", line 80, in wrapper
    return await func(*args, **kwargs)
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discordLevelingSystem\decorators.py", line 104, in wrapper
    return await func(*args, **kwargs)
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discordLevelingSystem\leveling_system.py", line 1432, in get_data_for
    async with self._connection.execute('SELECT * FROM leaderboard WHERE member_id = ? AND guild_id = ?', (member.id, member.guild.id)) as cursor:
AttributeError: 'NoneType' object has no attribute 'id'

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

Traceback (most recent call last):
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 358, in invoke
    await injected(ctx)
  File "C:\Users\CENSOR\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
rare ice
#

interaction has an attribute of guild that is a guild object

cold eagle
#

oh i didn't think it would be that big

obtuse juncoBOT
cold eagle
#

i'll use that next time

rare ice
cold eagle
#

thanks, it works

#

this is all very new to me and while i do know how to code i never do stuff like this, i really appreciate anyone who helps me out in the future

rugged lantern
#

and if not member:

simple canopy
#

how can i possibly share 1 slash command group between multiple cogs

#

should i just import it from 1 specific cog all the time

#

or there is a better way

cold eagle
#

after using await bot.close() is it normal for the terminal to not give a new line to type in another command?

#

because every time i use my slash command to shutdown the bot, i still have to kill the terminal to start it up again

simple canopy
#

yes

#

it just closes the connection to discord's api

cold eagle
#

is there a way to make it more bearable to start the bot again?

simple canopy
#

you can just call exit() i think

#

not sure

simple canopy
cold eagle
#

i tried that it's like when a window stops responding and you can't interact with it

cold eagle
simple canopy
#

i know there is reload extension method, not sure about full bot

celest lichen
#

hi guys, have some very barebones code here that essentially just gets my bot online on discord (still learning how all this works) - when i run main.py my bot comes online, but does anyone know what's up with the little warning message abt python-dotenv in the terminal?

simple canopy
#

there is something going on with your .env file

#

may be you typed in something by mistake

#

on line 1

celest lichen
#

my env

#

token removed for obvious reasons

#

should my token be in quotes? is that the problem?

#

nope, appears to have made no difference

#

ohhh, it's the

env title=".env"
#

what should i change that to? is that line necessary?

simple canopy
#

you can just have ```bat
TOKEN=TOKEN_HERE

fading granite
#

Hello.

#

Is it possible to disable a View after certain number of seconds (ignoring interactions)

#

I'm not talking about timeout

fervent cradle
tiny wagon
#

i want to pass a channel list to choice(slash) after sets operations with it, is that possible?

fading granite
lofty falcon
#

after sending the message with the buttons

#

asyncio.sleep(10) //10seconds sleep

#

then you edit your message

fading granite
#

ye but I want to do a giveaway sort of thing

#

Where it disables at a specific time

young bone
fading granite
#

i did, i just dont know this asyncio thing

young bone
fading granite
#

oh ok thanks, will look into it

fossil canopy
#

Hey how can I get the inviter when someone joins over an invite link in a voice channel

fervent cradle
#

Hi , how can i fix this error "no modules named 'telegram' "

fading granite
#

hello, if i want to disable all items in a view,
can i use super().disable_all_items()
instead of

for child in self.children:
    child.disabled = True
#

your cog should be initialised like this

#

so self.bot contains all the info of the bot

full basin
#

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

fading granite
#

what's the error

fading granite
#

oh crap lol

#

you should use member.id instead of member bcs you're comparing id to id

full basin
#

a member object will never be an int

toxic tapir
#

is there a reason my cogs are not sending errors when they are loaded? When parts of my code are broken the cog doesn't load and it doesn't send errors to let me know how I can fix my code.

grizzled sentinel
toxic tapir
#

perfect, thanks :)

viscid wren
#

Hello, I wanted to ask if it was possible to work with cogs+slash commands without needing to reload the whole bot when making changes. As far as I understand you need to load the cogs before executing the bot.run() method. Is that correct? am I missing something?

fading granite
#

how do you define a default emoji on discord?

#

i used the :name: but it returns invalid emoji, when i set the emoji on a button to it

celest lichen
#

hi guys, what exactly do lines like @bot.event do exactly? it's not syntax i've ever really seen outside of writing discord bots

#

i think i understand that 'bot.event' is an attribute of my bot object, it's the @ i'm confused about

fading granite
fathom cipher
proud pagoda
#

It pretty much registers an event handler with the bot

#

So it takes the function below the decorator and runs that function every time the event is triggered

celest lichen
#

ahhhh

proud pagoda
#

so if you have

@bot.event
async def on_message(msg):
  pass

the function will be run every time a message is sent

fading granite
#

how do you apply the same callback to multiple buttons which were created by a loop?

celest lichen
#

okay! thank you!

proud pagoda
celest lichen
#

i understand you now

proud pagoda
celest lichen
#

i did a whole course on python 3 on codecademy and i don't think they mentioned any of this haha

#

i assume i can find a list of all events in the readthedocs site

fading granite
fathom cipher
#

bot.event is a method that takes a function (on_messasge) and subscribes and event based on the function's name

you could do the same thing just by

def on_message(msg):
  pass

bot.event(on_message)
proud pagoda
fading granite
#

ahh i get it

#

so button = Button()
then button.callback = await ...

proud pagoda
#

theres no need to put await

fading granite
#

hmm okay

proud pagoda
#

Because await will run the callback

#

since the callback should only run when the button is clicked

#

So instead so this:

button = Button()
button.callback = function_name
fathom cipher
#

await will not run.

proud pagoda
#

And the function should take one parameter of type discord.Interaction

proud pagoda
fervent cradle
fervent cradle
#

thank you

proud pagoda
#

You're welcome

proud pagoda
#

*typeerror

#

Pretty much it awaits an object representing a function, which is different from a coroutine

fathom cipher
#

I kind of lost track of the development here, so I don't want to waste my time digging through blames. psyduck
How I should handle command groups from legacy discord.ext.commands in Cogs? I came back to my project, did an update and got a million of type errors cuz types changed.

fading granite
#

ah got it thanks

proud pagoda
fathom cipher
#

yup

from discord.ext.commands import Cog, Context, group
class MyCog(Cog, name="My Cog"):
    _bot: CustomClient

    def __init__(self, bot: CustomClient):
        self._bot = bot

    @group(name="mygroup", invoke_without_command=False)
    async def my_group(self, ctx: Context):
      pass
fathom cipher
#
Argument of type "(self: Self@ModerationUtilsCog, ctx: Context[Unknown]) -> Coroutine[Any, Any, None]" cannot be assigned to parameter of type "((Concatenate[CogT@group, ContextT@group, P@group]) -> Coro[T@group]) | ((Concatenate[ContextT@group, P@group]) -> Coro[T@group])"
  Type "(self: Self@ModerationUtilsCog, ctx: Context[Unknown]) -> Coroutine[Any, Any, None]" cannot be assigned to type "((Concatenate[CogT@group, ContextT@group, P@group]) -> Coro[T@group]) | ((Concatenate[ContextT@group, P@group]) -> Coro[T@group])"
    Type "(self: Self@ModerationUtilsCog, ctx: Context[Unknown]) -> Coroutine[Any, Any, None]" cannot be assigned to type "(Concatenate[CogT@group, ContextT@group, P@group]) -> Coro[T@group]"
      Parameter 1: type "Concatenate[CogT@group, ContextT@group, P@group]" cannot be assigned to type "Self@ModerationUtilsCog"
        "Concatenate[CogT@group, ContextT@group, P@group]" is incompatible with "ModerationUtilsCog"
      Function accepts too few positional parameters; expected 2 but received 1
      Keyword parameter "ctx" is missing in destination
    Type "(self: Self@ModerationUtilsCog, ctx: Context[Unknown]) -> Coroutine[Any, Any, None]" cannot be assigned to type "(Concatenate[ContextT@group, P@group]) -> Coro[T@group]"
      Parameter 1: type "Concatenate[ContextT@group, P@group]" cannot be assigned to type "Self@ModerationUtilsCog"

for some reason it doesn't recognize methods properly :/

fervent cradle
proud pagoda
fervent cradle
#

channel = select.guild.create_text_channel(f"{author}'s'{select.values[0]} Ticket")

proud pagoda
fervent cradle
proud pagoda
#

yeah

#

Hold on are you trying to get what the user selected or just the first value of the select menu?

proud pagoda
proud pagoda
fathom cipher
#

It doesn't work because it's not even related to that 😩

fervent cradle
#
        await select.response.send_message(f"I'm Creating a Ticket for you...", channel)
proud pagoda
#

Well the syntax appears to be correct

fervent cradle
#

TypeError: send_message() takes from 1 to 2 positional arguments but 3 were given

proud pagoda
#

Remove the channel part

fervent cradle
#

then where do i add a channel

proud pagoda
#

send_message will send it to the channel in which the interaction occured

fervent cradle
#

so how do i create a channel when they press it?

proud pagoda
#

Uh

#

Well

#

Just get the channel object

#

After creating the channel

#

And then use channel.send

fervent cradle
#

i did it

#

but

#

the channel name is bad

#

it has the name and the numbers

#

async def button_callback(self, button, interaction):

#

it says that this line of code is invalid syntax

#

@rare ice sry for tagging u

#

it says this is invalid

viscid wren
rare ice
fervent cradle
#
    @discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.danger)
    async def button_callback(self, button, interaction):
      await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
rare ice
#

Do you have any code above that?

fervent cradle
#

just my roblosecurity

#

i think its a glitch

#

how do i send that view when the new channel is created?

#

and its in that channel

#

@rare ice how do i fetch a channel by defining it by the current channel that your in

#

sry for taggin u again

rare ice
#

Explain more please.

fervent cradle
#

like i want the close button to close the channel

#

delete it

#

but all the channel fetching ive done is by name or id

#

@rare ice

#

i really need help

rare ice
#

interaction.channel

#

Is the channel the interaction was used in

lusty token
#

So uh. I'm trying to get some embeds to work with slash commands. i can't get them to work. even when i use embeds=[embedVar]

fervent cradle
#

ok

#

and i need the permsiions to be only the one who created a ticket and the mods can enter the channel

lusty token
#
async def testCommand(ctx: interactions.CommandContext):
    testEmbed = discord.Embed(title='Testing', description="For testing")
    testEmbed.add_field(name="What's Being tested", value="Seeing if Embeds can be sent")
    testEmbed.add_field(name='Debug log', value=f"This Works! ")
    await ctx.send(embeds=[testEmbed])``` Am i just using outdated resources or am i just dumb
fervent cradle
rare ice
#

b!rtfm pyc discord.Permissions

rare ice
lusty token
fervent cradle
#

but how do i add specific roles

rare ice
#

?tag guide

obtuse juncoBOT
lusty token
#

i started by using the Normal stuff. but i wanted to use slash commands. took me forever to even find a slash command Structure that works

rare ice
#

do you mind sending what you tried and what error you got (if any)?

lusty token
#

You want me to show the whole of what i have now?

fervent cradle
#
        await channel.set_permissions(select.guild.default_role, send_messages=False)
tiny wagon
#

hi, i want to display a list of channels to choose in slash except some channels that i dont want to

fervent cradle
#

that makes it available to everyone how do i limit it to a specific role

lusty token
# rare ice do you mind sending what you tried and what error you got (if any)?
@bot.command(name = "test",description='Testing')
async def testCommand(ctx: interactions.CommandContext):
    testEmbed = discord.Embed(title='Testing', description="For testing")
    testEmbed.add_field(name="What's Being tested", value="Seeing if Embeds can be sent")
    testEmbed.add_field(name='Debug log', value=f"This Works! ")
    await ctx.send(embeds=[testEmbed])

if i do this the main error that's thrown is that AttributeError: 'Embed' object has no attribute '_json'

#

if i do it just embed

lusty token
rare ice
lusty token
#

i remember trying that and it not working, but i'll try again

tiny wagon
#

like can i use set union or intersection?

rare ice
rare ice
#

if you're wanting announcement channels to show:

#

?tag announcement_channel_options

obtuse juncoBOT
#

To add the discord.ChannelType.news channels to the discord.TextChannel channel list for slash commands, pass in channel_types=[discord.ChannelType(5)] into the option.

Credit: #997341890988998667 message

tiny wagon
celest lichen
#

can someone help me understand why the first function here runs fine, but the second returns TypeError: command() takes 1 positional argument but 2 were given? obviously the second one is a useless function i'm just trying to figure out more how decorators work

tiny wagon
lusty token
celest lichen
lusty token
rare ice
#

pip freeze

lusty token
#

sorry if i'm being a bit dumb pycord is just the whole of Discord.py correct

rare ice
tiny wagon
#

at 1.7.3, yes

celest lichen
lusty token
rare ice
celest lichen
#

lmao, fair enough

tiny wagon
#

um

rare ice
celest lichen
#

ohhh maybe because bot.command takes ctx but bot.event is a method without any arguments ?

civic jayBOT
#

Install pycord:

pip uninstall discord.py
pip install py-cord

Install pycord from git repository: (alpha)

pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
celest lichen
#

understood

lusty token
#

like overall

celest lichen
#

okay uhh, what the fuck

#

all i did was add the () to @bot.command()

rare ice
rare ice
#

we have all the features combined from discord.py, discord-py-slash-command and more.

#

i personally prefer pycord since it's updated more and maintained by more people

viscid wren
#

Do slash commands need to be added before running the bot (bot.run())? seem to only work that way

celest lichen
#
import discord
import os
from dotenv import load_dotenv

load_dotenv()
bot = discord.Bot(debug_guilds=[1004467511833677915],intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f"!!! ALERT !!! {bot.user} HAS BEEN ACTIVATED !!!")

@bot.command()
async def on_ready():
    print(f"!!! ALERT !!! {bot.user} HAS BEEN ACTIVATED !!!")

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

my full code

rare ice
#

hence why im working here :)

rare ice
rare ice
# celest lichen ```python import discord import os from dotenv import load_dotenv load_dotenv()...
import discord
import os
from dotenv import load_dotenv

load_dotenv()
bot = discord.Bot(debug_guilds=[1004467511833677915],intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f"!!! ALERT !!! {bot.user} HAS BEEN ACTIVATED !!!")

@bot.command()
async def on_ready(ctx):
    print(f"!!! ALERT !!! {bot.user} HAS BEEN ACTIVATED !!!")

bot.run(os.getenv('TOKEN'))``` just needed the `ctx` parameter for the command.
lusty token
fading granite
#

how do you add multiple buttons with the same callback

rare ice
fervent cradle
#

hello everyone, does anybody knows how to fix that?

#

its vsc btw

viscid wren
rare ice
fervent cradle
#

how to troubleshoot

viscid wren
rare ice
fervent cradle
#

thanks ig

lusty token
rare ice
viscid wren
#

ok, what about hot-reloading cogs?

viscid wren
#

Im interesting in never having to restart the bot

rare ice
viscid wren
#

loading/unloading cogs without restarting the bot

rare ice
lusty token
#

Is there an Easier way to do slash commands?

fervent cradle
#

@rare ice

async def button_callback(self, button, interaction):
      await interaction.response.send_message("This Ticket will be Deleted in 10 Minutes") 
AttributeError: 'Button' object has no attribute 'response'
rare ice
fervent cradle
#

that is it

#

class CloseTicket(discord.ui.View): # Create a class called View
@discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.danger)

async def button_callback(self, button, interaction):
  await interaction.response.send_message("This Ticket will be Deleted in 10 Minutes") 
  await asyncio.sleep(5)
rare ice
lusty token
rare ice
viscid wren
lusty token
#

oh it's just .slash_command lol

rare ice
viscid wren
#

so the usual way is restarting the bot everytime you make changes?

fervent cradle
errant craneBOT
silver moat
rare ice
#

oh thank god squid is here running_duck

viscid wren
rare ice
#

well restarting your bot is inevitable. so you may have to.

viscid wren
#

it was avoidable with prefix commands

silver moat
#

I pretty sure reloading cogs with slash commands is bugged anyways.

viscid wren
#

:(

rare ice
#

yeah it only works with prefixed commands.

silver moat
#

I just realized that no one opened an issue with that yet.

viscid wren
#

great, I should tbh

#

kinda really demotivated to make the switch to slash commands now. I have been reading conflicting opinions so maybe I can ask here:
is my bot going to stop working with prefix commands (a bot with <100 servers) in the near future?, or we don't really know

viscid wren
#

can I have a link?

silver moat
#

to what?

viscid wren
#

to read more about that announcement

silver moat
lusty token
#
@bot.slash_command(name="test",description="Testing Stuff")
async def test(ctx):
    testEmbed = discord.Embed(title="Test Embed", description="For Testing Stuff")
    testEmbed.add_field(name="What's being tested", value="Running embeds")
    await ctx.respond(embed=testEmbed)```
#

is this good for sending embeds?

rare ice
lusty token
#

or do i just flat out send the embed as is

silver moat
rare ice
silver moat
#

and py-cord isn't installed

silver moat
lusty token
#

good

viscid wren
# silver moat literally in 26 days

tell me if I am reading this wrong, but it only affects bots that are in more than 100 servers? mine is not going to be in that situation ever

lusty token
#

That was much easier than what i had before

silver moat
fervent cradle
viscid wren
#

ah great, thank you all for the help

rare ice
fervent cradle
#

u just ruined my entire code

#

u just messed up my entire code

silver moat
#

it simple as uninstalling them and reinstalling them. :\

fervent cradle
#

yes

#

and now my code is ruined

lusty token
#

How do i put options into my Slash commands? Like if i wanted input

errant craneBOT
#

Here's the slash options example.

lusty token
#

ty

#

will it make those options required for the command to run?

silver moat
fervent cradle
#

@rare ice

#

can we get in a vc?

rare ice
#

it's not that hard to reinstall it

rare ice
lusty token
fervent cradle
silver moat
silver moat
#

there's this thing called required = True/False

fervent cradle
#
class CloseTicket(discord.ui.View): # Create a class called View 
    @discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.danger)
    
    async def button_callback(self, button, interaction):
      await interaction.response.send_message("This Ticket will be Deleted in 10 Minutes") 
      await asyncio.sleep(5)
      #await channel.delete
#

Button' object has no attribute 'response'

#

@rare ice

silver moat
#

in the params

fervent cradle
#

ok

#

File "main.py", line 33, in button_callback
await channel.delete
TypeError: object method can't be used in 'await' expression

#
    async def button_callback(self, interaction, button):
      
      await interaction.response.send_message("This Ticket will be Deleted in 10 Minutes") 
      channel = interaction.channel
      await asyncio.sleep(5)
      await channel.delete
fervent cradle
#

i did call it

#

well obviously i didnt, but how do i fix that

silver moat
#

channel.delete()?

fervent cradle
#

how do i call it

#

aaaaaaaaa

silver moat
#

... await channel.delete()?

fervent cradle
#

alr, the last thing in my ticket bot, when i create the ticket, i want the channel perms to be only mods and admins, and also the person who created it

silver moat
rare ice
#

^

celest lichen
#

if i'm running

@bot.event
async def on_message():
  pass

what do i need to get the content of the message itself? i thought it would be ctx.message, but on_message() doesn't take any arguments, so i'm confused now

silver moat
#

on_message takes an argument with type discord.Message

#

b!rtfm pyc on_message

celest lichen
#
@bot.event
async def on_message(discord.Message):
    print(discord.Message)

so like this ??

rare ice
fading granite
#

almost 6969 messages, nice

fervent cradle
celest lichen
fervent cradle
#

not object

#

message: discord.Message

celest lichen
#
@bot.event
async def on_message(message=discord.Message):
    print(discord.Message)
    await bot.proccess_commands(message)
``` here's what i changed it to - now i get a `AttributeError: 'Bot' object has no attribute 'proccess_commands'` when i actually send a message for it to print in my test server
rare ice
#

oh mb spelling

celest lichen
#

OH lmao

#

i missed that haha

rare ice
#

await bot.process_commands(message)

#

i love it when autocorrect doesn't work

celest lichen
#

is it process_application_commands? process_commands doesn't work either

rare ice
#

are you using commands.Bot or discord.Bot?

celest lichen
#

discord.Bot, that's what i've been seeing used in examples. should i swap to using commands.Bot?

rare ice
#

discord.Bot should work fine

celest lichen
#

bot = discord.Bot(debug_guilds=[1004467511833677915],intents=discord.Intents.all())

rare ice
#

b!rtfm pyc discord.Bot.process_application_commands

rare ice
#

ok so try that

celest lichen
#

okay well!! not crashing anymore! but when it prints to the console all it prints is <class 'discord.message.Message'> hahaha

woeful spindle
#

do cog listeners still require the self argument?

celest lichen
#

what is the difference between discord.Bot and commands.Bot anyways ??

lusty token
#

is there a way to put slash commands into a different document for the sake of Orgainization?

errant craneBOT
#

Here's the slash cog example.

grizzled sentinel
lusty token
#

I've used add_cog before i just wasn't sure if it'd work with Slash

grizzled sentinel
#

Works the same way :)

lusty token
#

ah good. It annoyes me when i have a buncha unrelievent code in my main.py

grizzled sentinel
#

understandable.

lusty token
#

would i do this instead for a slash command? @commands.slash_command() async def test(ctx):

#

instead of @commands.command()

#

Uh oh

#

so I tried to create the command in the document. but it doesn't seem to run

#
import discord
from discord.ext import commands

import os
from dotenv import load_dotenv

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

    @commands.slash_command()
    async def test(self,ctx: discord.ApplicationContext):
        await ctx.response("This Works")
#

nvm

#

i see it

tepid belfry
#

can someone guide me on how to create buttons the guide on the website outdated and isnt working for

lusty token
woeful spindle
#

Hey, anyone know why I’m getting this error?
Error:

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 715, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/container/cogs/moderation.py", line 150
    await member.remove_timeout(*, reason=reason)
                                 ^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/main.py", line 39, in <module>
    bot.load_extension(f'cogs.{cog}')
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 787, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 718, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: SyntaxError: invalid syntax (moderation.py, line 150)

Code:

@commands.command()
    @commands.guild_only()
    @permissions.has_permissions(manage_roles=True)
    async def unmute(self, ctx, member: discord.Member, *, reason: str = None):
        """ Unmutes a user from the current server. """
        if await permissions.check_priv(ctx, member):
            return
        elif member == None:
            await ctx.send("You must provide a member.", delete_in=5)
        else:
            await member.remove_timeout(*, reason=reason)
            await ctx.send("unmuted")
        if reason == None:
            reason = "No reason provided."
        except Exception as e:
            await ctx.send(e)
unkempt loom
#

hi, do you know if this fork of discord.py supports voice receive?

lusty token
#

How do i make the bot react to embeds with slash commands

silver moat
lusty token
#

how do i do that?

silver moat
#

If you already have the discord.Message object, you can use message.add_reaction()

lusty token
#

like

#

Message would be message = await ctx.respond("Message")

silver moat
#

await ctx.respond returns an interaction

#

b!rtfm pyc interaction.original_message

silver moat
#

would give you the message,

lusty token
#

ah

#
interaction = await ctx.respond("Message")
    message = interaction.original_message```
#

like this?

silver moat
#

it's a coro, you should await it

lusty token
#

and i couldn't get the slash_cog to work in a different document

silver moat
silver moat
lusty token
#

i got an error apparenly slash_cog couldn't be found

woeful spindle
silver moat
#

b!rtfm pyc remove_timeout

dire spadeBOT
silver moat
#

The asterisk doesn't mean you put it in your code as well. It represents how the values are taken.

lusty token
silver moat
lusty token
#

there

#
Traceback (most recent call last):
  File "/home/pi/S.H_pybot/main.py", line 17, in <module>
    bot.load_extension('slash_cog',store=False)
  File "/home/pi/.local/lib/python3.9/site-packages/discord/cog.py", line 857, in load_extension
    raise final_out
discord.errors.ExtensionNotFound: Extension 'slash_cog' could not be found.
silver moat
#

what did you name your cog

#

and how does your file structure look like

lusty token
#

OH

#

I'm dumb

#

i followed the thingy.

#

i didn't know i was supposed to name it after the doc

#

and this is where they are

#
import discord
from discord.ext import commands

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

    @commands.slash_command()
    async def test(self, ctx:discord.ApplicationContext):
        await ctx.respond("Yes")

def setup(bot):
    bot.add_cog(testCommand(bot))```
#

and then main

#

import discord
from discord import option
from discord.ext import commands

import os
from dotenv import load_dotenv

load_dotenv()
token = os.getenv("DISCORD_TOKEN")
ver = os.getenv('Version')

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

bot = discord.Bot(intents=intents,command_prefix="-")



#When the Bot Starts
@bot.event
async def on_ready():
    print(f"Bot is up")
    await bot.change_presence(activity=discord.Game(name="Crusading isles Beta"))

    bot.load_extension('test')

bot.run(token)```
#

idk why it's not working.

proud pagoda
lusty token
#

i did

proud pagoda
#

Whats the error?

lusty token
#

the term isn't throwing one

#

the command isn't showing in the Ui

proud pagoda
#

Try to set guild_ids to the id of a guild that you will run the command in

#

So:

    @commands.slash_command(guild_ids=[...])
lusty token
#

still not showing

proud pagoda
#

hm I've heard that sometimes slash commands can take some time to display

#

So wait a few min

lusty token
#

if i code it into main it shows almost instantly

#

the command. when i code it into the doc i removes the command

proud pagoda
#

By the way, do you know if the cog loads?

lusty token
#

how can i tell?

proud pagoda
#

Add this to your cog:

@commands.Cog.listener()
async def on_ready(self):
  print("Cog is online")
lusty token
#

into my main, or into the Document?

proud pagoda
#

Into the cog

lusty token
#

is the cog one of my documents?

#

do u mean test or main

proud pagoda
#

What do you mean by document?

#

Into test

#

Within the class

lusty token
#

mm

#

Nothin thus far

solid agate
#

Anyone ran into this issue?

Traceback (most recent call last):
  File "/root/---/bot.py", line 137, in <module>
    bot.run(bot.token)
  File "/usr/local/lib/python3.9/site-packages/discord/client.py", line 715, in run
    return future.result()
  File "/usr/local/lib/python3.9/site-packages/discord/client.py", line 694, in runner
    await self.start(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/discord/client.py", line 658, in start
    await self.connect(reconnect=reconnect)
  File "/usr/local/lib/python3.9/site-packages/discord/shard.py", line 462, in connect
    raise item.error
  File "/usr/local/lib/python3.9/site-packages/discord/shard.py", line 185, in worker
    await self.ws.poll_event()
  File "/usr/local/lib/python3.9/site-packages/discord/gateway.py", line 589, in poll_event
    await self.received_message(msg.data)
  File "/usr/local/lib/python3.9/site-packages/discord/gateway.py", line 539, in received_message
    func(data)
  File "/usr/local/lib/python3.9/site-packages/discord/state.py", line 635, in parse_auto_moderation_action_execution
    event = AutoModActionExecutionEvent(self, data)
  File "/usr/local/lib/python3.9/site-packages/discord/raw_models.py", line 462, in __init__
    self.content: str = data["content"]
KeyError: 'content'

Bot has been running prior to this seemingly random error for about an hour, without issue.

proud pagoda
proud pagoda
solid agate
#

2.0.0

proud pagoda
#

Alright cool

proud pagoda
#

Oh wait hold on

solid agate
#

correct.

proud pagoda
#

Just install the master version of pycord

#

Run

pip install git+https://github.com/Pycord-Development/pycord.git
solid agate
#

I figured it was going to fix that. As it seems to be a new thing "AutoModActionExecutionEvent"

proud pagoda
#

Yeah

solid agate
#

would be dope if there was a known issue for it 🤔

#

(or better, if it were pushed to prod :P)

cold eagle
#

line 72, how come .avatar_url is not recognized as a method?

proud pagoda
cold eagle
#

oh

#

thanks

proud pagoda
#

You're welcome

rugged lantern
#

if any(word in BlacklistedWords for word in message):

lusty token
#

can i use this to get all members of a server? guild = self.bot.get_guild(ctx.author.guild.id)

#

i want to get all of the members of the server and get their roles

fallen cove
#

how do you send multiple views in a message?

lusty token
#

For some reason the Required thing in options isn't working

#
@option("write",description="Wrting your discription",required=False)```
#

it still requires it

#

when i use the command

lusty token
#

nvm

#

How can i get the User without the message?

#

the command works up to that point

rugged lantern
#

don't use json as a db

empty tree
empty tree
lusty token
#

i got it lol

empty tree
#

ah ok

rugged lantern
empty tree
#

nah it really doesn’t

#

of course it would be less performant than other options but if you’re just starting out it’s not that bad

lusty token
#

well I'm familiar with json. and this bot's not gonna be that big

empty tree
#

yeah personal-use types of projects that don’t rely on many reads and writes per second can use json

rugged lantern
#

it's a bad practice and generally unreliable if you want to change information stored in it. if you use json as a db you generally don't make it failsafe either so the odds of changing one set of data and before it is saved, try to alter another; are not minimal and will absolutely make the json invalid and unusable.

empty tree
rugged lantern
#

it's still a bad practice and you should switch to a proper db and use that practice instead- as it is both reliable for smaller and big projects. there's practically no reason to not choose a proper db over a .json file

empty tree
#

I’ll just dm

tranquil pivot
#

can you pass ctx into a modal?

#

I want to add the output to a json where the user id is the key

rugged lantern
#

by adding a variable to the __init__()

tranquil pivot
#

trying it now

lusty token
rugged lantern
tranquil pivot
#

I'm also a fan of storing data in a database

#

So Norman I'm not sure if I should use a thread for this or not but I'm still having issues passing in ctx. Should it be like this? ```python
async def btn1callback(interaction: discord.Interaction):
print("Submit Time Button pressed")
if interaction.user != ctx.author:
await interaction.response

        #JSON
        user_id = str(ctx.author.id)

        await interaction.response.send_modal(MyModal(title="Time Submission", ctx= ctx))
#
class MyModal(discord.ui.Modal):
    def __init__(self, ctx, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        print(ctx)
        self.add_item(discord.ui.InputText(label="Please enter your time in the mm:ss format"))

    # what is displayed as the Modal message 
    async def callback(self, ctx, interaction: discord.Interaction):
tranquil pivot
rugged lantern
rugged lantern
tranquil pivot
#

did you mean self, ctx?

rugged lantern
#
class MyModal(discord.ui.Modal):
    def __init__(self, ctx, *args, **kwargs) -> None:
        self.ctx = ctx    
tranquil pivot
#

do you mind explaining why that works? why do you need to set self.ctx = ctx?

rugged lantern
#

could you give me your command for the modal? idk how to properly phrase a solution unless you do that :p

tranquil pivot
#

sure

#

well the whole command is kind of long. Are you looking for the sub classed callback?

rugged lantern
#

for example await ctx.send_modal(modal)

#

or whatever you use to send the modal

#

ill just go by the example given from the docs wait

tranquil pivot
#
async def btn1callback(interaction: discord.Interaction):
            print("Submit Time Button pressed")
            if interaction.user != ctx.author:
                await interaction.response

            #JSON
            user_id = str(ctx.author.id)

            await interaction.response.send_modal(MyModal(title="Time Submission", ctx= ctx))
            print(Submission_Info)
            Submission_Info = await self.Submission_Info(ctx)
            msg = await interaction.response.edit_message(embed = Submission_Info[0], view=view)
#

I'm using a button to call the modal

rugged lantern
#

tbh, i don't understand what the issue is? is ctx not passed to the modal

tranquil pivot
#

so your suggestion to add self.ctx=ctx to the init worked but I was just curious as to why it was needed

#

was it just because the other class needed it defined?

#

I just want to understand why

full basin
#

Modals don't take ctx.

#

That's why interaction is "missing" in your original function

#

Why would you even pass ctx? You don't use ctx to respond to a interaction

tranquil pivot
#

True I'm having to go about this is a convoluted way but I'm trying to get the output from multiple dropdowns and then insert them into a database. Since dropdown selections are local variables i'm dumping everything into a json then at the end I'll take that json and turn it into a sql insert statement

#

You're explanation makes sense. I appreciate it 🙂

meager heron
#

Just encountered something in 2.0.0 but not 2.0.0rc1.

If you have an import error in a cog, the bot will load without issuing any warnings (or crashing). The cog will just be skipped, so commands will disappear without explanation.

Is this a bug or intentional (for some reason)?

celest lichen
#

can someone explain (or link to an explanation) to me the difference between using commands.Bot and discord.Bot?

#

do i have to choose one or the other for my discord bot?

fervent cradle
#

How do I globally set debug_guild?

meager heron
#

Looks like you didn’t await

fervent cradle
meager heron
#

debug_guilds

limber grove
#

is there an alternative to await ctx.respond and await ctx.send?

cold eagle
#

would member on line 105 be a discord.Member?

meager heron
#

Which line is crashing?

#

Nothing jumps out at me there. Try adding some logging

#

Or fire up the debugger and step through

cold eagle
meager heron
#

Go for it

#

Nothing jumps out at me. I'd try those logging statements so you can pinpoint where it's happening

#

Or someone else may catch what I missed

#

get_role() isn't a coro, so it shouldn't be that

full basin
#

You're missing the event decorator mate

meager heron
#

How frequently is discord.Bot.latency updated, if ever?

night cargo
#

How many Input Texts can you have in a Modal?

meager heron
#

5

#

View.message says this:

The message that this view is attached to. If None then the view has not been sent with a message.

I send a view with await ctx.respond(..., view=my_view), yet my_view.message is None. Am I misunderstanding this property?

celest lichen
#

are there any good online examples of per-server settings for bots written with pycord?

fierce elm
#

Without doing

# ...
if isinstance(error, SomeException):
    error = error  # type: SomeException
elif isinstance(error, discord.HTTPException):
    error = error  # type: discord.HTTPException
else:
    # ...

is there a way to type hint that error is a certain exception class per statement?

#

that would make IDE's work, like pycharm

rugged lantern
#

by doing error: <type>?

tiny wagon
#

how to add option value pair in autocomplete list?

rugged lantern
#

subcommands?

fading granite
#

Modals?

#

Is there an efficient way to store data in python? I want to store question data for a quiz command

fading granite
#

nope

#

but its for local use only

#

not storing server or user stuff

young bone
#

I use a Json file but the bot is only on one server

#

You can use aiosqlite

fading granite
#

json is a bit inefficient imo

tranquil pivot
#

I'm trying to create a button that prompts a user to upload an image but every time I click the button, it gets to the try except then doesn’t see the message and times out. I do have message intents enabled in the dev portal. Any ideas on how to fix this?

#
async def btn3callback(interaction: discord.Interaction):
            print("Proof of Time Entry pressed")
            if interaction.user != ctx.author:
                await interaction.response  
            await interaction.response.send_message("Upload a photo of your time.")
            print("After first interaction")
            while True:       
                print("within while True")    
                try:
                    message = await self.bot.wait_for('message', timeout = 60, check = check)
                    print(f"message is {message}")
                    proof_of_time = message.attachments[0].url
                    print("message attached")
                    print(proof_of_time)
                    submission_info = await self.Submission_Info(ctx)
                    msg = await interaction.response.edit_message(embed = submission_info[0], view=view)
                    break

                except asyncio.TimeoutError: 
                    await interaction.response.send_message("Timeout. Please try again")
                    break

                except Exception: 
                    await interaction.response.respond("Please reupload your time photo.")
#

Eventually I want to be able to edit the original interaction with "interaction.response.edit_message" but right now I'm focusing on getting the attachment

#

it's a slash command

#
@event.command(name = "submit")
    async def submit(self, ctx, proof_of_time: discord.Option(discord.Attachment)=None, proof_of_armor: discord.Option(discord.Attachment)=None, message=None):
#

I have it setup so it can except attachments when first starting the slash commands but there are known bugs so I wanted to have another way to add it. it works on my pc but not on my phone

#

Figured it out. I didn't have my check defined within the button

tiny wagon
#

how to add option value pair in autocomplete list?

pallid trench
#

you can still use OptionChoice

restive harbor
#

Why are these Info Logs shown? It suddenly started showing up

mental maple
#

Does anyone know how to set X and Y for this?

    @discord.ui.button(label="✊ rock", style=discord.ButtonStyle.green, custom_id="self.rpsrock") 
     async def rock(self, button: discord.ui.Button, interaction: discord.Interaction):```
alpine helm
#

Can we add a cooldown to button presses?

mental maple
#

I think yes if u want

alpine helm
#

How?

mental maple
#

Idk tho

#

If i say ill make like a dict that contain yes or no

#

Like cooldown = [buttid]

#

if theres no support

alpine helm
#

No I thought if there was some kind of decorator like the one you have to add cooldown to commands

fervent cradle
#
from discord.ext import commands, tasks
from datetime import time, timezone

class Shanza(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.remind_shanza.start()

    @commands.Cog.listener()
    async def on_ready(self):
        global shanza_user
        shanza_user = self.client.get_user(734346204892233768)
        print("Cog: Shanza.py loaded")

    # Minus 3 hours from UTC to get the current time in gmt+3
    @tasks.loop(time=time(1, 52, tzinfo=timezone.utc()))
    async def remind_shanza(self):
        print("Test")
        general_channel = self.client.get_guild(880368659858616321).get_channel(880368661104316459)
        await general_channel.send(f"test thing")


    @remind_shanza.before_loop
    async def before_my_task(self):
        await self.wait_until_ready()  # Wait until the bot logs in

def setup(client):
    client.add_cog(Shanza(client))

The cog doesn't seem to load at all. Any idea?

dim blade
#

do i need to subclass discord.ui.View for every view i want to create?

rancid plaza
#

i try to run the bot but it says Traceback (most recent call last):
File "main.py", line 2, in <module>
from discord.ext import commands
ModuleNotFoundError: No module named 'discord'

lusty token
#

Is there a way to set a timer to delete a message after a set time?

fervent cradle
#

message.send(delete_after=seconds)

lusty token
lusty token
silver moat
#

wait what is message.send

lusty token
#

i used discord.py for a bit so that's kinda faimilar to me

silver moat
#

b!rtfm pyc message.send

fervent cradle
#

ctx.send whatever 😄

lusty token
#

it

#

it's ctx.respond normally isn't it?

silver moat
#

yeah

fervent cradle
#

it`s all the same 😄

lusty token
#

in words yes, in code no

silver moat
fervent cradle
#

send_message() 🙂

#

just a squid hopefull you could help me in my thread 😄

silver moat
#

which one lol

lusty token
#

how do you get the pfp of the user?

lofty falcon
proud pagoda
lofty falcon
#

ctx.author.avatar or something like that

#

or ctx.author.avatar_url

#

it keeps changing, just test it out, while coding in visual code it shows you

proud pagoda
lofty falcon
#

yeah, it keeps changing while coding it shows you the correct form anyways

silver moat
#

vsc doesn’t have the best autocomplete tho

lofty falcon
#

you need to install the python plugin

silver moat
lusty token
#

How do you do stuff with reactions, can you do stuff with them in different document

silver moat
lusty token
#

lemme try that again

#

I want to use a reaction to delete a message

silver moat
#

b!rtfm pyc on_reaction

silver moat
#

here are some reaction events

lusty token
#

in my cog doc or do i have to do those in main?

silver moat
#

I don’t understand what a cog doc is.

lusty token
#

not a program document other than main

silver moat
#

you mean a file?

#

instead of cog.docx

lusty token
#

omg

silver moat
#

either should work

lusty token
#

The other program docs that aren't main.

#

do i need to do @discord.on_reaction_add?

silver moat
#

in a cog, @discord.Cog.listener
in main, @bot.event

lusty token
#

so id do the listener, then i would do that?

#

or would i use a async def

silver moat
#

yes

lusty token
#

Async def or the @

jade walrus
#

Is there a way to pass dynamic data to a select menu?

class AccountSelector(discord.ui.View):
    optionss = []

    def __init__(self, options):
        super().__init__()
        self.optionss = options

    @discord.ui.select(
        placeholder="Select an account",
        min_values=1,
        max_values=1,
        options=self.optionss # Error here because self isn't in scope

    )
lusty token
#

can you delete a message by id?

silver moat
#

yes

lusty token
#

i got the reactions to work, but now i need to delete the message how would i delete it

silver moat
#

b!rtfm pyc fetch_message

lusty token
#

after i do that can i just do message.delete?