#Basic Pycord Help (Quick Questions Only)
1 messages · Page 52 of 1
yeah
Pulling this down
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 🤔 )
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?
Unfortunately you won't be able to; discord doesn't have the ability to send unsolicited ephemeral messages.
You could DM them (although I always have DMs off and hate that as a solution, but noting it.)
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
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)
@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?
Bruh why didn’t this show up on my search results, tysm
Modals?
Maybe lay out your workflow. If a user invokes a slash command, you can send a message with a Dialog/Modal, buttons, etc
@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.
What is the difference between a regular discord.channel obj and a discord.abc.GuildChannel obj?
Yup. You could just store the message they used to interact and respond to it, or just send a raw message and @ them
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.
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.
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
.rtfm guild.channels
I used exactly this (using utils.get)
Then tried to use that object to run channel.set_permission
and?
interaction.guild.channels should work, right?
As I wanted to use discord.utils.get(interaction.guild.channels, name=“example”)
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.
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
Do you have guild intents?
🙂 @silver moat
Because you asked it to 
Can I use client instead of bot
.tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
?tag client
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)
How can I make it so a command will run even if only one check returned true?
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.
add a custom check
Copy and paste the entire Discord Docs to it
lol
No, please understand that when you
add_item, you're adding a discord.ui element to the view. Since you have added fiveCronTabSelectinstances, which areSelects, taking up five elements in the View, you cannot add asubmit_btn. You should also remove thesubmitandcancelfunctions 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.
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
check_any iirc
.rtfm check_any
there
is this view sent with an interaction or with a normal message?
view sent with an interaction
the latest version from github
i mean i clone the repo and install it
hmm
Why are you using a git-installed version instead of the latest release (2.3.2) on pypi?
bc idk
Anyone have any idea about this?
Give an explanation instead of spoonfeeding
Hmm
Show how you are sending the view. Also show the subclass init if you have made one
Pass timeout=None while creating the view object
Okay, where would I pass that
Where you create the object. Which in your case is view=MyView()
Yes that should work
What about setting timeout=None directly in the params of the __init__?
That works too
Awesome
I can't seem to find out any issues with that code
ok
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()
ok
response()*
Something is still timing out
As I made a test
async def on_timeout: print(“timeout”)
And I saw timeout in my terminal and my button no longer functions
Oops my bad
Show how you did it
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
ah yes if you are overriding the view class init then you have to do it like that
Ty
oh i just found a way to fix it also ty
cool
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
For what?
A custom check I'm making
.rtfm permissions_for
discord.Thread.permissions_for
discord.DMChannel.permissions_for
discord.TextChannel.permissions_for
discord.StageChannel.permissions_for
discord.ForumChannel.permissions_for
discord.VoiceChannel.permissions_for
discord.GroupChannel.permissions_for
discord.CategoryChannel.permissions_for
discord.abc.GuildChannel.permissions_for
this?
It will check for a permission or a role
3rd one might interest you
Let me see
Those return the permissions that the user has
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
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:
...
I'm not sure what that if is doing, but I want to check if check_perms is in member_perms
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
member_perms >= check_perm this is that part
i added the if as an example to use it
Will this work on guild permissions as well?
it should
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.
not directly. you can run a task everyday and check if today's date is the 1st. if it is not, return. else do the stuff
i think that would be the closest you can get
Okay, thx <3
How do I create a channel when clicking on a button? trying to make a ticketing system
Current code
the same like a command
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))```
but with interaction
never opened created a channel with a command lol
remove the "channel: discord.TextChannel"
do you know how to create a channel with a normal command?
thanks
.rtfm reaction
discord.Reaction
discord.Reaction.clear
discord.Reaction.count
discord.Reaction.emoji
discord.Reaction.is_custom_emoji
discord.Reaction.me
discord.Reaction.message
discord.Reaction.remove
discord.Reaction.users
discord.on_reaction_add
discord.on_reaction_clear
discord.on_reaction_remove
discord.InteractionMessage.add_reaction
discord.InteractionMessage.clear_reaction
discord.InteractionMessage.clear_reactions
discord.InteractionMessage.reactions
discord.InteractionMessage.remove_reaction
discord.on_raw_reaction_add
discord.on_raw_reaction_clear
discord.RawReactionClearEvent
How i can get user activities? When i fetch members from guild attribute activity is None
user or member?
member
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
I want to get members who playing now, what i need to do?
use the cache
guild.members
use utils.find
.rtfm utils.find
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)
?tag idw
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.
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
is this enough?
ok renaming solved it idk how ?? But this is solved
try commenting out the command, running the bot, uncommenting, and running the bot again.
I solved it by renaming the command, ty
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"
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
discord.online??
?
wtf is discord.online?
bros making that up as he goes along
.
i fixed it
Can you somehow edit an image with a task, without having the id of the message?
it wouldnt work as its got a "w"
wdym by that?
how are you planning on referencing the message then?
im not sure, that what i want to figure out
im not using a database, so im not sure how i would give the id
you should store the msg id in a cache or db if you want to access it later
you can use lists or dicts as a cache on some bot var
what are you trying to do by editing it? like where are you editing it?
in a task loop? inside a cmd? some event handler?
the task is inside a py file
i want to change the emped, depenting of a process is running
alright
The task checks it every 5min
and from where is this embed originally sent?
or is it a static msg? one that would stay constant throughout the life of the bot
ah ok
and how do you plan on making it unique?
but, there should be only one embed
👀
Uhm
ok no need for it to be unique then
coulnt i just use the newest one?
yea that works
im using buttons that i add_view
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
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
if you want to retain the id even after restarts, you would need a db
Well I'd input the user input (1w) to the task duration but it wouldn't work as it can't take a string right?
or am I doing this wrong
so you have a few options at hand
-
easiest and cleanest way to do it - use
time_strmodule which can be installed using pip https://pypi.org/project/time-str/ -
convert the stuff into timedelta or seconds yourself. has further options-
i) split the string at the last char. down side is you cant do stuff like1w 10d
ii) use regex patterns like(\d+)([wdhms])or similar
i suggest using 1
Ill look into one, thank you
👍
So would
converter = Converter('11 months 9days 1m 3 sec')``` convert to its number form? (this is from pypi page)
it would be used to convert to datetime.timedelta
👍
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
code
are you deferring at the first line of the cmd/callback ?
yes
async def my_name(self, ctx):
await ctx.defer()
asyncio.sleep(5)
await ctx.send_followup(str(ctx.author))
?tag blocking
No tag blocking found.
dont use time.sleep
use asyncio.sleep
we have fucked up tags
This is a list of Frequently Asked Questions regarding using Pycord and its extension modules. Feel free to suggest a new question or submit one via pull requests. Coroutines: Questions regarding c...
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()
you might be having insanely high latency. where do you host your bot?
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
this is my fear
that it can't even defer in the allotted 3seconds
that emphasises on the host latency issues too
right
try changing your host
I was hoping there'd be less dramatic steps before I'd need to try porting my bot
but I will look into it
I cant find the guide/docs for tasks, is it discord.ext.tasks
yeah
.rtfm tasks
discord.ext.tasks.Loop
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
discord.ext.tasks.Loop.minutes
discord.ext.tasks.Loop.next_iteration
discord.ext.tasks.Loop.remove_exception_type
discord.ext.tasks.Loop.restart
discord.ext.tasks.Loop.seconds
discord.ext.tasks.Loop.start
alr ty
👍
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
Where are you starting the loop?
Isnt that on tasks.loop? sorry i just tried following the docs
I think i mis understood it lol
or it starts when i run the cmd
go through the stuff, then click the button in the code above
huh
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
Oh how would i start it? I dont see it in the examples in docs.
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
I know, and i asked above for the docs on it then looked at what i found, and i do beleive mis under standing something is alright.
I didnt know self.printer.start was starting the task
well you would've known if you read what the method does 
I simpily asked for help, thats it.
And you got it
Yes, thank you.
And please use consistent and proper naming conventions, your code is incredibly hard to read
The names of functions, cmds ect?
yes
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
Alright
wtf are you trying to do
why are you trying to start a task from a function in another class?
Im just trying to start it from the button
Well thats what im struggling on, what am i doing wrong?
You need to learn how classes and class methods work in Python
and the basics of OOP
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)])```
You can not bypass the character limit
Ye that's why i was asking if there's tips to reduce lenght or smthg similar
Pretty sure there isn't a way other than renaming your emoji to something short
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
You can't control the user's clipboard through a bot lol
is there a way i can edit the options of the view outside of the class
If you mean attributes, yes
i mean the select menu options
And what's stopping you from doing it in the class?
i want the options to be based on a list of things i have and i cant rly do that in the class
You can subclass the select and pass the options to the init
oh oki ty
and is there a way to add multiple views (a select menu and a button) to a single message?
A view can contain multiple items
how do i add a button and a menu?
the same like the other stuff
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?
Has anyone made a makeshift datetime slash command option utility that takes in a string of some format and converts it to a datetime?
I know about that one, but I don't think it works for datetime.datetime
I might just make something myself
Read our guide. guide.pycord.dev
That would be funny 😂
use the repo as a sample-like thing then.
Its not possible to register commands in dm only right?
you are right
Shucks alright thanks 🙂
We can use emojis in option field?
Is it possible to have an @ Option() choice create new options when selected?
(before the slash command is submitted)
hey, how do i take boolean as discord.Option
Use bool as the type
Or
.rtfm slashcommandoptiontype.bool
That
You can accept a string and parse it. That's all that's possible
No. You can't have dynamic options
Wdym by use these two?
await interaction.response.send_message(embed=embed, view=SetWelcomeChannelView(), ephemeral=True)
await interaction.response.edit_message(view=self)
yep did that
i just put 2 descriptions by mistake
did not read the error correclty haha
.idw
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.
?tag xy
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.
.rtfm add_item
bro what is this
i uninstalled and re installed the discord.py but it didnt work
can anyone help me??
.install
- 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
Show pip list
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```
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?
when i try to print the error in on_command_error, it doesn't log the whole error. how can i fix that?
You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
how long will it take
i ran my bot for 18 hours
and i am getting this now
Then you're either spamming the API or using a free shitty host
oh i am using a free host
and that's why we don't use free hosts kids
oh
Well you can't. You need to subclass the select menu
You need to get the traceback
Got it. Thanks!
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
Catch the notfound error instead of checking if it returns None
fetch_ban is never gonna return None either way
Either pay for a server to host it on or host it on a machine at home, whatever suits you better
like this?
@unban.error
async def unbanerror(self, ctx, error):
#if isinstance(error, MissingPermissions):
#await ctx.respond(error, ephemeral=True)
elif isinstance(error, discord.NotFound):
await ctx.respond(error)
#else:
#await ctx.respond("Something went wrong...", ephemeral=True)
#raise error
yes, or just use a try catch
alright, I'll try a try catch, cause when doing this, it always responds with "something went wrong"
nvm fixed it
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
Can you show your code and the error
Generally you would use interaction.send_message()
That is likely your problem
obviously you can't use ephemeral in channel.send, who's the message going to be seen by? The channel?
Omg I didn’t think of that I’m dumb-
lol
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?
you can't
Why do you need it to be ephemeral?
Bc I’m using it for a config thing
and why can't you just send the new view as a response to whatever interaction you're doing to edit the other view?
This is how it works now
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
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)
does running an event handler in an asyncio create_task make it not block the bot no matter how long it might take
Idk
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?
try it and see
^
Seems to be like itd be worth trying so i will
but fr if ima waste my time please say 🤣
alr
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))```
for slash commands?
Yes
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
is it possible to get a user id from name and discriminator
If they're a server member yes
how would i go about doing that?
.rtfm Converter
discord.ext.commands.Converter
discord.ext.commands.Converter.convert
discord.ext.commands.UserConverter
discord.ext.commands.UserConverter.convert
discord.ext.commands.RoleConverter
discord.ext.commands.RoleConverter.convert
discord.ext.commands.GameConverter
discord.ext.commands.GameConverter.convert
discord.ext.commands.FlagConverter
discord.ext.commands.FlagConverter.convert
discord.ext.commands.FlagConverter.get_flags
discord.ext.commands.FlagConverter.parse_flags
discord.ext.commands.GuildConverter
discord.ext.commands.GuildConverter.convert
discord.ext.commands.EmojiConverter
discord.ext.commands.EmojiConverter.convert
discord.ext.commands.run_converters
discord.ext.commands.ObjectConverter
discord.ext.commands.ObjectConverter.convert
discord.ext.commands.MemberConverter
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
thank you so much this is exactly what i needed
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)```
Run the command again?
I aint that smart tbf so doubt ill think of something else 🤣
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
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
Event handler in asyncio.create_task ? Wdym by that?
If the code you execute inside a task is blocking, it would still be blocking
If you have code that's blocking you need to solve that, not try to work around it
There is a simple workaround if you really want to know, but it always always recommend to use async alternatives
threading maybe?
asyncio.to_thread
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)
yeah, but that should be a last resort. If there are async options, use them instead
pip list and send output.
Is this method better than what me and kastu we're talking about?
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\____>
topggpy requires discord.py which interferes with py-cord
is there a way i can get around that? it works on other machines with a similar list of installed libraries.
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
If dpy is not in pip list then doesn't that mean topggpy did not install dpy as a dependency?
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()```
that fixed it, thank you so much!
Well I'll have to read through that whole thing 
It's just that that msg was the first one discord showed me when i opened the channel, so i thought of replying, and forgot to check if someone had helped already
few things:
- name don't name message objects
ctx. - what is
update_leaderboard.
Why add the listener manually, When using the decorator already does it?
^
@silver moat the decorator adds the listener regardless of the event name right
you're also doing 2 SQL queries that could be done in one
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)```
Message has no method called respond
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
Ah okay yes I guess I was thinking too complicated somehow 🤦🏼♂️
self.update_leaderboard()```
Which parameter do I have to pass here for the ctx variable in update_leaderboard?
it's not a ctx
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?
Is there a method I should be calling that cancels this timeout?
view.stop()
Yeah even i tend to originally start over complicating stuff, only to realise that this isn't necessary at all lmao
For the parameters part,
Ctx would rather be a Message
You don't seem to use any attributes ctx has that message doesnt
Thank you kindly. Any thoughts on keeping a button disabled while the callback is running? Do I have to explicitly disable it before calling defer? I'm surprised this doesn't show a "Bot is thinking" message like it does for slash command deferrment.
Discord considers a defer on the button as a full complete response. Meaning it is not necessary to send a follow-up message
.rtfm interactionresponse.defer
Set invisible to False
Okay already many thanks!
if self.leaderboard_message:
await self.leaderboard_message.edit(embed=embed)
```Why does this not work?
Although you have a send a follow-up message then
Does delete_original_response() count as a followup?
Hmm was self.leaderboard_message ever defined? Else it would continue to stay None or whatever the default value is
Pretty sure no. But that method won't work the way it earlier used to. I suggest you play around a bit and see
I wanted to write the message ID of the embed in here so that I then update the correct embed when editing or is this again an unnecessary thing that I have in mind?
You would need to either hardcode it or use a command to first set that variable and get things running
Or you would need a db to persist it after restarts
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()
Actually, deleting does seem to count. I don't get any further error messages.
Thats good
After disabling the items, you have to edit the message with the view again
that unfortunately disables it for everyone
That part is fine. The View is in an ephemeral anyway
ah thats good
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.
you will have to use interaction.message.edit
Unknown message
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.
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
"
This is what I was expecting to happen (found in Discord Devs), but it's like.... not.
Then I would just save the whole thing to my DB.
How can I then update the embed via the message ID?
it does the thing which it's supposed to do but still says failed how do i remove this?
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)
Why do you have an indent there?
(Posted on DDevs if anyone cares
#1066429467930661076 message )
Indent for the code after the if
if thats where you're talking about
You don't have an if there
and once again, learn to name your variables correctly
your code is impossible to read
Yeah im going to go through them all after i've got it sent and make them better, whats a better variable name as they seemed fine to me?
Use proper naming conventions instead of just doing random camel case and upper camel case
Alright
can anyone help :p
send code thanks
IfNone = await self.bot.wait_for("message",timeout=120)
if IfNone == "None":
GiveawayEmbed=discord.Embed(title=f"Giveaway for {PrizeInput.content}")
await ctx.send(embed=GiveawayEmbed)``` Still isnt responding
Python naming conventions are snake_case for variables. Also, since it's a message, you should probably denote it as such instead of referring to it by a type
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
.
Interactions require a response. use interaction.response.edit_respond instead
oo
AttributeError: 'InteractionResponse' object has no attribute 'edit_respond' 😅
I can spell, edit_response
Small typo, but make sure to read the docs, as well 🙂
https://docs.pycord.dev/en/stable/api/models.html#discord.Interaction.edit_original_response
Is it not possible for an if statment to be after a wait_for? because it works fine without the if.
btw it worked without ur thing i just had to defer it.
Probably because you still have a random indentation for no reason
For the 150th time, you need to learn basic Python before making a bot
Ayo, I've checked for that and there aint any, so yeah thats not why.
unless am blind now
Really? There aren't any weird indentations at all?
Alright, well first be nice, thats litearly discord showing it not my code.
Well take a screenshot or something then if you can't show your actual code in Discord
Er, I seem to recall folks mentioning not to send screenshots because it makes it harder to read 🙂
Yeah, but he supposedly can't send his code so what other option is there?
Either way, it's not super hard to get the code to look correct in Discord
gist or some other text dump? (Just answering the question, I have no skin in the game)
Mabye it just happens when i copy and paste it from vsc
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```
best way would be to use partial messageable objects
partial_channel = bot.get_partial_messageable(channel_id)
partial_message = partial_channel.get_partial_message(message_id)
message = await partial_message.edit(...)
this uses the least number of api calls and also returns the full message
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
yeah that doesnt happen
not equals is extremely basic Python
its interaction.response.edit_message right
that's deprecated?
no thats the other one
interaction.edit_original_message got deprecated in favour of interaction.edit_original_response
💀
I tried
return NoReqs.content == 'None' and NoReqs.content != 'None'
await ctx.send()``` but that dosent work as await cant be there
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,))```
I do think of this stuff first smh
equals None and does not equal None?
and why are you trying to do ctx.send there?
Cause if != "None", it sends a message saying it needs to be None or none (but none not added yet)
honestly we should have smth that abstracts away all this weird stuff of interaction.message.edit vs interaction.response.edit_messagee vs interaction.edit_original_response
i have no idea whom to ask but can we have this?
Okay? But your comparison is literally never going to be True. And aren't you just making a check function?
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)
Yeah, but i need it to check for two things. (If its the right response, and if it isnt)
That is not at all how you do that
151th time: Learn Python before making a bot
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.
Well, how do i do that its one issue im having.
Pretty easy if you know basic Python
151_st_ ;P
yeah i dont like that either. hoping discord adds it is the only way ||or asking @waxen whale to pitch it to the discord devs||
I'm happy to exploit @waxen whale for the greater good.
(I'm totally getting banned once she wakes up)
Hey, I know basic python, i tried what i thought i was supposed to do and nicley asked for help and this is my response? nicee
How many times have you been told to learn Python in here? You keep coming back and getting the same response, does that not tell you something?
lemme take a look
lul
missing the from:
well there is a few things
ctx.respond would return the Interaction
so you would have to do await interaction.original_response() to get the message object.
you would also need to store the channel id along with the msg id
then using the exact lines i showed you inside the if messageid: block would work

Uh, this isn't so much a coding error as it is a low-level logic error. It is nonsensical for a string to be both a literal 'None' AND not a literal 'None' (which is wholly separate from the type None, btw)
So if i change it from None to something else itd work?
I have no idea, I don't know what you're actually testing; you left out a ton of context.
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)```, Just need to check if the response ISNT None
- 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.
In my code the return is just below The C in check
Then you have an issue with mismatched spaces and tabs. Indentation should be spaces, specifically to mitigate this issue.
wym on the 2nd bit
so my check= in wait_for will always return String None?
IfNone = await self.bot.wait_for("message",timeout=120,check=Check)
wtf
I actually don't know what wait_for does. I know it's a real thing, but I've never used it.
First time i've gotten user input in pycord, so if its wrong thats likley
You’ve summoned the demon
It basically just halts the execution of the method until the specified event occurs and then continues
HORRAY. We need Button .defer() to keep the Button inactive 😄
wait_for returns an object and other args just as an event listener would have. its pretty cool. kind of like an one time event listener
Yep you’re right with that and it won’t be changed afaik
Here's the wait for event example.
Okay I'm lost and just do not know more 😄
so whats wrong with it?
i just used the docs
Interesting. Seems like a narrow use case, because wouldn't it just catch and return the very first message sent in the entire server?
wait are you naming a variable called IfNone 
nah its temp
i just couldnt think of a name lmao
yes but you can implement checks
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
Anything else wrong or just name?
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.
Like components in Modals? 👀
nah other stuff looks good. i didnt read it completely
Nope not that sadly
(╯°□°)╯︵ ┻━┻
Can’t tell you more than „it’ll be cool stuff“
I hope it will be like... check/state-boxes, e.g. 'Yes/No', 'On/Off'
Better 
WHAT'S BETTER THAN ON/OFF, LALA?!
Anyways cough
Okay, go back to sleep. Thanks for answering me 🙂
Alright, so mind helping me figure out what to do? (checking if the user input isnt None, or i think mby i shouild change it to smth else)
Will do
indentation looks wrong
👀 👀
datetime? but that was a slash cmd option and not a component 
Haven’t heard anything about that one but I poked Ian about updating the roadmap.
hmm cool
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()```
@proud mason
ctx.respond would return the Interaction
interaction = await ctx.respond(...)
also, i think you dont have channel_id defined
Something went wrong.
Nobody helps you? See #help-rules §2, then you know why.
Where? Look in the screenshot i sent
yea its correct
So?
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,)) ```
Well what's wrong
any errors? use a debugger ||or some print statements|| to see till where the code is being run
I have fixed the problem thanks for your help!!!
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):```
You can pass args to the start method
What does that mean?
I don't have a ctx argument in the on_ready method that I can pass? 🙄
how to download py cord
.install
pip install py-cord
?tag install
- 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
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
.rtfm interaction.original_response
Nope
.rtfm interaction.edit_original_response
You can also do that. It is 1 less api call
No tag git found.
What python version are you using?
Try running python3 -m ensurepip
Oh it's 3.11
.rtfm interaction.edit_original_response
#883236900171816970 🙂
That was just bc I couldn’t press button thingy in time :c
Yes
It say this
Oh. You can click on the link tho
You seem to have multiple python installations
python3 seems to be 3.10 while py -3 seems to be 3.11
Yeah yeah i mean that. Click on the blue name to open docs link
Is there a way for me to pass an argument into a view class
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
Yes. Subclass the view and override init
Ok
Say this now
Fixed it
I disable my virus protection
ah ok
.-.
How can I then start the loop in the on_ready method? 😬
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)
what stuff from ctx do you need?
specifically all cogs
I've got as far as reloading one
.rtfm reload
.rtfm is_owner
@spring hull ^
ctx.respond and ctx.guild.id
you cant respond if you dont receive an interaction
you can send a message in the channel tho
store the channel id and guild id in a db. or hardcode them
Iterate over them
bot.extensions has all the currently loaded extensions
its a check
just add that @commands.is_owner() after the command decorator
where's that?
do you use cogs or no?
yes, that's why i want to make a command to reload them
oh lmao im dumb 
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.
so your commands should be looking like this?
@commands.command()
async def hi(self, ctx):
...
if you want to persist variables even after restarts, you need to store it in a db
slash cmd?
Can I just save the ctx to the db?
i gtg brb in like 20 mins idk. Keep typing and i'll see it when i get back
aah ok
no no. I'm making a command in main.py (only one in there) that allows me to hot reload on discord
every other command is in cogs
so a /reload command
well not really possible. you can still use the check but it will be visible to others. they wont be able to use it
you can have the reload cmd as a prefix cmd
why would you do that? i just told you that you need to save the channel id and guild id in the db
ok ok
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
I use the slashcommand, store Guild ID, Channel ID and Message ID in the DB and just pass the 3 parameters to the function and then instead of using ctx.respond just use a send_message?
yes. that is correct. Although im not sure if you need message id, but thats upto your code
also, interactions only live for 15 mins. post that, you cant use ctx.respond. so you would need to send a normal message anyways, using channel.send
Idc about them seeing it
I'll just have a check to make sure it's me, atleast I will when discord register the slash commands
yeah so you can add the check. if someone else tries to use the cmd, the check will fail and they wont be able to use it
are you overriding the on_connect event? that causes the slash cmds to not sync
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()```
?
i don't mind that
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.
Don't you need to call sync_commands to reload slash commands?
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
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)```
you might be taking more than 3 seconds to respond
defer the interaction in the first line of the cmd
But then I can not be sure that the action was performed correctly?
Defer it
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)
I keep getting this error when reloading cogs
anyone know if there is something i can use like active_developer to flag if the user has that badge?
.rtfm Converter
discord.ext.commands.Converter
discord.ext.commands.Converter.convert
discord.ext.commands.UserConverter
discord.ext.commands.UserConverter.convert
discord.ext.commands.RoleConverter
discord.ext.commands.RoleConverter.convert
discord.ext.commands.GameConverter
discord.ext.commands.GameConverter.convert
discord.ext.commands.FlagConverter
discord.ext.commands.FlagConverter.convert
discord.ext.commands.FlagConverter.get_flags
discord.ext.commands.FlagConverter.parse_flags
discord.ext.commands.GuildConverter
discord.ext.commands.GuildConverter.convert
discord.ext.commands.EmojiConverter
discord.ext.commands.EmojiConverter.convert
discord.ext.commands.run_converters
discord.ext.commands.ObjectConverter
discord.ext.commands.ObjectConverter.convert
discord.ext.commands.MemberConverter
Any ideas?
Can you pls stay in one channel?
ok... i just thought that it my post may have been lost
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```
what are you doing? you cant have select menus inside a modal
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
try passing it as a positional argument
also, you might not be accepting it in your modal subclass init
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)
ah, so accept title in your init and pass it to super init
def __init__(self, title): ?
mhm
can i use the discord.slash_command decorator in a Cog?
Traceback?
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
it was
how do I defer an interaction with a Context object
like ctx.defer() in upstream discord.py
have you tried ctx.defer()?
can I use tasks to end a giveaway after specific time? and how?
depends how do you start the giveaway
and by tasks do you mean discord.ext.tasks.loop ?
.rtfm guild_only
why can't you just click copy ID on an emoji 
Oh, I figured it out. for search posterity: here's how you get an emoji code https://i.gyazo.com/e63ad666175791840c93186dbb9f600c.mp4
this was a joke lmao. Hopefully someone gets it
😄 ty
yep lmao
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!

- commands.Bot for prefix and second show your pip list
I know why I named the file discord.py
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.
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
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
What
You subclass a View and then self.add_item(AnItem()) on the jnit
shit, I meant to say Response >.<
discord.ui.View is not a decorator
Anyway to create Models I think they are called
Like pop ups that you can have fields entered with a submit btn?
Here's the modal dialogs example.
@knotty surge
Can I register a view as permanent if it requires custom parameters to initialize an instance of it?
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?
Persistent views are only based on their custom id. If your working can work with that and ignore parameters then sure
why are my ` not formatting
should read as d6, d7
the same formatting works fine in a field value
just not in a description
You could store custom id along with parameters you would have passed in a db
Then in the callback, keep parameters optional. check if custom id in db, if yes, use the data store, else, use parameters passed
hmm. I think I get what you're saying. thanks om.
how to kick and ban a member with pycord
.rtfm member.kick
.rtfm member.ban
Although it's not recommended to make commands that replicate built in discord functionality
You parse the it to a hexadecimal int and pass it to the Color class
thanks it worked
Because discord snowflakes are too large to be passed as an integer. Use a string
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
it can if it has permission to use external emojis
why not just use the role input type 
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
bot has administrator permission but it send just :name:
Instead of using PartialEmoji you can just send <:name:id> in the string
And the bot needs to actually be in a server with the emoji of course
oh that's it , thanks!! 😂
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")```
use autocomplete
Here's the slash autocomplete example.
you cant dynamically set option choices without that
Explain what you're trying to do and explain what's wrong instead of just sending code next time
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..

Please do
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
- Use English to code. You save the library some pain.
- Use cogs.
Here's the slash cog groups example.
Ок
Thx
I will try
@full basin Thanks!!! It helped.
is there a way to make a paginator interactable for everyone, not just the person who called it?
author check
missed that
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
?tag codeblock
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.")
Any errors?
none
Anyone have "select menu" docs link? (not guide)
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)
.rtfm select_menu
Target not found, try again and make sure to check your spelling.
discord.ui.select
discord.ui.Select
discord.ui.Select.add_option
discord.ui.Select.append_option
discord.ui.Select.callback
discord.ui.Select.channel_types
discord.ui.Select.custom_id
discord.ui.Select.disabled
discord.ui.Select.from_component
discord.ui.Select.is_dispatchable
discord.ui.Select.is_persistent
discord.ui.Select.max_values
discord.ui.Select.min_values
discord.ui.Select.options
discord.ui.Select.placeholder
discord.ui.Select.refresh_component
discord.ui.Select.refresh_state
discord.ui.Select.row
discord.ui.Select.to_component_dict
discord.ui.Select.type
Thank you
Can messages with embeds be ephemeral (only shown to the user who requested the slash command)?
yeah why not
.tias
how do i set the link on a link button
do you know why it doesn't work though?
@livid monolith btw dm if you want a code i had written for this
cant know just based on the code. run a debugger ||or add a few print statements|| to see till where code is running
it could be related to the fact that you use after.guild which can be None
use before.guild
ctx.reply returns the message. store a reference to that message
you can then use the edit method on it
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'edit'
ctx.reply returns the message. store a reference to that message
eg-
msg = await ctx.reply(...)
await msg.edit(...)
no worries
just do ctx.edit()
;3
hmmm
seems like they tried that but didnt work
.rtfm context.edit
only works for slash cmds 
I will try it
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?
ok, it doesnt work xd
what returns none?
full error ?
No error
it will return None if the bot cannot find it
you are accepting a str
Yeah cause int wouldnt work for channel ID's
convert to int
alr
Change it to accepting int or get str then convert it to a int
2nd one
👍
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)
lmao rip 💀
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 :)))
@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?
did you read what @proud mason was writing?
convert chatid to int. not Chat

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?
How can I make it in Autocomplete that when I enter a letter, only hits with the corresponding first letter are displayed? 🙂
Is the list for Autocomplete limited to 25 entries?
no
only choices is limited to 25
same for menus
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
I have a list with 100 entries but only 25 of them are displayed 🙄
We won't help you make a feature that's against ToS
yes, because discord is only displaying 25. If you write a letter discord will show the other ones
thats how autocomplete works
What do you mean?
Discord obviously won't display all 100 autocomplete options at the same time
^
did you never used autocomplete?
even the IDE´s doing autocomplete
What is the best way to trade it if I have a maximum number of options of 54 by filtering?
Can I somehow filter this down further with initial letters or similar?
Here's the slash autocomplete example.
Is it possible to make a command only visible to one user?
Like through the bot
Not with the integration thingy
no


