#Basic Pycord Help (Quick Questions Only)
1 messages · Page 3 of 1
or this off
sometimes they can't
how to ask user for a list of channels from slash command input boxes
Here's the slash options example.
print("An error occurred with the kick command:" + e) This should print my text with the variable e right?
yes
if e is a string
e is my err
str(e) then
i have except Exception as e:
ok okay ty
would there be any reason at all for my slash commands to disappear right after I execute one them
Discord issue lol
seriously?
smh.
I knew Discord had a few hiccups recently but come on this is a joke
well try discord PTB or discord Canary
😂
I'll just wait till they fix their shit
(if they do, probably wont)
discord y2k 😭
Is there an update button?
Discord: switch to slash commands
Also Discord: Slash commands don't actually work btw
I've had that issue before, and it was caused by me running my development bot which had slash commands and my production bot which didn't at the same time
I fixed it by using a separate bot for development
honestly feels like this
I can't say I have the same setup
I just add code when I need to, its just my personal bot
Yeah so then it could be a Discord end issue like just a squid said
resetting the bot token fixed it
Huh
Are you sure you're not running the bot elsewhere as well?
Alright
Is there any problem if I put all @bot.event in a cog called Events?
for example
You should be using @commands.Cog.listener() in cogs
Yeah, since bot will not be defined within the cog
You're welcome
I just made the Events.py cog and now my other cog is acting strange, its executing a command twice, (the command does not exist in the other cog)
Do you have an on_message event anywhere?
You're welcome
Are global commands also available in the bots private chat or only in guild text channels?
They're available in dms too
Is it possible to disable them in dms?
As in not being seen no
You can make them guilf only
is there a way to generalize commands.CommandError handling?
Have you heard of elif
each error there is for a different command so I dont see where I would use elif
Add a global error handler?
thats what im asking, if this exists, like:
@commandError.error
async def commandError(self, ctx, error):
if isinstance(error, commands.CommanError):
await ctx.message.add_reaction("X")
required = True
if you already have that then comment out the command, run the bot, uncomment it, and run the bot

whats the ( * ) meaning on:
aysnc def command(ctx, *, arg)
```Nvm figured out
How do I get str to post the full string instead of one word?
that
@woeful spindle
oop ok ty
is there a way to cast a string arg and transform it in a discord.Member type?
what is the string
he does not give me nothing after the args print
i pinged myself
so you only want the 347498475031756802 part
yea
actually my last objective is get the id
i think im taking a hard way
i will just need the id so the thing is
im trying to catch the args but the guy can leave it none or just say a string that is not a ping cuz im doing a inventory search:
example:
Error: $inventory 213842 @ZaC#6588
Success: $inventory @Zac#6588 121030
Success: $inventory 129839184 (bc its going to read the ctx.author)
Success: $inventory
you can take a discord.Member object with type hinting to be discord.Member
it will take ID or name
or mention
how do I do this type hinting?
btw im using this to load the args
cuz i will use the split method
async def command(ctx, member : discord.Member =None, *arg2=None):
pass
remove the astricks
this will give me an error when i try to put the args after the ping
or dont ping
hold i will look for someway to extract only numbers from a string
then put another one
like this
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
still this
One message removed from a suspended account.
but I want to make optional the use of the args and the member mention like the example where the numbers and none make it succed
.
this one was not working either but I found something on stackoverflow about MemberConverter
I will try this one and i will tell
I couldn't find a documentation with the name banentry! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake
b!rtfm pyc BanEntry
because users is a BanEntry object
please name your variables according to what they actually are
BanEntry is not a list of users
Completely forgot, how do you edit a aplication response
@silver moat i got it working now, i spent some hours figuring out a way to catch it, now it catch mentions and ids:
id = ""
symbol = None
if arguments!=None:
arg=arguments.split()
if len(arg) > 2:
raise commands.CommandError
return
i=0
for args in arg:
if not args.isalpha():
for s in arg[i]:
if s.isnumeric(): id += s
else: id += ""
else:
symbol = arg[i]
if len(arg) == 2 and i==0: i=1
else: break
auth_id = id
if auth_id == "":
auth_id = str(ctx.author.id)
arguments are the (ctx, *, arguments)
General
question.
Say I have a dict:
votes = {
'For': 1,
'Against': 2,
'Abstain': 3
}
I'm using max(votes, key=votes.get) to give me the key associated with the largest value. But I want to exclude 'Abstain' votes from being considered.
I would've thought this would be a lambda function, e.g.
max(scores, key=lambda k, v: v if k != 'Abstain' else 0)
but I can only seem to get the dict keys out of the lambda, so it whines about v.
Is my only course of action filtering votes into a new dict, or is there some logic that I'm missing?
Edit: Ah-hah. Wasn't terribly far from the answer.
max(scores.items(), key=lambda x: x[1] if x[0] != 'Abstain' else 0)
INFO:discord.client:Cleaning up tasks.
INFO:discord.client:Cleaning up after 15 tasks.
Getting this after my bot does a long function. And the bot crashes all shards
idk if this can help you but i have a method that basically returns a value in the dict:
def timestamps(tempo):
options = {
1: "1h",
24: "24h",
7: "7d",
30: "30d",
60: "60d",
90: "90d"
}
return options.get(tempo, "?")
so basically timestamps(1) == "1h" and if its not in the dict it returns me "?"
in your case I would do like:
def score(x):
options = {
"For": 1,
"Against": 2,
}
return options.get(x, 0)
in other words it will return 0 if the x is not For and Against
how do I make a description for the args in a slash command
@commands.Cog.listener() takes an argument name, which is allegedly the event name.
Wouldn't @commands.Cog.listener('message') annotate any arbitrary method name to behave like on_message()?
Answering own question: The name argument has to be on_message 😬
hey
how can i get the guild and guild owner without intents
using a for loop
like for guild in bot.guilds: print(guild) print(owner)
idk how to print the owner tho
without intents
nvm
How can i give role to member, when member boost server
There is a server booster role built in tho
but i need to add another
then what you can do is, make an on_member_update event and if a member gets the default server booster role you can add another role or do whatever you want to do with it
await ctx.send(f'https://discord.com/channels/{ctx.guild.id}/{ctx.channel.id}')
you are welcome
How do you register slash command groups in cogs?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_cog_groups.py at master · Pycord-Development/pycord
Have tried that, the command still isn't registering 😓
so umm... what is the name of this
modal
oh ok, thx
so I'm working on this modal and I've run into a problem.
I want to use ctx.guild but cuz I'm in a callback for the modal, I can't use ctx. How to I work around this?
oh wait so interaction is the replacement of ctx
ok intresting, problem solved by myself i guess
How can I make my bot read what is sent to his dms
on_message event
yeah but how can I make him send what is sent to his dms to my dms ?
Or a channel
Get the channel and send the content?
Dms guild is None so you'd check If guild is none
Really late reply
but if you still don't have the solution, you can use interaction.followup.edit_message(), with the message ID of the response https://docs.pycord.dev/en/master/api.html#discord.Interaction.followup
is there any way tp give extra arguments in a discord.ui.view class?
something like that
class VeryCoolView(ui.View, title: str):
You should supply the args in the __init__ function
how would this look ?
def __init__(self, text: str):
self.text = text
like thaT ?
So something like this:
class MyView(discord.ui.View):
def __init__(self, title: str):
self.title = title
okay thanks man
You're welcome
class SelectMenuSelfRoleView(ui.View):
def __init__(self, optionsvar: list):
self.optionvar = optionsvar
@discord.ui.select(
placeholder="Rollen auswählen",
min_values=1,
options=self.optionvar,
)
why i am getting NameError: name 'optionvar' is not defined or with the self NameError: name 'self' is not defined error ?
The issue is that self isn't defined since the decorator is outside of the method
is there a workaround for this ?
I think you could subclass the select menu for that
Heres an example of it: https://github.com/Pycord-Development/pycord/blob/master/examples/views/dropdown.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/dropdown.py at master · Pycord-Development/pycord
i'll try this, thanks man
You're welcome
Is it possible to make an arg required in slash commands if a specific option is selected without having to do a manual check in the command callback? (Ping on reply)
hihi
yea so i came back to bot dev after long time and my bot is in like 75 or msth servers idk and no command is working, like the on_message thing works but no command
?tag message-content
As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.
You will need to enable the intent on the developer portal, as well as in your code:
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
As the popularity and number of Discord bots grow, it's important to keep our users and developers safe and healthy. This means from time to time, like any maturing platform, we need to update our ...
it can see on message things
like supposed @bot it responds but like command doesnt work
Will I be able to fetch a webhook that was created by another application or will it throw a 403 error?
as long as you can get that webhook's url
stil not working 👍
it says command not found what 💀
oh wai only the one in cogs doesnt work
is there some new way of cog
kinda of?
so how do you load your cog?
the one we used for discord.py normal wala
no, it works, it just doesn't raise an error by default like it used to
the actual loading part
ignore the not miya part i was testing smth 👍
it says command not found for the one in cogs
ok so they have this now:
bot.load_extensions("cogs", recursive = True)
ohhhh
this will load all the cogs in the /cogs directory
but cogs also don't raise errors. to fix this, add store = False
okok
lemme see iph this works first
are u srue its extensions"s" or just extension
I mean both exist
b!rtfm pyc bot.load_extensions
No results found when searching for bot.load_extensions in pyc
b!rtfm pyc bot.load_extension
extension then
- 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 !git to find out how to install git.
Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
2b
np
what is your file structure and send the code of that cog?
Send the entire cog
also add this to your cog loading
ok wait
Wait isn't it store=false
i didnt set it yet
yeah that
so no errors were raised?
Do you have an on_ready listener in the cog?
yes
Is it triggering?
wait no
Add it then and add a print function inside to check whether the cog is even being loaded
no no on ready
okay
error is leadrboard isnt foun d
now ill try to on ready wait
If it doesn't work, try updating to master branch.
pip install -U git+https://github.com/Pycord-Development/pycord
did this?
okie wait
Ooo that's handy, will change my code to this instead. (I know you weren't helping me, just 👀 the chat and boy, that cuts down my code which is handy, and stored=true looks useful)
it's store, not stored
btw
nope
- uhh might wanna edit your message then
How can I create a webhook using pycord is there a guide?
so did this work before py-cord?
yea
yeah there is. It's called docs
b!rtfm pyc Wehook
wait does the on_message work?
no idea
wait
nope
it isnt working
how annoying
so all the cogs work except this one, correct?
yes
Tnx alot i was looking for it everywhere
Has anyone got a solution to slash command groups though?
SlashCommandGroup isn't registering in my cog
sigh
I applied and got the message intent but can't actually deploy the moderation system I coded cos of this 😓
So, in summary, pycord version 2.0.0rc1 works better than 2.0.0
Alright goin' with that version for now then
Nevermind, the moderation system I coded doesn't work with the older versions of Pycord 😓
Am just gonna have to wait I guess
just don't use cogs
Uh
If all my commands were in my main.py file
It'd look like chaos
SCG?
also, isn't that already the case?
surely not all of your commands are groups, right?
well no I separate my commands into cogs
No no of course not
I did a lazy dev move by moving all my commands to Bridge
And bridge commands do work properly which is good
But I do plan on using Slash command groups a lot more, so for now I guess I'll just put it in my main.py file
i want to select multiple channels
You can add more optional options
btw can i send a select menu that has some pre-enabled option that were enabled before using same command, pressing those options again makes them unselected
is this released or not?
But can I make the bot create a webhook by himself
yes
1|rimuru | Traceback (most recent call last):
1|rimuru | File "/averycooldirectory/RIMURU/main.py", line 54, in <module>
1|rimuru | from pycord.discord.http import Route
1|rimuru | ModuleNotFoundError: No module named 'pycord'
Little problem here ^
I've made a bot with pycord and have another bot on the same ID (made in JDA) and both add slash commands, but only my slash commands are showing up. why is that? (they're both using server-id slash commands)
https://docs.pycord.dev/en/master/api.html#discord.ui.Select.add_option
(default parameter)
love you sir, you help alot, #squid for promo
because Pycord unregisters all the commands not in its code. also JDA may also do that.
maybe it can be fixed by sync commands
its just discord not pycord
Anyone know the problem here?
or you cant multihost slash commands?
If i add my commands as non server-id based will the JDA ones work too?

technically you can
Thanks for telling me
you just need the command itself (with options and all) and put pass in the callback
I'll give it a go
gl
otherwise i'll just make another bot account
how would i do that as pass isn't a corutine and making a function with it doesn't work
@slash_command()
async def thingy(ctx):
pass
ah, putting pass at the end
maybe some command that ignores the slash that are not in code, i am pretty sure i saw this somewhere in pycord while briefing through the source code
It's says that the create_webhook function is not defined
please show code ty
Me?
yes
Wait
async def create(ctx):
await create_webhook()

lol

create_webhook is a method of a discord.TextChannel object.
ooo okayyy
you can get a discord.TextChannel from ctx.channel
tnx it's solved
@silver moat its not appending the list, just printing the first element
idk why but my slash commands are not registering, I tried to put it in both discord.Bot(debug_guilds=[...]) and in cog commands
try downgrading version
i can see the whole list tho, len > 1
2.0.0b4 works?
omk lol i was not active since a long time
so what's the output?
what is ctx.guild.text_channels then
general```
lol
Tnx for help it works so good have a good day

wait you're saying it has all these elements and it just doesn't iterate?
yes
I don't see anything wrong with your code tbh
🤷♂️
idk, did you spell channel wrong?
hmmm now the cogs are throwing error while loading... 405 HTTPException
How are you still using Permissions v1
me?
no, nyu19
hmm, he might be inactive since a month
lol he dont even know anything
ishhh
Pretty sure it's been like half a year
💀 true
Yeah April 27th
so um, whats going on tbh. 
@commands.slash_command(name='info', guild_ids=[934026380092530708])
async def info(self, ctx):
options = []
for channel in ctx.guild.text_channels:
print(ctx.guild.text_channels)
print(channel.name)
options.append(discord.SelectOption(label=str(channel.name), value=channel.id))
view = View()
view.add_item(Control_OCR_Channels(options))
await ctx.respond(content='done', view=view)
idk try moving the print channel name below the options.append
wait value takes a string you gave an int
was trying to learn djs but the docs.. 💀 those are real crappy
ok so code freezes at append statement
probably ;p;
idk how anything works. I made a 3.3k line long dictionary earlier today
@tiny wagon so did you fix this?
hmm lemme try
ok fine lmao its working now
but why it didnt log any error in console
Because no one would be stupid enough to not read docs
i'want to make auto link delete, but on_message doesn't work
@discord.Cog.listener()
async def on_message(self, message):
bad_words = ["https://discord.gg", "http://disord.gg", "discord.gg"]
for word in bad_words:
if word in message.content:
await message.channel.purge(limit=1)```
and i've got message_content intent
there is message intent which makes you receive on_message events and message_content intent which makes you receive message content
I found what I was looking for “edit_original_message()”
show intents?
also check if cog loads or not
on_member_join work
I tried to delete every webhook after creating it using the method delete()
But it doesn't work
await message.delete() ?
and this thing doesn't work
but user can send not url, user can send text with link
Like this https:
yes, and like this "Hey! please join my server ||link||"
Why?
It should work
idk
Does it show any errors?
no
Put await message.delete() and try
i've used it already
Hm weird
I have a similar command and it works for me
Try reinviting the bot
ok
The same thing
Does the bot have permission to delete messages?
It will send an error if it doesn't have
nothing
What's your pycord version?
ok
hey how can i clear messages of a specific member?
Using on_message
and with await channel.purge()
Yes
It works for me
await message.delete()
Maybe something is wrong with your cog
Or maybe the bot doesn't have access to the channel
this thing doesn't work without cogs and bot has admin access
Is the cog being loaded?
Can someone help me with some permission issues? i have a bot that should kick member with a specific role, but it keeps telling me that it does not have permission to do that. i gave it all the permissions in the world and still says the same thing
The bot needs to have a role above that role
that is the case
are they the server owner?
the bot ? or who ?
yea
Send code of your cog
import discord
from discord.ui import *
from core import bd, ui
from loguru import logger
b = bd.HFD
logger.add("./main.log", rotation="500 MB")
bt = b.open(self=b)
class Bot(discord.Bot):
def __init__(self):
super().__init__(intents=discord.Intents.all(), status=discord.Status.idle, activity = discord.Activity(type=discord.ActivityType.playing, name = 'пальчики бекона'))
intents = discord.Intents.all()
intents.message_content = True
intents.messages = True
intents.dm_messages = True
intents.members = True
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(view=ui.PersistentView())
self.add_view(view=ui.RolesUs())
self.add_view(view=ui.RolesCst())
self.add_view(view=ui.RolesBot())
self.persistent_views_added = True
print(f"Logged cog as {self.user} (ID: {self.user.id})")
print("------")
bot = Bot()
cogs_list = [
'events',
'mod',
'warns',
'admin',
'ctm_roles',
'proles'
]
for cog in cogs_list:
bot.load_extension(f'cogs.{cog}')
bot.run('.GD')
#--------------------------------------------------------------#```
but on_member_join work
Send your cog
from datetime import timedelta
import discord
from loguru import logger
ban_link = ["https://discord.gg"]
class Events(discord.Cog):
def __init__(self, bot):
self.bot = bot
@discord.Cog.listener()
async def on_message(self, message):
bad_words = ["https://discord.gg", "http://disord.gg", "discord.gg"]
for word in bad_words:
if word in message.content:
await message.delete()
@discord.Cog.listener()
async def on_member_join(self, member):
age = member.joined_at - member.created_at
if age.days < 1:
until = timedelta(hours=12) + member.joined_at
await member.timeout(
until, reason=f"АвтоМод: Недавно созданный аккаунт ({age.days} дней)"
)
await member.send(
f""
)
else:
roleJoin = member.guild.get_role(863696255224643605)
await member.add_roles(roleJoin, reason=f'{member} (ID: {member.id}) зашёл на сервер')
@discord.Cog.listener()
async def on_member_remove(self, member):
try:
await member.send('')
except:
print(f'{member} (ID: {member.id}) покинул сервер и не получил сообщение')
@discord.Cog.listener()
async def on_message(self, message):
if message.content.startswith('@loud glade'):
await message.channel.send('Привет! Я мульти бот для сервера **HFD**. Мой префикс `/`')
else:
pass
def setup(bot):
bot.add_cog(Events(bot))```
I think it's because you have two on_message listeners
i've got 3
Probably that's why
try doing something like
@discord.Cog.listener('on_message')
async def on_invite_link(self, message):
oh, thank you very much
It works?
yes
welcome :)
How do I get the username + avatar of who used the slash command
interaction.user.name and interaction.user.avatar.url I think
It doesn't work
when i do py await ctx.respond(embed=embed) it sometimes says ```
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
is this like a bug or something i would have done wrong
its not always just sometimes so i dont think ive done smoething wrong
A slash_command?
yea
Can slash command permissions be applied to command group children, or just the parent?
afaik it's just the parent
Darn. Understood -- and actually I see @tiny wagon mentioned this a week or two ago. Thank you for confirming
yw
Option in my slash_comand are not showing, I did everything correctly
comment out, run the bot, uncomment, and run the bot
Comment out?
Wt is that
# this is a comment
Yes I know this
just comment the slash command
and
Tnx working
And what about how can I get the author's username and avatar
b!rtfm pyc discord.Member.display_avatar'
No results found when searching for discord.Member.display_avatar' in pyc
b!rtfm pyc discord.Member.display_avatar
b!rtfm pyc discord.Member.name
And how can I make an option in a slash_command for images
Option(discord.Attachment)
is it possible to join a stage channel as a speaker w a bot?

b!rtfm pyc StageChannel
discord.StageChannel
discord.StageChannel.bitrate
discord.StageChannel.category
discord.StageChannel.category_id
discord.StageChannel.changed_roles
discord.StageChannel.clone
discord.StageChannel.connect
discord.StageChannel.create_instance
discord.StageChannel.create_invite
discord.StageChannel.created_at
i did but theres nothing on becoming a speaker
it just connects
It doesn't seem like bots can become speakers
pain.
Hey 👋 One little question:
How can I import a View from another file into my file? Or is that even possible?
Example: I have command.py with a slash command. When the command is executed, the bot should respond with the class MyView, which is written down in views.py. How can I use the class MyView from views.py in the command.py file? Because currently, if I try to import the MyView Class into the command.py file, all commands from the command.py file disappear on discord (I'm using Cogs btw).
Could you show how your code and imports look like, I can import views into my command cog with no problem
Sure, sec...
i think you can work around this by connecting the bot to a regular vc, having it play something, then moving it into the stage channel?
wouldnt it become an audience member by being moved in
i think it depends on the bot's perms
Oh damn, sorry sorry sorry, was a very dumb mistake by me (forgot the : at the end of the class and my IDE didn't highlighted it)
Now it works... Sorry
i see
at least through the UI, when i moved a speaking music bot into the stage it was automatically a speaker because it was considered a stage mod
ah ight ill try that
It's okay 
what is the ctx.message.author for slash commands?
ctx.interaction.user, but in both types of commands you can just do ctx.author as a shortcut
Can i still use command groups when i want to use bridge commands?
nope
Is there a example for models in pycord?
Here's the modal dialogs example.
^ @fervent cradle
Thanks
So the Option(Discord.role) displays all of discord roles in the server. Would it be possible to get the same select options with a list of role ids?
internal message cache is not meant for storing large amounts of messages right? It seems like when I delete a message that is cached, from a very long time ago, it tries to retrieve that message from cache as a blocking call, so the bot doesn't respond to anything for like 10 seconds until it finds that message and sends the log

is it possible to set a default embed color so that I don't have to set it all the time?
if isinstance(ctx, discord.ApplicationContext):
await ctx.respond("Pong!")
elif isinstance(ctx, commands.Context):
await ctx.send("Pong!")```
is this the correct way to reply in a bridge command?
Does this import exist?
Eh, sorta. Just make it a var then assign the color as that var.
No discord.ui
What?
should be under discord.ui instead
I'm trying to make a / command that brings up a set of pages you can cycle through with buttons.. But I get this errors:
TypeError: expected Item not <class 'src.button_views.server_button_view.ServerButtonView'>
Code:
class ServerButtonView(View):
"""
Server Button View
"""
def __init__(self, pages: list, user: Optional[discord.Member] = None):
super().__init__(self)
self.current_page: int = 0
self.pages = pages
self.user = user
self.length: int = len(self.pages) -1
self.children[0].disabled = True
@commands.has_permissions(administrator=True)
@commands.slash_command(name = "server-setup", description="Used to set up the server, adding it to the DB.")
async def server_setup(self, interaction:discord.Interaction):
"""
Sets up the server!
"""
pages = [
discord.Embed(title = "page 1/5", color = discord.Color.blue()),
discord.Embed(title = "page 2/5", color = discord.Color.blue()),
discord.Embed(title = "page 3/5", color = discord.Color.blue()),
discord.Embed(title = "page 4/5", color = discord.Color.blue()),
discord.Embed(title = "page 5/5", color = discord.Color.blue())
]
await interaction.response.send_message(embeds = pages[0] if isinstance(pages[0], list) else [pages[0]],
view = ServerButtonView(pages, interaction.user))
I followed a YT tutorial - but I may have done something wrong
?tag guide
This will help
Ignoring exception in on_application_command_error
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 877, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "d:\Code\t2e-alpha\cogs\user.py", line 67, in stats
await ctx.defer(ephemeral=True)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 556, in defer
await self._locked_response(
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 956, in _locked_response
await coro
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 211, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
``` how could ctx be an unknown interaction??? its only happens after some messages
What does your code do?
Do you mean predefine the roles that show in the option?
i keep getting this error but i dont know where in my code it is coming from ```Traceback (most recent call last):
File "bot.py", line 1561, in <module>
bot.run(token)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 715, in run
return future.result()
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 694, in runner
await self.start(*args, **kwargs)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 658, in start
await self.connect(reconnect=reconnect)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 553, in connect
await self.ws.poll_event()
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/gateway.py", line 589, in poll_event
await self.received_message(msg.data)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/gateway.py", line 539, in received_message
func(data)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/state.py", line 635, in parse_auto_moderation_action_execution
event = AutoModActionExecutionEvent(self, data)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/raw_models.py", line 462, in init
self.content: str = data["content"]
KeyError: 'content'
sends an sql query and then format it into embed
and some other operations
is there a list of all the listeners in pycord?
hey how can i make it so that you can only select two channels with slash commands?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_options.py at e44164180158f62fac99460bb3cf782d86ec23c7 · Pycord-Development/pycord
If your code can sometimes take longer than 3 seconds to respond you need to defer the response. Discord only allows 3 seconds for your bot to respond, sometimes SQL can be slow so by adding ctx.defer() to the beginning of your command callback discord will allow you up to 15 min.
.
@grizzled sentinel
code?
apply ##1521 (or update to master branch)
we should really have incremental 2.0.x releases for major bugs
Please elaborate.
i want you to do a certain thing in 2 channels. Now how can I make it so that a selection menu appears for example kanal1 and kanal2, if you select kanal1 a message will be sent to kanal1
So in the option there will only be 2 options. You could get the channel names and pass them to choices=["name1", "name2"] in the option
@grizzled sentinel
https://www.toptal.com/developers/hastebin/asayevefim.py
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how can i specify the channel?
i did make an issue on github, i was told its not a bug
if, you want any channel and not just 2, use discord.TextChannel as the type
I would like to be able to send the command only in 2 channels, so I only want 2 options, but where do I enter the channel then?
choices is only the name
or?
choices is an argument for Option
discord.Option(choices=["1", "2",])
defer before your sql queries
95% of the time the defer should be the first thing you call in the command callback
also you're responding at the top without stopping the command
so even if you do something wrong it'll still try to continue
...and that isinstance setup at the top is a complete mess, just make the option type discord.Member
Yes, but when I click on 1 nothing happens. again I want that when I press 1 a channel is killed and a message is sent in it
what does your command callback look like?
@bot.slash_command()
@option(choices=["Channel1", "Channel2"])
async def choice_test(ctx):
Channel1:
So far I don't know how to get the appropriate channel or how to transfer it to channel1
Just check what was chosen and get the channel
When specifying the option like that the first argument should be the name of the argument.
Than you need to have the argument stated after ctx
i think he want's to convert the channel name to a channel object
Noo 😣
with the commands.cooldown is it possible to have users have a 60s delay but if they have a role its reduced to 30s?
I want only when i click channel1 then a send in channel1 a message
ok
so you take channel 1
convert it to the channel object
then await channel.send
don't think so, you'd have to build your own cooldown system for that
dynamic cooldown is completely automatic
So
@bot.slash_command()
@option(choices=["Channel1", "Channel2"])
async def choice_test(ctx):
channel = bot.get_channel(939551193145950258)
Channel1: channel
await Channel1.send("skasl")
?
idk how it works either but it's not really what you'd think

Well like if I use discord.Roles it shows all of the roles only the server. I want to relocate the same style of it with my own list of role ids. Was wondering if that’s possible
well how is the option passed into the function? i dont see additional params other than ctx
async def info(ctx: discord.ApplicationContext, name: Union[discord.Member, str]):
TypeError: Invalid usage of typing.Union am i being stupid or is this not how it's used in the example
oh i need channel1 in the parms?
you can't union slash option typings anyway
if you look at the example you posted earlier. you will notice that you need to say what arg the option is for and specify that arg after ctx
you need to give your option a name
Okay
if you just pass in discord.Member it lets you search members or input a member ID
@option(
"channel",
description="Select a channel",)
async def select_channel(
ctx: discord.ApplicationContext,
channel: Union[discord.TextChannel, discord.VoiceChannel],
):
im pretty sure union would break there too? you have to input the separate channel_types kwarg
Yeahh but then is all channel there..
or maybe it works idk, options have gone through a lot
im trying to do either member or a name or something i have as a variable not an id
So i have
@bot.slash_command()
@option(name="Channel1", choices=["Channel1", "Channel2"])
async def choice_test(ctx):
channel = bot.get_channel(939551193145950258)
Channel1: channel
await Channel1.send()
is that right?
that ist the code you should use its an example of what you have to do. notice the channel arg
you'd have to use str then, discord only supports a single type at a time
option names cant have capitalized letters + you didnt add a new param in the function
@bot.slash_command()
@option(name="channel1", choices=["Channel1", "Channel2"])
async def choice_test(ctx, channel1):
channel = bot.get_channel(939551193145950258)
Channel1: channel
await Channel1.send()
though i think you could use MemberConverter but i haven't experimented with it myself
and then?
see how channel is the first argument of the oprion decorater and is an argument in select_channel
this is painful
ill have to do two options and have neither required then
channel: Union[discord.TextChannel, discord.VoiceChannel] thats all channel or?
now you need to learn OptionChoice to give a nice readable text to the end user but provide the id to the code (name, value)
you will also have to provide the id as a string since the ids are too long for int type
Yes, that is not the code you should use, it is the code form the example I was just posting a snipet to show you.
okay
Anyway I'll just leave it thanks anyway 
async def idee(ctx, idee: Option(str, "Give your idea on.")):
File "C:\Program Files\Python310\lib\optparse.py", line 570, in __init__
self._set_opt_strings(opts)
File "C:\Program Files\Python310\lib\optparse.py", line 594, in _set_opt_strings
if len(opt) < 2:
TypeError: object of type 'type' has no len()
Why is that not working ? Huhhhhh ??? 
@bot.slash_command()
async def idee(ctx, idee: Option(str, "Give your idea on.")):
Option(str, "Give your idea on.") is not working
is there any way to get both application and text commands error with one event handler?
You know that doesn't make sense right
why?
No
ok
Channel1: channel
And that won't even work if you select channel2
But i need help to this why is that not working?
Would there be a way to stop the paginator from within a custom view?
You can paginator.stop iirc?
1st: create your embed
example:
embed = discord.Embed(color=int("hex code", 10), title="embed title", description="embed description")
embed.set_image(url=image url)
embed.set_thumbnail(url=thumbnail url)
embed.set_footer(text="embed footer")
embed.set_author(name="embed author")
embed.add_field(name="a field", value="embed field")
then you can send using send thing await ctx.send whatever then inside the () put embed=embed
is it ok to shutdown my bot using exit()?
is there any better way?
color = discord.Color.green()
discord.Color.from_rgb()
if u want a custom color u can find a hex and replace the hex code thing with the hex code
might want to put emb inside that def (i dont know about other part)
it should work
oh sorry
ok
How do I get a modal to close once submited
it doesent matter, i did it before and its throwing the seme error
View is not persistent. Items need to have a custom_id set and View must have no timeout
client.add_view(LoginView(ctx=discord.ApplicationContext))
😟
also how do i make them not have a timeout
I stumbled on this discussion on github https://github.com/Pycord-Development/pycord/discussions/251. Does anyone know if subcommands in cogs have been implemented since then?
class LoginView(discord.ui.View):
def __init__(self, ctx):
super().__init__()
self.value = None
AuthLink = discord.ui.Button(
label="Fun",
style=discord.ButtonStyle.gray,
emoji="funny emoji here",
url="https://rebrand.ly/"
)
self.add_item(AuthLink)
SubmitButton = discord.ui.Button(
label="Submit",
style=discord.ButtonStyle.green,
emoji="🔒",
custom_id="Submit"
)
self.add_item(SubmitButton)```
Seems to be it yeah, cheers 👍
Great !
how do i make this code not have a timeout
i keep getting ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
for
client.add_view(LoginView(ctx=discord.ApplicationContext))
https://github.com/Pycord-Development/pycord/blob/master/examples/views/persistent.py
This is the example for persistent views
WIll pages.Page automatically create a new page if I reach the max amount of fields in a embed?
no?
Hmm alright thanks
My paginator's custom buttons aren't working, it just says this interaction failed
I can send my code in about 20 minutes
what is the 4th argument that can be given?
Is it possible to use converters with slash commands?
Basically what I want to do is parse a str argument using a converter and remove some unnecessary text using a converter
if you are trying to make a help command please check out the guide https://guide.pycord.dev/extensions/commands/help-command
Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "", line 382, in _run_event
await coro(*args, **kwargs)
File "", line 154, in on_voice_state_update
if member in channel:
TypeError: argument of type 'VoiceChannel' is not iterable
@bot.event
async def on_voice_state_update(member, before, after):
channel = bot.get_channel(1002189083927396412)
if member in channel:
kanaL = bot.get_channel(1002189165380763689)
await kanaL.send(f"tst")
why is that not working?
You should be using channel.members
I already used the guide on github, but I'm trying to make such a help with the paginator
currently, you're looping through the channel object itself
oh thanks
You're welcome
@silver moat
as a class commands.Cooldown takes rate and limit
oh okay, thx
Do you know why?
what is menus lol
My slash command from my bridge command disappears after I use it once. It works the one time I can use it. What could be the problem?
idk but i do it according to this guide
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96#help_pagination_intergrate
discord
it uses some external library outside of pycord while pycord can paginate natively
Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!
the information here will probably be suffice
Hey my paginator isnt working when I use await paginator.edit(msg, suppress=True)
Anyone know why that might not be working? I can't switch pages
show code ty
alr one sec
games[f"{ctx.author.id}{player.id}"] = False
page_buttons = [
pages.PaginatorButton(
"first", emoji="⏪", style=discord.ButtonStyle.green
),
pages.PaginatorButton("prev", emoji="⬅", style=discord.ButtonStyle.green),
pages.PaginatorButton(
"page_indicator", style=discord.ButtonStyle.gray, disabled=True
),
pages.PaginatorButton("next", emoji="➡", style=discord.ButtonStyle.green),
pages.PaginatorButton("last", emoji="⏩", style=discord.ButtonStyle.green),
]
if turn == 1:
person = ctx.author
otherperson = player
while len(p1hand) < 3:
p1hand.append(random.choice(p1cards))
hand = p1hand
else:
person = player
otherperson = ctx.author
while len(p2hand) < 3:
p2hand.append(random.choice(p2cards))
hand = p2hand
await thread.send(f"Make your move {person.mention}!")
mainmsg = await thread.send("Loading....")
cardpages = []
for card in hand:
origcard = list(carddict.keys())[list(carddict.values()).index(card[0])] + f"-{card[1]}"
cardobj = card[0]
rarity = int(card[1])
cardcost = cardobj["powers"]["cost"] * round(rarity/2) if round(rarity/2) != 0 else cardobj["powers"]["cost"]
carddmg = cardobj["powers"]["dmg"] * rarity
filename = f"{cardobj['name']}-{rarity}-{random.randint(0, 10)}"
cardimg = discord.File(f"cardoutput/{origcard}.png", filename=f"{filename}.png")
view = discord.ui.View()
view.add_item(PlayCardButton(person, otherperson, cardobj))
cardpages.append(pages.Page(content="What will you play?", files=[cardimg], custom_view=view))
paginator = pages.Paginator(
pages=cardpages,
show_disabled=True,
show_indicator=True,
use_default_buttons=False,
custom_buttons=page_buttons,
loop_pages=True
)
paginator.user = person
mainmsg = await paginator.edit(mainmsg, suppress=True)
playedcard = None
while not paginator.is_finished():
if games[f"{ctx.author.id}{player.id}"] == True:
playedcard = cardpages[paginator.current_page].custom_view.cardobj
print('stopped idiot')
paginator.stop()
await asyncio.sleep(0.1)
it's all in a command, so ignore the indentation
games = {}
class PlayCardButton(discord.ui.Button):
def __init__(self, user, otheruser, cardobj):
self.user = user
self.user2 = otheruser
self.cardobj = cardobj
super().__init__(label="Select")
async def callback(self, interaction: discord.Interaction):
if interaction.user != self.user:
return
games[f"{self.user.id}{self.user2.id}"] = True
msg = await interaction.response.send_message("Great choice!")
await asyncio.sleep(5)
await msg.delete()
Then the custom button I have
but yeah, the paginator isn't working, I can't change pages or anything
you should use paginator.send
Yeah but it needs ctx, and I'm using a slash command, meaning it would have a ctx type of ApplicationContext I think
But I'll try
then paginator.respond(ctx.interaction)
it sends as a followup
Wait really?
yes
Application Command raised an exception: InteractionResponded: This interaction has already been responded to before
I'm using await paginator.respond(ctx.interaction, target=thread)
why is this being sent in a thread again?
So what I'm doing is I don't want to clog up the commands channel with text from my game, so I'm making a thread that contains all the cards played
Pretty much I don't want to clog up a channel, so I'm using a thread
Any thoughts?
then why not just use paginator.send if you already responded
I might be misunderstanding, but doesn't "send" require a prefix command context? And not a ApplicationContext?
Yeah
hmmm true... but if im not mistaken there's a util to create a context from a message? i wonder if i can find it
Oh thank you so much!
Nope
I'm using discord.Bot, should I switch to commands.Bot?
ah.. if you want i guess
but idk paginator.respond should be using followup anyway
what version are you on?
print discord.__version__
2.0.0
discord/ext/pages/pagination.py lines 1060 to 1070
if isinstance(interaction, discord.Interaction):
self.user = interaction.user
if target:
await interaction.response.send_message(target_message, ephemeral=ephemeral)
msg = await target.send(
content=page_content.content,
embeds=page_content.embeds,
files=page_content.files,
view=self,
)```
should I install from git?
oh so because they're specifying target
setting a target makes it respond with a message
and target doesn't check for is_done
maybe check interaction.response.is_done() further up and change the function based on that, which would avoid cluttering this section with more if/elses
??
Why do I always get 0 when using this
you should get 0 if you didn't enable members intent
They are included
fetch_guild doesn't return members anyway
I'll edit the pycord pagination.py on my local machine
How should I proceed then?
get_guild
use get_guild
I changed line 1050's if to
if target and not interaction.response.is_done():
and enable guild intents as well if you haven't already
not awaited
it's not a coro
thx very much
that would likely do the opposite of what you want
because then target isn't used at all
oh lol
discord/ext/pages/pagination.py line 1050
)```
2.0 is probably a bit different from master
true
should I use the master branch?
a bit messy but what about this?
method = interaction.followup.send if interaction.response.is_done() else interaction.response.send_message
if target:
await method(target_message, ephemeral=ephemeral)
...```
trying
how do i get all the channel names of a specific guild
nope, "this interaction has already been responded to before"
ok but HOW
alr thx
probably use try-except then
i guess
OH IK THE PROBLEM, me being dumb and not adding await method(target_message, ephemeral=ephemeral)
yep, fixed! Thanks so much
ey nice
you want to make the pr?
yeah, i'll go eat first
and also the implementation kinda sucks because of the rest of that block
it's official, I found a bug lol
One more question, I don't want it to send a target_message, but it needs to send a string, what should i do?
shouldn't target_message be optional?
as in the paginator.respond target_message
the one that defaults to "Paginator Sent!" or something
changed it to this for now
nope that doesnt work
None?
How do I set the permissions of an already existing channel
assuming TextChannel https://docs.pycord.dev/en/master/api.html#discord.TextChannel.set_permissions
thx
It can't be optional because it has to respond
True, but I already responded, so I don't want to respond again
I want it to ONLY send a message to the target, and not to the interaction's channel
Better?
*not interaction.response.is_done():
guys I'm having a super weird issue that I've seen happen to more. trying to self.client.get_guild or self.client.get_channel returns None no matter what
did you enable guild intents?
What's that? I have these 3 enabled (All, i think)
in your code
intents = discord.Intents.all()
I think so.
what's the actual bot instance
client = commands.Bot(command_prefix=prefix, intents=intents, help_command=None, case_insensitive=True) # Setting prefix
why is error not showing up in terminal?
for what
while using cog
store = False, error will show up
2.0.0 seems like it
will be fixed in 2.1 i think
ok
[<Guild id=894902529039687720 name='Moonball Network' shard_id=0 chunked=True member_count=238>, <Guild id=951055432833695764 name='Bot Emojis' shard_id=0 chunked=True member_count=10>, <Guild id=984859985534136350 name='Bot Emojis' shard_id=0 chunked=True member_count=4>]
did you convert your IDs to int before using get_guild/get_channel
to me?
no raj
ok
added int now, that changes nothing
await self.client.get_guild(int(guild_id)).get_channel(int(general_channel)).send(f"Hey {user.mention}! Couldn't DM you your reminder.", embed=r_embed)
huh?
i meant, i added int() to them now
didnt solve the issue
wait, its prob running before the bot ready's up
that would be the reason
my 2nd issue
@check_reminders.before_loop
@check_for_birthday.before_loop
@check_giveaway.before_loop
async def before_my_task(self):
await self.wait_until_ready() # Wait until the bot logs in
functions don't even run when i do this
the 3 functions
yeah it has to be after on_ready
yep, but then when I try to do this it stops the functions from running entirely
can you use decorators like that to assign the same coro to several tasks? im not sure if that works
also should be self.client.wait_until_ready
self.wait_until_ready only works here because self is the client
this fixed it
if you're doing it in a cog, it would be self.client or self.bot, whatever your bot object is
thanks a lot! yep
allgood
Hey, I'm trying to write a function that enables users to edit one of my bot's messages. I'm using a MessageCommand and I would like some kind of check that the message from which the command has been used is from the bot.
- Should I use
discord.MessageCommand.checksfor that? - If so, I dont get how to retrieve the message author's ID within the callable. I tried with some of the
discord.ApplicationContextproperties but either the message object was None, or the id wasn't the author's
uhh can you explain a bit more
is there any way to get list of banned members?
b!rtfm pyc guild.ban
Say I used my bot to send a message with another command I wrote, I want the bot to edit its own message, so I would want to use a MessageCommand on that message. But that command would only work if the bot is the author of that message (since the bot can't edit another user's message). So I'm trying to understand where I should check that and if discord.MessageCommand.checks is a correct way to do that
i'd say at the start of the command, just check message.author == ctx.me
ctx.me will always be the bot's member object
you could create your own check but it's not really necessary
Okok! Also, it's not really possible to only show the command in the UI if this condition is met is it?
the message author's ID can be retrieved with Message.interaction.user
no, you can only filter it in the UI by user/channel via the integrations menu
Thanks a lot!
allgood
my issue my bot is like registering a wrong embed
elaborate?
doesn't include slash commands?
i wonder
description is Embed.Empty by default if I'm not mistaken
ok so?
bridge commands don't have their own type do they...?
oh wait that's the wrong description I'm stupid
yeah there's bridgecommand
hmm
i think both walk_commands and walk_application_commands would straight up ignore them then
lemme check
ok hmmm should i add a field for a command without a for loop
hm nope they do seem to include bridge
remove the line checking if not description... and prefill the add_field description with another value instead
got another help error Ignoring exception in on_connect Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event await coro(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1040, in on_connect await self.sync_commands() File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 647, in sync_commands registered_guild_commands[guild_id] = await self.register_commands( File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 476, in register_commands prefetched_commands = await self.http.get_guild_commands(self.user.id, guild_id) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 353, in request raise Forbidden(response, data) discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Hey, I am migrating my bot from emoji reactions to buttons... the only problem is I am too dumb to figure out how to await a button click in the main program, and then run other code. I know I can do it in a callback, the only problem is, it is horrible long...
I would rather just pass the list and let them handle everything.
In short, here is the working code, but I want to await it in the register function.
async def npc_reaction_message(msg, embed, buttonlist):
view=View()
i = 0
res = []
for button in buttonlist:
thisbutton = Button(label=button, style=discord.ButtonStyle.secondary, custom_id=f'btn_{i}')
print(thisbutton)
res.append(thisbutton)
view.add_item(thisbutton)
i += 1
await msg.send(embed=embed,view=view)
return res
async def on_interaction(interaction: discord.Interaction):
await interaction.response.send_message(f"Button: {interaction.data['custom_id']}\npressed by: {interaction.user}")
#I dont want to code it here, I want to wait for the button click in #register
#OnCommand
@bot.command()
async def register(msg):
buttonlist = ["YES", "NO"]
embed=discord.Embed(title="**Welcome to the Adventurer's Guild!**", description="**Marie & Anne**: Do you perhaps want to go on an **Adventure**?", color=0xfbe8d2)
gotback = await npc_reaction_message(msg, embed, buttonlist)
for btn in gotback:
btn.callback=on_interaction
#wait here for the button click and do something
bot.run(token)
I would appreciate it, if someone knows the answer, discord-components does not work for me. I am using discord.py and pycord.
wtf is happening
nvm figured out that i had a function named users...
and i was trying to reach a object users too
mhmm
In general discord, there is a text limit of 2k charakters, what´s the limit of the embed? I read something like 4096?
and is that the right way to check the length, and cut it to the right lenght?
if len(post.get_text()) < 4096:
embed = discord.Embed(title=f"New Post:",
description=f"{post.get_text()}")
else:
embed = discord.Embed(title=f"New Post:",
description=f"{post.get_text()[:4096]}")
embed.set_thumbnail(
url='https://c.tenor.com/WCE5JUszKGMAAAAC/tenor.gif')
file = discord.File("xxx.png")
embed.set_image(url='attachment://xxx.png')
await channel.send(file=file, embed=embed)
i am not sure about this
{post.get_text()[:4096]}
is this right? found it on stackoverflow
if the variable is str
len(str(variable)) then it returns the amount of characters, so yes
oh wait, I should read to the end
it´s a str
it´s all coded yet except the check for lenght and the trim
i know i could improve the code 😄
now it´s better
just use else
if i trim it there is no need for the check
if it is shorter than 4096, nothing will change
somethimes you are brain busted 😄
but yeah. you are right, did not think about this 😄
Is there an example for the select menues?
Here's the dropdown example.
Alr thanks 👍
A simple issue but I cant seem to get it to work, how do I make a bot send a user a DM from a button click, I think that its possible
async def on_interaction(interaction: discord.Interaction):
await interaction.response.send_message(f"Button Custom ID: {interaction.data['custom_id']}\npressed by: {interaction.user}")
user=await client.get_user_info(interaction.user)
await client.send_message(user, "Your message goes here")
@sleek arch
import discord
from discord.ext import commands
from discord.ui import View, Button
from discord.ext import commands
bot = discord.Client(intents=discord.Intents.all())
bot = commands.Bot(intents=discord.Intents.all(),command_prefix="!")
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
view.add_item(thisbutton)
await msg.send(embed=embed,view=view)
async def on_interaction(interaction: discord.Interaction):
await interaction.response.send_message(f"Button: {interaction.data['custom_id']}\npressed by: {interaction.user}")
user=await bot.fetch_user(interaction.user.id)
await user.send("Your private message goes here")
#OnCommand
@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)
bot.run(token)
whole code
dependencies:
py -3 -m pip install git+https://github.com/Rapptz/discord.py
py -3 -m pip install pycord
Why are u using dpy?
ohnvm
dsicord.py 2.0 and pycord
that just conflicts
never had a problem
if it really does, then just install pycord
the way I code is weird, but it works
Not sure how it still works
by getting the button id and user id, I can process the things further depending on my needs
not that. more like the discord.py + py-cord
#1002289194544136323
if someone knows my problem, I would appreciate it
I don't want to make a
->
->
->
->
->
code blocks
I have lots of lists and data and follow ups
hmm ?
well, you use await msg.send(embed=embed,view=view)
oh ic, msg is a Context






