#discord-bots

1 messages · Page 691 of 1

unkempt canyonBOT
#

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**.
junior terrace
#

what is the * for inpy async def rps(ctx, *, args):?

unkempt canyonBOT
#

*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

junior terrace
#

and why is * separated by a comma

#

and it is not *args

cloud dawn
slate swan
lost wolf
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: choice() takes 2 positional arguments but 3 were given

slate swan
#

how do i make my bot delete channels

lost wolf
#

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}!**__")

cloud dawn
unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

slate swan
plucky shoal
#

Bruh

cloud dawn
#

!d discord.abc.GuildChannel.delete

unkempt canyonBOT
#

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.
cloud dawn
plucky shoal
slate swan
#

ha

#

big panda know it all

plucky shoal
#

Wise man

slate swan
#
async def lol(ctx,*,time)

time is a kwarg

#

Since *, made it a kwarg

cloud dawn
slate swan
#

It ate all the text

slate swan
cloud dawn
slate swan
cold sonnet
#

I don't think anyone would copy that from a pic

slate swan
#

Ikr

pliant gulch
#

OCR moment

slate swan
pliant gulch
#

Yea

slate swan
#

is message.mentions a list?

magic ore
#

Yes

cloud dawn
magic ore
#

!d discord.Message.mentions

unkempt canyonBOT
#

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.

slate swan
#

How can I check if only 1 person is mentioned and NOT store it as a list

cloud dawn
#

imagine it being just a long string.

cloud dawn
magic ore
#

!d discord.User.mentioned_in

unkempt canyonBOT
magic ore
#

Ah nevermind I didn't read your message fully

slate swan
cloud dawn
#

!d len

unkempt canyonBOT
#
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").
slate swan
#

oh kk thanks

#

Ah reply counts as a mention aswell right? I did if message.mentions and not message.reference

cloud dawn
slate swan
#

Yea but for most ppl

#

it is turned on

#

and counts as a mention

compact tartan
#

hi guys, can i share a post

cloud dawn
slate swan
#

If its on topic yes

#

@cloud dawn And member is what?

member = discord.Member

slate swan
#

kk

cloud dawn
compact tartan
slate swan
#

Ot

manic wing
pliant gulch
#

🤔

manic wing
#

its typehintlibrary.Union

pliant gulch
#

Say your correction outloud and see if it makes any sense

#

Its an union??

manic wing
#

omg

#

fuck im dumb

cloud dawn
#

an onion

manic wing
#

whats the vegetable

#

yeah that jesus christ im dumb

#

i tried trolling and i trolled myself

cloud dawn
#

Why are these gifs so big :/

slate swan
#

They always are lol

modest plover
#

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.

cloud dawn
modest plover
#

Yeah, how do I do that? I haven't really done APIs before?

cloud dawn
#

Well you use a token if needed else just code it? API i just to make requests and sometimes post that's it.

slate swan
#

@cloud dawn Got it now but it is still seen as a list. Even tho there's only 1 User

slate swan
modest plover
#

So would that include Disnake, it's a dpy fork

slate swan
#

And yes i do know about disnake since i use it

junior terrace
#

in py @commands.cooldown(1, 1000, commands.BucketType.user) what the 1 stands for?

cloud dawn
slate swan
junior terrace
#

ok? cuz if i change it with 2 the cooldown doesnt work anymore

cloud dawn
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@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.
slate swan
#
@commands.cooldown(1, 60 commands.BucketType.user) 

This adds 60 second cool down after a command

cloud dawn
junior terrace
#

ok

#

ok

#

and is there a way to show the minutes for example?

slate swan
#

Probably is but idk

junior terrace
#

ok tysm for the help

slate swan
#

Their is a error handler for it when its still on cooldown

slate swan
junior terrace
slate swan
# cloud dawn Well it only passes if there is one item so just index it

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?
pliant gulch
#

Well using len you 100% know the list has only one element

#

Just index the first element

slate swan
#

GOT IT

#

it was a dif mistake sorry

slate swan
#

hi can samone help me with making leveling system cuz my dosent work well

manic wing
tulip frigate
flint dome
#

Anyone here wanna help make a bot with me

#

Node.js

manic wing
#

this is a python server, try asking in the nodejs server.

sick birch
#

worst of the bunch

manic wing
#

i just clicked on the first video there was …

sick birch
#

99% of the youtube tutorials for discord.py are horrible

slate swan
#

Lucas isnt that bad

sick birch
#

nah he's pretty bad

slate swan
#

Its outdated but its pretty good compared to freecodecamp

sick birch
#

personally ofc

#

lesser of the 2 evils haha

slate swan
#

fr

sick birch
#

the bar is set really low here

slate swan
#

Yeah

pliant gulch
#

It's good

slate swan
#

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:

  1. test
  2. test2
  3. test3
  4. test4```
#

!code

unkempt canyonBOT
#

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.

slate swan
#

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

manic wing
pliant gulch
manic wing
sage otter
#

*enumerate

pliant gulch
#

!e ```py
strings = """
a
b
c
"""
fmt = map(lambda s: "1" + s, strings.splitlines())
print(list(fmt))

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

['1', '1a', '1b', '1c']
pliant gulch
#

brain fart for a sec

sage otter
#

Literally just use enumerate

manic wing
#

!e ```py
strings = """a
b
c
d
"""
fmt = []
for index, k in enumerate(strings.splitlines(),start=1):
fmt.append(f"{index}. {k}")
print(fmt)

unkempt canyonBOT
#

@manic wing :white_check_mark: Your eval job has completed with return code 0.

['1. a', '2. b', '3. c', '4. d']
slate swan
#

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
#

Just add it to the end of the str

#

!e ```py
print("aa" + "1")

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

aa1
slate swan
#

ah yeh true

#

thanks

#

Also

pliant gulch
slate swan
#

['1. a', '2. b', '3. c', '4. d']

How can I get it

  1. a', '2. b', '3. c', '4. d
pliant gulch
#

You want to turn them into one singular string?

slate swan
#

yes

pliant gulch
#

Use .join method of string

#

!d str.join

unkempt canyonBOT
#

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.
slate swan
#

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
slate swan
#

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 pfpyert

#

I keep getting this:
aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe

after running my bot for like 1h

slate swan
leaden jasper
#

what is the max image size

#

for embeds

slate swan
#

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

slate swan
kindred epoch
#

Then use it?

mighty dust
#

how do i get the username of a person that did a command?

slate swan
#

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

slate swan
slate swan
#

sameone can help me

slate swan
#
    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

heavy folio
#

json...

slate swan
#

what json?

#

i mean what do u mean by joson...

lyric tusk
#

Do u have a jason file

#

@slate swan

slate swan
#

yes

#

but only for leveling up

slate swan
lyric tusk
#

Yeah

slate swan
#

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

unkempt canyonBOT
slate swan
#

i ill use it

#

How can I check if a VALID user ID is in a message? Using an on_message event

heavy folio
#

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)

wicked atlas
heavy folio
#

oo

#

how can i convert json into an embed, e.g. the "title" key into embed.title

jade tartan
#

Hello how do i guys send a message in a channel and member that this member has verified himself?

heavy folio
#

define "verified himself"

jade tartan
#
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()))```
jade tartan
heavy folio
#

wdym by "verified himself"

#

also why so many if statements

#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@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").
heavy folio
#

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

heavy folio
jade tartan
#

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?

sage otter
#

This is going to be in a command right?

#

Or is this gonna be whenever anyone reacts to the message at any time.

jade tartan
#

What would be easier?

#

i think message is

sage otter
#

Those are two different things. It’s one or the other.

jade tartan
#

yeah cuz i want them to react in the same reaction message

sage otter
#

Make your bot listen for
on_reaction_add

heavy folio
sage otter
#

And just do a bunch of logical processing.

jade tartan
heavy folio
#

!d discord.on_reaction_add

unkempt canyonBOT
#

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.
heavy folio
#

use a listener/event

jade tartan
#

Whats the listener/event code?

sage otter
#

He’s literally asking how to use it

jade tartan
sage otter
#

You literally just said what I said but pulled up documentation.

#

Use

jade tartan
#
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)
sage otter
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@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...
sage otter
#

It would be just

jade tartan
#

So have that in a class.event?

slate swan
#

what?

sage otter
#

Wtf is a class.event?

slate swan
#

ikr

sage otter
#

Just put this in your code

jade tartan
#

@client.event

slate swan
#

just

@client.listen()
sage otter
#

No

jade tartan
#

I mean like have them in an new @client.event or ?

slate swan
#

:-:

jade tartan
#

ohh on th reaction add

slate swan
#

'-'

#

thats a decorator

jade tartan
#

Am confused

slate swan
#

read the description

sage otter
#
@Bot.listen("on_reaction_add")
async def rero_listener(reaction, user):
    …
slate swan
#

thats how you use them thats why my listens never work smh

sage otter
#

Something like that.

slate swan
#

🚶

jade tartan
sage otter
#

Ah actually I forgot this is reaction roles

#

You should use on_raw_reaction_add

#

that only takes in payload

jade tartan
#

Right?

slate swan
#

what is payload exactly?

cloud dawn
unkempt canyonBOT
#

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.
slate swan
jade tartan
cloud dawn
jade tartan
#

Nvm

#

But is this right?

sage otter
jade tartan
#

yes

manic wing
#

!enumereate

unkempt canyonBOT
#

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.

jade tartan
#

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.

#

?

slate swan
#

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

cloud dawn
slate swan
#

How can I check if a VALID user ID is in a message? Using an on_message event

slate swan
#

links?

#

your kidding?

jade tartan
#

really

slate swan
jade tartan
#

At least id hope so

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

they just want to invite you to their workspace

#

ik

#

Not a virus

jade tartan
#

Only payload.channel_id and payload.member to be used for this concern?

slate swan
#

i just thought he ment multiple

slate swan
#

I cant share the full code coz word limit can anyone join my replit link?

slate swan
unkempt canyonBOT
#

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.

cloud dawn
slate swan
#

^

jade tartan
#

in the first reaction add for the first one or

#

2nd

cloud dawn
slate swan
slate swan
slate swan
heavy folio
#

why'd you risk your token just for help

slate swan
#

hes using replit

#

cause you can always reset it

#

and a third party lib

jade tartan
#

Is this right?

slate swan
#

I doubt the if emoji == '✅' part

heavy folio
heavy folio
#

yes

slate swan
#

yea ofcourse

#

thats funny

slate swan
heavy folio
#

just use this

unkempt canyonBOT
#

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.

slate swan
#

good thing i dont use replit

jade tartan
#

i say wdym a lot

slate swan
#

i would help but i dont use third party libs only use disnake

jade tartan
#

idk why

cloud dawn
jade tartan
#

My english is my 2nd language so

slate swan
jade tartan
#

@slate swan Wdym?

heavy folio
#

yeah

#

dont compare a str with a unicode emoji use white_check_mark instead

slate swan
#

Just do str(payload.emoji) == "✅"

#

i want to host my bot so bad in heroku but idk if i should lol

heavy folio
#

get a vps be it gcp or aws

slate swan
#

its a little test bot that only has one guild and one member so i think its fine

#

🧍‍♂️

heavy folio
#

and discord slash

slate swan
slate swan
slate swan
slate swan
heavy folio
#
client = discord.Client()
client = commands.Bot(command_prefix=">", intents=discord.Intents.all())```??????????
#

tutorials.

cloud dawn
#

Guys please don't mock him.

slate swan
#

When you don't stick to a single tutorial

heavy folio
heavy folio
#

the thing here is following tutorials wont benefit you, especially when using an advanced lib like dpy

slate swan
jade tartan
#
  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```
cloud dawn
slate swan
slate swan
slate swan
#

Change it to bot.close()

slate swan
#

has a reminder command and a note command so its pretty handy

slate swan
slate swan
#

But heroku deletes any data you save...

cloud dawn
# slate swan Ok

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.

slate swan
#

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

cloud dawn
slate swan
#

i just type a note i want to save and it dms it to me lol

cloud dawn
#

No one has done it before lol

slate swan
#
@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

#

pithink You can make something like the .bm command here

#

it's quite similar to what you have

pliant gulch
#

The embed constructor is killing me

slate swan
pliant gulch
#

Why not just do ```py
a = Class(
...
)

cloud dawn
slate swan
#

for me if it works it works im a simple person lol

#

vsc should automatically indent it that way tho

cloud dawn
#

I don't get why people add datetime to their embed like the time is at the top??

nimble plume
#

anyone help

#

in #help=bana

cloud dawn
sullen shoal
slate swan
#

that looks so cursed

sullen shoal
#

i thought it looks nicer tho

slate swan
#
embed = Embed(
      title = ...,
      description= .....,
)```
slate swan
#

The indents

slate swan
#

i saw that

slate swan
#

time to reright 2 different bots🚶

sullen shoal
pliant gulch
slate swan
pliant gulch
#

A code formatter

sullen shoal
#

black . supremacy

pliant gulch
#

!pypi black

unkempt canyonBOT
slate swan
pliant gulch
#

They even are partnered here as well

slate swan
#

to lazy

#

ill do it myself

#

😩

sullen shoal
#

you're just wasting your time

pliant gulch
#

That sounds bad if you wanna be lazy

slate swan
sullen shoal
#

in vscode you gotta just change thr default formatter and do shift + alt + f or smth

slate swan
#

ill do it manually because im bored and should waste my time

slate swan
#

ever heard such a phrase "i should waste my time"

#

lmfao

pliant gulch
#

You could've used that time to make your reddit api wrapper

slate swan
#

😔

pliant gulch
#

I might fuck around and just steal that idea from you if you don't do it

#

But lefi comes first 😔

slate swan
slate swan
#

or when you send it to pypi

pliant gulch
#

It's already on pypi kek

#

It's on pre-release though

#

!pypi lefi

unkempt canyonBOT
#

A discord API wrapper focused on clean code, and usability

slate swan
#

when its fully ok

#

🚶

pliant gulch
#

Danm, really gonna make a bad impulse decision and finish wrapper in a week

sullen shoal
pliant gulch
#

no

sullen shoal
#

nice

pliant gulch
#

After I grind a bit osu I will start dev again 😔

slate swan
#

what does this do?

\"{thing}\"
sullen shoal
#

!e print("\"hello\"")

unkempt canyonBOT
#

@sullen shoal :white_check_mark: Your eval job has completed with return code 0.

"hello"
slate swan
#

ohhhhhh

#

to send illegal stuff

#

like double quotes

#

andy dont do it

sullen shoal
#

single ones also works

pliant gulch
#

don't do what

slate swan
#

andy dont send a fat explanation

#

like you always do

pliant gulch
#

I wasn't gonna say anything other than that \ is an escape character lol

slate swan
#

cap

#

you always send a whole page on why

drifting tulip
#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.
drifting tulip
#

!paste

unkempt canyonBOT
#

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.

drifting tulip
#

its saying that i was creating channels but i was not?

sullen shoal
#

why is your message like this

drifting tulip
#

lol

#

what?

#

That would be if their not in the whitelisted list

sick birch
#

!e

print("Line 1\nLine 2\nLine 3\nLine 4")
unkempt canyonBOT
#

@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
drifting tulip
#

!e
print("Fr?\n,")

unkempt canyonBOT
#

@drifting tulip :white_check_mark: Your eval job has completed with return code 0.

001 | Fr?
002 | ,
slate swan
drifting tulip
#

does the python bot take js?

sick birch
#

of course not

#

actually

#

!e

console.log("e");
unkempt canyonBOT
#

@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
sick birch
#

lol

slate swan
#

robin what makes you think i dont know🧍‍♂️

drifting tulip
#

nope

sick birch
#

i think \t is a thing too?

slate swan
sick birch
#

!e

print("test\ttest")
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

test	test
sick birch
#

oh nice

slate swan
#

🧍‍♂️

sick birch
#

i did it in java didn't know if it worked here

slate swan
#

it does

sick birch
#

cool stuff

slate swan
#

"learn python"

#

jk btw

sick birch
#

lmao

slate swan
#

@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)
cloud dawn
#

\t s universal

cloud dawn
unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

001 | 809849084763963455
002 | 169790484594556928
slate swan
#

Is it stored in a list then?

cloud dawn
#

no

slate swan
#

i dont get it

cloud dawn
#

it just iterates

slate swan
#

so what is w? Is it true? Or false

#

w is a character from string

cloud dawn
#

!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)

unkempt canyonBOT
#

@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
slate swan
#

ohhhh

#

i get it

#

Bro it's 6 am for me and I have no sleep my thinking process is kinda slow

cloud dawn
#

i could make a fancy regex but i was way too lazy at that time.

slate swan
#

that's ok

cloud dawn
#

excuses

slate swan
#

5:48

drifting tulip
#

its 11pm for me 😭

cloud dawn
slate swan
#

12am

#

for me lol

slate swan
cloud dawn
slate swan
#

OH WHUT

#

me germany

#

netherlands is like 30 min from here

#

netherlands is in quarantine, right?

drifting tulip
#

pip install [wtv]

#

in replit shell

slate swan
drifting tulip
#

yep

slate swan
#

[]

drifting tulip
#

dont use []

slate swan
#

pip install wtv

drifting tulip
#

replace wtv with youtubesearchpython

slate swan
#

pip install youtubesearchpython

drifting tulip
#

yes

slate swan
slate swan
#

pip install youtube-search-python

cloud dawn
#

pretty sure that lib is sync lol

sullen shoal
#

lets see

#

!pip youtube-search-python

unkempt canyonBOT
slate swan
#

pithink isnt it possible by using aiohttp and bs4?

sullen shoal
#

they have async handlers not sure if they're using it or not tho

#

also those function names damn

slate swan
#

they do

sullen shoal
#

nice

#

i did some cool shit with contextlib for this

#

i kinda like the way it works

steep drift
#

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.

maiden fable
#

Guess what. I got Students Developer GitHub Pack!

slate swan
maiden fable
#

U got it?

sullen shoal
maiden fable
#

I applied like last night and got the answer a few hours ago

slate swan
#

didnt signed in for it yet

maiden fable
#

Ah, hmm

#

Sadly it didn't take the Class 10th passing certificate ;-;

Had to give my 2 year old school ID Card lmao

heavy folio
maiden fable
#

Thanks

steep drift
maiden fable
#

Not to mention it got rejected twice before being approved*

heavy folio
#

i dont wanna sign up for it because i use a whole different username and email for school and this (online)

steep drift
sullen shoal
maiden fable
sullen shoal
#

or its just a discord thingy

sullen shoal
steep drift
sullen shoal
#

you insert it by js too but its html

steep drift
#

oh okay

#

got it

#

ty

sullen shoal
full valley
#

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

slate swan
#

How can I find and delete a specific Key in my json file?

sullen shoal
#

"find"
now you have accomplished the need of an actual database

spring verge
#

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

sullen shoal
unkempt canyonBOT
#

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...
spring verge
#

so both ppl will see same leaderboard

#

but it should be different for both of them

full valley
slate swan
sullen shoal
full valley
#

yeah alrighty ty

spring verge
spring verge
#

cant

slate swan
#

run the command 4 time

#

um

sullen shoal
#

.jsk repeat

spring verge
#

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

slate swan
#

well yea , if you dont use run_in_executor , yes

cobalt jacinth
#

can a webhook message trigger the bot to do something ?

#

or bot on bot is no no ?

sullen shoal
#

uh i think the discord api does send webhook messages to the client

slate swan
#

not in the command framework ( bot.command / commands.command)

#

but yea , if you use on_message events , yes

sullen shoal
#

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

cobalt jacinth
#

yes i need to trigger something using on_message when a webhook lands in a channel

slate swan
#

you can do that

cobalt jacinth
#

okok thanks

#
@bot.event
async def on_message(message):
    # do some extra stuff here

    await bot.process_commands(message)
#

is this correct format ?

maiden fable
#

Or u can just simply change the decorator to bot.listen()

#

No need to process commands then

cobalt jacinth
#

ohkkk thanks

pliant gulch
#

This receives all incoming messages though, if you strictly want webhook messages you can check for discord.Message.webhook_id

cobalt jacinth
#

so this recieves all messages and then i can filter out the webhook one ?

#

any way to make it only listen to one channel

slate swan
#

use an if statement...

cobalt jacinth
#

so it listen to all channel and then i need to if/else right

slate swan
#
    #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
cobalt jacinth
#

okok got it

#

does this put stress on bot performance ?

upbeat otter
#

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

wary ice
#

This prob is users.json ? Why

slate swan
#

Tried resetting the json?

upbeat otter
#

And using json as a database is not a good idea

wary ice
upbeat otter
upbeat otter
#

I'm not gonna be spoonfeeding

#

Sorry

slate swan
# wary ice Yes

if not user.id in users , you need to check the string form of id as eevee just said

wary ice
#

Οκ τνχ

slate swan
#

Already wanna use aiosqlite with my discord bots

#

😩 Im bored with aiosqlite , about to shift to pg SQL

boreal ravine
#

copied code

#

bot.send_message isn't even a thing anymore

slate swan
#

?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

boreal ravine
#

in what server

slate swan
#

Lucas

boreal ravine
#

o

#

lucas has a server?

slate swan
#

Yea a support server for his python and discord.py series

#

with a single invite ever created lmao

somber crown
#
        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

slate swan
somber crown
#

so

#

like, uhhh

#

sec

boreal ravine
somber crown
#
        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)}')```
slate swan
#

!e py list = [] for i in ['a','b','c']: list.append(i) print("\n".join(list))

#

Ah f

boreal ravine
#

cast it

somber crown
#

oh

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

001 | a
002 | b
003 | c
somber crown
#

in my case i suppose id be doing py list = [] for i in ['type','name']: list.append(i)

slate swan
#

just append the thing you're sending till now

somber crown
#

alright

slate swan
#

f"{connection_type} : {connection_name}"

#

and use ctx.send with join outside the loop

somber crown
#
      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?

slate swan
#

nah

somber crown
#

or should i put list at the top

slate swan
#

List should be at top

#

And just append what you were sending till now

wary ice
maiden fable
#

@wary ice what happened

wary ice
#
  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?
maiden fable
#

The file isn't there

pliant compass
#

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?

maiden fable
#

Ah

pliant compass
#

I was thinking of using eval()?

maiden fable
#

!d discord.ext.commands.Bot.add_command

unkempt canyonBOT
#

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")
maiden fable
pliant compass
pliant compass
#

I saw it on a YouTube video a few days ago

#

Its what gave me the idea for adding commands

maiden fable
#

With eval, people can get hold of your bot token, shut it down or make it a spam bot and literally control your bot

pliant compass
#

👍

compact harbor
#

It's kinda slower.

maiden fable
compact harbor
#

!e

print("\n".join(i for i in  ['a','b','c'])
unkempt canyonBOT
#

@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
maiden fable
#

Oops u forgot a )

compact harbor
#

!e
print("\n".join(i for i in ['a','b','c']))

unkempt canyonBOT
#

@compact harbor :white_check_mark: Your eval job has completed with return code 0.

001 | a
002 | b
003 | c
slate swan
maiden fable
#

Hmm

slate swan
#

Hunter , close the } when? ( About me intensifies)

compact harbor
#

Use one liner as much as possible while coding in Python. And, use built-in functions then code will be much faster.

maiden fable
slate swan
#

pithink Discord bad

maiden fable
#

Facts

#

My bot in 99 servers but still flagged ;-;

slate swan
#

Guys will this work?py @client.event async def on_message(msg): if message.channel.dmchannel: return else: await client.process_commands(msg)

maiden fable
#

No

#

if isinstance(message.channel, discord.DMChannel)

pliant compass
#

Anyone know a good tutorial for discord.ext.commands.Bot.add_command? I'm finding the docs difficult to understand

maiden fable
#

!d discord.ext.commands.Command

unkempt canyonBOT
#

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.
maiden fable
#

It needs an instance of this

#

Do one thing... Are you okay with reading some part of the source code?

pliant compass
#

Yeah

maiden fable
#

Okay lemme get it then

pliant compass
#

Is this it?

maiden fable
#

No

#

Lemme get it

tough lance
#

Create a command function with @commands.command decorator and use bot.add_command(Function_name)

unkempt canyonBOT
#

discord/ext/commands/core.py line 205

class Command(_BaseCommand, Generic[CogT, P, T]):```
maiden fable
#

Here, see this class, and make a class instance yourself @pliant compass

pliant compass
#

Ok

pliant compass
maiden fable
#

No

maiden fable
#

client.command() automatically calls add_command bro

tough lance
#

Just add parantheses to commands.command

pliant compass
#

Ok

tough lance
maiden fable
compact harbor
tough lance
pliant compass
#

The command passed must be a subclass of Command?

maiden fable
#

I told u 🤷‍♂️

#

It automatically adds to bot.commands

#

The logic behind commands.command and bot.command is the same

compact harbor
tough lance
#

I literally yeeted my mobile for being wrong

pliant compass
#

Sorry, I'm getting really confused

maiden fable
#

Same tbh

tough lance
#

Same

maiden fable
#

Okay lemme tell u what to do

#

@pliant compass do u know how a decorator works?

pliant compass
#

I think so

maiden fable
#

Okay. Lemme get u the code

compact harbor
#

It's really hard to explain you everything in detail.

maiden fable
#

This is what a decorator does

pliant compass
#

Ok

maiden fable
#

And u just gotta do all that manually

pliant compass
#

So is it just basically asking for a function?

tough lance
#

I was right

compact harbor
pliant compass
#

ok

compact harbor
#

@commands.command inherits from commands.Cog and @bot.command inherits from discord.Bot()

#

Follow docs you will get an idea.

tough lance
#

I think they all are different classes

vague sundial
slate swan
#

because its a cog?

tough lance
slate swan
#

ofcourse , when you add_cog its automatically done

tough lance
#

So according to them they want to use commands.command outside of a cog

slate swan
#

why go thru that pain when you can just @bot.command lol

maiden fable
#

What's even happening here CM_CatStare

tough lance
slate swan
#

but souvik is in a cog , and he has no other choice

vague sundial
slate swan
compact harbor
vague sundial
slate swan
compact harbor
heavy folio
#

is it possible to disable copy link while creating a webhook

vague sundial
visual island
maiden fable
visual island
maiden fable
visual island
#

yeah you're rich ^^

#

rich person doesn't got gifted nitro

maiden fable
#

See your DM @visual island

visual island
maiden fable
#

Lmao

upbeat otter
#

Lmao

maiden fable
#

No iirc

heavy folio
#

how did other bots do that

upbeat otter
heavy folio
#

if i remember correctly

upbeat otter
#

I see

heavy folio
velvet tinsel
#

*server owner

heavy folio
#

no

velvet tinsel
#

iirc

heavy folio
#

fine the bot was NQN

#

the server owner doesnt disable it, the bot auto creates it and disables it somehow

heavy folio
#

trying to make a echo command but eh i dont want people to abuse the webhook disgust

maiden fable
boreal ravine
#

imagine not already having an echo command

tough lance
boreal ravine
#

!ot @tough lance

unkempt canyonBOT
#
Did you mean ...

» ot
» off-topic-names

boreal ravine
#

!ot <=

unkempt canyonBOT
#
Did you mean ...

» ot
» off-topic-names

boreal ravine
#

wtf

#

bot broke

visual island
#

lol

#

!ot hi

unkempt canyonBOT
#
Did you mean ...

» ot
» off-topic-names

visual island
#

!ot

unkempt canyonBOT
tough lance
#

Wait you literally saw me going off topic

visual island
#

umm

boreal ravine
#

!ot h

#

broke

heavy folio
#

where did you get that from

#

also how do i set the webhook avatar and name (without editing the actual webhook)

boreal ravine
#

!d discord.Webhook.edit

boreal ravine
#

without editing it

slate swan
#

you can do that at the moment you create it

boreal ravine
#

obviously

hollow agate
#
@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?
visual island
#

the error appears when parsing the args, not when sending a message

#

use on_command_error function or @mention.error to handle it

slate swan
#
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
heavy folio
#
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 ![disgust](https://cdn.discordapp.com/emojis/765710447448948816.webp?size=128 "disgust")
#
        webhook = await ctx.channel.create_webhook(
            name=member.name,
            avatar=member.display_avatar.url,
            reason="echo command"
        )
```this was prolly where the error occured
dapper cobalt
#

What's display_avatar?

heavy folio
#

2.0

slate swan
dapper cobalt
#

Try printing member.display_avatar.url.

boreal ravine
#

member.display_avatar already returns a url

#

and the avatar kwarg takes a bytes object iirc

dapper cobalt
#

!d discord.Member.display_avatar

unkempt canyonBOT
#

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.
dapper cobalt
#

!d discord.Asset.url

unkempt canyonBOT
boreal ravine
slate swan
#
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
boreal ravine
#

json needs double quotes

#

not single quotes

dapper cobalt
heavy folio
#
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
boreal ravine
#

!d discord.Asset.read @heavy folio use this

unkempt canyonBOT
#

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.
heavy folio
#

oh

dapper cobalt
#

Never used 2.0; hence I'm unfamiliar with it.

boreal ravine
#

lol

slate swan
boreal ravine
unkempt canyonBOT
#

discord/asset.py lines 249 to 250

def __str__(self) -> str:
    return self._url```
heavy folio
#

if it's that then it returned another error

slate swan
#

with my leveling system

boreal ravine
heavy folio
#
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
boreal ravine
#

try with_format

#

!d discord.Asset.with_format and then use read on this

unkempt canyonBOT
heavy folio
#
        webhook = await ctx.channel.create_webhook(
            name=member.name,
            avatar=member.display_avatar.read(),
            reason="echo command"
        )
```part where error occured
visual island
#

await it

boreal ravine
#

hm

#

o its a coro

visual island
#

yep

heavy folio
#

wdym

visual island
heavy folio
#

oh wait

#

read()

#

got it thanks

slate swan
maiden fable
heavy folio
#

oh

#

what does it do

maiden fable
#

That way, there ain't a huge number of webhooks made for a server

slate swan
heavy folio
maiden fable
visual island
# slate swan

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.

maiden fable
unkempt canyonBOT
#

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.
visual island
#

yea?

slate swan
#

so i am ban?

visual island
#

temporarily

slate swan
#

time?

visual island
#

few hours

maiden fable
# unkempt canyon

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

slate swan
#

ufff okay

heavy folio
#

oh

copper gulch
# slate swan

ohh I got this error once, it will be back to normal in about 5 hours so dont worry xd

visual island
#

why

slate swan
#

isnt it an one-day-old message

vestal marsh
#

!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()
slate swan
#

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

tawdry perch
#

can you place that in code block and share relevant code

vestal marsh
#

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...
tawdry perch
vestal marsh
#

so, where?

tawdry perch
vestal marsh
#

i already did

slate swan
#
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

vestal marsh
#

aha

solar pine
#

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'
tawdry perch
#

does not seem like so

vestal marsh
#

I broke my backspace key

slate swan
#

nah its not

tawdry perch
#

!paste it here if possible

unkempt canyonBOT
#

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.

solar pine