#discord-bots
1 messages Β· Page 468 of 1
just text to speech
@drifting arrow who says it's against ToS?
yeah in this one its just tts
Why lol
Then I appologize @white perch. I was mistaken.
I said I donβt know but google will lmao
No prob
Music Bots are, but not tts
Even music is allowed, as long as you don't use YouTube
Im gonna go take a shower and when I return I'll educate myself better.
There's a reason they come here to get help...
But anyone have a solution to the issue? #discord-bots message
Haha its all cool. What matters is u understood
You can download a music a play it in a loop if you want, you don't rely and stream directly from YouTube so yeah
Yea
Also, music bots are not against TOS!!! Rythm is literally a VERIFIED BOT
Rythm is being shut down
Rythm is shutting down anyways we shouldnt discuess that here
Yea
In case you didn't know
Oh lmao I didnβt even know my fault
Why tf is it verified then thatβs dumb lmaooo
Isn't that what I said....?
Discord never forced any bot to shut down
!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)
its against tos
lol
Music bots are allowed if you have a legal written permission from youtube which is a 0.01% chance of anyone having written permission though
But anyway
Just buy YouTube and you'll be fine
What do you expect, what happened, etc.
No error, It joins the vc, sends the making audio message, it also saves the audio file but doesn't play it in vc and doesn't send the Played! text
LOL π
guys, what python version does supports:
except A, B:
Just break many laws and download the video. Upload to your own private server. and reference that video.
TADA! Break all the laws at once.
asked in #python-discussion but not answered 
Back to my shower
isnt that supported?
3.8 nah
Is this an effective way to get a list for the names of all the roles in my server:
wut
[i.name for i in cl.guild.roles]
Just put it in () and magic happens
Like you only get lyrics from the api of the song you want
Again
Everything is based on the ToS of the service
We don't know what service you use, we don't know if it's allowed or not
Read their ToS
Just give me 2.5 billion bucks and I'mma buy it
No, just asking in general, Ksoft shut down for legal reasons (the api rythm used before)
kinda cool tbh, thanks
So i was just confused
@color.error ig
Very cheap. /s
oo wrong parentheses sorry
Ikrrrr
That's why. Gimme 2.5 billion USD and I'mma revive every music bot :D
For fucks sake, finally figured out this stupid API
Which one?
Ok?
It's literally just a self-role command
π
been working on this way too long
It's been taking me forever to figure python out ya know
Understandable
nah
Oh. Forgot to remove the decimal 

its 2020 anyways
My IDE kinda lookin like a fine plate of spaghetti rn. Seasoned with just the right amount of bullshittery
I love Python man, It's so fun
I love Python too.
Can my command errors be in a separate file than the command?
sure
Yes. Just make the error handler in another file.
o ok
!d discord.Embed
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
how can I get message by id?
TextChannel.fetch_message
Time to attempt to add an api to my bot \o/
!voiceverify
java looks cooler, imo 
python java is cooler
Wot
can anyone help me with wavelink??
isnt it used to download yt vids?
i wasnt talking about that
Neato. League of legends has an api πΌ
..... :C
This is against youtubes TOS and can get you banned from youtube or worse. Sued! DUN DUUN DUUUUUNN!!
is it possible to get the message that a message replies to?
how can i host my bot for free
Run it on your own pc.
any other ways
https://somehost.xyz is a good free hosting imo.
Free and paid hosting
this free
Paid and paid hosting.
mm
'Paid and paid' π
Yes, it's free. Lmao.
hm
But I chose the paid plan because it's really good.
KeyError: Python
!d discord.Embed
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
@bot.command()
async def help(ctx):
embed = discord.Embed(
title = 'JarvisBOT Help',
description =
'Prefix is $',
color = 0x8b0000)
await ctx.send(embed=embed)
is this channel still used for discord.pyPyc-cord
Nah, I'm missing only life.
pycord related stuff can go in their server
Whats kwargs
keyword arguments
Keyword arguments.
btw @heavy radish
Yes
i think the color code is wrong
Yea, Its a copy paste
-_-
ok
any other methods
this have no reply
Outside of paying or finding a free VPS, there's just hosting it yourself.
What do you mean "no reply"?
Eyes are a blessing, aren't they?
At the end of the day, you get what you pay for. If you choose to go the free route, you may not get the greatest service.
Alternatively, you'll have to host the bot yourself (simply run it on your computer or some other device.)
If you do decide to pay out 5 bucks a month, there's some decent options available.
I paid only $3 to this host and it isn't even monthly, it's once a lifetime.
For me right now, I am contemplating getting a go-daddy VPS. since I already have my website hosted through them.

rito games made me read all their TOS for using their api only for it to essentially say 'Be good. dont break shit you lil' shit.'
did i can host on heroqu
but
What vps are you using?
the youtube videos on it have
No VPS, I'm using that hosting I sent.
youtube is a lie and merely a reference at best. like stackoverflow.
If I will buy a VPS I would go with https://nextarray.com
How to host your discord bot for free using heroku. This tutorial shows you how to host your python bot for free using heroku services. We simply need to setup a few things to heroku, upload our code and turn the bot on!
Text-Based Tutorial: http://techwithtim.net/tutorials/discord-py/hosting-a-discord-bot-for-free
Heroku: https://heroku.com
...
Again, it's not recommended
mm
Why do you ask us if you're so sure you want to host it there when we say it's not a good plat
@novel rampart Just because he uses it, doesn't mean you should. Not every hosting service is ideal for your needs. For example, some hosting services require you to use UBUNTU or LINUX. I dont have those, and therefore i cant use them. despite wanting to coz of their prices.
You ask us if Heroku is a good solution, no it's not.
Now choose whatever you want to do.
mm
You should not use Heroku to host your bot.
-
Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.
-
Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.
-
Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.
-
Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)
-
Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
then how will i host my discord.py
Enjoy the reasons on why not to use Heroku
for free
i want to make a command run like this
!download AWebsite
so i can automate it by using discord
Free and paid hosting
You don't host discord.py, you host a bot and you already got told above..
how will i host using this
Read what the bot sent once you joined.
@novel rampart
@novel rampart just listen to these smart people and they'll do you aight. i been here for like 2 weeks now and they dont lead a man astray
i read but i don't understand anything on that
Then ask there
mm
Then ask in their support channel.
Not here
ok
how
buy it?
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany
https://www.time4vps.eu/ Lithuania.
Self-hosting: Free hosting: Kinda free:
Any computer. No. Not even heroku. GCP, AWS have one year free micros.
*from dpy server
remove embeds
web server != discord bot
why wont the embeds get removed?
nono I was removing it so editing it again and again got back the embeds
any mistake?
Is there even any by the name of vsc?
VSC = Visual Studio Code.
@client.command()
I know that lol
oh ok
But they are taking about hosting service
Take code -> open in vsc -> click run
still not working
That's just running the code, not really hosting it
not even any error
can you send the actual code and not a picture so I can copy and paste
π
ok
try. it. and. see
no not working
indents
You dont want to use a Virtual Private Server (VPS) which is either free or hosted, which many have offered, so run it your damn self.
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Do you have any error handlers
y u making a variable for the avatar if u didnt use it?
And you wrote
{member}
i made it and i forgot about it lol
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
Which will send the whole member object
do str(member)
If you want the name / tag
@ocean leaf remove the variable
i already did
also why make on_message events for commands?
f'Avatar of member {member}`
Will send the whole member object
@ocean leaf
!d discord.ext.commands.Bot.command
command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
It won't
i typed it out myself. ty for not posting code @ocean leaf =.=
It will send the username#tag
yes
It would?
Wouldn't
no it would just send the member's name
No
ctx.author would send the whole member object
Username#tag
Username#tag
It's already in a string
ctx.author doesn't return a string
It returns the discord.Member object
It returns a member object
it returns object right?
Yes
Or discord.User if the command is invoked in DMs
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this contextβs command. Shorthand for Message.author
now?
I like to run the code to test it
If u put it inside an f-string it does
It returns a Member object not a string
!d discord.Message.author this also works (:
putting an object inside f-string will call object.__str__
^
Yes
Oh yeah
So u can also do str(ctx.author)
it would call the str dunder method
ok
Yes it would
@ocean leaf
@bot.command()
async def avatar(ctx, *, member: discord.Member):
userAvatar = member.avatar_url
embed = discord.Embed(color = member.color, timestamp = ctx.message.created_at)
embed.set_author(name = f'Avatar of {member}')
embed.set_image(url = userAvatar)
embed.set_footer(text = f'REquested by {ctx.author}', icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
this works for me
lemme try now\
lemme try
Change @raven peak to @client.command()
yes ik
Lol
cool
StIlL DiDnT WoWk
What
empty
Wdym empty
to get the user avatar
Your bot is online. run the command on discord.
i did
dosen't work nothing happens
Do u have an on_message event
just out of curiosity.. do you have
from discord.ext import commands
```?
Are you running the correct bot token?
yes
This too
his fault.
just remove the on_message thing
U can use ``
yup

do you have any bare on_message event
yes i do
Show it
Do u have process_commands at the end of it
Or better
!d discord.ext.commands.Bot.process_commands
Yup
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageβs author is a bot and doesnβt call [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Add that at the bottom of your on_message

Or better, use .listen()
^
@client.listen()
You don't need to call process_commands
!d discord.ext.commands.Bot.listen
listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
ok
Hmm
with what i have to use .listen? client.listen?
under all on_message commands?
How many do you have
4
And yes, if you have multiple on_message events then use .listen()
bellow all?
It's a decorator
So
@client.listen()
async def on_message(message):
...
Like this
It's an external event listener, so you have multiple event listeners of same type, it would work asynchronously and will.not block other events and commands
With the brackets BRUH, read the docs
ok
just curious ik that we have to use brackets
i tried editing a embedded message but it gave this errror.. i tried same type of file but it sends the file at first but when editing it gives this error
Okay
anyone pls help me i have a variable and i want that its value should me different for all servers
how i can do that
Code?
Have a dictionary and have the guild id as a key
..
really?
data = dict()
data[guild_id] = ...```
What version of discord.py are you using?
wait
i tried editing a embedded message but it gave this errror.. i tried same type of file but it sends the file at first but when editing it gives this error
..
how can i check?
Use member.avatar.url
avatar_url
.
discord.__version__
i learnt python properly also i know oop but i am confused in discord.py
Not in d.py 2.0
Oh.
how to check

ok
..help
avatar.url in dpy 2.0
Code?
@ocean leaf do pip install Discord.py -U
use member.avatar.url or author.avatar.url
embed = discord.Embed(title=f"{str(ctx.author)}'s new cards", description=f'You have successfully created a profile, **{name[0:-5]}**\nYou got a {card1} of {choose} and {card2} of {choose2}')
embed.set_image(url=f'attachment://{card_name1}.png')
file = discord.File(f'C:/Users/ogtla/OneDrive/Desktop/python/cogs/{card_name1}.png')
message = await ctx.send(embed=embed, file=file)
await message.add_reaction(':rewind:')
await message.add_reaction(':fast_forward:')
def check(reaction, user):
return reaction.emoji == ':fast_forward:' or reaction.emoji == ':rewind:' and user == ctx.author
react = await self.bot.wait_for('reaction_add', check=check)
embed2 = discord.Embed(title=f"{str(ctx.author)}'s new cards", description=f'You have successfully created a profile, **{name[0:-5]}**\nYou got a {card1} of {choose} and {card2} of {choose2}')
embed2.set_image(url=f'attachment://{card_name1}.png')
file2 = discord.File(f'C:/Users/ogtla/OneDrive/Desktop/python/cogs/{card_name1}.png')
await message.edit(embed=embed2, file=file2)
member.avatar.url
are you using commands.client or commands.bot? idk if it makes a difference but I am using commands.bot
..
Yes
ok
anyone pls help me i have a variable and i want that its value should me different for all servers
how i can do that i learnt python properly also oop but i am confused in discord.py
avatar can be None if they have the default one
rtfm for breaking changes
use display_avatar instead
You need to pass in a file like object into discord.File
display_avatar? hmm)
Sed
the bot doesnβt have 2.0 docs
how i can use it ?
to make different values?
use a dictionary and have the guild id as a key
like i have a variable giveawayStatus
if someone start giveaway
its value changes to true
but in other servers also
π¦
bruh, i literally said what to do
dont use a dict, use a database instead
json isnt a db
yes
And add a column which will contain the guild id
a json file can pretend to be a database tho π
no it cant
Lol
If you use json as a db, you would deal with more issues that good
its mostly used to send data throughout the web
If you're willing to put the work in, you can use a json file as a database. wont be very good but it will work
how to create and use a db?
@steep estuary visit #databases
Traceback (most recent call last):
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "d:\Coding\Python\Discord.py\Economy Bot\economy.py", line 70, in on_command_error
raise error
TypeError: exceptions must derive from BaseException
when i run any command it shows this error, which is triggered by the error handler
send your code
youβre probably overriding error somewhere
I prefer to have the code, run it. Fiddle with it and if I can get it to work, send the revised code.
here it checks the value (pls ignore the variable names)
you should definitely use a database
what
Can you please copy and paste the whole code and not images? lol preferably just the entire function.
thatβs not a database
@client.event
async def on_command_error(error, ctx):
if isinstance(error, commands.CommandOnCooldown):
cooldown_emb = discord.Embed(title="Hey, you are on a cooldown", description='Please try again in {:.2f}'.format(error.retry_after))
cooldown_emb.set_author(name=ctx.author.name, icon_url=f'{ctx.author.avatar_url}')
await ctx.send(embed=cooldown_emb)
elif isinstance(error, commands.CommandNotFound):
pass
else:
raise error
here
k π
ctx comes first then error
oh ok
!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.pydis.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.
@shy schooner Always remember:
if it's a top level function (not a cog or in class), ctx is always first.
If it's a lower level function (in a cog or in a class), self then ctx
what is "share my whole class"
π
yes
i know how to use class
btut in discord.py
you clearly donβt
i have no idea
no
itβs still python
:/
what
@steep estuary you arent referencing your functions in your class to be 'self'
async def gstart(ctx ...)
could be
async def gstart(self, ctx ...)
there were some errors and problems so i did so many changes
than it worked
it is giving some problems
with self
because you arenβt inheriting from Cog
please lear how to use classes and cogs
learn*
cog is only in discord.py not in python?
i sent code.. :/
cogs are classes
I can send you my example cog code if you want @steep estuary
k pls
!d discord.ext.commands.Cog
class discord.ext.commands.Cog```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
i watched some tutorials of python oop atleast 3-4 tutorials
they didn't explained that
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
..
gives error when i edit embedded message :/
Classes aren't specific to discord.py
:(
:/
so i deployed my bot to heroku, and when i run it, it doesnt come online. i have no errors in my code, and it runs fine when executed in the IDE. how do i fix this?
by not using heroku
bruh
free
and also we are not heroku support
can you recommend any other free hosting service?
and you can use str.join instead of ```py
listtostr = list(Participants.keys())
members = str(listtostr)
members = members.replace("'","")
members = members.replace("[","")
members = members.replace("]","")```
:(
?
i think i should delete the class and code it again
why sad face
how do i set a custom attribute to the Context class when a command is called? im trying to make a queue for my soundboard
how do i send a message in a channel by just knowing the channel id?
pls bal
client.fetch_channel
dank memer is not in here
what bots are here?
none this server and this channel is about help with discord bot coding
thx @slate swan
yes
how do i make command from different files?
like
1st file is for making bot online and listening to 2nd file
if the bots rise against us, you'll be the first to go
Cogs?
ya how do i make that
i see some people use it for multi process(?)
This is the main loader/unloader for cogs in the main script.```py
#Loads the cogs
@bot.command()
@commands.is_owner()
async def load(ctx, extension):
bot.load_extension(f'cogs.{extension}')
@bot.command()
@commands.is_owner()
async def unload(ctx, extension):
bot.unload_extension(f'cogs.{extension}')
@bot.command()
@commands.is_owner()
async def reload(ctx, extension):
extension = extension.lower()
bot.unload_extension(f'cogs.{extension}')
time.sleep(1)
bot.load_extension(f'cogs.{extension}')
actx.send(f'Reloaded {extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
Your cog.
```py
class MyExample(commands.Cog):
stuff for a class here.
def setup(client):
client.add_cog(MyExample(client))
The first block of code is your main discord bot code.
The first 3 functions allow you to manually load, reload, and unload a cog.
The loop is to essentially auto load them so you dont have to.
The second block of code is your cog. A class of commands specific to that cog. You're grouping commands so you dont have a big ol' mess.
You turn this:
into this:
thankyouu
No worries. Hopefully this helps
OH RIGHT this reminds me. need to educate myself on TTS
message = await ctx.send(file=discord.File(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\king_of_diamonds.png'))
await message.add_reaction('π€')
def check(reaction, user):
return reaction.emoji == "π€", user == ctx.author
msg = await bot.wait_for('reaction_add', check=check)
embed2= discord.Embed(title='bye')
await message.edit(file=discord.File(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\red_joker.png'))
why it gives this error :/
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type File is not JSON serializable
text to speech?
Yeah. I promised someone I would coz I made a mistake.
..
you need to pass in a file like object into discord.File
not a string
but it works at first when sending message but doesnt work while editing
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
try discord.File(open(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\red_joker.png'))
Poor @small crown
Lol that ninja edit
code mostly works until this line:
await message.edit(file=discord.File(r'C:/Users/[My Name]/Desktop/example2.png'))
``` π¦
Nobody saw my original message π
ye.
hey so basically i want my bot to be able to edit the messages that he posted
so for example, if my bot said something like "ello wassup", i want him to be able to edit it to say something like "hello wassup"
HelloHi,
how to ignore " when typing a command where " might include`?
discord.ext.commands.errors.UnexpectedQuoteError: Unexpected quote mark, '"', in non-quoted string
!d discord.Message.edit
await edit(**fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
\"?
oh ok thnx
What do you mean? Can you give me an example?
message = await ctx.send("ello wassup")
await message.edit(content="hello wassup")
wait so how does it work
ohhhhhhhhhh
ok thnx
The message sent returns a discord.Message object.
Can we load/unload cogs for specific guilds?
I don't think so.
:/
What do you mean?
cause in my bot, i dont know what the message is gonna be until runtime, sooooooooooooo the edit thingy wont really work
ok so basically im making it so that if i say a command
the bot prints out the words after the command
WHAT TO DO FOR IT TO WORK..
str.replace()
so if the command is "imitate", if i type "imitate hello", it shuld print out "hello"
!e
text = "hello scoopy"
text = text.replace("scoopy", "")
print(text)
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
hello
:/ what to do
@cyan bay
ohhh, ty
You're trying to delete the image and put a new one in its place right? i dont think u can.
yea
um..
hi
Unless π€
unless???
Hold up. my internet decided to say no to me.
..
how do i print the reaction user has reacted
I'll do a thing and get back to you.
aightt
@bot.event
async def on_message(message: discord.Message):
if message.guild is None and not message.author.bot:
print(message.content)
print(message.author)
embed = discord.Embed(title="Confirm Mail creation",description="This system is used for reporting bugs,reports concerning to the moderators.",color=0x3DFD1E)
a=await message.author.send(embed=embed)
await a.add_reaction('\u2705')
await a.add_reaction('\U0001f6ab')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == ['\u2705','\U0001f6ab']```
yo it worked tysm
No problem. 
how do i print the reaction user has reacted?
The reaction emoji. May be a custom emoji, or a unicode emoji.
can we edit a sent image?..
so don't need check?
heh?
i mean
will reaction.emoji be enough
def check(reaction, user):
return user == message.author and str(reaction.emoji) == ['\u2705','\U0001f6ab']```
or also must use check
@dapper cobalt
Are there any examples of tempmute commands?
Unable to convert 'temmute' to valid command, tag, or Cog.
!src mute
Temporarily mute a user for the given reason and duration.

@frosty prairie i give up. π¦ i cant figure it out
I have fail D:
I shall go and repent while listening to Taylor Swift
so we cant edit a image..?
You can probs edit the embed instead
is what I was trying to do
but i havent got the brainstems to figure out how.
Where is reaction defined?
i edited the embed too.. :/
message = await ctx.send('hi')
fetch = await message.channel.fetch_message(message.id)
print(fetch.reactions)
idk what your purpose is. But new idea:
delete old message. Send new message. victory! ;D
yea thought bout that.. my purpose is like uk u have bunch of characters and they type maybe, !character and there is button to show next character ..
hello
I am making help command in cogs
There are no error popping in the console but the bot isnt responding to the fl.help <command> type commands
..
hello
I am making help command in cogs
There are no error popping in the console but the bot isnt responding to the fl.help <command> type commands
This is my code for the one the fl.help <command> type command
#Help mute command
@help.command()
async def mute(self, ctx):
em10 = discord.Embed(title="Mute π", description="A mute command through which the admin,mods of the the server can mute the server members\n**NOTE**:- This command requires you to have a admin or mod role to use it")
em10.add_field(name="**Syntax**", value="`fl.mute <mention>`")
await ctx.send(embed=em10)
ig it has smth to do with "@help" .. idk
nvm i found it
ight
@sick talon Don't do it like that, read this guide https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
alright thank you
fix the indentation probably
and str(reaction.emoji) == ['\u2705','\U0001f6ab'] is wrong
to check if a string is in a list, you use the in keyword
str(reaction.emoji) in ['\u2705','\U0001f6ab']
ok thanks
wait
you haven't add the await bot.wait_for()
hmm
this is a sample for it
id_correct = user.id == turn.id
emoji_correct = str(reaction.emoji) in (nagant_str, "β")
reaction_correct = reaction.message.id == react_message.id
reaction, user = await client.wait_for("reaction_add", check=lambda reaction, user: id_correct and emoji_correct and reaction_correct)), timeout=150.0)```
hm
i also have to do this
yes
if not the bot won't actually wait for a reaction to be added
hmm ok
not like that
the bot alrdy has the reactions added
i want to print the reaction the user reacted on
yeah... you need await client.wait_for for that
client.wait_for is to "read" what the user reacts
how to make command.has_roles work for more than one role
add_reaction is to add the reaction
!d discord.ext.commands.has_any_role
discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
thanks
How do i fetch a users' avatar?
Like I want the link to be https://cdn.discordapp.com/avatars/656073353215344650/c82b734a7e7c1eb6bea0086e6400d344.png?size=128 and not https://cdn.discordapp.com/avatars/656073353215344650/c82b734a7e7c1eb6bea0086e6400d344.webp?size=1024
how i can purge messages for only specified user?
hmmm
add a check
no the 1st one is png and the 2nd one is webp
wdym?
a check
k
:/
Just search the manual for it lol
Please tell me how to put slash command in a group like
Music
Slash command related to music
yes i'm using an api and it doesn't work with .webp only .png
i want to purge messages of a particular specified user :/
add a check
!d discord.TextChannel.purge
await purge(*, limit=100, check=None, 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/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting botβs messages
check = ctx.auhor for ex?
I have a problem, basically my slash command works well but every time i use it the bot sends an error message that only the author can see. It's just a message but is there any way to fix that
hey there i want to make a bot which will react on every message on the server
how do i?
rate limit go brrrr
ahhhhhhhh thats a slow messaging server
people read messages after half an hour
how
api abuse
he isnt spamming or pinging
he?
hey there i want to make a bot which will react on every message on the server
thats api abooz
thats a dead server so i want to tell people to stay online after they send message
Please tell me how to put slash command in a group like
Music
Slash command related to music
theres a reason why you can only change ur pfp twice per hour
it wont even hit 2 requests π
there is some on reaction thing, just find it yourself in docs
???
adding a reaction adds one request right?
I think? Not sure
make a loop
while True:
print('hey yall stay alive')
other stuff
okay
how to use a check?
i only want it to be sent when someone comes online to send a message
wym
so is there any solution to my problem? slash command, everything works well but bot sends an error message that only author can see, I want to get rid of that somehow :o
whenever a person sends a message
what
ok how do we detect spam
@bitter depot mod
!warn 762007641455067169 You've been told that this is classed as API abuse and not something we can help with here, so please stop asking and trying to find ways to get around it.
:incoming_envelope: :ok_hand: applied warning to @surreal dust.
on message ig
man how do we detect spam means stop people by soft banning them
and you just
wut
warn me uselessly
hes doing his job as discord moderator π
!custom-cooldown You can use a custom cooldown for detecting spam, depending on your definition of spam @surreal dust
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
ohok thanks
anyone uses SNEKBOX?
wait a minute let me try
But you wouldn't want to be sending a message every time a message gets sent, because that's just going to get your bot banned for API abuse @surreal dust
ohok
If you're talking about https://github.com/python-discord/snekbox and you need help with it then you should ask in #dev-contrib
i want to add it to my personal bot
if ... you need help with it then you should ask in #dev-contrib
k ty
every time I execute a slash command it works but the bot says it failed. is it possible to fix that or disable these automatic error messages?
not rlly
How do I code the uptime??
How do i put an emoji like im making
emoji = 'emoji'
await message.add_reaction(emoji)
what will i put in emoji =
try on_command_error?
How do I convert png images on discord to webp?
do slash commands have on command errors?
i mean its a command none the less
make a variable thats set when the file is ran
can always check if it works
no its a slash command
How
datetime module
how do i make an if condition of
if message is in a certain channel
@spring flax sorry for the ping but u prolly know this so can u help me ._.
can you explain please
So like lets say
channel = general
so IF there is a message in the channel GENERAL then the bot will react with an emoji
i probably do not have time now, someone else would help i assume but if not will do once I have time
Al righty, thanks for checking on it though
!d discord.abc.Messageable.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destinationβs message history.
You must have `read_message_history` permissions to use this.
Examples
Usage...
uh if i got what you said correctly this might help
oh wait you can use the on_message event
yes what would be the if statement
just
if == message.in channel``` will this work?
if i make a channel = client.get_channel()
welp there's my question, how do i make if = message.in channel statement
what even is that
i want to add a reaction if a message is in a certain channel
So I got this code:
@bot.command()
async def build_deck(ctx):
category = get(ctx.guild.categories, name = "deckbuilder")
await ctx.guild.create_text_channel("CHANNEL_NAME", category=category)
How would I make it so that specific channel is only viewable by specific people? sorta like how the ticketsbot does it
Can discordpy create threads?
π€
2.0 yes
How do I check what discordpy im using? i assume i am using latest. but to confirm
And also how? xD
how what
if you're asking about how to install it
you first need to install git
and then pip install git+<github url>
or you could git clone the repo
cd into it and execute setup.py
No i meant, how do to discordthreads with discordpy
you need 2.0
Whats the github url for discordpy 2.0?
its the master branch
oh i probs have the latest version of discord.py then
since i started like a week ago.
I did pip install discord.py
and for creating a thread you need Message.create_thread or TextChannel.create_thread
as i said, its not on pypi
you can only install it through git
pip install discord.py this fetches it via pypi
aight
i got the new 2.0 one. is it the same imports? or how do I import it into my code?
its just a new version
you can use this to create threads
Why is this error coming? ```
@commands.Cog.listener()
async def on_ready(self):
global startTime
startTime = time.time()
#create a command in the cog
@commands.command(name='Uptime',aliases=['uptime','onlinetime'])
async def _uptime(self,ctx):
global startTime
# what this is doing is creating a variable called 'uptime' and assigning it
# a string value based off calling a time.time() snapshot now, and subtracting
# the global from earlier
uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
await ctx.send(embed=discord.Embed(title=f"Chad has been online for:",description=f"{uptime}:zo_tick_anim:",color=discord.Color.random()))
here is the docs for 2.0 https://discordpy.readthedocs.io/en/master/
shows starttime not defined
uhhhh then wht can i do?
futuredate = message.created_at + timedelta(seconds = timeremaining)
how can i convert futuredate in seconds?
futuredate.total_seconds()?
Don't use globals 
AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'
oh right
what do you want exactly
cuz there is datetime.seconds
are you trying to store it?
its timedelta.total_seconds iirc
yeah
!d datetime.timedelta.total_seconds
timedelta.total_seconds()```
Return the total number of seconds contained in the duration. Equivalent to `td / timedelta(seconds=1)`. For interval units other than seconds, use the division form directly (e.g. `td / timedelta(microseconds=1)`).
Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.
New in version 3.2.
See I told you
You can use relativedelta too
if they want to store it, they could store its timestamp
its pretty clear
your bot object doesnt have an attribute called launch
and that's probably copied code, so stop copying code
dude but then wht cld i do
learn how to use class attributes
instance attributes
x = datetime.datetime.utcnow() futuredate = message.created_at + timedelta(seconds = timeremaining)
i have these 2 objs, now i am trying to do is send a msg before 15 mins than futuretime
futuredate - timedelta(minutes=15)
gimme example?
!e ```py
import datetime as dt
class Foo:
def init(self):
self.time = dt.datetime.utcnow()
def foo(self):
print(self.time)
foo = Foo()
foo.foo()``` 
@lament mesa :white_check_mark: Your eval job has completed with return code 0.
2021-09-13 11:28:10.596614
class Foo:
x = 10 # class attribute
def __init__(self):
self.y = 20 # instance attribute
Foo.x
>>> 10
Foo.y # Not initialized
>>> AttributeError
Foo().y
>>> 20```
Hey guys, i'm trying to turn the binary from gateway.discord.gg to human readable format
I've tried a bunch of stuff, but have no idea how to do this
b'\xc2\x1b\x1a86\x83\x91\xd7\xe6\xa2\xee\xcc\xc1h\x911Zd\xd0\xad\xc8\x00\x00\x00\x00\xff\xff'
An example of binary received
# Z_SYNC_FLUSH suffix
ZLIB_SUFFIX = b'\x00\x00\xff\xff'
# initialize a buffer to store chunks
buffer = bytearray()
# create a zlib inflation context to run chunks through
inflator = zlib.decompressobj()
# ...
def on_websocket_message(msg):
# always push the message data to your cache
buffer.extend(msg)
# check if the last four bytes are equal to ZLIB_SUFFIX
if len(msg) < 4 or msg[-4:] != ZLIB_SUFFIX:
return
# if the message *does* end with ZLIB_SUFFIX,
# get the full message by decompressing the buffers
# NOTE: the message is utf-8 encoded.
msg = inflator.decompress(buffer)
buffer = bytearray()
# here you can treat `msg` as either JSON or ETF encoded,
# depending on your `encoding` param
an example from docs
you could look at the source of discord.py too
How would I use this? If you don't mind elaborating
I've read through those docs too, but I don't understand this
this is how dpy does it
if type(msg) is bytes:
self._buffer.extend(msg)
if len(msg) < 4 or msg[-4:] != b'\x00\x00\xff\xff':
return
msg = self._zlib.decompress(self._buffer)
msg = msg.decode('utf-8')
self._buffer = bytearray()
``` `self._zlib` is just an instance of `zlib.decompressobj()`
Thank you, i'm not using zlib compression for this, but when I try to decode to utf-8, doesn't work
and then you json.loads the msg
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: invalid continuation byte
Is the error i'm getting
you need to decompress the bytes
By this, I mean, my compress:false
using that method
i've compressed it now.
import zlib
ZLIB_SUFFIX = b'\x00\x00\xff\xff'
# initialize a buffer to store chunks
buffer = bytearray()
# create a zlib inflation context to run chunks through
inflator = zlib.decompressobj()
to_decode = b'\xc2\x1b\x1a86\x83\x91\xd7\xe6\xa2\xee\xcc\xc1h\x911Zd\xd0\xad\xc8\x00\x00\x00\x00\xff\xff'
buffer.extend(to_decode)
print(inflator.decompress(buffer))
The error:
Traceback (most recent call last):
File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 52, in <module>
asyncio.run(go())
File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 42, in go
print(inflator.decompress(buffer))
zlib.error: Error -3 while decompressing data: unknown compression method
if len(msg) < 4 or msg[-4:] != b'\x00\x00\xff\xff':
return
``` you need to check this too
oh wait, its correct
if messgae.channel.name == "general":
#code```
ahh i see thanks
diabolical stonks
they increased the msg delay on this channel ._.
if x >= earlyrem:
earlymsg = await message.reply(f"**The event will start in 15 minutes.**")
print("First reminder has been sent.")
earlymsgtime = message.created_at
if earlymsgtime >= x <= futuredate:
pass
if x >= futuredate: # timer for event reminder
await message.reply("**The event has started.**")```
it spams for `if x>= earlyrem` how can i make it send once and then wait for futuredate?
can you send your full code
I want to make a battle command
how to get the avatar url?
I know it's avatar_url
!d discord.Member.avatar_url
avatar_url```
Equivalent to [`User.avatar_url`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User.avatar_url "discord.User.avatar_url")
but it's not working
what is your code
error?
no
hey guys, so i want to have a timer in a discord channel, what would be the best way to go about doing that
it could be updating on a minute basis
@client.command()
async def battle(ctx, member: commands.MemberConverter):
yourAvatar = ctx.author.avatar_url
memberAvatar = member.avatar_url
await ctx.send(f"{yourAvatar} {memberAvatar}")```
lemme check
member : discord.Member``` you can typehint to that
thanks, that was the issue
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
use while True
while True:
is it possible to set 2 images in an embed?
i don't believe so
sad
what I want to do is make a battle command that shows the avatars of the 2 fighters
in 1 embed
maybe use author and footer?
it's ugly
Or PIL
tell more
To merge the two images
TELL HOW
!pypi Pillow
Ah yea pillow. My bad
Ah yea
do I keep it url or do I need to save it?
!d discord.Asset
class discord.Asset```
Represents a CDN asset on Discord...
U can save it with this
ok but
Save it into a BytesIO object
I'm asking if I must have files or I can use also urls to merge images
!d io.BytesIO
class io.BytesIO([initial_bytes])```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3.10/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3.10/library/io.html#io.IOBase.close "io.IOBase.close") method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3.10/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3.10/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3.10/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3.10/library/io.html#io.IOBase "io.IOBase"):

https://paste.pythondiscord.com/dayirufuzo.py
If a User is banned, the Bot doesn't add 1 to the failed variable
how do I check the content of the message next the bot? example:
user: >battle another user
bot: another user do you accept?
another user: yes
bot: battle started
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/stable/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
import asyncio
import base64
import secrets
from json import load
import aiohttp
ws_key = base64.b64encode(secrets.token_bytes(16)).decode('utf-8')
headers = {
'Pragma': 'no-cache',
'Origin': 'https://discord.com',
'Accept-Language': 'en-US,en;q=0.9,es;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Sec-WebSocket-Key': ws_key,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/93.0.4577.63 Safari/537.36',
'Upgrade': 'websocket',
'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
'Cache-Control': 'no-cache',
'Connection': 'Upgrade',
'Sec-WebSocket-Version': '13',
}
async def go():
from main import buffer, inflator
session, ws = None, None
try:
with open('first_message.json') as file:
to = load(file)
session = aiohttp.ClientSession()
ws = await session.ws_connect(url='wss://gateway.discord.gg/'
'?encoding=json&v=9&compress=zlib-stream',
headers=headers)
msg = await ws.receive()
print(msg.data)
await ws.send_json(to)
async for msg in ws:
print(msg)
buffer.extend(msg.data)
print(inflator.decompress(buffer))
finally:
if ws:
await ws.close()
if session:
await session.close()
if __name__ == "__main__":
asyncio.run(go())
first message is just the hello, nothing weird there
import zlib
ZLIB_SUFFIX = b'\x00\x00\xff\xff'
# initialize a buffer to store chunks
buffer = bytearray()
# create a zlib inflation context to run chunks through
inflator = zlib.decompressobj()
This is what gets imported
must it be an event?
or can I put it into a command
you can
@client.command()
async def battle(ctx, member: commands.MemberConverter):
await ctx.send(f"<@!{ctx.author.id}> wants to battle. <@!{member.id}> do you accept?")
await client.wait_for("message", check="yes")
await ctx.send("Test")```
like this?
no
hmm
the check need to be a callable
no, it can also be a lambda
or a object which has __call__
I'm a noob, so can you send the code if message = .delete [channelname]
so i previously had written some code to send a post from a subreddit, but users complained that it was too slow, and its cuz praw isnt made for an async environment, so i decided to move to asyncpraw. i changed the stuff that was mentioned in the docs, but i get this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'ListingGenerator' object is not iterable
My code:
subreddit = await reddit.subreddit("memes")
all_subs = []
hot = subreddit.hot(limit = 50)
for submission in hot:
all_subs.append(submission)
random_sub = await random.choice(all_subs)
name = random_sub.title
url = random_sub.url
embed = discord.Embed(title = name)
embed.set_image(url = url)
await ctx.send(embed=embed)```
the for loop is causing the error
random.choice isnt coro
and i think subreddit.hot needs to be awaited
and you need to have an async for loop
ah i think thats causing the error. i'll change it and let you know
@lament mesa discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object ListingGenerator can't be used in 'await' expression
my code:
subreddit = await reddit.subreddit("memes")
all_subs = []
hot = await subreddit.hot(limit = 50)
async for submission in hot:
all_subs.append(submission)
random_sub = await random.choice(all_subs)
name = random_sub.title
url = random_sub.url
embed = discord.Embed(title = name)
embed.set_image(url = url)
await ctx.send(embed=embed)```
dont await subreddit.hot and try
hmm ok
so that fixed the listing generator error, but now i get this:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object Submission can't be used in 'await' expression
@lament mesa
Send your code 
subreddit = await reddit.subreddit("memes")
all_subs = []
hot = subreddit.hot(limit = 50)
async for submission in hot:
all_subs.append(submission)
random_sub = await random.choice(all_subs)
name = random_sub.title
url = random_sub.url
embed = discord.Embed(title = name)
embed.set_image(url = url)
await ctx.send(embed=embed)```
what line is the error on?
and random.choice is not coro 
uhh yeah its in that line
dont await random.choice 
ty! its fixed now
π
guys, i cant seem to find DiscordUtils' docs. Anyone can help?
def get_prefix(client, message):
conn = sqlite3.connect("prefix.db")
c = conn.cursor()
with conn:
c.execute("""SELECT * FROM prefix_data WHERE guild_id = :id""", {"id" : message.guild.id})
data = c.fetchone()
return data[1]
client = commands.Bot(command_prefix=get_prefix, intents = discord.Intents.all())```
my error:
```py
File "main.py", line 17, in get_prefix
c.execute("""SELECT * FROM prefix_data WHERE guild_id = :id""", {"id" : message.guild.id})
AttributeError: 'NoneType' object has no attribute 'id'```
The message was sent in dm
and there is another error i get if i type in the server
File "main.py", line 19, in get_prefix return data[1] TypeError: 'NoneType' object is not subscriptable
Is.... Is it true discord.py won't work anymore by April 2022



