#discord-bots
1 messages · Page 506 of 1
???
can you explain your question
Lemme show u what I want to do
so, in this code, I want my bot to automatically check if time is in the list of modules and if it is, then add a line import time into the code
how are you going to get the list of imports
and how are you going to know whats imported
and whats not
I can use sys.modules and sys.builin_module_names to get the list of modules and check if the module name is in any of them
And I can use an except with NameError, and do all this in that block
Why not do it how jishaku does it
I don't use jsk
I have my own working eval
wait nvm
Jus see how they do it lol
I misread understood your question
Ah, well I didn't know jsk can do that. I'mma see how they do it. Thanks for the headsup!
you can use sys.modules? how? parse the code manually?
can someone help me im wanting to learn how to use embeds for my bots help menu
wym......?
you have code a string
Check pins
and you say you want to check sys.modules
pins?
that means you'll have to parse the code
Nice! You're already 10 parts in, good job! In this part I'm going to show you all about embeds.
I would just catch NameError exception
and get the name which raised the error
if the name is a module, then add an import line in the code, else just send the error
what if the NameError was raised on something thats not a module
^^^
sys.modules are the currently imported modules
Oh
Well it is a list of loaded modules, as said by Python docs
so yea, lemme see if there is any other way
just check how jishaku does it with module!
Ig they use ast? I haven't seen the impl myself
Yeah same
I am making a deco (first time), and was trying to get the ctx object. So I should do args[0] to get it?
cant you just do def wrapper(ctx, *args, **kwargs)
That gonna work? Dang
ah wait, nvm. I am just mentioning one param instead of getting from args
if its always passed in as the first argument yes
Andy won't like that Callable typehint 😩
also its better to do Callable[..., Any]
Why tho
because its not complete
u mean annotions?
and not correct
Cuz ^
have what
Nvm
The typehint?
:loading:
Haha MyHelp is a class
Hmm
i think he can just check if the function has the __self__ attr
Oh okay
nvm
check the instance
Don't mind me, I thought it wasn't a command
I think I'mma do
if isinstance(args[0], Context):
. . . .
That's a bad Ellipsis!
Uhhh, what?
!e ```py
print(...)
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
Ellipsis
Can you be slow like a lil :crying:
Ah, well it was just some context I was giving
🤣
So in a Cog, self will always be the first param... Gotcha
staticmethods laughing
when I use them I get called dumb so you shouldn't.

Haha
you're always dumb nova

how to fix this now
whats wrong with this?
(I suck at typehinting)
color
?
remve the ()
ok
why ctx is optional there haha
why would you set ctx = None
like None.send
why is it showing Unknown?
Oh
Idk much about typehint stuff sry
discord/ext/commands/context.py line 69
class Context(discord.abc.Messageable, Generic[BotT]):```
see the Generic
Ah
Pylance screams at me if I don't do them
static typing will be future
noooooooooo. I do most of my coding by looking at those lmao
my error:
main.py:149: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
await ctx.send(embed = discord.Embed(title="test 1", description="test 2", colour=0xffb300()))
They are garbage, they jus get complex easily and like, they are hard to read too.
That is what I told...
Haha
remove the ()
Not always but when things start getting deeper into the hole
-> Callable[[Callable[[Request, HTTPException, Union[PartialRoute, Route]], Coro]],
Callable[[Response, HTTPException, Union[PartialRoute, Route]], Coro]]:
``` not very complex
Indeed
Ikr
you probably didnt close a (
Someone please can check this? It keep raise ExtensionNotFound but i can t understan why
Weird
the rain destroyed me. anyways
new_embed = embed_message.embeds[0]
tempTuple = new_embed.fields[0].value
tempList = list(tempTuple)
tempList[1] = "test"
tempTuple = tuple(tempList)
new_embed.fields[0].value = tempTuple
print((new_embed).fields[0])
await embed_message.edit(embed = new_embed)
@hasty iron if youre still here 🙂
what line is causing your error
well the problem really seems to be that when i do "new_embed.fields[0].value = tempTuble"
when i print it, it doesnt seem like it updates the embedded tuple
because i understand that tuples cant be changed, but they should be able to be replaced right?
async def wrapper(*args, **kwargs):
if isinstance(args[0], Context) and not in_a_cog:
ctx: Context[Bot] = args[0]
elif in_a_cog:
ctx: Context[Bot] = args[1]
try:
task = ctx.bot.loop.create_task(wait_for(fut=func(*args, **kwargs), timeout=timeout)) #type: ignore
return await task
except TimeoutError:
return await ctx.send(f"Hey there! Sorry, but the command timed out after {timeout} seconds, {ctx.author}") #type: ignore
But then, in my eval it is raising an error that a kwarg (*, code) isn't being passed
why are you creating a task and then immediately awaiting it
Oh wait, nvm. I forgot to do functools.wrap()
just await the wait_for directly?
U mean I should just make them in one line?
ah okay
im having a really weird error with something being undefined, if anyone can help lmk
basically, i defined "buttons", but in my actual command where it says "await message.edit(components=buttons, embed=embed", it says buttons is not defined
show how you defined buttons, maybe i'll see something while waiting for help 😄
Okay so that doesn't work. Still blocks the bot haha
Define buttons as a Button object
one moment
buttons = [
Button(style=ButtonStyle.grey, label = '1'),
Button(style=ButtonStyle.grey, label = '2'),
Button(style=ButtonStyle.grey, label = '3'),
Button(style=ButtonStyle.grey, label = '×'),
Button(style=ButtonStyle.grey, label = 'Exit')
],
[
Button(style=ButtonStyle.grey, label = '4'),
Button(style=ButtonStyle.grey, label = '5'),
Button(style=ButtonStyle.grey, label = '6'),
Button(style=ButtonStyle.grey, label = '÷'),
Button(style=ButtonStyle.grey, label = '←')
],
[
Button(style=ButtonStyle.grey, label = '7'),
Button(style=ButtonStyle.grey, label = '8'),
Button(style=ButtonStyle.grey, label = '9'),
Button(style=ButtonStyle.grey, label = '+'),
Button(style=ButtonStyle.grey, label = 'Clear')
],
[
Button(style=ButtonStyle.grey, label = '00'),
Button(style=ButtonStyle.grey, label = '0'),
Button(style=ButtonStyle.grey, label = '.'),
Button(style=ButtonStyle.grey, label = '−'),
Button(style=ButtonStyle.grey, label = '=')
]```
oh, so its an array or arrays of buttons,
yes
does component accept that, have you tried feeding it like buttons[0][1] and see if it works?
@commands.command(aliases=['calc', 'c'])
async def calculator(self, ctx):
message = await ctx.send(content="Loading calculator...")
await ctx.send(message, delete_after=3)
expression='None'
delta = datetime.utcnow() + timedelta(minutes=10)
embed = discord.Embed(
title=f"{ctx.author}\'s | {ctx.author.id}",
description=expression,
timestamp=delta
)
await message.edit(components=buttons, embed=embed)
instead of components=buttons -> components=buttons[0][1]
should i change the components=buttons to components=buttons[0][1]?
because i know that for adding reactions, i couldnt await several ones in a single call, i had to do an await for each individually, so maybe something similar is happening
yeah, try that
embed = discord.Embed(
title = f"{client.user.name} is online!",
color = client.embed_color,
timestamp = datetime.datetime.now(datetime.timezone.utc)
)
embed.set_footer(
text = client.footer,
icon_url = client.footer_image
)
client.log_channel = client.get_channel(log_channel_id)
await client.log_channel.send(embed = embed)
``` don't get what is wrong
same error, "buttons is not defined"
Okay so
great feeling
hmm, id like to see your code, where did you define it. does it have access to it
ill dm you the cog src
try:
task = ctx.bot.loop.create_task(wait_for(fut=func(*args, **kwargs), timeout=timeout)) #type: ignore
return await task
except TimeoutError:
return await ctx.send(f"Hey there! Sorry, but the command timed out after {timeout} seconds, {ctx.author}") #type: ignore
task is a blocking task, how to end it in the except clause?
I need the theme's name.
is it possible to send an embed without ctx?
If u have the channel object, sure
task.cancel()?
embedA=discord.Embed(title="GOAL")
embedA.add_field(name=submission.title, value=submission.url, inline=False)
await channel.send(embed = embedA)```
doesn't work
I have the channel and can send a message fine outside of an embed
in the except block, it is reachable? czzz
then do ```py
task = loop.create_task(wait_for(*args, **kwargs))
try:
return await task
except TimeoutError:
task.cancel()
...
ah okay
i dont understand this error
let's see
U have a missing bracket in the preceding lines
?
Still no work lol
what do u mean
u have a missing )
but i dont
Bruh
Lol
my pc is garbage, it takes 2 minutes just to install everything
1 minute to install just embed
anyone who has a bit of tuple knowledge? 🙂
my error:
Ignoring exception in command test:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 149, in test
await ctx.send(embed = discord.embed(title="Fun Commands:", description=""))(embed.add_field(name="<ping", value="Bot replies with 'pong!'", inline=True)(embed.add_field(name="<poll2", value="starts a poll with 2 options.", inline=True)(embed.add_field(name="<poll3", value="Starts a poll with 3 options.", inline=True)(embed.add_field(name="<say [word]", value="Bot repeats what you say.", inline=True)(embed.add_field(name="<diceroll", value="Rolls a six-sided die.", inline=True)(embed.add_field(name="<mobprofile [mob name]", value="Bots sends the profile of the specified Minecraft mob.", inline=True)))))))
AttributeError: module 'discord' has no attribute 'embed'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord' has no attribute 'embed'
Embed*
capital e discord.Embed
capital E
just ask your question
i did, ill do it again
new_embed = embed_message.embeds[0]
tempTuple = new_embed.fields[0].value
tempList = list(tempTuple)
tempList[1] = "test"
tempTuple = tuple(tempList)
new_embed.fields[0].value = tempTuple
print((new_embed).fields[0])
await embed_message.edit(embed = new_embed)
well the problem really seems to be that when i do "new_embed.fields[0].value = tempTuble"
when i print it, it doesnt seem like it updates the embedded tuple
because i understand that tuples cant be changed, but they should be able to be replaced right?
my new error:
the profile of the specified Minecraft mob.", inline=True)))))))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in command test:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 149, in test
await ctx.send(embed = discord.Embed(title="Fun Commands:", description=""))(embed.add_field(name="<ping", value="Bot replies with 'pong!'", inline=True)(embed.add_field(name="<poll2", value="starts a poll with 2 options.", inline=True)(embed.add_field(name="<poll3", value="Starts a poll with 3 options.", inline=True)(embed.add_field(name="<say [word]", value="Bot repeats what you say.", inline=True)(embed.add_field(name="<diceroll", value="Rolls a six-sided die.", inline=True)(embed.add_field(name="<mobprofile [mob name]", value="Bots sends the profile of the specified Minecraft mob.", inline=True)))))))
TypeError: 'Embed' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Embed' object is not callable
Yea, you cannot do like that
?
embed.add_field()
huh?
then how
im following this thing that someone sent me earlier:
https://vcokltfre.dev/tutorial/10-embeds/
Nice! You're already 10 parts in, good job! In this part I'm going to show you all about embeds.
why not just recreate a new embed object instead of going through hoops to change that there? sadly I have no way to test what you're doing right now
well i can, but can i replace the old one easily? tryna learn the most efficient way to go about it
can someone help me
what im trying to do is, i send an embed to the channel, with reactions on it. And then i want to track the people that react. My final step is to update the embed with the information every time someone reacts
hm are you sure new_embed.fields[0].value is a tuple? i'd assume it'd turn out to be a string
wow, and here im just trying to get an embed to work
it is, i looked at it
@fallow mauve 🙂 its making me sweat at times hahah, ive never touched python
it looks like this when printed: EmbedProxy(name="test1", value="test2", inline=False)
then why u here?
and it says i cant mutate it because its a tuple when trying to directly change it
because im learning?
same
yeah that's not a tuple, it's an instance of EmbedProxy
but my embed wont work still
can someone help me with this huge error i have that i cant figure out?
hello guys i wanted to know if anyone here knows how to fix this
CreateChannel = await guild.create_text_channel('mod-logs')
channel = discord.utils.get(ctx.guild.channels, name="mod-logs")
alright so i want to set the permissions off that channel so only administrators can see it is there any way to do that
when you do embed.fields it returns these proxy instances
https://github.com/Rapptz/discord.py/blob/master/discord/embeds.py#L546-L554
so trying to mutate it there wont really change anything @sacred folio
imo it'd be easier to just create new embed objects, or you can try mutating embed._fields in the same way you're currently doing with embed.fields (although there are no tuples involved)
discord/embeds.py lines 546 to 554
@property
def fields(self) -> List[_EmbedFieldProxy]:
"""List[Union[``EmbedProxy``, :attr:`Empty`]]: Returns a :class:`list` of ``EmbedProxy`` denoting the field contents.
See :meth:`add_field` for possible values you can access.
If the attribute has no value then :attr:`Empty` is returned.
"""
return [EmbedProxy(d) for d in getattr(self, '_fields', [])] # type: ignore```
could i do like await channel.set_permissions

add_field for possible values you can access
thanks for clarifying, i assumed it was tuples because of its structure
yoda
set everyone's permissions to not be able to see that channel
CreateChannel = await guild.create_text_channel('mod-logs')
channel = discord.utils.get(ctx.guild.channels, name="mod-logs")
how can i set this channels permissios to administrator oly
Is there something called a checkerror if the check in await bot.wait_for() fails?
asyncio.TimeoutError
no
yeah but how can u give an example
not timeout
??
checkerror
I'm searching, wait
if the condition hasn't been satisfied
await channel.set_permissions(guild.default_role, viev_channel=False)
you could raise the error in your check function
otherwise no
he means he only wants specific roles to see the channel
only administrators
yep
administrators will see the channel anyways
but thats the everyone role what if they like have a members role that the server made
await channel.set_permissions(yourRoleInstance, viev_channel=True)
you can set the members' permission to this too
yourRoleInstance would be like special role right?
hmmm what if we make the channel private and then we dont need to set permissions
use logic to spare code
bruhkitty
Is there any way to catch a specific error that was raised by a command? I'm aware CommandInvokeError can somewhat catch that, but it's too ambiguous and can mean literally any command error. How can I catch a defined error that was raised by a command?
Example?
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AccountNotFound: UID None isn't associated with any server```
do research mate 💀
Here, for example, I'd like to catch only the AxcountNotFound error/exception specifically. @spring flax
AccountNotFound? You mean MemberNotFound?
Oh no, it's not really a Discord exception. It's a different library. But yeah, basically I'm not sure how to catch a suberror(?) from a CommandInvokeError.
No idea what that is but for example you can use
if isinstance(error, commands.MemberNotFound): for dpy membernotfound error
How do you connect Spotify to a discord bot
Like let the user play Spotify with the bot
tos?
Do you mean stream music from Spotify into a voice channel?
yes
If so, that's against Spotify's Terms of Service. Therefore, we cannot assist you with that.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
CommandInvokeError error wraps the original error, so you have to handle the original attribute it has
!d discord.ext.commands.CommandInvokeError.original
The original exception that was raised. You can also get this via the __cause__ attribute.
How do, I link a main py file, to a cogs, music file?
wdym?
I’m trying to make a music, bot. But I Getting a error, linking them.
code and traceback
ok...
Soon, busy with rl, atm, can I dm you?
eh, didn't understand anything, but yes you can dm me
Ah ty that's exactly what I was looking for, thanks a bunch for the help guys @pliant gulch and @spring flax 
!d await discord.wait_for
6.4. Await expression
Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function.
await_expr ::= "await" primary
``` New in version 3.5.
..
@vestal owl #bot-commands pls, thanks
!d discord.Client.wait_for
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.9)"). 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.9)") 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.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
thank you mate
Hello guys
Hi
can someone tell me how to add auto reply on my bot
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
Context.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
i forgot
i mean if you send (Hi) the bot will send Hello
on_message event

you need to learn more python
clearly you don’t know enough to be using discord.py
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
primary_txt = str(message.content)
print(primary_txt)
translator = Translator()
transl = translator.translate(primary_txt, src = translator.detect(primary_txt), dest = lang)
print(transl)```
Error:
``` File "C:\Users\minua\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\googletrans\gtoken.py", line 62, in _update
code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'```
What does this mean?
its an issue with the lib
what can I do about it?
how do I change versions
did you even read the comments
nvm
primary_txt = str(message.content)
print(primary_txt)
translator = Translator()
print(translator.detect(primary_txt).lang)
transl = translator.translate(primary_txt, src = translator.detect(primary_txt).lang, dest = lang)
print(transl)```
does this look right to you?
i never used the lib so idk
because this is my feedback from console:
Finished
en
Translated(src=en, dest=ar, text=Finished, pronunciation=Finished, extra_data="{'translat...")```
ah
anyone mind helping me?
i am trying to make cogs for my bot, but it does not seem to work. Could someone help
if filename.endswith('.py'):
initial_extensions.append("cogs." + filename[:-3])``` ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||https://khadz.fuckedyourmom.today/
import os
😭 why did you not read the error omg
LMFAO
def check(reaction, user):
if (str(reaction.emoji == emoji_yes) and client.user != user):
return reaction.users()
reaction, user = await client.wait_for('reaction_add', check=check)
I use this to handle players that react on an embed, is there anyway to retrieve, basically a 'reaction_add' equivalent for whenever a user removes their reaction?
how do i fix this, ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||https://khadz.fuckedyourmom.today/
🤷♂️ youre trying to indice something that isnt there
reaction_remove
should i show u the code?
i already told u
if you know enough python then you should be able to understand what im trying to say
tbh, im a learner ive just started coding py.
ive watched a few tutorials
How do we create a trivia bot
nice start you got there
well, not really tutorials
look for a lib that randomly generates trivia questions or facts idk
freecodecamp?
ig thats ok
discord.py is not ment for people who just started coding py
so learn more of python first and then come back to this lib
is there any efficient way of sending an embed every last day of the month on 12 am est?
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3.10/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
import asyncio asyncio.sleep(1) # stops asynchronously for a second
.
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
hm
ye use that, so add a number in the position of a and another one in b
and import random
so if a is 1 and b is 10
it will pick a random number between 1 and 10
if you want 3 digits
then do 100 and between some other 3 digit number
wdym
it will only select a random number between the numbers you give it
do you want 3 random numbers or 3 digit random numbers?
they want 3 digit random numbers
your thing of doing randint(100, 999) wont work cuz they want numbers to be 001 and 090 for example
how could i make a global sleep time sort of thing,
for example if 5 users join across 5 different servers, on the member join event i want it to wait x amount for each dm across 5 servers(so dms are not fast and trigger antispam) - for welcome dms
if you have numpy installed you could use numpy.random.default_rng
@cooldown(1, 86400, BucketType.user)
@commands.has_any_role("europe1")
async def promoeu1(ctx):
channel = client.get_channel('892884253875007529')
for i in range(1):
await channel.send("f{ctx.author.mention}, Thanks you see check DM")
await ctx.author.send("Code your: **The code is not available code**")
await asyncio.sleep(1)
await ctx.message.delete()```
problem error D:
that will raise other errors
why are you using range?
and get_channel takes in an int not a string
@hasty iron hmm how you please write explain?
but sorry my no idea lol
no is "" change example
channel = client.get_channel(892884253875007529) no?
hmm maybe yes is
is work
string wont be defined
string is still not defined?
i dont even get what you mean by test = string()
yeah there #discord-bots message
do you want an empty string?
@hollow iron oh
Oh really? That’s it?
I thought we would have to do something complex?
wait seconds
using the lib might be complex
@hollow iron yes work thanks.
how would a lib that generates facts be complex
might
how?
99% of the time you’re going to use an api for facts or stuff like that
which isn’t even close to complex
true
@sly cliff do you want random facts?
seems like a good lib
Tyyy :)
are there any tutorials on making global chat bots?
Any Linux folk with thoughts on https://www.reddit.com/r/linuxquestions/comments/py615a/hi_folks_linux_audio_proxying_play_mp3_from/ please ?
0 votes and 0 comments so far on Reddit
is it possible to turn a selenium webpage element found through xpath into binary form without saving it to send to discord
tl;dr take picture of website part and send to discord with most efficient solution
Extension 'cogs.Anti' raised an error: ModuleNotFoundError: No module named 'motor'
nvm
!d discord.Client.wait_for
is it possible to change the bots discord pfp w a command
why
await edit(*, username=..., avatar=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the current profile of the client.
Note
To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.9)") must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.9)") is given through the use of `fp.read()`.
The only image formats supported for uploading is JPEG and PNG.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned.
Ok, so I have this function here,
async def init_bot(self, bot: commands.Bot, get_locale_func: Callable[..., Coroutine[Any, Any, Any]] = None):
self._bot = bot
if get_locale_func is None:
# Just use the fallback
get_locale_func = lambda *_: self._fallback
async def pre(ctx):
await self.set_current_locale(await get_locale_func)
self._bot.before_invoke(pre)```
And the issue is that i need to pass `ctx` to `await get_locale_func`, but either removing/keeping it gives me:
passing `ctx` (calling it):
```py
TypeError: 'coroutine' object is not callable```
, but removing `ctx` gives me
```py
return preferences[ctx.author.id]
AttributeError: 'cached_property' object has no attribute 'id'```
I don't know how to pass ctx without calling get_locale_func, or I don't even know if I have to call get_locale_func anyways, it's weird and if anyone could explain I'd gladly appreciate
Anyone knows how to edit the message a bot sends TO AN EMBED.
Ik how to do it normally ofc... message.edit(content="") problem is since content is a kwargs i can't really do content=embed=myembed i tried putting it in parethesis too like (content=(embed=myembed)) but that didnt work either it gives me a syntax error for sum reason
So what do I do?
message.edit(embed=newembed)
wait i can do that??
yes?
it takes the same kwargs as .send
alr if u say so
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
@slate swan
cool
hope it works
how do i get a list of all members in a server
why is this happening to my pymongo database?
!d discord.Guild.members
property members: List[discord.member.Member]```
A list of members that belong to this guild.
if message.content.startswith(messsage.role_mentions[0]):
guys im kinda stoopid today, tryna figure out how to make this actually work
this is off of a client.wait_for "on_message" function
it doesnt work
post your code
it gives me <class 'discord.member.Member'>
you would have to do players = ctx.guild.members
that doesnt work. it only gives me the bot itself
class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
New in version 1.5...
o
ok ill try enabling them again but i tried with a bot that has intents and it still doesnt work
but ill try again
only enabling them in the dev portal wont work
you have to pass it through your constructor
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=prefix, intents=intents)
well if he's looking for a spefic player couldn't he just use user: discord.Member
his function says pickplayer
or does it mean random player?
of it random
then he can use do for members in ctx.guild.members B)
oh actually
wait i take that back
he can do what u said earlier with the players = ctx.guild.members
then use the random module
to choose a random player out of that list
that would be alot more efficient
yep just an intents issue
can someone help me with above
id ask in #databases if its a database error
@slate swan
i dont know how to make it not expiered
well u should be using #data-science-and-ml channel for this
dunno anything about that
data science?
idk why tf it corrected to data-sciense 🥴
i did shift+enter so it does it for me
where did u define stat?
First image.
Barely. I'm learning.
this is basic stuff, u should be learning python before discord.py
or ur gonna struggle hard
trust me i tried the same thing, omg the pain
Alright. Thanks.
anyways yeah
@dusk karma yea really tho i learned dpy before python

not easy to understand things and errors
syntax
a
!d discord.Message
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
stat is defined after you refer it?
make sure its used on a message object
you dont need to use the content kwarg for ctx.reply()
already solved his issue btw
ah okay
he referenced after assignment
wait im dum
other way around lmao
before assignment
yeah haha
yeah i confused what referenced and assignment means there , we dont talk about that
haha thats alright, we make mistakes like that sometimes~
yee
Yall got any ideas for commands? Im kinda hitting a block because i've reached my python level cap
oh I actually need some help as well
Reaction Roles B)
eval command
using raw_on_reaction_add
I would have to put in so many safe guards
:)
well u asked for ideas for commands
Ig I could make it for me only
take it or leave it B)
How would I get started with an eval command?
embed=embed
is how i did it
yeah, for sending an embed you'd use the embed kwarg
and is anyone here familiar with discord-components?
this has nothing to do with datasciene or ai
well if u would read the context aka scroll down a bit more
im trying to make a button, and when the button is clicked an ephemeral embed sends
u would know better
How would I get started with making an eval command?
it has everything to do with #databases not ais
holy shit READDDA;KFJLBF
you should first set up a paginator
No idea what that is

honestly neither do i
excuse me
🤣
its discord.ext lol
fff
kill me
dis?
oh u mean using
message.edit(embed=)?
talking about those buttons where u react to it moves to another "page"
when really it jsut edits a button
why does it-
Why would I need to make one?
Can't I just cut it off after a certain amount of lines
wait wut, u mean like an anti raid/security bot?
good luck my boi, u gonna need some modules for that
also it might be hard for u since google kinda fricked over some popular music bots like rythm & groove for the same reason
using c o p y r i g h t e d m u s i c
imagine
they should be blaming the modules not the bots
What would I do after I create a paginator for an eval command?
Is there a built in function to execute command?
Or would I have to build it myself?
That's like saying, blame false news, not the people who spread it
Does not make any sense to me
yes, not doing any of the anti i jsut want it to send the information to a channel
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 109, in on_ready
title(f"[NukeX | chasa.wtf] Waiting for {PREFIX}n in guild..")
File "main.py", line 48, in title
ctypes.windll.kernel32.SetConsoleTitleW(content)
AttributeError: module 'ctypes' has no attribute 'windll'```
NukeX? 🤔
bro
(from the code ive seen so far)
so helping or...?
This server does not help with selfbots
there is no reason for you to be using ctypes inside a discord.py environment
i mean, isnt the error a bit too clear
thats not helpful
it is
Did you mean @help.command()?
instead try teaching me
If they think it’s a self bot they can’t 🤷♂️
are you even on windows
post your full code for the command that errors
what
I don't see the point of using a fork right now though
discord.py still isn't broken
they dont help with third party libs
No need to move imo until it does or beforehand
This is all the code that involves it: ```py
-- coding: utf-8 --
import discord
from discord.ext import commands
import json
import asyncio
from colorama import init, Fore
import ctypes
import sys
import os
import random
import time
import requests
import threading
init(autoreset=True)
green = Fore.LIGHTMAGENTA_EX
dgreen = Fore.LIGHTMAGENTA_EX
white = Fore.RESET
red = Fore.LIGHTMAGENTA_EX
yellow = Fore.LIGHTMAGENTA_EX
blue = Fore.LIGHTMAGENTA_EX
dblue = Fore.MAGENTA
gray = Fore.LIGHTBLACK_EX
intents = discord.Intents.all()
channel1 = f"{gray}[ {Fore.LIGHTGREEN_EX}Channel{gray} ]"
channel2 = f"{gray}[ {Fore.LIGHTRED_EX}Channel{gray} ]"
roles1 = f"{gray}[ {Fore.LIGHTGREEN_EX}Roles{gray} ]"
roles2 = f"{gray}[ {Fore.LIGHTRED_EX}Roles{gray} ]"
name1 = f"{gray}[ {Fore.LIGHTGREEN_EX}Guild{gray} ]"
name2 = f"{gray}[ {Fore.LIGHTRED_EX}Guild{gray} ]"
ban1 = f"{gray}[ {Fore.LIGHTGREEN_EX}Banning{gray} ]"
ban2 = f"{gray}[ {Fore.LIGHTRED_EX}Banning{gray} ]"
delete = f"[{Fore.LIGHTRED_EX}-{gray}]{white}"
create = f"[{Fore.LIGHTGREEN_EX}+{gray}]{white}"
perms1 = f"{gray}[ {Fore.LIGHTGREEN_EX}Perms{gray} ]"
perms2 = f"{gray}[ {Fore.LIGHTRED_EX}Perms{gray} ]"
status = f"{gray}[ {Fore.LIGHTGREEN_EX}Pings{gray} ]"
bad = f"{gray}[{blue}-{gray}]{white}"
pings = 0
bans = 0
members_count = 0
ban_threads = 0
def title(content):
ctypes.windll.kernel32.SetConsoleTitleW(content)```
Assuming discord announces changes as it should
that seems like your typical selfbot
whats a selfbot??
seems like a threaded nuker lol
whats a selfbot??
How would I catch output from aexec (async version of exec) and assign it to a variable?
whats a selfbot??
it’s self explanatory
??
a bot that runs on a user account
automation of a user account
I would use contextlib.redirect_stdout to catch the output
!d contextlib.redirect_stdout
contextlib.redirect_stdout(new_target)```
Context manager for temporarily redirecting [`sys.stdout`](https://docs.python.org/3.10/library/sys.html#sys.stdout "sys.stdout") to another file or file-like object.
This tool adds flexibility to existing functions or classes whose output is hardwired to stdout.
For example, the output of [`help()`](https://docs.python.org/3.10/library/functions.html#help "help") normally is sent to *sys.stdout*. You can capture that output in a string by redirecting the output to an [`io.StringIO`](https://docs.python.org/3.10/library/io.html#io.StringIO "io.StringIO") object. The replacement stream is returned from the `__enter__` method and so is available as the target of the [`with`](https://docs.python.org/3.10/reference/compound_stmts.html#with) statement:
```py
with redirect_stdout(io.StringIO()) as f:
help(pow)
s = f.getvalue()
``` To send the output of [`help()`](https://docs.python.org/3.10/library/functions.html#help "help") to a file on disk, redirect the output to a regular file...
Inside the context manager you would run exec
Ill probably need more help with this
Never used something like this
Imma read the docs first
ok but what do I do with this?: py AttributeError: module 'ctypes' has no attribute 'windll'
No one else answer
if you’re on windows it should’ve worked
why are you even trying to do that?
yes
you dont know?
You obviously know
for random?
so your brain was just like "ahh there is ctypes.windll.kernel32.SetConsoleTitleW that i could use for my discord bot"
prob skidded
Imma try to direct the output to a file then read the file and send it
thats basically using redirect_stdout
Yeah ik
io.StringIO is a file without a file
wdym
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
This is above my knowledge tbh
alr
Ill start with adding the output to a file and then reading it
Ill try the other way though
Well, it can take an io.BufferedIOBase which inherits IOBase which TextIOBase inherits which after a lot of inheriting StringIO inherits
Why shouldn't it have worked in the first place
does anyone know the rgb or hex of the discord embed background
that part by any chance
From reddit 36393F
Haven't tested it
the dark color is HEX #2f3136 or RGB (47,49,54)
0x2F3136
Also from reddit 54,57,63
Just get a color picker
i used a color picker
It’s so much easier
Even with my phone I can make a screenshot and do a color pick built in
you guys are life savers
i feel like i made something wrong but im not sure
@commands.command()
async def count(self, ctx: commands.Context):
submission: discord.Message = ctx.message.reference.resolved
print(submission.reactions)
why does this returns a []
Maybe there are no reactions?
i mean the message i replied to when using the command has reactions
Cache doesn’t have it stored then?
it does works if i'm using the message.reactions directly, just not with a resolved reference
wait
that might be it lol
If that is, that is one of the main downsides of dpy, the cache is a complete mess
And hence why @river walrus started disthon :p which I’m helping with writing
I have never made a discord bot, but I made a bot generate code for a discord bot.
?
yeah it was the cache. fetching the message again showed the message reacts
This is some of the code that the bot wrote
!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)
can someone tell me what they want a discord bot to do?
stuff
Haha yup, I was looking at the source code yesterday and gotta say, it's a looot cleaner than dpy's imho
anyone familiar with discord components
I mean we still have a lot to write but I did skip quite a few weird steps that dpy has taken this far haha. Like how dpy handles hb doesn’t make sense for me at all
Also, Danny using EmptyEmbed instead of None is weird imho
dpy uses threads and so do you?
Does anyone want me to generate a bot for them?
Idts
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.command()
async def hello():
"""Says hello"""
await bot.say("Hello!")
bot.run('token')
It's not
i mean, ctx is now a required argument in commands and bot.say is deprecated so idk what you mean
.say 
You should see my impl for discord api 😔
Semi impl*
It was generated
generated by who??
a bot
Copilot?
no
what bot
sussy
Wouldn't expect copilot to do this anyhow
Doesn't have a name yet
how would i make a discord bot create a webhook and make it say a message?
it can
Good or bad? Lol
it writes descriptive docstrings for me
Clean, super super clean
which is a blessing
Ah haha. What's your lib link @pliant gulch
you made it?
Ah cool
import discord
import asyncio
import os
client = discord.Client()
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_message(message):
if message.content.startswith('!hello'):
msg = 'Hello {0.author.mention}'.format(message)
await client.send_message(message.channel, msg)
client.run(os.environ['DISCORD_TOKEN'])
The bot is still a wip
what will this do?
did you make it??
Dang, yours is clean, Andy
Coolest thing is probably the O(1) popitem and getitem cache
Unlike discord.pys O(n) getitem for message cache
Well I didn't see each and every file, but I'mma take a look at it more closely once I get home from school
(I saw the http.py file and it's neat)
any github link
not any yet
lame
I'll prove to you that it works
tell me something to generate
like "ask user for their name and print out the number of letter in their name"
i mean idk how you are generating this code, you could he just copy pasting some stuff and telling me that a bot generated it
Then tell me to generate something unthinkable
show me how it’s actually generated
and i'll have it done in 1 sec
I can't show anything to the public yet
huh?
"why does from future import __annotations__ do not work with parameter converter?"
im just asking what are you doing to generate the code
Is this generation static from a template or does it change overtime
from __future__ import annotations
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field, root_validator
from . import schemas
from .schemas import (
ParameterConverter,
ParameterConverterType,
ParameterConverterValue,
)
class ParameterConverterModel(BaseModel):
"""
ParameterConverterModel
"""
type: ParameterConverterType = Field(
..., description="Parameter converter type"
)
value: ParameterConverterValue = Field(
..., description="Parameter converter value"
)
@root_validator(pre=True)
def check_type(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""
check_type
"""
type_ = values.get("type")
value = values.get("value")
if type_ == ParameterConverterType.DICT:
if not isinstance(value, dict):
raise ValueError(
f"ParameterConverterType.DICT requires value to be dict, got {type(value)}"
)
elif type_ == ParameterConverterType.LIST:
if not isinstance(value, list):
raise ValueError(
f"ParameterConverterType.LIST requires value to be list, got {type(value)}"
)
elif type_ == ParameterConverterType.TUPLE:
if not isinstance(value, tuple):
raise ValueError(
f"ParameterConverterType.TUPLE requires value to be tuple, got {type(value)}"
)
elif type_ == ParameterConverterType.SET:
if not isinstance(value, set):
raise ValueError(
f"ParameterConverterType.SET requires value to be set, got {type(value)}"
its not even dpy
here's some of the code it generated, can't fit it all into discord

nice pydantic
if change == "update_support":
mymsg = await ctx.send("__Support Role Configuration__\n**`What would you like to change the support role to? [State ROLEID]`**")
def check(user):
return user == ctx.author
try:
message, user = await client.wait_for("message",check=check,timeout=30.0)
except asyncio.TimeoutError:
await mymsg.edit(content="__Configuration Cancelled__**\n`You took too long to respond, configuration cancelled`**")
else:```
anyone knows why this aint workin?
it goes straight to the timeouterror
ignores my input all together
what are you trying to make?
@median coyote
user is discord.Message
wait wtf
It's been trained on lots of data
fr?
yea
oh okay thx
lots of outdated data it seems like
it's because the bot wasn't made to generate discord bots
I'm just testing discord bots rn
do you use something like gpt-2??
yeah its lame
free source dpy files? lol
then what are you using
this is our own bot
we aren't using anything else
for getting the music
oh nice
g
i can already see that ytdl is pretty useful
sure u can dm me
i might try myself
@hasty iron I told my bot to generate a picture of a blanker
ok
def main():
"""
Main function
"""
width = int(input("Enter width: "))
height = int(input("Enter height: "))
print("*" * width)
for i in range(height - 2):
print("*" + " " * (width - 2) + "*")
print("*" * width)
if __name__ == "__main__":
main()
now do you believe me?
not really
this isn’t really "proof"
when you make a github repo send me a dm or something and ill check it out
what mistake have i done? i want it to not just break off when i forget to provide a message
@client.command()
async def hello(ctx):
await ctx.send("Hey")
@client.command()
async def kick(ctx, member: discord.Member, *, reason = None):
await member.kick(reason = reason)
await ctx.send(f'User {
member
} has kicked.')
Help me
Control_panel means u need to print hello this works in console?
@slate swan help me
async def hello(ctx):
await ctx.send("Hey")
@client.command()
async def kick(ctx, member: discord.Member, *, reason = None):
await member.kick(reason = reason)
await ctx.send(f'User {member} has kicked.')```
no i need it to send Hello, it works in a channel
Oops wait a second
i have referrenced them
@client.command()
async def kick(ctx, member: discord.Member, *, reason = None):
await member.kick(reason = reason)
await ctx.send(f'User {
member
} has kicked.')
EOL means that you've got an un-closed string.
Oh
You won't be changing lines in a single string even if its a f string
You can do client.get_channel() instead of getting the guild then the channel using the guild's instance.
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
i need the guild variable
for later
Btw, if you want it to include the whole argument and not just the first word, use *, before message.
ctx, *, message.
is there a way to remove a users reaction off a message that has reactions
@client.commands
async def invite(ctx):
await ctx.send("Invite Belle officials and Enjoy it. Link- (link entered in here) ")
is there a kwarg for this? I use ctx.cog to display this and i wanna change it to something else
how do i check if the bot is playing something in a vc? is it by doing
#code here```
ctx.cog returns a commands.Cog object.
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
hm
I'm a little stuck, I'm trying to get a dictionary
but with a sub dictioniary
so, like here
I could get name/age/married/divorced/children/pets/cars
but how could I get the model of cars
In the python guide, it never showed it
?
idt this is related to discord bots
I'm trying to do something for my discord bot-
is there a better python server or something
Well, cars is a list. Let's say you want the first item in the list, you would do x["cars"][0].
I'll try that
you shouldnt be using json for discord bots. try using a db like mongo as its similar to json, or use SQL
I don't think so. You can create a help channel, though. #❓|how-to-get-help
TYSM
If you're asking only for discord.py they have a official server
No problem.
.gg/dpy is their vanity
class MyNewHelp(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
embed = discord.Embed(description=page)
embed.timestamp=datetime.utcnow()
embed.set_author(name=ctx.author, icon_url=ctx.author.display_avatar) #current error: ctx not defined
embed.set_footer(text='Minimal Help Command', icon_url=ctx.author.display_avatar)
await destination.send(embed=embed)
This is my code currently and I was wondering how would I use ctx here? If I add a ctx param next to self it says Command raised an exception: TypeError: send_pages() missing 1 required positional argument: 'ctx'.
Hi,
Write a program to accept 5 names from user and store these names into an array sort these array element in alphabetical order.
self.context
thanks
!d sorted
sorted(iterable, *, key=None, reverse=False)```
Return a new sorted list from the items in *iterable*.
Has two optional arguments which must be specified as keyword arguments.
*key* specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). The default value is `None` (compare the elements directly).
*reverse* is a boolean value. If set to `True`, then the list elements are sorted as if each comparison were reversed.
Use [`functools.cmp_to_key()`](https://docs.python.org/3.10/library/functools.html#functools.cmp_to_key "functools.cmp_to_key") to convert an old-style *cmp* function to a *key* function.
list.sort will work also
how do we retrieve the data from requests
like if i put in a url
how do i get my bot to print the facts on the website (the url is of the website)
You making a fun facts bot @sly cliff ?!
request is blocking
use aiohttp
lmaoao i wanted to make one where its like the bot asks questions and then you can answer
Oh
how do i do that
not as fun as a fun facts bot 😦
await aiohttp.ClientSession().get("https://www.example.com").text
better question is how do i learn this stuff
but that will just get the text of the site content
not just the fact text
I'd recommend u don't ping the site that many times, u might get rate limited
yeah
Use tasks.loop and have it loop each minute of each 5m
except if it's your own api endpoint
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Using that
@tasks.loop(minutes=5)
async def api_req():
... # Here add your code to do requests to the api, use aiohttp
api_req.start()
He's helping a lot
Man deserves a medal tbh
this is my code
i've used the cmd
but it only sends the first word in the channel
pls help me. i want to send the full word
Ctx, *, message
what does that * do?
add * in the parameter before message
what does that do?
To send the whole thing
ok
how to make images/banners for levels ?
use pillow
can someone send the documentation for discord library
!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.
!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.
okay
Because you just set client.launch_time to the exact same moment?
Maybe because you defined client.launch_time in the command
so when u invoked the command the timer started then u subtracted that time so its 0
E
sure just define it somewhere else
Anyone that has any idea how to get a hold of a user that just removed a reaction? Had no trouble seeing who added it.
!d discord.on_reaction_remove
discord.on_reaction_remove(reaction, user)```
Called when a message has a reaction removed from it. Similar to on\_message\_edit, if the message is not found in the internal message cache, then this event will not be called.
Note
To get the message being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires both [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Note
Consider using [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") if you need this and do not want to enable the members intent.
@maiden fable will this tell me whether or not which user it is that removes it?
@client.event
async def on_message(ctx, message, member):
for i in range(len(Filter)):
if Filter[i] in message.content:
for j in range(1):
await member.ban(reason='filter')
await ctx.send('A member has been banned')
``` The bot doesn't ban
Yea. The user param
why are u using ctx in an event?
also is there an error
To send a message
No there is no error
use message.send
Ok
....?
yeah because its an event it isnt a command
Then why did u tell then message.send???
how u suppose to use the args if its an event lol
because they used context?
I mean, u can only use one param in on_message, nothing else
context is for commands only tho?
Yea
Still not working
if u wanna ban the author