await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
#discord-bots
1 messages · Page 691 of 1
what is the * for inpy async def rps(ctx, *, args):?
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
Because the discord.py lib format it like that so you can do this it just repacks the var. Pretty weird yeah.
Makes every arg after that a kwarg
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: choice() takes 2 positional arguments but 3 were given
how do i make my bot delete channels
Wait what🕴️
code:
@commands.command()
async def work(self, ctx):
place = random.choice("Mcdounalds", "Hacking Service")
earnings = random.randrange(40000)
user = ctx.author
users = await self.get_bank_data()
await ctx.send(f"__**You Worked Very Hard At {place} and Earned {earnings}!**__")
Yeah it's super weird it just works.
Not likely.
No documentation found for the requested symbol.
Doesnt it make everything after it a kwarg
Bruh
!d discord.abc.GuildChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Nope
Sadge
Wise man
Yes it does
async def lol(ctx,*,time)
time is a kwarg
Since *, made it a kwarg
And regen your token
Read the token
🕴️
I don't think anyone would copy that from a pic
Ikr
OCR moment
Using *args makes it an unknown amount of arguments and **kwargs makes it an unknown amount of kwargs but if its *, it will be all the arguments after that a kwarg
Yea
is message.mentions a list?
Yes
i mean mentions
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
How can I check if only 1 person is mentioned and NOT store it as a list
imagine it being just a long string.
if member in msg.mentions and len(msg.mentions) == 1
!d discord.User.mentioned_in
mentioned_in(message)```
Checks if the user is mentioned in the specified message.
Ah nevermind I didn't read your message fully
What does len mean again?
!d len
len(s)```
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
**CPython implementation detail:** `len` raises [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](https://docs.python.org/3/library/stdtypes.html#range "range").
oh kk thanks
Ah reply counts as a mention aswell right? I did if message.mentions and not message.reference
Well depends if the user has the mention on or not on the right side of the msg box.
hi guys, can i share a post
Is it Discord related?
kk
But it can also be a user it's a union.
nerr is a blog about python and some other programming languages. is about update on its popularity and occupational outlook
Ot
an union*
🤔
its typehintlibrary.Union
an onion
whats the vegetable
yeah that jesus christ im dumb
i tried trolling and i trolled myself
They always are lol
Hey, how do I make my bot interact with a number of APIs? I'm making a stats command for my bot.
Meaning it needs to interact with multiple game stats APIs.
Connect to it..? Also you need to make it async
Yeah, how do I do that? I haven't really done APIs before?
Well you use a token if needed else just code it? API i just to make requests and sometimes post that's it.
@cloud dawn Got it now but it is still seen as a list. Even tho there's only 1 User
Most apis have their own connections and comamnds which you can check their docs but it has to be async since dpy is an async lib
So would that include Disnake, it's a dpy fork
Disnake isnt an api its a fork of the dpy api wrapper which is async
And yes i do know about disnake since i use it
in py @commands.cooldown(1, 1000, commands.BucketType.user) what the 1 stands for?
Well it only passes if there is one item so just index it
Means from what number the cool down will start with
ok? cuz if i change it with 2 the cooldown doesnt work anymore
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`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") and the local error handler.
A command can only have a single cooldown.
@commands.cooldown(1, 60 commands.BucketType.user)
This adds 60 second cool down after a command
rate meaning you need to do it twice.
Probably is but idk
ok tysm for the help
Their is a error handler for it when its still on cooldown
Yw
yeah i'm already using it to show the remaining time in chat ty
Your welcome 
Nvm i think the problem is something else. So I get this error
AttributeError: 'list' object has no attribute 'id'
And this is the line:
if str(user.id) in users:
And the users is a list reading from a json file.
with open("temp.json", "r") as f:
users = json.load(f)```
How can I check it in another way so it isn't seen as a list?
Well using len you 100% know the list has only one element
Just index the first element
hi can samone help me with making leveling system cuz my dosent work well
In this video, we create a level system that allows users to level up based on how many messages they send in the server.
Join here: https://discord.gg/4Fy88WN
If you have suggestions for future video topics, leave it in the comments below.
And yes I did get a new mic :D
#DiscordBot
do not use it, its mega outdated and it just spoonfeeds you
this is a python server, try asking in the nodejs server.
i just clicked on the first video there was …
99% of the youtube tutorials for discord.py are horrible
Lucas isnt that bad
nah he's pretty bad
Its outdated but its pretty good compared to freecodecamp
fr
the bar is set really low here
Yeah
Most tutorials i see of a fork is pycord lol
i have a string variable with this value:
test
test2
test3
test4```
How can I add something before every line? It's all seperated with `\n` And I want something like this:
- test
- test2
- test3
- test4```
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
hi can sameone help me @bot.command() async def rank(ctx, member: discord.Member = None): if not member: id = ctx.message.author.id with open('users.json', 'r') as f: users = json.load(f) lvl = users[str(id)]['level'] await ctx.send(f'masz poziom {lvl}!') else: id = member.id with open('users.json', 'r') as f: users = json.load(f) lvl = users[str(id)]['level'] await ctx.send(f'{member} {user.mention} ma poziom {lvl}!') the mention dosent i mean the user dosent get mention mentioned when i type +rank but i add it
you would split it into a list, and replace the start of each list index with the iteration count
You can use map and splitlines here
you wouldnt be able to get iteration number with map
*enumerate
!e ```py
strings = """
a
b
c
"""
fmt = map(lambda s: "1" + s, strings.splitlines())
print(list(fmt))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
['1', '1a', '1b', '1c']
brain fart for a sec
Literally just use enumerate
pls sameone
!e ```py
strings = """a
b
c
d
"""
fmt = []
for index, k in enumerate(strings.splitlines(),start=1):
fmt.append(f"{index}. {k}")
print(fmt)
@manic wing :white_check_mark: Your eval job has completed with return code 0.
['1. a', '2. b', '3. c', '4. d']
What if I want to add something add the end aswell?
So one at the beginning and one at the end So it writes the message likethis`
oh
shit
Bruh this is hard
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
aa1
You could with zip and use that instead with the map instead of just splitlines()
['1. a', '2. b', '3. c', '4. d']
How can I get it
- a', '2. b', '3. c', '4. d
You want to turn them into one singular string?
yes
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
oh kk what if I want to just add '-' after each line in one singular string @pliant gulch
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "bot.py", line 212, in rank
lvl = users[str(id)]['level']
KeyError: '697140703943458927'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '697140703943458927'``` i got this error
The user with ID 697140703943458927 couldn't be found
em
but he has nickname Szymon
and he has this id
697140703943458927
the same id as in the error
so idk whats wrong
but he is offline rn
@slate swan He isn't found in your file
oh
what should i do
Guys rate my pfp
I keep getting this:
aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe
after running my bot for like 1h
to not getting this error
I want to have a background task which does a specific thing every 24 hours. Should I do await asyncio.sleep(86400)? Because it seems kinda weird when putting in a large number for a sleep
Use tasks.loop
Yeh but it has to be every 24h. I know that I have to use task.loop
Then use it?
how do i get the username of a person that did a command?
Use the author attr
If your using ctx just use
ctx.author
And if you want to mention him just use the .mention attr
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "bot.py", line 212, in rank
lvl = users[str(id)]['level']
KeyError: '697140703943458927'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '697140703943458927'``` i got this error what sholud i do to not getting this error
when i use +rank @nick on the other servers
If your getting the name just use the .name attr
code?
wait
if not f'{user.id}' in users:
users[f'{user.id}'] = {}
users[f'{user.id}']['experience'] = 0
users[f'{user.id}']['level'] = 1
async def add_experience(users, user, exp):
users[f'{user.id}']['experience'] += exp
async def level_up(users, user, message):
with open('levels.json', 'r') as g:
levels = json.load(g)
experience = users[f'{user.id}']['experience']
lvl_start = users[f'{user.id}']['level']
lvl_end = int(experience ** (1 / 4))
if lvl_start < lvl_end:
await message.channel.send(f'{user.mention} gratulacje zdobyłeś poziom {lvl_end}')
users[f'{user.id}']['level'] = lvl_end
@bot.command()
async def rank(ctx, member: discord.Member = None):
if not member:
id = ctx.message.author.id
with open('users.json', 'r') as f:
users = json.load(f)
lvl = users[str(id)]['level']
await ctx.send(f'{member} masz poziom {lvl}!')
else:
id = member.id
with open('users.json', 'r') as f:
users = json.load(f)
lvl = users[str(id)]['level']
await ctx.send(f'{member} ma poziom {lvl}!')```
here this is leveling system with rank command
json...
You mean json
Yeah
JavaScript Object Notation
And why use json for a leveling system just use a db which actually is used to store data unlike json
Sql is easy to learn and for async libs just use aiosqlite
!pypi aiosqlite
mabe
i ill use it
How can I check if a VALID user ID is in a message? Using an on_message event
nvm
anyone has any api or smt which can convert a pastebin url and get the json from there to make an embed (making an embed command)
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hello how do i guys send a message in a channel and member that this member has verified himself?
define "verified himself"
async def reactrole(ctx, emoji, role : discord.Role, *, message):
if ctx.author.guild_permissions.manage_roles == True:
if emoji == '☑️':
await ctx.send(embed=discord.Embed(title="Reaction Roles", description="**Syntax** : `gm<reactrole (emoji) (name or role) (message)`", color=discord.Color.blue()))
elif role == Member:
await ctx.send(embed=discord.Embed(title="Reaction Roles", description="**Syntax** : `gm<reactrole (emoji) (name or role) (message)`", color=discord.Color.blue()))
else:
emb = discord.Embed(title=f"_Get access to all channels!_", description=message, color=discord.Color.blue())
msg = await ctx.channel.send(embed=emb)
await msg.add_reaction("\U00002705")
with open('reactrole.json') as json_file:
data = json.load(json_file)
new_react_role = {'role_name': role.name,
'role_id': role.id,
'emoji': emoji,
'message_id': msg.id}
data['Member'] = new_react_role
with open('reactrole.json', 'w') as f:
json.dump(data, f, indent=4)
else:
await ctx.send(embed=discord.Embed(title="Missing Permissions", description="You dont have permission to use this command!", color=discord.Color.blue()))```
wdym?
wdym by "verified himself"
also why so many if statements
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
use this instead, the py if ctx.author.guild_permissions.manage_roles == True:and last else statement would be redundant + it makes your code much more cleaner
anyways back to the point uh
elif role == Member:
```what is "Member"
its fine it works either way
I want to be where if a member reacts to the emoji it automatically sends a message that {member.mention} has been verified. In channel and dm.
What?
This is going to be in a command right?
Or is this gonna be whenever anyone reacts to the message at any time.
Those are two different things. It’s one or the other.
yeah cuz i want them to react in the same reaction message
Make your bot listen for
on_reaction_add
it'll get troublesome when you screw up things
And just do a bunch of logical processing.
How?
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
use a listener/event
Whats the listener/event code?
He’s literally asking how to use it
already have that
async def on_raw_reaction_add(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="Member")
await member.add_roles(role)
@client.event
async def on_raw_reaction_add(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=829665222380879912)
await payload.member.add_roles(role)
!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/master/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...
It would be just
So have that in a class.event?
what?
Wtf is a class.event?
ikr
Just put this in your code
just
@client.listen()
No
I mean like have them in an new @client.event or ?
:-:
ohh on th reaction add
Am confused
read the description
@Bot.listen("on_reaction_add")
async def rero_listener(reaction, user):
…
thats how you use them thats why my listens never work smh
Something like that.
🚶
Ah actually I forgot this is reaction roles
You should use on_raw_reaction_add
that only takes in payload
what is payload exactly?
!d discord.RawReactionActionEvent
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
ah i see
How do i get those commands. or where to find them?
You mean how i found this info?
Is this bot only meant to work in one guild?
yes
!enumereate
Ever find yourself in need of the current iteration number of your for loop? You should use enumerate! Using enumerate, you can turn code that looks like this:
index = 0
for item in my_list:
print(f"{index}: {item}")
index += 1
into beautiful, pythonic code:
for index, item in enumerate(my_list):
print(f"{index}: {item}")
For more information, check out the official docs, or PEP 279.
I want to be where if a member reacts to the emoji it automatically sends a message that {member.mention} has been verified. In channel and dm.
?
payload.member gets you the member
payload.channel_id gives you the id of the channel in which reaction was added , get the channel and send the message there
Why buttons not there
Because you didn't have a view in the .send()
show code to see the error lol
Why is there no context?
How can I check if a VALID user ID is in a message? Using an on_message event
Dm i share you multipler link
links?
your kidding?
smells like grabify
At least id hope so
you trying some command which takes some user id ?
just copy paste the code
Multiplayer
To big code
send the func

they just want to invite you to their workspace
ik
Not a virus
Only payload.channel_id and payload.member to be used for this concern?
i just thought he ment multiple
No. I want to do something, if a USER ID is sent in a message. And it's not a command it's an event
I cant share the full code coz word limit can anyone join my replit link?
basically payload.member would give u the member , you can use payload.member.send() to send the message to them ,
payload.channel_id gives you the channel ID , you can use bot.get_channel(payload.channel_id) to get the channel object , and use .send() there :)
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
string = 'some text 809849084763963455 yes lol'
for w in string.split(' '):
if w.isdigit() and len(w) == 18:
# Can raise member not found -> discord.NotFound
member = await bot.fetch_user(w)
^
Where do i put that?
in the first reaction add for the first one or
2nd
I didn't even agree and you DM'ed me
Or , you can use get_or_fetch_user

Wherever you want to use it?
why'd you risk your token just for help
THANK YOU
I doubt the if emoji == '✅' part
i know but if you share a inv link other people can access your env vars
bruh really?
yes
Its a test bot
just use this
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
good thing i dont use replit
i would help but i dont use third party libs only use disnake
idk why
that's ok
My english is my 2nd language so
Emoji.name will never return a ✅ unicode emoji
@slate swan Wdym?
Just do str(payload.emoji) == "✅"
i want to host my bot so bad in heroku but idk if i should lol
get a vps be it gcp or aws
its a little test bot that only has one guild and one member so i think its fine
🧍♂️
sigh another user using discord components
and discord slash
Yes its a test bot
Sigh?
wasnt talking to you
Ohh
https://paste.pythondiscord.com/upateceqak.py i still like my eyes
was talking about my own test bot lol
client = discord.Client()
client = commands.Bot(command_prefix=">", intents=discord.Intents.all())```??????????
tutorials.
my eyes
Guys please don't mock him.
When you don't stick to a single tutorial
should i guys?
that isnt mocking
the thing here is following tutorials wont benefit you, especially when using an advanced lib like dpy
How can a guild have one member. When the bot is already in the server
ret = await coro(*args, **kwargs)
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002ED13722200>
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002ED13722200>
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed```
No you're right it's very rude and very disrespectful.
one member not including him🧍♂️
Xd , in that case just selfhost it when you're online?

you have bot.logout somewhere
Change it to bot.close()
the thing is it has a eval command i want to be able to use on my phone when im not at home lol
has a reminder command and a note command so its pretty handy
Well yea , then you can just go for it
yeah i was thinking about it since its my only personal bot with only a guild an 2 members and 3 commands rn
But heroku deletes any data you save...
I advice you to, take a look at this and get this sorted out -> https://vcokltfre.dev/
There are some things not going really well and i also recommend taking a look at Disnake.
Unfortunately we are not allowed to help with this project since you do violate the ToS.
not saving data LOL
i dm the notes to myself
Oh , so you cache the reminders and notes stuff?
Ah I see
haha no
and reminder i just use .sleep since its my only i was too lazy to use a db
Using a DM as your database, save the messages and edit them on update etc.
why would i
i just type a note i want to save and it dms it to me lol
No one has done it before lol
Ok
@bot.command()
async def note(ctx,*,note):
try:
embed0 = discord.Embed(title="Note Has been set",
description=f"Your Note has been sent to you",
timestamp=datetime.datetime.now())
msg2 = await ctx.send(embed=embed0)
await msg2.add_reaction("✅")
embed1 = discord.Embed(title="Note",
description=note,
timestamp=datetime.datetime.now())
await ctx.author.send(embed=embed1)
except:
embed2 = discord.Embed(title="Error",
description="Your dms permissions are off\nplease turn them on for notes",
timestamp=datetime.datetime.now())
msg3 = await ctx.reply(embed=embed2)
await msg3.add_reaction("❌")
see
pretty nice
ignore the bare except btw
i know i shouldnt use it to follow pep8 im just to lazy
You can make something like the .bm command here
it's quite similar to what you have
to lazy
The embed constructor is killing me
why the order?
Why not just do ```py
a = Class(
...
)
If we would apply PEP8 here then pepe would officially throw it away. 
🧍♂️
for me if it works it works im a simple person lol
vsc should automatically indent it that way tho
I don't get why people add datetime to their embed like the time is at the top??
i just like it

for the embed you could do,
embed = discord.Embed()
embed.title = ...
embed.description = ...```
why🧍♂️
that looks so cursed
i thought it looks nicer tho
looks cursed🚶
embed = Embed(
title = ...,
description= .....,
)```
thats kinda what i do ig
The indents
i saw that
fine🧍♂️
time to reright 2 different bots🚶
because of bare except, its gonna send that even when you dont have permissions to react to a message
what?
Just install black and run that over the codebase
whats that
A code formatter
black . supremacy
!pypi black
i just add the check mark for detail lol
you're just wasting your time
That sounds bad if you wanna be lazy
have extra time so i should
in vscode you gotta just change thr default formatter and do shift + alt + f or smth
ill do it manually because im bored and should waste my time
You could've used that time to make your reddit api wrapper
im scared ok😖
😔
I might fuck around and just steal that idea from you if you don't do it
But lefi comes first 😔
but i dont even know what to read😞
when its fully fully released ill make a bot with it for fun
or when you send it to pypi
Danm, really gonna make a bad impulse decision and finish wrapper in a week
are user bots allowed
no
nice
🧍♂️
After I grind a bit osu I will start dev again 😔
what does this do?
\"{thing}\"
!e print("\"hello\"")
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
"hello"
single ones also works
don't do what
I wasn't gonna say anything other than that \ is an escape character lol
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
why is your message like this
also used for things like new lines \n
!e
print("Line 1\nLine 2\nLine 3\nLine 4")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
001 | Line 1
002 | Line 2
003 | Line 3
004 | Line 4
!e
print("Fr?\n,")
@drifting tulip :white_check_mark: Your eval job has completed with return code 0.
001 | Fr?
002 | ,
robin i know that bro🧍♂️
does the python bot take js?
@sick birch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'console' is not defined
lol
robin what makes you think i dont know🧍♂️
nope
¯_(ツ)_/¯
i think \t is a thing too?
yes its for tabs
!e
print("test\ttest")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
test test
oh nice
🧍♂️
i did it in java didn't know if it worked here
it does
cool stuff
lmao
@cloud dawn What happens if there are 2 User ids?
example:
string = 'some text 809849084763963455 nani 169790484594556928 yes lol'
for w in string.split(' '):
if w.isdigit() and len(w) == 18:
# Can raise member not found -> discord.NotFound
member = await bot.fetch_user(w)
\t s universal
!e ```py
string = 'some text 809849084763963455 nani 169790484594556928 yes lol'
for w in string.split(' '):
if w.isdigit() and len(w) == 18:
print(w)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
001 | 809849084763963455
002 | 169790484594556928
Is it stored in a list then?
no
i dont get it
it just iterates
!e ```py
string = 'some text 809849084763963455 nani 169790484594556928 yes lol'
for w in string.split(' '):
if w.isdigit() and len(w) == 18:
print(w)
else:
print(w)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
001 | some
002 | text
003 | 809849084763963455
004 | nani
005 | 169790484594556928
006 | yes
007 | lol
ohhhh
i get it
Bro it's 6 am for me and I have no sleep my thinking process is kinda slow
i could make a fancy regex but i was way too lazy at that time.
6 am here aswell
that's ok
excuses
5:48
its 11pm for me 😭
Where do you live at
Netherlands
OH WHUT
me germany
netherlands is like 30 min from here
netherlands is in quarantine, right?
For me?
yep
[]
dont use []
pip install wtv
replace wtv with youtubesearchpython
pip install youtubesearchpython
yes
pretty sure that lib is sync lol
isnt it possible by using aiohttp and bs4?
they have async handlers not sure if they're using it or not tho
also those function names damn
they do
Hey does anyone know how when I post a link like Funimation the Embed is a different colour, how would I do that with a website of my own.
Guess what. I got Students Developer GitHub Pack!
👀 wow ggs
you want random colors or smth or want to know the meta tag for colors?
I applied like last night and got the answer a few hours ago
didnt signed in for it yet
Ah, hmm
Sadly it didn't take the Class 10th passing certificate ;-;
Had to give my 2 year old school ID Card lmao
congrats
Thanks
this happened with another website too, all I'm wondering is how it is Purple when I just put the link in the message
Not to mention it got rejected twice before being approved*
i dont wanna sign up for it because i use a whole different username and email for school and this (online)
Look @sullen shoal : https://www.funimation.com/
lools like you have this metatag,
<meta name="theme-color" content="..." />``` for some reason
I don't have a school email. I submitted my gmail and they just asked my school documentary proof, like ID Card or something and boom. It's approved
or its just a discord thingy
in js right?
oooh
html
oh I see
you insert it by js too but its html
other metatags can be found here: https://cookieandrock.dev/posts/candr-website-005
@steep drift
Anyone know how I’d go about checking if a voice channel is empty only after it has been filled to the user limit?
I don’t have the channels id though since it’s just temporary
How can I find and delete a specific Key in my json file?
"find"
now you have accomplished the need of an actual database
so I had a doubt related to pillow module
now for example I have to save my image template
but what if I dont want to save it as file and instead assign that file to a variable
because what if 2 ppl are using leaderboard at almost same time
but because of that issue the one file which is saved gets replaced
!d discord.on_voice_state_update i think
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
Yeah just struggling to adapt it to my needs
thats not gonna happen since pillow is blocking and it will complete the task for the person who ran the command first and then the second one
both before and after has channel attr
check if members hit the user_limit then add it to a dict or your database then on every call of the event check channels with the dict or databse data
yeah alrighty ty
so if 4ppl use a command almost at the same time to generate image and lets say that image takes 5 seconds to generate then 4th person will have to wait 20 seconds approx?
try doing it yourself
cant
.jsk repeat
because I have to select an option from menu .. it creates gap of time while doing it T-T so I wont be able to see much difference
well yea , if you dont use run_in_executor , yes
uh i think the discord api does send webhook messages to the client
not in the command framework ( bot.command / commands.command)
but yea , if you use on_message events , yes
but ig Member.bot will be true so depends on the code of bot if they ignore them or not
if its your own bot, you may use webhooks to trigger smth
using the on_message listeners
yes i need to trigger something using on_message when a webhook lands in a channel
you can do that
okok thanks
@bot.event
async def on_message(message):
# do some extra stuff here
await bot.process_commands(message)
is this correct format ?
Yea
Or u can just simply change the decorator to bot.listen()
No need to process commands then
ohkkk thanks
This receives all incoming messages though, if you strictly want webhook messages you can check for discord.Message.webhook_id
so this recieves all messages and then i can filter out the webhook one ?
any way to make it only listen to one channel
use an if statement...
so it listen to all channel and then i need to if/else right
#the message comes in any channel
if message.channel.id != Your channel ID : return``` will not do anything if it's not the channel you want
Not really, its just a conditional that checks the channel id so....
xD, this is probably copied from lucas or glowstik
You can just use the lvl_end variable and the user's current xp, subtract the value of the current xp to the value of lvl_end, thats the remaining xp they have to acquire to move to the next level
This prob is users.json ? Why
Tried resetting the json?
And using json as a database is not a good idea
Yes
The user id should be a string
ok but where do i need to put?
In the rank
I'm not gonna be spoonfeeding
Sorry
if not user.id in users , you need to check the string form of id as eevee just said
Οκ τνχ
oh
Already wanna use aiosqlite with my discord bots
😩 Im bored with aiosqlite , about to shift to pg SQL
Then go for it
?tag old level
replace client.send_message(channel, with channel.send(
and replace every user.id with str(user.id)
They literally have a tag for this lol
in what server
Lucas
Yea a support server for his python and discord.py series
with a single invite ever created lmao
for account in accounts:
print(account['type'], account['name'])
connection_type = account['type']
connection_name = account['name']
await ctx.send(f'{connection_type} : {(connection_name)}')```how can i get this all in 1 message? splitting the messages with `\n`
@boreal ravine hi! its terror, got termed again
@idle quail
thats not me
@slate swan thats me
append all these stuff to a single list
And use "\n".join(list)
how many times have you got termed lmao
for account in accounts:
print(account['type'], account['name'])
connection_type = account['type']
connection_name = account['name']
connection_type = {}
connection_type = {}
await ctx.send(f'{connection_type} : {(connection_name)}')```
cast it
oh
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | a
002 | b
003 | c
^^
in my case i suppose id be doing py list = [] for i in ['type','name']: list.append(i)
just append the thing you're sending till now
alright
list = []
for account in accounts:
print(account['type'], account['name'])
connection_type = account['type']
connection_name = account['name']
for i in ['connection_type','connection_name']:
list.append(i)
await ctx.send(f'\n'.join(list))```
that better?
nah
or should i put list at the top
and how I do it once
and how I do it once
@wary ice what happened
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "c:\Users\user\.vscode\extensions\ms-python.python-2021.12.1559732655\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
cli.main()
File "c:\Users\user\.vscode\extensions\ms-python.python-2021.12.1559732655\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 444, in main
run()
File "c:\Users\user\.vscode\extensions\ms-python.python-2021.12.1559732655\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 285, in run_file
runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 268, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 237, in _get_code_from_file
with io.open_code(decoded_path) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'c:\\Users\\user\\OneDrive\\πολογιστής\\Bots\\main.py'``` what is this error?
The file isn't there
I'm making a feature in my bot that will let people make custom commands with a JSON file. The file looks like this:json [ { "name": "hello", "output": "Hello!" }, { "name": "bye", "output": "goodbye" } ] I want to make these into commands. Foe example if I did -hello then I would get the output Hello!. I have got the code to get all of the data from the JSON, but I'm not sure how to make them into commands.
Anyone know how I can do this?
Ah
I was thinking of using eval()?
!d discord.ext.commands.Bot.add_command
add_command(command)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.
This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.
Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/master/api.html#discord.ClientException "discord.ClientException")
NEVER
Thanks.
Why not eval?
I saw it on a YouTube video a few days ago
Its what gave me the idea for adding commands
With eval, people can get hold of your bot token, shut it down or make it a spam bot and literally control your bot
👍
Use list comprehension, don't code like that.
It's kinda slower.

!e
print("\n".join(i for i in ['a','b','c'])
@compact harbor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print("\n".join(i for i in ['a','b','c'])
003 | ^
004 | SyntaxError: '(' was never closed
Oops u forgot a )
!e
print("\n".join(i for i in ['a','b','c']))
@compact harbor :white_check_mark: Your eval job has completed with return code 0.
001 | a
002 | b
003 | c
Ofcourse , that was just an example for their purpose
Hmm
Hunter , close the } when? ( About me intensifies)
Use one liner as much as possible while coding in Python. And, use built-in functions then code will be much faster.
When discord spares me 

Discord bad
FileNotFoundError
Guys will this work?py @client.event async def on_message(msg): if message.channel.dmchannel: return else: await client.process_commands(msg)
Anyone know a good tutorial for discord.ext.commands.Bot.add_command? I'm finding the docs difficult to understand
bot.add_command(...)
!d discord.ext.commands.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
It needs an instance of this
Do one thing... Are you okay with reading some part of the source code?
Yeah
Okay lemme get it then
Is this it?
It's almost the same as adding a cog, just that you're adding a command from another file or in the main file without a cog
Create a command function with @commands.command decorator and use bot.add_command(Function_name)
discord/ext/commands/core.py line 205
class Command(_BaseCommand, Generic[CogT, P, T]):```
Here, see this class, and make a class instance yourself @pliant compass
Ok
Something like this?```py
@commands.command
async def newCommand(ctx):
print("test")
client.add_command(newCommand())
No
Yup clearly
client.command() automatically calls add_command bro
Just add parantheses to commands.command
Ok
Its commands.command
Same thing 🤦
It's for cogs.
It is, but for registering commands out of cogs, bot.add_command is used
The command passed must be a subclass of Command?
I told u 🤷♂️
It automatically adds to bot.commands
The logic behind commands.command and bot.command is the same
I've never used in btw.
I literally yeeted my mobile for being wrong
Sorry, I'm getting really confused
Same tbh
Same
I think so
Okay. Lemme get u the code
You can follow up my project to get some help:
https://github.com/SouvikGhosh05/Discord-Chatbot
It's really hard to explain you everything in detail.
Ok
And u just gotta do all that manually
So is it just basically asking for a function?
Decorators are used to wrap a function to another function. It's more like functional programming stuff.
ok
@commands.command inherits from commands.Cog and @bot.command inherits from discord.Bot()
Follow docs you will get an idea.
discord.ext.commands.Bot*
I think they all are different classes
Any specific reason u are choosing commands.command() over bot.command()
because its a cog?
If it's a cog then bot.add_command isn't needed
ofcourse , when you add_cog its automatically done
So according to them they want to use commands.command outside of a cog
why go thru that pain when you can just @bot.command lol
What's even happening here 
That's the question notclarkkent was asking
but souvik is in a cog , and he has no other choice
So if u use cog u have to use commands.command?
yes , you cannot just @bot.command there
Because those are in cogs.
I am sorry if this question is dumb but why is it so?
because you dont acess to the bot variable there
Yes correct.
is it possible to disable copy link while creating a webhook
Ohhkk now I get it a bit
imagine buying nitro
Imagine being gifted nitro
lie
U sure?
See your DM @visual island
yea
Lmao
Lmao
No iirc
how did other bots do that
What even is "iirc"
if i remember correctly
I see
hm
They dont disable that, the server does it
*server owner
no
iirc
fine the bot was NQN
the server owner doesnt disable it, the bot auto creates it and disables it somehow
decorators cool
trying to make a echo command but eh i dont want people to abuse the webhook 
Facts
imagine not already having an echo command
!ot @tough lance
Did you mean ...
» ot
» off-topic-names
!ot <=
Did you mean ...
» ot
» off-topic-names
Did you mean ...
» ot
» off-topic-names
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Wait you literally saw me going off topic
umm

where did you get that from
also how do i set the webhook avatar and name (without editing the actual webhook)
!d discord.Webhook.edit
how do you propose you set a webhook avatar
without editing it
you can do that at the moment you create it
obviously
@client.command()
async def mention(ctx, member: discord.User=None):
if member is None:
a = await ctx.reply('You must actually mention a user/user ID!')
await asyncio.sleep(5)
await a.delete()
await ctx.message.delete()
return
else:
try:
a = await ctx.reply(f'{member.mention}')
await asyncio.sleep(10)
await a.delete()
await ctx.message.delete()
return
except:
a = await ctx.reply('The mentioned user/user ID is not valid! Please try again.')
await asyncio.sleep(5)
await a.delete()
await ctx.message.delete()
return``` When I put an invalid user ID, the try and except doesn't seem to work with it. Is there a way for it to work?
the error appears when parsing the args, not when sending a message
use on_command_error function or @mention.error to handle it
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "bot.py", line 182, in on_message
with open('level.json','r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'level.json'
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "bot.py", line 182, in on_message
with open('level.json','r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'level.json'
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "bot.py", line 182, in on_message
with open('level.json','r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'level.json'```
i got this error
Read the last line.
Ignoring exception in command say:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\user\Desktop\valid-user\cogs\managers.py", line 797, in say
webhook = await ctx.channel.create_webhook(
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\channel.py", line 583, in create_webhook
avatar = utils._bytes_to_base64_data(avatar) # type: ignore
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 480, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 466, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
TypeError: startswith first arg must be str or a tuple of str, not bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
```idk what went wrong 
webhook = await ctx.channel.create_webhook(
name=member.name,
avatar=member.display_avatar.url,
reason="echo command"
)
```this was prolly where the error occured
What's display_avatar?
2.0
i done it
Try printing member.display_avatar.url.
member.display_avatar already returns a url
and the avatar kwarg takes a bytes object iirc
It returns a discord.Asset object.
!d discord.Member.display_avatar
property display_avatar: discord.asset.Asset```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
!d discord.Asset.url
property url: str```
Returns the underlying URL of the asset.
k
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "bot.py", line 183, in on_message
users = json.load(f)
File "/usr/local/lib/python3.8/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.8/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 14 column 7 (char 256)``` i got this error
Ah, then you don't need the url attr.
Ignoring exception in command say:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\user\Desktop\valid-user\cogs\managers.py", line 797, in say
webhook = await ctx.channel.create_webhook(
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\channel.py", line 583, in create_webhook
avatar = utils._bytes_to_base64_data(avatar) # type: ignore
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 480, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 466, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
AttributeError: 'Asset' object has no attribute 'startswith'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Asset' object has no attribute 'startswith'
```hmm
!d discord.Asset.read @heavy folio use this
await read()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this asset as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.9)") object.
oh
Never used 2.0; hence I'm unfamiliar with it.
lol
so what sholud i do
replace ' with "
discord/asset.py lines 249 to 250
def __str__(self) -> str:
return self._url```
so like display_avatar.read()?
if it's that then it returned another error
https://www.toptal.com/developers/hastebin/rejiriwugo.sql thia is my code for more looking into this or somethin
with my leveling system
show
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\user\Desktop\valid-user\cogs\managers.py", line 797, in say
webhook = await ctx.channel.create_webhook(
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\channel.py", line 583, in create_webhook
avatar = utils._bytes_to_base64_data(avatar) # type: ignore
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 480, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 466, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
AttributeError: 'coroutine' object has no attribute 'startswith'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'startswith'
C:\Users\user\AppData\Local\Programs\Python\Python38\lib\asyncio\events.py:81: RuntimeWarning: coroutine 'AssetMixin.read' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
with_format(format, /)```
Returns a new asset with the specified format.
show code btw
webhook = await ctx.channel.create_webhook(
name=member.name,
avatar=member.display_avatar.read(),
reason="echo command"
)
```part where error occured
await it
yep
wdym
.
but where and what in my code i send my leveling system code https://www.toptal.com/developers/hastebin/rejiriwugo.sql
BTW big bots like NQN doesn't do that
It makes a single webhook and changes it's name and stuff iirc
That way, there ain't a huge number of webhooks made for a server
yeah that's what i want to do
^
#Ratelimited
replit uses shared IP, that means if a replit user got banned from discord API (rate limited), then everyone using the same IP (including you) will got ban also.
!d discord.Webhook.edit
await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits this Webhook.
but i am rate limited
yea?
so i am ban?
temporarily
time?
few hours
BTW as your bot grows, it will get ratelimited easily since u will be calling the API again and again to change the name and stuff
ufff okay
oh
ohh I got this error once, it will be back to normal in about 5 hours so dont worry xd
why
isnt it an one-day-old message
!e
from turtle import *
#Comment...
def fan():
for i in range(8):
fd(100); bk(100); lt(45)
#Comment...
def fan2():
for i in range(360):
fd(1); lt(1)
#Comment...
def building():
fd(57); rt(70); fd(200); rt(110); fd(250); rt(110); fd(200); rt(70); fd(57)
fan()
fd(57)
lt(90)
fan2()
pu; lt(90); fd(57); rt(90); fd(50); rt(90); pd; building()
on_message
await message.channel.send(content=None, embed=embed)
File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in
send
data = await state.http.send_message(channel.id, content, tts=tts, embed=
embed,
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in
request
async with self.__session.request(method, url, **kwargs) as r:
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117,
in aenter
self._resp = await self._coro
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 544,
in _request
await resp.start(conn)
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client_reqrep.py", lin
e 890, in start
message, payload = await self._protocol.read() # type: ignore
File "/usr/local/lib/python3.8/dist-packages/aiohttp/streams.py", line 604,
in read
await self._waiter
aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
can you place that in code block and share relevant code
bruh
from turtle import *
#Comment...
def fan():
for i in range(8):
fd(100); bk(100); lt(45)
#Comment...
def fan2():
for i in range(360):
fd(1); lt(1)
#Comment...
def building():
fd(57); rt(70); fd(200); rt(110); fd(250); rt(110); fd(200); rt(70); fd(57)
fan()
fd(57)
lt(90)
fan2()
pu; lt(90); fd(57); rt(90); fd(50); rt(90); pd; building()
#Comment...
not related to this channel
so, where?
I have no idea what you are trying to do, if you need help take a look at #❓|how-to-get-help
i already did
on_message
await message.channel.send(content=None, embed=embed)
File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in
send
data = await state.http.send_message(channel.id, content, tts=tts, embed=
embed,
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in
request
async with self.session.request(method, url, **kwargs) as r:
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117,
in aenter__
self._resp = await self._coro
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 544,
in _request
await resp.start(conn)
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client_reqrep.py", lin
e 890, in start
message, payload = await self._protocol.read() # type: ignore
File "/usr/local/lib/python3.8/dist-packages/aiohttp/streams.py", line 604,
in read
await self._waiter
aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
cant get the code rn
aha
Hello, I'm using gspread_asyncio
gsheetcell = await sheet.acell('B4').value
The error is
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'value'
is this the whole traceback?
does not seem like so
I broke my backspace key
nah its not
!paste it here if possible
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I'm pretty sure the docs tell me to use .value though
