#Basic Pycord Help
1 messages · Page 52 of 1
and not using pillow anywhere that "should" be running while idle
for the part of pillow, try to replace it with that :
.tag rie
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.
just in case, if you still have the other issue send the file with the link i gave u and i will take a look
also, for the record
i have changed nothing regarding pillow usage between this not happening and now
and you told me this happen without any command running ?
yes
this happens with me doing nothing besides writing python fractalrhomb.py in the console
does fractalthorns_api is async ?
uh
what?
i think those kind of thing :
fractalthorns_api.purge_cache(cache)
might be blocking the bot
yeah might be that
everything is using requests
which is blocking, so ig the request to the api block ur whole bot
i dont have the fractalthorns_api in the thing u sent me
but since no fractalthorns_api are awaited
i think it can be the issue
i'm gonna test a thing
hmm
i can just make the following comment
if i change it to
def main() -> None:
parse_arguments()
try:
asyncio.run(frg.bot_data.load(frg.BOT_DATA_PATH))
except Exception:
discord_logger.exception("Could not load bot data.")
#async with aiohttp.ClientSession() as session:
#frg.session = session
bot.load_extension("cogs.fractalthorns")
token = getenv("DISCORD_BOT_TOKEN")
bot.run(token)
if __name__ == "__main__":
main()
```it doesn't give me heartbeat blocked warnings anymore
also for you know, asyncio.run is blocking
so using asyncio.run might block ur bot
and so give u the hearthbeat
ok
literally just adding an async with bot: before the await bot.start stopped the error
A little confused with the new guild commad/user command app install system. Before 2.6 I used ad = SlashCommandGroup("admin", "Admin controls for the bot", guild_ids=[xx]) to lock to a guild. But not they won't show up at all. So how do you do it now?
how can i split long messages in a way that wouldn't mess up markdown formatting?
but the guild_ids parameter is for the guilds where the commands will be registered, it is not used to lock specific guilds
I’m aware, I was just saying locking the command to the guild so only that one as access
when a member only has one mutual server with a bot and then gets kicked, and has had no previous interaction with the bot before (e.g., dms), do they get uncached?
also how do bots like carlbot processes a bunch of channel overwrite updates at once if those events are sent individually?
hi, how subcommand works already read the doc but not so sure where to start
if you use cogs, manually create a SlashCommandGroup, then do
@groupname.command()
and from there on its like any other command
I think how to do slash groups in cogs isn't on the guide
if you don't use cogs, there is definitely a guide on groups
Here's the slash cog groups example.
There's the example
alrr
ok working now thanks
what about cog slash cmd like a normal slash cmd
ok i figured it out
restart discord
ive followed the docs https://guide.pycord.dev/interactions/application-commands/slash-commands here
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
ah okay
thanks 😭
ok so how do i get classes returned 
what
that arguably explains it even less
do you mean stuff like return discord.Guild as a class or what
i want to pull the class callback
can you please explain what you want to do in a full sentence or two
so like a custom ctx for commands? im still so confused
well for that you can just subclass ApplicationContext
but not sure though how you populate / actually pass that into the commands, never did that
maybe someone else knows
alrr
Here's the custom context example.
Custom context is very useful
#general message this can happen because py-cord (the install name of the package) doesnt match discord, the import name
if it works, dont worry about it
but if you did pip install discord, thats not pycord
i followed the pycord installation process
Can you show the pip list pls
If everything works you can ignore those warnings
I also get them in pycharm, it's correct that they show up, tho annoying
i yet again switched muahaha
switched what
to vscode
.
yeah one sec
its quite long so i gotta make it a txt file probably
if its longer than fits in a discord message you are long overdue for using venvs
aaand wrong
i blame linux mint for this
WHY IS IT THERE
has nothing to do with it
you dont have pycord installed at all
You installed it
i literally JUST Installed it for good measure
you didnt
i did
it aint in here
but WHY
because yo udidnt install it
i hate u, random person on stackoverflow
- uninstall discord.py
pip install py-cord
the install instructions are on the repo, the website itself, the guide..
well
no need to trust random idiots from probably 4y ago on stacky
wellllll
so i GOTTA follow the stackoverflow gods who had the same problem as me
oh my god i last saw that when someone tried using python on a chromebook
the horrors
its making me suicidal
did you try apt install python3-py-cord like it says
and you said its Linux Mint?
mint is debian based
and?
in case you mean it saying debian-based in the error text
lol
well, then did you follow the rest of the text and make a venv?
oops
and? what speaks against them using mint lol
yeah hold on
...
people not reading errors is the worst pandemic to strike programmerkind
i read it
but?
that is not how you install the stuff....
zervy
yes, it is
else there wouldnt be a literal text step by step guide on how to do it when you try the normal way
idk what kind of messy install they have that that happens, but they do
tho tbfh the chromebook person that happened to didnt succeed either in the end so 
did that
yeah imma just code on windows then
and do everything else on linux
the way its absolutely NOT Intended
they call me mr. opposite
i mean, you didnt exactly do what it says

I have an embet with buttons and logic And I want to update the embet in another file 1 picture when entering the voice channel send this message to the chat and the one who is first, that is, foz change the captain and choose your timemate 2 pictures and after the button the button changes the embet and deletes the buttons, and I want to connect another file where there will be other buttons, and it will be possible to add new buttons and change the embet, if you need a code, I can support
It's been 6 minutes. Nobody gets help in 6 minutes.
in one file?
No, he means you already have an active Post that hasn't even had time to get noticed by people who could help
please forgive me, I've just been suffering for more than one day and I'm afraid that I'll soon throw my computer into the ocean )))
That would make it difficult to apply any changes people may suggest.
Ok friend
i fixed my problem
i literally just had to pip install through the vscode terminal
bruh
i have no idea why it didnt work through the terminal
lol
"linux is so easy and makes sense"
It is easy to use xd
cleeeeearly
The user just didnt know what he was doing xd
whats wrong with trying to pip from the terminal?
clearly it didnt work as they showed
I was using Linux for half a year without any experience
And it was pretty nice to use
Here's the cooldown example.
is the bot role above that role?
do you have members intents?
and maybe you also need manage roles
but the docs dont say anything about that
are member_remove and member_ban the only two events associated with members leaving a server
think so, there isn't really anything else
i see
yea
just as a counter-check, you can print member.roles right
it can be printed
this is a task, i can't get interaction
yea lol, but i mean if they can
hm but not sure then, and im too tired to think harder about this
sorry, didn't seem like you were talking to someone
all good
how to make the command only for the owner of the bot?
thanks
how can i check if my bot has a dm with a certain member
cant check rn but it hink there's Member.history
How do you register slash command groups to a certain command? Is it done through the command or the slash command group?
Here's the slash cog groups example.
^
Oops I missed my main part lol. How do I register to a certain guild. not sure why i wrote command lol
guild_ids=[]
ad = SlashCommandGroup("admin", "Admin controls for the bot", guild_ids=[x]) So like this? I did this and nothing is showing up in the server which is how i did it before the update
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...
mhm
Weird I am having no luck with that. Nothing seems to register in that server.
try it by adding it directly to the commands and not the group
it has to be on the group
probably not invited with the right scope if no command registers?
So it registers but it registers in all servers tho.
I have
ad = SlashCommandGroup("admin", "Admin controls for the bot")
@ad.command(guild_ids=[910359176327364619])
yea because you can't pass guild ids to individual command group commands
Right okay hmmmm
All other commands register just fine, I think its something in 2.6 as the previous version worked just fine when I registered the guild id in the slash command group
maybe a stupid question or unrelated to the library but im streaming an audio file through discord and it plays it through my laptop first before it plays it on the bot, is this normal with pycord? or is it the other library
is it possible to tell if a "the application did not respond" error has occurred or no
it is easy you just gotta try every method there is until something works
Unless you have an oversight in your code where you never .respond(), there should always be an error that causes that (which you can see in the console)
guys, what is it space and how to fix it? (pycharm)
git blame thingy mb?
but uh thats not really pycord related lolw
right click the grey area at the top and it should tell you what it is

wait no i think that is the annotations tab lol
right click this other grey part up here, should let you close it
?
Why does this does not give the same number ?
len(list(self.bot.entitlements(limit=None, exclude_ended=False).flatten()) => 199 while
Any ways to send a audio message as a voice message in discord so it can be seen on mobile?
Not possible as far as I am aware.
Does someone know why this is not added as "persistent"?
I added the View also with "add_view()
show
do you see any custom id?
man idk
you add the custome id to the button
did you bot.add_view
.
ok I got it
I have to load it all at the main file I see
with @client.listen()
No
I don’t think it’s because of that
Cos im adding the add_view in cog and different file
Only thing that’s im not using is a subclass of button
Its working fine at the main file but not at the cog
Can u try putting it inside the cog
And not using a subclass of button v?
like do button = …
Are you sure the cog is being loaded then
Or that the listener actually runs
I do load my views on a cog listener too and I got no issues
Are u subclassing button ?
Oh, no
if i wanna send a bunch of embeds at once, is the max char limit of 6k supposed to be a limit of the total chars in all of the embeds?
per embed iirc
for some reason it seems like it's total
It is but you need a client mod which is forbidden by tos.
Nah
Then it's not possible...
Yeah, what I meant is the api endpoint isn't limited whatsoever
Objects: Attributes average_latency, channel, endpoint, guild, latency, loop, session_id, source, token, user. Methods async disconnect, def is_connected, def is_paused, def is_playing, async move_...
how it works ?
what exactly do you want to do
like send a attachment and the discord bot play the song (of the attachment ofc)
but it's write I need to make that in parameter
Objects: Attributes average_latency, channel, endpoint, guild, latency, loop, session_id, source, token, user. Methods async disconnect, def is_connected, def is_paused, def is_playing, async move_...
Target not found, try again and make sure to check your spelling.
of course
naah
you get first, only when you receive None you fetch
else you'll float api calls and, depending on scale, could face disconnect due to too many api calls.
# idk why it didn't work... lemme send the traceback
if ctx.message.attachments[0]:
await ctx.guild.create_custom_emoji(name=str(ctx.message.attachments[0].filename.split(".")[0]), image=await ctx.message.attachments[0].read(), roles=list(ctx.guild.default_role))
(and yes I read the doc but why this error in name parameter)
The name you're passing is not valid for the library
👀
bruh
alr
nice it work
also if you're only using default_role, just don't bother passing roles at all
ye it's wth I does here
I modify my code so now it's clean
I do a for ... in ctx.message.attachments:
and so we can create multiple emojis
is there a way to do every emojy from the bot in an embed?
do you know, how to get the emojys? i tried it with self.bot.emojis but this are only the emojys from the server, where the bot is
app emojis aren't in pycord yet
app emojis aren't implemented yet
and in discord.py ?
i dont know? lol
ask them
i think also not.
😦
how do i fix this ide error?
That is already for so long at pycord xd
"ide" lol
so there's no way to remove it? idk why im getting it
use the decorator
you won't regret it, trust me
also, what
i added the under score just in case I use anything for status_group and dont want to have to change a ton of decorators
im already hella used to what im already using

just because you're used to it doesn't mean its better
and it gets rid of the warning
and really, its a minimal change
It's funny because the decorator LITTERALLY hijacks the function signature typehints
@commands.guild is not depreciated ?
Hello! Is there a possibility that the bot will skip discord.on_voice_channel_status_update? Maybe a temporary loss of connection or something like that
yes
hey guys, i basically got a flask api where an endpoint is supposed to remove a role/add a role to some user, what is the best way to do that?
should i switch to quart?
i tried having a list of users, and in my on_ready() function to check each time a memebr gets added to that list to add/remove a role, but after like 5-6 hours, the bot starts glitching, doesnt find the role etc
You should use an async option
flask is async ready?
okay ill switch to that directly
Is it?
is it okay if i run the bot this way?
then simply have my endpoints under that, and starting the flask app normally?
yo, how do I check if message has mentions
.rtfm message.mentions
if a discord bot disconnects and then reconnects, and i have asyncpg.Pool() objects, do i need to close them explicitly
How do I get the user ID from list of mentioned user
ahh just how do I convert the str into user property
mentions is a list of Member or User objects, not strings
if I installed pycord before uninstalling discord.py, do I need to uninstall both then reinstall pycord for it to work? cuz VS code is saying it's not recognizing it.
reinstall py-cord
gotcha, thanks
So I didn't use the mentions one, but I have this code, it split messages and the first item is user mention, I just want to convert the mention from string into user objects, but I've been struggling with that.
@command()
async def verify(self, ctx, *, msg):
main_ally = ['58-K', '58-D', '58-B']
cmd = msg.split(', ')
user = cmd[0]
nickname = cmd[1]
ally = cmd[2]
member = cmd[3]
Why don’t I do
@command()
async def verify(self, ctx: commands.Context, user: discord.User, nickname: str, ally: …, member: discord.Member ?
the thing is nickname could have space
err
I'll just do slashcommand
okay so why doesn't it show the command when I type slash
How do you load the cogs?
like this
if __name__ == "__main__":
for cog in listdir('./cogs'):
if cog.endswith('.py') == True:
bot.load_extension(f'cogs.{cog[:-3]}')```
no need for == True
you can just use if cog.endswith('.py'):
I've also close and reopen the client
this is the code
btw why is the slash command different in guide
Fixed, had to reinvite with application.command scope
don't use == True bcs if + arg bool is alr true
idk if ur understand
cog
import discord
from discord.ext import commands
class MM(commands.Cog):
def __init__(self,bot):
self.bot = bot
mm = discord.SlashCommandGroup("mm","test")
@mm.command(name="1v1")
async def mm1v1(self, ctx):
await ctx.respond("test")
async def setup(bot):
await bot.add_cog(MM(bot))```
main
import discord
from dotenv import load_dotenv
import os
from discord.ext import commands
import asyncio
import aiosqlite
bot= commands.Bot(command_prefix="!",intents=discord.Intents.all())
load_dotenv(".env")
TOKEN: str = os.getenv("DISCORDTOKEN")
@bot.event
async def on_ready():
print("Bot Ready!")
async def Load():
cogs_list = ['mmq']
cogs_loaded = 0
for cogs in cogs_list:
bot.load_extension(f'cogs.{cogs}')
cogs_loaded =+ 1
print(f'Cogs loaded: {cogs_loaded}')
async def main():
async with bot:
await Load()
await bot.start(TOKEN)
asyncio.run(main())```
anyone know what's wrong here?
the command isn't working.
what "isnt working"
like a async def func. at the cog ;3
the app command won't show up in my server
do you use py-cord or discord.py?
py-cord
restart discord
remove the async and await
oh, lol
;3
yea your IDE shouldve warned you about that
How come you're not supposed to do that? I'm not very familiar with the async and await stuff
got it, thank you.
check out the guide if you're not familiar
Okay, thanks
hey guys, how's that possible?
member.roles doesnt contain the Tester role even though its there
is this the proper way to get it?
what is val?
just a dict containing either "id" either "username"
i dont think issue could be from there, its just providing them
and if i restart the bot, then it gets the roles good for the first time, then not anymore, like it caches them or something
Keep in mind that people can change the user name
so you would add the wrong thing to a user
yup sure
but i dont undetrstand why member.roles doesnt get the right roles
only the first time
just like it caches them
i have a loop running on the on_ready function
why?
thats not what on_ready is meant for..
on_ready can runs multiply times while running your bot
can*
I kinda competently removed on_ready at my bots
^
ah okay thanks, ill check that out
Will give an error can’t edit something running
You should copy the to_add_roles to not get this error
not really in that case, since im only removing the current element
@bot.command()
async def memberconvert(ctx, member : Union[str, discord.Member, int]):
if not isinstance(member, discord.Member):
class myconverter():
def __init__(self):
pass
async def converter():
member = await commands.MemberConverter.convert(self, ctx=ctx, argument=member)
myconverter().converter
await ctx.reply(content=member.mention)
yo guys why it raise that
discord.Member catches member IDs too, there's no need to use a union
just do member: discord.Member
itll work and convert
and i dont even wanna know why you are defining a class inside of a command
bcs it raise an error like this : missing required argument 'self'

but just do this
ok i'm gonna test it rn
@bot.command()
async def memberconvert(ctx, member : discord.Member):
member = await commands.MemberConverter.convert(ctx=ctx, argument=member)
await ctx.reply(content=member.mention)
``` that's weird
traceback :
pls help what is state parameter
befor,e you said widget :)
ye but now I'm trying a new thing
you dont create assets manually ever im p sure
again, what do you even wanna do
then use requests or smth for that lol
but idk how to do it without aiohttp
why not use aiohttp lol
bcs aiohttp didn't send a format like .jpg or smthing like that
so my code is wront
wront
wrong
does the link end with a file ending
nah it end with the emoji id
did u know an another module to read a link content
I found how it work nice imo it work
https://cdn.discordapp.com/emojis/{emoji_id}.gif
or .jpg
glad it works
self.bot._connection.clear() theoretically shouldn't clear the bot's user object right?
it does
might that be why i get a scenario where self.user is None when i startup the bot?
that'll only happen if you do stuff before on_ready is complete
cuz i get this
i can see why this is happening, but you appear to be the first person to ever hit this error in the many years of that line existing
and why does it happen?
because user is none, but that event wouldn't fire before on_ready
but why does that come directly from the bot.run line?
any error that kills the bot would come from run because that's how the loop works
oh lol
then why would this happen?
if that event isn't supposed to fire before the bot's ready?

it's not that "it's not supposed to", it literally can't receive other events until ready has fired
like that's what i mean
then how likely is it that it's something beyond my control?
so that means i should do something about self.bot._connection.clear()?
i can't really tell, like i said above literally no one has ever seen this error (from what i can tell) in the 9 or so years that it's checked for self.user.id, so my assumption is that it's something on your end but i wouldn't really know what
(i.e. if this had ever been a problem before, it would have been patched years ago - otherwise it'd be odd for there to be no null check for self.user)
quite frankly patching it is the matter of a few characters, but understanding why it's like that is more important for both you and the library itself
and if i print self.bot.user after self.bot._connection.clear(), it should be None right
you're just nuking your entire cache and it won't refill then 💀
oh 💀
literally ```py
def clear(self, *, views: bool = True) -> None:
self.user: ClientUser | None = None
self._users: dict[int, User] = {}
self._emojis: dict[int, Emoji] = {}
self._stickers: dict[int, GuildSticker] = {}
self._guilds: dict[int, Guild] = {}
self._polls: dict[int, Guild] = {}
if views:
self._view_store: ViewStore = ViewStore(self)
self._modal_store: ModalStore = ModalStore(self)
self._voice_clients: dict[int, VoiceClient] = {}
self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()
# extra dict to look up private channels by user id
self._private_channels_by_user: dict[int, DMChannel] = {}
if self.max_messages is not None:
self._messages: Deque[Message] | None = deque(maxlen=self.max_messages)
else:
self._messages: Deque[Message] | None = None
if you're gonna use undocumented stuff, at least read the source
is discord.ext.commands.Bot.get_emoji need the bot be in the guild to get it or ?
This gets it from the cache
.tag get
Tag not found.
Did you mean...
get_x
.tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
so my command not gonna work with that
.rtfm fetch_emoji
bruh
why
yeah because you need the guild for that
how to delete bot's message with button?
await interaction.message.delete()
thx
np
Can anyone tell me how I can test this cog with pytest?
I always have problems with ctx
test_testfunc - TypeError: Test.testfunc() missing 1 required positional argument: 'ctx'```
```py
import discord
from discord.ext import commands
from config import BOTCOLOR
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="test")
@commands.has_permissions(administrator=True)
async def testfunc(self, ctx):
embed = discord.Embed(
title="Test",
description="""Test""",
color=BOTCOLOR,
)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Test(bot))
@pytest.fixture
def bot():
return MagicMock(spec=commands.Bot)
@pytest.fixture
def cog(bot):
return Test(bot)
@pytest.mark.asyncio
async def test_testfunc(cog, mocker):
# Mock the context
ctx = AsyncMock()
ctx.send = AsyncMock()
# Mock the permissions check
mocker.patch("discord.ext.commands.has_permissions", return_value=True)
# Call the command
await cog.testfunc.__call__(ctx)
# Assert that ctx.send was called once
ctx.send.assert_called_once()
# Get the call arguments
call_args = ctx.send.call_args[1]
# Assert that an embed was sent
assert "embed" in call_args
# Check the embed properties
embed = call_args["embed"]
assert isinstance(embed, Embed)
assert embed.title == "Test"
assert embed.description == "Test"
assert embed.color.value == BOTCOLOR
def test_setup(bot):
setup(bot)
bot.add_cog.assert_called_once()```
I'll be real, test automation is just unnecessary for discord bots
honestly it ain't
never is
being able to check that you didn't break anything
I can't count how many times tests saved me
as well as type enforcement
If I also pass self as a mock, I can run the test.
Is that the right way?
@pytest.mark.asyncio
async def test_testfunc(cog):
# Mock the context
self = MagicMock()
ctx = AsyncMock()
ctx.send = AsyncMock()
# Call the command properly
await cog.testfunc(self, ctx) # Directly call testfunc with ctx
# Assert that ctx.send was called once
ctx.send.assert_called_once()
# Get the call arguments
call_args = ctx.send.call_args[1]
# Assert that an embed was sent
assert "embed" in call_args
# Check the embed properties
embed = call_args["embed"]
assert isinstance(embed, Embed)
assert embed.title == "Test"
assert embed.description == "Test"
assert embed.color.value == BOTCOLOR```
There is no real way of doing it rn, there is an incomplete and not ready pr for testing
Okay, so it's not useful for checking Discord-related functionality, but rather only for functions that do something in the background and have nothing to do with Discord?
Like calculating something or something similar?
wait no
it has been abandoned unfortunately
yeah
because it's unnecessary
it isn't
No.
Bots are so simple compared to big programs that unit testing automatically is more work than just testing stuff once manually, unless you reach sizes like dyno
why would they
It's not in the library yet, but you can upload up to 2000 emojis to your bot on the developer portal
Then to use them, just hit the copy markdown button
What is the point of that ?
so I use pfps in some of my commands, when the user has recently changed a pfp I'm getting this error
An error occurred:
Traceback (most recent call last):
File "/root/Project Valor/bot_files/cogs/Dueling.py", line 14761, in enter_depth
data1 = BytesIO(await ctx.author.display_avatar.with_format("png").read())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/Project Valor/venv/lib/python3.11/site-packages/discord/asset.py", line 76, in read
return await self._state.http.get_from_cdn(self.url)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/Project Valor/venv/lib/python3.11/site-packages/discord/http.py", line 397, in get_from_cdn
raise NotFound(resp, "asset not found")
discord.errors.NotFound: 404 Not Found (error code: 0): asset not found
before I used to just use ctx.author.display_avatar but I read that if I added .with_format it might fix the issue. Its a weird thing it doesn't happen always but sometimes many users report it at the same time otherwise its never an issue
do you have member intents?
that's why; if a member updates their avatar, the bot can't detect it
to get around this, you can just fetch the member/user
(because fetching doesn't require intents)
instead of ctx.author
isnt it better to just enable the intent?
probably
but in case they can't for some reason, they have to fetch
ideally if you can, just enable all intents lol
I'll need approval from discord
then fetch instead
ok
guild.fetch_member will have both their server-specific display_avatar and global avatar
how to put a tag in thread? (forum)
does the tag already exist
yup
use forumchannel.get_tag with its id, then use thread.edit and pass applied_tags as a list
should probably make it more convenient in future versions
Hello, is it possible for a bot to check if a message content is triggered by automod rules before sending the message ?
I own a translation bot, and in a server, some users are using it to send racial slurs using the slash command to translate. The bots seems to be bypassing the automod rules so I am searching if there is any way I can check all automod rules of the server, and if I get a match with my message and the automod rule, then I don't send the message.
maybe
how to lock and close a post?
no forget that nvm
thread.close?
I don't see any coroutine or event that I can call to check the message content I am going to send before sending it. Even after my message is sent
what I meant is that you could check the guild's automod rules and on your side "emulate" the discord behaviour
yeah, how do I do that ? I have never played with automod. I have some rules but I don't check how to edit / view / make / check them using pycord
It's not an easy thing to do that's for sure
yeah
you'd have to manually recreate all the blocked words and regexes
honestly just punish the users that abuse the bots being able to bypass automod
much simpler
I think automod only accepts * and ? in regex. No ? Do they accepts the loooong strings that nobody understand too ?
The only thing discord doesn't support in regex for all I know is lookback and lookahead
else you can do anything
okay, so I just have to use the re module to check each regex. How do I see the content and the type of each automod rule ?
if you really wanna go into that rabbit hole, check the Guild class for the automodrules getter, idk what it's called exactly
you can fetch the rules yes
fetch_auto_moderation_rules() thanks, I'm going to go into this abyss to play with the worst creature that exists... regex
good luck
after brainfuck language for sure
at least you don't have to create any new rules
Guild.fetch_auto_moderation_rules returns a list of AutoModRule
AutoModRule has an attribute trigger_metadata, which has further attributes keyword_filter and regex_patterns
just read up on everything carefully and it should be easy to manage
Do you know why I got these ... ?
for rule in automod_rules:
if rule.trigger_metadata.keyword_filter != "..." :
print(rule.trigger_metadata.keyword_filter)
if rule.trigger_metadata.regex_patterns != "..." :
print(rule.trigger_metadata.regex_patterns)
PartialEmoji represent discord base emojis or no ?
Discord and pycord docs dont say anything about that
oh, i know
it's probably the built in filters
okay this is a class of discord.utils._MissingSentinel, I will only keep the lists then
e.g. "commonly flagged words"
all these are built in and will most likely cause the ...
Also yet another discord bug, the icons are fucking tiny..
is there a way to make it so that when I send multiple of the same view I can have distinct IDs to each one? or when the call back happens I can send a value back to where the view was called?
there's View.wait() that lets you wait for an action to be taken in a view
but you can just handle whatever you need in the view's callback
I need it so that the views can be related to each other, so that if someone clicks on a button it will put something in a list and use it later.
I don't know how to do that with just the callback
Use the view's message id
that will be unique
store it in a database or something
does the allow_list can include some rust regex ?
no
okay fine !!
@bot.command()
async def getusers(ctx, *, member : str):
members = member.split(",")
for membe in members:
membe = int(membe)
membre = await bot.fetch_user(membe)
await membre.send("Test by koryai sry...")
why it not convert into a integer
but why are you getting members as str
use discord.Member as the option, only then do you get actual member objects
yea ok but change it to discord.Member lol
nah bcs wait
Here it is. not that difficult
for rule in automod_rules:
if (type(rule.trigger_metadata.keyword_filter) == list) and (any(AutoModActionType.block_message == action.type for action in rule.actions)) and (not ban_word) :
for keyword in rule.trigger_metadata.keyword_filter :
if fnmatch(Traduction.text, keyword) :
ban_word = True
if (type(rule.trigger_metadata.regex_patterns) == list) and (not ban_word) :
for keyword in rule.trigger_metadata.regex_patterns :
pattern = flpc.compile(keyword)
if flpc.fmatch(pattern, Traduction.text) :
ban_word = True
if (type(rule.trigger_metadata.allow_list) == list) and (ban_word) :
for keyword in rule.trigger_metadata.allow_list :
if fnmatch(Traduction.text, keyword) :
ban_word = False
break
Retrieves a User based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
yea but 
good job copy pasting but that has nothing to do with what I'm telling you rn
also, if you wanna use it on people you dont share a server with, you cant DM those anyway
ahj
alr
tysm for the information
why dont u use discord.User ?
you know that you can pass multiple user attribute
like do +getusers @fresh sierra @fresh sierra @fresh sierra @opal swan @opal swan
like so
ye Union
ik
but I wanna like do
- discord.User takes also an id arg
send a user id (he is not in the guild) and the bot send the msg
this would work
even if there are not inside the guild
cos its discord.User
users are not related to guild
idk
and ?
you're just repeating what i said while missing the point
i already said what you said
*, member : str): -> can be edit to discord.User and using something else it will try to catch all user that u passed inside
no
which is what i already said, just with discord.Member, which is better if they wanna use it on someone already in the guild
nah I testing it and it not found it
no
bcs discord.User is based on ctx.guild
no
where did u talk about it
it isnt
no
ctx, users: commands.Greedy[discord.User]
#1132206148309749830 message
and im not talking about that
you literally are
cos that will only work for 1 user
.
don't worry guys it was just a test
💀
a command test
ik
its more to make u learn a new thing
not related directly to that command
@bot.command()
async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'):
slapped = ", ".join(x.name for x in members)
await ctx.send(f'{slapped} just got slapped for {reason}')
ur good guy
this make that u can do
+slap @fresh sierra @opal swan reason
and it will find all member, so you dont need to fetch them
and u dont need to do one member per one member
I know it I alr read this part of doc
mb then
with pleasure
but ur .join is without []
[x.name ...]
u dont need the [] when using a .join
how work parameter "size" about discord.Asset.with_size
it's just the size in pixels
try it and see
but dont really understand what is the issue here
with_size don't work
and i'm stupid
I write .read
and I don't need it
alr
bruuuhhhh
idk why but it doesn't work ofc
always me
....
im using it like so :
png_avatar_url = user.display_avatar.with_format("png").with_size(2048).url
try adding .url at the end maybe
256 ok nice
4096 for max quality
Is there no way to have it so when a button is pressed some value is sent back to function/command that called it?
using a callback ?
Within the callback function to pass something to where the view is called, 4 views sent out to 4 pepe at once they all have to agree and I want to track who agreed and who didn't
in ur callback for exemple do it for it send a message with the id of the member
and then u choose to accept and not
u can track for exemple interaction.user.id
if u want to track based on user
the confirm.py example showcases this
which event gets fired when TextChannel.delete_messages() is called?
if multiple messages are deleted at once, on_bulk_message_delete
in that example, once someone clicks one button, the confirm or cancel, will both buttons stop or no?
the entire view will stop
okay, thank you
also would there be a way to make it so that if one user clicks cancel it will cancel the whole interaction, because right now what I'm encountering is there will be 3 view.waits() and it will have to wait for all of them to proceed to further logic
that ultimately depends on how you implement it
e.g. store all references to the views in a list, then loop through and stop them all if someone cancels
how do i prevent random choice keeps given the same output unless i restart the bot but still given the same thing again and again
item = ["item1", "item2" "item3", "item4", "item5", "item6", "item7"]
random.seed[7]
itn = random.choices(item, k=10)
return itn[0]```
i mean, you literally set a random seed
i just try every possible way, still happens even without seed
i don't understand random.choices
why not random.choice
you just want to return a random item in the array item right?
mhm!
def getitemname():
item = ["item1", "item2" "item3", "item4", "item5", "item6", "item7"]
itn = random.choice(item)
return itn
should do what you want
the thing is, it keeps giving the same output again and again
where/how is the function being called
inside class
i'm also assuming that there's actually a comma between "item2" and "item3" right? and the code you shared was simply a typo?
yes
could you provide the code on how it's actually being used
one sec
r1 = Rarity()
rr = r1.rr1 #result each rarity pull from class #1
ricon = r1.rrc1 # pulling rarity icon emoji from class #1 shortcut(ricon = rarityicon)
with open(f"cards/{getitemname()}.json") as jf:
data = json.load(jf)
lower_name = getitemname()
jc_name = data["NAME"]
jc_quote = data["QUOTE"]
jc_game = data["GAME"]
jc_element = data["ELEMENT"]
jc_thumbnail = data["THUMBNAIL"]
jc_title = data["TYPE"][0]["STANDARDS"][0][f"RARITY{rr}"]["TITLE"]
jc_tier = data["TYPE"][0]["STANDARDS"][0][f"RARITY{rr}"]["TIER"]
jc_credit = data["TYPE"][0]["STANDARDS"][0][f"RARITY{rr}"]["CREDIT"]
jc_era = data["TYPE"][0]["STANDARDS"][0][f"RARITY{rr}"]["ERA"]
jc_card = data["TYPE"][0]["STANDARDS"][0][f"RARITY{rr}"]["CARD"]```
getitemname()
did you set the seed anywhere
nope
should the file name and lower_name be the same?
yes
what do you actually have as getitemname()
but somehow it keeps 'item6' every cmd i execute
Is your computer's clock frozen somehow?
no, why
well, python uses system time to calculate random numbers
.
wdym
how is it actually defined
like the output?
it defined as string
a = getitemname() print(a) will return string from array
this!
you don't have random.seed anywhere in your code?
yes i confirm
probably ask this in discord.gg/python I have no idea what's going on.
alr ToT
How to create a command that can be used only in guilds and not in private chat
def check(ctx):
if ctx.guild:
return True
else:
#write wth do u want
@bot.command()
@bot.check(check)
async def ...(ctx):
....
or use this
:
@bot.command()
@commands.guild_only()
async def ...(ctx):
...
I mean slash commands
it's the same imo
use that
just add @commands.guild_only()
how to use bridge commands in cogs ?
search on the guide
can i get the link for it
i got it thanks
and waht about the groups
is it possible to create one for bidge ?
I remember a simple way with @bot_slash_command decorator, inside of it
got that too thanks
alr
I never rlly use slash_command
nice
I forgot how to do this command so don't trashtalk me pls 😭
@bot.command()
async def bingo(ctx, channel : discord.TextChannel):
numero = random.randint(1, 100)
await ctx.reply(f"Bingo commencé : \n**Numero**\n{numero}")
def check(m):
return m.channel == channel and msg.content.isdigit()
while True:
try:
msg = await bot.wait_for('message', check=check, timeout=800)
except:
return
if msg:
if int(msg.content) == numero:
await msg.reply("> Bravo, Tu as trouvé !")
return
0 traceback
it's weird
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="+", intents=intents, owner=[970697240953905162])
🤔
@errant trout yoooo
prob bcs i'm on IDE on my phone
nice ty it work now
you can use the contexts kwarg
i need help
await message.edit(embed=embed2)```this is returning an error:
discord.app_commands.errors.CommandInvokeError: Command 'ping' raised an exception: AttributeError: 'NoneType' object has no attribute 'edit'
message = await ctx.send(embed=embed1)
discord.app_commands.errors.CommandInvokeError: Command 'ping' raised an exception: AttributeError: 'Interaction' object has no attribute 'send'
this is discord.py btw not pycord
but they are similar
try that :
here is the full command ``` @app_commands.command(name="ping", description="test")
async def ping(self, ctx):
file = discord.File("./bot_dc/assets/loading.gif", filename="loading.gif")
waitForConfirmationsEmbed = discord.Embed(title="Waiting for confirmations", description=f"Waiting for confirmations with `a` This may take a while.")
waitForConfirmationsEmbed.set_thumbnail(url="attachment://loading.gif")
waitForConfirmationsMessage = await ctx.send(file=file, embed=waitForConfirmationsEmbed)
await waitForConfirmationsMessage.edit(embed=embed1)```
not with slash commands
message = await ctx.channel.send
app_commands are not from py-cord
why all love dragons
it worked, thanks guys
np
I want to put the "unmute all:" field next to "mute all:" but I have tried changing the inlines of the fields without success, basically I want the fields below to be shown like the second image, or is it impossible to do it that way?
inline = False ?
doesnt work
look here the code
do it on this line
It's already there, look at it in the code
@opal swan the last 2 fields have inline = False
They are in the code that sent it there
and it still shows like the picture
just in case I restart the bot
docs said nothing about it....
that's why I asked here
and it stays the same
so how did u do for the index 0 and 1 in the field embed ?
What is the problem with it?
@little cobalt
I actually like it how it is currently
you should let it like that
and at the mobile version its gonna be whole different soooo xd
Well I wanted to see if it looked better like this, but maybe you're right.
TRUE I FORGOT ABOUT THAT XD
you really should let it like that
imo it's bcs u have a lot of character for disable inline
... U didn't know that before ?
Yes I knew it but I had forgotten that point
and seeing it from this my tablet is right
I'll have to leave it like this
did u use just json for that or ur using the github thing for the color
but at least the staff liked it
discord.Color.blue
nah I'm not meaning that
you can do this or use hex
ur words in ``
but just know that this does not work for tablet
well on mobile devices in general
ofc
You can also use this:
#1033750255889559582 message
can't see the channel
just click and it will take you

is there a way I can pass a list through into a view so that the list will be updated as people intereact and I can check if someone canceled with each interaction?
Just use a DB for it
Yes, override the view's init and pass whatever you need
I don't think a DB is needed tbh. His stuff is very temporary
k
how to edit message using button?
Which message
easy way
The interaction message, a message from a text channel?
await interaction.message.edit("test")
content=
imo yes
interaction msg
await interaction.response.edit_message()
it's the first parameter so it's facultatif
idk if we say that in english
For edit you have to add content=
me i'm using wth I write
mb
If its a str
bcs me I edited message embed with my command embed
and it's like 1 month I don't use edit in interaction type button
ok thank u both of u
👍
don't use wth he said if u alr use response
alrr
would embed= also work?
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 ...
just place that in parameter embed=urembed
urembed = discord.Embed ofc
is there a way to make it so that paramters of app command are optional, and if you can make it so only people with certain perms can view certain options?
optional yes, locked to permissions no
You could technically use autocomplete to return options based on the user... but idk
mehhh quite hacky
should I use the decerator for the options or the .options type hinting?
is there any benefit to one over the other?
alright, thank you.
the decorator hijacks typehint so it's hackier anyway
ultimately it's personal preference 
in user-code its much cleaner
anyone knoe why my options with discord.Member are not working but my options with int is working? is there something specific I got to do?
define "not working"
the description set for the int is working, while the description and required option are not working correctly for the ones where I have discord.Member I don't know if that has anything to do with it or if something is wrong with my code.
this is the code
eh
longshot, but remove the types from your decorator
otherwise that code looks more or less fine? what does the command look like on your UI
restart your discord @proven valley
Man I did this so many times, I did it one more since you said it and now it works
Must be a skill issue
yes
is there any way to get file link
of?
.. Coding in js rather than pycord, but question is relevant enough. For some reason I'm receiving blank messages, I'm assuming this has something to do with my intents? Does anyone know if I'm missing any?
When printing the context it's just " "
you’re missing the MessageContent intent
u can't do all intents in one time ?
ye I remember now for js guys u need to go on intents generator or smthing like that
No because the less intents the less usage of memory and cpu and network
Enabling all intents when you don't need them is just silly
ye but all imo it's not that high
Can pages work dynamically, like based on the data it has to display or something?
wdym dynamically what are you trying to do?
pages require content to show
whether thats an embed, or message content
displaying match history, some users might have more or less matches played than others
then whats the issue?
I was asking if pages will adjust how many pages will be displayed based on data available
Pages are pages. You format the pages however you want.
You're the one supposed to handle that.
If you have an array of data, then iterate over it and create a page for each one (assuming each item is a piece of data for the user)
okay, thanks
i tested out this code https://docs.pycord.dev/en/stable/ext/pages/index.html but it returns this error```py
Extension 'cogs.page' raised an error: AttributeError: 'Bot' object has no attribute 'remove_command'
AttributeError: 'Bot' object has no attribute 'add_command'
This module provides an easy pagination system with buttons, page groups, and custom view support. Example usage in a cog: API Reference: Page: Attributes content, custom_view, embeds, files. Metho...
you need to use commands.Bot
but isnt it for prefixed command?
Exception has occurred: ExtensionFailed
Extension 'cogs.page' raised an error: AttributeError: 'Bot' object has no attribute 'remove_command'
AttributeError: 'Bot' object has no attribute 'add_command'
During handling of the above exception, another exception occurred:
File "/Users/macbookprom1/PomPom/cogs/page.py", line 265, in setup
bot.add_cog(PageTest(bot))
AttributeError: 'Bot' object has no attribute 'remove_command'
The above exception was the direct cause of the following exception:
File "/Users/macbookprom1/PomPom/main.py", line 20, in <module>
Pompoki.load_extension(cog)
discord.errors.ExtensionFailed: Extension 'cogs.page' raised an error: AttributeError: 'Bot' object has no attribute 'remove_command'```
ok, what Bot class are you using in your main file
Pompoki
and what Bot class does it inherit
import discord
import os
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
Pompoki = discord.Bot()
@Pompoki.event
async def on_ready():
print(f"{Pompoki.user} is ready and online ^^!")
int_ext = []
for file in os.listdir('./cogs'):
if file.endswith('.py'):
int_ext.append("cogs." + file[:-3])
if __name__ == '__main__':
for cog in int_ext:
Pompoki.load_extension(cog)
Pompoki.run(os.getenv('TOKEN'))```
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)