#Basic Pycord Help (Quick Questions Only)

1 messages · Page 52 of 1

meager heron
#

You'll need to pull the data, but I'm confident you can figure it out from the guide/example code in the repository

worn void
#

yeah

meager heron
#

Pulling this down

gleaming falcon
#

Sweet. Was able to figure this out:

class MySelect(discord.ui.Select):
  # ...

  async def callback(self, interaction: discord.Interation):
    if self.values:
      for option in self.options:
        if option.value in self.values:
          option.default = True
    # ...

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

(Although now that I can do that, it may not make sense to update the Embed with the selections, as I had been doing 🤔 )

olive fog
#

I'm having trouble figuring out: When I receive a discord.Interaction from a /command, I can immediately send a response which prompts the user to input named data fields which match "non-standard" parameters in the event coroutine itself. That is sent as an embed JUST to that user. But then to send them a report after doing the actual work, how can I send an Embed just to that one originating user in the originating channel?

gleaming falcon
civic tulip
#

I need to know what function/class to use to change channel permissions (role and member specific) as I couldn’t find any pycord examples or docs for it

gleaming falcon
#

You could also defer if the task is run immediately and just takes a minute or so to run (I don't actually know the limit of defer followups, though)

olive fog
#

@gleaming falcon Is there any other way to prompt the user to input the required variables, without using up my 1 ticket for Interaction.response?

civic tulip
#

Bruh why didn’t this show up on my search results, tysm

gleaming falcon
olive fog
#

@silver moat @gleaming falcon Sorry, I got it. You said I can't send unsolicited EPHEMERAL messages. I can send unsolicited embeds to a single user. Still would like to stick that notification on the same channel where they ran the command.

civic tulip
#

What is the difference between a regular discord.channel obj and a discord.abc.GuildChannel obj?

gleaming falcon
#

Yup. You could just store the message they used to interact and respond to it, or just send a raw message and @ them

olive fog
#

It's not the kind of report they would want to advertise.

#

It's the kind of report that should only go to that user.

gleaming falcon
#

Oh damn. ChatGPT just tried to school me (pardon the use of discord.py, it doesn't know Pycord)

I asked for a slash command example and they gave me a text command.
I said "This doesn't create a Slash command within Discord. A slash command would accept discord.Option arguments. Are you familiar with those?"

Mr. Smarty Pants says "As for the discord.Option, it is not an argument type used in discord.py library, but rather it is an implementation of the Discord UI element that allows users to select one or more options from a list."

#

It really doesn't know how to create Slash commands, though. I might have to teach it.

civic tulip
#

Basically how do I obtain a GuildChannel object from the object Guild, as I obtained the channel object but set_permissions isn’t a attribute of it apparently

silver moat
#

.rtfm guild.channels

winter condorBOT
civic tulip
#

I used exactly this (using utils.get)

#

Then tried to use that object to run channel.set_permission

silver moat
#

and?

civic tulip
#

interaction.guild.channels should work, right?

#

As I wanted to use discord.utils.get(interaction.guild.channels, name=“example”)

olive fog
#

Erm. I guess I don't know what docs I was reading, but I don't apparently have to send anything to get Discord to prompt the user to fill in the blanks.

civic tulip
#

So if I wanna use the name of a user + the discriminator as a channel name, and then want to gain its ID using that name, then would something like discord.utils.get(interaction.guild.channels, name=(str(usr.name)+str(usr.discriminator)) be ok?

#

As when I try to return the channel obj it’s just “None”

#

Fixed it

#

Needed to add .lower() as names aren’t all lowercase but channel names are

fringe socket
#

Because you asked it to FalseFacePalmLaugh

astral mist
#

Can I use client instead of bot

silver moat
#

.tag client

winter condorBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
proud mason
#

?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)
digital storm
#

How can I make it so a command will run even if only one check returned true?

gleaming falcon
#

I'm trying to teach ChatGPT how to write pycord UI elements but it doesn't seem to understand that having five Selects in a View would prevent Buttons from being added.

silver moat
digital storm
gleaming falcon
#

No, please understand that when you add_item, you're adding a discord.ui element to the view. Since you have added five CronTabSelect instances, which are Selects, taking up five elements in the View, you cannot add a submit_btn. You should also remove the submit and cancel functions from the View because they are related to the Buttons which we no longer need. Please try again.

#

I'm trying to reason with an AI.

civic tulip
#

How can I set my own timeout time on an interaction using code like this example:


import discord

bot = discord.Bot() # Create a bot object

class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎") # Create a button with the label "😎 Click me!" with color Blurple
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked

@bot.slash_command() # Create a slash command
async def button(ctx):
    await ctx.respond("This is a button!", view=MyView()) # Send a message with our View class that contains the button

bot.run("TOKEN") # Run the bot```
#

Basically I don’t want my button element to timeout

proud mason
#

.rtfm check_any

winter condorBOT
proud mason
#

there

static juniper
proud mason
static juniper
proud mason
#

pycord version?

static juniper
#

i mean i clone the repo and install it

proud mason
#

hmm

gleaming falcon
#

Why are you using a git-installed version instead of the latest release (2.3.2) on pypi?

civic tulip
limber urchin
#

Give an explanation instead of spoonfeeding

proud mason
proud mason
# static juniper

Show how you are sending the view. Also show the subclass init if you have made one

proud mason
civic tulip
#

Okay, where would I pass that

proud mason
#

Where you create the object. Which in your case is view=MyView()

civic tulip
#

Wait, so view=MyView(timeout=None)?

#

With a timeout referenced in the class params?

proud mason
civic tulip
#

What about setting timeout=None directly in the params of the __init__?

civic tulip
#

Awesome

proud mason
static juniper
#

ok

proud mason
#

Print self.message in one of the button callbacks

#

And check what gets printed

static juniper
#

for some reason it return None

proud mason
#

Hmm

#

This is weird

#

Try setting the message object yourself

#

In the Slash cmd, create the view before responding and assign it to a variable called my_view.

Then send that view object using ctx.respond. it returns an interaction. Assign that to a variable too

And then do my_view.message = await interaction.original_response()

static juniper
#

ok

civic tulip
#

As I made a test
async def on_timeout: print(“timeout”)

#

And I saw timeout in my terminal and my button no longer functions

proud mason
proud mason
civic tulip
#

Sure

#
class MyView(discord.ui.View):
��������    def __init__(self, bot, timeout=None):
����������������           super().__init__(timeout=None)
����������������        self.bot = bot
��������    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary)
��������    async def button_callback(self, button, interaction):
    *stuff*```
#

And is called by:

#
@bot.slash_command()
async def button(ctx):
    ��������if ctx.author.id == 883670260404867114:
����������������        await ctx.send("** **", view=MyView(bot, timeout=None))```
#

I know the timeout = none on the view=MyView is redundant

#

But I included it just in case

#

The indentation is definitely goofed there due to discord stuff

#

But there are no indentation issues in the actual code

#

Although It hasn’t timed out yet so I’ll leave it for a while longer

#

And if it’s still good then I think it was the super().__init__(timeout=None) that did it

proud mason
civic tulip
#

Ty

proud mason
#

just so you know,

#

bot instance can be accessed from interaction.client

static juniper
proud mason
digital storm
#

How can I check if a member has a specific permission, when I have the permission as a variable? I have the permissions like this:

perm = discord.Permissions.manage_messages # or any other permission
young bone
#

For what?

digital storm
#

A custom check I'm making

proud mason
#

.rtfm permissions_for

proud mason
#

this?

digital storm
proud mason
digital storm
digital storm
#

Which means I can do things like

#
can_manage_channels = perms.manage_channels
#

To see if the member has that permission

#

But, the permission I'm looking for is stored in a different variable

#

And I can't do

permission_I_am_looking_for = discord.Permissions.manage_roles
has_that_perm = member_perms.permission_I_am_looking_for
proud mason
#

sorry i did not understand

#

ah wait

#

do you want smth like this

check_perm = discord.Permissions(manage_roles=True)
member_perms = ctx.channel.permissions_for(ctx.author)

if member_perms >= check_perm:
    ...
digital storm
#

But wait I think I can do something from what you want

#

discord.Permissions(manage_roles=True) that line was maybe what I was missing

proud mason
digital storm
proud mason
#

it should

digital storm
#

I'll try it

#

Thanks :)

ornate swan
#

Is there a way to run a task at the beginning of each month.

@tasks.loop(time=datetime(year=datetime.now(tz).year, month=datetime.now(tz).month, day=20, tzinfo=tz))
#

Error: Extension 'tasks.motmTask' raised an error: TypeError: Expected datetime.time or a sequence of datetime.time for time, received <class 'datetime.datetime'> instead.

proud mason
#

i think that would be the closest you can get

ornate swan
#

Okay, thx <3

fervent cradle
#

How do I create a channel when clicking on a button? trying to make a ticketing system

#

Current code

fervent cradle
#
from discord.ext import commands
from discord.commands import slash_command
import discord

class TicketSystem(discord.ui.View):
    @discord.ui.button(label="Create Ticket", style=discord.ButtonStyle.green, emoji="🎫")
    async def create_ticket(self, channel: discord.TextChannel, button: discord.ui.Button, interaction: discord.Interaction):
        await channel.create_text_channel(name=f"ticket-{interaction.user.id}")
        await interaction.response.send_message("Ticket Created", ephemeral=True)
    
    
class Ticket(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @slash_command(name="ticket", guild_ids=[1065333151632719974])
    async def ticket(self, ctx):
        await ctx.respond("For support, please open a ticket down below.", view=TicketSystem())
        
def setup(bot):
    bot.add_cog(Ticket(bot))```
young bone
#

but with interaction

fervent cradle
young bone
#

remove the "channel: discord.TextChannel"

fervent cradle
#

Alright

#

Then what?

#

channel.create_text_channel

#

what should that be?

young bone
#

do you know how to create a channel with a normal command?

fervent cradle
#

no

#

I would like some docs if there is any :)

fervent cradle
#

thanks

olive orbit
#

.rtfm reaction

gray peak
#

How i can get user activities? When i fetch members from guild attribute activity is None

gray peak
#

member

young bone
#

mhm

gray peak
#

But he is online and playing

#

What i'm doing wrong?

young bone
#

I would not fetch every member in a guild

#

you will get really fast a rate limit

#

with fetch_member you do everytime a discord API call

gray peak
#

I want to get members who playing now, what i need to do?

proud mason
#

guild.members

#

use utils.find

#

.rtfm utils.find

winter condorBOT
regal lark
#

how to make an argument in a slash command?

#

this doesn't work ```py
@discord.slash_command(name = "avatar", description = "Display avatar of a user", guild_ids=guild_ids)
async def avatar(self, ctx, user1:str = ""):
if user1:
await ctx.respond(f"{user1.avatar}")
else:
await ctx.respond(f"{ctx.author.avatar}")

#

it's been 1 day, so I don't think that it is not registering (not sure tho)

limber urchin
#

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

regal lark
#

The command is registered and when I use it, no argument shows up in discord. The code simply takes the else path

#

an Optional argument should have been present

regal lark
#

ok renaming solved it idk how ?? But this is solved

silver moat
regal lark
fervent cradle
#
  await ctx.send(f"How long would you like the giveaway for {PrizeInput.content} to last?")``` How can i get this question, to be the time in a task or whatever
eg.
1w
it wouldnt work as its got a "w"
astral mist
#

is there a tag for presence

#

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 34, in on_ready
    await bot.change_presence(status=discord.online, activity=game)
#

i am getting this traceback

#

from using online

limber urchin
#

discord.online??

astral mist
limber urchin
#

wtf is discord.online?

fervent cradle
astral mist
ornate swan
#

Can you somehow edit an image with a task, without having the id of the message?

proud mason
proud mason
ornate swan
#

im not using a database, so im not sure how i would give the id

proud mason
#

you should store the msg id in a cache or db if you want to access it later

proud mason
ornate swan
#

how would i save it in a cache?

proud mason
#

in a task loop? inside a cmd? some event handler?

ornate swan
ornate swan
#

The task checks it every 5min

proud mason
#

and from where is this embed originally sent?

ornate swan
proud mason
#

or is it a static msg? one that would stay constant throughout the life of the bot

ornate swan
#

i send the embed via a slash command, from slash.py

proud mason
#

and how do you plan on making it unique?

ornate swan
#

but, there should be only one embed

proud mason
#

👀

ornate swan
#

Uhm

proud mason
ornate swan
#

coulnt i just use the newest one?

proud mason
#

yea that works

ornate swan
#

im using buttons that i add_view

proud mason
#

so you could do smth like
bot.embed_msg_id = msg.id in the slash cmd where msg is the message sent

#

and then use it in the task loop

#

?tag botvar

obtuse juncoBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

proud mason
#

if you want to retain the id even after restarts, you would need a db

ornate swan
#

hm pepoThink

#

makes sense

fervent cradle
#

or am I doing this wrong

proud mason
#

i suggest using 1

fervent cradle
#

Ill look into one, thank you

proud mason
#

👍

fervent cradle
fervent cradle
#

👍

jovial shoal
#

Running into this error sporadically on a handful of commands at the defer stage:

  File "/home/runner/bot/cogs/commands.py", line 54, in my_name
    await ctx.defer(ephemeral=True)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/interactions.py", line 655, in defer
    await self._locked_response(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/interactions.py", line 1090, in _locked_response
    await coro
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/webhook/async_.py", line 213, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

I used to get a similar error when a command didn't respond in time and a deferral was required. But now I'm getting it on the deferrals themselves

fervent cradle
#

code

proud mason
jovial shoal
#

yes

    async def my_name(self, ctx):
      await ctx.defer()
      asyncio.sleep(5)
      await ctx.send_followup(str(ctx.author))
silver moat
#

?tag blocking

obtuse juncoBOT
#

dynoError No tag blocking found.

proud mason
#

dont use time.sleep
use asyncio.sleep

proud mason
silver moat
jovial shoal
#

okay, this is only an example of one of many commands that all yield the same error. It doesn't seem to matter what is happening after the defer()

proud mason
jovial shoal
#

The error does not appear consistently. Any command I have has thrown this error about 25% of the time. Sometimes they work, and sometimes they don't

jovial shoal
#

that it can't even defer in the allotted 3seconds

proud mason
jovial shoal
#

right

proud mason
#

try changing your host

jovial shoal
#

I was hoping there'd be less dramatic steps before I'd need to try porting my bot

#

but I will look into it

fervent cradle
#

I cant find the guide/docs for tasks, is it discord.ext.tasks

fervent cradle
#

alr ty

proud mason
#

👍

fervent cradle
#
class Req(discord.ui.View): 
    @discord.ui.button(label="I dont need any reqs", style=discord.ButtonStyle.primary, emoji="❌") 
    async def NoneReq(self, button, interaction):
            @tasks.loop(seconds=5.0)
            async def start(self):
                channel = 1053331335005098047
                interaction.response.channel.send(embed=GiveawayEmbed)``` how can i make it send to the channel? aint sending any errors
#

This just temp, no time stuff properly setup w the giveaway

limber urchin
#

Where are you starting the loop?

fervent cradle
#

I think i mis understood it lol

fervent cradle
#

go through the stuff, then click the button in the code above

limber urchin
#

huh

fervent cradle
#
import discord
from discord.ext import commands
from discord.ext import tasks
GiveawayEmbed=discord.Embed(title="Giveaway for yes your mum yes ey13y2")
PrizeEmbed=discord.Embed(title="What do you want to giveaway?",description="")
class Req(discord.ui.View): 
    @discord.ui.button(label="I dont need any reqs", style=discord.ButtonStyle.primary, emoji="❌") 
    async def NoneReq(self, button, interaction):
            @tasks.loop(seconds=5.0)
            async def start(self):
                channel = 1053331335005098047
                interaction.response.channel.send(embed=GiveawayEmbed)


    @discord.ui.button(label="I would like to add some reqs", style=discord.ButtonStyle.primary, emoji="✅")
    async def Req(self,button,interaction):
        await interaction.response.send_message(view=ReqSelect())
class create(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command() 
    async def create(self,ctx):
        EmbedMsg = await ctx.send(embed=PrizeEmbed)
        PrizeInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"How long would you like the giveaway for {PrizeInput.content} to last?")
        LengthInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"How many winners should their be for this giveaway?")
        WinnersInput = await self.bot.wait_for("message",timeout=120)
        await ctx.send(f"Should their be any requirments for this giveaway?",view=Req())
     


#

The questions lead to a button, thats supposed to activate the task

limber urchin
#

yeah, but you never start the loop

#

you're just defining it

fervent cradle
#

Oh how would i start it? I dont see it in the examples in docs.

limber urchin
#

You won't find an example for everything

#

Sometimes you have to read on your own

#

And there actually is an example if you read the docs

fervent cradle
#

I didnt know self.printer.start was starting the task

limber urchin
#

well you would've known if you read what the method does NPCMechanicShrug

fervent cradle
#

I simpily asked for help, thats it.

limber urchin
#

And you got it

fervent cradle
#

Yes, thank you.

limber urchin
#

And please use consistent and proper naming conventions, your code is incredibly hard to read

fervent cradle
limber urchin
#

yes

fervent cradle
#

import discord
from discord.ext import commands
from discord.ext import tasks
GiveawayEmbed=discord.Embed(title="Giveaway for yes your mum yes ey13y2")
PrizeEmbed=discord.Embed(title="What do you want to giveaway?",description="")
class Req(discord.ui.View): 
    @discord.ui.button(label="I dont need any reqs", style=discord.ButtonStyle.primary, emoji="❌") 
    async def NoneReq(self, button, interaction):
           @tasks.loop(seconds=5.0)
           async def printer(self):
            print(self.index)
            self.index += 1
            


    @discord.ui.button(label="I would like to add some reqs", style=discord.ButtonStyle.primary, emoji="✅")
    async def Req(self,button,interaction):
        await interaction.response.send_message(view=ReqSelect())
class ReqSelect(discord.ui.View):
    @discord.ui.select( 
        placeholder = "Choose 1 or more Reqierment(s)",
        min_values = 1, 
        max_values = 1,
        options = [ 
            discord.SelectOption(
                label="User Must Have Sent An Amount Of Messages",
                description="Pick this if you like chocolate!"
            ),
            discord.SelectOption(
                label="User Must Have One or More Roles",
                description="Pick this if you like strawberry!"
            )
        ]
    )
    async def select_callback(self, select, interaction): 
        await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")
class create(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.index = 0
        self.printer.start()``` 
discord.errors.ExtensionFailed: Extension 'Commands.Gwcreate' raised an error: AttributeError: 'create' object has no attribute 'printer' I used the example to understand how to create a task and start it, but its given this error i assume its because of the cog class being later than the task code
fervent cradle
limber urchin
#

wtf are you trying to do

#

why are you trying to start a task from a function in another class?

fervent cradle
#

Im just trying to start it from the button

limber urchin
#

You're not

#

not even close

fervent cradle
#

Well thats what im struggling on, what am i doing wrong?

limber urchin
#

You need to learn how classes and class methods work in Python

#

and the basics of OOP

somber remnant
#

Hello, i'm trying to make a map using emoji in an embed
The problem is that there's only 1024 lenght so when i put custom emojis, i can only do a 6 by 6 map (which is too low for me)
Any way to reduce the lenght of custom emojis or a way to put them even if there's limitation ?
Code i'm using to place emojis (plain is the emote):

''.join([plain*6 + '\n' for _ in range(6)])```
limber urchin
#

You can not bypass the character limit

somber remnant
#

Ye that's why i was asking if there's tips to reduce lenght or smthg similar

limber urchin
#

Pretty sure there isn't a way other than renaming your emoji to something short

strange cradle
#

this is complicated to so i really need help
The idea: make a text that you can click and get the text to your Control V
Can i do that in a embed? need buttons or smth else? i have 0 idea, accepting any info

limber urchin
#

You can't control the user's clipboard through a bot lol

strange cradle
#

F

#

ty owoPain

hushed cargo
#

is there a way i can edit the options of the view outside of the class

full basin
hushed cargo
full basin
#

And what's stopping you from doing it in the class?

hushed cargo
#

i want the options to be based on a list of things i have and i cant rly do that in the class

full basin
#

You can subclass the select and pass the options to the init

hushed cargo
#

oh oki ty

#

and is there a way to add multiple views (a select menu and a button) to a single message?

full basin
#

A view can contain multiple items

hushed cargo
#

how do i add a button and a menu?

young bone
#

the same like the other stuff

hushed cargo
#

await interaction.response.send_message(embed=embed, view=SetWelcomeChannelView(), ephemeral=True)
await interaction.response.edit_message(view=self)

#

is there a way i could do thesw two?

little hill
#

Has anyone made a makeshift datetime slash command option utility that takes in a string of some format and converts it to a datetime?

silver moat
little hill
#

I know about that one, but I don't think it works for datetime.datetime

#

I might just make something myself

waxen whale
waxen whale
silver moat
near hollow
#

Its not possible to register commands in dm only right?

silver moat
near hollow
#

Shucks alright thanks 🙂

wild socket
#

We can use emojis in option field?

vapid pumice
#

Is it possible to have an @ Option() choice create new options when selected?
(before the slash command is submitted)

west quest
#

hey, how do i take boolean as discord.Option

proud mason
#

Or

#

.rtfm slashcommandoptiontype.bool

winter condorBOT
proud mason
#

That

proud mason
proud mason
proud mason
hushed cargo
# proud mason Wdym by use these two?

await interaction.response.send_message(embed=embed, view=SetWelcomeChannelView(), ephemeral=True)
await interaction.response.edit_message(view=self)

west quest
#

i just put 2 descriptions by mistake

#

did not read the error correclty haha

winter condorBOT
proud mason
#

?tag xy

obtuse juncoBOT
#

An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.

You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.

vapid pumice
#

.rtfm add_item

blazing tide
#

bro what is this

#

i uninstalled and re installed the discord.py but it didnt work

#

can anyone help me??

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

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

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

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

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

proud mason
#

Show pip list

fervent cradle
#

Is it py-cord error?

/Volumes/disk/Coding/Py-cord/HFD-zebra/venv/lib/python3.10/site-packages/discord/ui/view.py:414: RuntimeWarning: coroutine 'Messageable.fetch_message' was never awaited
  await item.callback(interaction)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
supple sinew
#

Hey!
Im trying to get familiar with decorators and now im struggling to determine hot to provide variables inside decorator.
To not to make many classes i just want to make it work this way
@discord.ui.select( placeholder=placeholder, # 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 maximum number of values that can be selected by the users disabled=False, options=list_of_options )

#

Where placeholder and list_pf_options is variables inside @bot.slash_commands decorator

#

Can someone point me the direction to search?

ornate current
#

when i try to print the error in on_command_error, it doesn't log the whole error. how can i fix that?

astral mist
#

how long will it take

#

i ran my bot for 18 hours

#

and i am getting this now

limber urchin
#

Then you're either spamming the API or using a free shitty host

astral mist
limber urchin
#

and that's why we don't use free hosts kids

astral mist
#

oh

proud mason
supple sinew
fervent cradle
#

Is there any way I could get my bot to send "This user isn't banned" when trying to unban someone? I've tried fetching the ban on the user, but it just outputs an error in the terminal.

#
        ban = await ctx.guild.fetch_ban(user)

        if ban is None:
            await ctx.respond("❌ This user isn't banned.")
            return
#

I just receive this: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10026): Unknown Ban

limber urchin
#

Catch the notfound error instead of checking if it returns None

#

fetch_ban is never gonna return None either way

astral mist
limber urchin
#

Either pay for a server to host it on or host it on a machine at home, whatever suits you better

fervent cradle
limber urchin
fervent cradle
hushed cargo
#

I want to update one interaction anddd send the user another one, I tried interaction.Channel.send but then it said ur didn’t recognize ephemeral as an argument

grizzled sentinel
#

Can you show your code and the error

#

Generally you would use interaction.send_message()

#

That is likely your problem

limber urchin
#

obviously you can't use ephemeral in channel.send, who's the message going to be seen by? The channel?

hushed cargo
#

Omg I didn’t think of that I’m dumb-

hushed cargo
#

Listen- I was just working on the bot for like 8 hours straight- my ability to think was kinda messed up-

#

How would I send a message with an ephemeral in a channel without it being a response to something?

fervent cradle
#

you can't

hushed cargo
#

I-

#

So is there no way to edit current view anddd send another?

limber urchin
#

Why do you need it to be ephemeral?

hushed cargo
#

Bc I’m using it for a config thing

limber urchin
#

and why can't you just send the new view as a response to whatever interaction you're doing to edit the other view?

hushed cargo
#

Now the way I tried to deal with it was just deleting the message after enough time but this definitely should use the ephemeral arg

#

And I’m not completely sure how editing the original view to just be replaced by the second menu works

silk walrus
#

90 % done but gives error

Write a decorator to cache function invocation results. Store pairs arg:result in a dictionary in an attribute of the function object. The function being memoized is:

def fibonacci(n):
assert n >= 0
if n < 2:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

--- here what i did write 😄

def memoize(func):
   func.cache = {}
   def wrapper(n):
    try:
      ans = func.cache[n]
    except KeyError:
      ans = func.cache[n] = func(n)
    return ans
    return wrapper
@memoize
def fibonacci(n):
  
   print(fibonacci.cache)

    fibonacci(1)
    
    fibonacci(2)
    
    fibonacci(10)
    
    fibonacci.cache[10]
   
    fibonacci(40)
    
   
    assert n >= 0
    if n < 2:
        return n
       else:
     return fibonacci(n-1) + fibonacci(n-2)

limber urchin
#

Oh my god

#

use codeblock please

#

and this looks like a school assignment

light river
#

does running an event handler in an asyncio create_task make it not block the bot no matter how long it might take

hushed cargo
#

Idk

fervent cradle
#

Would using py await asyncio.sleep(DurationOfGiveaway) and storing the user's duration input in that ^ variable work? so it sleeps for eg 1 week, then continues code?

limber urchin
#

try it and see

young bone
#

^

fervent cradle
#

Seems to be like itd be worth trying so i will

#

but fr if ima waste my time please say 🤣

hushed cargo
#

Try with a couple mins first-

#

If it works fine like that a week will prolly work

fervent cradle
#

alr

green hinge
#

What is an alternative to @bot.group() to make it work?

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

    @bot.group()
    async def levelsettings(self, ctx):
      return

    @levelsettings.command()
    async def enable(self, ctx):
      async with self.bot.db.cursor() as cursor:
        await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild= ?", (ctx.guild.id,))
        levelsys = await cursor.fetchone()
        if levelsys:
          if levelsys[0]:
            return await ctx.send("Levelsystem is already enabled!")
          await cursor.execute("UPDATE levelSettings SET levelsys= ? WHERE guild= ?", (True, ctx.guild.id,))
        else:
          await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (True, 0, 0, ctx.guild.id,))
        await ctx.send("Levelsystem enabled!")
      await self.bot.db.commit() 

    @levelsettings.command()
    async def disable(self, ctx):
      async with self.bot.db.cursor() as cursor:
        await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild= ?", (ctx.guild.id,))
        levelsys = await cursor.fetchone()
        if levelsys:
          if levelsys[0]:
            return await ctx.send("Levelsystem is already disabled!")
          await cursor.execute("UPDATE levelSettings SET levelsys= ? WHERE guild= ?", (False, ctx.guild.id,))
        else:
          await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (False, 0, 0, ctx.guild.id,))
        await ctx.send("Levelsystem disabled!")
      await self.bot.db.commit() 

def setup(bot):
    bot.add_cog(LevelSystem(bot))```
green hinge
fervent cradle
#

Its going to be a public bot, multiple giveaways at one time so im struggling to see my best option?

#

Yeah but i dont know how i will actualy send the giveaway, and make it end at the specfic time chosen by the user.

#

Yeah i know how to convert "1w" to a week, but actualy making the message (giveaway) stop and send a new message (winners msg) after the time

#

is what i am struggling on

#

I'm planning to use buttons and I understand what you've said, but how do I make it do the random choice after a week for example

marble obsidian
#

is it possible to get a user id from name and discriminator

full basin
marble obsidian
full basin
#

.rtfm Converter

fervent cradle
#

Is this the most efficent way or the go to option? making an infinite loop dosent sound right but mabye im just being dumb

#

alright thanks

marble obsidian
#

thank you so much this is exactly what i needed

green hinge
#

Does anyone know how I can make it so that the leaderboard is automatically updated when someone moves up a level?

    @slash_command(description="Aktuelles Top 10 Leaderboard")
    async def leaderboard(self, ctx):
      async with self.bot.db.cursor() as cursor:
            await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild= ?", (ctx.guild.id,))
            levelsys = await cursor.fetchone()
            if levelsys and not levelsys[0] == 1:
                return await ctx.respond("Das Levelsystem ist auf diesme Server deaktiviert!", ephemeral=True)
            await cursor.execute("SELECT level, xp, user FROM levels WHERE guild= ? ORDER BY level DESC, xp DESC LIMIT 10", (ctx.guild.id,))
            leaderboard = await cursor.fetchall()
            if leaderboard:
              embed = discord.Embed(title="Leaderboard", color=discord.Color.blurple())
              for i, data in enumerate(leaderboard):
                user = ctx.guild.get_member(data[2])
                embed.add_field(name=f"{i+1}. {user.name}", value=f"Level: {data[0]} | XP: {data[1]}", inline=False)
              await ctx.respond(embed=embed)
            await ctx.respond("Es gibt noch keine Einträge auf dem Leaderboard!", ephemeral=True)```
full basin
#

Run the command again?

fervent cradle
#

I aint that smart tbf so doubt ill think of something else 🤣

limber urchin
#

If you're going to use a singular loop you should cache the end date and compare to that. Constantly querying a database for the same results is a waste of resources

proud mason
# fervent cradle Would using ```py await asyncio.sleep(DurationOfGiveaway)``` and storing...

I don't see why not.

Don't forget all gaws will stop running anytime you restart. They would be lost forever without being able to recover them. The only ways to recover them would be either manual checking or to read through the history of all channels the bot has access to and check if any message the bot sent has an embed/msg that is similar to the one you sent when creating the gaw

proud mason
limber urchin
#

If you have code that's blocking you need to solve that, not try to work around it

proud mason
#

There is a simple workaround if you really want to know, but it always always recommend to use async alternatives

proud mason
clever lark
#

I can't start my discord bot. pycord 2.3.2 (py-cord==2.3.2) is installed, but I can't get past this line.

Traceback (most recent call last):
  File "C:\___\___\main.py", line 2, in <module>
    from discord import Option, OptionChoice, guild
ImportError: cannot import name 'Option' from 'discord' (unknown location)
limber urchin
fervent cradle
clever lark
# silver moat `pip list` and send output.
C:\Users\____>pip list
Package            Version
------------------ -----------
aiohttp            3.7.4.post0
async-timeout      3.0.1
attrs              22.2.0
beautifulsoup4     4.11.1
certifi            2022.12.7
cffi               1.15.1
chardet            4.0.0
charset-normalizer 2.1.1
click              8.1.3
colorama           0.4.6
cryptography       38.0.3
dice               3.1.2
docopt             0.6.2
gTTS               2.3.0
idna               3.4
imageio            2.19.3
multidict          6.0.4
numpy              1.23.0
Pillow             9.4.0
pip                22.2.1
py-cord            2.3.2
pycparser          2.21
pyparsing          3.0.9
python-dotenv      0.20.0
requests           2.28.1
setuptools         63.2.0
six                1.16.0
soupsieve          2.3.2.post1
topggpy            1.4.0
typing_extensions  4.4.0
urllib3            1.26.14
yarl               1.8.2
youtube-dl         2021.12.17

[notice] A new release of pip available: 22.2.1 -> 22.3.1
[notice] To update, run: python.exe -m pip install --upgrade pip

C:\Users\____>
silver moat
clever lark
#

is there a way i can get around that? it works on other machines with a similar list of installed libraries.

silver moat
#

install the master branch of topggpy:

pip uninstall topggpy
pip install git+https://github.com/top-gg/python-sdk/
#

then re-install pycord

#
pip uninstall py-cord
pip install py-cord
proud mason
green hinge
#

Why doesn't my embed update when a user reaches a new level?
If I enter the / command again then it works but it does not update automatically when a user reaches a new level...

class LevelSystem(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.leaderboard_message = None
        self.bot.add_listener(self.on_user_level_up, "on_user_level_up")

    @commands.Cog.listener()
    async def on_user_level_up(self, ctx, user_id, level):
        await self.update_leaderboard(ctx)

    @commands.Cog.listener()
    async def on_message(self, message):
.
.
.
.
if xp >= 100:
              level += 1
              await cursor.execute("UPDATE levels SET level= ? WHERE user= ? AND guild= ?", (level, message.author.id, message.guild.id))
              await cursor.execute("UPDATE levels SET xp= ? WHERE user= ? AND guild= ?", (0, message.author.id, message.guild.id))
              await message.channel.send(f"{message.author.mention} has leveled up to level **{level}**!")
              self.bot.dispatch("on_user_level_up", ctx=message, user_id=message.author.id, level=level)
await self.bot.db.commit()```
clever lark
proud mason
fervent cradle
#

oh alr

#

Ill assume the other option is the way to go ig

silver moat
#
  1. name don't name message objects ctx.
  2. what is update_leaderboard.
proud mason
young bone
#

^

proud mason
limber urchin
green hinge
# silver moat 1. name don't name message objects `ctx`. 2. what is `update_leaderboard`.
    async def update_leaderboard(self, ctx):
        async with self.bot.db.cursor() as cursor:
            await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild= ?", (ctx.guild.id,))
            levelsys = await cursor.fetchone()
            if levelsys and not levelsys[0] == 1:
                return await ctx.respond("Das Levelsystem ist auf diesem Server deaktiviert!", ephemeral=True)
            await cursor.execute("SELECT level, xp, user FROM levels WHERE guild= ? ORDER BY level DESC, xp DESC LIMIT 10", (ctx.guild.id,))
            leaderboard = await cursor.fetchall()
            if leaderboard:
                embed = discord.Embed(title="Leaderboard", color=discord.Color.blurple())
                for i, data in enumerate(leaderboard):
                    user = ctx.guild.get_member(data[2])
                    embed.add_field(name=f"{i+1}. {user.name}", value=f"Level: {data[0]} | XP: {data[1]}", inline=False)
                if self.leaderboard_message:
                    await self.leaderboard_message.edit(embed=embed)
                else:
                    self.leaderboard_message = await ctx.send(embed=embed)
            else:
                await ctx.respond("Es gibt noch keine Einträge auf dem Leaderboard!", ephemeral=True)```
proud mason
#

You are passing the message in the event dispatch

#

This is why you shouldn't name message objects as context

#

Name and typehint parameters correctly

#

Will help you a lot down the road

#

Message has no method called send too iirc
Use message.channel.send

#

Also, any specific reasons for this listener-dispatcher system? Are you listening for this event in multiple cogs?

If not, just use a simple linear function call rather than dispatching it over the bot event system. It would save you some headaches

#

Errors arising from events are sent over another event called on_error. And handling that is a pain in the a**
It becomes a bit difficult to debug and troubleshoot while development

green hinge
silver moat
#

it's not a ctx

gleaming falcon
#

A bit confused on deferring Button presses.

When I click the button, obviously it disables and shows the "thinking" throbber while submitting.
But the first action in my callback is await interaction.response.defer(), since the action might take a few seconds. This strangely re-enables the button (I guess because it's technically been answered?). I had assumed defer would continue to show the throbber. Is there a way to do this so that another interaction couldn't be submitted (unless there was an error or something).

Additionally, I have the View time out after 5 minutes, but I also delete_original_message just because it's not needed. But after a few minutes, the bot reports an error because it's trying to time out the now-unknown message. Is there a method I should be calling that cancels this timeout?

silver moat
proud mason
#

For the parameters part,

#

Ctx would rather be a Message

#

You don't seem to use any attributes ctx has that message doesnt

gleaming falcon
proud mason
#

.rtfm interactionresponse.defer

winter condorBOT
proud mason
#

Set invisible to False

green hinge
proud mason
gleaming falcon
proud mason
proud mason
green hinge
proud mason
gleaming falcon
# proud mason Pretty sure no. But that method won't work the way it earlier used to. I suggest...

Actually, deleting does seem to count. I don't get any further error messages.

And I see that invisible=False just shows the "Bot is thinking" as a separate message. That part is fine, I suppose, but how do I keep the Button itself disabled? Explicitly editing the message with the updated state seems sub-optimal, but is that the only way to go about it?

For reference, here's my submit(). My goal is for this button to be completely disabled while the actions are being performed. (Would be super-cool if Discord allowed you to keep the "submitting" state with the animated dots 😦 )

    @discord.ui.button(label='Save', style=discord.ButtonStyle.primary, emoji='💾', disabled=True, row=1)
    async def submit(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.defer(ephemeral=True, invisible=False)

        # Prod handling
        # if await self.callback(self.sentinel):
        #     self.disable_all_items()
        # else:
        #     return interaction.message.reply(ephemeral=True)

        await asyncio.sleep(4)
        self.disable_all_items()

        embed = discord.Embed(...)
        # ... More Embed stuff

        self.stop()
        await interaction.message.channel.send(embed=embed)
        await interaction.delete_original_response()
proud mason
#

that unfortunately disables it for everyone

gleaming falcon
proud mason
#

ah thats good

gleaming falcon
#

I'm just trying to ensure impatient folks don't try to click the Save/submit multiple times. (And I guess disable_all_items is superfluous if I'm deleting the original response anyway. Which is also why it sucks I have to edit the message to update the view heh)

#

But okay, I think I have it. I have to update the message/view to disable the Buttons. Then if there's an error where I would be okay with them re-submitting, I'd re-enable and update the message/view again?

#

..nope. Looks like I can't defer and edit the message 😦

    @discord.ui.button(label='Save', style=discord.ButtonStyle.primary, emoji='💾', disabled=True, row=1)
    async def submit(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.defer(ephemeral=True, invisible=False)
        self.disable_all_items()
        await interaction.response.edit_message(view=self)

        # ...

discord.errors.InteractionResponded: This interaction has already been responded to before
Doesn't matter if defer is first or last in this list.

proud mason
#

you will have to use interaction.message.edit

gleaming falcon
#

I feel like this is a pretty common use case, no? You click a button and it takes more than Discord's expected short response time. A little baffled why this is so complex.

proud mason
#

Then if there's an error where I would be okay with them re-submitting, I'd re-enable and update the message/view again?

you can have a workaround. save the state of the working in a variable. smth like self.is_running = False
set this to true when you do your stuff
if another interaction is sent when it is true, respond with something like "i am working. please dont try to break me kek "

gleaming falcon
#

This is what I was expecting to happen (found in Discord Devs), but it's like.... not.

green hinge
dapper flare
#

it does the thing which it's supposed to do but still says failed how do i remove this?

fervent cradle
#

I have self.bot.wait_for("message", timeout=120) but im struggling to check for an input as it just gives me unexpectected indentation, using an if statment just above
Code:

  IfNone = await self.bot.wait_for("message",timeout=120)
        IfNone == "None":
              GiveawayEmbed=discord.Embed(title=f"Giveaway for {PrizeInput.content}")
              await ctx.send(embed=GiveawayEmbed)``` (Do not worry about any missing variables, eg prizeinput)
limber urchin
#

Why do you have an indent there?

gleaming falcon
fervent cradle
#

if thats where you're talking about

limber urchin
fervent cradle
#

oops

#

i see i wasnt thinkin and just added the var name instead

limber urchin
#

and once again, learn to name your variables correctly

#

your code is impossible to read

fervent cradle
limber urchin
#

Use proper naming conventions instead of just doing random camel case and upper camel case

fervent cradle
#

Alright

silver moat
fervent cradle
gleaming falcon
limber urchin
dapper flare
# limber urchin not unless you actually show your code
async def callback(interaction: discord.Interaction):
                if str(select.values[0]) in pages:
                    eu = discord.Embed(title=f"CSGO inventory, {select.values[0]}", colour=discord.Colour.blurple(), timestamp=datetime.datetime.utcnow())
                    s = ''.join(x for x in select.values[0] if x.isdigit())
                    print(int(s))
                    start_index = (int(s) - 1) * 15
                    end_index = start_index + 15
                    for x in range(15):
                        try:
                            eu.add_field(name=page_guns[start_index][0], value=f"Has stickers: {page_guns[start_index][1]}", inline=True)
                            start_index+=1
                        except:
                            pass
                    await interaction.message.edit(embed=eu)
            select.callback = callback
            view.add_item(select)```

here
#

it does the job edits the message but still manages to fail the interaction idk why

silver moat
dapper flare
#

oo

dapper flare
silver moat
#

I can spell, edit_response

fervent cradle
dapper flare
limber urchin
#

For the 150th time, you need to learn basic Python before making a bot

fervent cradle
#

unless am blind now

limber urchin
fervent cradle
#

Alright, well first be nice, thats litearly discord showing it not my code.

limber urchin
#

Well take a screenshot or something then if you can't show your actual code in Discord

gleaming falcon
limber urchin
gleaming falcon
#

Either way, it's not super hard to get the code to look correct in Discord

gleaming falcon
fervent cradle
#

Mabye it just happens when i copy and paste it from vsc

green hinge
#

Can anyone tell me why I always get the following error message?
Code:

await cursor.execute("SELECT messageid FROM levelSettings WHERE guild= ?", (ctx.guild.id,))
                messageid = await cursor.fetchone()
                if messageid:
                    msg = await ctx.channel.fetch_message(messageid[0])
                    await msg.edit_original_response(embed=embed)
                else:
                    msg = await ctx.respond(embed=embed)
                    embed_id = msg.id
                    await cursor.execute("INSERT OR IGNORE INTO levelSettings (messageid, guild) VALUES (?,?)", (embed_id, ctx.guild.id,))

Error:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event 
    await coro(*args, **kwargs)
  File "c:\Users\User\Documents\Coding\OnlyFrames\cogs\levelsystem.py", line 62, in on_message
    await self.update_leaderboard(message)
  File "c:\Users\User\Documents\Coding\OnlyFrames\cogs\levelsystem.py", line 174, in update_leaderboard
    msg = await ctx.channel.fetch_message(messageid[0])
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1686, in fetch_message
    data = await self._state.http.get_message(channel.id, id)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 362, in request      
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message```
proud mason
fervent cradle
#
            return NoReqs.content == 'None'
            
        IfNone = await self.bot.wait_for("message",timeout=120,check=Check)
        
        GiveawayEmbed=discord.Embed(title=f"Giveaway for {PrizeInput.content}")
        await ctx.send(embed=GiveawayEmbed)``` How can i check if the users Input is NOT None
limber urchin
proud mason
silver moat
proud mason
#

no thats the other one

#

interaction.edit_original_message got deprecated in favour of interaction.edit_original_response

#

💀

fervent cradle
green hinge
# proud mason best way would be to use partial messageable objects ```py partial_channel = bot...

What's the best way to incorporate this? 🤔

                await cursor.execute("SELECT messageid FROM levelSettings WHERE guild= ?", (ctx.guild.id,))
                messageid = await cursor.fetchone()
                if messageid:
                    msg = await ctx.channel.fetch_message(messageid[0])
                    await msg.edit_original_message(embed=embed)
                else:
                    msg = await ctx.respond(embed=embed)
                    embed_id = msg.id
                    await cursor.execute("INSERT OR IGNORE INTO levelSettings (messageid, guild) VALUES (?,?)", (embed_id, ctx.guild.id,))```
fervent cradle
#

I do think of this stuff first smh

limber urchin
#

and why are you trying to do ctx.send there?

young bone
#

we dont even know what you are doing...

#

#how-to-get-help

fervent cradle
proud mason
limber urchin
gleaming falcon
# proud mason yeah that doesnt happen

Damn. So there's literally no way to keep a long-running Button from being pressed a second time? What an oversight 😐

I guess if I can't both edit the message (to disable manually) and also set a deferment (which... also means I wouldn't be able to edit the message again if I need to re-enable?), I'll have to do the state check as you mentioned. Just seems janky (no offense; more a gripe on Discord's need to be janky)

fervent cradle
limber urchin
#

151th time: Learn Python before making a bot

gleaming falcon
#

This error says that you're trying to access a 'code' member of a string, which is obviously not logical. But your actual code doesn't show where .code is being referenced.

fervent cradle
limber urchin
gleaming falcon
proud mason
gleaming falcon
fervent cradle
limber urchin
fervent cradle
#

missing the from:

proud mason
gleaming falcon
fervent cradle
gleaming falcon
#

I have no idea, I don't know what you're actually testing; you left out a ton of context.

fervent cradle
gleaming falcon
#
  1. Fix the intent of your return, that's definitely not a paste error.
    1a. Check() will always return the string "None", so there's no point in evaluating the rest of this particular method.
fervent cradle
#

In my code the return is just below The C in check

gleaming falcon
#

Then you have an issue with mismatched spaces and tabs. Indentation should be spaces, specifically to mitigate this issue.

fervent cradle
proud mason
#

IfNone = await self.bot.wait_for("message",timeout=120,check=Check)
wtf

gleaming falcon
#

I actually don't know what wait_for does. I know it's a real thing, but I've never used it.

fervent cradle
#

First time i've gotten user input in pycord, so if its wrong thats likley

limber urchin
gleaming falcon
proud mason
waxen whale
errant craneBOT
#

Here's the wait for event example.

green hinge
fervent cradle
#

i just used the docs

gleaming falcon
proud mason
fervent cradle
#

i just couldnt think of a name lmao

proud mason
waxen whale
#

Workaround would be you ignore users pressing the button a second time while it’s not finished and answer the second presses in the meantime with update message. So it just shows nothing. Like a „i ack it but don’t do anything“

#

I know it sucks but with discords architecture with message interactions, there is literally no way atm. They would have to change much stuff to get that working

#

And atm they’re working on other components so they’re busy

fervent cradle
gleaming falcon
#

I think @proud mason mentioned that with using a state variable. It's an ephemeral View anyway, so that won't be a big deal I suppose.

gleaming falcon
proud mason
waxen whale
#

Nope not that sadly

gleaming falcon
#

(╯°□°)╯︵ ┻━┻

waxen whale
#

Can’t tell you more than „it’ll be cool stuff“

gleaming falcon
#

I hope it will be like... check/state-boxes, e.g. 'Yes/No', 'On/Off'

waxen whale
#

Better smug

gleaming falcon
#

WHAT'S BETTER THAN ON/OFF, LALA?!

waxen whale
#

Anyways cough

gleaming falcon
#

Okay, go back to sleep. Thanks for answering me 🙂

fervent cradle
waxen whale
#

Will do

fervent cradle
proud mason
fervent cradle
#

if thats what ym

waxen whale
green hinge
# proud mason well there is a few things ctx.respond would return the Interaction so you woul...

When I set this, I always get "interaction" is not defined.

await interaction.original_response()```

```py
                await cursor.execute("SELECT channelid, messageid FROM levelSettings WHERE guild= ?", (ctx.guild.id,))
                data = await cursor.fetchone()
                channel_id = data[0]
                message_id = data[1]
                if message_id:
                    partial_channel = self.bot.get_partial_messageable(channel_id)
                    partial_message = partial_channel.get_partial_message(message_id)

                    message = await partial_message.edit(embed=embed)
                    await cursor.execute("UPDATE levelSettings SET messageid= ? WHERE guild= ?", (message.id, ctx.guild.id,))               
                else:
                    msg = await ctx.respond(embed=embed)
                    embed_id = await interaction.original_response(msg)
                    await cursor.execute("INSERT OR REPLACE INTO levelSettings (channelid, messageid, guild) VALUES (?,?,?)", (channel_id, embed_id, ctx.guild.id,))
                    await self.bot.db.commit()```
fervent cradle
proud mason
#

also, i think you dont have channel_id defined

proud mason
#

huh

obtuse juncoBOT
#

dynoError Something went wrong.

proud mason
#

lmao

#

?tag nohelp

obtuse juncoBOT
#

Nobody helps you? See #help-rules §2, then you know why.

fervent cradle
proud mason
#

yea its correct

green hinge
# proud mason > ctx.respond would return the Interaction `interaction = await ctx.respond(...)...

What am I doing wrong now? -.-

                await cursor.execute("SELECT channelid, messageid FROM levelSettings WHERE guild= ?", (ctx.guild.id,))
                data = await cursor.fetchone()
                if not data:
                    interaction = await ctx.respond(embed=embed)
                    message = await interaction.original_response()
                    embed_id = message.id
                    channel_id = message.channel.id
                    await cursor.execute("INSERT OR REPLACE INTO levelSettings (channelid, messageid, guild) VALUES (?,?,?)", (channel_id, embed_id, ctx.guild.id,))
                    await self.bot.db.commit()
                else:
                    channel_id = data[0]
                    message_id = data[1]
                    if message_id:
                        partial_channel = self.bot.get_partial_messageable(channel_id)
                        partial_message = partial_channel.get_partial_message(message_id)

                        message = await partial_message.edit(embed=embed)
                        await cursor.execute("UPDATE levelSettings SET messageid= ? WHERE guild= ?", (message.id, ctx.guild.id,))  ```
fervent cradle
#

Well what's wrong

proud mason
green hinge
proud mason
green hinge
# proud mason Cool. No worries

How can I make it so that I can pass something into the ctx variable in the on_ready event so that my tasks.loop then runs?

 @commands.Cog.listener()
    async def on_ready(self):
        setattr(self.bot, "db", await aiosqlite.connect("level.db"))
        async with self.bot.db.cursor() as cursor:
            await cursor.execute("SELECT channelid, messageid FROM calender WHERE guildid = ?",(self.bot.guild.id,))
            data = await cursor.fetchone()
            if not data:
                pass
            else:
                self.update_events.start()    

    @tasks.loop(seconds=10)
    async def update_events(self, ctx):```
proud mason
green hinge
green hinge
fervent cradle
#

how to download py cord

full basin
#

.install

winter condorBOT
#

pip install py-cord

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

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

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

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

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

hushed cargo
#

Is there a way to edit a message in an interaction thingy multiple times?

#

I wanna make it edit it as soon as the button is pressed then again like 10 seconds later

full basin
#

Get the message

#

.rtfm interaction.original_response

winter condorBOT
hushed cargo
#

.rtfm interaction.original_response

winter condorBOT
proud mason
winter condorBOT
proud mason
#

You can also do that. It is 1 less api call

fervent cradle
#

When I try to get pip it say this

#

?tag git

obtuse juncoBOT
#

dynoError No tag git found.

proud mason
#

Oh it's 3.11

hushed cargo
#

.rtfm interaction.edit_original_response

winter condorBOT
proud mason
hushed cargo
#

That was just bc I couldn’t press button thingy in time :c

fervent cradle
proud mason
hushed cargo
#

Nono I mean I didn’t use the select menu thingy in time

#

So said interaction failed

proud mason
proud mason
hushed cargo
#

Is there a way for me to pass an argument into a view class

proud mason
# fervent cradle Wdym

See your screenshots
Using python3 says python3.10 in the lines
Using py -3 says python3.11 in the lines

Try doing python3.11 -m ensurepip or py -3 -m ensurepip

#

Also try opening the cmd promt using admin perms

proud mason
proud mason
#

||how tho 🤔||

fervent cradle
proud mason
boreal dust
green hinge
spring hull
#

How can i reload cogs? I wanna make a command to reload cogs so i don't have to restart the bot (and also only allow the command to be sent if it's me)

proud mason
spring hull
#

I've got as far as reloading one

proud mason
#

.rtfm reload

proud mason
#

.rtfm is_owner

proud mason
#

@spring hull ^

spring hull
#

right, but what about all

#

also i don't understand the is_owner thing...

green hinge
proud mason
proud mason
#

bot.extensions has all the currently loaded extensions

proud mason
spring hull
#

where's that?

proud mason
spring hull
#

yes, that's why i want to make a command to reload them

proud mason
green hinge
# proud mason you cant respond if you dont receive an interaction you can send a message in t...

My problem is that I call the function via a slash command:

@slash_command(description="Zeigt die kommenden Events an")
    async def events(self, ctx):
      await self.update_events.start(ctx)```
But if I then restart the bot the loop has to be restarted as well and here I thought I would just do that in the on_ready method if the embed that is created in the function is present. But my function is using ctx.respond and ctx.guild.id.
proud mason
spring hull
#

yes, but this one is in main.py lol. It won't register with discord......

proud mason
spring hull
#

yes

#

it's a slash command to reload cogs

#

that only i can use (i hope)

green hinge
proud mason
#

also, you cant modify and hot reload the main.py file like you can do with cogs

spring hull
#

i gtg brb in like 20 mins idk. Keep typing and i'll see it when i get back

proud mason
spring hull
#

every other command is in cogs

#

so a /reload command

proud mason
proud mason
proud mason
proud mason
# spring hull so a /reload command

yeah so like i mentioned before, you can use the check, the command will be visible to other but they wont be able to use it. you can have it register in a private guild if you want

or keep it a prefix cmd

green hinge
proud mason
spring hull
#

I'll just have a check to make sure it's me, atleast I will when discord register the slash commands

proud mason
proud mason
green hinge
# proud mason yes. that is correct. Although im not sure if you need message id, but thats upt...

This is my slash command:

    @slash_command(description="Zeigt die kommenden Events an")
    async def events(self, ctx):
        async with self.bot.db.cursor() as cursor:
          await cursor.execute("SELECT channelid, messageid FROM calender WHERE guild= ?", (ctx.guild.id,))
          data = await cursor.fetchone()
          if not data:
            await self.update_events.start(ctx)
          else:
            channel_id = data[0]
            message_id = data[1]
            channel = self.bot.get_channel(channel_id)
            message = await channel.fetch_message(message_id)
            await message.delete()
            await cursor.execute("DELETE FROM calender WHERE guild = ?", (ctx.guild.id,))
            await self.bot.db.commit() 
            await self.update_events.start(ctx)
          await ctx.respond("Der Kalender wurde erstellt!", ephemeral=True)```
And that is the function I call and update regularly:
```py
    @tasks.loop(minutes=20)
    async def update_events(self, ctx):
        .
        .
        .
        .
            async with self.bot.db.cursor() as cursor:
                await cursor.execute("SELECT channelid, messageid FROM calender WHERE guild= ?", (ctx.guild.id,))
                data = await cursor.fetchone()
                if not data:
                    interaction = await ctx.respond(embed=embed)
                    message = await interaction.original_response()
                    embed_id = message.id
                    channel_id = message.channel.id
                    await cursor.execute("INSERT INTO calender (channelid, messageid, guild) VALUES (?,?,?)", (channel_id, embed_id, ctx.guild.id,))
                    await self.bot.db.commit()
                    #await self.update_events.start(ctx)
                else:
                    channel_id = data[0]
                    message_id = data[1]
                    if message_id:
                        channel = self.bot.get_channel(channel_id)
                        message = await channel.fetch_message(message_id)

                        message = await message.edit(embed=embed)
                        await cursor.execute("UPDATE calender SET messageid= ? WHERE guild= ?", (message.id, ctx.guild.id,))
                        await self.bot.db.commit()```
spring hull
#

wdym overriding the on_connect?

#

It was working fine until i added this command

#

I just tried registering a command inside a cog, that worked... hmm, odd

#

so /test works in that cog, /reload and /cogreload don't work in main.py

#

So commands are syncing, just not this one

#

So i can't put it in main.py for..... idk.. but i can't put it in a cog either cuz this command reloads cogs.

silver moat
#

Don't you need to call sync_commands to reload slash commands?

spring hull
#

yes, but why is this command, the one to add /reload, not registering

#

(also, this command does sync commands when it is used successfully)

#

I made a post

green hinge
#

Does anyone know why I always get the "application not responding" message?

    @slash_command(description="Zeigt die kommenden Events an")
    async def events(self, ctx):
        async with self.bot.db.cursor() as cursor:
          await cursor.execute("SELECT channelid, messageid FROM calender WHERE guild= ?", (ctx.guild.id,))
          data = await cursor.fetchone()
          if not data:
            await self.update_events.start(ctx.guild.id, ctx.channel.id)
          else:
            channel_id = data[0]
            message_id = data[1]
            channel = self.bot.get_channel(channel_id)
            message = await channel.fetch_message(message_id)
            await message.delete()
            await cursor.execute("DELETE FROM calender WHERE guild = ?", (ctx.guild.id,))
            await self.bot.db.commit() 
            await self.update_events.start(ctx.guild.id, ctx.channel.id)
        await ctx.respond("Der Kalender wurde erstellt!", ephemeral=True)```
proud mason
#

defer the interaction in the first line of the cmd

green hinge
young bone
#

Defer it

supple sinew
#

Hey! Is there any way to get self.region attribute inside @bot.slash_command decorator?

class SelectMenu(discord.ui.Select):
    def __init__(self, placeholder, options):
        super().__init__(
            placeholder=placeholder,
            min_values=1,
            max_values=1,
            options=options,
        )
        self.region = None

    async def callback(self, interaction):
        await interaction.response.send_message(
            f"You chosen {self.values[0]} region"
        )
        self.region = self.values[0]


class SelectView(discord.ui.View):
    def __init__(self, placeholder, options):
        super().__init__()
        item = SelectMenu(placeholder, options)
        self.add_item(item)
spring hull
#

I keep getting this error when reloading cogs

sage bear
#

anyone know if there is something i can use like active_developer to flag if the user has that badge?

tough briar
#

.rtfm Converter

spring hull
young bone
spring hull
#

ok... i just thought that it my post may have been lost

green hinge
#

How can I create a dropdown menu with all members here?

class AddUser(discord.ui.Modal):
    def __init__(self, channel):
        super().__init__(
          title = "User zum Ticket hinzufügen",
          timeout=300,
          )

        self.channel = channel

        # Erstelle eine Liste aller User des Guilds
        member_list = [member.mention for member in channel.guild.members]

        self.user = discord.ui.Choice(
          label="User",
          options=member_list,
          required=True,
          placeholder="Wähle einen User aus"
          )
        self.add_item(self.user)

    async def callback(self, interaction: discord.Interaction) -> None:
        # Hole den ausgewählten User anhand der erhaltenen Erwähnung
        user = discord.utils.get(interaction.guild.members, mention=self.user.value)
        if user is None:
            return await interaction.send(f"User konnte nicht gefunden werden!")
        overwrites = discord```
proud mason
fallen cove
#
bot\src\cogs\medbayV2.py", line 252, in deny      
    await interaction.response.send_modal(MedbayDenyModal(title="Reason for Denial"))        
TypeError: MedbayDenyModal.__init__() got an unexpected keyword argument 'title'

any idea why the title keyword is unexpected but when removed it expects it

proud mason
#

also, you might not be accepting it in your modal subclass init

#

show your init method

fallen cove
# proud mason show your init method
class MedbayDenyModal(discord.ui.Modal):
    def __init__(self):
        super().__init__(
            discord.ui.InputText(
                label="Reason for Denial",
                value="Enter reason here",
                style=discord.InputTextStyle.long,
            )
        )

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(
            title="Reason for Denial",
            fields=[
                discord.EmbedField(
                    name="", value=self.children[0].value, inline=False
                ),
            ],
            color=discord.Color.red(),
        )
        await interaction.response.send_message(embeds=[embed])


# button to send modal
@discord.ui.button(label="Deny", style=discord.ButtonStyle.red, custom_id="MBV2Deny")
    async def deny(self, button: discord.ui.Button, interaction: discord.Interaction):
        modal = MedbayDenyModal(title="Reason for Denial")
    
        await interaction.response.send_modal(modal)
proud mason
fallen cove
proud mason
versed cave
#

can i use the discord.slash_command decorator in a Cog?

versed cave
#

alright

#

I was wondering where this error was coming from when I tried to

full basin
#

Traceback?

versed cave
#
Traceback (most recent call last):
  File "C:\Users\parke\AppData\Local\pypoetry\Cache\virtualenvs\discordnpc-JC7EQ1JP-py3.11\Lib\site-packages\discord\commands\options.py", line 211, in __init__
    self.input_type = SlashCommandOptionType.from_datatype(input_type)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\parke\AppData\Local\pypoetry\Cache\virtualenvs\discordnpc-JC7EQ1JP-py3.11\Lib\site-packages\discord\enums.py", line 772, in from_datatype
    if datatype.__name__ in ["Member", "User"]:
       ^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?
#

wait

#

it might be the fact I have annotations enabled

versed cave
#

how do I defer an interaction with a Context object

limber urchin
#

have you tried ctx.defer()?

simple plover
#

can I use tasks to end a giveaway after specific time? and how?

proud mason
#

and by tasks do you mean discord.ext.tasks.loop ?

#

.rtfm guild_only

north gorge
#

why can't you just click copy ID on an emoji pepehands

proud mason
north gorge
#

😄 ty

north gorge
#

i've spent like half an hour wondering why get_emoji wasn't working, turns out I was copy -> pasting the message ID and not the emoji ID because right clicking one and hitting copy ID lies!

fervent cradle
#

Idk what to do

#

Please help

young bone
fervent cradle
livid monolith
#

code track = await vc.node.get_tracks(query=f"https://pds.g3v.co.uk/track/{spotid}", cls=wavelink.LocalTrack)

error discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: LoadTrackError: Connecting to the URL failed.

vapid pumice
#

Can buttons be added as self.add_item in the class init?
If so, how could I find more info about how to call the interaction?

I can't use @discord.ui.View because it won't let me access self.variables

vapid pumice
# full basin Yes they can

Do you have any idea where I could get info, from the docs perhaps, on calling the actual Response in that regard? Trying to do it the same way as using @discord.ui.View doesn't seem to be cutting it. <3

full basin
#

You subclass a View and then self.add_item(AnItem()) on the jnit

vapid pumice
#

shit, I meant to say Response >.<

full basin
#

discord.ui.View is not a decorator

knotty surge
#

Anyway to create Models I think they are called

#

Like pop ups that you can have fields entered with a submit btn?

errant craneBOT
#

Here's the modal dialogs example.

full basin
#

@knotty surge

north gorge
#

Can I register a view as permanent if it requires custom parameters to initialize an instance of it?

neon raven
#

Okay I am trying to create like a messaging bot to acess my email. I pass the email data in a file called message.txt but it is not being read by bot as a file. What do I do?

proud mason
north gorge
#

I don't know how I'd do that in this case sadge

#

thank you for the response though

heavy jungle
#

why are my ` not formatting

#

should read as d6, d7

#

the same formatting works fine in a field value

#

just not in a description

proud mason
north gorge
#

hmm. I think I get what you're saying. thanks om.

fervent cradle
#

how to kick and ban a member with pycord

proud mason
winter condorBOT
proud mason
#

.rtfm member.ban

proud mason
#

Although it's not recommended to make commands that replicate built in discord functionality

amber shale
#

quick question how to change embed color using hexcode?

#
hex_code = "#2f3136"```
limber urchin
#

You parse the it to a hexadecimal int and pass it to the Color class

amber shale
#

thanks it worked

limber urchin
#

Because discord snowflakes are too large to be passed as an integer. Use a string

bitter lance
#

can't the bot send custom emoji from other servers?

#

I use other server emoji in button ui with emoji=discord.PartialEmoji.from_str(':name:id'), but I can't use in message or embed description

limber urchin
#

it can if it has permission to use external emojis

proud mason
#

why not just use the role input type rooThink

#

also, dont name your variables id

#

its a built in python function

#

tbh you can still do role.id to get it

#

yeah but you can have errors down the road and you wouldnt understand where they are coming from. it not a good practice, but its your choice

bitter lance
limber urchin
#

And the bot needs to actually be in a server with the emoji of course

bitter lance
green hinge
#

Can someone tell me how I can get this to work?:

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

    async def get_water(self):
        async with aiosqlite.connect("database.db") as db:
            cursor = await db.execute("SELECT * FROM waters")
            waters = await cursor.fetchall()
            await cursor.close()
            return waters

    @slash_command(description="Trage hier deine Trophy ein")
    async def trophy(self, ctx, gewässer: Option(str, "Wähle dein Gewässer aus", choices=lambda :[i[0] for i in (await self.get_water())] )):
        await ctx.respond(f"Du hast {gewässer} ausgewählt")```
proud mason
#

use autocomplete

errant craneBOT
#

Here's the slash autocomplete example.

proud mason
#

you cant dynamically set option choices without that

limber urchin
soft girder
#

Hello. I want to know. How to make input values ​​in groups commands?

#

I can send examples of what I want to do and examples of my work.

#

Which don't work..

soft girder
#

5sec

#

It's what I WANT

#

and.....

#

this. I have

#

I can't do option member

#

удалiть = discord.SlashCommandGroup("удалить", "Вернуть участника из мута.")

@commands.guild_only()
@commands.has_permissions(administrator =True)
@удалiть.command(name='мут', description='Вернуть участника из мута.')
async def удалить_мут(ctx: discord.ApplicationContext, участник:discord.Option(discord.Member,name="участник",description="Участник ,которого вы вернёте.") ,причина=None):
    if причина == None:
        причина="Не указано."
        await участник.remove_timeout(reason=причина)
        await ctx.respond(f'Участника {участник.mention} вернули в обсуждение.\nПричина: {причина}',ephemeral=True)

client.add_application_command(удалiть)

#

This my code

full basin
#
  1. Use English to code. You save the library some pain.
  2. Use cogs.
errant craneBOT
#

Here's the slash cog groups example.

soft girder
#

Thx

#

I will try

soft girder
#

@full basin Thanks!!! It helped.

viral peak
#

is there a way to make a paginator interactable for everyone, not just the person who called it?

#

author check

#

missed that

livid monolith
#
    async def on_voice_state_update(self, member, before, after):
        if not member.id == self.bot.user.id:
            return
        elif before.channel is None:
            time = 0
            while True:
                vc: wavelink.Player = after.channel.guild.voice_client
                await asyncio.sleep(1)
                time = time + 1
                if time == 300:
                    if len(vc.channel.members) == 1:
                      embed = discord.Embed(description=":octagonal_sign: Left the voice channel and cleared the queue due to inactivity.")
                      await vc.tchannel.send(embed=embed)
                      await vc.stop()

                if not vc.is_connected():
                    break

is meant to leave after the user disconnects from the channel but does not

proud mason
#

?tag codeblock

obtuse juncoBOT
#

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

That makes reading code in Discord a lot easier:

print("This is an example.")
livid monolith
#

none

thick pumice
#

Anyone have "select menu" docs link? (not guide)

proud mason
# livid monolith none

that is one whacky code tbh

            while True:
                vc: wavelink.Player = after.channel.guild.voice_client
                await asyncio.sleep(1)
                time = time + 1
                if time == 300:
                    if len(vc.channel.members) == 1:
#

it only checks the length at 300

#

why not just do asyncio.sleep(300)

proud mason
winter condorBOT
#

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

proud mason
#

hmm

#

.rtfm select

proud mason
#

yeah that

#

1st

thick pumice
#

Thank you

plush moat
#

Can messages with embeds be ephemeral (only shown to the user who requested the slash command)?

winter condorBOT
plush moat
#

I have

#

Oh huh. It didn't work just now, but now it does. Cool, ty!

marble obsidian
#

how do i set the link on a link button

livid monolith
proud mason
#

@livid monolith btw dm if you want a code i had written for this

proud mason
#

it could be related to the fact that you use after.guild which can be None

#

use before.guild

lethal valve
#

how do i edit a message reply

#

like ctx.reply then edit the reply

proud mason
lethal valve
proud mason
lethal valve
#

Ohhhhhh

#

Thanks dawg

proud mason
#

no worries

proud mason
proud mason
#

.rtfm context.edit

proud mason
#

only works for slash cmds thinkCat

young bone
#

I will try it

fervent cradle
#

import discord
from discord.ext import commands

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

    @commands.command(name="giveawaychat") 
    async def giveawaychat(self,ctx,chatid:str,):
        Chat = self.bot.get_channel(chatid)
        print(Chat)
        Gwchatembed=discord.Embed(title=f"Giveaway chat has been set to{Chat} ")
        
        await ctx.send(embed=Gwchatembed)
def setup(bot):
    bot.add_cog(GiveawayChat(bot))``` Why is it returning none?
young bone
proud mason
#

full error ?

fervent cradle
#

No error

fervent cradle
#

When i print it

young bone
#

it will return None if the bot cannot find it

fervent cradle
#

It does exist though

#

Am i doing the get wrong

proud mason
fervent cradle
proud mason
fervent cradle
#

alr

fervent cradle
fervent cradle
#

👍

plush moat
#

made a question thread for it :P

#

nvm, I had 2 bots open on accident, one running outdated code, and both were sending requests to sync the command list with their own versions of it (one with and one without)

plush moat
#

yup, and now I'm blocked out of uploading command lists for a day, so I can't continue working on my bot for 24 hours :)))

fervent cradle
# proud mason 2nd one
   @commands.command(name="giveawaychat") 
    async def giveawaychat(self,ctx,chatid:str,):
        Chat = self.bot.get_channel(chatid)
        ConvertedChatID = int(Chat)
        print(ConvertedChatID)
        Gwchatembed=discord.Embed(title=f"Giveaway chat has been set to{Chat} ")``` 
typeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType' , Am i convertiing wrong?
young bone
#

did you read what @proud mason was writing?

harsh canyon
#
import discord
from discord.ext import commands, tasks

import datetime
from backports.zoneinfo import ZoneInfo

from bin.storage import Config

times = datetime.time(hour=19,minute=12,second=0)

class Quotequeue(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.db = bot.db
        self.quotetime.start()
        print(self.quotetime.next_iteration)
    
    @tasks.loop(time=datetime.time(hour=19,minute=12,second=0))
    async def quotetime(self):
        channel = self.bot.get_channel(1004178748205187086)
        await channel.send("test")
    
    @quotetime.before_loop
    async def before_quotetime(self):
        await self.bot.wait_until_ready()
        
def setup(bot):
    bot.add_cog(Quotequeue(bot))

it prints none and never runs the task, what am i doing wrong?

fervent cradle
#

sorry

green hinge
#

How can I make it in Autocomplete that when I enter a letter, only hits with the corresponding first letter are displayed? 🙂

green hinge
#

Is the list for Autocomplete limited to 25 entries?

young bone
#

only choices is limited to 25

#

same for menus

livid monolith
#
    async def play(self, ctx, *, trackid):
        """Search from Spotify to add to the song queue."""
        await ctx.defer()
        if ctx.author.voice is None:
            embed = discord.Embed(description=":warning: **Not in a voice channel**")
            await ctx.respond(embed=embed)
            return
        if not ctx.voice_client:
            vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
            await ctx.guild.change_voice_state(channel=ctx.author.voice.channel, self_mute=False, self_deaf=True)
        else:
            vc: wavelink.Player = ctx.voice_client
        vc.tchannel=ctx.channel
        if vc.queue.is_empty and not vc.is_playing():
          try:
              track = await vc.node.get_tracks(query=f"https://pds.g3v.co.uk/track/{spotid}", cls=wavelink.LocalTrack) 
              await vc.play(track)
              await vc.set_volume(50)
              await ctx.respond(f'Added `{track.title}` to the queue')
          except:
              await ctx.respond(":warning: Unable to find that song.")
        else:
          try:
              track = await vc.node.get_tracks(query=f"https://pds.g3v.co.uk/track/{spotid}", cls=wavelink.LocalTrack) 
              await vc.queue.put_wait(track)
              await ctx.respond(f'Added `{track.title}` to the queue')
          except:
              await ctx.respond(":warning: Unable to find that song.")

replies with "Unable to find that song." even though its a valid spotifyID

green hinge
# young bone no

I have a list with 100 entries but only 25 of them are displayed 🙄

limber urchin
young bone
#

thats how autocomplete works

limber urchin
#

Discord obviously won't display all 100 autocomplete options at the same time

young bone
#

^

young bone
#

even the IDE´s doing autocomplete

green hinge
errant craneBOT
#

Here's the slash autocomplete example.

hushed cargo
#

Is it possible to make a command only visible to one user?

#

Like through the bot

#

Not with the integration thingy

silver moat
#

no