#discord-bots
1 messages · Page 19 of 1
I have a role that overwrites it...
ctx.guild.default_role
!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.
waht?
I just want to do it for every role, How do I do it
Docs: https://discordpy.readthedocs.io/en/latest/
GitHub: https://github.com/Rapptz/discord.py
Frequently Asked Questions: https://discordpy.readthedocs.io/en/latest/faq.html
Learning Guide: https://pythondiscord.com/pages/resources/guides/discordpy/
D.py Discord: discord.gg/dpy
OK SIR
:(
f
ok just leave it
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
Best way to charge for premium commands?
it returns all the channels of the guild whether a text, voice, news, stage, forum channel, text_channels will return the text channels
I guess it can be done with patreon but there may be better alternatives
there's no way imo, what you would charge for would have been already provided by some other application for no cost
but yeah patreon would be okay
if you do have them
im asking 🤷♂️
MEE6: yes:)
most big* bots
yeah was about to say that
No way people are getting paid for this stuff
You can create a website with Discord Oauth2 & Stripe API, and save premium users in a database
common people are getting fooled 
Scammed
yeah but how would I process payments? I guess its not that hard but Im more worried about user's security
Stripe will process payments
wtf
If you have the student dev pack you get some stripe benefits
well the commands im planning on making will give you access to a database with bans
No transaction fees for first 1000$ or something
like, check where x user is banned and stuff like that, and the bot has already gathered quite a few bans from 230+ servers
oh that's useful, thanks
how do I add error message, For example if a command is wrong or missing arguments, any error, Should ctx.send(error)
Add an error handler, and check for specific types of errors
It should just send the error, So it doesn't need to check
Right, but different errors will have different error messages
I would use the bot's docs command but I don't remember how its called
Okay how do I do that?
you say that when you have nitro
give me that editor
hey master👋
But this is for the info command, How do I make it global?
gifted nitro doesn't require money
plus I never asked for one
copyright
ash simps paying for ashs nitro smh

smh
nobody, literally nobody does, why you gotta even say that
cute fat cat
Use the on_error event
yeah... 7 frkin' kilos, I can barely hold him
chuncky🙀
lmao
even that is only for events 😔
7 kilos hmm that's a lot
yeah but that's again only for commands 
Which is what they want, I suppose
I guess I overfed him :XD:
i always found background image it's tough to see the code the transperency kills me
@client.event
async def on_command_error(ctx, error):
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
await ctx.send(f'Command not found. Type ?help for a list of commands.')
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'Missing required argument. Type ?help for a list of commands.')
elif isinstance(error, commands.MissingPermissions):
await ctx.send(f'You do not have permission to use this command.')
else:
await ctx.send(f'An error has occurred. Type ?help for a list of commands.')
lmao
I love github co-pilot
yeah, same, I'm choosing to leave it or to backup to the older one
Yeah that's pretty much good
that's so bad, ew
Except the else part
okimii: then gimme that bg
err i tried co pilot but it dosent suit my task it always gives code suggestions i don't need and then i switched it off
yeah raise the error in that else block
You should also use the traceback library to print the exception traceback to your console
The other person is saying it's bad.
her standards are a bit high
u can go with what u are doing
just remember to dm urself the traceback
For the most part it's good... the else is obviously wrong. it could be improved a little bit. E.g commands.MissingRequiredArgument has an attribute that says which argument was missing, so you can provide more detailed error messages depending on the command
dm or print or send in a channel
Good idea
send me that cat through the mail ill take care of him😳
he will be a box with a fragile sticker on him
he won't fit in mail u go pick it up personally
he can fit in a box😳
no, me is keeping him that fat, you dont know the recepie, also he'll be scared a lot, he lives 4 years with me
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
move in with me then😉

Isn't scargly a pokemon
i dont know english fully( so i didnt get what does move in with me mean
okimii wants to live in the same house/apartment as you
if yes: then it's not a cat, so we dont need to go there
We have some strange conversations in the internal staff only channels, of which those OTs are born
ohhh

✈️
when
5hours😪
that's a take off time?
no the whole flight🗿
@brazen raft
@tasks.loop()
async def streamThread(channel,users):
stream.filter(token)
who knows
you
camelCase😔
😳
Even this blocks io, because the stream creates an event loop waiting for notifications in itself so I am genuinly convinced this needs to be multithreaded
Unless I don't understand the tasks.loop() decorator
you need seconds or minutes or hours in it i gues
superiorCase
lowerCamelCase
Well I want it to run forever though haha
✅
while True 💀
without blocking io 🙂
Roie said there was no need for multithreading and that it can be done with tasks but i don't know how
It does run forever, seconds, minutes or hours is the interval between each loop
the case that never gets used in python😔
Is there a way for it to run forever without creating a loop, it just connects to a stream api and listens?
while True loops, as long as you're yielding to the event loop inside said while True, you're not blocking I/O
discord.py internally uses a few while True loops adhering to this rule
async def foo() -> None:
while True:
...
asyncio.create_task(foo())
What is stream
Is the Python wrapper library for Twitter's API not asynchronous?
What library are you using for this
which all it does is just run in a seperate thread
which I wanted to do manually from the start p much
- that's v1
You just have to use the asynchronous tools tweepy provides
Is it unavailable for version 2?
has a different client but is available i just checked
I just don't see the difference to just running it on another thread
There's also tweepy.asynchronous.AsyncStreamingClient if you can use streaming clients instead
It doesn't have to be
API (or literally all HTTP) requests can be issued and awaited with Python's async/await stuff instead of multi-threading
aunt
aunty ashy 
uhm, I have one aunt and he does not live with me, well in same country but not even in same city
while testing this is quite unique because it tasks a coroutine yes, but it runs when the code has yielded which is quite awesome imo
he💀

"aunt", "he"
master has stopped working
that prooves that im 100000 times stupider than everyone here
master32 playing gender bender
Maybe their s key doesn't work properly
I'm dying
that's so funny
gender blender
tf auto correct
now we all cant type😳
it's a feature not a bug
haha
fingering-
iiii cant evem tyoe properly, im too laughonf/
wytf am i goinb french
💀
omw which style?
oh my gosshhh, aight gotta remember my aunts
any preferences?👀
ITS MY WORK
anything with you in it😳
she's my aunt
hes my aunt🗿
he/she doesn't matter nnow
couldn't this drop requests if two were queued simultaneusly?
if its bare python, it would probably run 1 over the other over concurrently
why is the discord-bots chat so horny
what did he say? i couldn't see I was laughing and crying at my pillow
are u German?
its not horny, its just full of people that are sleep drunk
bro💀
worse
sure
HTTP requests are never dropped, I think, you will be waiting forever, which will only stop the current iteration of the task and nothing else in the program (assuming you are doing it asynchronously)
it's the second most active channel for a reason
at least for me
(reason=None)
idk German to me is like the first language with most weird pronunciations and words
you should try spanish
how bout russian?
Krankenhaus
isn't it very precise?
thats hospital in german
Asher es mi bebe😳
precise my ass
i am pretty sure everyother almost all languages hospital has h in it atleast but whats krakenhaus😭
kill the kraken
отель (otel') doesnt look weird?
lmao

master i sense malice coming from u just sent a tingle down my spine👀
snale isnt even a word
nail😳
it looks like encoding gone wrong
kitty under a lot of pressure
import ctypes
```
i was gonna use another synonym for kitty
you know russian was hard for me to learn, im native speaker bruh, wtf is да нет конечно (word by word trans: yes no of course)
hmm ic 👌
why does it look like little cool houses
🤔🤨🥲
paint
lmaooo your associations are so good
It's like "Yeah, no, of course"
💀
it's like "obviously not" lmao
i never thought of it
to me it looks like someone mixed utf-8 ansii and effed up encoding and put in a food processor
well actualy its "Well, of course not"
You are affirming their negatively toned question by saying "of course"
no
i would love to learn russian but im to lazy and i have no time
💀
uh
удачи
double negations are also a must in russian
me with spanish: 
W emoji
you know what? E-e
doesnt everyone speak it?
no
how
cyka, why
WHAT if I execute a short loop in my async function and another function would get called during this outside of the loop, it would get dropped or am I just not understanding it @brazen raft
i speak python, the long pauses means the indents
@shrewd apex what is your native language
i am from West Bengal so begali hindi Sanskrit and English thats my language set
You should learn asynchronous programming in Python
imagine python as real lang, you'd spend your whole life to say a good sentence on exam
i learned a bit of German in school but i forgot
oke
i thought that's a javascript thing
imagine js
It's a programming concept
me
print opening parenthesis quote hell world quote closing parenthesis
(Master32.stopped_worked === true);
no UwU u
ok cool. würdest du aber das hier noch verstehen?
Inb4 Elias gets banned
ok
bruh hell world is absolute true
i don't understand
oke
bugs have copyrights
features have patents
bugs: bzzzbzzz
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
yes it was a good convo while it lasted
bruh I pressed reply and almost sent !ot but remember that i cant delete that pythons message
isnt that you, aunt, carrying him?
🤫
alr gn guys have fun
bbye
gn
good dreams
Good night asher, dont let the bed bugs byte❤️
get it byte as in the 8 bit storage unit😳
my cat
@final walrus This server has a help channel (#async-and-concurrency) for this
😳
So if I understood it correctly, the point of asynchronous programming is to only execute one task a time, but when the program isn't doing anything (await) it will execute whatever task is next in the event loop... But isn't that exactly the opposite of what I would want with multiple objects being streamed to my 2 listener classes in real time?
alright
In asynchronous programs, there is an asynchronous event loop which schedules tasks. Only one task can run at a time because computers run synchronously (at least in the same thread). What async/await in Python lets library developers do, is use asyncio.sleep in IO blocking operations such as waiting for file reads or for stream or HTTP responses, for example, so that other tasks can run (asyncio.sleep tells the scheduler to come back to this task after the given number of seconds, so the scheduler runs other tasks if any)
So, if you use tweepy.asynchronous, you will be able to use its asynchronous classes which wrap around Twitter's API asynchronously, which means the library can abstract API interactions in such a way that lets you run other tasks meanwhile an interaction waits for a response from the API

When the program isn't doing anything
This happens when you're waiting for I/O, since, compared to CPU-bound operation (like arithmetic, for example), I/O ops like network requests, database queries, take an eternity, or at least it seems to the computer. Lots of wasted time when it's waiting for a network task to finish, so while it's waiting on that, you can go do something else
Not related to execution, but does anyone know why my IDE throws "delete" is not a known member of "None"
@client.event
async def on_command(ctx: commands.Context) -> None:
"""
Delete command invocations.
"""
# Delete Command Invocation
await ctx.message.delete()
Is it because I am using type annotations and discord.py has funky ones?
Maybe the context doesn't have a discord.Message object associated with it
I think it's because the type for ctx.message is Unknown | None according to my IDE.
Does it work at runtime, then?
Yeah it works at runtime because the type of ctx.message is only found once you send a message
The IDE can't figure it out before
How can I make it realize that it's a discord.Message? Do I just have to add # type: ignore?
yeah, that could fix it
how can I create a status for my bot which displays the current time and updates on a new minute
just ping or dm me
Also, just saying, maybe you would want to use on_command_completion instead (https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_completion)
I want to delete the invocation before, so I have to use on_command
I like how the closing parenthesis is on the next line on my screen
Thanks though
How can I create a status for my bot which displays the current time and updates on a new minute
Just ping or dm me
bbruh
discord.context.Context
ext.commands?
That's the link I got from clicking on the fancy anchor thing
and that's the thing you have to pass in !d command
What?
!d discord.discord.ext.commands.on_command_completion
discord.ext.commands.on_command_completion(ctx)```
An event that is called when a command has completed its invocation.
This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.
class MyView(discord.ui.View):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.ctx = None
async def interaction_check(self, interaction) -> bool:
if interaction.user != self.ctx.author:
await interaction.response.send_message(content="You are not allowed to do that!",ephemeral=True)
return False
else:
return True
I am subclassing around the discord View class and I want the interaction_check to send a message and delete it after like 1-3 seconds
what is the correct approach for this?
sed, there is no delete_after arg. then probably the sleep way?
Does discord.InteractionResponse.send_message return anything though
It isn't documented
it does return a coroutine
Also no delete_after is documented
Well, yes, but after you await it
Does your editor show Coroutine[Any, Any, None] or does it show something else for the third type there
oh I see thanks for enlightening
Ah ye true
Coroutine[Any, Any, Interaction]
message - interaction
What
Also, it might help type hinting self.ctx = None like self.ctx: commands.Context | None = None
For example, I like the automatic suggestions
Optional[commands.Context] :power:
I don't like importing typing
Correction
I don't like importing unnecessary modules
Doesn't it always return a Connection
When would it not
Isn't it a getter?
Oh because you type hinted the actual thing with | None
when my db will be hecked and closed for using unnecsessary 7 kilo cats
sqlite or aiosqlite huh
@brazen raft I got it to work thanks to you
I am glad I helped
Appreciated, allthough it feels like with craft or something
And it seems not to drop anything, just delays it by queueing it which is great
wth, do I really have to do isinstance(message.reference.resolved, DeletedReferencedMessage) to check if message is deleted? There must some other way, right?
it is absolutely possible
also people are lazy, there are audit logs
It's supposedly convenient, and it's for deleted referenced messages only
well pretty enough
👁️👁️
are u always watching for me?
im always watching
I am the Watcher. I observe all that transpires here. And I do not, can not, will not interfere 😳
vocobalaru
What quote
Is it a movie? I know nothing about Marvel's comics and I also haven't watched every Marvel movie obviously

How can I create a status for my bot which displays the current time and updates on a new minute
Just ping or dm me
there is no built in logging system, you should make it yourself, and the channel is just a property to where send logging messages, you can store in db or in a json file
i am not, it's just an option and so I listed it, I don't like it either
why would you state anyways, that's not a good practice too
@slate swan remember about my 3am idea about nerd bot
yeah I do, it's 3 am ?
No
got some nerdy idea?
It depends on the kind of data. It's better to use a database if you mean to be storing user data
I know.....?
I'm.......I'm speechless
wowww, can you give it to me pls, I want this satisfaction
Oh god
What he means
Now you've got me
Meaning of life is everything
what is sus
It's encouraging members to break rules ig I will have to ban it
I want some help with discord-ext-menus
Amazing
They're hard to use
d = {'yes': 'no'}
print(d['yes'])
How can I create a status for my bot which displays the current time and updates on a new minute
Just ping or dm me
Like in the image shown below :
is it possible to make your bot so that if someone tries to use a command in a channel that isnt in the bot channels, the bot simply doesnt respond at all? instead of saying something like "you're not in the right channel"
@bot.check
async def is_in_bot_channel(ctx: commands.Context) -> bool:
return ctx.channel.id in (#insert channel ids here)
When the check fails the commands.CheckFailure is raised, ig you just gotta eat it in the error handler
Personally I wouldn't recommend updating the presence every minute (there might be per-route ratelimit for that endpoint) but you can do it with the task loop
!d discord.ext.tasks.loop examples are on top
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
is there any way to add some stuff to every command?
no like not the time that the status changes like the actual current time
like giving random item on every command randomly
Like in this image
What exactly are you struggling with
on_command event
Getting the time itself or updating the presence
It works when I do it with listening but when I try to do it with watching it doesn’t work
Could you show your code that works and the one that doesn't
Sure later when I’m on pc
Okay so two questions
1) When using app_commands.check should I use it as a common check or use the deco implementation? Is there any benefit to doing it either way? https://discordpy.readthedocs.io/en/latest/interactions/api.html?highlight=check#discord.app_commands.check
2) so ik discord.AppCommandOptionType.attachment exists but how do I use that in a app_command command? https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.attachment
wait but how do I check if the message is deleted?
Might want to look into on_command_completion event if you want this to happen after successful commands only, or on_command for when a command is invoked
You use what you have shown. For normal messages, you fetch and get discord.NotFound
As for first it's only your convenience, those two methods are functionally the same
oh wait im super dumbass
all that time i could've just used try, and i wanted to check the deletness of message
But with own decorator you can parse some stuff into the function unlike with the @commands.check
I mean sort of a decorator argument
i will make some researchs
thank you

oh cool. and I found an answer for my second question
what a cool emoji :D
thanks 
❤️
Do Discord App and Bot names have limits on how long they can be?
the Bot can have a name of max len 32
thank you
how can i fix this
it means you used emulator before it was defined
@commands.Cog.listener()
async def on_message_delete(self, message):
async for entry in message.guild.audit_logs(action=nextcord.AuditLogAction.message_delete,limit=1):
embed=nextcord.Embed(title="Message delete", description= f"Deleted by {entry.user.mention} in {message.channel.mention}\nMessage: {message.content}\nMessage author: {message.author.mention}",color=0xfd9fa1, timestamp=datetime.datetime.utcnow())
await self.bot.get_channel(933978399280599080).send( embed=embed)
can someone help me with my audit log line? Im trying to correctly return entry.user for who deleted the message, but sometimes it doesnt work and returns the wrong person
Audit log is unreliable, especially for message deletes. You're just gonna have to deal with it
ahh so no fix?
@sick birch could u check this?
NAME_HEX_MAP: Final[Mapping[str, int]] = {color['name']: int(color['hex'][1:], base=16) for color in RAW_COLOR_MAP.values()}
COLOUR_NAMES: Final[list[str]] = list(NAME_HEX_MAP.keys())
def color_autocomplete(ctx: discord.AutocompleteContext):
return sorted(color for color in COLOUR_NAMES if color.lower().startswith(ctx.value.lower()))[:25]
class ColourNameConverter(Converter[discord.Colour]):
async def convert(self, ctx: Context, argument: str) -> discord.Colour:
try:
return discord.Color(value=NAME_HEX_MAP[argument])
except KeyError:
raise BadColourArgument(argument)
it just raises the keyerror
Not really, no
there is no error for this code but the bot doesnt do anything
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Probably got an IndexError then
So I have a slash command which takes a attachment input and sends it in a embed but I also want this command to send a modal.
This model will create a embed with all of the values from the modal and I also want it to add the attachment to the embed.
Is there a way for me to pass the attachment through to the model to access in the on_submit or should I use return statements in the on_submit and on_error funcs of the model and construct the embed in the command func?
Some ppl over on dpy suggested using the init to pass the attachment object in, Whilst I have used init and super init a few times now they still confuse me when writing them to start with.
Is there anything inherently wrong with doing this:
should I use return statements in the
on_submitandon_errorfuncs of the model and construct the embed in the command func?
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction does someone know why this happens?
It happens when i click sometimes the button
The strange part is that happens when i run the from vps host
When I run the bot from the pc, it doesnt throw that error
And it happens for all the buttons that i have
is there anyway to fix that?
Remove the try/except and see if you get any errors
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
still does nothing
thats super weird
What channel are you calling the test command in?
What version are you using? I'm seeing an obvious problem but it's strange you're not getting any errors
of discord.py
Right
it wouldnt necessarily error if you use an event name that doesnt exist
I'm talking about sent_msg = await ctx.send_message(ctx.channel, embed=embed)
Maybe in an older version it's called send_message?
yes this code is quite old
And ctx.add_reaction
a lot has changed since their legacy version
Are you responding to persistent view buttons i.e ones you've sent once and just click without resending each time you restart the bot? Could be the bot running on the VPS doesn't have the persistent view session data. That is mostly a guess so feel free to correct me if I get any parts wrong
whats even defining bot?
Oh yeah bot isn't used either
Whoever wrote this code doesn't seem to know what they're doing
You did say earlier that you got it from github?
I think send_message is still a thing, most ppl just prefer the shortened send method
I'd suggest you try to re-write it yourself
It's not showing up in the docs, might be an alias or something
yes i did
there's two existences of send_message, one is Client.send_message which is legacy (does not exist now), and the other is InteractionResponse.send_message which is in dpy 2.0 / forks
👍
Here it's just commands.Context.send_message which I'm not even sure was a thing in legacy?
I'm trying to access the legacy docs but it's hard to navigate lol
If i click once and the bot throws the error and wait some seconds and click again the button , ill not get an error
I don't even know if the ext.commands extension was a thing then
that error can occur if your bot takes too long to respond to the interaction (>3s), and since you said its less frequent on your PC, it might mean an issue related to your VPS is slowing it down too much
hmmm..Is this fixable?
by changing the code
if your code is potentially slow sure, you could start with a defer() so you dont have the 3 second limit
so
await interaction.response.defer()
and then the await interaction.response.send_message()
your response afterwards would need to use the .followup webhook
How i can use that?
though id test with a plain send_message('hello world') to see if rewriting your code would even do anything
Returns the follow up webhook for follow up interactions.
you'd use it like a normal webhook, i.e. Webhook.send(...)
Do I need webhook url?
the interaction already has the url set for you
Should just be interaction.followup.send("Hello World") i think based on what gamecracks said, I've personally never used it
yeah thats what i meant by the .followup attribute part...
await interaction.response.defer()
await interaction.followup.send(f"**test**")```
Is this ok?
can someone help me with this indentation
That looks right, are you getting any errors?
No its ok but for some reason it replies slow
I mean it replies after 2-3 seconds
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
and this happens sometimes again
not every time
Sometimes replies with good speed 😂
What's wrong with the indentation? Any particular line(s) causing issues?
What's wrong exactly
guys, how i can make commands run only in a specific server?
Looks fine to me, except for the missing code under the if statment on line 30
you could make a list of guild id's then on the command check if the command is being invoked from one of the guild id's
and maybe a few other little things...
mmm
sure
i'll search for this invoke guild check
IDS= ["id1", "id2"]
def is_in_server_list(server_list):
def predicate(ctx):
return ctx.message.server.id in server_list
return commands.check(predicate)
@bot.command()
@is_in_server_list(IDS)
async def dosomething(ctx) -> None:
# command here
something like that probably.
"cog" is the better way to put my commands in other folder and call in my main?
thanks so much
try it out
im getting this error
well what is the actual code for that line?
Not sure but there might be a white space on that line which could do with being removed. If its the line between the for and if statements
@client.event
async def test(ctx):
global api
if str(ctx.channel.name) == "success": #Set channel name it is viewing
guessing this is what it is
You have an empty if statement
If the channel name is "success", then what?
Oh yeah
Did i do something wrong? Or why isnt the if statement running lol
https://i.leaked-your.info/XN6SN1b3
https://femboi.best/5QipZlrc
When i print user premium guilds, its there https://i.leaked-your.info/6FX8C8vR
The guild IDs are strings in your JSON
server.id is an integer
!e print(12345 == "12345") # this is what's going on here
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
Can you make an ephemeral message not ephemeral after already sending?
Sorry pal, this was not a response to you
unless you send the exact same message in a non-ephemeral way, no
have you synced your tree?
Gotcha, are you able to auto-dismiss or delete a ephemeral message, or does the user have to do it?
the user has to delete the ephemeral
Is there anyway to restrict command use/visibility to role-specific users?
For slash commands or message commands?
slash commands
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
Appreciate you Master man
👍
Are you syncing?
The only thing I am doing is making a request to an API
@slender hamlet what request are you making and to what endpoint?
Anyone wanna make a discord bot together?
You want to get the webhook content?
Yes
you probably just get the message object and get the content of it
yt tutorials are bad for dpy
lomao
so no errors? you just run command and it does nothing right?
wait why the hell would you name the function self? I mean.. it probably won't affect but why not just name it stats or _stats?
Also.. I don't really get what does self.synced do, because in docs Client does not have this attr, but I did not use slash commands so probably it matters
there is nothing called self.synced its a custom attr
and also use a setup hook dont that in on_ready
u are in the guild with id that you set in command right?
@bot.command()
async def roll(ctx):
embed=discord.Embed()
embed=discord.Embed(title=f"{ctx.author} just rolled a ",description=(random.randint(10,1000)),color=0FF00)
Why wont it run?
Oh.
why would you create embed var and recreate it on the next line?
probably not
also in description= you put your randint into brackets
there is not reason to do that
Oh
Still a error
Invalid syntax for the whole code i sent
show the error
Yes.
it should point with ^ where is inval syntax
same?
wdym that I have?
^
the closing ) ?
I did do that
you forgot the x in your hexcode
you need to have random.randint(10, 1000)
I did that
then this @cold tide
?
Oh okay
i also saw that color is not good but i didnt think it could raise syntax inavlid
it wouldnt, the brackets were raising the syntax error, what was passed to the color kwarg would just raise undefined
ohkay
hey okimii 👋
hey y9, been a while hasnt it
a little while, few hours
lol
hi i had a quick question: what goes in place of the 123456 and token-here
webhook.send('Hello World', username='Foo')```
id and token of webhook
!d discord.SyncWebhook.partial
classmethod partial(id, token, *, session=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook").
you can get webhook's url and there are id and token in it
i only see the url but no id and token?
@silk fulcrum, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.
...
i wanted to send an example
is it possible to screenshot?
the url has ID and token in it
they're inside the url
how do i know which is which?
discord.com/api/webhooks/id/token
how long should I wait for my bot's avatar to change?
it's usually pretty quick for me
umm it's instant is it not?
sed make it leave and join again
ok..
could it be that you changed the avatar too many times in a short period of time?
the only time I changed it was when I created it
A
and second right now
you should change it in the bot settings, not application settings
this avatar will appear while inviting the bot, not on discord
🗿 same but sometime it does, sometime it doesnt
im trying to change the avatar for the webhook and when i set an image link i get this
Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/webhook/sync.py", line 792, in edit
payload['avatar'] = utils._bytes_to_base64_data(avatar) if avatar is not None else None
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/utils.py", line 570, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/utils.py", line 556, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
TypeError: startswith first arg must be str or a tuple of str, not bytes
The above exception was the direct cause of the following exception:```
?
did i not set it to a string?
ohhh so i just need to add the b in front of the string and ill be good to go?
hello, im getting an error TypeError: can't subtract offset-naive and offset-aware datetimes, may someone help me please?
@Cog.listener()
async def on_member_join(self, member: discord.Member) -> None:
created_at = member.created_at
delta = (datetime.now() - created_at).days
print(delta)
I don't know what do you want to do with that startswith but the least you can do is just remove b at it'll be a string
okok
did you do from datetime import datetime?
well anyways it's type error, not arguemnt...
You have a problem with timezones, one is timezone aware and the other is not and u cant subtract them
uhoh
another breaking change in 2.0
yes
discord.utils.utcnow() :laom:
ty
discord.utils.utcnow?
yeah that exists
Fair
Yea thats good since It’ s tz aware
now = discord.utils.utcnow()
delta = (now - created_at).days
print(delta)
its always printing 1707
i dont know why..
maybe because the time difference is 1707 days
!e
print(1707/365.4)```
Is that syntax correct?
yes
yeah thats basically (timedelta).days
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
4.671592775041051
created_at = member.created_at
but the member just joined the guild
created_at is account creation
its joined_at
yea i want to defined if its alt account or no
Ohh ok so It’ s dt
ip ban :laomeo:
Try printing everything not just .days
okay
i tried different members ids
Can you send a ss of ur code
Ty
np xd
Print out created_at
you have to add the timezone yourself iirc
created_at -->
how
datetime.now(timezone.utc) I think.
They used discord.utils.utcnow
It’ s tz aware
Oh that's the same?
Oh that's not the same
No, thats tz aware
Have accounts been created around similar time?
why is the datetime library so weird
Wdym
no
Try putting in my id
Um, actually, why isn't the datetime library so good?
you should rewrite it for me
Um, actually, pendulum is an upgraded version of datetime library 🤓
my fault 🤓
What are the upgrades
!pypi pendulum
and it won't find you cus you're not in that guild
Oh okok
@still swan what is your code supposed to do
Um, actually, I shouldn't rewrite it for anyone
Do an acc that you know when it was created
Um, actually you should
Find how long ago account was created
Um, actually, I should not
he said that he wants to check if that's an alt acc
It’ s pretty nice
Um actually not actually
I just want a code to define the alts
on_member_join
You mean self bots?
alt != selfbot
Cus I have alts that were created 2 years ago
xd..
these are alts
👀
wait wtf is this
O_O
Love this feature
when discord made it, i totally missed
For testing
@still swan add .days to your delta variable
I told him to take it out for a bit so we can see the full output
1707 days
What does discord.utils.utcnow() do exactly?
.
date in utc tz
Same as dt.now except It’ s tz aware
why not use datetime.utcnow() and compare with Member.created_at
!d datetime.datetime.utcnow
classmethod datetime.utcnow()```
Return the current UTC date and time, with [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") `None`.
This is like [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now"), but returns the current UTC date and time, as a naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") object. An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. See also [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now").
Warning
Because naive `datetime` objects are treated by many `datetime` methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling `datetime.now(timezone.utc)`.
they're same
exactly the same?
why not use discord.utils.utcnow?
I don't know
It’ s not
Um actually Why it's not?
is there any alternative of
await ctx.send``` ?
Read the 3rd paragraph
It’ s naive
message.send
datetime.now(timezone.utc) would be the same as discord.utils.utcnow
impossible
wwwtttfff
what is this monstrosity
do you even see your code?
there is 2 problems
!d discord.Message.channel.send
No documentation found for the requested symbol.
only 2
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
a bot can send stickers
i dont want triggers so
What do u wanna do
kill his code
probably use utils and get the channel object
will bot be used in multiple servers
Can you not see the 2 red underlines
await requires async def
underlines mean code is very good
You cant await coroutines outside async function
i can see but i dont know how to solve it
U can do asyncio.run
get the channel object and you can use .send on it after
But not just straight await …
master32 is genius ask him @little lava
im colorblind
😂
unfortunate

No worries 😂
Do you want this to check status continuously or just once
AHAHAHHA python is like pointing everywhere, like saying are u stupid?
continuously, but when status changed to "stopped"
pycharm moment
tomorrow
Ok so you want to keep checking status until It’ s stopped
Just wanna confirm
enslo code it for them
I wont spoonfeed
lets go
you sure
yes correct
ctx ?
i don't have much knowledge on coding but im trying..
So step one, press ctrl + A and then press backspace
it's all good
Dw ill try and guide u
they are meanies don't listen to their mean words
that's delete
im not making a selfbot for just sending that me is brainblind
Um actually, xtc?
Um actually, tcx
Yes, that wont work, even if the await outside coroutine wouldnt be an issue, it would only check it once and stop running
but thats pythons interpreter.....
Um actually, txc
but pycharm
@little lava I want you to read this https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
he won't understand it if he really is new new
I think those docs are rly user friendly
pycharm moment
y9 moment
Master32 moment ;
Pycharm wants u to make send static or classmethod
idontcare
Me
i can outsmart him really easy
me
Why
I have pro license
fair
um actually why not
Smart
I had it too, but they removed it cus of my region(
Vscode 🤮
i wanna learn how to use @tasks.loop and waht it does
@slate swan can you believe this
I had it in clipboard from b4
um actually, why if vscode better? pycharm is specially for ptyohn
stop saying um actually
Vscode is text editor with ide plugin
it's getting on my nerves 😭
ok
W
not exactly, more like an ide with a text editor
Real
Also It’ s from Microsoft
dont blender sublimetext and vs
or how its called
@slate swan When comparing strings of same lens, are their byte sizes compared?
Nope everything they make sucks, I learned it when using windows and office 356
office sucks windows I like
No but I think u gotta download some plugin for it to get ide features
I wanna punch bill gates for making windows
windwows is good only because EVERYTHING is wrote for it
I have to use windows in school for coding
every single game
Game
Windows > 😄
Not bash
windows != linux
Or brew
Yes also linux > windows
correct, windows.programming < linux.programming
absolutely
Except if u do game dev
!e
windows = 10
linux = 1
if windows > linux:
print("True")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
well it can be easier with WSL, but still not that easy as on linux

!e py windows = -10 linux = 1 print(windows > linux)
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
The fact that things need to exist for it to be easier makes it less easier
probably not, its probably measured by unicode or something else
!e
import sys
print(sys.getsizeof("a"), sys.getsizeof("A"))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
50 50
you oneline
