#discord-bots
1 messages Β· Page 1129 of 1
π
What is the command you used?
try python -m pip install ...
okay do you know events? of coure you know
i will exmple it the simplest way i could do.
def dispatch(self, event_name: str, /, *args: Any, **kwargs: Any) -> None:
# super() will resolve to Client
super().dispatch(event_name, *args, **kwargs) # type: ignore
ev = 'on_' + event_name
self.webhookEvents(event_name, *args, **kwargs)
for event in self.extra_events.get(ev, []):
self._schedule_event(event, ev, *args, **kwargs) # type: ignore
this func handle your bot events i wnat to know how _schedule_event works so i can know how i must pass the args and how do i run async func, events funcs are async funcs but i don't know how to run them
..?
lmao
huh i am bad at exmpling
and bad at english too
python -m pip install py-cord and then to run ur file you type python filename,py
thats a method in that class, look at the source code, it basically calls all the listeners
it shouldn't say module not found tho
did u do this?
I'm sorry but I don't know what you mean by giving it to another class. You want to have all the events in some kind of custom class?
yes i know but i don't know where is it i treid to find it in bot.py but didn't find it. and in the core file but nothing
ctrl+f ...
... that exacly what i did
and why do you want to use the internals?
Google for get-pip.py for python3.10 and run that file
Why do I see camelCase in there
ignore that, its not related
why is it in the Music directory π€¨
dude just make a venv and do things there
uh okay i am making a custem bot that intercat with anther bot but i want to get the events and give it to the other bot
but the quesc how do i get the events?
use that bot's bot.dispatch method then, no need to mess with internals
PS E:\Computer Science\Python\Game\Discord> mkdir temp && cd temp && py -m venv p
Directory: E:\Computer Science\Python\Game\Discord
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 6/30/2022 3:10 PM temp
PS E:\Computer Science\Python\Game\Discord\temp> .\p\Scripts\activate
(p) PS E:\Computer Science\Python\Game\Discord\temp> python -m pip install py-cord
Collecting py-cord
...
(p) PS E:\Computer Science\Python\Game\Discord\temp> python
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import discord
>>> discord.__version__
'1.7.3'
see how easy it is with a venv
you're coding in 3.9 and running with 3.10
It says C:\Users\AppData\Local\Programs\Python`Python310`\python.exe: can't open file 'C:\U....
how the bot is not a discord bot
are you sure?. i want to get all the evnts possible, theren't a way to listen to all events at the same time?
is an event
oh. how it works ?
just a minute
bruh
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
oh thanks that was helpful
how could i use it ?
commands.Cog.listener()
async def on_socket_raw_send(self,payload):
print(payload)
hey quick question how do i change path in terminal of vscode?
i dont wanna raise a channel for it
no errors, nothing at all is sent
@client.command()
@commands.cooldown(1,10,commands.BucketType.user)
async def bounty(ctx):
worth = random.randint(1000,100000)
rounded = str(round(worth,-3))
print(rounded)
if bounty <= 10000:
mbed1 = discord.Embed(
title="noob monke. imagine low bounty",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed1)
elif bounty >= 10000:
mbed2 = discord.Embed(
title="u are good but not enough to be pro monke",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed2)
elif bounty >= 50000:
mbed3 = discord.Embed(
title="pro monke, must've done some bad things to get this bounty",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed3)
elif bounty >= 75000:
mbed4 = discord.Embed(
title="damn, certified pro monke. I wonder what you did to have such a bounty",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed4)
elif bounty == 100000:
mbed5 = discord.Embed(
title="OUR LORD AND SAVIOR. WE SHALL MAKE A CREW AFTER YOU: MONKE PIRATES. WE SHALL PROTECC DA CAPTAIN!!!",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed5)
but the bounty is printed
MONKE
use shell commands
os.chdir?
im a newbie
File & Directory Commands
To navigate into the root directory, use "cd /"
To navigate to your home directory, use "cd" or "cd ~"
To navigate up one directory level, use "cd .."
To navigate to the previous directory (or back), use "cd -"
in terminal
k thanks
OKAY its "on_socket_event_type"
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
rip
your fault
u are no longer a kid mentally
smh
Yo. Today suddenly all my commands stopped working no idea why
that's cool
Did u update ur module version?
What type of commands?
all of them
context?
User and message commands
What module u using?
python 3.10
Module
context commands?
^^^
EH
hes asking what module do you use, like discord.py or disnake
I am not using disnake or things like that
eh.. I started the bot on my pc and the commands were working
when I started it on the vps, the commands stopped working
now everything stopped working expect on_raw_reaction_add events..
Guys like i have a embed comamnd
embed = discord.Embed(title="test", description="1:hello 2:bye", color=#fffff)
How can I make the description in the next line like
1:hello 2:bye
Not like that
no idea
For ex: 1:test 2:test
And i have to do
1:test
2:test
yep idk
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
eh ty
use \n I guess?
that works for strings
Ok
and how can I make this big distance between words
cuz now it is like this
I would like to make the names far from each other
like on the first picture
?
I want to make this in an embed messgae
Well _ _ _ _ _ _ _ _ _ _ _ _ that works in embed too I guess 
like this
noo I tried
I'm pretty ready to bet it works
I tried
What have you tried, most likely the wrong way
Send here what you've tried as normal message
Like this hello _ _ _ _ _ _ _ _ _ _ world
value = " ".join(data2)
And the output?
Ye
It works
wwait a sec
Yeah it does that's what I know
That's why I ask for the output
how you guys send blank messages
Zero width character probably
_ _
u mean what it shows on the embed?
two underscores with a space in between
Yeah this Hello _ _ _ _ _ _ _ _ _ _ world actually
ohh
Horrible, but works
I spammed space lmao
Yeah that will just be shrunk to one space
I believe at least
Yeah not these messages whatever
Bot messages probably
Ikr
eh it is still like this
Is that from another bot or something?
this is my bot
and the example was from an other bot
The one above with the spaces
(not mine)
this is the other bot
looks like they're using three fields with two of them having invisible titles
its what i do for my server statuses
oo
wait in theory you can do table design using fields
for the second and third fields you can type '\u200b' to get a blank title
whats wrong with direct spaces tho.?
?
i meant can't they "Mate. Mylan."?
They get shrunk to one single space at the end
Try it yourself
I think they can't
Hello, i got a problem to solve, i have a command !play to play a game but i only want the next event to run when somebody typed !play before, so if somebody random write HEAD nothing would happend
async def play(ctx):
channel = client.get_channel(988434979493122138)
await channel.send('Are you ready to lose everything {}?\nIf yes, type HEAD or TAIL after this message!'.format(ctx.message.author.mention))
@client.event
async def on_message(message):
coin_toss_list = ["HEAD", "TAIL"]
channel = client.get_channel(988434979493122138)
if message.content == 'HEAD':
random1 = random.choice(coin_toss_list)
if random1 == "HEAD":
await channel.send("You got some luck mate{}! ".format(message.author.mention))
else:
await channel.send("Not everybody born to be a winner{}... ".format(message.author.mention))
if message.content == 'TAIL':
random2 = random.choice(coin_toss_list)
if random2 == "TAIL":
await channel.send("You got some luck mate{}!".format(message.author.mention))
else:
await channel.send("Not everybody born to be a winner{}...".format(message.author.mention))```
weird-er, this appears with spaces on android but with no spaces on desktop
!d discord.ext.commands.Bot.wait_for use this for events related to commands
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
use
"```\ntext\n````"
instead of whatever youre using
I use f"{release_Date}
Then use
....
Which is with three back ticks instead of only one
And a newline indicator after the first three back ticks and before the last three (\n)
f"```\nstuff\n```"
Also a big creativity and originality from your side
Hi
How's the code jam qualifier going
π
Wasn't it Sparky who wanted the role to appear 'cool'?
i think so
Aight just wanted to be sure
i just have the role cuz i actually want to try out code jam lol
I don't like code jams kek
So if I solve and submit it I will get in, which I don't want
no?
"Code Jam Participants" - that's the role
you submit your qualifier and you have the role and you qualified but later on you need to fill out a form if youre actually going to participate so you can be a green bean like me
So I believe that yes, your participation is counted
Yeah that's just like saying 100 times you will come to a party and at the end the day before you say you don't come, it's just disrespectful towards the organizers in my opinion.
i doubt they really mind, after all the only thing they encourage is for people to try it out.
No
I want to participate
I believe you said the role was cool and you wanted it
Now people interpret it the way they want
Apparently I'm not the only one that interpreted it that you want the role kek
why do I get this, although I get a response from the bot? https://i.gyazo.com/9277080236bf58a12f3a45fe06d30159.png
You're obviously not getting a response in that screenshot
Ye I said that but I also want to participate
You're probably just sending a message in the channel and not responding to the interaction
Ye
code pls
It's probably something like .reply or something similar
ok fixed it
Or .send but on the interaction object
Good to know
Ye
had to use await interaction.response.send_message
Yes
haha
Yeah, is that some third party add-on?
Haven't seen a library using send_message for ages
its part of dpy 2.0's interactions
ye
several libraries fork from 2.0 too
No way they're still using that as name, yikes
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
response.send_message^
oh lordy lord
the most weird one was Client.say
Yeah okay that's another level
They do disnake do
interactions have multiple ways to be responded to, maybe that's why they used send_message
disnake I think you can just use i.send, unless they also changed
we are talking about response message right
About responding to an interaction, in that case a slash command.
disnake has Interaction.send() to correctly use either the interaction/followup webhook
So it's basically a short way to make your life easier
that feeling when you clean up a piece of code from 93 lines down to 43 
Sometimes it might not even be a cleanup
But brings more issues later on or make the code horrible to re-read later
@slate swan how long are u in programming?
?
Early verified bot developer
π
Oh you mean how long I've been coding for?
black - lemme change it to 120
Ye
Probably a month or two
how u got that badge then π
@slate swan i think he is owner of flantic
badges, well..
Probably not since I've never heard of that name before
I mean we're they that popular on those days?
If it's a bot, then never heard of it
@slate swan i said ig because i thought owner of flantic was krypton i just didnt knew tag
ah okay
πit has failed my nukes
then it's not me
yeah, you got one easily if you created a bot application and managed to get it added in specific amount of servers
π’ the reason why they don't give dev badges anymore
That is actually wrong
They should have a test or something
They didn't and still don't verify bots for being in ghost servers
now
Ye
You'll either get flagged for inorganic or suspicious growths
Everybody who is interested in that topic know already what happened. If not: Discord removed the developer badge for everyone who applied after august 19th.
I understand why this step was necessar...
Same when it was first introduced
Lol i also had early verified bot dev id earlier it got tokken grabbed sadly
wo cool
It was not my id anyway i also grabbed it
Yeah, that's the reason why they stopped giving it
However you've said
[...] you got one easily if you created a bot application and managed to get it added in specific amount of servers [...]
Which is wrong
You wouldn't get the badge at all if you were doing this
Yep now each bot takes a long time to get verified
You would get declined and that's it. They simply got to decline way too many - which led to huge waiting time for legitimate bots.
i wasn't talking about the fact that what kind of server it required to be, there were no verification system for intents and other things right? cause I've seen many users who have 0 programming knowledge but the badge
First they need to touch around 100 servers because thats limit then only we can apply for it to get verified
That's because the people who were added in the team of the bot in the developer portal also got the badge
oh
People just asked their friend who had a legitimate bot to add them in their team for the badge
Its not their ids some ppl buy ealry dev id and some token grab them/hack them
They should check the bots traffic
Typical behavior for sad badge hunters
and remove all self bots
Yeah that too
Self bots are hard to distinguish
I also token grabbed a early dev id
π what you tryna do β¨
Guys how we can add reaction to message?
Ye sad
Message.add_reaction(emoji)
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
Fine im late
L i dont yave knowledge about coding i am just a skid
Hover on the message and add a reaction, that's how we can add a reaction /s
@slate swan whats the argument after emoji?
the (emoji,/) the /
That's nothing you need to worry about
Simply put the emoji as argument and that's it
Ok
/ means positional arguments, basically you can't do Message.add_reaction(emoji= ...), you need to Message.add_reaction(...)
it's just to enforce the arguments before it to be made positional, and has nothing to do with as krypton said
nvm
:) me near to done with Asher's challenge!
great! what was it though?
Letβs not talk about that here please, thanks
Poll command upto 10 options with reactions
My phone just got randomly off, nice
Yep i am just talking about how polluted dc com is noe legit ppl with early verified devs id dont know a shit about coding

oh that's cool, good luck
await ctx.channel.purge(limit=limit)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'PartialMessageable' object has no attribute 'purge'
2.0
π good luck!
was the command used in dms?
no
what mind of channel was that?
text channel
no wait
its a slash command right?
no
!d discord.ext.commands.Context.channel wait
Returns the channel associated with this contextβs command. Shorthand for Message.channel.
Challenge is 90% done
Only reactions left even i tested command and it worked
Actually I was asking for slash commands today for this challenge but i made with prefix comamnd now
amazing!
Isn't that just a string split and reaction add?
krypton π yes
ctx.channel won't return a PartialMessageable
you either messed with the intents, or ctx there is an interaction
just asking, might've been something else
like with time ending, saving the results, etc.
that's quite messy, tried to make it but uhhh
@commands.command(name="purge")
async def purge(self, ctx, limit=5):
await ctx.channel.purge(limit=limit)
i'm in cogs
show intents
@slate swan
async def reaction(message,number):
if number == 1:
await message.add_reaction(1οΈβ£)
Is reaction thing correct?
emoji has to be inside strings
Ok
intents = discord.Intents()
intents.message_content = True
intents.guild_messages = True
intents.members = True
'' or ""?
yeah its the intents, change discord.Intents to discord.Intents.default()
another funny case where dpy messed.
async def reaction(message,number):
if number == 2:
await message.add_reaction('1οΈβ£')
Now?
btw you can use discord.Intents.all() since you're using them all and set .presence to false later
Ye
yes.
discord.Intents.all()
Am i right?
yes sir.
We have a poll command if you wanted to take a look at one implementation of it
Build a quick voting poll with matching reactions with the provided options.
bot/exts/utils/utils.py lines 205 to 206
for reaction in options:
await message.add_reaction(reaction)```
bot/exts/utils/utils.py line 198
if len(options) > 20:```
Oh
the bot can add upto 20 reactions for a poll
Ye it's enough
i think its because of discord limits, there's a limit to how many emojis can be added as a message reaction
lemme run the poll command code cause i wanna test something
bot/exts/utils/utils.py line 202
options = {chr(i): f"{chr(i)} - {v}" for i, v in enumerate(options, start=codepoint_start)}```
yeah you can only add 20 reaction emojis to the message π
!e ```py
l = ["first", "second", "third"]
for i, a in enumerate(l, start=1):
print(i, a)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 1 first
002 | 2 second
003 | 3 third
Ohk now I understood thanks
π
Hunter gave me complications on understanding enumerate π
Agreed.
so uwu π
def enumerator(iterable, start=0):
for item in iterable:
yield start, item
start += 1
++ moment π
lmao
https://github.com/python-discord/bot/blob/b5ab79aea21ae38fad942cc98e36c2bfe2b24e30/bot/exts/utils/utils.py#L201-L203 they using the 1οΈβ£ emoji uncodes, sick
bot/exts/utils/utils.py lines 201 to 203
codepoint_start = 127462 # represents "regional_indicator_a" unicode value
options = {chr(i): f"{chr(i)} - {v}" for i, v in enumerate(options, start=codepoint_start)}
embed = Embed(title=title, description="\n".join(options.values()))```
I see
π
wot
π
slap π
rip
Seems a good way ngl
?
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
joe mama
Objects/clinic/enumobject.c.h line 36
fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, 1, 2, 0, argsbuf);```
π€―
It's C after all
can some1 format this for me? always get the error: Not a well formed URL
stockx_url = "https://stockx.com/search?s=" + product_name + color
Look how the URL needs to be formatted and compare with a print() of sockx_url. Note that you probably need to URL encode spaces and other similar characters in product_name and color with, for example, urllib.parse.quote("...")
Is there you can make a command so it bans all users from a specific time they joined? Because servers are getting botted and yk I am trying to help
Sure. Loop through all members of a guild, check the datetime they joined. If it's after a specific interval, ban them. Make sure to add a sleep in between each ban, so you don't get rate limited
!d discord.Member.joined_at
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
ok I know the problem now. there must be "%20" for every space between the words. how can I put that between the words?
The urllib library should be able to do that for you
See my example above
How?
Someone is used to an eval
!e
import urllib.parse
print(urllib.parse.quote("Hello world"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
Hello%20world
?
My eval was with return so I got used to it
@shrewd apex challenge done!
π
Na
π
no command challenge
Wtf discord
That
poll command with graph
I'll post code lator i gtg for now
It opened Navi's profile and clicked the link in his About Me
Oof i forgot graph
okay
Can I do graph tommorow
Command is done without graph
it's ur challenge π
And I thought someone got access to my user token and made me join that server π
Thats my server link for advertising π
yoikes
Haha
I'll do it's easy
π
how can i check a user?
like whats the if statement called?
what check do you want to do?
if a user is a user yk?
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
^
if isinstance(ctx.author, discord.User):
like the command will only process if im the user if not it will run my else:
thank you :)
if ctx.author.id == your_id:
Add a decorator for that I guess
just a conditional would work...?
helpful :)
Or commands.owner_only()
thanks
Forgot what it was called
is_owner()
Yeah it's that I think
That, yea
Can you make? Huh see that you can make before telling to others
@shrewd apex can you have me. Any idea how would I add graphs to my command?
Pyplot?
yeah u can or just generate an image
or just use reactions for bargraph like a progress bar
I am not able to understand how would I update the graph when someone add reaction
As I said, I started coding 1-2 months ago. Have you ever heard of sarcasm? If not I recommend this wonderful article explaining it https://wikipedia.org/wiki/Sarcasm
Idk how to use on_reaction event
π₯ π₯ π₯ π₯ π₯β¬
Hmm it's ugly
oh you mean a graph like that
I'll prefer bar graph
if u can alr
well for that you don't need a library either way 
Can you help me at one thing
How can I do that when someone add reaction the graph gets updated?
Listen to the event and edit the message, store the message ID and channel ID in beforehand so that you can use them in the event
Can you give me example of the event?
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
It works like any other event
How to use it?
Add the decorator, create the function, add the parameter it needs and then put your if statement to check if the message ID is the right one, then edit the message based on the ID you've saved before
It's very confusing π΅
You can get the message ID to reaction got added to with payload.message_id as the documentation says
π΅βπ«
First add the event so that you see it triggered
Then just print the message ID
Then you can continue by adding a check to see if the message ID is the message ID of the poll
@bot.listen("on_raw_reaction_add")
async def rrad(payload: discord.RawReactionActionEvent) -> None:
if payload.message_id == your_message_id:
#do stuff
you require Intents.reactions for this
don't see anything confusing right here
How can I get message id of the poll comamnd?
It is confusing if you don't have enough background in python
Save it somewhere when you create the poll
^
Like i used poll comamnd it's id is 12547837
And i used it again 53883838
So the first one poll comamnd would be useless
You send the message with the poll somewhere, assign that to a variable and then you can get the ID of that message
Like
x = await ...send(...)
x.id
Ik that but
are u using cogs?
Then you have to save that to use it later
Yes
just make a class attr and store it there
Ok
Class attr?
storing the message id in a class attr to use in the listener
wtf then if the bot shuts down, the effort would be useless
Example?
Guys i have a simple question can I ask?
absolutely
Like i used poll comamnd it's id is 12547837
And i used it again 53883838
So the first one poll comamnd would be useless
So if i want if i add reaction in both poll message the graph get updated so how can I do that?
Dictionaries/lists exist for saving multiple message IDs of these polls
class MyCog:
@command()
async def ...():
self.msg_id = message.id
@commands.Cog.listener("on_raw_reaction_add"))
async def rrad(self, payload: discord.RawReactionActionEvent) -> None:
if payload.message_id == self.msg_id:
u might have to handle some things, but this should work
yup
At least the example
I'd put either an array or dictionary
Sorting the message ID of the poll and the message ID to edit, if they're not the same
And even that, if the bot restarts it's gone, that's when a database would become useful
Thanks, is there any documentation or tutorial on this?
Not really sure where to start from.
The library documentation
Where you can see the attributes of each object
And research what could help you
class Menu(menus.Menu):
async def send_initial_message(self, ctx, channel):
self.m = f'Hello {ctx.author}'
return await ctx.send(self.m)
@menus.button('π')
async def on_thumbs_up(self, payload):
...
@menus.button('β')
async def on_stop(self, payload):
self.stop()
class MenuCog(Cog):
def __init__(self, bot: Bot) -> None:
self.bot: Bot = bot
@commands.command()
async def hello(self, ctx):
await Menu().start(ctx)
or they can use menus, it creates a new instance every time function is called, so don't have to do any checks
For your example - You need every member of a guild, so let's start by searching for the Guild object in the documentation.
After you've found it you can look at an attribute that could give the members list of that guild.
Once you've found that you can search for an attribute on a discord Member object in the documentation that would give the date when they joined.
Now you're just missing how to get a Guild object, a Context (often shortened as ctx) is also on the documentation, so you can take a look at it and see what could give a Guild object.
Then you're done with getting the information and it all comes to making the final logic.
yeah but for a poll with up to 10 options i'd rather use a select menu
ya that works as well
hi, my bot command is slow, is there a way to fix that? may someone help me please?
Are you running it on your computer or where are you running it
on my computer
Maybe dumb question but, is your computer performant enough and has a decent connection
Otherwise you'd need to share your code for the command
the first command is working well but the second command is taking long time...
Yeah then you'd need to share code of your second command
what does the second command do?
Might be something time consuming
@cooldown()
async def voicechannel(ctx: commands.Context) -> None:
if not JsonAttrs.CommandsManager.VoiceChannel.from_owner_id(ctx.author.id):
await ctx.reply(f'There were no **temporarily voice channels** owned by you.\n_For better explanation use ``{JsonAttrs.prefix}{bot.help_command._command_impl} {ctx.command}``_')
raise ErrorHandlerException()
if len(ctx.message.content.split(' ')) == 1:
await ctx.send_help(ctx.command)
@voicechannel.error
async def on_voicechannel_command_error(ctx: commands.Context, error: commands.CommandInvokeError) -> None:
if isinstance(error.original, ErrorHandlerException):
return
raise error
@voicechannel.command(syntax_examples=['{usual}'], description='1')
@cooldown()
async def lock(ctx: commands.Context, option: Optional[str.lower]) -> None:
obj = JsonAttrs.CommandsManager.VoiceChannel.from_owner_id(ctx.author.id)
channel = await bot.fetch_channel(obj.channel_id)
everyone_overwrite = channel.overwrites_for(channel.guild.roles[0])
author_overwrite = channel.overwrites_for(ctx.author)
async def lock_voice():
everyone_overwrite.connect = False
await channel.set_permissions(target=channel.guild.roles[0], overwrite=everyone_overwrite)
author_overwrite.connect = True
await channel.set_permissions(target=ctx.author, overwrite=author_overwrite)
obj.lock.voice = True
async def lock_chat():
everyone_overwrite.send_messages = False
everyone_overwrite.add_reactions = False
await channel.set_permissions(target=channel.guild.roles[0], overwrite=everyone_overwrite)
author_overwrite.send_messages = True
author_overwrite.add_reactions = True
await channel.set_permissions(target=ctx.author, overwrite=author_overwrite)
obj.lock.chat = True
if not option:
await lock_voice()
await lock_chat()
return await ctx.reply(f'both **chat** and **voice** for <#{channel.id}> have been locked.')
elif option.startswith('v') and not obj.lock.voice:
await lock_voice()
return await ctx.reply(f'<#{channel.id}> **voice** has been locked.')
elif option.startswith('v') and obj.lock.voice:
return await ctx.reply(f'<#{channel.id}> **voice** is already locked.')
elif option.startswith('c') and not obj.lock.chat:
await lock_chat()
return await ctx.reply(f'<#{channel.id}> **chat** has been locked.')
elif option.startswith('c') and obj.lock.chat:
return await ctx.reply(f'<#{channel.id}> **chat** is already locked.')
when i use the command .vc lock
its taking long time, like 3 or 4 seconds
Well first I'd type hint to a channel object instead of a string lowered
Then you don't need to make an API call with fetch_
As you already have the object
how
no the option is like, if its going to lock the voice or the chat
temp voice channels that owned by someone etc
ah yeah got confused with the parameter name
xd...
but this command is slow idk why...
Well yeah shouldn't be slow. have you compared with your other faster command, if it's the unlock command
i didnt make unlock command yet but everything is working good except this
I'd take a random guess and say the JsonAttrs thingy might slow it down
i only have this command tbh XD, but .vc command is working good, also the task loop but .vc lock isnt...
Its just a class that control the json file etc
getting the data and changing it
You can try put some print statement before and after your code does something, to see approximately how long that took to execute
Yeah well depending on how to read and change it, it can take some time
I'd just check quickly
oh
okay xd, 1sec
I don't see why not but it's a bit odd.
Good question actually. The wait for may pick up the message that triggered the on_message
The on_message is already waiting for a message anyways
ok thx
Might trigger it twice
Robin you got some time for my question? π
i womder what i did wrong
Once for the global event and one for the wait_for
i think its because the computer xd
Sure, I'll take a look
Possible yeah
It's in #help-coconut :3
Alright I'll be there in a min
another question
embed.add_field(name="Created At", value=datetime.strftime(member.created_at, "%A, %B %-d, %Y"))
ValueError: Invalid format string``` any ideas?
when i react to the message
Does %-d even exist?
why doesnt it work
idk
like
it doesnt
what should i try then
hold on
Remove the -
ok
alright
yes sry
try:
reaction, user = await ctx.wait_for("reaction_add")
except:
pass
else:
user_roles = user.author.roles
print(user_roles)
permitted = False
for i in ["Operator", "π Executive Operatorπ", "πModeratorπ"]:
if i in user_roles:
permitted = True
break
if permitted:
print("so this happened")
await ctx.remove_roles(991367608324608061) # Removes unverified role
await ctx.add_role(991622560519311401)
await ctx.reply("You are now verified!")```
why doesnt the else statement run when i react on the message
Well one reason is pretty simple
user.author.roles returns a list of role objects, checking if a string is in a list of role objects will always return false
ohhh
Hence permitted will always be false
So it probably goes into the else statement, just doesn't do anything
how do i make it so that it returns a list of the roles as a string
You can create a new list that contains the name of the role
One liner or whatever you want with r.name, r being an iterated role object
userroles = [a.name for a in user.author.roles]
The name of the role.
roles*
not very good with list comprehensions
for a in user.author.roles:
print(a.name)
its a class property
ok
And .name will be that attribute
ok got it
On mobile π± π
imma try the bot now
Β―_(γ)_/Β―
Thanks for explaining him
so i tried it
sparky no take part in jam?
the else statement still didnt run
user is already a user/member object
syntax for both if and else in a list comp is a bit diff
so like [a.name for a in user.roles]?
Yeah
ye
ctx.add_roles doesn't exist - it would be user.add_roles
member π
user
i forgot to mention that was the main problem but somehow this convo it shifted to the user_roles xd
That's how they named their variable if you read the code.
still thanks tho
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
that's a naming convention π
nono i made a ctx var
That doesn't matter
user is for dms i think member being for servers
Just saddening to see how this channel hasn't changed for the past months
it hasn't, we like good code π
wdym
names = [role.name for role in user.author.roles]
permitted = any(m for ["operator", ...] in names)
if permitted:
...
this could be better and faster than a for loop tbh
nvm
too late already ig
I see the for loop
dude
π
any fix for the else statement not running?
send ur code
k hold on
try:
reaction, user = await ctx.wait_for("reaction_add")
except:
pass
else:
user_roles = [a.name for a in user.roles]
print(user_roles)
permitted = False
for i in ["Operator", "π Executive Operatorπ", "πModeratorπ"]:
if i in user_roles:
permitted = True
break
if permitted:
print("so this happened")
await ctx.remove_roles(991367608324608061) # Removes unverified role
await ctx.add_role(991622560519311401)
await ctx.reply("You are now verified!")
Same
i should learn how to use list comps π
[operator] is this list of role names?
any(m for ["operator", ...] in names) what's that even supposed to mean
use the finally keyword instead of else or unindent the code after removing else
ye
ohh ok
if any name in your_specific_role_names in role_names
checks = set(["Operator", "π Executive Operatorπ", "πModeratorπ"])
user_roles = set([a.name for a in user.roles])
if checks & user_roles:
print('Present')
else:
print('Absent')
isn't that
any(name in ["operator", ...] for name in names)
wai
works for me dunno
!d for I gotta go back in time and take a look at this now
You can't
rip
you can panda
alright it works
You can see if they have boosted the server.
Bet show..
problem is
click on profile then see the nitro badge
check user badges?
.
Yes
UnboundLocalError: local variable 'user' referenced before assignment
same goes to you Ashley F. Ketchum
It's not a badge accessible by the bot api afaik
no direct way to check for nitro sub
Actually i didn't got that msg my WiFi sucks
nope
sheesh
in reaction, user = await ctx.wait_for("reaction_add") the user var is the one that reacted right?
Hunter are you good with asyncpg?
never used postgres, sorry
:(
Hunter's a God, Panda π
My brain is having a fatal error.
But u might wanna try yr luck in #databases or #βο½how-to-get-help
help
I already did the #βο½how-to-get-help 
Sad
But I always ask difficult questions apparently it's coconut.
yikes a run until complete

ask easier questions next time :)
Just for fun lmao.
yup cz why not
stop making me think that I'm hallucinating
hallulla abdallah vallah you're thinging to yourself imaginary stuff
why use run_until_complete tho
it's long and I like long stuff
sus, and nice.
I just violated rule 9, living on the edge 
!rule 9
thing
why am i getting Local variable 'user' might be referenced before assignment error
try:
reaction, user = await ctx.wait_for("reaction_add")
except:
pass
finally:
user_roles = [i.name for i in user.roles]```
there was an exception
that's the worst try except I've ever seen
^
im sorry π
u should not use a bare except
Whom ur talking to?
...? nvm
I am navi'alt
I wanted to ask if I used the command and the ID is 5939938 and I use again and I'd is 6378288 so when I'll reasct to first one it will not work . So how can we make all work
just don't use try either
oh
ashley on drugs
i thought i needed to use a try except statement for wait_for
u might wanna take this to an ot tbh
u need try except when u use a timeout
oh
rip just one message
like asyncio.TimeoutError
@shrewd apex tell me what would I do to make it work
If there is no solution for this
I would lose the challenge
the convo gonna go on and on and on and on and on and.....
on
hunter looks into the future
Ye
ot again lol
work what?
Like I used the command and message I'd is 45584938 and I store into variable
mhm
And if I use poll command again and store 73883838 message id into variable the first one ID would stop working
remind me why u are not using a json again?
I am not able to understand the strategy
Can yiu have a idea what you are telling me
wait a sec
Ok
Build discord bot using discord.py based on images. - Discord.py-Bot-Series/poll.py at main Β· DevStrikerTech/Discord.py-Bot-Series
if member.premium_type >= 1:```
Why does not it work?
Compare it with PremiumType enum
How can I do that?
Member class has no premium_type attribute, what do you want to check?
I've been looking all day for a way to check if a user has nitro
the api provides you no way of doing that, you can just make some guesses, like checking if the User's avatar is animated, they have a custom banner, or if they are boosting a server
What does ctx.author print
And the attributes in discord.Profile like premium and nitro that return True or False, they don't give anything?
ctx.author.mention or ctx.author.name
I mean like what does it print
name#discriminator
Ok thanks
!d discord.Member.profile
No documentation found for the requested symbol.
its deprecated
Can some make me a discord bot? I cant invite bots for some reason.
how can you trust some random person on making a bot, and can't invite and use a public bot?
ok
do you have to implement it
What was the way btw?
can't you look for badges?
No
I didn't find nitro in public flags
it doesnt detect nitro but flags like hypesquad and other things
Ye
!d discord.Member.public_flags
property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.public_flags "discord.User.public_flags")
There is no way in the API to reliably check if a user is nitro
it was deprecated since 1.7.3
i think thats the only way, if someone is aware of others please add up
bro i spam clicked and download a 5gb video 10 times π π
!d discord.UserFlags.premium_promo_dismissed
The user has dismissed the Discord Nitro promotion.
well, the doc says pretty much what it does
This is for promotions such as the epic games thing
Also, there is a way to check whether or not a user is nitro. But this requires you to use oauth2 scopes, meaning you'll pretty much never end up getting this information with a regular bot
Perhaps in a dashboard where you ask people to login, or some sorts
why is there no normal way to check in api? userflags for example?
I'm gonna assume it was designed in that way to stop advertising or something? Like official discord developers actively tell people not to give rewards for invites, I'm assuming it's something like that
maybe because of privacy and thats really not something related to bots, similarly you can't even get a user's About Me
did they ever allowed checking that
?
How does this affect privacy?? This is public info
I never said anything about privacy?
it was me
ops, yes
I will then make a user feature checker with nitro
._.
i can think of one, bots that dm nitro users to boost a server
would be bad
Not really, when you consider you can automate bots but not users
For example if you've got a bot in a large server with potentially thousands of members, a bot can easily get all of their about me's, while a user really can't do that manually without a lot of work
already understood
that's the point of a bot
we like bots
not music bots tho
I barely use bots for the very reason that makes them great, the events stuff
Most importantly MESSAGE_CREATE, I like to keep my messages to myself and the people I specifically send them too
Kind of ironic, being that the platform is discord where pretty much you are monitored
can you do slash commands with discord py?
yes
interseting
oh they just added them, cool
"second last" π
that is?
?
the first thing ill suggest is to learn by docs instead of youtube tutorials because most of them suck.
I'm confused, is there no way to fetch message object from message id?
@slate swan Hello?
i have your token, go reset it.
ok
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
the twoth written source of the lasts made to be remembered in this specific writing session of ours
is there no way to fetch a message object from just the id of the message?
are you happy
done
Amen.
already invalidated it
did u guys familiar with command, "crushxx" or "crash+" something like that...
all my channels just disappeared with command like that & deleted by itself, did u guys know WHY thats happen?
what
what library are you using
we are making discord bots, not nuking our own servers with premade ones
discord
done
iom fine with using a different library, im just doing like one small thing
now start with making a basic bot, learning how to respond to messages and events, how cogs work ( because how the tutorial is doing it is def not how it works ) and then look forward for a music bot and get !ytdled
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
dont you have the channel id though?
lol i never learned what cogs are, i just have everything in a 3k line file
no
I highly recommend learning them.
!d disnake.Client.get_message exists but works only when the message was sent during tuntime
get_message(id)```
Gets the message with the given ID from the botβs message cache.
yea cant do that
Using the API to fetch a message without a channel ID is impossible
The endpoint URL Is formed with the channel ID after all
all ids are unique, how can there not be a way to fetch it
well then fetch uses the channel.id in its route
im confused
there is, but do you wanna loop on all channels your bot can see and make requests to them?
Yo andy, do you know any good nvim rust plugins which like show the errors on screen and highlight stuff?
sure
nvim-lspconfig
ill need to do it about 100 times for like 1000 channels but all g
Setup a rust language server to lint or something
its a one time thing
require('lspconfig')['rust_analyzer'].setup{
on_attach = on_attach,
flags = lsp_flags,
-- Server-specific settings...
settings = {
["rust-analyzer"] = {}
}
}
ah nice, thanks
What method can be used to check if a user's banner is animated? Or just a custom banner
im confused
sorry, how do i loop over all the channels the bot can see? (answer after these other peeps ay)
!d discord.Client.guilds
property guilds```
The guilds that the connected client is a member of.
!d discord.Guild.text_channels
property text_channels```
A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
!ytd; read this
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
!d discord.Client.get_all_channels
for ... in get_all_channels()```
A generator that retrieves every [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") the client can βaccessβ.
This is equivalent to:
```py
for guild in client.guilds:
for channel in guild.channels:
yield channel
``` Note
Just because you receive a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") does not mean that you can communicate in said channel. [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for") should be used for that.
!d discord.Asset.is_animated
is_animated()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)"): Returns whether the asset is animated.
i just thought they wont need to get thevoice, stage and category channels ;-;
oh so i loop over all guilds and all text channels, thanks
I found out what was wrong in my code and apparently the wait_for kept coming up as a cancelled task but I tried this (below) and it still isn't working, any help?
try:
ll = await shield(bot.wait_for("message", timeout=1800))
except asyncio.TimeoutError:
async with chn.typing():
await asyncio.sleep(random.choice(times))
embed = discord.Embed(...)
# more code
The best way I can explain is that the wait_for seems stop midway through the process and just doesn't do anything when it finishes, as if the timeout is too long.
But when it's a short time, for example, 30 seconds or even 5 minutes (300 seconds), it does everything correctly.
It doesn't work with long periods of times like 3600 seconds
what does it mean
i read it
maybe your bot listens to another some other message in that time being?
Oh right they are looking for text channels specifically
creating a discord bot that plays music via YouTube is against YouTube's terms of service
ohh
music bots are against youtube's ToS, so we dont provide help with that.
ok
i think i will have to use that, since i also want to be able to check dms, ONLY BECAUSE IM CHECKING IF THE BOT HAS SENT SOMETHING SPECIFIC IN THE CHANNEL im not spamming i swear π
thank you
How then to independently check the banner and avatar for animation?
man you asking the hard questions
So if the message isn't from that channel, it ignores it
there is no way in heaven or hell you code like that
are you doing that for just checking a message, no intents of making a bot run or something?
Damn, give a beginner a chance-
the wait_for message could be any message since you aint using a check
if member.avatar_url.is_animated() == True or member.banner_url.is_animated() == True```
Dont worked ._.
well yea, i want to find every channel where someone has said a specific string (that my bot has allready stored so no need to request discord) then after i collect all those channels i will do something
banner wasnt even added in 1.7.3
maybe get their avatar url and check if it ends with .gif
use hikari then. it has a RESTBot which can do this stuff easily
they can also end with .webp
π
member.is_avatar_animated()
async def on_message(ctx) :
