#discord-bots
1 messages · Page 668 of 1
You can install it through the command tool, but I’d not think that is in the chrome book version
try:
await ctx.send(…)
except discord.HTTPException:
pass```
Hello Caeden
Average python chat
correct
Thanks Caeden, I will try it 🙂
Stop pinging him, he will be here in his own time
Learn to have some patience
i cant
Why?
lol
I thought you were a discord dev
Average python user
How can i fix this?
You are a discord bot developer yet your having trouble event downloading python
Good one
What are you using to run commands
I’ve seen on_message and bot.command() but yield from?
@client.command()
Send whole command
So I can get some context from what your doing
Are you trying to send a message from the on_message event
Why are you using % use f to format the str
If so message.channel.send(“text”) should work
yes
Idk where your getting “yield from” from
I don't use Linux but I guess Gzipped
🕴️
That emoji scares me
You use aiofiles
It’s so confusing
I think 
I think you use aiofiles
Use a try except
Im not listening to a stackoverflow solution thats 2 years old🕴️
It’s not a discord error so I think try except should do fine
I read ones that are 9

no
And don't use a bare except lol
you would make an event error handler
Is there a way I can check if a User has the 10$ version of Nitro?
Afaik no
I like it when Caeden says some cool sounding words
and becomes hella smart
Are you obsessed with caiden
Maybe you have to DOWBLOAD MAINFRAME FOR DISCORD PY AND BECOMR PRO HACKER
That's unfortunate
Oh
!d discord.on_error || but you also need to edit your discord.py sourcecode because danny kinda fucked it up
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.9)").
If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.9)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
Use an online service for running your python code
#simpforcaeden lol
Linode

this code wants to murder my terminal
i get so many errors
what im trying to do is get a token from a list of bot tokens and get the username and id of it and print it to the console
then running the main bot
What’s wrong
everything
Everything doesn’t specify
its returning the name and id of the bots in the list
but then it throws an error when trying to run the main bot
i assume its because im using bot.close()
which is throwing off something
Which error
ill send teh traceback
ok
I think
You ran the token twice
And it threw an error
It’s something to do with the run() function ig
i figured that
the tokens it is running are two seperate bots
(memer and memer2)
you leaked your token
😢
did I
refresh it in the dev portal quickly
Is this how I change a channels permission for a specific role?
member_role = ctx.channel.overwrites_for(918955830810923049)
member_role.send_messages = False
i checked
i did not
what should I do to prove it to you
I sent it to you
nvm i did
indeed you did 
refreshed
it wasnt in any servers anyway
how to make a clear command
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting bot’s messages...
I don't think nuking a channel is something I'm gonna help you with
huh
i wouldn't call that nuking
I would
how
deleting every message from a channel
is called nuking it
yep i need to to start my channel message history from fresh
just because he wants to clear all the messages in a channel doesn't mean he is doing it for a bad purpose
it makes as many API calls as possible aswell
With regards to this method, I know that Discord itself has a retry method in place, I imagine this has the potential to create conflict with that or at least duplicate messages, is there any way of preventing that or is it a non-issue?
can't u just delete it then create a new one
does nuking has to be for a bad purpose tho
im using the id somewhere else so i cant
well store the id
what is the max number to clear in one request
hm
I don't think there's something like that
and you can set the limit to none which actually nukes the channel
but you should be a lil bit aware of that
nukes as in deletes the channel?
or all the messages in it
- discord crashes
- bot will get rate limited eventually
this
well you'll see
You can clone the channel and delete the original one
yep
wdym?
infinite api calls
setting limit to None runs forever?
no
it deletes all messages in a channel
which is a lot of api calls
especially when you have a lot of messages
above 10000, I'd rather just delete the channel
maybe above a couple thousands aswell
no i have less than 1k messages in the channel
this is correct right
@commands.command()
async def clear(self, ctx):
await ctx.channel.purge(limit = None)
If you want to "nuke" a channel, safest way is to clone the channel, delete it. Then add the clone back
I think so
i dont want to lose the id tho
so deleting all messages is the best way
Again, just store it
for a little task no need
but thanks
Your bot is going to get rate limited
This wouldn't even work
Limit has to be passed as an int, or not passed at all
Because purge checks the channel's history, that requires an integer
it would work
No it won't
I know, cuz I already messed that up
default is 100
got a channel nuked
None means all
discord/iterators.py lines 297 to 298
if self.limit is None:
raise ValueError('history does not support around with limit=None')```
No it does not kek
how
:o
so how did somebody tell me
in the dpy server
that his channel got nuked
when I told him to set it to None by accident
Not sure how that is possible ¯_(ツ)_/¯
I quite literally just read the source code for purge just barely
It won't work if None is passed to limit
Even checks for it, and raises an error if it is
ill write 100million then
How to get rate limited 101
That wouldn't work either
The max for history iirc is 100 messages
How to I edit a roles permission in a channel cause this won't work.
await ctx.channel.set_permissions(918955830810923049, send_messages=False)
How do I run 2 bots at once then close one of them
Considering what's going on in #python-discussion I'm going to avoid helping you for the time being
Wtf did I do wrong
What you're doing is strange
It’s a bot running program for ease of accesss
I’m trying to access a list of bots that I have saved in a text file
And that's what's strange about it
I would just write the tokens in manually
But I prefer to have it in a text file
I’ll explain my full code
a .env is easier, just copy the token.
It gets all the tokens in a text file and checks if they are valid
Just in case I’ve typed a token in wrong
And to avoid some run errors
Then it runs that token and gets the username and ID of the bot
It closes the bot
Why do you have so many tokens?
I have 2
you using discord.py @slate swan
Because I have 2 bots
Yes?
Then why not do it manually?
Because it’s supposed to be a program for ease of acces
bro like i told you you need to do it differently
are you running 2 bots on the same code?
They are just going to tell you the same thing
Then explains how to do it
I did you just left
That was eivl
can you show the code without the tokens pls @slate swan
How many tokens do you have?
okay if you got a list [1, 2] would you for loop this?
Then you will get errors??
That’s why I’m checking for valid tokens
To test the valid token checker

And so I have a reason to loop it
how does discord secure tokens from people typing random tokens?
They dont
It is pretty impressive if you can get a token out of it.
It’s 59 characters in a token
So there is a VERY low chance you will get a working one
how many chances are they?
more than a billion i would guess
Fact that you also know the exact length is very sus
To check for valid tokens
!e ```py
print(262610**56)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
67600000000000000000000000000000000000000000000000000000000
A lot
thats allot lol
So there would be no point to brute force tokens
Because it would take century’s
@slate swanDo you know what try/except is?
Yes
Then why isn't that in the 'validator' if you are checking for wrong tokens?
I’m just checking for 59 characters
I’m getting the base code down
I’ll add it later

🚶
Show the whole code and i agree
every single bit of my code
hmm
@slate swanShould i help him? I need a second opinion.
Validating tokens is kinda 
I’m gonna release this program online when I’m finished
So other people can use it
It’s a utility for discord bots, to make it easier to make one
To check if a token is valid? What would that benefit?
How will it help the user?
By telling them if it’s invalid
I'm pretty active here and most issues here are not token related
Current code already does that..?
Idk seems weird as a user would do that
Its nothing bad its just easy to make it against tos
Everything is easy to make against tos
I'm asking the mods rn if they agree then i will help. It's not you i've helped some people b4 to later find out they just used it to break ToS.
Ok
It can be malicious which is against tos and rules in this server
It’s really obscure. I understand why you would be suspect for something against TOS
This is correct isn't it?
?
channel = await self.bot.fetch_channel(917238203101089832)
sorry forgot to send code lmao
Yeah
Well try to get it from the cache first but other than that 👍
This is why I’m not gonna post the source code for the program online because people are gonna use it for stuff against tos
Yeah its sensitive stuff
oh that makes it better :)
I don’t think it would be decompilable
well at least they know its safe :)
😂
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
I'm still waiting for the mods.
To be honest i'm not certain so let's just wait for their opinion.
Making it a exe makes it even better for users
Is this sarcastic?
yes.
🕴️
Also smart screen, an unsafe program is going to get executed, do you wish to continue?
You don’t need to install python to run it
@slate swan Why do you need to check tokens?
Exactly
That's not something you should ask for help here.
My problem is running two bots at once
Nothing about this smells right
I'm not sure I'm comfortable with us fielding this
No... you wanted to validate tokens??? You didn't ask about running 2 bots, only later.
Send a single peice of evidence asking how to validate tokens
I know how to validate them
I don’t need help with that
So a definite no on the token validator, i can help with the 2 bots in one file?
Yeah, I'm shutting this down. We're not helping with this
Mods are shutting it down anyway
Okay thanks for clarifying guys.
I’m just gonna ask stack overflow
For clarification, regardless of whether or not the question is about having two bots in a file or not, it's clear that this is all rather sketchy and against ToS. I'm not having our server linked with anything like that.
There should never be a time that you need to "validate" a file full of tokens
There’s 2 tokens
The questions werent very clear and confusing which made it really sketchy and questionable
And there both mine
And you got invalid token(s) inside it, therefor i responded why not keep the 2 valid ones. But you quite insisted on validating it.
why do you want to upload the exe then? 
Because I’m trying to make a program in python
Nothing about what your code says or what you just said is believable. If this question gets asked again here further moderative action will be taken. Okay? Okay
Making it a exe and easier makes it even more suspicious
Okay dokay
Okay but considering the mods already shut it down let's get back on topic :)
And I assume me asking further questions about discord.py will get no results
Like last time this happened
Is this how I add reactions?
It will but not those 2 questions like the mods mentioned.
poll = await channel.send(embed=poll_embed)
await poll.add_reaction(":arrow_up_small:")
await poll.add_reaction(":arrow_down_small:")
Yes
ok cool
I recommend just testing it out, result is satisfying 
Ikr
Very beautiful
Hmm i especially if i have been coding for an hour then decided to test it to see if i'm still doing it correct and it just passes all test owww

I can't tell if you are being sarcastic or not 😂
he's not.
!d discord.Message.add_reaction || you can just add a reaction onto any message
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Why would i what are you coding for if not result?
Alr
Why do I receive this error when there is no other command called ping.
discord.ext.commands.errors.CommandRegistrationError: The command ping is already an existing command or alias.
Did you restart/reload and are working in the correct file?
speaking from experience
Did you also try CTRL+F "ping" across all files?
Yeah I am 100% running from the correct file and have tried multiple times but still receive the same error.
I thought ctrl + f only works within the file you are working in
did you do alias=['ping'] or something?
CTRL+SHIFT+F allows all file search for current projects.
ah ok
it depends your IDE does it not?
Found it!
Atom and VScode support this feature.
ctrl + shift + f found it, thanks
yeah noone cares about pycharm anyway
Mighty tool.
i use vscode
Pretty sure Pycharm has it too lemme check
Pycharm has way too many options for my liking i like a light build like atom or vim
Not that light i still need my github integration lol
i have an array that looks like this [[userid, "username#0000", 0]] and i want to make it so you can add/ subtract from that number.
i have this
async def points(ctx, user: discord.User, method, points):
userid = user.id
if type == 0 and any([userid in elem for elem in points]):
idk what to put into the if statement
!d any
any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:
```py
def any(iterable):
for element in iterable:
if element:
return True
return False
hehe
Why not have this in a dict? This looks very complicated
agreed
i should
but i want to do smth later and i feel like it would be a lot easier in an array
I get this error when running my poll command?
poll = await channel.send(embed=poll_embed)
await poll.add_reaction(":arrow_up_small:")
await poll.add_reaction(":arrow_down_small:")
Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji
users = {
12890128312: {
"name": "yte"
"points": 28382
}
}
Even better would be a database :)
ye i thought about that. but i have zero clue how
You need to input something else..
wdym
does the server have the emoji?
it's a default discord emoji
default emoji
oh
!d discord.Message.add_reaction || the argument needs to be a unicode emoji.
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
!d discord.PartialEmoji.from_str
classmethod from_str(value)```
Converts a Discord string representation of an emoji to a [`PartialEmoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialEmoji "discord.PartialEmoji").
The formats accepted are...
\U0001f53c: UP-POINTING SMALL RED TRIANGLE - 🔼
Unicode
poll = await channel.send(embed=poll_embed)
await poll.add_reaction(u"0001f53c")
await poll.add_reaction("\u0001f53c")
!charinfo 🔽
\U0001f53d: DOWN-POINTING SMALL RED TRIANGLE - 🔽
I forgot the syntax lol
I just paste the actual emoji inside my script xD
same lol
I get the exact same error?
poll = await channel.send(embed=poll_embed)
await poll.add_reaction("\u0001f53c")
await poll.add_reaction("\u0001f53d")
eh paste the emoji
its easier
idk how to do it
just find it online
I just ctrl-c it from discord
you cant do that
🔽
wait can you??
omfg you can
yes lol
i went to that website every fucking time lol
wtf i swear it just gave the name
Here if it really not workinghttps://paste.pythondiscord.com/ufajacopoz
did they change it?
must have
😢
sowwy 
Hi , i'm trying to do a commands thats gonna has a user to a blacklist so prevent him to use my bot how?
@slate swan Reason for Dm'ing invite?
Make a custummm mcheckckckck
o:
!d discord.ext.commands.check
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
!d discord.ext.commands.Bot.check || you would use a check. it triggers before each command and if it returns True, then it activates, else it doesnt. py @bot.check async def bot_check(ctx): if ctx.author.id == blacklisted_id: return False #dont acctivate command. Raises GlobalCheckFailure return True
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
weird
oi go away i gave a better explanation you just typed it first 😡
is it possible to display a jpg as an emoji inside of a message?
no.
I didn't mean to do that sorry @cloud dawn
you need to make the jpg and emoji
ah ok, figured as much
Idm accidents can happen.
Yeah first look if it is an image in the embed then convert it and post it then delete it. It is possible though.
they can? lol
better.
sounds slow, have you ever done this before?
Heroku pricing is a bit confusing. Does the hobby plan have 10M database rows?
God no hahaha
You know how much data you can store with this.
10M? lmao
What I mean is whether I will get that amount of database rows by purchasing a hobby plan or not.
cause their pricing is confusing.
@cloud dawn
I don't see anything about database rows
Heroku Postgres
and that's why I was saying that it's confusing xD
Oh
yeah hobby is 10m
Heroku is pretty damn expensive though jeez
250 bucks a month for 2.5gb ram
Then i can setup my own server in a year lol
Opening files
The built-in function open() is one of several ways to open files on your computer. It accepts many different parameters, so this tag will only go over two of them (file and mode). For more extensive documentation on all these parameters, consult the official documentation. The object returned from this function is a file object or stream, for which the full documentation can be found here.
See also:
• !tags with for information on context managers
• !tags pathlib for an alternative way of opening files
• !tags seek for information on changing your position in a file
The file parameter
This should be a path-like object denoting the name or path (absolute or relative) to the file you want to open.
An absolute path is the full path from your root directory to the file you want to open. Generally this is the option you should choose so it doesn't matter what directory you're in when you execute your module.
See !tags relative-path for more information on relative paths.
The mode parameter
This is an optional string that specifies the mode in which the file should be opened. There's not enough room to discuss them all, but listed below are some of the more confusing modes.
'r+' Opens for reading and writing (file must already exist)
'w+' Opens for reading and writing and truncates (can create files)
'x' Creates file and opens for writing (file must not already exist)
'x+' Creates file and opens for reading and writing (file must not already exist)
'a+' Opens file for reading and writing at end of file (can create files)
You need to indent everything under the function definition
Notice how line 62 is at the same indentation level as line 63. That's incorrect.
right , so how do i make a database
@cloud dawn my internet isn't the best so I can't rely on it now. Do you have any better alternative than Heroku?
I need to host 2 bots and I need a Postgres database.
For free? No.
Paid.
Then AWS but you will need a credit card
I recall some people on staff praising netcup https://www.netcup.eu/
Their pricing system is the worst imo
There are so many options for hosting and they all have competitive pricing.
This is cheap holy
They don't seem to have a Postgres database.
With this amount of RAM you can just run it inside the VPS lol
Oh you want a managed db instance?
Cause yeah, you can run pg yourself in the server
Opening files
The built-in function open() is one of several ways to open files on your computer. It accepts many different parameters, so this tag will only go over two of them (file and mode). For more extensive documentation on all these parameters, consult the official documentation. The object returned from this function is a file object or stream, for which the full documentation can be found here.
See also:
• !tags with for information on context managers
• !tags pathlib for an alternative way of opening files
• !tags seek for information on changing your position in a file
The file parameter
This should be a path-like object denoting the name or path (absolute or relative) to the file you want to open.
An absolute path is the full path from your root directory to the file you want to open. Generally this is the option you should choose so it doesn't matter what directory you're in when you execute your module.
See !tags relative-path for more information on relative paths.
The mode parameter
This is an optional string that specifies the mode in which the file should be opened. There's not enough room to discuss them all, but listed below are some of the more confusing modes.
'r+' Opens for reading and writing (file must already exist)
'w+' Opens for reading and writing and truncates (can create files)
'x' Creates file and opens for writing (file must not already exist)
'x+' Creates file and opens for reading and writing (file must not already exist)
'a+' Opens file for reading and writing at end of file (can create files)
It will be a bit slower than having an actual server handling all the connections but still for starters. Will also save the hassle.
Sounds like a hustle XD
Well you can just install it it's pretty easy.
Heroku has one, I want something like that tbh
24GB for 16 bucks a month jeez next time i'm hosting my minecraft server there lol
If they allow port forwarding that is.
Prob not lol
.bm yes
@cloud dawn they don't have a good documentation tho.
I can't see a tutorial on how to set up a Discord bot on Netcup.
It's a vps
and? XD
you need to setup the vps first?
It's not as straight forwards as Heroku.
vps is basically a remote virtual machine
best is to use unix based since windows is a bit heavy
What is the best package for Asynchronous HTTP Requests to an API within a DPY project for things like user data storage etc?
So aiohttp to send the HTTP request and fast API for the actual API? Sounds like something I can definitely make happen!
!pypi discord-ext-ipc
A discord.py extension for inter-process communication.
Really? That's awesome! What does the built in module intended to handle?
authentication by logging ins some other stuff.
AttributeError: 'Client' object has no attribute 'Command'```
That is true.
how to fix?
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
so discord.Bot() instead of discord.Client()?
@cloud dawn I will probably end up using ElephantSQL and netcup.
discord.ext.commands.Bot
I recommend reading this and clicking the url
client = class discord.ext.commands.Bot(command_prefix=".", help_command="help", description=None)
No
sorry im new to dpy
bot = commands.Bot(**kwargs)
I recommend checking this out then -> https://vcokltfre.dev/
But first learn oop and python basics if you havent
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Anyone have any tips with ui.view for pagination
Disnake?
Disnake has git examples
Heyy i am not sure what this might be called but when a member gets verified or like reacts to a role to be verified in the server can it send a message to where itll say that this member has been verified?
how can i use a PIL image in an embed?
discord.Member, discord.TextChannel are common subclasses of discord.Messagable
ok How is it done?
all discord.Messagable subclasses have a send() method
Which, as you may have guessed, can be used to send a message to that channel/user
Sure , save the image locally first , and ```py
embed = discord.Embed()
embed.set_image(
url="attachment://filename.png"
)
image = discord.File("/path/to/filename.png")
await ctx.send(
embed=embed,
file=image
)
Ok and thats a @client.event right?
No it's a coroutine
Wait for a reaction and get the author of it and mention the author
Can you walk me through it?
I think it has a author attr
Nah never done it before
Sure, where do you want to send the message to?
A DM or a channel?
Right, do you have access to the discord.TextChannel object and the discord.Member object?
You should if you have the ctx
ohh wait hang on ill do that now
@sick birch how do i get all the messages from a channel
Generator of any discord.Messageable subclass
If its a command yes you can name the function anything
Well
no just a client.event?
If a event depends what your waiting for
Personally naming a command ban, kick, etc... causes issues
Yeah except that
Try to avoid naming your commands after the library's method
acually didnt cause any issue for me
If you absolutely must, you can prefix the command with an underscore, and pass in the name= kwarg into the decorator with the actual name that you'd use on discord
tho
Naming a function methods will give you naming errors
those 2 commands works perfectly fine for me
Odd
Most commands give hinting or naming erros
none of that happened
Nope as your defining async functions afaik
how can I make a command only usable once and never again?
Might be wrong but i dont think i am
Have some sort of persistent data storage method (database preferable), a key like "is_used" of a boolean value that indicates if it's been used or not
you can then use the @before_invoke decorator to define if the function should be called or not
After a command add a value to a var and if that var is that value disable the command
Or, alternatively, after the command is called, disable it
Can you do that?
Ok so how so?
Wdym?
im getting this
async def get1(ctx, channel : discord.TextChannel):
async for message in ctx.channel.history(limit=200):
print(message)```
in a class.event
You need the positional argument
plz bear with me as my english is my 2nd langauge
Use the (on_member_join) event
Same lol
how do i do that 
You add the arg
like i want it to be when a member is verified want it to send a message saying .... and to send it in a channel and dm
Aka the channel obj
and if that does not happen
just add channel as a param?
it sends a message to a member that u would need to get verified to be able to see the rest of the server channels
After a join add a role and on reaction you remove the role
for both payload function?
or sorry def
@slate swan
~channel id
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
@bot.command(name="snipe")
async def snipe(self, ctx):
"""A command to snipe delete messages."""
if not self.last_msg: # on_message_delete hasn't been triggered since the bot started
await ctx.send("There is no message to snipe!")
return
author = self.last_msg.author
content = self.last_msg.content
embed = discord.Embed(title=f"Message from {author}", description=content)
await ctx.send(embed=embed)
hello
where
When you call the command
Remove self
but i need self
Is it in a cog?
So
no
Then remove it
No need for it
self is used to acces the class the command is in
then what do i use for self?
Delete it
you can use botvar for it
it prints author etc but not the actual message
for replacing self
umm hello?
@bot.command(name="snipe")
async def snipe(ctx):
"""A command to snipe delete messages."""
if not last_msg: # on_message_delete hasn't been triggered since the bot started
await ctx.send("There is no message to snipe!")
return
author = last_msg.author
content = last_msg.content
embed = discord.Embed(title=f"Message from {author}", description=content)
await ctx.send(embed=embed)
never heard of it
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
o_o
anyway, this type of question should be asked in #python-discussion
async def on_raw_reaction_remove(payload):
ourMessageID = 914720242297630750
if ourMessageID == 914720242297630750:
member = payload.member
guild = member.guild
emoji = payload.emoji.name
if emoji == '✅':
role = discord.utils.get(guild.roles, name="Unverified")
await member.add_roles(role)
@client.event
async def on_raw_reaction_remove(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for key, value in data.items():
emoji = payload.emoji
role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=832120561848156180)
await payload.member.add_roles(role)
No need for raw reaction
is payload context?
Iirc raw reaction makes a call as the msg isnt cached
yep so best case
Alr
Anyone know how to prevent database locking due to async in dsicord bots?
async database module
^
Well idk ur saying like
mb but what do u mean by that though
like making me do
@whole sparrow answering ur question
and telling u which module to use
async versions of the database module
ohh
@client.event
async def on_member_join(member: discord.Member):
....
Dont think you need to type hint it tho
ohh well i have it right here
you don't need to typehint it , but it's more readable and efficient to do that
async def on_member_join(member: discord.Member):
guild = client.get_guild(730651046459998218)
channel = client.get_channel(885464532959526913)
Myembed = discord.Embed(title= f"Welcome",
description=(f"Welcome {member.mention}, You are member {guild.member_count}. \n Please enjoy your stay here and dont forget to read the await [#904279966693355550](/guild/267624335836053506/channel/904279966693355550/)"))
Myembed.add_field(name="Account Created at:", value=f"{member.created_at(datetime)}", inline=True)
await channel.send(embed=Myembed)
await member.send(embed=Myembed)
roles_list = ["Unverified","•.¸¸.•:Colours:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Verification:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Age:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Gender:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Sexuality:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•",
"•.¸¸.•:Distance:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Ethnicity:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Hobbies:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Relationship:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Location:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•",
"•.¸¸.•::•.¸¸.•`Seeking`•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:DM:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Levels:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Games:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•"]
for roles in roles_list:
role = discord.utils.get(member.guild.roles, name=roles)
await member.add_roles(role)```
Yeah i just sometimes do it
With the event just add the unverified role and on reaction remove it
bot.wait_for("reaction")
iirc
gangster , you trying to do something like -> member joins -> unverified and other roles get added -> when the user reacts on some message , the unverified role gets removed?
either reaction_add or reaction_remove
Yeah that
is there any possible way to make a bot listen to other bots?
You make the bot type in the commands of other bots
not really
Then what exactly?
yeah but bots dont listen to other bots, that's just how discord works. is there any workaround though?
Please elaborate
ok hold up
Bots do
Some bots can but i dont think you can with dpy
damn
As mee6 does take commands but those are private wrappers
I think with discord client you can
And not the bot instance
When a member reacts to this i want it to where itll send a message to DM and channel to when this member has go verified and is able to talk in channel now
And if it has failed
it either sends his another message saying to either verify again or kicks him from the server
Make sense?
On join add a role which doesnt have permission for anything then on reaction you dm the author and remove the role with no permission and send a message with a mention of the author
You can add a timeout and after that it will send a msg if not verified it will kick the member
ok can you walk me through it?
^
^
is DM await member.send(embed=Myembed) RIght?
Yes
The member obj on join
async def on_member_join(member: discord.Member):
guild = client.get_guild(730651046459998218)
channel = client.get_channel(885464532959526913)
Myembed = discord.Embed(title= f"Welcome",
description=(f"Welcome {member.mention}, You are member {guild.member_count}. \n Please enjoy your stay here and dont forget to read the await [#904279966693355550](/guild/267624335836053506/channel/904279966693355550/)"))
Myembed.add_field(name="Account Created at:", value=f"{member.created_at(datetime)}", inline=True)
await channel.send(embed=Myembed)
await member.send(embed=Myembed)
roles_list = ["Unverified","•.¸¸.•:Colours:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Verification:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Age:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Gender:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Sexuality:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•",
"•.¸¸.•:Distance:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Ethnicity:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Hobbies:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Relationship:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Location:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•",
"•.¸¸.•::•.¸¸.•`Seeking`•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:DM:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Levels:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•","•.¸¸.•:Games:•.¸¸.•``•.¸¸.•``•.¸¸.•``•.¸¸.•"]
for roles in roles_list:
role = discord.utils.get(member.guild.roles, name=roles)
await member.add_roles(role)```
This is my code
Yes
It will add the unverified role
Then send a msg and wait for a reaction after the reaction it will remove the roles
Is that with a ctx attribute?
👍
Wdym?
The message part do i add await ctx.send(You will need to react to the emoji in 5 more minutes. Or action consequence will occur.)
something like that
No since you arent waiting for context
Just send a msg with the channel obj
WIll work?
Message = discord.Message(description= f"Please pick your gender role by reacting to the emoji"
idk
No?
plz guide me through?
You use the channel obj you got
In this case the channel you got is in the channel var which channel has the .send attr
await channel.send(embed=Myembed)
Yes
Ohh and i just replace it with? You will need to react to the emoji in 5 more minutes. Or action consequence will occur.
If thats what you want to send yes
And after everything you can clear the channel if that is what you want
Ok then and how do i make it to where itll kick a member when he/she doesnt react to a certain timeframe?
I think wait_for has a kwarg for timeout
Where is that placed?
Where you want to wait for a reaction
async def reaction_test(ctx):
await ctx.send(f"**{ctx.author}**, please react with :white_check_mark: or :x: on this message in 60 seconds")
def check(r: discord.Reaction, u: Union[discord.Member, discord.User]):
return u.id == ctx.author.id and r.message.channel.id == ctx.channel.id and \
str(r.emoji) in ["\U00002705", "\U0000274c"]
try:
reaction, user = await client.wait_for(event = 'reaction_add', check = check, timeout = 60.0)
except asyncio.TimeoutError:
await ctx.send(f"**{ctx.author}**, you didnt react with a ✅ or ❌ in 60 seconds.")
return
else:
if str(reaction.emoji) == "\U00002705":
return await ctx.send(f"{ctx.author} reacted with a ✅")
``` Will this work?
Run the code.
Well before this is this how it can work when a member doesnt react to the emoji in a certain time frame? if "VALORANT" in message.content: await message.author.kick(reason = "He said the word")
Dont know much about union but try lowercase
Nope same?
Dont really know
About Type hinting something with 2 types or objs in this case
Aka union
What?
Union is used to type hint 2 types am i correct?
How exactly?
What u mean by this
the command doesnt work
I think its Union[type,type]
ohh right yeah and?
Then why question?
how to get a list of all commands of my bot but not as object. I want it to be a list like this ['>ping', '>avatar'] with prefix.
you would have to loop thru bot.commands which returns all command objects , and use .name attribute to get the command names
or you can write it yourself
eh, not recommended though since there's already a better way to do it
^^ just list comp bot.commands
Sorta. Its basically telling your IDE "this value can be this type or this type".
Ik it was a jk lol
Yeah ik
with prefix?
what if the bot has like 500 commands
All nighter time
embed.add_field(inline = False, name="guild name:", value=member.display_name)```
how do i make the id and display name embedded with this code, to make them look like the times?
import discord
from discord.ext import commands
Token = "The Token"
client = commands.Bot(command_prefix=".", owner_id=521325126722125874)
client.run(Token)
print("Launch successful")
doesn't print Launch successful even when bot goes online
Cz no code after client.run works
Really what ever you want
you can simply use .join to join the prefix
that's the neat part, i dont know what im supposed to do!
Put it before client.run
await get_prefix(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the prefix the bot is listening to with the message as a context.
Its usually popular to say: {Bots Name} is online. I've also seen some creative ones like the uptime of the bot, and some statistics since its been last shut off/restarted
how to do that 
Which one?
I haven't worked with discord.py for a while but
const Discord = require('discord.js');
const client = new Discord.client();
client.once('ready', () => {
console.log('Twinnem is online!');
}
client.login('token');
what did i do wrong
Wrong server
@tasks.loop(seconds=5)
async def dispatch_webhooks(self):
await self.bot.wait_until_ready()
if self.logging_batch:
for webhook, embeds in self.logging_batch.items():
if embeds:
to_send = embeds[:10]
print(to_send)
webhook_to_send = discord.Webhook.from_url(webhook, session=self.bot.session, bot_token=self.bot.http.token)
await webhook_to_send.send(embeds=to_send, username=f"LogRack Logging", avatar_url=self.bot.user.avatar.url)
self.logging_batch[webhook] = embeds[10:]
i have this task, this should send 2 embeds but it only sending 1 embed any reason for that? it prints [<discord.embeds.Embed object at 0x05ECF340>, <discord.embeds.Embed object at 0x05ECF148>] and send only the second 1
yes thats what i'm doing
Looks fine to me at a glance. If possible, use a debugger to set breakpoints and inspect what the actual API request is.
actually i dont know how to use debugger, if you can help me
Are you using an IDE
vsc
Still it's not working?
nah
Oops
This explains the basics https://code.visualstudio.com/Docs/editor/debugging. You'll want to set a breakpoint on the webhook send() line. Then use the step into button until you reach discord.py's internals and can see the HTTP request it built. You can see the value of local variables in the side bar on the left.
Not sure if that is a sufficient explanation but if you're willing to try go for it and I'll try to help more if I can.
C:\Users\ADMIN\PycharmProjects\Fluxo>python main.py
Launch Successful!
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\ADMIN\PycharmProjects\Fluxo\main.py", line 11, in on_ready
await self.client.change_presence(activity=Activity(name=f"branch {version}", type=2))
NameError: name 'self' is not defined
I know i'm supposed to define self but how do i do that? im new to discord.py
Remove self
you type it as the first argument of the function
or method
also is that a cog
ugh
show code
C:\Users\ADMIN\PycharmProjects\Fluxo>python main.py
Launch Successful!
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\ADMIN\PycharmProjects\Fluxo\main.py", line 11, in on_ready
await client.change_presence(activity=Activity(name=f"branch {version}", type=2))
NameError: name 'Activity' is not defined
do i also remove activity
nop im trying to squish the code into main.py cause i dont think im ready to learn cogs
looks like youre doing completely wrong stuff in it
import discord
from discord.ext import commands
from discord import Activity
Token = ""
client = commands.Bot(command_prefix=".", owner_id=521325126722125874)
@client.event
async def on_ready():
print("Launch Successful!")
await client.change_presence(activity=Activity(name=f"branch {version}", type=2))
client.run(Token)
dont name Bot instance as client its not what python devs do, dont do stuff on on_ready event, it is not the right thing to change presence
!d discord.ext.commands.Bot.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
The activity being used upon logging in.
They dont?🕴️
put it their
?
Python devs dont name bot instance client🕴️
you may want to read the message again ig
Why do python devs call the bot instance bot🕴️
And not client🕴️
Im joking lmfao😭
the thing is that, there is another thing called discord.Client and when you would ask for help, we would expect that you named that thing as client not Bot
Are you telling that to me🕴️
both of you

so the instance needs to be called something like that as well
alright i get it
looks like i ruined the joke
I was joking🚶
Yes you did🚶 🕴️
😪
C:\Users\ADMIN\PycharmProjects\Fluxo>python main.py
Traceback (most recent call last):
File "C:\Users\ADMIN\PycharmProjects\Fluxo\main.py", line 13, in <module>
property_activity: Optional[Union[
NameError: name 'Optional' is not defined
C:\Users\ADMIN\PycharmProjects\Fluxo>
now?
what do i do?
the reason is that you didnt import it
i probably should change my laptop username from ADMIN to something else cause if i join a hacked wifi it'll be easy as fuck to guess
Thx for the password🕴️
@sullen shoal
C:\Users\ADMIN\PycharmProjects\Fluxo>python main.py
Traceback (most recent call last):
File "C:\Users\ADMIN\PycharmProjects\Fluxo\main.py", line 13, in <module>
property_activity: Optional[Union[
NameError: name 'Optional' is not defined
C:\Users\ADMIN\PycharmProjects\Fluxo>
Keep stepping into the code (F11) until you reach the point where it's created the HTTP request payload
No🕴️
from typing import Optional, Union
Then inspect that payload to see if it has both embeds in it
What exactly are you trying do?
debug the code
where can i see that?
prob gonna change it to "Federal Bureau Of Investigations"
Do you want to get in voice chat here and screen share? Then I could guide you through it easier.
in 5-7min?
ok
and what do you get as a result?
import discord
from discord.ext import commands
from discord import Activity
from typing import Optional, Union
Token = ""
client = commands.Bot(command_prefix=".", owner_id=521325126722125874)
@client.event
async def on_ready():
print("Launch Successful!")
property_activity: Optional[Union[
discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]
client.run(Token)
doesn't have activity
what are you even trying to do?
have a discord actvity
something like
"Listening to Lofi"
i linked the docs to Bot.activity and he straight up copy pasted the docs
!d discord.ext.commands.Bot.change_presence , or activity kwarg in commands.Bot
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
how does one fix this
show code
just trying to run my bot
from discord.ext import commands
client = commands.Bot(command_prefix = '$')
@client.event
async def on_ready():
print('bot is online')
client.run('token')```
no token
is that all? i dont see e/Desktop/vsc test/bot.py" there

ik that bruh
thats literally it
no liek
how do you run it?
thats the error that comes up
not my repo but i helped him with it some time ago,
https://github.com/CristianEduardMihai/dpy-music-bot/blob/main/bot.py#L22-L29
bot.py lines 22 to 29
bot = commands.Bot(
command_prefix=bot_prefix,
case_insensitive=True,
activity=discord.Activity(
type=discord.ActivityType.watching,
name=f"{bot_prefix}help"
)
)```
just to clarify for discord.Game("") im supposed to add a api right?
press dis butin heer
tbh that thing is slow asf, should run it from the terminal
yea
*for free
self host is the best option for free
takes not more than 3 secs for me O.o
how can i do that
running it from the terminal takes 1
run it 24/7
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 60003): Two factor is required for this operation
Im trying to create channel, but i get this error
wdym like keep vsc open 24/7
how to solve?
ya basically
bruh
get a aws ec2 instance, costs $1/month if u run 24/7
any help with my issue please?
Lets see the code
async def test(ctx):
await ctx.guild.create_text_channel('test-channel')```
Indentation is wrong but thats fine
i dont think a bot user should get that error
Can we see all of your code?
from discord.ext import commands
import discord
from discord import Embed
intents = discord.Intents(messages=True, guilds=True, members=True)
intents.reactions = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command(name="test")
async def test(ctx):
await ctx.guild.create_text_channel('test-channel')
bot.run('')```
server owners can enable some shit to allow only people with two factor authentication unlocked to do the moderation stuff
but that doesnt apply to a bot iirc
Can you even enable 2 factor authentication for a bot?
I would be inclined to agree




