#Basic Pycord Help
1 messages · Page 10 of 1
I'm sure it.only displays 15 and you can type to search other channels
like no
min_values: The minimum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.
max_values: The maximum number of items that must be chosen for this select menu. Defaults to 1 and must be between 1 and 25.
its 25
ahhhh. i didnt know i could type in it. i didnt even try. but this helps i guess
so i think its able to display 25
the dropdown shows only top15 channel/categories. but i can type and search for the ones that arent shown
okay, didnt know
channel_types: A list of channel types that can be selected in the menu. This is only valid for selects of select_type discord.ComponentType.channel_select.
think it can help to delete categories
Channel and user selects work differently
yea. im trying to play with it. but i cant make it work. also, if its possible, how i do make it only show channels from just one category and not all?
you can't. But at that point, you can just use a normal select menu
You'd use a normal select menu instead
Y you type so fast
I hate squids
but then, i will only be able to show a maximum of 25 channels right? this way, i can show all of them, but choose a maximum of 25
rn it doesnt, but it will in future
or just use an autocomplete option
each sel menu is 5 options, and each view is 5 sel menus for a max of 25 options
that helps me choose more than 1 channel?
each select menu is 25 options for a maximum of 125
Each select menu has 25 options at max
ooh. i read that wrong. that helps. thanks guys
depends on how you implement it, yes
okay. then ill look into autocomplete first. cz i dont wanna be hitting limits
Is Pycord better than Discord Py? had seen pycord and wanted to try it out but it has a lot of things that are different in discord py
it's personal preference
is it possible to send an attached text file under the bot's message embed? When you send a file it goes under your message, but when sent by bot it's above its message (if it's an embed)
How I can edit description in embed?
Its goes with the title
embed = discord.Embed(title="Text", description="Text.", color=...)
Hi all. Im using py-cord 2.4.1. My on_member_update is only triggering when a change is made to the bot account but not anyone elses. I think I have done everything correctly with Intents.
how is bot defined?
bot = discord.Bot()
you never passed the intents to your bot
I see thanks. This code used to work a while ago. I guess that has changed? Now it should be this?
bot = discord.Bot(intents=discord.Intents.all())
Yep, that did it. You guys rock! Thanks
Somehow my bot with message intents (both in code and on the dev portal) and admin perms doesn't react to on_message events at all
Any ideas why?
Hmm okay, what's the biggest difference between these 2 ?
I did change the intents within the last 24 hours, don't know if that matters anything
mainly the application command structure
How did you define your intents?
can you send me an example
Here's the slash basic example.
how is your on_message event defined
well, you never initialized the parent cog class
not sure if that directly causes the issue
You edit the attribute.
Such method doesn't exist.
also the name arg should just be left blank unless you are dispatching your own events
looks like this now
that's what caused the issue, thx
and i read that the original dpy is no longer updating but why there update the lib ?
Cogs don't need super().init btw
awesome thx
was confused how this'd been working for over a year if it wasn't correct
if you don't initialize the class, you didn't initialize the methods no?
None of my cogs have super().init
they have a base class where they base their cogs on
Oh?
But then how have my cogs been working just fine in the past?
Any ideas why message.content prints an empty string?
@core.Cog.listener()
async def on_message(self, message: discord.Message):
"""Event for when a feedback message is sent.
Parameters
------------
message: discord.Message
The message that was sent."""
if message.guild.id != core.config.rip_guild_id or message.author.bot or not core.is_valid_thread(message.channel) or message.channel.parent_id != core.config.feedback_channel_id:
return
if core.is_feedback(message.content):
tags: list[discord.ForumTag] = [tag for tag in message.channel.applied_tags if
tag.id != core.config.bell_tag_id]
await message.channel.edit(applied_tags=tags)
do you have message_content intents?
figured I'd only need message and message content no longer exists, as it's not mentioned in the docs under on_message
thx
For my own sake please reduce those if conditions gawd 😭
figured it'd be most efficient to return asap
One if condition does the same thing
Python checks conditions in order
First to last
Why would you use an and lmao
Just group the conditions into one if with or
I don't wanna, just figured that's what you suggested I was like hell nah, not gonna add that
meant or, nvm
tho I feel like ors just make it ugly and harder to read
Whatever you want
hmm ig this doesn't look too bad
now you got me thinking
how do i make it so that instead of disabling buttons in a paginator, it would just cancel the paginator on timeout?
What is "cancel the paginator" supposed to mean?
what was the error one for the guild_only decorator?
commands.PrivateMessageOnly
I found it for dm_only but not for guild_only
The reference manual that follows details the API of Pycord’s bridge command extension module. Bots: Bot: Methods def add_bridge_command,@ bridge_command,@ bridge_group. AutoShardedBot: Commands: B...
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
how can i create dropdowns in cog
Why should it not be possible to do it?
this
async def cancel(
self,
include_custom: bool = False,
page: None | (str | Page | list[discord.Embed] | discord.Embed) = None,
) -> None:
"""Cancels the paginator, removing all of its components from the message.
Parameters
----------
include_custom: :class:`bool`
Whether to remove components added via custom views.
page: Optional[Union[:class:`str`, Union[List[:class:`discord.Embed`], :class:`discord.Embed`]]]
The page content to show after canceling the paginator.
"""
items = self.children.copy()
page = self.get_page_content(page)
for item in items:
if (
include_custom
or not self.custom_view
or item not in self.custom_view.children
):
self.remove_item(item)
if page:
await self.message.edit(
content=page.content,
embeds=page.embeds,
view=self,
)
else:
await self.message.edit(view=self)
i have a slash command. it sends a view in the response. i also passed an argument in the slash command. how can i use it in the view's callback method
is it possible to send a sticker using bot?
put your view in a class
I did make a class. Called ChannelSelect which inherits the discord.ui.View
Is that what you mean?
then add an argument in your class
and call it with self
Oh. So like. In the slash command response when I do view=ChannelSelect()
I would be doing view=ChannelSelect(variable)
Like that?
@tropic dawn 
yeah.Just remember to initiate the variable in the init of your class
no problem
I was trying things like interaction.selected_options
I guess that's for command interactions and not interaction response
You'd have to subclass the paginator and override on_timeout to do what you want
was reading the docs on discord.ext.commands.Bot.wait_for and saw this
am i capable of using an asynchronous function here, with an argument?
and if so, how would i do so
i have a /command on a cog but its not load in my bot
i use prefix command but i only want to add one /
the files is load and the other command of the cog(prefixed work)
do i need to do other thing than simply load the cog ?
It's a sync function, not async
?tag slashnoshow
No tag slashnoshow found.
.tag slashnoshow
Application Commands Not Showing Up?
- Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
thanks
womp :(
thanks for the answer tho
Np
It's something like
def my_check(message):
if message.author == ...:
return True```
yeah i had a def as it is
my whole problem is that i had to use
requests
if there’s no way to async it though then i’ll just have to take that L
you can use aiohttp and call it with asyncio loops/run
Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they are not asynchronous. Otherwise known as blocking.
Aiohttp is a low level threading and http handler. Py-cord already uses aiohttp, so it should be installed. An example of code using aiohttp and Py-cord:
async with aiohttp.ClientSession() as cs:
async with cs.get('https://httpbin.org/json%27') as r:
res = await r.json() # returns dict
await ctx.send(res['slideshow']['author'])
For more help, see aiohttp's documentation
OP needed an example where there are no async or await keywords present.
you CAN call async functions within a "normal" function.
But to cover this particular case i need more information about what needs to be done
Or do i got it wrong?
oh good point, thanks
so i’ve seen lol
i entirely switched to aiohttp ages ago thanks to it
didn’t know how to actually use it in this specific case
Is there a way to make animated emojis more consistent in embeds? The bot is in the server where all the emojis exist and yet in other servers they will either work or just not. The bot has administrator permissions and I even tried setting the channel permissions to allow external emojis.
The format of the emoji in the embed is 
Is it because the other servers block external emojis?
Well in the other server I am testing in, some of them work and some dont
It also is administrator in it and the channel has external emojis enabled for the bot
For example here page 1 of a paginated embed
and this is page 2
Turns out the guild default role needs to have it enabled.
How can I edit the paginator in the view ?
I have sent a select menu in an ephemeral night and now I want to create the paginator with the pages in the callback function and then edit the message so that the select menu is removed and the paginator is displayed in the ephemeral night. Does anyone know how I can do this?
paginator = PaginatorView(cards_info)
await paginator.respond(interaction)
await interaction.response.edit_message(content=f"Kategorie {selected_category} ausgewählt.", view=paginator)
class PaginatorView(Paginator):
def __init__(self, cards_info):
self.pages = self.create_pages(cards_info)
self.custom_buttons = [....]
super().__init__(
pages=self.pages,
use_default_buttons=False,
custom_buttons=self.custom_buttons,
timeout=300,
author_check=True,
)
I'm new to bot making: I started making a bot and I tried making a simple slash command like in the docs, but I didn't found how to limit a slash command to only one guild . Thanks :D
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = True
intents.presences = True
#bot = commands.Bot(command_prefix='!', intents=intents) # useless, only /command
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
@bot.command(description="Sends the bot's latency.", guild_ids=[833351790719926292]) # is "guild_ids" the right thing?
async def test(ctx):
await ctx.respond(f"Pong! Latency is {bot.latency}")
bot.run('TOKEN')
Hi
You can define guild ids within the slash command decorator
Like guilds=[00000,00001,00002]
(Dont push me into it. Maybe its guild_ids)
@robust turret 

just use slash_commands

Imagine
The possibilitys
If you put the stuff, that the lib is doing, onto a WEBSITE

so, if you use bot.command() and your bot is commands.Bot, the commands will be a prefix command. If you change it to discord.Bot than bot.command() will be a slash command
bot.command works with discord.Bot as a slash command
Funfact, you can still predefine a prefix and havin both.
I thought he is knowing about the slash command stuff since he asked how to limit them, not creating
i think he's using commands.Bot
Because this is the first thing you will find in the docs
Yea, exactly
Well than just alter the decorator
To @slash_command(name="stuff", guild_ids=[stuff])
Im on mobile maybe im havin a typo
Viola, slash command
If u want to have them global, just remove the guild_ids thingie
U ok with this?
Is it possible to defer an autocomplete function? I have a large list that it is getting from an endpoint and the time it takes exceeds the duration of the interaction
nope
note that you only need to return 25 values instead of the whole array.
Ah, thank you
Yes, thank you
Anyone who knows a bit about Paginator? 🙂
If the user cant valid a command check in pycord, is it then possible to hide a command from a user?
As an example to an userslash command from a user which cant validate an command check?
nope
Thank you anyway ^^
Whats the correct way to use await bot.sync_commands() ? Im keep getting Failed to reload cogs.atlyr: 'NoneType' object has no attribute 'guild_ids' but doesnt matter if I add guild_ids= or commands= in the sync_command variable
Im also using this version py-cord-dev==2.5.0rc5
For a reload command?
Yes, not sure if unload are working properly yet but mainly reload
Did you also have uninstalled py-cord?
Yea both uninstall and build up venv from scratch too
Did you add a command to sync?
I've this, im new to py-cord but think its correct or really close to correct
@commands.slash_command(name="reload", description="Reload a cog", guild_ids=[1084058095774355490])
@commands.has_permissions(administrator=True)
async def reload(self, ctx: discord.ApplicationContext, extension: str):
try:
self.bot.reload_extension(extension)
command = self.bot.get_application_command(extension)
await self.bot.sync_commands(commands=[command], guild_ids=[1084058095774355490])
await ctx.respond(f"Reloaded {extension}")
except Exception as e:
await ctx.respond(f"Failed to reload {extension}: {e}")
is the file name and the command name the same?
When reloading im using /reload cogs.[filename]. So thats the extension variable. Reloading itself works but syncing slash command are failing
?
@little cobalt Can you give me a bot name? That's literally the only reason I havent made a good one yet.
and a fitting icon mybe
I also need a good bot name ;3
The cog file is not same as the command names no if I understood correctly 😅
But you know what "NoneType" means?
Yea it gets no value from guild_ids, it is specified in sync and the commands
Remove the ctx.respond?
Can you use custom emoji in a select menu?
Yes
"Expected Interaction or BridgeContext"
You pass ctx.interaction
Not just ctx
something like ctx.interaction
PartialEmojis are a no-go then?
I get:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options.0.emoji.name: Invalid emoji
when passing a custom emoji as a PartialEmoji
Should I cast str on it 🤔
You can just pass it as <:emoji:id>
Hmm, yeah but I figured it'd be easier to just do use the __str__ method but that doesn't seem to be working for me
I'd rather look into why than do the manual <:emoji:id> method because not all the emojis I have are custom
To elaborate: after casting str() on an emoji, it still returns a PartialEmoji object regardless of whether the emoji is custom or not
I'll investigate further because there's no way the __str__ function is broken
Here's the background task example.
Try it and see
If i have a dynamic buttons, eg, a button creates another view and that view has dropdown menus, etc, etc... do I need to create a random customid for each of those components? @lofty parcel
no
no
For example, do those ids need to be completely unique per each creation
unless it is a persistent view
no
sorry, i am trying to implement persistent views
it doesn’t have to be random
Or can i simply just have "my_id1", "my_id2", and it doesn't matter how many people interact with it
@shell radish can u help me with this 
Here's the background task example.
@shell radish i'm correct?

im following it 
so 00:52:00 am UTC?
Is it because PersistentViewBot() instantiates a unique hook by default?
Trying to wrap my head around why each interaction does not have to be a unique custom id
iirc each component in a view should have a different custom ID
Yes, this is true - i know. but what if lets say, you and i both interact with it
We both have our ephemeral components (we see our own, ofc)
that doesn't change anything
if i restart the bot, will our owns stil work
uhh no
did you start the task
given functionbasic: functionbasic.start()
there we go
idk how i miss that
💀
reading is hard
For every persistent view, I have to put it under async def setup_hook(self) -> None: right? @shell radish
what is setup_hook
oh discord.py
you can do that
and pytz.timezone doesn't seems to work
so i'll use utc
Well, I am using pycord.. but I think I can still use this? Unless pycord has its own
I think I saw a youtube video where someone using pycord used persistence
pycord doesn't have setup_hook
Is there an example on how to implement persistent view with pycord?
Here's the persistent example.
aha.
I'm making a jumbo command for emojis, but it only works with custom emojis. Does anyone know how we can do it for native discord emojis as well?
Starting from a command ID, can I get a mention of the command?
What is a jumbo command
The mention is just </:name:id>
jumbo commands convert emojis to large png like stickers
yess ik, and for the sub-commands?
Oh uh. Native emojis aren't images
ik : C
So I guess you'd need to do some wonky stuff like trying to get an api to give you an image
Based off the emoji name or something
okay, np
and it is possible to pass the command ids to comands. ? get_slash_command_by_id ?
Wdym
is there much difference when using default_permissions over has_guild_permissions? Just want to make sure
default_permissions limit users to see the command
has_guild_permissions is just an internal check
So should I use both or does it not really matter?
Up to you I guess
Just wanted to make sure theres no risk of someone without the permissions using the command with default_permissions
It's always good to have an internal check.
Alright and can that still be overridden with the server integration settings?
Is it possible to use the once=True kwarg in the on_ready event of a subclassed bot?
I may oversee something, but is there still a clean way to retrieve the display name of a member if they did not set any nick name in a guild? I do not want the global username, which is lowercase but the displaying name. Yet member.display_name is the lowercase global username if there is not nick set. For example in my case I would like to retrieve 'MR.e' instead of 'matrix_exe' and do not want to set a nick for each guild first.
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
Ok, thanks for the info but my Member object unfortunately does not have a global_name which I apparently would like to retrieve in this case. Any ideas why?
Because you might not be on the latest release
Uninstall py-cord and install py-cord-dev
ah, there is a dev package. Because I already checked that I have the newest py-cord 2.4.1. Will try the dev
works just fine, thanks for the quick support @lofty parcel
Sorry about that we have had some issues with finalizing the official release for the feature due to some administrative setbacks.
no worries, just didn't know about the dev package yet
<Message id=1155014139773734924 channel=<TextChannel id=1152878856139718676 name='meme-subsissions' position=4 nsfw=False category_id=1066217740051939358 news=False> type=<MessageType.default: 0> author=<Member id=988436414490378292 name='banana_lol_7678' discriminator='0' bot=False nick=None guild=<Guild id=1066217739565420554 name="Katz's Destruction area" shard_id=0 chunked=True member_count=6>> flags=<MessageFlags value=0>>
how can i disable theese
What do you mean?
How can I create an autocomplete with guild members' name? I've tried using [member.name for member in bot.get_all_members()] but the list is empty
guild = bot.get_guild('Your guild id')
[member.name for member in guild.members]
1 guild is fine. But I've tried it and guild is not populated unless I ran it in on_ready first
And because my function is async it thrown me an error about guild being None
send your code
ok ill make a minimum working code. Give me a sec ❤️
I'm having issue with button.disabled doesn't work. No output error whatsoever.
class AcceptButton(discord.ui.View):
def __init__(self, member, copied_embed, *items: Item, timeout: float | None = 180, disable_on_timeout: bool = False):
self.member = member
self.copied_embed = copied_embed
super().__init__(*items, timeout=timeout, disable_on_timeout=disable_on_timeout)
@discord.ui.button(label="Accept", style=discord.ButtonStyle.success)
async def accept_button(self, button, interaction):
button.disabled = True
button.label = "Accepted"
await interaction.response.send_message(embeds=[self.copied_embed])
use class for your button
hi guys i want to give user display name but how ?
which subclassing discord.ui.Button
Alright will try thank you.
good luck!
@arctic ploverbro
you can help me?
phew
from discord.commands import Option
intents = discord.Intents.default()
intents.members = True
bot = discord.Bot(intents=intents)
@bot.event
async def on_ready():
global guild
guild = bot.get_guild(put_guild_id_here)
for guild in bot.guilds:
print(guild)
print(guild.id)
@bot.slash_command()
async def add_user(ctx, name: Option(str, "Enter the display name", require=True,
autocomplete=discord.utils.basic_autocomplete(
[member.name for member in guild.members]))):
pass
TOKEN = "Put token here"
bot.run(TOKEN)
also I just realized that this wouldn't even work bc it will complain that guild is not defined
hi
u can use database
@arctic ploverI forget which code we used to get the user's display name.
use discord.Member object. it has member.display_name property
As in creating my own database and read from it?
yes, you can use sqlite3
I see that makes sense. Thank you
just get member object
via guild.get_member(member_id)
and then use member.display_name property
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
That shows how to get different member names/nicks ^
thanks you
but member.nick is on this server
i need a global nick
if you want the global display name you can use member.global_name
but you need to either use the master branch or py-cord-dev for that
?tag install
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
if you want to use the master branch, take a look at the last row
if you want to use py-cord-dev just uninstall py-cord and install py-cord-dev
Do you know how to code discord.py?
discord.py can be used almost the same as pycord but with some differences only
You should ask that in the discord.py server instead if you want to know
Thank you, I know this, but I found out that I was banned from there :)
are you using discord.py or pycord?
im using discord.py
Then we can't help you. This server is only for pycord support
But since they are almost similar, I don't mind.
I know buddy but thank you for showing me the way.

can I create a button with no label or set the column of a button?
I want to let the option type be text channels, but not all types of channels
@bot.command(name="移除新公告發送頻道", description="移除新公告發送頻道")
@commands.has_permissions(administrator = True)
@option('公告頻道', description='你要公告定期發送的頻道', type=SlashCommandOptionType.channel.text)
I dont know how it works with SlashCommandOptionType
with a normal option it would be discord.TextChannel
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
oh i found it
What could be the reasons for my select menu showing an error, but working as intended? I still can't figure it out..
use interaction.response.edit_message instead
is it required to do this in the select callback?
yes
at least preferably
wait but i thought the callback is done after i select my items, not when the select menu appears?
yes it is
the original interaction that edited the message wasn’t acknowledged officially
do edit message necessary when disabling a button using button.disabled = True?
that line only sets the change locally but that is never reflected to Discord
i see, so i supposed to somehow edit my roll random modifier button in the callback? but this is not right..
class RandomModifierButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value: bool = False
@discord.ui.button(label="Roll Random Modifier", style=discord.ButtonStyle.green,custom_id="persistent_view:roll")
async def button_callback_yes(self, _, interaction):
self.value: bool = True
interaction.response.edit_message(view=None) # ?
self.stop()
be like that eh
Hi! I attach images to the message and the use them in embeds. I don't want the images to show outside of the embed but sometimes they randomly appear. How to fix it?
?tag persistent_view
No tag persistent_view found.
No tag persistant found.
No tag persistant found.
okay so i want to have a persistent view that i'll send to multiple users when a command is called(implementing a bounty system that asks for confirmation), that bounty gets an pending id(for the process of confirmation) which ill also use to access it in the Database, is there a way to "store" it in the view(there will obv. be different ones) besides just sending it in the message and scanning interaction.response.original_message().conent for the id?
Why not storing the value based off the user id
.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.
eh already storing author_ids of bounties to see whom to notify, but also a user could have multiple bounties whose kills they need to confirm so there would be multiple process/pending ids associated with a user
i have already put in too much thought into it to the point i lost track of my plans lol
Then store store a dict based off the user ID using the message ID and then the value
“The palest ink is better than the best of mind” or something like that - some proverb from some country I forgot
ah looks like i havent put enough thought into it, my database atm doesnt even have a column for storing whther or not it was confirmed
i assume when i send a persistent view to multiple users and reattach it or whatever after restart it wont complain? the custom_id should work for multiple "instances" right?
Yes
good good
eh ill probably use a ulid.timestamp as id and set it as footer or stuff and read that
Why..
no, let me be frustrated in peace
for a Star Citizen Org thats inactive af rn 
my bounty system will have a whopping user count of me and another guy to test it
you know what, maybe i should accept advice if i come here for it
a dict wont do it but going off of message id is something proper
I want to send an embed with an image in the top-right corner. The image is a local file. I attach it and then use it in the embed.
This method works most of the times, but occasionally fails. When that happens, the image is visible in the same message.
embed = discord.Embed(color=discord.Color.blue(), description=description)
path = f"images/talents/{filename}"
file = discord.File(path, filename=filename)
embed.set_thumbnail(url=f"attachment://{filename}")
tooltips.append((embed, file))
if len(tooltips) == 10 or index == len(results) - 1 or index == amount - 1:
embeds, files = list(map(list, zip(*tooltips)))
await context.respond(embeds=embeds, files=files)
Hi, I want to store user data but I just want to check if it's ok to do it like this, or if there's a more secure way or something. I have a userdata folder with files named based on user IDs. A file is created for a user if the user uses the /settings command. All the information that is stored in the file, is some basic non-personal parameters used in another command that personalises their experience.
Because you're sending it as a file too?...
Json files are not databases. Use an actual db
so just like that
better to use a db yeah but this works for me right now with low user count
if the images are static, just send them from a cdn.
imo i would just use a sql database with a table called usersettings with columns: user_id, setting, value
Still, I don't get why it only happens 5% of the time or so.
probably discord quirks
Thanks. I need to search how to do it as I never did it.
If you have a link explaing it or with an example, that would be helpful.
well tbh i am uneducated on DBs let alone how to implement one and transfer it between devices
Well a sqlite db is literally just a .db file
And SQL syntax isnt too hard to learn IMO
probably but, I gotta setup SQLite as well right? Or can it all be done in python?
All python
Natively
Import sqlite3
with sqlite3.connect('path to your db') as con:
c = con.cursor()
c.execute("CREATE TABLE IF NOT EXISTS usersettings (user_id INTEGER NOT NULL, setting TEXT NOT NULL, value TEXT")
con.commit()
@sonic sorrel
Thats for setting it up intially
I like to slap that into a def init_tablename():
I like to use MongoDB (NoSQL)
I simply use what i have been using so far because i know how to use it
cool i will look into this more now
and to move between machines all you need to do is move the .db file? assuming i just put it next to main.py
Yes
If the code has an active connection to the db overwriting on the target device gonna be a bit problematic but eh
Thats why closing connections is important!
well i just stop the code and override the .db file and go again?
safest way
i wouldnt have tried any other way tbh
Never challenge the computer god
komputer dumb only know 1 and 0
iirc a basic settings tuple for a user would be kinda like
usersettings = [row for row in c.execute("SELECT setting, value FROM usersettings WHERE user_id = ?",(user_id(a variable in your func))).fetchall()]```
That can then probably be turned into a dict and stuff
upload image to imgur and copy link
for example
IMO just upload it to a channel somewhere and copy the discord.attachment link
Already on discord that way
they are planning to make attachment images non-permanent
Oh
Yeah... i was wondering they didnt alread do that
hmm okay, thanks
I mean each server probably has gigabytes of media on avg.(every server is a bit of an exaggeration but)
Ah, ok! I thought you meant something more complex, via Pycord and/or Discord. Thanks again.
Me remembering the time my bot accidentally sent the same 5 images what felt like 20 time a second for 30 secs before i noticed, yet didnt get rate limited
Mf just cant decide whether to be on or off
quantum states go brrrrrr
nah that aint real
Ugh am i the only one that sees code after closing their eyes to sleep when they've been coding for a couple hours
this is coding help, not mental health help
according to some that is all just quack science
Tetris effect? Google it.
Interesting
QQ: How to get information about a member (by either the object, or ID)
like, Username, Tag, Avatar Link etc. etc.
simply user.avatar.url or stuff, user.display_name
hmmm
Alternatively 
is there a list somewhere?
yeah asking for that, navigating PyCord's docs is like navigating a jungle
I can barely find what I'm looking for
and if I do, it's always just half of what I need
what in the world, there's a search bar?
I was going blind looking through pages for all this time and didn't notice the goddamn search bar
I'm so sorry lmao, I spent hours looking for things and I didn't even notice the search bar
Lmao
lmaoooo I'm so sorry
I can tunnel vision so hard sometimes even I'm surprised
Yeah
Seachbars truly are innovative
Uhhhhhhhhhh
.rtfm Member.avatar
discord.Asset
discord.Asset.is_animated
discord.Asset.key
discord.Asset.read
discord.Asset.replace
discord.Asset.save
discord.Asset.url
discord.Asset.with_format
discord.Asset.with_size
discord.Asset.with_static_format
discord.asset.Asset
discord.Activity.assets
discord.RawMessageDeleteEvent
discord.RawMessageDeleteEvent.cached_message
discord.RawMessageDeleteEvent.channel_id
"Represents a CDN asset on Discord."
Ah right sleep...
I have no idea what I could do to convert it to an url (or at least an embed)
Are you familiar with oop?
I have no idea what that even is
It literally has the url attribute
Object Oriented Programming
oh so class stuff, well no
The avatar url literally is user.avatar.url
well kinda, but not really
It is a property of that object
so, just avatarurl = user.avatar.url solves the issue?
huh.
Member.avatar returns a discord.Asset which represents the avatar image, you access the url either the .url attribute
Might need to str() it but dunno
better safe than sorry amirite
url already returns a str
.
url already returns a str
It's redundant
at least that is
I mean it probably simply is stored as a string
speaking of, I've had this thing; what is the second variable supposed to be
Where we are going we don't need performance
A not used one
_ just indicates that its trash you don't care about
It's just Member as far as I know
.rtfm on_member_join
so it returns member... twice?
Nah
only member
It's just member
It takes the second arg thats passed into it
member: discord.Member
You do need performance on a bot
if I don't include , _ it throws a non-crash error
remove that
... if you have users :(
see, but removing it makes the program throw a fit
Is it inside a class?
Does it take self as arg?
wait
(self, member: discord.Member)
This is why you need to learn OOP
IT JUST CLICKED
Yes....
NOW I KNOW WHY CLASSES ARE USEFUL AND NOT JUST GARBAGE
people who were explaining it to me were... pretty shit at doing so
Lady's and gentlemen, he got it
so I only ever half understood classes
but I assume, class just spoon feeds each function with a variable that it provides, yeah?
ignore the flavour text, but this is what the mess™️ is rn
And then access it with print(self.varname) or shit
ah, got it
contained global
essentially
so uhh, I assume move on_member_join out of the class?
or make a class of it's own?
Also lets say you have
def __init__(self):
self.strvar = 'i am an attribute, or was it property?'```
You could initiate CoolClass as f.e. cc with cc = CoolClass() and then print(cc.strvar) and so on
neat
you don't initialize a class. You create an object/instance of that class
Do you see on message above taking self in its constructor
yes
Yeah yeah, i know how to do it but not the fancy language slang(aka terms/names for things)
So go add that as first argument
ooh, so spoon feed self to everything now, alright
If its in a class it WILL receive a self as first, member is being used as self by the class
and _ is member
because theres no self
right
Everything in a class yes
yes
understood
so essentialy, this piece of code is having an existentional crisis
so I have to remind it that it's self
got it, got it
well it doesn't need to be called seld
never thought a piece of code could be going through what I'm going through/hj
except for static and class methods
its just that 'self' is called member and you are doing operations on self that you want to do on member
OH
no, self refers to the client object here
Well yes but i meant self as whatever the fuck you call the self var/obj, and that got stored inside member
Ah god i should actually sleep, coherence is leaving my head
you're not making much sense
Yes
Well I know what i mean
Lol
I love the brains ability to understand concepts without combining them with any kind of words or other information you can properly communicate
So i just end up babbling some gibberish
the member arg is unrelated to self
Yeah
a brain is essentially what a beginner programmer would write as their first official project
it's so jumbled that NO ONE not even themselves understand what it does
or how it does it
but isnt self usually the first arg no matter what its called in the defs constructor(?)
except for static and class methods
Yes
would this work for sending something in one message on multiple lines
Use \n for newline
oh.
yes, but the indentation will be there
so like this?
OH
THAT INDENTATION
It was \n and not /n right? I usually do it by muscle memory on pc
okay so
what's the display name thingy again
user.what?
display_name didn't work
it returns back member object
.rtfm member
discord.TeamMember
discord.TeamMember.accent_color
discord.TeamMember.accent_colour
discord.TeamMember.avatar
discord.TeamMember.banner
discord.TeamMember.bot
discord.TeamMember.color
discord.TeamMember.colour
discord.TeamMember.created_at
discord.TeamMember.default_avatar
discord.TeamMember.discriminator
discord.TeamMember.display_avatar
discord.TeamMember.display_name
discord.TeamMember.id
discord.TeamMember.jump_url
discord.TeamMember.membership_state
discord.TeamMember.mention
discord.TeamMember.mentioned_in
discord.TeamMember.name
discord.TeamMember.permissions
odd
.rtfm user.display_name
my name is Normal Man, yet it returns back the_real.me
which is my tag
which is the exact same as the member object
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
these return the same thing
What the fuck is pomelo? A major version overhaul or smth?
Username changes after the deprecation of discriminators
do I need to import anything
No?
discord preferrably
okay good
Lol
Can you you show the whole def/func
What's your pycord version
uhhhh
Are you on 2.5.0rc5
how do I check again
discord.__version__
pip list
ah
Do you perhaps still have discord.py installed
yeah so there's a dev version which include pomelo
yeah
#library-updates
oh
@opal hamlet go to sleep. You're clearly not mentally ok rn
OH COME THE FUCK ON
Is anyone mentally OK at this point of the year
I was assuming what the * emant
why tf did you use self
there was a *
so?
I assumed it was some self bs
Why you passing self? 
Lmao
what does the star mean
you also clearly don't know how python works
or asteriks
Placeholder
...oh
For potential args
I work on (huge) trial and error
Ever seen *args, **kwargs
...not really
great
In f.e. def name(*args, **kwargs)
nope
Ah
wait
waiting
What
no
well no that's what I got
Its a potentially unlimited number of args
or is it full on *args
so whatever you do def(abc) it checks abc if it's 1, def then it does the same and so on
Don't 💀 me!
*args means take these arguments and make them into an array named args
just remove self, in your case
You can do f.e. name = args[0]
OH
overloading
OH MY GOD
Keyword args
you're not native to python
ah
I kind of understand python, but I'm also kinda throwing myself into deep water
trial and erroring until it works
this is more like shallow waters...
Ive taught myself coding via chatgpt for the past 3-4 months and have been trial and erroring discord bots, so no lmao
but yeah
to you, but not to me
More like a black hole
the pits of hell have opened to swallow you whole
I just suck at remembering names or terms for things
wait until you hear about multiprocessing
Ah yes
yeah, learning everything at 4 am is definitely going help you remember them
shut
Uh hello? Its merely 0:41!
same timezone let's gooo
And i usually only do code until 2am, big difference
I'm running on an energy drink and like 4 different coffees
🤥
4 different coffees are whats needed to compensate for lack of sleep alone
and then factor in ADHD
and the fact I get so scatterbrained when tired I forget to sleep
my head is pounding but code is the cure
Me telling myself to go to sleep for the past 3 hours but discord and manga keep me awake
hmmmmm
@opal hamlet sorry to bother u, do u know how to manually add a row of user data to sqlite3 db? do i need a program to open the db file, or maybe in pycharm?
I recommend DB browser
https://sqlitebrowser.org/ @sonic sorrel
Can also be uhhh selected as standard app for .db which is CONVENIENT
Wdym
Is it supposed to send them multiple times from a loop?
well yesn't
if kicked, send message
it sent this only once
man it feels so raw without an avatar
but that's beside the point
What exactly was it supposed to send besides that
it, but again
well that was easy, thanks again
Did you add some nice traceback to your function?
👍
yup
traceback, wdym by that
Just be careful with INSERT OR REPLACE, it may create a few duplicates, implement a check if exists func that returns a bool
it does everything nicely, but not the send message part
Its a standard library
Maybe put the send before kick?
Maybe discord is bitching that the member kinda doesn't exist or smth
I forgot that alt has dms from people blocked
.....
Lmao
Nah but i personally like to wrap everything inside a function in
try:
except: traceback.print_exc()
Gotta import traceback first tho
on_error listeners exist
If you use on_error you dont have to use all the try and except stuff
Isn't it only for commands? Cuz im generally using it
that what you mean is on_command_error
only for events
Logging tracebacks it is then.
are there some examples?
I'm sure there are
U know some?
I have an option for a slash command as
person = discord.Option(input_type = discord.Member, name = "target", description = "Who you want to ask the question to", required = True)
but it's a string and not a discord.Member object and I don't know why
from discord import Option
@client.slash_command(name="avatar", description="Shows a users avatar.")
@commands.guild_only()
async def useravatar(ctx: discord.ApplicationContext, user: Option(discord.Member, "The user to show the avatar for.", required=False)):
This is how I am formatting arguments in slash commands.
yeah i figured it out although im not particularly sure why it has to be a typehint
just how it's coded
is it possible to mention a command with an option already specified?
do you mean something like autocomplete?
discord.AutocompleteContext
discord.AutocompleteContext.bot
discord.AutocompleteContext.cog
discord.AutocompleteContext.command
discord.AutocompleteContext.focused
discord.AutocompleteContext.interaction
discord.AutocompleteContext.options
discord.AutocompleteContext.value
discord.Bot.get_autocomplete_context
discord.commands.context.AutocompleteContext
discord.ext.commands.Bot.get_autocomplete_context
async def complete_bounty(self, ctx:discord.ApplicationContext, target:Option(str, name_localizations={'de':'ziel'}), evidence:Option(discord.Attachment, name_localizations={'de':'beweis'})):
how would i limit evidence to attachments of type image or video?
would i need to do smth like py if not evidence.contentent_type == 'video': return
how do i fetch my bots top role in a server?
from discord.utils import get
async def assignrole():
role = 'rolename'
gs = bot.guilds
for g in gs:
role = get(g.roles, name=role)
if not role:
await g.create_role(name=role)
role = get(g.roles, name=role)
if not role in g.me.roles:
await g.me.add_roles(role)```
not *exactly* what you are looking for, but what i had laying around
i think the guild.me.roles would be key here
lol its always something obvious you just never used before, eh?
well.. kinda. When you mention a cmd called cmd it will look like /cmd and you can click it, then specify options etc. But I wonder if you can mention it like /cmd option:value so when it's clicked, it has the option filled already
i think there should be some kind of default value of sorts
@bot.event
async def on_reaction_add(ctx, reaction, user):
# Check if the message ID and reaction emoji match
if reaction.message.id == 1155467049687072819 and str(reaction.emoji) == "✅":
# Get the role object
role = discord.utils.get(user.guild.roles, id=1155467114568745071)
# Check if the user already has the role
if role not in user.roles:
# Add the role to the user
await user.add_roles(role)
Not sure why this code doesnt do anything could someone point me in the right direction
.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.
its meant to constantly listen for ✅ to be added as a reaction to a message and then its meant to add the role but it doesnt do anything no erroring bot has sufficient permissions everywhere and nothing happens
?tag intents
Pycord Docs - Intents
Discord API Docs - 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)
intents = discord.Intents.all()
bot = discord.Bot()
client = discord.Client(intents=intents)
my intents are defined
and are enabled on the dev portal
embed.set_image(url='attachment://blogpost.png')
message = await channel.send(file=file, embed=embed)
How can I get the URL of the picture in the sent message?
i believe it is this
return message.jump_url
or this
channel = discord.utils.get(client.get_all_channels(), id=1234567890)
message_url = await get_message_url(channel, 1234567890)
I am sorry. I mean the URL of the picture in the message
async def get_image_url(message):
"""Gets the URL of an image sent in a message.
Args:
message: The message containing the image.
Returns:
A string containing the URL of the image, or None if the message does not contain an image.
"""
if not message.attachments:
return None
# Get the first attachment
attachment = message.attachments[0]
# Check if the attachment is an image
if attachment.content_type not in ["image/png", "image/jpeg"]:
return None
# Return the URL of the image
return attachment.url
This will only work if the message is cached. Try using on_raw_reaction_add
i tried that still didnt work :(
is it in a cog?
If so use this instead discord.Cog.listener of bot.event
Why do you have discord.Bot and discord.Client?
Zervy is right, you should not need client, just move intents into bot and replaces all client references with bot
that does not work. return None
i think it is because the image is in the Embed?
hey, is client.latency the ping in ms?
.tias
It should be
nvm Docs say it is seconds
good point, however:
they do? I must've overlooked that
oh yup I overlooked that
it was easy to miss
yeaa your brain automatically starts skipping over when you see words completely alien to you
and it's at the end of them
I wonder, does everything from events have to be put under this?
and then, slash commands have to be put outside of this class, right?
Because events are method in the bot class
so, events go under this class, but slash commands go OUTSIDE the class, yes?
For slash commands you would have to change it
or does it not matter
?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)
Yes
Because you create the command based off the class
@bot.command()
You can't do @self.command()
ah
I assume like this, or am I missing something
I'm enjoying the fact that doing all of this is going smoother with each day
The hell is that supposed to be
uhhh
the class thingy, just like the discord.Client one
oh, so replace the class Client(discord.Client) with class Client(discord.Bot)
instead of make a new class
*1000 for ms
Yes..
This is why you need to learn OOP x3rd time
fair
.rtfm user
discord.PublicUserFlags.bot_http_interactions
discord.PublicUserFlags.bug_hunter
discord.PublicUserFlags.bug_hunter_level_2
discord.PublicUserFlags.discord_certified_moderator
discord.PublicUserFlags.early_supporter
discord.PublicUserFlags.early_verified_bot_developer
discord.PublicUserFlags.hypesquad
discord.PublicUserFlags.hypesquad_balance
discord.PublicUserFlags.hypesquad_bravery
discord.PublicUserFlags.hypesquad_brilliance
discord.PublicUserFlags.partner
discord.PublicUserFlags.premium_promo_dismissed
discord.PublicUserFlags.staff
discord.PublicUserFlags.system
discord.PublicUserFlags.team_user
discord.PublicUserFlags.value
discord.PublicUserFlags.verified_bot
discord.PublicUserFlags.verified_bot_developer
discord.UserFlags
discord.UserFlags.staff
.rtfm PublicUserFlags
discord.PublicUserFlags
discord.PublicUserFlags.DEFAULT_VALUE
discord.PublicUserFlags.VALID_FLAGS
discord.PublicUserFlags.active_developer
discord.PublicUserFlags.all
discord.PublicUserFlags.bot_http_interactions
discord.PublicUserFlags.bug_hunter
discord.PublicUserFlags.bug_hunter_level_2
discord.PublicUserFlags.discord_certified_moderator
discord.PublicUserFlags.early_supporter
discord.PublicUserFlags.early_verified_bot_developer
discord.PublicUserFlags.hypesquad
discord.PublicUserFlags.hypesquad_balance
discord.PublicUserFlags.hypesquad_bravery
discord.PublicUserFlags.hypesquad_brilliance
discord.PublicUserFlags.partner
discord.PublicUserFlags.premium_promo_dismissed
discord.PublicUserFlags.staff
discord.PublicUserFlags.system
discord.PublicUserFlags.team_user
#app-commands
can somebody send a short template of a slash command since I'm getting nothing out of the docs
assuming I'm looking at the right thing(discord.SlashCommand)
Here's the slash basic example.
Dont use discord.Client and discord.Bot at the same time
Im still having issue with my code
Im trying to have it when a message recieves a reaction of ✅ that they recieve a certain role
I have defined all my intents and when i react to the message nothing happens and i recieve no errors
intents = discord.Intents.default()
intents.reactions = True
bot = discord.Bot(
intents=intents
)
#######
@commands.Cog.listener()
async def on_raw_reaction_add(reaction, user):
# Check if the reaction is a white_check_mark emoji and the message ID is correct
if str(reaction.emoji) == '✅' and reaction.message.id == 1155467049687072819:
# Get the role by its ID
role = user.guild.get_role(1155467114568745071)
if role is not None:
# Add the role to the user
await user.add_roles(role)
print(f'Added role {role.name} to {user.display_name}')
but, I'm not?
that's the only class I have
Oh ok
that's the entire code for this class
Is it outside of the class?
yes
wait...
it was the client.slash_command() trying to use the previous thing
💀 my bad
hmmm, but the site uses @bot.slash_command and I'm forced to use @client.slash_command
what could be the thing
Because you declared your class as Client
You don't copy the code exactly as the example
You understand and write yours
I assumed there was an error lol
also
any clue why this doesn't work
doesn't work as class Client(discord.Bot) either
no error just
silence
the bot itself is alive though
How can i limit a command option attachment to img or video
I am going insane
on another note: while this is broken;
what does ctx mean?
is it just command whatever?
kinda like a command object
abbreviation of context
being you know, the context of the command
oi Dnoxl
any idea how to fix the above issue
I think I might've accidentally lobotomised my bot and I have zero idea how I did that
class Bot(discord.Bot):
async def on_ready(self):
print(f"I'm alive, at {self.user}!")
async def on_message(self, message):
print(f"{str(message.author).rstrip('#0')}: {message.content}")
async def on_member_join(self, member):
userID = member.id
channel = bot.get_channel(1155232310468280320)
welcomeChannel = bot.get_channel(1130586203855540266)
getCurrentDate()
userMention = member.id
userAvatar = member.avatar.url
userDisplayName = member.global_name
userName = member.name
userIDstring = str(userID)
if userIDstring in whitelistIDs:
await channel.send(f"{date_time} | `Traffic Syndicated for {userID}, recognised as {whitelistIDs[userIDstring]}`")
await welcomeChannel.send(f"Greetings, {member.mention}")
elif userIDstring in blockedUserIDs:
await channel.send(f"## **{date_time}** | @autumn gust `Potentially Dangerous Traffic Blocked: {userID}, recognised as {blockedUserIDs[userIDstring]}`")
await channel.send(f"Mention: **<@{userMention}>**\n Avatar: **<{userAvatar}>**\n Name: **{userName}**\n Display Name: **{userDisplayName}**")
await member.send("You were kicked, reason: Banned on the Whitelist.")
await member.kick(self, reason="Banned on Whitelist.")
else:
await channel.send(f"## **{date_time}** | `Remote Traffic Blocked: {userID}`")
await channel.send(f" - Mention: **<@{userMention}>**\n - Avatar: **<{userAvatar}>**\n - Name: **{userName}**\n - Display Name: **{userDisplayName}**")
await member.send("You were kicked, reason: Remote Traffic Blocked; Disconnected.")
await member.kick(reason="Connection Denied.")
un-indent on_ready
its not inside a Cog file is it?
just get rid of the class


