#Basic Pycord Help (Quick Questions Only)
1 messages · Page 4 of 1
no errors
so what's the output?
for this
I ran it no errors
testing code from:
#1002289194544136323
so if someone knows how I can get await custom_id and the user id in the "main loop". I would be thankful
the callback into another function is not a solution 4 me

ok, but you really need to name your variables/parameters better
I recommend you subclassing view and adding the buttons with the corresponding callbacks
Why not?
because I automatically generate everything based from lists afterwards to corresponding buttons also in a list with NPC data -> there is a minimum chain of 100 possibilities
it will get very messy
if its not in the main loop
I really need to await it in the main loop
you could use partials to generate button objects each with different values in the callback
@bot.command()
async def button(ctx):
await ctx.send(
"Hello, World!",
components = [
Button(label = "WOW button!", custom_id = "button1")
]
)
interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")
await interaction.send(content = "Button clicked!")
discord_components
had something like this
but it doesn't work anymore
that's what I need, but it doesn't work for me anymore
I spent 3 days of losing hair
those buttons need to be wrapped in a View object and that sent with the message using view kwarg
you can simply provide a list of components as args when initializing a View object and theyll automatically be added to the view with no further action
the buttons work, the response doesn't
interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")
await interaction.send(content = "Button clicked!")
this doesnt work anymore
those should be set as the button's callback attribute
that also eliminates the need for a custom id for each button
is there somewhere a code example?
simply define an async function that takes one argument interaction and set that as the callback attribute for the given component
async def create_message_with_button(msg, embed):
view=View()
thisbutton = Button(label="button", style=discord.ButtonStyle.secondary, custom_id='mybutton1')
thisbutton.callback=on_interaction
async def on_interaction(interaction: discord.Interaction):
await interaction.response.send_message(f"Button: {interaction.data['custom_id']}\npressed by: {interaction.user}")
@bot.command()
async def hello(msg):
embed=discord.Embed(title="**Welcome!**", description="**Press this button to recieve a DM**?", color=0xfbe8d2)
await create_message_with_button(msg, embed)
yep
are you using a third party package to pycord?
because its incompatible
there are no errors, the code works
as I said, the problem is, I need to await the button click in the main loop
or get the custom_id and user id as a return value from a function directly to the main loop
yeah no i cant help you with that
i was under the impression that the issue was something else
if you installed dpy after installing pycord then you're running dpy
since it'll just overwrite the files
wdym the main loop
I uninstalled discord, and blaseted pycord over it, didn't change anything
Are you using slash commands?
@lofty falcon Maybe instead of using 3 libraries you could just use Pycord and then we can help you better, since we’re not going to help you the best when you’re not using our library components.
async def hello(msg):
embed=discord.Embed(title="**Welcome!**", description="**Press this button to recieve a DM**?", color=0xfbe8d2)
await create_message_with_button(msg, embed)
#await For button click here, or await the return value from a function with custom_id from the button and user id
this doesn't work because button_click isn't a real event
I just have pycord installed now
K
You can just do it inside of the button callback
yeah... idk why you're so reluctant to just use the callback
that's the best way to handle it
Just use the same callback for all the buttons
^ and decide the outcome based on custom_id
if you really want you could use wait_for("interaction") but it isn't the best practice
that would be pure gore
I am sorry, but I rather leave it at emoji reactions, which is way slower
just use guard clausing if you dont want the mess of alot of indents?
I will do it the ugly and hard way.
Json database for every user...
with counters
yuk
i would suggest against that
and instead learning a sql or nosql database solution
if you mean using .json files that is
How?
again if you want to emulate reaction_add then you can use interaction, but im struggling to understand what you're trying to do that would make using callbacks impossible/harder than coding it all inside the command
because I want to migrate my code
then migrate it and optimize later
not have to code 150000 lines just to emulate the same functionality in a callback ...
im sorry but it's hard to help you if we don't actually know your end goal, outside of generic advice like using wait_for
Man wants to migrate but doesn't want to write new code. He just wants the old code work his way with pycord views
Which is literally impossible
exactly, I wrote code that codes itself, 60 lines, but if I have to use the callbacks, it ends up in tons of code lines and pure code gore
which solution didn't offer callbacks ?
right here
wait_for but you listen for interaction instead
you mean this?
One single callback can probably get the job done in 30-40 lines
again button_click isn't a real event, which is why im suggesting interaction
maybe it's a dpy thing? idk but it ain't here
hmm
By the way, do SlashCommandGroups with guild_ids set refresh every time the bot is run?
doesn't everything refresh on run by default
Yeah well it just stopped doing that for some reason
Alright finally it refreshed the commands
By the way are guilds fully loaded in from self.bot.guilds?
they should be yes
So does it have the same data as if I had fetched it using fetch_guild, except maybe a bit outdated depending on when the bot was started?
fetch_guild returns way less data
well not way less, but https://docs.pycord.dev/en/master/api.html#discord.Client.fetch_guild
Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.
you do get an approximate member count but nothing specific
So self.bot.guilds is refreshed every time a new guild is joined or removed as well, right?
yes, the cache is always updated
Ok thanks
allgood
this looks.... doable
I will just make for each user a session with their user id, return the btn_id and listen for the interaction
well yeah that's what we've been telling you the whole time
and then we told you wait_for("interaction")... this is exactly what you found
wait_for(on_interaction)
leave out the on_
interaction is the event name
on_x means that that function is called when (or on) the event is triggered
What do you have against using a callback?
By the way, is guild.owner not stored by self.bot.guilds?
i believe that is something you need the members intent for
Yeah I have it
Because my already existing algorithm with self coding function wouldn't work in a callback, therefore it would end up in coding gore
it should be, but if not you should at least have guild.owner_id?
im pretty sure it would if you just used custom_ids for your buttons but 
hmmm for some reason it just doensn't have the guild owner when i fetch it as well
the test bots only in 3 guilds and I'm the owner of all of them
oh it won't if you fetch it
Even when I don't, it doesn't work
that's pretty odd, it should be fine on that scale
huh it worked this time
When I put a print statement for the guild.owner right before accessing the name attr
wait no, fetching should give you owner_id but not owner
because guild.owner just checks guild.members for owner_id but it doesn't have .members when fetched
havefun
Now I will just optimize it
Found the issue, I was running the command before on_ready had triggered
ahh rip
async def btn_pressed(msg):
answered = False
while (answered == False):
try:
myinteraction = await bot.wait_for('interaction', check=lambda i: i.user == msg.author and i.channel == msg.channel, timeout=180)
except asyncio.TimeoutError:
await msg.delete()
return
else:
answered = True
return myinteraction.data['custom_id']

if someone needs it, await for button click with custom_id as return value from the button
exactly what I needed
idk if this is possible but how do you pass the context of a message that has a button into a function im bad at explaining
class buttons(discord.ui.View):
def __init__(self, x):
super().__init__()
self.x = x
@discord.ui.button(label="a", style=discord.ButtonStyle.grey)
async def callback(self, button, interaction):
await function(interaction.context, x) # <----```
github copilot said interaction.context but it does not exist
and just interaction says AttributeError: 'Interaction' object has no attribute 'author'
access interaction.user for the user that instigated the interaction
function is just another command but idk how to do the ctx part
i cant do interaction.user bc its ctx.author in the actual function
context is not an attribute of Interaction
so if i wanted it to redo the command by pressing a button how would i give ctx?
you dont
class buttons(discord.ui.View):
def __init__(self, x, context):
super().__init__()
self.x = x
self.context = context
@discord.ui.button(label="a", style=discord.ButtonStyle.grey)
async def callback(self, button, interaction):
await function(context, x) # <----``` i just did this idk if its bad but it works
i said it works lmfao
misread that
it's not bad, thats how you pass it correctly
Anyone know why my commands are taking a while to sync even though I am using debug_guilds
Is there a way to avoid system messages for pins, or is the only way to manage those by watching on_message for a message.type of pins_add?
(Kinda sucks cuz I'm doing it in a Thread, and if I delete the message, it will show "No recent messages" in the thread highlights instead of the actual important bit, the message itself)
Unfortunately not, the only way to delete them is the way you mentioned.
I'm using PyMongo and I got this error:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/commands/core.py", line 358, in invoke
await injected(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}```
code:
post = {'_id' : 0, 'user' : ctx.author, 'uses' : +1}
collection.insert_one(post)```
your connection string is probably incorrect
plus pymongo is blocking use motor instead
how to get user description?
i dont think there is a way for that 
I was trying to get user description from banned user
and how to give reason such that it shows in that list
Hey everyone, sorry, probably a v dumb question so asking here; I want to send a message without an interaction, but have it ephemeral & in a specific channel; now with the recent discord API changes in not sure how to achieve this ¿
I try to tie it to a specific channel (server related bot), checked permissions, but I didn't figure out how to get it to be ephemeral whilst without a user interaction ; I tried tying it to a user id variable sadly no succes
can i get the reason why you want to send it as emphemeral?
It's as a status update , related to the user if they enabled it. Then it's in a specific channel on a server where the bot is in, and only for users whom enabled it of course. I want users to chose whether its a normal or emphemeral message and that's also stored already
That might work, but due to everything kinda being in that one channel and server related I'd imagine people like to keep it there
But thanks anyways 🌻 👍
Is it possible for a bot to join a group chat?
nope
ok
how do I ignore these when I override run method
Ty :)
class DmMes:
def mute_dm(reason, mod, days, hours, minutes, seconds):
embed = discord.Embed(
title=":mute: Вы были заглушины",
description="Вы были заглушины на сервере **HFD**",
color=discord.Colour.from_rgb(56, 27, 161)
)
embed.add_field(name="Причина", value=f"`{reason}`")
embed.add_field(name="Модератор", value=f"`{mod}`")
embed.add_field(name="Время", value=f"`{days}д. {hours}ч. {minutes}м. {seconds}cек.`")
def ban_dm(reason, mod):
embed = discord.Embed(
title=":hammer: Вы были заблокированны",
description="Вы были заблокированны на сервере **HFD**",
color=discord.Colour.from_rgb(56, 27, 161)
)
embed.add_field(name="Причина", value=f"`{reason}`")
embed.add_field(name="Модератор", value=f"`{mod}`")
def warn_dm(reason, mod):
embed = discord.Embed(
title=":exclamation: Вы получили предупреждение",
description="Вы получили предупреждение на сервере **HFD**",
color=discord.Colour.from_rgb(56, 27, 161)
)
embed.add_field(name="Причина", value=f"`{reason}`")
embed.add_field(name="Модератор", value=f"`{mod}`")```
i want to send this message to user
What i need to return?
learn python
bot = discord.Client(intents=discord.Intents.all())
bot = commands.Bot(intents=discord.Intents.all(),command_prefix="!")
how did you import discord
which module do you use
anyways, just look at my example
intents = discord.Intents.all() should work if you have everything installed right
windows or mac ?
which library do you use
did you install the dependencies ?
with pip
how to send a paginator in bridge command? i got this error TypeError: expected Interaction or BridgeContext, not <class 'discord.commands.context.ApplicationContext'>
it is discord.ext.commands.Bot
you can add this statement at the top of the file 👇
from discord.ext import commands and then you can use commands.Bot
What's the limit of webhooks
is there any way to get hex_code as user input?
i think you will need to create a role for muted user and assign that to user
can you hep me on this?
yeah timeouts handle muting for you, pretty cool feature
yes
Just read the docs here
Yeah that works, though you don't need to purge
If you respond as ephemeral=True then it'll be silent
Allgood
Oh wait
Duration
Id explain but I can't rn, you need to use datetime.timedelta; just read the docs, it explains there
how can i make a reaction listener persistent
think you misread a bit, that's the method timeout_for uses. duration should be a datetime.timedelta object https://docs.python.org/3/library/datetime.html#datetime.timedelta
an example would be py from datetime import timedelta ... await member.timeout_for(timedelta(days=1, hours=12)) which would timeout the member for 1 day and 12 hours
the docs i linked just there shows you other things you can pass in to customize it
it would convert it
ok
Only days, seconds and microseconds are stored internally. Arguments are converted to those units:
A millisecond is converted to 1000 microseconds.
A minute is converted to 60 seconds.
An hour is converted to 3600 seconds.
A week is converted to 7 days.
ok thanks 🙂
if you want your duration argument to be in minutes then yeah that works
just make sure you import it
i was thinking to convert time to seconds, so user could input like 7d or 2.5h or 1.3w
either way works; in my case, i just made tons of arguments which are all optional
i just read the docs 
timeout uses a datetime.datetime object to specify an exact time
but for easier usage, you should use timeout_for with datetime.timedelta
though discord's planning on adding a datepicker option for slash commands so timeout may become more convenient
all my commands work most of the time but at random times it just decides to do this
even tho it works 5 seconds earlier
anyone has the code for a delete button which deletes the bot message
its very simple to make
Learn all about implementing buttons in your Discord Bot using Pycord.
when you send the message with the bot
botmsg = await msg.channel.send("This MSG is from the bot")
await botmsg.message.delete()
you need to store the information from the message you send out in a variable, so you can later access the stuff
you can pass over the botmsg to the button callback
you can also use a simpler form
in the callback the interaction variable has every information you need
view=View()
thisbutton = Button(label="Delete Me", row=1, style=discord.ButtonStyle.secondary, custom_id="DelBTN")
thisbutton.callback=on_interaction
async def on_interaction(interaction: discord.Interaction):
await interaction.delete_original_message()
I'm modelling my bot as subclass of discord.Bot
How do I register a slash command in the cog and in the subclass of discord.Bot(my actual Bot class)?
The decorator @discord.Bot.slash_command needs a self argument, and that makes sense, since the examples on docs showed the actual bot instance being used, I've tried that as well, which works.
But I want to have the commands in my subclass/cogs, do I use @discord.slash_command? I've tried that, it doesn't get registered as a slash command in the end.
class MyBot(discord.Bot):
@discord.slash_command(name='ping', description='Latency', guild_ids[x])
async def ping(self,ctx):
await ctx.respond(f'Pong! Latency is {self.latency}')
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/listeners.py", line 60, in on_message
await ip_embed(ctx)
File "/home/container/backend.py", line 181, in ip_embed
await ctx.reply(embed=ipembed, view=DeleteButton(ctx))
File "/home/container/.local/lib/python3.10/site-packages/discord/message.py", line 1639, in reply
return await self.channel.send(content, reference=self, **kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1467, in send
raise InvalidArgument(f"view parameter must be View not {view.__class__!r}")
discord.errors.InvalidArgument: view parameter must be View not <class 'backend.DeleteButton'>
what does this mean?
Quick question: how do you get the content of a deleted message(it's for logging)?
on_message_delete shows messages deleted that are in your cache and on_raw_message_delete shows messages deleted regardless of your cache
b!rtfm pyc on_messgae_delete
No results found when searching for on_messgae_delete in pyc
b!rtfm pyc on_message_delete
I can spell
so I should use on_raw_message_delete instead of on_message_delete?
is there an example to the delete button code in the bot?
Summary slash command decorator in subclassed bot doesn't work Reproduction Steps Try to implement a subclassed bot with a slash command as described here in the documentation https://guide...
code
Thank you, I have largely solved my problem on my end, will still take a look though.
class DeleteButton:
def __init__(self, ctx):
super().__init__()
self.value = None
self.ctx = ctx
@discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
async def button_callback(self, button, interaction):
button.disabled = True # set button.disabled to True to disable the button
button.label = "Deleted" # change the button's label to something else
await self.ctx.delete_original_message()
await interaction.response.edit_message(view=self) # edit the message's view
await ctx.respond(embed=ipembed, view=DeleteButton(ctx))
DeleteButton doesn't subclass discord.ui.View
you're not subclassing discord.ui.View
OH
also
how do i delete the bots message?/
which one lol
the one on which the button is
like the bot replies with a message and that message has the delete button
interaction.response.delete_original_measage()?
yes
ah thanks
async def add(self, ctx, du: discord.Option(discord.Member, description="The user you want to select"):
...
Hey! Right now the parameter inside of the slash command is required. How would I make it just a normal option that isn't required?
required = False, default = something
inside of the discord.Option
What is default?
default is what it is if the user skipped it
class DeleteButton(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
async def button_callback(self, button, interaction):
interaction.response.delete_original_measage()
TypeError: View.to_components() missing 1 required positional argument: 'self'
Ah for me it would be None then.
full traceback thanks
Like this?
du: discord.Option(discord.Member, description="The user you want to select",required=False, default=None)
yes
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/listeners.py", line 60, in on_message
await ip_embed(ctx)
File "/home/container/backend.py", line 181, in ip_embed
await ctx.reply(embed=ipembed, view=DeleteButton)
File "/home/container/.local/lib/python3.10/site-packages/discord/message.py", line 1639, in reply
return await self.channel.send(content, reference=self, **kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1469, in send
components = view.to_components()
TypeError: View.to_components() missing 1 required positional argument: 'self'```
if it doesn't update, comment out the command, run the bot, uncomment out command, and run the bot
this should force discord to update
Was about to ask 😆
Also could be the reason, that it didn't work before
DeleteButton is a class, you need to create a DeleteButton object with DeleteButton()
Oh
Perfect it worked
np
Ignoring exception in view <DeleteButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Delete' emoji=None row=None>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 375, in _scheduled_task
await item.callback(interaction)
File "/home/container/backend.py", line 458, in button_callback
interaction.response.delete_original_message()
AttributeError: 'InteractionResponse' object has no attribute 'delete_original_message'
in ```py
class DeleteButton(discord.ui.View):
def init(self):
super().init()
self.value = None
@discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
async def button_callback(self, button, interaction):
interaction.response.delete_original_message()
this one
so you can pass in ctx and use await self.ctx.message.delete()
lemmetry
this gives message has no attribute message, and self.ctx.delete() gives
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 375, in _scheduled_task
await item.callback(interaction)
File "/home/container/backend.py", line 458, in button_callback
await self.ctx.delete()
File "/home/container/.local/lib/python3.10/site-packages/discord/message.py", line 1204, in delete
await del_func
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 356, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
oh you're using on_message, not an actual prefixed command
await interaction.delete_original_message()
try that, not response
that's a shorthand for interaction.message.delete()
and interaction.message is the message that was responded with
yep
wait i may have a solution, is there a way to add a view after sending a message?
editing it
i could do
msg = await ctx.send("e")
await msg.edit("e", view=view)
and then could i use msg.delete() within the button?
I still don't understand your name convensions
Is it possible to get a role in a slash comamnd choice?
discord.Role
if I want to get a certain role in the choices, how would I get that role?
404 again doing
msg = await ctx.respond(embed=ipembed)
wait msg.edit(embed=ipembed, view=DeleteButton(msg))
class DeleteButton(discord.ui.View):
def __init__(self, msg):
super().__init__()
self.msg = msg
@discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
async def button_callback(self, button, interaction):
await self.msg.delete()
so make a list with those roles
wait i have existing code for something like this
ctx.respond responds with an interaction
oh wait i think i messed something up
choices = []
for i in roles:
choices.append(discord.OptionChoice(i.capitalize().strip(), value=i.strip().lower()))
so you get either get roles from getting all roles of the server. or u want specific roles?
here
is my custom functions
Option(discord.Role, "Please choose a role", choices = ["Role 1", "Role 2"], required = True)
this is what I have
uhh discord.Role should give all of the roles in that server
okay it doesn't work like this
wait ill show you
he wants specific i think
what if I only wanted 2 roles in the server?
wait ill show u
ok
then just take a str
and then put the roles in the choices and convert them to roles internally
yeah Ive done that before but was wondering if there was an easier way
role: discord.Option(choices=
[
discord.OptionChoice("role1", value="roleid"),
discord.OptionChoice("rol2", value="role_id2"),
]),
here, make value the role id
and you can get the role object
It really is the same either way, you still need to do it internally
i mean for specific roles this works
also, fixed the delete button issue
class DeleteButton(discord.ui.View):
def __init__(self, message):
super().__init__()
self.message = message
@discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
async def button_callback(self, button, interaction):
await self.message.delete()
and the actual message code
message= await ctx.reply(embed=ipembed)
await message.edit(embed=ipembed, view=DeleteButton(message))
what is ctx
Is this in a command or on_message
on_message
then please name your variables to what they actually are
if it's a message name it message. if it s a context name it ctx
kk
When I click my button I get this:
<main.messageTest object at 0x0000014F21494A30>
I think I need to define something like __init__ but im not sure how as what I have tried is not working.
show code thanks
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
async def login_help2(ctx, user:discord.Member, *, message=None):
message = "message"
embed = discord.Embed(title=message)
embed.title = "title."
embed.description = "des"
embed.color = 0x11806a
await user.send(embed=embed)
await ctx.respond(content="content", embed=None, ephemeral=True)
class MyTest(discord.ui.View):
@discord.ui.button(label="Button 1", style=discord.ButtonStyle.primary)
async def first_button_callback(self, button, interaction):
await interaction.response.send_message(messageTest())
@discord.ui.button(label="Button 2", style=discord.ButtonStyle.primary)
async def second_button_callback(self, button, interaction):
await interaction.response.send_message("Done")
@client.slash_command() # Create a slash command
async def button(ctx):
await ctx.respond("Click mee", view=MyTest())```
done, made it message
what is messageTest?
my question too
because you are using super() and not supering anything
and it doesn't remotely make sense
you are missing __init_ in class MyTest
messageTest is the embed that gets sent in the userDM (top of the code)
I didnt mean to add that, my bad
def __init__(self):
super().__init__()```
@sleek arch
I mean you are sending a class. So what did you want to happen?
he's sending MyTest() and not subclassing discord.ui.VIew
Why i can not use bot in select menu? when i use bot in parms from selcet menu then come this error..
Ignoring exception in command test:
Traceback (most recent call last):
File "", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "", line 63, in test
await ctx.send(f"Test", view=ticket_select())
TypeError: ticket_select.__init__() missing 1 required positional argument: 'bot'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "", line 344, in invoke
await ctx.command.invoke(ctx)
File "", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: ticket_select.__init__() missing 1 required positional argument: 'bot'
class ticket_select(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
technically they doesn't need to because they're no overriding the __init__
the code which has view=ticket_select() is missing bot
ohh
i know
it's supposed to be view=ticket_select(bot)
Okay all I am trying to do is make a button send a user the DM. I have probably done this really wrong
yeah you did
oh yeah i have this forget haha thanks ❤️
so you can send message with await interaction.response.send_message() and sending a DM with await user.send() where user is a either a discord.User or a discord.Member
Would I not need the async def login_help2(ctx, user:discord.Member, *, message=None):
how does that even begin to make sense
I mean it works
It does if I put the message in a separate slash command, so not with a button
Do you even know Object Oriented Programming in the slightest?
why does button and interaction have to be there when the IDEs saying they aren't used? without them the button breaks
Do you want to treat me with any respect?, sorry I just thought this was a place people were supposed to help not insult
yeah and pycord is supposed to help people who actually know python
because py-cord passes the button and interaction when it receives a callback
ah, got it
lmao I actually learnt all the python I know today while making a singular discord bot in the span of 2 months, and somehow didn't ask any question too dumb and get called out for not knowing Py here
AttributeError: 'NoneType' object has no attribute 'create_text_channel' huh? 
line of code please
create_ticket = await guild.create_text_channel(f"{interaction.user.name}", category=kategorie)
what's guild
and where's guild from
guild = self.bot.get_channel(guild_id)
guild_id = 934909638514704474
well, so you get_ tries to find the guild in your bot's cache.
you can turn on guild caching with the guilds intent
guild intent whats that and how turn on ?
on the dev portal
but this is on?
all intent
no this one is a non-priveleged intent
oh
?tag intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Mhh but i have all intent on ?
intents=discord.Intents.all()
you have intents = discord.Intents.all()?
ah this is working lul thanks
np
bump
How do I get the voice of an author from a bridgeCommand?
should just be ctx.author.voice
there is still a rate limit with debug_guilds
are you restarting your bot a lot?
Not loads, but that could be the issue
thats what ive always had do it for me
Any idea what the ratelimit for command registration is?
twice per minute i think?
its been a while but that sounds right
They haven't appeared all day
role in user.roles
eyo why user.banner dont work even if I got a banner ?
do you have the right intents?
my testing bot got discord.Intents.all()
same for user.premium_since
you can only get banner from bot.fetch_user, it doesn't appear in cache
and premium_since is only available for member objects
okay thx
What's the ApplicationContext version of ext.Context.command_failed?
discord.errors.ExtensionFailed: Extension 'cogs.set' raised an error: AttributeError: 'SlashCommand' object has no attribute 'command'
I mean the error is kinda self explanatory
You're probably doing @discord.slash_command.command()
i still get the same error when i do this
Are you sure it's the same line
is there any way to give user list of permission he can edit in a channel or category in bridge command?
Do your bot need special permission to use the button on the paginator in a channel ?
I cant change pages
code?
I fixed it by making it ephemeral=True
ok
I have two folders in which I have cogs. I have this code to load the cogs from both the folders
for file in os.listdir("./cogs"):
if file.endswith(".py"):
bot.load_extension(f"cogs.{file[:-3]}")
for file in os.listdir("./cogs2"):
if file.endswith(".py"):
bot.load_extension(f"cogs2.{file[:-3]}")
For some reason, only the cogs from cogs2 , and 1 cog from cogs is being loaded. I ensured that the cogs I'm looking to load are in the proper folder. Also, I tried moving the cogs from cogs folder, which are not loading, to cogs2, but they're still not loading. I've have proper setup function in every single file.
I also tried to manually add the cog with bot.load_extension("cogs.<filename>") for every cog which is not loading, but it also didn't work.
try adding continue behind it
What do you mean behind it?
after bot.load_extension
didn't make any difference
where do you load the cogs? like before bot.run or smth
yes. b4 bot.run.
I'm using MongoDB with pymongo in the cogs which are not loading. Can that be the issue?
try adding try and except block and make it raise the error...
prob not
How do you do that?
I thought if there was any error, it will be raised by itself
for file in os.listdir("./cogs"):
if file.endswith(".py"):
try:
bot.load_extension(f"cogs.{file[:-3]}")
except:
raise```
and see if any error is raised
weird
ig I'll just try to import the subclasses Cog and use bot.add_cog() in the main file
https://mystb.in/ could you send the code of where you load the cogs? remember to hide your token
wait
How do I share it?
How to get the url of the code which I pasted. never used it b4
did you write the setup function in every cog correctly?
def setup(bot):
bot.add_cog(Class(bot))
This is how the setup function is, right?
yes
Then yes, I've written them correctly
could you send an image of both of the cog's directory?
if file.endswith(".py"):
bot.load_extension(f"cogs.{file[:-3]}")
print(file)``` do this on both of the loops and send the output
ohk wait
The lines saying loaded <cog> are because I had the line print("loaded {}".format(__name__)) in __init__ of every cog
that means all cog is loaded correctly without errors
well, there is no message of loaded <cog> for snipe.py, esnipe.py, rsnipe.py and snipe_slash.py, and the commands which are from those cogs are also not working
you tried loading it manually but it isn't working as well right?
before you start loading cogs2 did them work?
Well, everything was working b4 I add the snipe_slash.py file, though there was no change in any other file
could you send your code in the file https://mystb.in/
it could be the problem then
wait
Well, I removed that file from that directory, but the other files still didn't load
since when the problem is there?
try revert all the changes and see if it works
Just a few hours ago.
ohk wait
if you needa delete any files, make sure to backup them
and might as well as big changes on a file
nvm. Figured out. It was because of a a import I was doing. As soon as I commented that line, the cog loaded
there we go
I did
from ..utils import *
it was the line which was causing the issue. How else can I import the functions from it?
just from utils import *
you dont need the double dot
ohh ok. thanks
is there anyway to to have grouping in bridge command?
Is there a way to check how long a user is in a vc or do I have to do stuff like take the time where he joined and compare it to the time where he left?
for now you have to compare the time where he joined and left.. idk if there are any other packages that may help
I did
Works, just wanted to ask if there was an easier way something like member.voice.time
nope there isn't
https://paste.pythondiscord.com/zirepolani - error
https://paste.pythondiscord.com/ezakisiyij - error coming from line 8 and 16
in select menu i use py await interaction.followup.send(f"you work in Greggs and earn **{number1}** :key:" )
But i've got this errorpy discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
How can i fix it?
Do you use that await interaction.response.send_message("") already?
i need to edit select menu
disable it

can i see your code ?
class Dropdown(discord.ui.Select):
def __init__(self, bot):
self.bot = (
bot
)
options = [
discord.SelectOption(label="Work in Greggs", emoji="👩🍳", ),
discord.SelectOption(label="Bake cupcakes", emoji="🧁"),
discord.SelectOption(label="Wash car", emoji="🚓"),
discord.SelectOption(label="Sell book", emoji="📕"),
]
super().__init__(
placeholder="Choose work",
min_values=1,
max_values=1,
options=options
)
async def callback(self, interaction: discord.Interaction):
user = interaction.user.id
number = random.randint(500, 1000)
number1 = random.randint(1000, 1500)
self.disabled=True
if self.values[0] == 'Work in Greggs':
await interaction.followup.send(
f"you work in Greggs and earn **{number1}** :key:"
)
b.add_bal(self=b, user=user, amt=number1)
self.disabled = True
await interaction.response.edit_message(view=self)
elif self.values[0] == 'Sell book':
await interaction.response.send_message(
f"you sell book and earn **{number}** :key:"
)
b.add_bal(self=b, user=user, amt=number)
await interaction.message.delete(delay=0.5, reason='Work complete')
```
class Dropdown(discord.ui.Select):
def __init__(self, bot):
self.bot = (
bot
)
options = [
discord.SelectOption(label="Work in Greggs", emoji="👩🍳", ),
discord.SelectOption(label="Bake cupcakes", emoji="🧁"),
discord.SelectOption(label="Wash car", emoji="🚓"),
discord.SelectOption(label="Sell book", emoji="📕"),
]
super().__init__(
placeholder="Choose work",
min_values=1,
max_values=1,
options=options
)
async def callback(self, interaction: discord.Interaction):
user = interaction.user.id
number = random.randint(500, 1000)
number1 = random.randint(1000, 1500)
self.disabled=True
if self.values[0] == 'Work in Greggs':
await interaction.response.send_message(
f"you work in Greggs and earn **{number1}** :key:"
)
b.add_bal(self=b, user=user, amt=number1)
self.disabled = True
await interaction.response.edit_message(view=self)
elif self.values[0] == 'Sell book':
await interaction.followup.send(
f"you sell book and earn **{number}** :key:"
)
b.add_bal(self=b, user=user, amt=number)
await interaction.message.delete(delay=0.5, reason='Work complete')
try this
i think we can't response twice
yea
we can't
ops sry haha
try the new edit code
but we still response it
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
But your error is there or not? the interaction can not find the webhook i think because of followup your first option.
But you can wait for someone else 
How can I add a member to a private text channel while creating a channel.... ik i have to use overwrites.... but can figure it out
please help ;-;
Is there any way to read the role id of the person who entered the slash command?
is it possible to execute a loop every 2 days?
AttributeError: 'ReplayButton' object has no attribute 'to_components'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 358, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 127, in wrapped
ret = await coro(arg)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 1171, in _invoke
await command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 358, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ReplayButton' object has no attribute 'to_components'
class ReplayButton(discord.ui.Button):
def __init__(self, ctx, video_url):
super().__init__()
self.ctx = ctx
self.url = video_url
self.client = client
@discord.ui.button(label="Re-Play", style=discord.ButtonStyle.gray)
async def button_callback(self, button, interaction): # Don't remove the two unused variables
await self.client.cogs.get('Music').play_video(self.ctx, self.url)
https://docs.pycord.dev/en/master/ext/pages/index.html#discord.ext.pages.Paginator.on_timeout
than you can change the timeout of the pagnater
anyone?
ctx.author.roles gets you a list of roles the user has. I think it is sorted so that the highest role they have is first in the list but it might be the other way around. Once you get the item in the list you want you can use item.id
You are tying to create a button in a button
i don't get it- how do i fix that
if ctx.author.roles(ctx.author.id) == 94358459264
is ok?
you don't need to put anything inside the bracket
and no idt it'll work
I think you might be looking to make it a view. So instead of sub classing a button you can subclass a view discord.ui.View
maybe if 94358459264 in ctx.author.roles
OHH
almost
you want to check if a user has a role?
yes
how does this even make sense, if it's roles it's plural, multiple roles. So it has to be a list. And you cant use == on a list and string. That get method is wrong too
You need to loop through the list of roles that you get from ctx.author.roles and in the for loop you can check if role.id == 123
Does that makes sense?
ok thanks. is there any way to group slash comands?
I want to run a command for a user with specific privileges.
discord.Permissions().manage_nicknames and discord.Permissions().manage_roles both give me that it's False even though i've enabled those permissions in the developer portal and readded the bot with the correct permissions. Checking the bots permissions in the 'Roles' tab inside the server shows that it has these permissions
so only a user with that role can run the slash_command?
yes
I suggest you use discords built in setting for that.
And when you say?
server settings > integrations > "your bot" > click on the command you want to limit > set everyone to "X" and add the role you want to yes.
discord.Permissions is not the permissions for your bot. You are creating a Permissions object that would normally be used for something like Member.set_perms(my_perms) you need to get your bots permissions using this to get the Member version of your bot for that guild
https://docs.pycord.dev/en/master/api.html#discord.Guild.me
and than get the permissions like this
https://docs.pycord.dev/en/master/api.html#discord.Member.guild_permissions
Thanks alot!
, why is the if query not working?
@discord.ui.button(label="test", emoji="📌", style=discord.ButtonStyle.green)
async def test_callback(self, button, interaction):
role = interaction.guild.get_role(rolle)
if role in interaction.user:
await interaction.response.send_message(f"Rechte")
else:
await interaction.response.send_message(f"Du hast keine Rechte.")
TypeError: argument of type 'Member' is not iterable..
interaction.user.roles
Ups thanks
I've given my bot the manage messages permission, put it's role on the highest place possible. But it still can't remove reactions of the lowest role.
Only when I give the bot Admin can it do it
hello im created a ticket system with select menu but isn't work it
class Ticket(discord.ui.View):
@discord.ui.select( # the decorator that lets you specify the properties of the select menu
placeholder = "for open ticket click me", # the placeholder text that will be displayed if nothing is selected
min_values = 1, # the minimum number of values that must be selected by the users
max_values = 1, # the maxmimum number of values that can be selected by the users
options = [ # the list of options from which users can choose, a required field
discord.SelectOption(
label="buy in store",
emoji=":shop:",
description="for a simple buy click me"
),
discord.SelectOption(
label="q before buy",
emoji=":1095roleiconsupportteam:",
description="for say your question click me"
),
discord.SelectOption(
label="درخواست همکاری",
emoji=":2853612e94fd237b37de09de4ad62a57:",
description="for send partner message click me"
),
discord.SelectOption(
label="ss",
emoji=":alert~1:",
description="ssss"
),
discord.SelectOption(
label="other",
emoji=":2952checkmh:",
description="fjdsjdjsd"
)
]
)
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
await interaction.response.send_message(f"creating ticket: {select.values[0]}",ephemeral=True)
categ=discord.utils.get(self.guild.categories,name="Opened Ticket") # selecting the category(by its name)
r1=self.guild.get_role(993493250893693022)
overwrite={
self.guild.default_role:discord.PermissionOverwrite(read_messages=False),
self.me:discord.PermissionOverwrite(read_messages=True),
self.author:discord.PermissionOverwrite(read_messages=True),
r1:discord.PermissionOverwrite(read_messages=True)
}
channel=await categ.create_text_channel(name=f"{self.author.name}-{self.author.discriminator}",overwrites=overwrite,topic=f"{self.author.id}") # creating the channel/ticket
em=discord.Embed(title="your ticket is created",description=f"Ticket created by {self.author.mention}",timestamp=datetime.utcnow(),color=discord.Color.random())
await asyncio.sleep(3)
await interaction.response.send_message(f"{channel.mention} if you want go to ticket click me",ephemeral=True)
await channel.send(embed=em)
@client.slash_command()
async def ticket(ctx):
embed=discord.Embed(title=":haraketli_: Create a New Ticket :haraketli_:", description=":3817hammermh: Click on the appropriate option to contact us!", color = discord.Color.blurple())
embed.set_image(url = "https://cdn.discordapp.com/attachments/993493251690594384/998517377316687892/fortnite-battle-royale-1920x1080-864336699.jpg")
await ctx.send(embed=embed, view=Ticket())
await ctx.respond("done!", ephemeral=True)
do you know what is the problem
?
maybe create a separate thread for this because it's a bigger problem
ok thank you
I'm trying to remove the reaction of an user who has the lowest role, I've placed my bots' role as the highest. Yet when I use remove_reaction I get a missing permissions error. My bot has the manage messages and view messages permission. And when I give the bot Admin it runs just fine
Is the bots riles overridden in that specific channel?
Now it is, and it works. Thanks!
How can I make my bot send errors
why is this happening while grouping command
class Test(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
super().__init__()
self.bot = bot
@commands.group(name="group")
async def _group(self, ctx: commands.Context):
await ctx.reply("in group")
@_group.command(name="command")
async def _command(self, ctx: commands.Context):
await ctx.send("in command")```
code
When creating the group with @commands.group, you need to set invoke_without_command to False so that it doesn’t call both callbacks.
So @commands.group(name="group", invoke_without_command=False)
ok thanks
Is it possible for me to give channels under a specific category as options?
Could you explain what you want to happen?
I am making a ticket module... i want staff member to be able to only add any user to channels listed under Ticket Category
b!rtfm pyc member
b!rtfm pyc member author
No results found when searching for member author in pyc
b!rtfm pyc member interaction
No results found when searching for member interaction in pyc
Is there a helper method of some sort that would return the lowest role that has a certain permission (e.g. View) in a channel?
I don't know that channel.changed_roles (this doesn't even seem to be what I would expect) or channel.overwrites tell the full story.
Edit: Ended up just iterating channel.permissions_for(role) for all roles in the server. Probably better than just trying to get the lowest role (since roles are linear in theory but not always in practice)
can someone give me a guide on how to make pages on embeds?
?tag guide
thanks
So I'm trying to use on_raw_message_delete and I know to get it to work you'll need payload and put payload. somewhere in front of code too iirc, but idk where, could someone tell me how to get it to work?
What's the code to know who used the slash command (author)
ctx.user or ctx.author
Why does it not work
how do I make a time limit for a bot.wait_for() response?
timeout=float
use the self if you are in a cog
thanks
Tnx
If my bot can't remove reactions, and has the highest role. Also has permission to manage messages, see them and the history. Has access to the channel. What permissions am I still missing? Because the code still gives a missing permissions error.
@commands.command(description="Sends a list of the bot's commands.")
async def help(self, ctx):
embed = discord.Embed(title=f"Cries | Help",
description=f"Testing", colour=col)
await ctx.respond(embed=embed)```
Would this automatically create a slash command?
If I define debug_guilds in commands.Bot?
I've reinvited the bot with applications.commands
yes
but where is the slash_command?
you use a prefix command at the moment
from discord.command import slash_command
Why did it ping 😭
@slash_command()
.
\o
Can I make a bot delete all the webhooks of a channel?
How can I disable one single button? by custom_ID?
Also I press the button, It completes the function
But says this how can I stop that?
respond to the interaction
Hey is there a way to detect if the message sent in a channel is a media (pic or vid) or is it a text
message.attachments[0].url.endswith('mp4'):```
I've used this
what about the pic
png and all that crap?
list = ['mp4', 'jpeg']
if message.attachments[0].url.endswith in list:
You could just make a list and put those in
true true
Etc .png .svg
thx mate
Idk if there is a straight up way
Then if just a message
if not message.attachments
Yeah you get the jist
Np
@ me if you need anymore help w it
@delicate jolt why dont i just check if the message is a text or a number and just go based on that
cant i do that?
Not sure
basically what i wanna do is
If anything except a vid or a pic is sent to a channel it gets deleted
yeah ik but would that be instant?
Yeah
bet
Am I able to disable the view after say 5 seconds if no interaction
Yeah, set timeout=5
Add an interaction_check to the view
and in that, check if the interaction.user.id == ctx.author.id, and if it does, return true
otherwise, return false after giving an error message so that it doesn't say the Application didn't respond
Epic cheers
You're welcome
Is there a way to disable the button?
Like grey it out when timed out?
So It can't be clicked
def check(m):
return m.channel == ctx.channel
message = await bot.wait_for('message', check=check)```
How to get the ID of the user who originally ran the slash command?
Like after pressing the buttons
If I pressed Right I want to get the original person who ran the help slash command
yeah but i want him to wait for a specific channel
Then compare the channel IDs in the check.
Set disabled=True for the button
and then edit the message with the updated view with the updated button
why...
is the callback in a class? if so self needs to be the first argument
nop
hold my sc doest not load
i added ctx.interaction rn
just to see if it works
remove the () when setting the callback. you dont want to call the function you want to reference it.
buttonleft.callback = button_callback
other wise you would be calling the function instead of just getting its "name" to call later
understood
How many discord servers can a bot own?
https://discord.com/developers/docs/resources/guild#create-guild
This says it can only create guilds if in less than 10 servers. Im not sure if that applies to ownership transfers.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Okay
I'm looking to store a user's ID and their CSID (given manually using this vetting command), but I seem to have an issue relating to a KeyError or something.
csids[str(user.id)]["CSID"] = csid
KeyError: '706324825181913128'```
For clarification, 706324825181913128 is someone's ID.
issue solved btw
could someone help me understand what this error is?
from .voice_client import VoiceClient, VoiceProtocol
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\voice_client.py", line 55, in <module>
from .gateway import *
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\gateway.py", line 37, in <module>
import aiohttp
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\__init__.py", line 6, in <module>
from .client import (
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\client.py", line 35, in <module>
from . import hdrs, http, payload
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\http.py", line 7, in <module>
from .http_parser import (
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\http_parser.py", line 15, in <module>
from .helpers import NO_EXTENSIONS, BaseTimerContext
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\helpers.py", line 667, in <module>
class CeilTimeout(async_timeout.timeout):
TypeError: function() argument 'code' must be code, not str```
For context, im trying to use the Spotipy library with my bot
hey
any one knows how to delete messages of a specific member? with that:
await channel.purge(limit=2)```
Yes but I think you should make an if query of the player so that only their messages are deleted.
and how?
is there any way to invoke a command by bot? for example if bot joins a new guild i want him to run a intro command
like that?
member = discord.Member
channel = ctx.channel
def get_purge_member(m):
return member == member
embed = discord.Embed(title='Clear ▼',
description=f"{ctx.author.mention} has cleared **{amount}** messages of {member.name}!",
color=0xdc143c)
deleted = await channel.purge(limit=amount, check=get_purge_member())
await ctx.send(embed=embed)
await asyncio.sleep(3)```
check=get_purge_member
@commands.command()
async def clear(self, ctx, amount: int, member: discord.Member = None):
if member == None:
channel = ctx.channel
embed = discord.Embed(
title="Clear ▼",
description=f"{ctx.author.mention} has cleared **{amount}** messages!",
color=0xDC143C,
)
await channel.purge(limit=amount)
await ctx.send(embed=embed)
await asyncio.sleep(3)
await channel.purge(limit=2)
else:
channel = ctx.channel
def get_purge_member(message):
return message.author == member
embed = discord.Embed(
title="Clear ▼",
description=f"{ctx.author.mention} has cleared **{amount}** messages of {member.name}!",
color=0xDC143C,
)
await channel.purge(limit=amount, check=get_purge_member)
await ctx.send(embed=embed)
await asyncio.sleep(3)```
works thanks!
how do I make the buttons work after restarting?
class JoinButton(discord.ui.Button):
def __init__(self, bot):
"""."""
super().__init__(
label=".",
style=discord.ButtonStyle.green,
custom_id="join",
emoji="👥",
)
self.bot = bot
async def callback(self, interaction: discord.Interaction):
pass
Is there a way to get user id from who ran the slash command?
Here's the persistent example.
^
ctx.author.id
Don't ask to ask :)
What is the problem? I'm no lawyer tho
Edited
@lost lodge I edited this
i have programmed a discord bot and a former friend has partially helped. He then received the code from me because I was on vacation and he wanted to do something. The problem is now that we have argued and he now threatens to publish the code. I have also offered him to delete his code places but he refused this offer.
Did your code have a license?
no
This basically says that sharing unlicensed code is not the agreement of it being open-source. So if you remove there code you would be able to have claims against it I belive.
That is the extent I can help tho.
thank you
can you say me how to write a licence
ctx can't be used in button functions?
Ignoring exception in view <HelpView timeout=10 children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='▶️' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 375, in _scheduled_task
await item.callback(interaction)
TypeError: right() missing 1 required positional argument: 'ctx'```
@discord.ui.button(emoji="▶️", style=discord.ButtonStyle.blurple, custom_id="help:right")
async def right(self, button: discord.ui.Button, interaction: discord.Interaction, ctx):
m = await interaction.channel.fetch_message(interaction.message.id)
embed = discord.Embed(title=f"Help", description=f"\nPick a category!", colour=col)
embed.set_footer(text="Page <2/2>",
icon_url="IMAGE_URL")
await m.edit(embed=embed, view=HelpView(ctx))
await interaction.response.send_message("")```
github has a page on it, also look it up, license are for open source though so you might not need one.
sorry i meant
interaction.user.id
I am trying to make it so
It brings up a help menu
by doing /help
But the person who ran /help is only able to use that menu
set ephemeral=True in the resonse
But
Im using buttons
and the bot can't edit the embed
When ephemeral is set to true
It should be able to. try using interaction.edit_original_message() instead of fetching the message and than editing it
Right okay I'll try that
How can I limit it to the original person who ran the slash command?
what do you mean? the buttons? if it is ephemeral only they will be able to see it
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
Ignoring exception in view <HelpView timeout=10 children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='◀️' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 375, in _scheduled_task
await item.callback(interaction)
File "C:\Users\tearx\Documents\GitHub\Cries-Bot\cogs\help.py", line 68, in left
await interaction.edit_original_message(embed=embed, view=HelpView())
File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\interactions.py", line 388, in edit_original_message
data = await adapter.edit_original_interaction_response(
File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\webhook\async_.py", line 211, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
When it's sent with ephemeral=True
can you show your code
Yes
for the whole help command (you can cut out parts with lots of text)
@discord.ui.button(emoji="◀️", style=discord.ButtonStyle.blurple, custom_id="help:left")
async def left(self, ctx, interaction: discord.Interaction):
embed = discord.Embed(title=f"Help", description=f"\nPick a category!", colour=col)
embed.set_footer(text="Page <1/2>",
icon_url="IMAGE LINK")
await interaction.edit_original_message(embed=embed, view=HelpView())```
@slash_command(description="See a list of commands available. For more detail type /help <name of a command>")
async def help(self, ctx):
embed = discord.Embed(title=f"Help", description=f"""
**[Help]()**
⤷ See a list of commands available.
For more detail type /help <name of a command>
**[Ping]()**
⤷ Displays bot latency.
""", colour=col)
embed.set_footer(text="Page <1/2>",
icon_url="IMAGE_LINK")
await ctx.respond(embed=embed, view=HelpView(), ephemeral=True)```
try adding interaction.response.defer() as the first line of your buton callback
Does discord strip whitespace from the end of a message?
alright
I believe so, i think start too.
there is a line above and below, yup, test got striped
interaction.response.defer()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in view <HelpView timeout=10 children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label=None emoji=<PartialEmoji animated=False name=':arrow_backward:' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 375, in _scheduled_task
await item.callback(interaction)
File "C:\Users\tearx\Documents\GitHub\Cries-Bot\cogs\help.py", line 69, in left
await interaction.edit_original_message(embed=embed, view=HelpView())
File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\interactions.py", line 388, in edit_original_message
data = await adapter.edit_original_interaction_response(
File "C:\Users\tearx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\webhook\async_.py", line 211, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
thanks
What does this actually do?
discord only gives 3 seconds to respond to an interaction, if you need more time they allow that command that bumps up the timeout time to 15 min
I see I see thanks
when the interaction timeout of discord side and you try to interact with it you get that error. is your ping high?
still not super high.
Say I have 8 pages
For my help menu
And Im on page 4 How could I check that?
Is there anything built in or would I need to store it
In a DB or something
like
Message_Id Page
ID HERE Page here
lots of the stuff you are making is built into the pagnater feture of pycord i would suggest cheking it out
Here's the paginator example.
ty
and there is a whole section of the docs
I see thanks
thanks its working, my initial problem was with the voice_state intent ^^
has anyone implemented a generic method for discerning attribute differences from event listeners' before and after objects?
really dont want to write a million if statements everywhere
yes. see TextChannel.create_webhook() and then use any trivial REST request module to do the HTTP POST to it
thats where the REST request module comes in
there are many. requests is popular
oh i see
look at the Webhook object's attributes
you want to access Webhook.url
i think that includes both the ID and the token
TextChannel.create_webhook() returns the Webhook which you can then use
no
doesnt look like __str__ is implemented
you need Webhook.url
yeah
documentation is ur friend
i just ctrl+f'd 'webhook' in the api reference lol
you did ctx.create_webhook rather than ctx.channel.create_webhook
and also you didnt catch the result in a variable
hook = await ctx.channel.create_webhook(name=name, avatar=avatar, reason=reason)
await ctx.respond(hook.url)
I am using a bridge command and have the problem that with the prefixed command it only takes the first word, f.e.: !play rick roll, will only take "rick" and doesn't do anything with the "roll". Is there anything I can add to the bridge command to fix this problem?
because spaces are perceived as separators for params
the command cannot have spaces in its name or give your command an argument to take
this is very silly to me
@commands.Cog.listener("on_guild_channel_update")
async def handle_channel_edit(
self,
before: GuildChannel,
after: GuildChannel
) -> None:
"""Updates the database with guild channel setting changes."""
if not before.guild:
return
delta = dict()
column_map = {
"category": "parent_channel",
"position": "position",
"name": "name",
"topic": "topic",
"nsfw": "age_gated",
"slowmode_delay": "slowmode_delay",
}
for attrib in dir(after):
if attrib not in column_map.keys():
continue
_before = getattr(before, attrib)
_after = getattr(after, attrib)
if _before != _after:
delta[column_map[attrib]] = _after
if len(delta) == 0:
return
q = "UPDATE guild_channel_settings AS settings SET "
v = dict(channel=after.id)
while len(delta) > 0:
pair = delta.popitem()
q += f"\"{pair[0]}\" = \%({pair[0]})s"
if len(delta) > 0:
q += ",\n"
v[pair[0]] = pair[1]
q += """
FROM guild_channels AS channels
WHERE
channels.id = settings.channel_ref
AND channel = %(channel)s;
"""
logger.debug(f"Query: {q}")
logger.debug(f"Bound args: {v}")
with self._bot.db.connection() as conn:
conn.execute(q, v)
i was looking at an ORM but i dont actually see a way to natively map arbitrary objects to database objects
ive never used an ORM before tho
Hi, just wanted to check, there's no official way to check for user connections (e.g. Reddit, YouTube, Twitch, etc.), right?
No there isn’t at the moment.
im trying to disable my buttons when the on_timeout function is activated, but the view timeout and the buttons are still enable (but ofc they dont respond to interaction)
can I have some advise?
you can use self.disable_all_items()
and on_timeout() does not have any arguments other than self
it does not disable
already removed that
is just that now
so to edit the message you'll have to pass the ctx
and do await ctx.message.edit(view=self)
tried with ctx.message.edit, self.ctx.message.edit, self.ctx.edit_message, but got nothing
only errors
what error are you getting?
argument errors and this one
this one i got from self.ctx.message.edit
ohh wait
when its a prefixed command and you get the context message, its the command being run
ctx.message would be !hello (or with whatever prefix you're using)
figured out
does it work?
no problem
Is it possible to resync commands in a cog? Have been trying but doesn't seem to work
Tried doing that but it doesn't resync slash commands
i think slash commands load automatically after an hour
if you added new slash commands try to kick and reinvite the bot in the server
Well kicking and reinviting isn't really ideal
Hello. Is there a way to disable all buttons on bot stop
basically there may be multiple buttons active when the bot is on, non persistent and timeout=None. Is there a way to disable them when we stop the bot (i dont expect them to un-disable when it comes online again)
If the bot dies, the buttons are just unusable
is a way to execute stuff when the bot is going to be killed
how do you even know that it’s going to be killed
you can store the msg data with the button in a database or a json and on relaunch grey they them out

ooo interesting idea, and example of that being implemented?
you can also store the msg data in a database and have another "bot" or script run in the background that notices if your bot dies and it restarts the bot to grey them out
it’s also likely both of them go offline at the same time unless using different hosts or something
I mean i restart my bot, it doesn't go offlien for long
It depends where it is hosted, my small home server runs for 3 years straight and not a single restart
also, disabling buttons on timeout, message doesn't exist?
well I update the code and restart the bot
you never declared self.message
In the docs it's not declared either
yep
try adding message as a parameter in the init function and pass it when calling the class (same way you did with voice)
like send the message first, save it as a variable and then edit it to include the view with the message passed into it
ah got it
wait is there a way to get the message through CTX?
i think ctx would just include the message of the person who sent the command
not too sure though
they mean the bot message I’m pretty sure
wouldn’t that just be the user’s message
botsmg = await msg.send("something")
and pass over the botmsg
yeah that’s what I said

my on_member_join suddenly stopped being called, I even shrunk it down to just print
@commands.Cog.listener()
async def on_member_join(self, member):
print(f"{member.display_name} joined")```
edit and delete aren't working either
it would appear the entire cog isn't being loaded
add store=False to the load_extension()
I had a syntax error in a view
is there a cooldown option for modals and/or buttons?
No there isn’t
how do i make one of thoes "custom" checks
like
@bot.command
@isverifed()
async def command(ctx):
You can use commands.check or write ur own decorator
With commands.check:
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
@bot.command()
@commands.check(check_if_it_is_me)
async def only_for_me(ctx):
await ctx.send('I know you!')
As a decorator:
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
@bot.command()
@is_me()
async def only_me(ctx):
await ctx.send('Only you!')
ooh nice
ty
you can get the components, but not the view itself
ok thx
b!rtfm pyc message.components
wasnt there a method in View to convert those components into a view?
aw. these <t:1659292760:R> dont work in footers?
b!rtfm pyc ui.View
View.from_message
Do webhooks have a rate limit?
when i try to get the link of the attachemnt the user sent this happens
print(str(ctx.attachments[0].url))
IndexError: list index out of range
you probably dont have message content intents, or the message has no attachments
it does i send a image and it sneds
then you don't have message content intents
everything in the api has a ratelimit



