#discord-bots
1 messages ยท Page 127 of 1
I have no idea really and the time won't affect the bot also
ok now it stopped working again
Go to the uptimerobot website
uptime robot?
Yeye
Mind showing me the settings?
sure
The link especially
Try running it again
alright
See if it's rate limited or something
Ye
๐
Rate limited
Gotta wait for a few hours before u can start it again
It happens in replit quite frequently
oh ok
And u can't do anything to stop it
should I make a new repl and copy paste the code?
It won't work
oh ok
Just wait
What I do is I have two bot
When one is rate limited I build the other one
Btw can anyone give me suggestion?
Should I use image as the Monopoly board like myuu. I have no experience in image stuff tho
hm?
But using emoji as board is not going to work cuz there is going to be like 4 players
So the board is going to be like 14 x 14 or even bigger
i guess using an image gonna be better but there is the problem that the bot should have to change the picture by every move? ||I am not that experienced||
That's what I'm thinking about
But I think I should ask the professional before doing anything silly ๐๐๐
^^
Come out proffesionals
i guess am gonna run my bot locally till replit works again, because I am testing new things ๐ญ
Lol

donโt use replit. Oracle cloud has a always free tier that is extremely good
repel it ๐
oracle cloud?
never heard of it tbh

Yeah itโs a somewhat hidden gem
I know a bot dev uses it for his decently sized bot and has never had issues
wow
fr lmao
.bm
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
it needs an payment option and I dont have one ๐ญ ๐
Should I use image as the Monopoly board like myuu. I have no experience in image stuff tho
You're trying to make a bot play Monopoly?
yup
and its going to be more than 2-6 players
so emoji map doesnt work
i was thinking about adding the token on the map
add token and add house + hotel
on a default map
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I think you can use an image of the map and just update the image after each turn. Perhaps you could start by learning an image manipulation lib such as PIL to achieve this
yeye
do u know any source?
How would I get all the channels names under a category?
!d discord.CategoryChannel.channels
property channels```
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
You can use a list comp and get the name attribute of all the objects in that
from an embed and forward them?
Yes
So when an embed is sent to the channel
I only want to grab certain things from the embed if it contains a word
oo
So if the title contains testing for example it will grab the whole title ๐
Any idea ๐
!d discord.Embed.description
The description of the embed. This can be set during initialisation. Can only be up to 4096 characters.
The title of the embed. This can be set during initialisation. Can only be up to 256 characters.
Still little confused
try and see if u can get the description of the embed with this
hmm still not working for me
Show how did you do it
@client.event
async def on_message(message):
if message.webhook_id and message.embeds:
embed = message.embeds[0]
channel = client.get_channel('1039871964745152161')
embed.remove_footer()
await channel.send(embed=embed)```
it shld be removing the footer yet isnt somehow
!d discord.Embed.footer
attributes don't come out of thin air, there's no such method
!d discord.Embed.remove_footer
remove_footer()```
Clears embedโs footer information.
This function returns the class instance to allow for fluent-style chaining.
New in version 2.0.
nvm
๐คฃ
your channel variable is invalid ( None)
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
and the if statement is faulty as well
why would a webhook id be a part of list of embeds
the channel id is the channel i want the copied embed to be sent in
ids are integers, not strings?
i have changed tht
.
but get this py TypeError: get_channel() takes 2 positional arguments but 3 were given
now you added something that shouldn't be there
check the part of embed that data belongs to
.
is field counted as description tho
i forgot what is it called
!d discord.Embed.fields - You mean this? 
property fields```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of `EmbedProxy` denoting the field contents.
See [`add_field()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed.add_field "discord.Embed.add_field") for possible values you can access.
If the attribute has no value then `None` is returned.
ye
is it counted as description?
I don't know what do you mean
is field under description when u do discord.Embed.description
nope
id just do "text" in json.dumps(embed.to_dict()) to check if something is in the embed
if i don't know what part it exists in*
probably the best free option
myex.dumps(me)
like what would u recommend
myex is not defined
like the best free option
๐
oracle or digital ocean if you have GitHub students
what is github student
i dont have it ๐
are you a student?
how can implement this?
just copy paste with replacing text with your string and embed with the embed object you want to check in
could you give an example
so can understand better
ye
i literally sent the code, how can i clarify it more
i mean how wld use it
like in a sense
go on the above link, fill in the info to join GitHub students
it gives you access to tons of developer tools for free ( that are usually paid)
only if you want to ofc
There is no guild specified
still confused bro, how do i then find the field name and replace it
Okay, I take a break from discord.py and this shit happens
[2022-11-09 13:28:53] [INFO ] discord.client: logging in using static token
wtf? I'm using the correct token ๐
That's not an error
well after that it throws an error
It's just telling you that it's logging into the bot with a static token
why do I need privileged intents?
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
!tag intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I'm using intents
you using message_content intents?
You need to enable them in the developer portal according to the error you sent
I just created this bot
I have, and the error is saying something about enabling privileged intents
can someone help me here or tell me how to make an Trivia command without a lib?
nvm
In the developer portal, there's 3 toggles for different intents that need to specifically be enabled
I read it wrong, thought it meant that you should enable it if your bot is in 100+ servers
Ah no they'd just need verification beyond that
Send your code around line 111
I dont have a line 111 yet
Oh I read the error wrong. Sorry not familiar with that library
neither am i.. just wanted to see if it would be simpler to use a lib to create a trivia command
what is that lib, and where do you use it? it is in conflict with asyncio
found it in pycharm
It has installed and probably it has using cffi which is a C interface for python
So i cant use it?
cffi uses PyPy, which is another C implementation
and PyPy doesn't support asyncio, so you will not be able to use it
This is what that error means according to the docs for nextcord
In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.
How would i get rid of an embed field when converted embed to dict
then can someone tell me how i can at least make a trivia/quiz command?
you can try to learn more and maybe find a solution in #c-extensions channel
I think you have the basic layout already figured out, just make lists for each difficulty of questions and use random.choice to pick questions out of those lists
hi! can I get some suggestions on creating a bot with python. links to documentation would be great.
and then how can i check if the users answer is correct or wrong?
ok
I would make it so it checks the reply to the message for an answer, if the answer matches correct answer, it's correct. If not, incorrect
an id has to be an integer, strings wont work
except for fetch_ methods
yes yes, godly piece of advice ๐
i have got the embed in a dict but how would i know remove a specific field
!d discord.Embed.fields is a list
property fields```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of `EmbedProxy` denoting the field contents.
See [`add_field()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed.add_field "discord.Embed.add_field") for possible values you can access.
If the attribute has no value then `None` is returned.
uhhhhhh 1 min
another daily reminder. sarth can I worship you from now on ๐
actually list.remove works it gets that from the parent class which is not documented
im sooo nice, so I'll allow you with that
๐ณ
hola amigo como estas
this is not related to discord bot but a text based bot,
i am trying to implement a fight() between two characters, like more popular bots out there (dank memer) however, there fight is between 2 real players, my fight is between 1 player and 1 enemy, the player is supposed to defeat the enemy using text based commands, can someone kindly help me design a logic as so how the enemy will attack the player and how so the player would attack the enemy
well hello sarth.
sarthak here!
lmao sarth is just an internet alias, my name's sarthak as well
ah! finally found the person who stole my twitter user ๐ญ
i'd also wanted @austere jetty on twitter and sarthak@gmail.com
but no, because people like you and me exist-
but hey sarthak! i am sarthak sidhant!
you'll be utilising bot.wait_for s with "message" events and establishing a relation between the 2 users in fight using a dict or something
!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.11)"). 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.11)") 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.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
i don't even use twitter:p
man came right to the point
its not for a discord bot BD
i just wanna design the logic
plain python, how the user gonna fight, what the perimeters, what the fight seqeuenee
ill definitely make this in a discord bot later, therefore asked about it here
ah, i thinking claiming a help channel ( #โ๏ฝhow-to-get-help ) and asking there would be a lot better
good idea.
cya human alias!
"I thinking" ๐
im typing with one finger totally relying on autocompletes so ywah
do you guys type with fingers?
not so cool
i use my paws sometimes
im in class lol
ahem ๐ sometimes I use my...
at 8pm-
it continues till 9pm
Man please.
At least ashley will not read that 
there's morning timings too but it's mostly for girls
Lol
That's my alt
well, you can be the famous guy
exactly what I don't want
based
Well, at least do yourself a favour and let become your d... the famous guy
Lets stop whatever the hell this is
lmao

who wants to make a dc bot with me?
Exception has occurred: ImportError
cannot import name 'handle_message_parameters' from 'discord.http' (C:\Users\gosia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py) help?
reinstall the library
might be some installation issue
how did you install discord.py?
no
bruh
yes
You installed it via yes?
does anyone have a ticket system that uses thread? please i need this script
Maybe
This is sound advice I think I'll do that ๐
Forgot to un-ping my bad
Sarth doesn't mind.
I know some people get pretty upset about it and I'm usually good about turning it off if it's not in reply to something recent
lol im mostly in the channel so it doesn't matter if you ping or not
Alright @slate swan
Is this saying they installed discord.http.py?
If they get upset they can just disable it.
Yea the notifications for it
@slate swan
https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
i tried this example here
and it only allowed me to select one
max_values = 1
How to obtain message id from the user who send command
just replying to a ping
I want to do something when a user type /example the bot will send a dm to the user who sent /example
yeah go study
explain me please
!d discord.User.send use this
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.11)") 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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
!e ```py
print(not True)
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
But this requires user id
you can ask for help in #python-discussion or claim a help channel (see #โ๏ฝhow-to-get-help) this is not the right channel
bro my classes just finished
That's when you study lol
it definitely doesn't, you can grab the author of the slash command user
Kk
its literally 9pm ๐ i need sum rest
not 1 == 1 checks if 1 is not equal to 1.
you need to get a 299 smh
what mean ==
i got 207 in last mock test ๐
what is == explain
it means is equal to ( check)
totally not satisfactory, must go to kota ๐
You should grab a regular help channel. But it checks if 2 values are the same
yo guess what, im in kota
no wonder why you seem depressed ๐ must survive (possibly)
so i wanna make that the user that opened the ticket will get a dm after a staff member closes the ticket, interaction.user doesnt work there cuz the staff did the interaction
totally not our fault, the discord api wrappers need to make their libraries more complicated to use so that more people and more beginners will ask for help in the channel.
the implementation in many libraries is too easy so far and people opt for those. There aren't enough problems to solve regarding discord bots, it's usually the problems related to "discord.py not found" or "why this not work" which are 99% of the times syntax errors and are not suitable for the channel but are "This error is in a discord bot".
Technically, this channel can be used as an OT channel, but the roles oppose this statement. Sadly.
You just wasted 15 seconds of your life reading that message ๐ no comments if you read that actually
well, that is because andy is very smart in the aspect of developing. so when andy explains something to someone who doesnt have the same knowledge, it may be looked at as confusing because andy is explaining something with the assumption it can be understood as simply as he/she understands the topic. so yeah it creates confusion. thats why you ask more and more. the more you ask the more you know. dont walk away misunderstanding the topic because one explanation didnt give you the knowledge needed. im sure andy would have been willing to break down the explanation.
well you can save somewhere about which user started the ticket
tf you people still simp for andy
like the channel description or in a dictionary
lol thats the only copy pasta i could find rn
cuz it was in this channel itself
yes
totally studying rn I see
you won't need a database if the ticket isn't supposed to be opened for too long, but yes thats the preferred way
im just walking home with some mango shake
Hereโs my cog, it says that collab function doesnโt exist
Here is the extension loader
Rate limitedโฆ
commands name can't have uppercase letters, the name parameter too is all lowercase
Actually command names can have uppercase in message commands.
And since kwarg passed doesn't exists it gets disregarded so the function name will be used.
So we need the traceback chief.
Which name parameter, the class? Or the file
Thereโs no error, the cog just wonโt load
yessss
I'm not aware of that package manager, is it new?
same
how do i add this on replit
I recommend not following that tutorial.
Last update on Feb 4, 2021
lmao
I'll take that as a no then
Once every 5 years.
How can I make an arg optional?
!arg-kwarg
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
โข Decorators (see !tags decorators)
โข Inheritance (overriding methods)
โข Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
โข Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
ty
Setting a default value will make it optional.
Example: ```py
def test(word: str = "Hello!") -> str:
return word + " World!"
print(test())
print(test("Flat"))
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello! World!
002 | Flat World!
async def commandlist(ctx, arg = 'None'):
if arg == 'None':
await ctx.send('!bread, !catcutie, !breadedcat, !sunglassescat')```
would be correct?
Is this a self bot?
nope
Oh no nvm, yeah I'd say so, but there is a help subclass for this.
Yep it worksd! tysm
Traceback (most recent call last):
File "/home/container/bot.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
pip install discord.py (or other module)
!dm
Dunder methods
Double-underscore methods, or "dunder" methods, are special methods defined in a class that are invoked implicitly. Like the name suggests, they are prefixed and suffixed with dunders. You've probably already seen some, such as the __init__ dunder method, also known as the "constructor" of a class, which is implicitly invoked when you instantiate an instance of a class.
When you create a new class, there will be default dunder methods inherited from the object class. However, we can override them by redefining these methods within the new class. For example, the default __init__ method from object doesn't take any arguments, so we almost always override that to fit our needs.
Other common dunder methods to override are __str__ and __repr__. __repr__ is the developer-friendly string representation of an object - usually the syntax to recreate it - and is implicitly called on arguments passed into the repr function. __str__ is the user-friendly string representation of an object, and is called by the str function. Note here that, if not overriden, the default __str__ invokes __repr__ as a fallback.
class Foo:
def __init__(self, value): # constructor
self.value = value
def __str__(self):
return f"This is a Foo object, with a value of {self.value}!" # string representation
def __repr__(self):
return f"Foo({self.value!r})" # way to recreate this object
bar = Foo(5)
# print also implicitly calls __str__
print(bar) # Output: This is a Foo object, with a value of 5!
# dev-friendly representation
print(repr(bar)) # Output: Foo(5)
Another example: did you know that when you use the <left operand> + <right operand> syntax, you're implicitly calling <left operand>.__add__(<right operand>)? The same applies to other operators, and you can look at the operator built-in module documentation for more information!
!d discord.User.send @rustic edge
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.11)") 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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
ty lol

What is that
nonce = None as seen in this embed
only for ephermal msgs i guess
Yea it sounds like it's a way to verify an ephemeral message was sent without being able to see it
But ephemeral isn't an argument for User.send 
Decorators
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
>>> import time
>>> def timer(f):
... def inner(*args, **kwargs):
... start = time.time()
... result = f(*args, **kwargs)
... print('Time elapsed:', time.time() - start)
... return result
... return inner
...
>>> @timer
... def slow(delay=1):
... time.sleep(delay)
... return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!
More information:
โข Corey Schafer's video on decorators
โข Real python article
How can I check if a user includes themselves in a command argument?
why this bot doesn't start with Intents.all (RuntimeError: Event loop is closed) but with Intents.default the bot starts but it doesn't respond with anything when using its prefix
Intents.all includes the privileged intents, so you need to enable them in your developer portal for it to work
With default, message content intent (which is a privileged intent) is not enabled, so none of your commands would work
Hello, how can I activate the bot I made with python?
I made a bot with python for the first time
im looking into it rn thank you
i think i enabled everything on the developer portal, but now when i try to copy the link to invite the bot i get "Please enter a redirect uri"
If you don't know how to use a redirect uri then you're likely making the wrong selections on the dev portal page
90% of the time all you need is the bot scope, and maybe the applications.commands scope (when using slash commands)
With the associated permissions under the bot scope
how can i remove the indexs of fields all at once?
what does that bot do?
where do i put the comma ;-;
The bot calculates the score about the game and then passes it to the table
yeah apparently when i selected "REQUIRES OAUTH2 CODE GRANT" i needed a redirect uri, deselected it and now the bot works as intended
worked on this sht since yesterday ur a god amongst men
help Pls
why wont a embed send i got this instead
you need to use the embed= kwarg in order to send the embed properly
e.g. py await channel.send(embed=my_embed_variable)
help me
this looks like a node.js program?
no python
i have a redeem command, if you redeem your id gets written into a file. i want the bot to remove the id after a certain time, is it possible? if so, how
If I use Putty, the program where I start the bot, it doesn't work
?
well your error message seems to be related to M-host, whatever service that is, and not your python code
works @hushed galleon thanks a lot bro
please
Your token is invalid
if people actually read error
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: WriteError: Unknown modifier: inc. Expected a valid update modifier or pipeline-style update specified as an array, full error: {'index': 0, 'code': 9, 'errmsg': 'Unknown modifier: inc. Expected a valid update modifier or pipeline-style update specified as an array'}
what does it mean?
@slate swan can I dm you my bot's code?
I am trying to make a daily system thing where you can claim coins once 24 hours passed since your last claim
using mongodb as a db
Why not just use cooldowns?
oh
any articles on those?
!d discord.ext.commands.cooldown its a simple to use decorator
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
class ApplicationManagerDropdown(discord.ui.Select):
def __init__(self, roles):
self.roles = roles
for x in roles:
discord.SelectOption(label=f"{x}")
options = [
discord.SelectOption(label='-------DESIGN-------'),``` Would it be possible to somehow make this work? I'm trying to have a dropdown that changes depending on a specific value.
Iโve tried to use .append as well, but I just cannot get anything to work.
use a list comp
options = [ discord.SelectOption(label=x.name) for x in roles]
any full example for that
the doc doesn't provide any
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
They do.
I want the bot to send a certain message when the cooldown isn't done
from discord.ext import commands
bot = commands.Bot(...)
@commands.cooldown(1, 10, commands.BucketType.user)
@bot.command()
async def test(ctx):
await ctx.send("this command can be used only once in 10 seconds")
bot.run()
you'll have to make an error handler for that purpose
oh
are those hard to learn?
nah they are easy
ty
so I expect that when someone uses the command before a cooldown is done it raises an error
Unfortunately, it's the same error I usually get. py Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task await item.callback(interaction) File "/Users//Desktop/Code/CookieServices/src/tickets/applications.py", line 61, in no await interaction.response.edit_message(content='Select the roles you would like to give them in the dropdown!', embed=None, view=view) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/interactions.py", line 856, in edit_message await adapter.create_interaction_response( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/webhook/async_.py", line 220, in request raise HTTPException(response, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In components.0.components.0.options: Must be 19 or more in length.
In components.0.components.0.options: Must be 19 or more in length.
what do you think this could mean
I must have 19 characters in the label? I donโt quite understand.
must have 19(+) elements for options
I still donโt quite understand, Iโm sorry.
that's discord.py right?
Yes, it is.
I have never seen that before
Oddly specific number
Iโm not sure whatโs wrong haha
Iโm sure not many people have tried to do this either :P
can i see your view class
Surely
and the select's super().init
class ApplicationManagerDropdown(discord.ui.Select):
def __init__(self, roles):
self.roles = roles
options = [discord.SelectOption(label=x) for x in roles]
print(options)
super().__init__(placeholder="Choose all the roles you're applying for!", min_values=1, max_values=19, options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message('test', ephemeral=True)
class ApplicationManagerDropdownView(discord.ui.View):
def __init__(self, roles):
super().__init__()
self.roles = roles
self.add_item(ApplicationManagerDropdown(roles))```
I can provide the entire file if that helps :D
max_values=19,
you are allowing user to choose a max of 19 options, but providing less than that
I am trying to make PyAv encode frames for aiortc. I receive bytes() object from server and I can't understand how I to properly encode bytes() object to make it numpy array to use AudioFrame.from_ndarray. To receive audio data I am using to_bytes, but looks like there is no from_bytes ๐ฆ I receive pcm audio bytes() from here https://github.com/Pycord-Development/pycord/blob/master/discord/opus.py#L518 and want to encode it into PyAv's Frame. I am using aiortc, but it needs the bytes() to be in Frame already. https://github.com/aiortc/aiortc/blob/ffe2a566da74e000fc5bef354ae3f0a9a90c40e2/src/aiortc/codecs/opus.py#L65 So I need a way to encode bytes() into av.AudioFrame
discord/opus.py line 518
return array.array("h", pcm[: ret * channel_count]).tobytes()```
`src/aiortc/codecs/opus.py` line 65
```py
def encode(```
Any way I can do this in a better way ๐ญ
One more thing, how could I allow them to select multiple?
I usually do that with max_values.
set max_values to the number of options you want them to choose
I think I need to convert the bytes() to numpy array and feed it into av.AudioFrame.from_ndarray(). But I can't find any examples.
Hm. They can choose up to 19 if all 19 are provided
How would I make it differ depending on how many roles are provided?
len(roles) lol
match/case? (python 3.10+)
All the expressions are the same, so just move their data into a list and put tuples (or dataclasses) of expressions literals into it. Then check for matches with for loop.
There is and it's called math.
how do i add unixtimestamps to my commands? like for example i wanna do .hello and a embed is gonna pop up with 30 days relative time countdown from that moment
how would i do that
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
pass in the datetime with style = "R"
how would i do that lmao
im kinda new to all this
OH my bad lol
did you get it or should i show an example
please do.
!e ```py
import datetime
now = datetime.datetime.now()
_5_mins_later = now + datetime.timedelta(minutes=5)
print(f"<t:{int(_5_mins_later.timestamp())}:R>")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
<t:1668028718:R>
when i paste the output: <t:1668028718:R>
i want my bot to take someone to a url if they click my button how is this done?
Intents.guild is present in Intents.all ?
code currently
!d discord.ui.button the url kwarg
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
and set button style to ButtonStyle.url
yes, .all() has all intents
thx
huh
?
you can't make a url button like that in a view, will have to manually create a ui.Button instance and add it to the view using view.add_item
got it ty @slate swan
WAIT I NEED HELP AGAIN LMAO
it doesnt work with embeds
what do i do
it won't work in field names, embed title, author name, and the footer
i want to make the bot send a message at a specific hour everyday, what should i modify here bcs i get "sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited"
are you in discord.py v2?
send me a dm :)
!rule 6 9
6. Do not post unapproved advertising.
9. Do not offer or ask for paid work of any kind.
Also save yourself the money and get help for free here :)
You did that on purpose
i need someone to help me make a python script thats send a message every 5 minutes in my discord server and deletes its self after 1 minute and also if someone dms me it will send an automated message back dm me please :)
i need help my discord bot is broken
nice
Sad how you probably want my tag
here is my stack overflow https://stackoverflow.com/questions/74382014/discord-bot-errors
I dont making mine authentic
Better. No advertising. Now, what code do you have so far, and please send any tracebacks so we can help with any specific issues you are having
wait do pthyon scrips run 24/7
On a general basis though, check this out for sending a message every 5 minutes:
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
And to delete a message after a minute, pass in delete_after=60 to your .send
You'll need to buy a VPS. Check #965291480992321536 pins for options
okay
do replit scrips work on python
yeah replit is shitty
you can run it off of your pc
only runs for 10 minutes max
yeah but can i take the script from replit and import it into python?
i have it downloaded
Sure, is it a .py file?
umm no
You might consider updating as I believe 2.0 has a nice method for running a loop at a specific time of day
i jus downloaded it straight from replit
node_modules, i wonder what does that belongs to โ
This doesn't seem like a Python project
thx
yeah its a replit
bruh that's a nodejs project
i was wondering if i could import to python
how do i make it a python project
Rewrite it from scratch
Python and Nodejs are 2 seperate programming languages
So Nodejs code won't work on Python and vice versa
No, that's against our server rules. Or you can do it yourself for free
(With help from this server)
i dont know how to do this stuff
It's an easy script just rewrite it 
Sounds like a good time to pick up a new skill!
if its that simple there already has to be a bot that does that task, just use a public one
If you'd like, I can send resources over to help you get started
There are also resources to host a node.js bot but you likely won't find them here
At least not in abundance
I believe all the hosts in #965291480992321536 should still apply unless they're specialized
DevOps and your programming language should mostly be independent of each other IMO
I used to use a website called autocode which is a serverless hosting site for node.js that offers a free tier for I think 500 api requests a month?
Personally I like to dockerize my code and chuck it onto EKS or just run it on ECS
imagine hosting
or if its just a hobby bot i'll throw it onto my raspberry pi
which i still can't find
even though it's connected to the network
wtf
I got a whole ass dell rack server in my house
just for hobbies
Schrodinger's Pi
haha. never know when that could come in handy
Gonna throw a plex server vm on it soon
Got a buddy that has a few thousand movies on his Google drive and he's already bought a couple hard drives for me to load up on movies
make sure it's overheating and try to smell where the fire is coming from
Ooo that's smart
the thing can't heat up to save its life
Just burn your house down and search the rubble
unlike my PC
you would think a liquid cooler would do an adequate job but nope
80C when coding
How many outlets do you have in your house that you can't find where it's plugged in lmao
Local SSH into it and try to track it down or something
If it has sound you could load up software that plays a ping
you underestimate how many outlets houses have
I own a house
You can prob find the IP via wireshark or termshark
if only it had speakers
Or prob ssh (...).local if you know the username & hostname
piece of shit raspberry pi
I don't see why not finding it would be a problem
think of it as a VPS
simply searching for it is also an option
hm.
Just walk around the walls and trace down everything that's plugged in anywhere
sounds like you don't want to find it
inb4 shut off all your breakers in your house and slowly turn them back on to see which breaker causes the Pi to go off the network
yeah tbh don't really care much either
i probably could if i wanted to, you're right
dont use it much these days anyway
the pi is probably off plotting plans to take over the world
Don't let the Pi figure out how to do matrix dot products
Make sure all your guns are accounted for you don't want it integrating those into its own system
of course. we programmers always keep a loaded gun next to our electronics in case they make a weird noise
Just not too close. You gotta be able to get to it before they do
free heat source
Use one like this it'll act as an afterburner for itself and be more efficient as a heat source
Anyone know if there's a discord bot for streaming video to discord? Like from a website not from a video game streaming service
If this was a joke about plugging itself into itself then I wouldn't be afraid as most circuits are protected nowawadays
Without streaming via discord call?
Because otherwise you'd basically have a glorified link sender
Well it would be via discord call. Like screenshare
how do i make my bot send a message after a person says something to it
if that makes sense
i want my bot to reply back to when the person says there id
Yea I don't wanna go around breaking tos with a self bot. Just had an idea to stream a TV series 24/7 in my server. Tried doing it with an alt account but discord dropped my frame rate significantly after 24 hours so I was wondering if there's some alternative where I could do it via a bot that's told when to stream and such
The API is only for user accounts not bot accounts
So there is no intended way for bot's to stream
Missed opportunity
And either way the bot would also receive a frame rate drop probably (if it were to be added)
not a on_messsage
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.
Wait_for()
how to use
For the discord bot sending a message at a specific hour, should i use date.time ?
dpy 2.0's task loops actually have support for scheduling based on a datetime.time, so its pretty easy to use
everything is against me trying to run a fucking discord bot, when I try on replit it says this:
i fixed it once by sending kill 1 in the shell but now that doesnt work
aight nvm
i got it ||for now||
You could just, not use replit
i just transferred my bot from replit to railway, is there a way to copy the sqlite database over with all of the data? if not what similar database is there that keeps all the data even if i migrate to a different platform
There should be a way to export the database then import it to the new machine
thx, do you happen to know whether railway supports sqlite? i know heroku resets sqlite after each push so i was wondering whether railway does the same
how do i make a select menu contain all users
in a server
using discord's native feature for "user selects"? dpy currently has this implemented in the master (i.e. development) branch, though i havent personally used it myself
if you want to install the development branch to try it, run pip install git+https://github.com/Rapptz/discord.py
and its documented in the latest version of the docs here (dont mix up with the stable version)
https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.select
i guess i'll wait
Hm
I mean I preferably use pycharm but sometimes I need to run it and canโt use it
use oracle cloud. no reason not too especially if you are resorting to repl it
Pycharm is an editor my guy
Use a vps
railway has an ephemeral file system and will remove all the extra files ( like your sql db) after some time
there arent problems w json right?
Change "arent" to "are" and this is right.
๐ญ
Json files aren't really meant to be edited.
db is just harder for me to use
I've tried both actually and json to let it work correctly is far more difficult then a db
And why just for you?
wdym
Well you said harder for me to use
yes
Why just for you?
its hard for a lot of ppl but also for me
I'm confident that everyone can learn sql in like a day
Easy to learn hard to master kind of language
ive tried learning
What did you try?
I recommend trying out postgresql then you can create a db and have an interface to test queries
thanks!
If you have any difficulties just ping me.
okay tysmmm
Great thing about it is that you don't need to know how to create a db with raw sql with is often the hardest part with sqlite
idk what to create tbh
someone told me to make the create giveaway slash command id but idk how to do it
That is a pretty hard command.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
you should at least know the sql basics
like doesnt matter if psql sql or sqlite
just learn at least of them
its gonna become handy in the feature pretty sure
For beginners postgre is easier.
tbh never tried
how do I make all this 1 string so I don't get this error?
use a multiline string
string = """
line 1
line2
"""
thank you i'll try it
it is also way to long and you will still get an error
oh nvm i see
Trying to make the bot respond with the string but I got an error
you're askin for a message argument in the command but aren't providing it
could you show me an example?
? what made you write "message" in the command argument
I thought the string would be the message since I specified message = string
bruh
Just like others functions, the parameters that you define must be provided
def myfunc(value):
print(value)
myfunc() #raises TypeError error, missing 1 required positional argument
mufunc(1) #prints 1
in dpy function parameters are taken by the input of the user within the command
@command()
async def mycommand(ctx, value):
#ctx is passed by default when the command is casted
await ctx.send(value)
if the user types <prefix>mycommand MissingRequiredArgument error is raised since value parameter was not being passed. If the user types <prefix>mycommand hello then value will be equals to hello and the bot will send hello
That's a long prefix ngl
oh I see, I get it
what happened
Your token is invalid
thank you very much
Def not the token
my uncle who makes websites for huge companies keeps a loaded sniper rifle next to him in his room
were in scotland
im not sure its legal
that message was sent 12 hrs ago bruh
why a sniper tho
why not a ak, ar I don't know anything that can be used in semi automatic
I suggest postgresql
If I have my dms closed, and dm a discord bot, would the bot be able to add reactions to my message?
ifyou dm first
it negates the closed dms
how about a paper with a few columns
So the bot would be able to respond too?
if you have the dms closed it wont be able to send you the message
even if there already is a convo
the reactions can be added unless you block the bot
They say a piece of paper is around 5kb
Discord bot on paper.
cheaper than a memory hungry database server
!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)
i can almost cite this ngl
how to send picture in embed
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
thanks
how can i take input with slash commands on nextcord
Whats the typehint for bot object in discord.py?
like inter is disnake.CommandInteraction, whats bot?
the same class that you used to create your bot object
ah yh im dumb its commands.Bot
thanks
Any reason why self.bot.get_channel(voice_channel_id) is returning a nonetype?
in disnake
Hmm id is valid so i'd assume its not that, what do you mean by it's not cached? and how would I solve it
you should be doing cache operations only after the bot is running
fetch makes an api call yes
it will always give you the channel even if its not cached
Yeah, thanks so much just searched up on google.
Yep, never knew about caching and channels so now its good knowledge
thanks for your help
What is the reason why nobody tests their bots? It seems standard to just run it and hope nothing errors.
it's not actually possible to do that without the gateway ( or some other source) sending payloads to the websocket since 90% bot processes depend on them
i know the python discord bot has their own test suite, but apparently it involves a lot of discord mocks, and im not sure what their test coverage is
https://github.com/python-discord/bot/tree/main/tests
https://github.com/python-discord/bot/blob/main/tests/helpers.py
it just tests all the constructors afaik
oh wait it does test models too
For all the nagging i see on testing things, i am quite surprised how often testing gets skipped for a large variety of software.
if it works, it works
Not as a complaint to bot devs. More so just the wierd standard of making tooling such as d.py not testable.
discord.py could be testable, but it's quite cumbersome to mock all those objects
As its more a tooling thing than a developer perspective.
not to mention mocking HTTP requests
I have seen regular bot developers unit test before but it doesn't add as many benefits as it should
I would just test your code inline rather than write down unit tests
Another reason in my eyes would be, well what exactly do you need to test? Discord.py wraps the API so mostly they would only need to test their abstractions, so once you get rid of testing the API from discord you get rid of like, 90% of the wrapper basically
How can I capture what the user is replying to when a command is sent?
You'd basically be testing attributes at that point
And again you could mock it, which would be useful for ratelimit testing E.g bucket limits, bucket hashing etc
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
Hi guys ! I just started thinking with the OOP paradigm few days ago, and I think i'm doing good already. However I still kinda get lost in my flow of data and I'd like to have some help if you guys fancy. In the following program, the bot instantly cancels the report after I run the command, without throwing any error and I'm confused. Can you guys help me figure it out? :D
asyncio.wait() returns a tuple of two sets, first containing the done task and the second containing pending tasks
https://docs.python.org/3/library/asyncio-task.html#asyncio.wait
I get <member 'reference' of 'Message' objects> when I print it
How do I integrate it into ctx.reply?
although the above issue only applies after one of those tasks finish, but if your command immediately says its cancelled after doing nothing, perhaps there's another bug
ohhh so i'm storing a tuple instead of a variable I get it, lemme try this
you didn't just copy paste discord.Message.reference, did you?
you can also rewrite check=lambda message: cancel_filter(self, message) as check=self.cancel_filter
and line 177, Reportee.ask() isnt awaited
I'm trying to understand a new thing for me
what exactly do you want to do
This
ctx.message.reference.resolved.reply
What about ctx.replied_reference or are those two the same?
idk about that but most probably not
One way to find out
AHHH thank you I wasn't sure about this one lol !
how do i get intents to work?
discord.intents = intents.default()
client = commands.Bot(command_prefix='!', intents=intents)
Traceback (most recent call last):
File "/home/ciaran/discord_bots/main.py", line 12, in <module>
discord.intents = intents.default()
NameError: name 'intents' is not defined
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
hint: it's case sensitive
-1 for only importing Intents, and -1 for not enabling message_content
oh okay, and now this:
Traceback (most recent call last):
File "/home/ciaran/discord_bots/main.py", line 25, in <module>
@client.command()
NameError: name 'client' is not defined
but otherwise yeah that example is how you'd do it
for the second one, this tag is like a year old lol
but yeah it could be updated
How to get command from cogs?
the last update to it was 6 months ago specifically to add that message content in the first paragraph, but the code example was not updated
maybe there's another PR about it, if not ill do it
I tried bot.get_command but it requires self and ctx arg, when I added them to callback it says self not defined
what do you need the command for? where are you using it in your code?
yeah that would be nice, adding comments about which privileged intents enables what features would be even more helpful !!
bot.get_command() should only require a single string describing the command's name
Yes, I want to let my code run the command in the cog
As a interaction response to the selection menu
!d discord.ext.commands.Bot.get_command
get_command(name, /)```
Get a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
Changed in version 2.0: `name` parameter is now positional-only.
hm, i guess that might be alright to do, though imo its usually easier to refactor your command into a third function
!d discord.ext.commands.Context.from_interaction
classmethod await from_interaction(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.
On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.
In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.
New in version 2.0.
async def check_cancel(self):
while not self.view.canceled:
continue
return True
Is this a proper way to listen to a cancel button?
(I subclassed View and added self.canceled = False that gets changed with a button callback)
your while-loop would run indefinitely and block the event loop
I'll use asyncio.wait() and it will run with another function tho
I mean I'm already using it
continue is used in a loop
you would either want to use a pass statement or return a False here
(pass will make the function return None here)
but your function is still not yielding to the event loop
I don't get it
how do i solve this?
2022-11-10 14:03:46 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
remember that the event loop relies on cooperative multitasking, as in tasks must yield themselves so others can run
that yielding only occurs when the task does an await, or async for, or async with
while not cancelled: pass never yields, so it prevents all other tasks from running
(not to mention it maxes out your CPU core)
you need to enable the message_content intent on your Intents object before you pass it to the commands.Bot constructor
he has it man....
e.g. py intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(...) # here is same as what you had before
wtf why is the bot dming the responses
instead of sending in chat
if message.content.startswith('hello'):
msg = 'Hello, how are you? {0.author.mention}'.format(message)
await message.author.send(msg)
a better solution would be using an asyncio.Event and having check_cancel() wait for it to be set by your cancel button, or if your cancel button calls View.stop() then i would use the built-in View.wait() method
message.author.send() is sending your text to the author of the message that it received in the event, hence why its written as message.author.send
if you want to send to the same channel that the message came from, you'd write message.channel.send()
the documentation will help you figure out what attributes and methods there are
!d discord.Message.channel
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if itโs a private message.
Just ctx.message.reference is what was needed. Can that return None, btw?
whenever the message doesnt reference anything, yes
resolved might also return none too
how can I add a parameter to load_extension? should I inherit commands.Bot or is there a better way?
await bot.load_extension(f"bot.member")
bot/member.py
class MyBot(commands.Cog):
def __init__(self, bot:commands.Bot) -> None:
self.bot = bot
self.database = "?"
well that's not what you showed in the screenshot but okay.
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") to do this.
you might want to make it a bot variable instead, see !botvar for more information
or you can make self.database a class variable instead and then import the cog class manually and set the database variable
'''bot/member.py'''
class SomeCogIDC(commands.Cog):
database: ... = None
def __init__(self) -> None:
...
''' main.py '''
from bot.member import SomeCogIDC
SomeCogIDC.database = "no"
you'll have to override or monkeypatch
I guess I'll override, I have many bots and many cogs for bots, so it'll be cleanest
what is monkeypatch though
you can just make database an attr of bot tho
async def some_fun(...): ...
bot.load_extension = some_fun
"some" "fun"
ahem
hello
bot wont send embed how to fix?
instantiate account -> account()
i always forget that thanks
function
Not this again
code :
@bot.event
async def on_member_join(member):
Channel = bot.get_channel(1040275571311116368)
background = Editor("pic.png")
profile_image = await load_image_async(str(member.display_avatar.url))
profile = Editor(profile_image).resize((200, 200)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")
background.paste(profile, (320, 60))
background.ellipse((320, 60), 200, 200, outline="white",stroke_width=5)
background.text((414, 320), f"Member: #{len(member.guild.members)}", color="white", font=poppins_small, align="center")
background.text((414, 260), f"{member.name}#{member.discriminator}", color="white", font=poppins, align="center")
file = File(fp=background.image_bytes, filename="pic.png")
await Channel.send(f"Helloooo {member.mention} welcome to **{member.guild.name}** ๐น๐น", file=file)```
error:
```Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Skater Hub Bot\cogs\moderation.py", line 121, in on_member_join
await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Skater Hub Bot\cogs\moderation.py", line 121, in on_member_join
await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'```
get_<...> tries to get stuff from bot's cache, if it doesn't exist it returns None
use fetch_<...> when get returns None
ru talking to me?
ya
Lol
im talking about
Channel = bot.get_channel(1040275571311116368)
bot.fetch_channel?
yea
ill try now ty!
C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py:509: RuntimeWarning: coroutine 'Client.fetch_channel' was never awaited
pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
i dont do await channel = bot.fetch_channel(id), right?
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Skater Hub Bot\cogs\moderation.py", line 121, in on_member_join
await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Skater Hub Bot\main.py", line 120, in on_member_join
await Channel.send(f"Helloooo {member.mention} welcome to **{member.guild.name}** \U0001f6f9\U0001f6f9", file=file)
TypeError: coroutine.send() takes no keyword arguments
C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py:509: RuntimeWarning: coroutine 'Client.fetch_channel' was never awaited
pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
channel = await bot.fetch_channel
OH
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Skater Hub Bot\cogs\moderation.py", line 121, in on_member_join
await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'```
ID is prolly wrong
Ah sorry never used Pillow
oh okay ty!
smort huhh
ahem
Seriously tho
nvm, I need to seriously fix my mind
Well u can help him if u have used Pillow lol
haven't ever
totally not learning pillow until desperation arrives
!pypi easy_pil is always there but ๐คท
then should i switch to postgres? or stay on sqlite and use replit
You should just quit replit if you need data storage
In fact you should quit it anyway
I see no reason in using browser IDE when you can use local IDE which is much more flexible and powerful
Unless you have like very low-end PC that can't even run VSC
How to invoke a command from another cog in discord py? For example when I do /menu then a embed message and a selection menu will pop up and if I select something in the selection menu, I want it to run another command from another cog
!d discord.ext.commands.Bot.get_command
get_command(name, /)```
Get a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
Changed in version 2.0: `name` parameter is now positional-only.
I tried, but nothing returns
property cogs```
A read-only mapping of cog name to cog.
So if I want the abc command is the cog to run I use โbot.get_command(โabcโ)โ
Mhm
Do u have an error handler
No
get a logger and it could fail coz two reasons an internal command error or duration to respond is greater than 3 sec if u did not defer
Try setting the coordinates to where you want stuff pasted to 1,1 that should put it in the top left corner and adjust from there based on how many pixels your image has
anyone have any examples of discord py, using buttons with @bot.listen commands.
yes i had a mistake in the code lol tyyy
Alright
Also you may DM me for errors just for privacy and save public space
Guy
Am tryna make a free crypto mining discord bot
but when somebody does !mine
it mines for him in his account
but how do i make it when its mining
like os.system(f"py cryptomining.py")
but when it does thhe procces
it pauses the bot
is there anyways i make it so it doesnt pause the bot or does the mining in another cmd tab like open another cmd tab and do it in there
is there if there is pls tell me
i dont think thats possible
I don't think you read what we typed
Yes
how
!d asyncio.create_subprocess_shell
coroutine asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Run the *cmd* shell command.
The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).
Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.subprocess.Process "asyncio.subprocess.Process") instance.
See the documentation of [`loop.subprocess_shell()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_shell "asyncio.loop.subprocess_shell") for other parameters.
Important
It is the applicationโs responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid [shell injection](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) vulnerabilities. The [`shlex.quote()`](https://docs.python.org/3/library/shlex.html#shlex.quote "shlex.quote") function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands...
Yes
os.system(f"java -jar cryptomining.jar {arg1} {arg2} {arg3} 60 5000 y")
@cloud dawn can you help me w some
can u make it so when it runs this command it opens a new shell pls
Sure :3

Look at this Embed, first arg is a cmd.
Hmm, I'd need more info, I get your idea but I need to think about it too since with slash you do need some kind of interaction.
@cloud dawn i just need u to give me a code i replace with this that makes it so it runs this command but in a different cmd os.system(f"java -jar XDDOS.jar {arg1} {arg2} {arg3} 60 5000 y")
like just transform that function innto a code a that makes it so it runs in new cmd
why u go 

me now sed D:
what is happening here
!d asyncio.create_subprocess_shell if u wanna run a cmd command from a discord bot
coroutine asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Run the *cmd* shell command.
The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).
Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.subprocess.Process "asyncio.subprocess.Process") instance.
See the documentation of [`loop.subprocess_shell()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_shell "asyncio.loop.subprocess_shell") for other parameters.
Important
It is the applicationโs responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid [shell injection](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) vulnerabilities. The [`shlex.quote()`](https://docs.python.org/3/library/shlex.html#shlex.quote "shlex.quote") function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands...
@maiden fable am new to this i dont understand anything
can u just make this os.system(f"java -jar cryptomining.jar {arg1} {arg2} {arg3} 60 5000 y")
Uh, do u know about asyncio and awaiting stuff?
into a command which does the same but in a new cmd
confusion 100
@cloud dawn is more experienced and will help u thanks
oke D:
We won't help with this since this tool is mostly used to ddos minecraft servers.

