A quick question about enabling pre-disabled interaction buttons - I am trying to dynamically disable/enable a button depending on the response from the bot (which is either a link (button should be disabled) or just text (button should be enabled))... What would be the best way to handle such a case? (my view is structured like this: https://hastebin.com/mixeyuzibe.py)
#Basic Pycord Help (Quick Questions Only)
1 messages · Page 51 of 1
I don't think link buttons can be disabled
Therse are not link ones, they're secondaries
it should be commands.BucketType.user I think.
The link I'm talking about is what the bot responds as a part of an embed (i.e. a field of it)
Sorry I misunderstood your question. You can use a ReGex to check if a url exists.
I know that, however would I need to put that check in the __init__ method? Or somewhere else?
depends on when you are checking the condition. Is the embed already known when the view is initialized?
Nope, it is just before it is
(here)
embed is the embed with the response inside of it
embed is a discord.Embed, so you can pass in the value of embed into the function and check the condition in __init__
I see. Thanks, that's what I was trying to understand 😄
yw
Disregard my previous statement. It appears you are passing in interaction.message, which may or may not exist.
Because get_bucket expects a message with an author, you can do the following:
new_message = interaction.message
new_message.author = interaction.user
bucket = self.cd_mapping.get_bucket(new_message)
interaction.user *
I'm trying to build a string, that holds a conversation. In discord, this conversation will be replies of messages, so message.reference exists in pycord.
I want to recursively go back through all the messages, starting with the beginning, and build a string of all the messages.
I'm having trouble thinking this through and finding a solution to recursively get all messages if message.reference exists.
This is what I'm doing now, and it works to build the previous message and the current message, but I need to keep going until there aren't anymore references and add all the text into the string..
built_message = f"{prev_convo.author.name}: {cleaned_prev_message}\n{message.author.name}: {cleaned_message}"
Any help would be
and appreciated ❤️
fwiw, something like this is halfway working:
cleaned_prev_message = await sanitize(prev_msg)
built_message = (
f"{prev_msg.author.name}: {cleaned_prev_message}\n" + built_message
)
if prev_msg.reference is not None:
prev_msg = await message.channel.fetch_message(
prev_msg.reference.message_id
)
but I'm missing the very first message texts...
You could use a loop
how do i make menu like this?
That's a modal
.guide
Here's the modal dialogs example.
https://ghgore.com/2019/08/14/fun-with-discord.py-and-matplotlib.html
I was wanting to do something like this (not with discord.py obviously), but I don’t want to actually save the file, but want a discord.File object from thepltfrom matplotlib. How can I do this?
io.BytesIO
its the solution for everything 
hey, sorry guys i couldnt easily find the information as to how to reply to a user in a textbox that only the user can see
About:
Dashboard
Invite link
Commands
Bot support server
Discord bot list Vote
Patreon link
Carl-Bot does what the most popular bots do but does it better, faster, and without the meme commands that spam and annoy you. Carlbot has been used to reduce the number of bots needed in a server from 3 to 4 or more… to just 1.
Members
812,530,108 total
261,215,812 unique
Channels
234,226,863 total
186,172,219 text
48,054,644 voice
Process
3167.85 MiB
7.30% CPU
Servers
7211651
4096 shards
Messages seen
0 messages (-0.0/s)
Uptime
1d 16h 32m 56s
this
if you guys know how please tell me a solution cause people are sick and tired of my bot sending messages in a not very active server lol
set ephemeral = True when sending response or followup
awesome, thank you so much.
for a modal could i have it require a bool or an integer instead of a string?
uhh i wanted to basically make a ticket channel like that and post all these answers in the ticket channel how do i do so
class MyModal(Modal):
def __init__(self) -> None:
super().__init__(title="Ticket Creating")
self.add_item(InputText(label="why ur unemployed?", placeholder="Your Answer here",style=discord.InputTextStyle.short))
self.add_item(InputText(label="ohh ye are u that failure?",placeholder="Your Answer here",style=discord.InputTextStyle.short))
self.add_item(InputText(label="Your A disappointment",placeholder="Your Answer here",style=discord.InputTextStyle.short))
self.add_item(InputText(label="Also get a job",placeholder="Your Answer here",style=discord.InputTextStyle.short))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(
title="Application Ig",
fields=[
discord.EmbedField(
name="Q)why ur unemployed?", value=f"A: {self.children[0].value}", inline=False
),
discord.EmbedField(
name="Q)what are your thoughts on being failure?", value=f"A: {self.children[1].value}", inline=False
),
discord.EmbedField(
name="Q)Are you still unhappy that you are disappointment", value=f"A: {self.children[2].value}", inline=False
),
discord.EmbedField(
name="Q)Also get a job", value=f"A: {self.children[3].value}", inline=False
),
],
color=discord.Color.random(),
timestamp=datetime.datetime.utcnow()
)
await interaction.response.send_message(embeds=[embed]) #instead of sending it in the interaction channel i want it in ticketchannel
No that's not possible
Get the channel category you want to create the tickets in using guild.get_channel
Then create a text channel
.rtfm categorychannel.create_text
And send the embed
You would want to pass perms overwrites to make it a secret channel yk
why does the .voicestates return wrong values? When i turn on the bot it shows 2 person in the vc ( which is correct) then it stays at 2 and doesnt update
.rtfm voice_channel.voice_states
Target not found, try again and make sure to check your spelling.
.rtfm voicechannel.voice_states
1 results
Hello guys
How do I make it so that user has to give at least any one of the available options
.rtfm discord.Option.required
Target not found, try again and make sure to check your spelling.
Is there something like hintText in an option to let the user know what format the option takes string in
read the docs
.rtfm paginator
81 total results
discord.ext.pages.Paginator
discord.ext.pages.Paginator.add_button
discord.ext.pages.Paginator.add_default_buttons
discord.ext.pages.Paginator.add_item
discord.ext.pages.Paginator.add_menu
discord.ext.pages.Paginator.cancel
discord.ext.pages.Paginator.clear_items
discord.ext.pages.Paginator.disable
discord.ext.pages.Paginator.disable_all_items
discord.ext.pages.Paginator.edit
discord.ext.pages.Paginator.enable_all_items
discord.ext.pages.Paginator.from_message
discord.ext.pages.Paginator.get_item
discord.ext.pages.Paginator.get_page_content
discord.ext.pages.Paginator.get_page_group_content
discord.ext.pages.Paginator.goto_page
discord.ext.pages.Paginator.interaction_check
discord.ext.pages.Paginator.is_dispatching
discord.ext.pages.Paginator.is_finished
discord.ext.pages.Paginator.is_persistent
So I have been trying to make country searcher and I am stuck with this, I can't figure out the problem (it says keyerror '{country i put in}',) which is reading from args (which I set to tuples)
(the error seems to only happen with "[tuple(args)]" cause when i put it in as specific country it works
Why are you trying to use a tuple as a key? That is not how dicts work in Python at all
so I should put it as object?
object?
what should I put it in as?
Do you know basic Python?
yeah i guess but doesnt seem to work in anyway
.rtfm discord.Embed
76 total results
discord.EmbeddedActivity.checkers_in_the_park
discord.EmbeddedActivity.checkers_in_the_park_dev
discord.EmbeddedActivity.checkers_in_the_park_staging
discord.EmbeddedActivity.checkers_in_the_park_qa
discord.EmbeddedActivity.chess_in_the_park
discord.EmbeddedActivity.chess_in_the_park_dev
discord.EmbeddedActivity.chest_in_the_park_staging
discord.EmbeddedActivity.chest_in_the_park_qa
discord.EmbeddedActivity.doodle_crew
discord.EmbeddedActivity.fishington
discord.EmbeddedActivity.letter_tile
discord.EmbeddedActivity.ocho
discord.EmbeddedActivity.ocho_dev
discord.EmbeddedActivity.ocho_staging
discord.EmbeddedActivity.ocho_qa
discord.EmbeddedActivity.poker_night_staging
discord.EmbeddedActivity.poker_night
discord.EmbeddedActivity.poker_night_qa
discord.EmbeddedActivity.putts
discord.EmbeddedActivity.sketchy_artist
Move to #883236900171816970 if you're going to spam random commands
ok
So why are you trying to set the key as a tuple?
using tuple list idk
nvm gonna move it json instead
How to set footer to Embed in pages.Page()
I trying use:
Pages[c_page].set_footer(text=f"Page {page_numbering}/{total}")
yeah I confused it with something else srry
Why are the docs in light mode. It's hurting my eyes
Probably because you aren't using the dark mode?
wait it has a dark mode?
Yes?
lmao my bad.
What do you think this button does?

idge
In Embeds is it possible to add a field with either empty name or value?
Kinda, iirc if you use an invisible charecter let my check real qucik
sure
Try using this unicode charecter
\u200B ->
worked
How to set footer to Embed if it was created via pages.Page()?
I found a way
Pages[page].embeds[0].set_footer(text=f"Page {page_numbering}/{total}")
why, when creating a Field via EmbedField, if the name starts with numbers, does it skip the creation of this and subsequent fields?
oh, it's my error
how to delete messages?
How would I go about sending logs of deleted messages/edited messages once the bot has been restarted. It seems to just not log messages from before the restart
.rtfm discord.Message
170 total results
discord.Message
discord.Message.activity
discord.Message.add_reaction
discord.Message.application
discord.Message.attachments
discord.Message.author
discord.Message.channel
discord.Message.channel_mentions
discord.Message.clean_content
discord.Message.clear_reaction
discord.Message.clear_reactions
discord.Message.components
discord.Message.content
discord.Message.create_thread
discord.Message.created_at
discord.Message.delete
discord.Message.edit
discord.Message.edited_at
discord.Message.embeds
discord.Message.flags
Question, does py-cord protect against rate limiting?
Or should I put checks in place so I don't get rate limited
no
Im not even if the other ones are doing it
Alr thanks
Is there something I can do to put checks in place before this happens?
Add your own checks wherever you might spam the API
usually you shouldn't need checks at all unless you're doing some specific spammy thing
I have a bot that creates an emoji, sends it and then deletes it, but deleting the emoji fails sometimes
Please ping if you respond
?tag idw
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
I assumed the code would delete the emoji after sending it but it only deletes it sometimes
wait no im dumb I think I know why
Why?
227 total results
discord.User
discord.User.accent_color
discord.User.accent_colour
discord.User.avatar
discord.User.banner
discord.User.bot
discord.User.can_send
discord.User.color
discord.User.colour
discord.User.create_dm
discord.User.created_at
discord.User.default_avatar
discord.User.discriminator
discord.User.display_avatar
discord.User.display_name
discord.User.dm_channel
discord.User.fetch_message
discord.User.history
discord.User.id
discord.User.jump_url
like user name
ping when respond
ctx.author?
is there a list for all the ctx
It should return discord.Member
.rtfm commands.Context
20 total results
discord.ext.commands.Context
discord.ext.commands.Context.author
discord.ext.commands.Context.can_send
discord.ext.commands.Context.channel
discord.ext.commands.Context.clean_prefix
discord.ext.commands.Context.cog
discord.ext.commands.Context.fetch_message
discord.ext.commands.Context.guild
discord.ext.commands.Context.history
discord.ext.commands.Context.invoke
discord.ext.commands.Context.me
discord.ext.commands.Context.pins
discord.ext.commands.Context.reinvoke
discord.ext.commands.Context.reply
discord.ext.commands.Context.send
discord.ext.commands.Context.send_help
discord.ext.commands.Context.trigger_typing
discord.ext.commands.Context.typing
discord.ext.commands.Context.valid
discord.ext.commands.Context.voice_client
They're called attributes
How do i add a dropdown with a page
Alr danke
how can i do automatic bot testing?
i need some basic idea to start, i am new to automated testig
is there a way to select users in a select ui?
yes, but the limit would be 25 users
im not sure how i would get the member object in the options.
options = [
discord.SelectOption(label=self.client.get_guild(get_guild()).get_member(user[0])) for user in get_all_motm_by_id()
]
im not sure how to give him the self value in that case
How can I enable the message_content intent?
my bot got verified and the message_content intent activated, how can I enable it?
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-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)
Pycord
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
yw
CA how often does a heart beat occur?
2-3 seconds or like 100-200 ms?
or somewhere in between
'TwoCaptcha' object has no attribute 'normal'
what does that mean?
You join the Server and send this random message?
not related to Pycord.
how would i go about organizing buttons in a list by a number in them?
like i have a list of buttons and the labels are "button 1", "button 3", "button 2" but how would i get it to have the buttons in order?
Sort the buttons in a list and add them to your view in order
oh ok
Hey all, I have a hopefully quick question. I am attempting to run my Bot but each time I run it I get:
Cannot find reference 'Bot' in 'init.py'
I have downloaded pycord with pip and verified that it is in my available packages for python.
show the pip list
and the code pls
full traceback thanks
in what format for code?
pep
bot = discord.Bot()
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}.')
testingServers = [1062908565431521363]
@bot.slash_command(guild_ids=testingServers, name="work", description="Checks to see if I am online")
async def work(ctx):
await ctx.respond(f"I am working! \n\nLatency: {bot.latency * 1000} ms.")
bot.run('token')```
.
File "C:\Users\Akira\Documents\Python\DiscordBot\Test\slashcmds.py", line 3, in <module>
bot = discord.Bot()
^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'```
you sure that is the right pip list?
pip list right?
Pycharm?
pycharm indeed
you have to use the pycharm terminal
on the bottom right corner there is something called packages
you would have to install the packages from there
or that ^
no the pycharm terminal is the same terminal
did you restart IDE?
just restarted my computer after posting the second code snippet
did you uninstall discord.py before installing py-cord or after?
uninstalled discord.py after installing py-cord, was wondering if that might be a potential cause
do you have a file named Discord?
anywhere on the computer or in one of the python directories?
in the same folder you are running your bot from.
how are you running your bot
Aren't you using PyCharm? Reinstalling from your terminal won't do anything
PyCharm creates virtual environments for every project, anything you do in your normal terminal will have no effect on things you're running from PyCharm
it doesn't grab from the site-packages folder?
Can you try it with the pycharm terminal
running it in the pycharm terminal
I mean the installation
no the pycharm terminal is the same terminal as the regular terminal
you would use the "python packages" UI
using this?
and right click one to uninstall
ok, py-cord was deleted, will try installing it through pycharm
hmm, got it through pycharm, still not working. Should I just use a different IDE?
this is what I see in the pycord installation
that might be the issue, though why I don't see any of the other folders like are shown on Git I have no idea
How can I get which user deleted a message?
nvm i think i figured it out
yep i did
what am I doing wrong? I created a .gitignore file and this is the content; venv/ . I don't want it to upload the venv directory to github.
wait if you don't upload the venv how do you start the bot?
someone opened a issue on my github project with this content, so I don't know...: The venv directory should be ignored, and definitely should not be pushed to GitHub. It's supposed to be on your computer and stay that way, never getting uploaded.
Vincent moment
so should I remove it or not?
dont ask me lol
lol
i want to make a new command creator like slash_command or bridge_command
can i get some place to start? (to learn or something like that)
.rtfm channel.voice_states
is this wrong way? I don't know why ping command not show
class Testbot(commands.Bot):
...
@slash_command(name="ping", description="ping", guild_ids=[...])
async def ping(self, ctx):
...
yes thats wrong
commands dont go inside the bot subclass
they go inside a cog class
.guide
aha
check it out
thanks!
is it a bad idea to start an event loop in a thread?
because i want to make the bot send messages in a thread but that doesn't seem to work
Pass the main event loop to the thread?
Also why not use ext.tasks ?
i'll check that out l8r
Hi ! Just updated my bot for the first time in ages, and i get this when reloading one of the cogs ```
File "/.../cogs/antiping.py", line 17, in on_message
mutedRole = discord.utils.get(guild.roles, name="|Muted|")
AttributeError: 'NoneType' object has no attribute 'roles'
File "/.../cogs/antiof.py", line 27, in antibot
guild = msg.channel.guild
AttributeError: 'DMChannel' object has no attribute 'guild'
```py
@commands.Cog.listener()
async def on_message(self, msg):
guild = msg.guild
mutedRole = discord.utils.get(guild.roles, name="|Muted|") # LINE 17, FIRST ERROR
@commands.Cog.listener("on_message")
async def antibot(self, msg):
guild = msg.channel.guild # LINE 27, SECOND ERROR
Has msg.guild been deprecated ?
One message removed from a suspended account.
Hi, i have to questions:
1 - can we somehow get something like a user.banner.url ?
2 - I heard that discord.py v2.0 have a banner method, can i use discord.py 2.0 with pycord?
for the first question i found this code (working)
req = await bot.http.request(discord.http.Route("GET", "/users/{uid}", uid=user.id))
banner_id = req["banner"]
if banner_id:
banner_url = f"https://cdn.discordapp.com/banners/{user.id}/{banner_id}?size=1024"
Link: https://stackoverflow.com/questions/68689808/accessing-a-members-banner-in-discord-py
.rtfm on_reaction
what is the difference between raw reaction and normal one?
You're using msg.channel.guild
msg.channel is returning a DMChannel, the error is explicitly telling you that
.rtfm DMChannel.guild
Target not found, try again and make sure to check your spelling.
No such attribute.
- Read the docs
- No, conflicting libraries
raw gets triggered despite the cache.
.rtfm DMChannel
16 results
discord.DMChannel
discord.DMChannel.can_send
discord.DMChannel.created_at
discord.DMChannel.fetch_message
discord.DMChannel.get_partial_message
discord.DMChannel.history
discord.DMChannel.id
discord.DMChannel.jump_url
discord.DMChannel.me
discord.DMChannel.permissions_for
discord.DMChannel.pins
discord.DMChannel.recipient
discord.DMChannel.send
discord.DMChannel.trigger_typing
discord.DMChannel.type
discord.DMChannel.typing
12 results
discord.on_raw_typing
discord.on_raw_message_edit
discord.on_raw_reaction_add
discord.on_raw_thread_delete
discord.on_raw_message_delete
discord.on_raw_reaction_clear
discord.on_raw_reaction_remove
discord.on_raw_integration_delete
discord.on_raw_bulk_message_delete
discord.on_raw_reaction_clear_emoji
discord.on_raw_scheduled_event_user_add
discord.on_raw_scheduled_event_user_remove
means this it will get triggered every time?
Yes
how do i change on_reaction_add(reaction:discord.Reaction, user:discord.Member): to data?
i am lost
is this like payload.message etc?
read the docs
Pycord
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
One message removed from a suspended account.
use bot var to store a single db connection?
One message removed from a suspended account.
One message removed from a suspended account.
yeah so use a bot var, which you can access from ctx.bot.conn
?tag botvar
No tag botvar found.
ugh one sec
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
One message removed from a suspended account.
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
thats dpy and not pycord 
but anyways, interaction.client.collection
One message removed from a suspended account.
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
Here's the slash basic example.
.guide
see that too
I got a warn, so its not a good idea xd
For sending a discord crashing video
lmao

By advice from a discord bot-help server, I uninstalled discord.py v2 and then installed py-cord 2.3.2 into PyCharm. There were two py-cord packages, one named py-cord and one named py-cord2, but py-cord2 was broken.
Upon installing py-cord 2.3.2 (and verifying that 2.3.2 is the latest version on Github too), PyCharm complains that discord.app_commands and discord.app_commands.tree are invalid/non-existent imports.
The other server suggested I try asking about this here, with the statement "that should not happen" because py-cord is a direct fork of discord.py.
Did I do something wrong, get a bad package, or any ideas?
Can you show the pip list?
An attempt to install py-cord2 generated another error involving reading the package, not just the description.
PyCharm complains that discord.app_commands and discord.app_commands.tree are invalid/non-existent imports
yes because pycord does not implement slash cmds using a tree. check out the guide
.guide
@proud mason Been doing so, thanks. I just wanted to make sure I didn't get a bad package or bad version through PyCharm. I think you confirmed that I probably have the right thing.
yeah lol 👍
Does a giveaway Bot require a database?
yes and no. depends on how much you rely on discord data
Is discords data reliable?
i mean, it has to be 
Fair enough
I say it only depends on whether you intend to persist A LOT of data in the backend. Reasons to persist bot-side data include that your bot won't track messages (or events such as reactions) which occurred before your bot joined the server, or occurred if your bot is in the server but shut down/offline for any reason. At that point your bot only tracks the last 5000 messages it saw. So if your bot ever goes down, has to be restarted, etc, it loses track of anything/everything that happened before it shutdown. If you won't persist A LOT of data, you can just serialize objects or arrays (aka lists/dicts/etc) in Python, but if you will persist A LOT or if you'll persist for A LOT OF TARGETS then you'd benefit from a relational database.
Oh okay thank you, i can work with that knowledge now
One message removed from a suspended account.
.guide
has a good writeup on that
Hey, Do i need a database to store channel ID's? (for eg storing the channel where a giveaway is sent, or can i have it so they choose whilst creating gw)
One message removed from a suspended account.
If your intention is to post a message and track reactions as "raffle tickets" then you need to know the Guild ID (unless the bot only lives in one Guild which is what API calls a server) and yes, you should store the Channel ID and the Message ID and you can also store the specific Emoji ID which represents the reaction itself, so you can provide options.
Sorry for ping-spam if that happened to anybody. I switched that from an @ to a reply for clarity.
But again, you can store all of that just as easily as a class-instance attribute and serialize the instances to disk. You don't need a relational database for that, especially if it's a custom bot for just 1 server
It probably will not be one server, meaning i would want to use a relational DB for this (would MYSQL be a good option?)
Sorry for so many questions
postgres, mysql are good options. you can also use sqlite if you want a file based db rather than a server based db.
i suggest postgres as it is considered the fastest
Server based DB can store more DB right? Does postgres use SQL?
yes and yes
Depends on what you intend to host it on. Debian and forks like Ubuntu default to Maria, which is a fork of MySQL. Oracle's actual MySQL is fine too. I also really like SQLite, which is A LOT EASIER than MySQL, especially for making backups and such, and doesn't require separate hosting. MySQL/Maria is a solution for 88 different services which all need to access the same database, where the DB lives on one server and the remote clients live on other servers.
What would be the fast, and not super hard to learn/understand DB?
So if you want users to log into your website and sign up for giveaways on their Discord server, then yes, MySQL is a better choice.
A website would not be involved, all discord side
SQLite, for fast/easy and also for bot-only, no website.
there isnt a very big difference between using postgres, maria, mysql
This dosent include bot advertising websites, right just checking
Spoken like someone who knows a half dozen SQL syntaxes and forgot that the S stands for Structured, not Standard :-) I have that problem sometimes too.
Alright, I tried MYSQL yesterday just exploring it and it was confusing (but i hadnt went to learn what to do in it or anything) so what would be my best next option? postgres?
I have linux on my PC (partioined) if that matters as you guys mentioned it earlier.
dont expect many differences with postgres
Bot advertising websites should really only contain a link to your website, where your invitation link should live.
👍
Hm, I mean of course if i put some time, and effort to see how to use MYSQL/postgres either should work, currently those are my two options witch should i use
The concept of Relational Databasing is not particularly easy to learn, but nothing says you have to learn all about Relational Data Architecture just because you're using a Relational Database. If you just want to learn about SQL for now, with the option to expand as you learn more, then absolutely any engine you choose is fine.
Alright, beleive it or not currently im learning SQL (in school, ig that still counts)
Just do yourself a favor and decide, before you start, whether you might ever want to expand into multi-client, because migrating from file-based local databases to web-based databases is a b***h. You have to learn a whole new style of configuration and maintenance on top of a whole new SQL syntax, and fix all your code to use the new thing.
Thank you for letting me know this it will come in useful, much appreciated for all the help.
Just want to put this out there: If you decide on a web-based database, like MySQL, don't shy away from good servers like Debian/Ubuntu because they use Maria (the MySQL fork) instead of the original. You literally use the same Connector for both, whether it's Python or PHP or DotNET or embedded C/++, you literally use the same commandset at the CLI, and you literally have all the same features and SQL syntaxes. Where Maria diverges are all "extras" and not "basics"
What are the main differences between maria and MYSQL? & Why would i use a web DB over a sofware sorta DB
I just said main differences are non-existent, as far as you should be concerned at your stated skill level. And I said before that a web-based DB is for when you have multiple clients, like 2 websites and a bot, all using the same data, but not all hosted on the same box. A file-based DB can do the same thing if your bot and webserver are all in the same server environment, but if you needed to access a file-based DB from a different network/internet host you would have to jerry-rig your own SSH interface or web-api type thing to make that happen.
MySQL for example allows direct TCP/IP connections to be SSL-encrypted, but if you wanted to imitate that with SQLite you would have to set up Apache (or whatever webserver you like) to proxy database queries for you.
Thank you, just one last question (hopefully), If the bot is being hosted on another PC than it is being created/tested on will that affect the database?
That would be a good reason to use MySQL/Maria instead of SQLite. I'm not sure about postgre. Never used it. I believe it is file-based like SQLite.
Well, that's not right.
You would probably want segregated test and production databases anyway.
So MYSQL (as i've at least used it before, but obviously not my only option) would be the way to go
no. postgres is just like mysql, a server based db
so what's the right awnsrr to this
i prefer postgres over mysql as it is slightly faster and has some more datatypes from what ik
okay so I'm thinking I will do further research then decide what dB to use
Dumb Python question - can one add async methods to the constructor by using an __await__ method? Would this work for pycord Cogs?
from https://stackoverflow.com/a/58976768/18366895
(ignore args, just curious if the the general concept is sound)
class Foo:
def __init__(self, settings):
self.settings = settings
async def async_init(self):
await create_pool(dsn)
def __await__(self):
return self.async_init().__await__()
I don't follow the "why you would want to do this"
you can be even crazier
class Foo:
async def __new__(cls, *args, **kwds):
obj = super().__new__(cls)
await obj.__init__(*args, **kwds)
return obj
async def __init__(self, *args, **kwds):
pass
foo = await Foo()
but you dont need to do all that
The idea is to run async commands when the class loads. You can't do it in __init__
you can use asyncio.create_task
Just seemed so dirty. But okay, I'll go back to using that.
its the cleanest tbh
def __init__(self, some_arg: str):
self.some_attr: str = some_arg
@staticmethod
async def create_new(some_arg: str) -> "SomeClass":
# Quotes around type-hint-for-return (above) allow you to type-hint without import errors on account of class
# being not fully initialized
return SomeClass(some_arg)
some_class = await SomeClass.create_new(r"test")
???
Stupid question, but will this also contextualize non-async code in a way that doesn’t block? I have an identity library that doesn’t support async itself. I thought there was a way to wrap calls so that they don’t block the main thread but I could be dreaming that
asyncio.to_thread allows you to call blocking func without blocking the event loop. i think you can use this along with asyncio.create_task
ive realised that asyncio has everything lmao
Would recommend PostgreSQL
mmm so when i try and link a user in a response, sometimes i get the actual user, but most of the time i just get a highlighted <@[user id]> can the bot just not see those users somehow?
IIRC, it's something to do with Discord's crappy caching on your local client, not the bot.
so it's just on my end and some users might see the actual name?
or will all users have to restart discord for it to update
Some, yes. Note that you do have to share a server with the user, just to make that clear for it to even have a chance to work. I don't think you're able to enumerate random user Ids.
But even in times where you do, I have seen it break
yeah i understood some aspect of the bot needing to 'see' the user someway
To be clear, it's not anything to do with the bot, I'm talking about yourself.
The <@userid> syntax in messages are locally rendered.
One message removed from a suspended account.
and for some reason the id to user name link isnt cached, is there any way to force the link somehow or cache update?
like from a local perspective, not the bot
Not that I'm personally aware of. It's definitely frustrating.
One of the most common bugs I come across on Discord.
k thanks though!
ask in dpy server
What method are you generating those by? discord.User.mention or discord.Member.mention or something else?
I save the user id and then use
content = f'<@{user}>'
this is for helping in a game where people could have a bunch of characters that link to one discord user
i also disable allowed_mentions for users
might be a possible culpret
want to basically link the discord user, but not ping them
That shouldn't have any bearing on whether it's shown.
@alpine kernel Try getting a handle on a User object such as via bot.get_user(id) and then using user_object.mention("message")
okey, yeah that might help
My syntax is bad, sorry.
f"{user_object.mention} rest of message"
Unfortunately that won't have any effect, either, because mention() literally just does what he's doing now
discord/user.py lines 251 to 254
@property
def mention(self) -> str:
"""Returns a string that allows you to mention the given user."""
return f"<@{self.id}>"```
Sorry then.
worth a shot =T
correct answer ^
Yeah, it's a super-frustrating issue for sure, I'd do everything I could to try to mitigate it, too. Just trying to save you the headache since I know I've gone through this whole process, too.
Strangely I don't see it mentioned a lot.
@alpine kernel So when this occurs, does the Mention still work as expected on the targeted user's end?
I dunno, i'll have to do more testing
I'd have to imagine yes, since it's a caching issue and presumably the targeted user has their own information
If so, then just to clarify for anybody affected by the bug, you could append something like:
f"({user_object.name}#{user_object.discriminator})"
after the mention itself.
yeah I'll have to figure something like that out
I'm reading through https://guide.pycord.dev/interactions and when I follow the links to User Commands and Message Commands it bounces me to the raw Discord API documentation on JSON interchange. Does that mean these features are not implemented in py-cord? Edit: Sorry about the raw string. I was trying to avoid embed-spam Discord attaches to web-links and then realized that not being able to click on a link is worse
Oh, nevermind. I found a working link further down the page. There are a couple of 404s in between there though.
man, frustrating day heh cant even get get_user to work, just returns none >.<
@alpine kernel I just discovered bot.get_or_fetch_user(id) while looking at my own project. fetch_user is evidently for working around the cache problem, and get_or_fetch_user checks the cache then fetches as needed.
mmm ok i'll check that out
oh i was using get_user in an async that's probably why it returned none
need more coffee i guess
Didn't Python give a Trace on it?
yeah, it just returned none though, cant you not do non async calls in an async function? need to go back and read what's ok and whats not heh
also, just started using my bot on my game friends server, is there a way to update the bot without interrupting the connection? i'm just running the bot locally and just re executing it when i update. might just make a separate bot for doing testing/dev
You can only use await inside a function marked async, but you can always call non-async from anywhere.
well that's still weird, get_user wasnt working but fetch_user did
Again, get_user looks in the cache and fetch_user makes a Discord API request
and was just using ctx.author.id to look up
Or so the docs imply
oh, well that's weird that i wasnt in the cache heh
You know most civilized nations have some law that if you have less than $1 of their currency, you are technically "vagrant." Better hit up an ATM and get yourself some cache!!!
any suggestion on this? heh
Supposedly you can call bot.reload_extension(name, *, package=None) at runtime. You would have to create a regular command to make the bot do that, though, so you could tell it what to do while it was online. And of course stop it to refresh the new code.
ok i'll check it out
i was doing something crazy on a project i was working on a few months ago heh
@commands.command(name='restart')
@commands.is_owner()
async def _restart(self, ctx):
"""Restarts the bot, can only be used as the owner of the bot"""
#await interaction.response.send_message(interaction.user.id)
sys.argv.append("--owner_restart")
sys.argv.append(str(interaction.channel.id))
embed = discord.Embed(title=":arrows_counterclockwise:", description = f"Restarting...")
await interaction.response.send_message(embed=embed)
os.system("cls")
os.execv(sys.executable, ['python'] + sys.argv)
was in discord.py
still seemed like a wonkey way to do it though
I find programming in Python to be like watching a movie. Check all your rational thought processes at the door and prepare to work around the runtime.
?tag restartcmd
Tag Credit: discord.py server
The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().
Do use:
- run your bot in a process manager such as:
- systemd
- openrc (gentoo, devuan)
- runit (void linux)
- supervisord
- upstart (old ubuntu)
- docker
- manually reboot it
Do not use:
- a bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
- subprocess.call (you will eat your memory up by not letting your old processes die)
- os.exec*
thanks!
mmm now sometimes either my command line gets hung up or people 'stress testing' it is making the command line stall
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
fixes itself by 'nudging' the command line
why do you use interaction?
i think it's an error in the package
?
So I have this weird thing with Context Menu Commands. This is how/why I ended up trying py-cord in the first place. I finally got py-cord to remove old/removed Context Menu items by calling bot.registercommands() but the same thing happens with py-cord that happened with discord.py -- The item shows up where it should, under Apps, when I right-click a user name, but then I get a little popup telling me that "This interaction failed" which a little while later changes to read "The Application did not respond"
?tag idw
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
Not sure what your point is. I can't describe it any more fully than I already did.
async def ciao(ctx: discord.ext.commands.Context, member: discord.Member):
await ctx.respond(f"Ciao {member.mention}")```
sync_commands does nothing, but register_commands makes it work. "Welcomes User" appears in the Apps part of the Context Menu, as already described. Clicking on it results in a little popup in the message part of Discord which first says "This interaction failed" and then changes to "The Application did not respond" after some time
can you remove : discord.ext.commands.Context?
async def ciao(ctx, member: discord.Member):
await ctx.respond(f"Ciao {member.mention}")```
Produces the same thing.
@discord.ext.commands.is_owner()
async def shutdown(ctx: discord.ext.commands.Context):
await ctx.message.delete()
await ctx.send(f"{bot.user.name} bot engine shut down by {ctx.author.name}")
await bot.close()
print(f"{bot.user} Bot engine shut down")```
This one works just fine.
It's a /command though.
which client do you use?
I think I just found the problem.
?tag clients
No tag clients found.
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
ok?
are you sure, that you have py-cord and nothing else installed?
Yep. I double-checked my venv after removing discord.py
Hi, sorry for the inconvenience, I've been looking for a solution to my problem for about 2 hours and I haven't found anything on the internet or in a post here.
So, I want to make a DropDownMenu where the values are put from the command, example :
class MyView(discord.ui.View):
#options = options that i want
@discord.ui.select(
placeholder = "Choose a Flavor!",
min_values = 1,
max_values = 1,
options = options
)
async def select_callback(self, select, interaction):
await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")
@bot.slash_command(name="view", help="Change the area of the character")
async def view(ctx):
options = [ # the list of options from which users can choose, a required field
discord.SelectOption(
label="Vanilla",
description="Pick this if you like vanilla!"
),
discord.SelectOption(
label="Chocolate",
description="Pick this if you like chocolate!"
),
discord.SelectOption(
label="Strawberry",
description="Pick this if you like strawberry!"
)
]
await ctx.respond("t", ephemeral = True, view = MyView(options))
character.save_to_db()```
But I can't find anything on how to do it, and on my own I have no idea.
Is there anyone who has a solution ?
did you uninstall py-cord and reinstall it?
I installed py-cord fresh after that, yes. I think PyCharm uses PyPi
I never had py-cord and discord.py installed alongside each other.
I removed discord.py, then I installed py-cord.
which version?
2.3.2
Can you create a new project and try it there again?
Sure. That will take a few though.
Done. I totally deleted every __pycache__ and PyCharm's .idea and the existing venv directory. I then re-created the project, re-created the venv, re-installed python-dotenv and py-code -- run the bot, joins the server, updates the context menu item, but clicking on the context menu item results in that little box which says "This interaction failed" and nothing else. No errors, no python trace, nothing.
For clarity: When building my bot's "invitation link" in the OAUTH2 configuration, I very carefully combed through all the possible scopes alongside the Discord API docs and I selected absolutely every scope except the 4 or 6 marked "Requires approval from Discord" which are about DMs and RPC.
I modified the code thus:@bot.user_command(name=r"Welcomes User") async def ciao(ctx, member: discord.Member): print('user command triggered') await ctx.respond(f"Ciao {member.mention}")
and the print never occurs either, so it seems like the interaction is never relayed to my coroutine.
man, still having issues with get_user() and get_or_fetch_user(), i enabled member intents, dunno if it's some sort of permission blocking, but certain users just return with None =T
for what do you need it?
getting a user info for a guild
yeah, it's just not really clear what exactly i need, I would expect it to throw a permissions error if i didnt have access :T
Could you show exactly how you're using the methods?
You don't need intents to fetch users, only server members
No, you don't need that for users
only server members
^ fetch_user doesn't require any permissions or intents
OK, my bad. Just trying to help.
yeah, i researched everything seems like its not a permissions thing, give me a sec to reorder my code
@commands.slash_command(name='howmany', description='1')
@discord.option("type", choices=['Users', 'Characters'], default='Users')
async def _howmany(self, ctx, type:str):
print(f"Got request to howmany {type} by {ctx.author} - <@{ctx.author.id}>")
if type == 'Users':
users = json.load(open('data/users-by-id.json', 'r', encoding='utf-8'))
l = len(users)
user, info = random.choice(list(users.items()))
try:
print(user)
#got_user = await ctx.guild.fetch_member(int(user))
print(got_user)
got_user = await self.bot.get_or_fetch_user(int(user))
ment = got_user.mention
except discord.errors.NotFound:
ment = 'USER NOT FOUND'
await ctx.send_response(content=f'_ _\nThere are {l} users in my database, {ment} is the coolest', ephemeral = True, allowed_mentions=discord.AllowedMentions(users=False))
dont bash me for not using a db to get stuff please, slowly building this stuff heh
Are you sure you're actually getting an ID from your json? And yeah, don't use json
yes
i manually confirm that the id retrieved IS a user on the server where i'm using the command
instead of using decorators, you can form the select menu manually py select = discord.ui.Select(...) # note the uppercase Select async def callback(interaction): ... select.callback = callback view.add_item(select)
did you convert the ID to int
yes, it's up there in the command
Could you try to only run fetch_user, instead of get_or_fetch?
yeah
I'm able to manually check my ID works, and some others IDs do work
ok
yeah it just throws discord.errors.NotFound
then the ID's definitely wrong
fetch_user is guaranteed to work on any real user
as for the initial issue, unlike fetch_user, get_or_fetch_user explicitly doesn't error if the fetch fails; it'll just return None
https://docs.pycord.dev/en/master/api/clients.html#discord.Bot.get_or_fetch_user
hmph that's annoying, i'll try and triple check everything i guess
can you show the intents?
wouldnt be out of the ordinary for me to be missing something small
intents = discord.Intents.members + discord.Intents.default()
MyBot = discord.Bot(intents=intents)
but from the above intents doesnt seem to be the issue, i've also just ran with default intents
Yeah no, you definitely have an invalid ID then
fwiw, if you manually input the IDs one common misstep people make is copying the message ID instead of the user ID
You're most likely saving your IDs incorrectly somehow in your json file
unless you manually input them and copied the wrong id, yeah ^
yeah i'm doing something wrong but I dont know what,
so if I do
user = "user number here"
print(type(user))
it says str object is not callable, am I dumb shouldn't that work? this isnt even using json, just a string
i think i'm missing something about working in async functions
do you have a variable called type
god i'm dumb
rip
oof
ok so that kinda leads me to another question, i want to use stuff like 'class' as a parameter name at least to SHOW on a option for a command, but it shadows is there any way to display it as one name but change how the variable is named?
only thing I can think of is just using something like class_
in Option(...) set name
ok I tried that, didnt work but i'll try it again and not be dumb
https://docs.pycord.dev/en/master/api/application_commands.html#discord.Option.name
The name of this option visible in the UI. Inherits from the variable name if not provided as a parameter.
it SHOULD work but options have a rocky history so who knows
yeah I might have also been impatient sometimes things take a while to update
You might have to refresh your Discord client for them to update with Ctrl + R
oh that's helpful thanks
Hey all hope you are fine ! I need to do a modal with a select menu to select a server role, how can I do that ?
You can't
Hmm I can create options looping the roles no ?
modals don't support select menus at the moment
Ah :p
ok to conclude, i'm really dumb i was making the discord ID mapping by copying id from the search window, which was copying the message id, not the user, rip about an hour of data entry -.-
Ok so I have to make a view
rip
yep, can only be on messages for now
also note you can't filter which roles are displayed; it will always display all roles in the guild
Have you got an exemple to make that ?
Here's the dropdown example.
ah i guess it's not displayed there
it depends on what you want
All roles
If you don't mind all guild roles showing, you can just use the discord.ui.role_select decorator
this won't have an options arg, you just use it
are there message command groups? like slash command groups... but for message commands
nope
alright cool thanks
Back again with the same issue, different question
For python packages, I assume they are generally saved to the site-packages folder of the most recent python version?
so If I get this
File "C:\Users\Akira\Documents\Python\DiscordBot\Test\pycord\slashcmds.py", line 3, in <module>
bot = discord.bot()
^^^^^^^^^^^^^
TypeError: 'module' object is not callable```
Bot not bot
bot has to be uppercase?
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
@mild sigil
\o
I think about that, but how i get the value of select?
select.value
you can access it in the callback still
Juste select.value ? Don’t have to take it somewhere before ?
nop
well, select.values as always
Yeah sure.
Well, i just wanted to make things more complicated than they are. 
Thank Nelo. 
Hello all, I am just wondering. For some reason the character ^ is being removed from my file name when sent using my discord bot. Does anyone know why this is happening?
I'm back for the same problem, i got an error trying to run the code :
NameError: name 'select' is not defined
So in know what's the error mean, i just don't know what i should put to correct that.
💀 It literally tells you what to do. Define "select"...
Thanks Aqua, but if i ask it's because i don't know if there's a specific way.
How do you grab the created_at for an AuditLogEntry fetched through message.guild.audit_logs?
Nevermind i found by myself.
im pretty sure that character cant be in the file name
Not even if its escaped? As I do need it in my filenames. Or is there any work around?
for some odd reason custom emojis get converted to their :name: version once a response is edited is there any way to fix that?
does everyone role have external emoji perms?
Is there a way to not return an interaction response?
wth lol why would they make it like that
works now ty
unfortunately no
yes
if you use button
ctx.defer()
Unfortunate. My way of "getting around" it in a Modal dialog is to send a response then delete it directly after.
in my error handling for permissions error I get a list of strings representing the missing permissions. How do I create a Permissions object from that type of string so that I can compare them to other Permissions objects?
How would i let my bot send a message in another discord?
you need to get an admin to invite the bot and then give it he appropriate permissions
Lexion, is correct your bot needs to be in the discord server for it to send messages.
But how would i refer to that specific guild so i can send messages there?
https://discordjs.guide/preparations/adding-your-bot-to-servers.html#bot-invite-links
Follow this guide (I know it says discord.js but it is the same for pycord) on how to get a bot invite link. Then give it to an admin of the server you want your bot to be in and yell them to click it.
Can you show your error handling code where you get the string of permissions.
You could turn the list into a dict where the keys are your list of permissions and the values are all true or false depending on your situation.
Than pass it to the permissions constrctor like in the accepted answer of this SO post
https://stackoverflow.com/questions/1496346/passing-a-list-of-kwargs
I decided on doing it another way and not overcomplicate things.
👍
I decided to just send the default error message string instead of making my own for each error.
on a similar note, why doesn't discord.errors.Forbidden get caught by the on_error handler?
on_error catches errors in events
my error was raised by a message that failed to send in another event handler
Is an on_command_error handler not an event?
It's an event in your app. It's not an Event in Discord.
I see
In Server-Client programming, you gotta keep 'em separated.
alright thamks
Should i store every user who joins a giveaway in a database? then either delete at end of gw or smth
Yes? What else would you do?
Whilst googling ^^^ i found some people using methods such as getting the reactions in a user variable and random.choice from there
@limber urchin ?
can I use dicord.Greedy in type hints to expect the name of a Cog?
doesn't seem like it from the docs so nvm
Do you mean the name of a class which inherits/extends from Cog or do you mean the value of the cog.name attribute from an instance?
Tekmunkey u got any idea? sorry you were nice to me and helped yesterday so mby u know dis
That really depends on how long a giveaway lasts. If it's 5 minutes or less, it wouldn't hurt anything if the bot crashed in the middle and the giveaway had to be restarted after the bot was restarted. If it's a day or two, then definitely persist the data involved.
Also thanks for saying I'm nice. Mostly people tell me I'm "aggressive" and "scary" or that my terminology is too technical.
I try to be nice!
@fervent cradle Also, gigabytes of storage are cheap AF so don't worry about deleting giveaways after they're done. Make a command Guild admins can use to review past giveaways.
A whole novel worth of raw text is to a gigabyte of storage is as a fist-sized rock is to a 5-gallon bucket.
oh okay thanks
And I'm talking Tolkien/Martin/Jordan novels, not little paperbacks intended to be read on a flight :-) Huge storage is CHEAP and text is itty bitty!
I am trying to setup to basic events, on_member_join and on_member_leave. When leaving and joining the server with the bot my bot is not sending in the embeds that are stated.
Upon checking console no error or stack trace appears.
@bot.event
async def on_member_join(member):
ch = bot.get_channel(1065333151632719977)
joinem = discord.Embed(title=f"**{member.name} Joined!**", description=f"{member.name} Joined our server, welcome! :grin:")
await ch.send(embed=joinem)
import discord
from discord.ext import commands
PrizeEmbed=discord.Embed(title="quick test",description="testing")
class create(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def create(self,ctx):
Input = await ctx.send(input(embed=PrizeEmbed))
InputNew = await ctx.send(f"{Input}")
def setup(bot):
bot.add_cog(create(bot))``` (first response) Nothing is being sent, no error either
Fixed but it was due to the input, how can i get a users input after an embed
I'm trying to start the bot coroutine using the .start() method, then once the bot has started, start a command line tool coroutine. However, when I create both tasks, the command line tool starts first and freezes the program waiting for an input. Any idea how I can make sure the bot coroutine starts fully before I start the command line tool?
the bot coroutine also freezes the program
I suspect it's because both are trying to access the terminal at the same time
Not directly pycord related, but perhaps might be the answer to my issue ...
I am posting to a webhook with a payload. I am intentionally doing some error testing by passing a bad embed field. I could've sworn that discord was more verbose about pointing out issues, but all I got was
{'embeds': ['0']}
How do I get better insight into issues? Pycord has a webhook client; would using that give me additional context?
A friend of me try to launch a discord bot, but when i launch the code, nothing happen. No error, if there's a print the content of the print appear, but the code just end ignoring the bot.run.
If someone know why. 
& the bot.run return none.
Can you show the pip list?
@opal geyser let you do it.
?
He's the friend who got the problem. x)
(I'm the friend, just joined the server ^^)
I copy-pasted the "Minimal Bot with Slash Commands" example here (https://docs.pycord.dev/en/stable/quickstart.html) and same problem : the program finishes immediatly...
Pycord
This page gives a brief introduction to the library. It assumes you have the library installed. If you don’t, check the Installing portion. A Minimal Bot: Let’s make a bot that responds to a specif...
what is the python version?
3.11 is fine with the version, mhm
Hello everyone,
I'm trying to have, as answer to a slash command, a message including multiple select menus
So I have something like this basically as view,
class MyView(discord.ui.View):
@discord.ui.select(...)
async def callback_shape(self, select, interaction):
...
@discord.ui.select(...)
async def callback_color(self, select, interaction):
...
callback_shape gives me the selected shape
callback_color gives me the selected color
I'd like to have 'red' and 'triangle' available somewhere together
Is that possible, or I'm joust doing this the wrong way ?
Are you show the token is the right one? can you try a new one
do you have intents enabled at the website?
yep, just regenerated a new token, same problem
I tried with all intents disabled and enabled, nothing changes
yes, only slash
sure, I also tried the closest I could be from the documentation example, and same result
the code is fine
mmh, it's on my end I guess
Can you try it with cmd?
I changed to PyCharm because it makes the stuff so much easier
Yes I think I'll reinstall it too
Thanks a lot for your help !
\o
why arent button callbacks working? i'm using it correctly like this
channel = self.bot.get_channel(1065374067898732555)
buttonSeat = discord.ui.Button(label=f'Seat {num}', style=discord.ButtonStyle.blurple, emoji='🪑')
async def buttonSeat_callback(interaction: discord.Interaction):
full code here (cant send due to char limit)
buttonSeat.callback = buttonSeat_callback
view.add_item(buttonSeat)
await channel.send(embed=embed, view=viewpoo)```
for some reason it doesnt work with less than 2 buttons
Trying out UI components for the first time, how do I defer and interaction and delay it for some minutes to process data? here is my code :
class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
@discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎") # Create a button with the label "😎 Click me!" with color Blurple
async def button_callback(self, button, interaction):
await interaction.defer() # Defer the interaction
time.sleep(1) # Sleep for 1 second
embed = discord.Embed(title="Button clicked!", description="You clicked the button!") # Create an embed
await interaction.response.send_message(embed= embed) # Send a message when the button is clicked
interaction.response.defer
And then you must use followups you can't use response.send_message
Can you edit my code as an example?
No
I have no idea if it's intentional or not.
But it's related to the fact that webhooks related stuff use everyone perms. And interactions are based on webhooks
dont use time.sleep
it will block the whole bot
You can't assign the callback in the loop like that. Rather, subclass the button
oh ok
avatar_url is now avatar.url for the member object right?
Pycord
v2.0 introduced new Discord features and deprecated some old ones. Part of the redesign involves making application commands and components. These changes include a new Bot class, ui.View, and a ne...
Also I am having trouble trying to find what emoji it is telling me is invalid as this is all it says.
Do you know what one it could be telling me.
can you show the emoji at the code?
There you go I am on mobile so that is why it is a pic.
Or anyone else know?
The last one should be an issue. You are passing in a string for a custom emoji, as opposed to a discord.Emoji or discord.PartialEmoji object
So is it the modlogo emoji that is making the problem happen?
yes
So how would I make it work then? I have forgotten some things as it has been a bit since I coded?
.rtfm discord.partialemoji
19 results
discord.PartialEmoji
discord.PartialEmoji.animated
discord.PartialEmoji.created_at
discord.PartialEmoji.from_dict
discord.PartialEmoji.from_str
discord.PartialEmoji.id
discord.PartialEmoji.is_custom_emoji
discord.PartialEmoji.is_unicode_emoji
discord.PartialEmoji.name
discord.PartialEmoji.read
discord.PartialEmoji.save
discord.PartialEmoji.to_dict
discord.PartialEmoji.url
discord.PartialEmoji.with_state
discord.ext.commands.PartialEmojiConverter
discord.ext.commands.PartialEmojiConverter.convert
discord.ext.commands.PartialEmojiConversionFailure
discord.ext.commands.PartialEmojiConversionFailure.args
discord.ext.commands.PartialEmojiConversionFailure.with_traceback
And where would I put that tho?
in place of the emoji
this is a link to the documentation of discord.PartialEmoji
Ah so it would be emoji =discord.partialemoji.id
uhh no
do you know basic python
Yes.
ok, then why are you assigning a class attribute
to an argument
when the argument takes the class
why do i get Can't keep up, shard ID None websocket is 10.6s behind.? i googled that it has to do with blocking events, but doesn't that send heartbeat blocked for more than X seconds?
probably an issue with one or many of the following:
Discord,
Your host,
Your code
what kind of code would cause the behind error tho
But we can rule out Discord.
things that are blocking
Pycord
This is a list of Frequently Asked Questions regarding using Pycord and its extension modules. Feel free to suggest a new question or submit one via pull requests. Coroutines: Questions regarding c...
Strange that it worked before but now it errors.
I can't figure out what I'm doing wrong here. I'm getting no error, but the bot is not removing any nicknames.
@bot.slash_command()
@option("role")
async def removenicknames(ctx, role: discord.Role):
for member in role.members:
await member.edit(nick = None)
my intents:
intents = discord.Intents.all()
intents.members = True
intents.message_content = True
intents.presences = True
bot = discord.Bot(intents=intents)
Mmm...after print role.members I get nothing. Therein lies my issue
Slash Commands usually do not give the full information. You can try accessing the cached values in bot.guilds.
ahh, okay! Thank you! I'll give this a shot
Seeming to be a permissions error...which is confusing considering intents are enabled, bot has admin, and other admin roles are being ignored.
I seem to have been inadequately skipping over users with higher perms. 
fun
yea..I'm still really confused about that role.members interaction tho...
print(role.id) yields proper id so the object is being properly called in the option, but when I print role.members I get nothing - mind blown
try to get the role from ctx.guild.roles
still yields nothing somehow. So bizarre...the original role is coming from an @option("role")
later defined as role: discord.Role in the function.

Am I calling role.members inaccurately?
I can't seem to get a proper list with it for any role
therole = discord.utils.get(ctx.user.guild.roles, name="T1")
print(therole.members)
hmm what about bot.guilds and then guild.roles
as long as you get a role, it should be fine.
I tried really hard to figure out what you're suggesting by this, but I failed...
I don't get why the role is being properly input but role.members is not doing its thing 🥹
Are you suggesting that I need to try a for loop taking the desired guild from bot.guilds and then receiving the desired role from guild.roles and then receiving the desired list from said role? something like:
g = <guild id>
for g in bot.guilds:
print(g.roles)
for T1 in g.roles:
print(T1.members)
42 total results
discord.Button
discord.Button.custom_id
discord.Button.disabled
discord.Button.emoji
discord.Button.label
discord.Button.style
discord.Button.to_dict
discord.Button.type
discord.Button.url
discord.ui.button
discord.ui.Button
discord.ui.Button.callback
discord.ui.Button.custom_id
discord.ui.Button.disabled
discord.ui.Button.emoji
discord.ui.Button.from_component
discord.ui.Button.is_dispatchable
discord.ui.Button.is_persistent
discord.ui.Button.label
discord.ui.Button.refresh_component
.rtfm intents
42 total results
discord.Intents
discord.Intents.DEFAULT_VALUE
discord.Intents.VALID_FLAGS
discord.Intents.all
discord.Intents.auto_moderation_configuration
discord.Intents.auto_moderation_execution
discord.Intents.bans
discord.Intents.default
discord.Intents.dm_messages
discord.Intents.dm_reactions
discord.Intents.dm_typing
discord.Intents.emojis
discord.Intents.emojis_and_stickers
discord.Intents.guild_messages
discord.Intents.guild_reactions
discord.Intents.guild_typing
discord.Intents.guilds
discord.Intents.integrations
discord.Intents.invites
discord.Intents.members
is there any way to fix this?
400 Bad Request (error code: 30032): Maximum number of application commands reached (100).
Awwh, you have to wait 24 hrs to commit new ones :(
Rate limiting stuffz :/
you can't commit more than 100 in a specific period of time iiuc
ah, ok. Thanks 🙂
nope. you have to wait.
Can someone confirm that my intents are not botched?
intents = discord.Intents.all()
intents.members = True
intents.message_content = True
intents.messages = True
bot = discord.Bot(intents=intents)
I'm getting an error that says
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ClientException: Intents.members must be enabled to use this.
are all the intents enabled in the panel
THE PANEL
Going check now! lolo.,l
yes :(
wait. change it to say this.
intents = discord.Intents.all()
bot = discord.Bot(intents=intents())
:O
and if that doesnt work then this
intents = discord.Intents.all()
bot = discord.Bot(intents=intents)
did it work?
No, this is what I'm already using
and intents is not callable :/
and what about this?
That's what I'm currently using
Such weird problems tonight 
I'm using this
client = discord.Bot(intents=intents)```
And it's working fine for me 🤔
I wonder if there is some update I need or something...it's weird because this has never been an issue before. I noticed that guild.members was returning partially so I tried calling guild.fetch_members() and got that error :(
hmm... weird
get rid of the following:
intents.members = True
intents.message_content = True
intents.messages = True
you are trying to pass intents twice
I also thought that was the issue, but the error persists upon their removal
checking - sec
omg I found the issue. My persistent view.. 
Agghh, what an L...
I think I have my persistant view bot setup such that it overrides my commands...
💀 I'm going to pretend I know what you mean.
I really appreciate your time. <3
how to make discord button
Learn all about implementing buttons in your Discord Bot using Pycord.
yes lol
e = None
@bot.event
async def on_ready():
e = "hi"
@bot.command()
async def printHI(ctx):
print(e)```
this prints none
why is that
Variable scoping
Use bot vars if you want to retain values across functions
?tag botvar
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
thanks!
Careful with the names tho
yeah i will
so when I am using tasks.loop ctrl + c does not stop the bot, any fixes?
when i remove the taskName.start() from the on_ready event ctrl + c works just fine
How can I make a beautiful field in embed? So that everything would be on the contrary
there it gets out of bounds and it is already unclear
how to hide the embed color bar like this
Change the color the same as the embed
You can't change how embed fields appear other than inline
What can I do that somehow separate and everything was clear? Due to the large number of letters, a line break is made and the participants are confused about their status and rating
You can't do anything, the only thing you could do is reduce the number of letters. And it will look different for everyone depending on how wide their screen is. For mobile users, way less letters are going to line break.
@commands.Cog.listener()
async def on_member_join(self, member):
channel = await self.bot.fetch_channel(1039573169968787567)
await channel.send('test', view=WelcomeButton())
Anyone knows, why the command isn't work?
Saying "isn't work" is useless, explain what's wrong
My bot does not send a message to the channel. He has all the rights to do so.
Error messages?
no, none at all. That's the funny problem.
Do you have member intents enabled? And why are you defining the listener in a cog?
yep, have them on in the dev portal. I also have the welcome message in my main bot in a cog
Do you have them enabled in the code too?
member intent correct?
Hey, i'm using a basic bot with slash commands and ctx.send works but ctx.respond is giving this error, does anyone know what could be causing this?
?tag idw
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
That is never helpful or even anything but agitating to folks. At the very least, change the bot-spam to explain that users should specify their Python version, use of IDE, IDE version, and preferably provide the snippet of code that generates the error. Also you specifically are way too quick to resort to idw. You did it to me a couple of days ago when I DID post the code and the mysterious results of it.
@formal field Another user had that same question last night. You're taking too long to send your reply to the Discord Interaction itself. You have 3 seconds to give it any reply at all, unless you defer it, and if you defer it then you have 3 minutes to put in a followup.
Understood, thank you very much. I'll give that a try now.
@formal field https://stackoverflow.com/questions/73361556/error-discord-errors-notfound-404-not-found-error-code-10062-unknown-inter
interaction.response.defer()
#
# Do stuff before sending a reply
#
interaction.followup.send()
Managed to get it working this way:
@bot.slash_command()
async def download(ctx, url:str):
await ctx.respond("Downloading video, please wait.")
await asyncio.ensure_future(download_video(url, ctx))```
Thanks again for the help
for shash commands use ctx.defer()
@formal field It makes more sense to send the response before doing the paperwork on it, unless it relies on data processing to form that response.
Hm, seems a bit different to asyncio.ensure_future, i'll see if i can find anything in the docs
File "/usr/local/lib/python3.10/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: InteractionResponse.defer() takes 1 positional argument but 2 were given```
can you show the code again?
dont put anything in the ()
Tried that, it's giving:
File "/usr/local/lib/python3.10/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InteractionResponded: This interaction has already been responded to before
its should look like this```py
await ctx.respond()
await ctx.defer()
await download_video(url, ctx)
.
.
I think you should use ctx.respond() to give the "downloading" status update, but then you need to hand off to something else entirely. The error shown above indicates that you have to pick between respond and defer.
The something else should be a separate coroutine which does the download and reports back to the invoker via a new message to server
that would be ctx.respond
async def download(ctx, url: str):
await ctx.respond("Downloading video, please wait.")
await do_download(ctx.guild.id, ctx.channel.id, ctx.message.author.id, url)
async def do_download(guild_id: int, channel_id: int, user_id: int, url: str):
#
# Download your file from wherever
#
user: discord.User = await bot.fetch_user(user_id)
guild: discord.Guild = await bot.fetch_guild(guild_id)
channel: discord.abc.Messageable = guild.get_channel(channel_id)
async def do_download(guild_id: int, channel_id: int, user_id: int, url: str):
#
# Download your file from wherever
#
user: discord.User = await bot.fetch_user(user_id)
guild: discord.Guild = await bot.fetch_guild(guild_id)
channel: discord.abc.Messageable = guild.get_channel(channel_id)
await channel.send(
content=f"{user.mention} Your file is ready!",
file=discord.File(
fp="local/path/to/downloaded/file",
filename="User-Friendly Name To Send With Message"
)
)
I did not run this, but I believe this is the droid you're looking for.
Edit: About an hour after posting I noticed an error in PyCharm. The file parameter can't just be a filename, it must be an instance of discord.File. Fixed that!
@formal field
thank you very much, will implement it
import discord
from discord.ext import commands
PrizeEmbed=discord.Embed(title="What do you want to giveaway?",description="")
class create(commands.Cog):
def __init__(self, bot):
self.bot = bot
class Req(discord.ui.View):
@discord.ui.button(label="I dont need any reqs", style=discord.ButtonStyle.primary, emoji="❌")
async def button_callback(self, button, interaction):
await interaction.response.send_message("This is where giveaway gets made")
@discord.ui.button(label="I would like to add some reqs", style=discord.ButtonStyle.primary, emoji="✅")
async def button_callback(self,button,interaction):
await interaction.response.send_message("yes")
@commands.command()
async def create(self,ctx):
EmbedMsg = await ctx.send(embed=PrizeEmbed)
PrizeInput = await self.bot.wait_for("message",timeout=120)
await ctx.send(f"How long would you like the giveaway for {PrizeInput} to last?")
LengthInput = await self.bot.wait_for("message",timeout=120)
await ctx.send(f"How many winners should their be for this giveaway?")
WinnersInput = await self.bot.wait_for("message",timeout=120)
await ctx.send(f"Should their be any requirments for this giveaway?",view=Req())
def setup(bot):
bot.add_cog(create(bot))
``` "Command create was not found" worked fine before adding buttons?
pls use the py if you create the code blocks
fixed
so whats the issue, im so confused
@fervent cradle Not sure how you can be at a beginner's skill level and not use an IDE that annoyingly whines about PEP8/formatting errors. May I suggest PyCharm Community Edition? It should not only help you format things so most Python programmers can read it intuitively, but it should also complain about errors like this one before you try to run the program.
Im using VSC, and have been using it fine for a while
And it doesn't tell you how many spaces to put between the end of one class block and the start of another, or between function defs?
It took me quite a few reads before I figured out that your class and its method are both lowercased 'create'
So bot.add_cog(create.create(bot))
Just saying. It'd be nice if you'd help folks who want to help you.
Do you have a raw except block in that code?
Change except: to except Exception as e:
That will break stuff
Use PascalCase for class names
I do. I was responding to FoolishBlue's code posting.
I'm actually quite annoyed by PyCharm/PEP8 wanting me to use lower_case_style instead of camelCase for function arguments and variables, but I go with it because it makes the code more readable for folks who don't program in umpteen lingos.
You are defining the commands inside the view class rather than the cog class
Js programmers are used to camelCase but since I started out with python, I'm more friendly with snake_case
C-like programmers. JS is C-like :-)
so indentation issues
Tbh you could just pass the guild, channel and user objects so no need to fetch them again. And since you are having a reference of them in the function, you can use them even if they drop out of the cache during execution. Api calls are really slow
No. View class should be outside the cog class
import discord
from discord.ext import commands
PrizeEmbed=discord.Embed(title="What do you want to giveaway?",description="")
class Req(discord.ui.View):
@discord.ui.button(label="I dont need any reqs", style=discord.ButtonStyle.primary, emoji="❌")
async def button_callback(self, button, interaction):
await interaction.response.send_message("This is where giveaway gets made")
@discord.ui.button(label="I would like to add some reqs", style=discord.ButtonStyle.primary, emoji="✅")
async def button_callback(self,button,interaction):
await interaction.response.send_message("yes")
class create(commands.Cog):
def __init__(self, bot):
self.bot = bot``` better?
@fervent cradle What The Om Nom Nom is saying is that I missed the 2nd class definition.
o
Yes member and guild both. Does the cog load? Add a print statement in the cog init
Does the event fire? Check that with a print statement too
Python typehinting please
Even dinking around in my private dev server where I'm the only user, I've found that unless responding directly to a discord.Message or discord.ext.commands.Context which already contains those objects, it is best to use guild.fetch_whatever and bot.fetch_whatever due to client-side caching issues.
That may be just my experience, but it derives my methodology.
done
All good. I have it already done. 😄
Ctx.guild ctx.author and ctx.channel are guaranteed to be present in a Slash cmd from what i remember. Unless it isn't a Slash cmd (i didn't check)
If you are worried about the cache, you should use partial objects rather than fetching them if you just want to send a message
Oh lol
That's a great tip!!! I will give it a shot.
Yes but both buttons can't have same callback class name. Also, where is the cmd now 
just didn't send cmd code, and yeah thanks
How can I send another context or message?
await channel.send(file=discord.File("willkommen.png"), view=WelcomeButton())
i mean, this should be one message
"text"?
channel.send(file=discord.File("willkommen.png"), view=WelcomeButton(),"Test")
Im getting this when trying to put the users input in a message.
@commands.command()
async def create(self,ctx):
EmbedMsg = await ctx.send(embed=PrizeEmbed)
PrizeInput = await self.bot.wait_for("message",timeout=120)
await ctx.send(f"How long would you like the giveaway for {PrizeInput} to last?")
LengthInput = await self.bot.wait_for("message",timeout=120)
await ctx.send(f"How many winners should their be for this giveaway?")
WinnersInput = await self.bot.wait_for("message",timeout=120)
await ctx.send(f"Should their be any requirments for this giveaway?",view=Req())```
Oh aight
PrizeInput would be a discord.Message object
Access the content on it
wym
.rtfm message.content
ty
Position args go before kwargs 👀
You can always pass content="test" if you want to pass as a kwarg
a.k.a "Test" has to be first.
Yeah i know thats what id normaly do, but i just added it there so he knew roughly what to do, sorry for any confusion
?
Ah nvm
Are their any examples of this? Im still struggling to see how id use it.
What do you need an example for? You got a message object and access the content attribute from it
Im just struggling to see what i do with it, & where
well what are you trying to do?
I want to have the users input, in the next message if that makes sense
use PrizeInput.content when sending the message 
Yeah? Send the content of your message object in your message
Oh i was thinkin smth completly different 💀
I think you've been told like 10 times to learn Python before making a bot, right?
I know python well enough to create what i am creating
Mhm, sure
Got it working
Btw @limber urchin can you make a tag for xy problems ||i think dpy has one if you wanna steal||
Yeah sure, I'll try
Thanks
?tag xy
An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.
You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.
That's a good one.
Is there a way to get the raw json of on_message?
raw json?
you mean just a json file?
I want to serialize all messages and events into JSON so I can ingest them into Elasticsearch
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
- MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
- PostgreSQL (Very popular and robust SQL based database management system)
- MySQL (Another popular SQL based system, good start for learning SQL)
You only get a message object with on_message. There is no json involved
I know I want to turn that message into an NDJSON so I can ingest it later into elastic
What´s the maximum time of the delete_after parameter? I did not find anything about it in the documentation
So each message is a line of JSON
10 minutes
Then you need to parse it yourself, like I said, you only get a message object
or 5 minutes, im not sure anymore
so it´s ok to use 600 seconds? or better 599?
ah ok i understand
Cursed regex it is for parsing then
async def on_message(self, message: discord.Message):
logging.info(f'Message from {message.author} (ID: {message.author.id}) in {message.channel} attachments {message.attachments} '
f'mentions {message.mentions}: {message.content}')
You also need to specify in your privacy policy that you're logging messages, as it's against ToS to store any data that you don't actually need
Cool
Can anyone tell me why I always get the "application not responding" message?
The embed is still displayed but I don't know why I always get the "Application not responding" message....
class ButtonTicketCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
self.bot.add_view(TicketButton())
self.bot.add_view(CloseButton())
@slash_command(description="Erstellen eines Support Tickets")
@commands.has_permissions(administrator=True)
async def createticket(self, ctx):
channel_id = TICKET_CHANNEL_ID
ticket_embed = discord.Embed(title=f'Herzlich Willkommen beim Support!',
description=f"""Wenn du ein Support Ticket eröffnen möchtest drücke bitte auf den "📩 Ticket erstellen" Button!
\nEin Supportmitarbeiter wird sich anschließend schnellstmöglich um dein Ticket kümmern und sich mit dir in Verbindung setzen!""",
color=ORANGE)
ticket_embed.set_thumbnail(url=f"{ctx.guild.icon}")
await self.bot.get_channel(channel_id).send(embed=ticket_embed, view=TicketButton())
def setup(bot):
bot.add_cog(ButtonTicketCog(bot))```
Because you're not responding to the command
you have to use ctx.respond(), without it you will get the error everytime you run the command
Okay so I'll just change this line:
await self.bot.get_channel(channel_id).send(embed=ticket_embed, view=TicketButton()) ```
In this:
```py
await ctx.respond(embed=ticket_embed, view=TicketButton())```?
you know what they are doing?
@green hinge I recently had the same problem. On the Discord Developer page, where you set up your App or Bot, there are a lot of demands for "a redirect URL" which is just confusing language. If you're on the first item, there are several of those demands which are OPTIONAL, and should all be blank if you're using a library like py-cord, because they redirect Discord messages from the WebSocket aka Gateway API to the HTTP aka REST API.
The only redirect URL you should fill in is on the OAUTH2 config page
The first one always sends the embed to the channel with the channel_id. So in this case TICKET_CHANNEL_ID.
And in the second case the embed is always sent to the channel where the slash command is executed or do I have something wrong?
yes
so you could just send a message like that the ticked was created
Also, can I somehow use ctx.respond to send the message only to a specific channel at a time?
You can still send the embed in the other channel, but you have to respond with something to the command or you'll get an error.
Ah okay so I can also just return a message with "Embed has been created"? 🙂
yes
Uhh that's not related to the question?
Yeah, that looks like an AI trying to respond to a question lol
Lmao
^
Is that a user self bot trying to help?
lmao
Okay thanks it works! 🙂
Why does pycharm issue such a warning? After all, the author has guild attribute
https://docs.pycord.dev/en/stable/api/models.html#discord.Member
Pycord
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
How can I fix the error in this case without sending a message?
create_channel = await interaction.guild.create_text_channel(
u'\U0001F4CB-{}'.format(interaction.user.name), overwrites=overwrites, category=category)
embed = discord.Embed(title=f'Herzlich Willkommen beim Support!',
description=f"""Hallo {interaction.user.mention}!
\nDein Ticket wurde erfolgreich erstellt! Schreibe dein Anliegen in den Chat und warte bis sich ein {admin_role.mention} oder {mod_role.mention} bei dir meldet.
\nUm das Ticket zu schließen drücke bitte auf den Button 🔒 Schließen""",
color=ORANGE)
msg = await create_channel.send(embed=embed, view=CloseButton())```
what?
Sounded like it was. Same error I was dealing with when I ended up here to begin with. I'll mute the channel.
When I click the button from the created embed I also get "This interaction failed" but my new room is created anyway....
class TicketButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='Ticket erstellen', custom_id="TicketErstellen", style=discord.ButtonStyle.secondary,
emoji='📩')
async def callback(self, button, interaction):
user = interaction.user
admin_role = discord.utils.get(interaction.guild.roles, id=ADMIN_ROLE)
mod_role = discord.utils.get(interaction.guild.roles, id=MOD_ROLE)
category = discord.utils.get(interaction.guild.categories, id=TICKET_CATEGORY)
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
user: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True),
admin_role: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True),
mod_role: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True)
}
create_channel = await interaction.guild.create_text_channel(
u'\U0001F4CB-{}'.format(interaction.user.name), overwrites=overwrites, category=category)
embed = discord.Embed(title=f'Herzlich Willkommen beim Support!',
description=f"""Hallo {interaction.user.mention}!
\nDein Ticket wurde erfolgreich erstellt! Schreibe dein Anliegen in den Chat und warte bis sich ein {admin_role.mention} oder {mod_role.mention} bei dir meldet.
\nUm das Ticket zu schließen drücke bitte auf den Button 🔒 Schließen""",
color=ORANGE)
msg = await create_channel.send(embed=embed, view=CloseButton())```
you are not responding to the button
How can I do that?
you do it with the interaction
What can I put behind here so I don't have to send a message or anything?
interaction.response.
You have to send a message
I can use this:
await create_channel.send(embed=embed, view=CloseButton())
await interaction.response.edit_message(view=self)```
? 😄
Does discord store the users messages (aka accessing how many they've sent)? or do i need a db
Any idea?
If i set something up on on_message to add a message to user every message, then stored in a database would that work?
Wait this wouldnt count old messages?
Yes or send a normal message and hide it
I'm trying to access the response message (that is, the message the bot sends after a user invokes a command)
My understanding is that it's interaction.original_response(), but I'm getting Unknown webhook. What fundamental thing am I missing?
class SentinalConfirmation(discord.ui.View):
def __init__(self, sentinel: SentinelTimelockRequest, callback: callable):
super().__init__(timeout=300, disable_on_timeout=True)
self.callback = callback
self.sentinel = sentinel
self.add_item(EventSelect(sentinel))
# [...snip...]
class EventSelect(discord.ui.Select):
def __init__(self, sentinel: SentinelTimelockRequest):
self.sentinel = sentinel
super().__init__(
...
)
async def callback(self, interaction: discord.Interaction):
""" This is failing """
msg = await interaction.original_response() # type: discord.Message
embed = msg.embeds[0]
embed.fields[2] = '\n'.join(self.values)
self.sentinel.conditions = self.values
await interaction.response.edit_message(embed=embed)
Anyway to get a users total message count?
Don't crosspost
dark yk?
It's a separate question from my thread 🤷♂️
You're asking twice
You can just ask in ur thread
I could, yes. But this is a separate, potentially-easier question for people to answer, versus the specific thread that many people may not care to visit. Don't overthink it.
anyways, help i've been tryna figure this out
please
.rtfm Member.history
1 results
Much appreictaed, should i then store the amount i get back from that in a DB or without be fine?
Can I run a loop only every 60 days?
@tasks.loop(seconds=60)```
That looks like 60 seconds
Yeah im just unsure what the better option would be
Is it possible?
@tasks.loop(day=60)```
I think the maximum is every 24 hours or?
Or can I extrapolate the hours to 60 days and do it that way?
@tasks.loop(hours=1440)```
loop only accepts s/m/h. That might be your best bet. Although you might be better off giving a specific time or using something like aiocron if you need it to be precise (like midnight, etc)
More general Select questions (not a crosspost 😉 )
When selecting values in a Select and drop focus, it submits the value, which then appears to refresh the UI item.
Is there a way to retain the context of the selected options so that they still have the check mark next to them?
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.get_application_command
How can I use this to create a mention to a group command? I've tried:
bot.get_application_command("group command").mention
I also tried setting type to discord.commands.SlashCommandGroup
Pycord
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
(When I use the mention, it just displays the command name in plain text, not as a link)
...
@discord.ui.select(
custom_id="app_dropdown",
placeholder = "Choose the position to apply into!",
min_values = 1,
max_values = 1,
options = [
discord.SelectOption(
label="Option 1",
description=""
),
discord.SelectOption(
label="Option 2",
description=""
),
discord.SelectOption(
label="Option 3",
description=""
)
]
)
async def select_callback(self, select, interaction):
await interaction.response.send_modal(TeamAppModal(title=f"Apply to the team."))
class TeamAppModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="question 1"))
self.add_item(discord.ui.InputText(label="question 2", style=discord.InputTextStyle.long))
self.add_item(discord.ui.InputText(label="question 3"))
async def callback(self, interaction: discord.Interaction):
selection = "" # <<< Make this the "label" selected in the dropdown.
embed=discord.Embed(title=f"{selection} Application")
embed.set_author(name=f"{interaction.user}", icon_url=interaction.user.avatar.url)
embed.add_field(name="question 1", value=self.children[0].value, inline=False)
embed.add_field(name="question 2", value=self.children[1].value, inline=False)
embed.add_field(name="question 3", value=self.children[2].value, inline=False)
await interaction.response.send_message(embed=embed)
...
Can I get the value they picked in the dropdown and pass it to the embed title?
selection = "" # <<< Make this the "label" selected in the dropdown.
Just pass the selection as an argument to the modal's constructor and use it from there
wdym
class TeamAppModal(arg, discord.ui.Modal): like this?
def __init__(self, selection, *args, **kwargs):
self.selection = selection
...
Then use self.selection wherever you want in the modal
ah ok
how do I pass selection to the modal?
just
Get the selection in your select_callback and pass it with TeamAppModal(selection, title="...")

