#discord-bots

1 messages Β· Page 1149 of 1

slate swan
#

🧍

#

🧍

#

🧍

dusky pine
#

🧍

slate swan
#

🧍

#

🧍

#
File "C:\Program Files\Common Files\System Bot\Bots\welcome\welcome.py", line 57, in on_member_join
  asset = member.avatar.with_size(1024) # This loads the Member Avatar
AttributeError: 'str' object has no attribute 'with_size'

it came with this error this time

#

avatar is a string

#

🧍

slate swan
#

dk if I should ask this
My discord presence extension never works

#

Like I have to mess with some things in it

#

And re open my vsc

#

for vscode?

#

Yah

#

ctrl+shift+p, reconnect to discord

#

Download discord rich presence

#

Extension

honest shoal
#

Please help me with this error console disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://neelpatel05.pythonanywhere.com/element/atomicnumber?atomicnumber=16')

slate swan
#

Oh works ty
Don’t mind the lines i wrote in bot.py πŸ’€ πŸ’€

paper sluice
slate swan
slate swan
shrewd apex
#

🧍

#

pip show lib_name

slate swan
paper sluice
slate swan
slate swan
#

πŸ˜” why no cogs

paper sluice
slate swan
#

my bad xd

#

thanks for the idea, ill try python 1 today

#

i saw a video on that, they dont even have the os module, or random

paper sluice
#

make a discord bot in python1

#

async generators

slate swan
#

!pip disco this may work mb

unkempt canyonBOT
slate swan
#

what the heck

#

this

paper sluice
#

lol

slate swan
#

how to make a bot read message history

#

!d discord.abc.Messageable.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
slate swan
#

nice

stable leaf
#

i have problem with my -balance command
This is the Code:

async def create_balance(user):
    async with bot.db.cursor() as cursor:
        await cursor.execute("INSERT INTO bank VALUES (?, ?, ?, ?)", (0, 100, 500, user.id,))
    await bot.db.commit()
    return


async def get_balance(user):
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT wallet, bank, maxbank, user FROM bank WHERE user = ?", (user.id,))
        data = cursor.fetchone()
        if data is None:
            await create_balance(user)
            return 0, 100, 500
        else:
            wallet, bank, maxbank = data[0], data[1], data[2]
            return wallet, bank, maxbank


@bot.command(aliases=['bal', 'b'], description="View a users balance")
async def balance(ctx, member: discord.Member = None):
    if member == None:
        member = ctx.author
    wallet, bank, maxbank = await get_balance(member)
    embed = discord.Embed(title=f"{member.name}'s Balance")
    embed.add_field(name="Wallet", value=f"`{wallet}`")
    embed.add_field(name="Bank", value=f"`{bank}/{maxbank}`")
    await ctx.send(embed=embed)

And this is the error:

#
Ignoring exception in command balance:
Traceback (most recent call last):
  File "/Users/sgolis/PycharmProjects/Discord_Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/Users/sgolis/PycharmProjects/Discord_Bot/main.py", line 69, in balance
    wallet, bank, maxbank = await get_balance(member)
  File "/Users/sgolis/PycharmProjects/Discord_Bot/main.py", line 97, in get_balance
    wallet, bank, maxbank = data[0], data[1], data[2]
TypeError: 'coroutine' object is not subscriptable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/sgolis/PycharmProjects/Discord_Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/Users/sgolis/PycharmProjects/Discord_Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/Users/sgolis/PycharmProjects/Discord_Bot/venv/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: TypeError: 'coroutine' object is not subscriptable
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine 'Cursor.fetchone' was never awaited
  self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
vocal snow
stable leaf
#

but idk what coroutine is

vocal snow
unkempt canyonBOT
#

Concurrency in Python

Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.

This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.

To call an async function we can either await it, or run it in an event loop which we get from asyncio.

To create a coroutine that can be used with asyncio we need to define a function using the async keyword:

async def main():
    await something_awaitable()

Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function

To run the top level async function from outside the event loop we need to use asyncio.run(), like this:

import asyncio

async def main():
    await something_awaitable()

asyncio.run(main())

Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().

To learn more about asyncio and its use, see the asyncio documentation.

stable leaf
#

ok but how can it fix my problem?

vocal snow
#

read the tag lol

stable leaf
#

ohh

#

i forgot

#

to await the fetchone()

vocal snow
stable leaf
#

sorry

#

my fault

slate swan
#

How to install discord.py the latest version using pip ?

vocal snow
#

unless by latest you're referring to the master branch?

slate swan
#

Too slow.... 😐

slate swan
#

there was some github command

vocal snow
slate swan
vocal snow
#

pip install -U git+https://github.com/Rapptz/discord.py

#

cls

#

where did powershell go 😭

slate swan
#

microsoft made it a paid software now lol

#

Still alive and kicking, just not really as much.... Unless your lucky like me looking after Windows based infrastructure...

#

And it made curious, I thought I was running 2.0 but after the convo just now, I realised I ain't so will do an upgrade later.

#

Is it worth it? Or is 1.7.3 fine to sit on?

#

1.7.3 will anytime stop working..

#

Cheers, better upgrade after work then just so I dont get hit with that.

#

its better to start refactoring your code rn so it won't be a ton of rewrite work for later.

#

Yeh, true, considering I am still pretty much at the beginning too.

#

(ngl, still stuck on my wait_for block) so yeh it won't be a big problem to rewrite πŸ™‚

slate swan
#

Rather than using @fresh banemands.is_owner

#

Uh-

slate swan
unkempt canyonBOT
#

The user IDs that owns the bot. This is similar to owner_id. If this is not set and the application is team based, then it is fetched automatically using application_info(). For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.

New in version 1.3.

slate swan
#

you can if ctx.author.id in bot.owner_ids

slate swan
#

So should I use self.client?

#

I mean owner_id would work in the cog right?

paper sluice
glad cradle
#

like self.client.owner_ids or self.bot.owner_ids

slate swan
#

why do we need cogs πŸ’€

#

i forgor

#
messages = await ctx.channel.history(limit=10, oldest_first=True, after=after_date).flatten() 

can i do dis

chanl = bot.get_channel(id)

mes = await chanl.history(...)
dusky pine
#

you don't need cogs, but it's useful for making your code readable and not making it a 5,000 line mess

sour basalt
slate swan
#

Cogs = easy to manage and clean code

#

Cogs also helps in help commands

#

For category

#

I get this error, but I don't know what it means, can someone help me?

st_charge() takes 1 positional argument but 2 were given
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\pyrogram\dispatcher.py", line 240, in handler_worker
    await handler.callback(self.client, *args)
TypeError: st_charge() takes 1 positional argument but 2 were given```
vocal snow
#

def foo(i):
    return i

foo(1) # fine
foo(1, 2) # passing 2 arguments, not fine
robust fulcrum
#

Which library should i use? Tell me any name

slate swan
#

difflib

#

!d difflib

unkempt canyonBOT
#

Source code: Lib/difflib.py

This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.

visual island
robust fulcrum
visual island
robust fulcrum
vocal snow
#

bruh

visual island
#

what else can it be

slate swan
#

Type of snake

robust fulcrum
#

Oh k

#

It's names weird

vocal snow
#

Bruh

#

It even has lib in its name 😭

slate swan
#

diff -> difference
its also a language/utility

robust fulcrum
slate swan
#

you need to check on the names, not the command object itself.

robust fulcrum
snow trench
tacit horizon
#
async def p(ctx, user : discord.Member == None):
    if user == None:
        user = ctx.author.id```
slate swan
slate swan
robust fulcrum
tacit horizon
robust fulcrum
#
@bot.listen("on_command_error")
async def error_handler(ctx, error):
    comlist = []
    for command in bot.commands:
        comlist.append(command)
    invoked_with = ctx.invoked_with
    matches = difflib.get_close_matches(invoked_with, comlist)
    await ctx.send(f"do you mean {matches}?")

Here is code

slate swan
#

comlist is a list of command objects, it should be a list of command names instead...

vocal snow
unkempt canyonBOT
#

property qualified_name```
Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in `?one two three` the qualified name would be `one two three`.
slate swan
unkempt canyonBOT
#

Do you ever find yourself writing something like this?

>>> squares = []
>>> for n in range(5):
...    squares.append(n ** 2)
[0, 1, 4, 9, 16]

Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:

>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]

List comprehensions also get an if statement:

>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]

For more info, see this pythonforbeginners.com post.

slate swan
#

you would be ```py
[ command.name for command in list_of_command_objects ]

dusky pine
#

I have an odd feeling he's making a help command without subclassing

dusky pine
#

oh yeah i didn't read above sorry

slate swan
#

how can I check if ctx.guild.channel is mentioned in ctx.message.content?

rain olive
#

you likely dont wanna do that

#

instead typehint the argument to discord.TextChannel

slate swan
#

this is parameter right?

rain olive
#

ye

slate swan
#

ok

#

but with this parameter, the channel should be mentioned right?

rain olive
#

yes

shrewd apex
#

not necessarily

#

if u typehint

rain olive
#

id, mention etc

slate swan
#

I can explain for what i need it so u can understand

shrewd apex
#

u can pass channel as Id name mention

#

but yeah u get the idea

slate swan
#

is there a parameter for time?

#

like 10s

#

or 10d 2h 5m

#

I'm trying to create giveaway command

visual island
#

no

dusky pine
#

no, create a Converter yourself

visual island
#

you have to parse it your own

latent sable
#

zbrt

slate swan
#

Ok

vocal snow
slate swan
robust fulcrum
# slate swan you would be ```py [ command.name for command in list_of_command_objects ] ```
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error,CommandNotFound):
        comlist = bot.commands
        comlists = [ command.name for command in comlist ]
        invoked_with = ctx.invoked_with
        matche = difflib.get_close_matches(invoked_with, comlists)
        embefk = discord.Embed(title=f"did you mean?", description=matche,color=discord.Color.yellow())
        embefk.set_thumbnail(url='https://media.discordapp.net/attachments/969254133779558410/997473128395587634/images.png')
        await ctx.send(embed=embefk)

It's returning empty list ;

slate swan
#

"it" could be clearer, cuz you have 3 lists there.

#

which variable?

robust fulcrum
#

Hmm

robust fulcrum
slate swan
#

what variable is giving you an empty list....?

#

comlist = bot.commands
this is an iterable
comlists = [ command.name for command in comlist ]
this is an iterable too
matche = difflib.get_close_matches(invoked_with, comlists)
and this too

which one are you talking about??

robust fulcrum
#

Matche

slate swan
#

print comlists and print invoked_with then see if you a matching string in them or not

vocal snow
#

you might want to adjust the cutoff as well

shrewd apex
#

cutoff=.5-.6

#

works well

robust fulcrum
#

Can you help pls

slate swan
#

How to install d.py 2.0 on replit πŸ’€

robust fulcrum
#

Can I help at dm?

slate swan
#

Yah?

#

sure

paper sluice
#

why not just help here pithink

slate swan
#

privacy :awkward1:

#

can someone help me with a handlers code please

slate swan
paper sluice
hazy oxide
#

error handling?

slate swan
#

if I do !check <word> it checks my txt file for that name then says Found

#

How do I do that

faint sapphire
#
if msg.startswith("val") or msg.startswith("Val") or msg.startswith("VAL"):
```is there a way to apply `.lower()` to this so i dont have to verify each case
slate swan
faint sapphire
slate swan
faint sapphire
#

its startswith cause therell be arguments too btw

#

i mean i can test

#
message.content.startswith.lower() == 'val'
```i hope that works
slate swan
#

ofc cz it's a method not

#

a property

robust fulcrum
#

Guys i need help can anyone?

slate swan
#

so?

robust fulcrum
#
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error,CommandNotFound):
        comlist = bot.commands
        comlists = [ command.name for command in comlist ]
        invoked_with = ctx.invoked_with
        matche = difflib.get_close_matches(invoked_with, comlists)
        if not matche[0]:
            matche = "command not found"
        else:
            matche = matche[0]
        embefk = discord.Embed(title=f"did you mean?", description=matche,color=discord.Color.yellow())
        embefk.set_thumbnail(url='https://media.discordapp.net/attachments/969254133779558410/997473128395587634/images.png')
        await ctx.send(embed=embefk)

It's comand intelligence but it not takes 2 comannds in it's list even i ahve loaded all cogs

slate swan
#

Anything like guild.created_at?

drowsy lotus
#

im tryna get bad apple on discord and all of a sudden i get this, can someone help me?

slate swan
#

2.0?

#

Try .avatar.url

#

It might have the same as 2.0

slate swan
unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a β€œserver” in the official Discord UI.

x == y Checks if two guilds are equal.

x != y Checks if two guilds are not equal.

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
drowsy lotus
slate swan
#

and read the error

drowsy lotus
#

ohh

#

oh and i cant read shit

slate swan
#

I saw

drowsy lotus
#

im just a dumbass with some technology

#

ik theres permission denied

#

but im too damn dumb to Understand

slate swan
paper sluice
# drowsy lotus

you didnt specify the file type and on windows when you have the file opened and then you try to open it in ur code, it raises that error

sour basalt
slate swan
#

how do i make something scan all messages for blacklisted texts and delete them?
for example:

!scan

Bot - 7:39
Found 4 blacklisted texts!
Josh - Bitc
GURLLL - Amogus
GURLLL - Amogus
TanGt - Gay

paper sluice
sour basalt
#

uhm you can make an example ??

paper sluice
#

in python, the function body is not executed until you call the function unlike other languages

def foo():
    print('hello')
# it doesn't print 'hello'
foo() # this prints 'hello'
sour basalt
#

` i = random.randint(0,5)

    switcher={
        0:zero,
        1:uno,
        2:due,
        3:tre,
        4:quattro,
        5:cinque
        }
    func=switcher.get(i)
    return await func()`
#

this not work?

paper sluice
paper sluice
# sour basalt ` i = random.randint(0,5) switcher={ 0:zero, ...

this is the function

  async def cinque():
        file = discord.File("/home/py/Desktop/TelSpin/TelSpinGif/TelSpinYellow.gif")
        e = discord.Embed()

        e.set_image(url=("attachment://TelSpinYellow.gif"))
        await ctx.send(file = file, embed=e)
        return 'cinque'
    
        i = random.randint(0,5)
     
        switcher={
            0:zero,
            1:uno,
            2:due,
            3:tre,
            4:quattro,
            5:cinque
            }
        func=switcher.get(i)
        return await func()

this function is never called so body doesn't get executed, and you did return 'cinque' so any code under that will not execute because return exits the function

paper sluice
slate swan
#

Maybe try os.listdir or something similar

drowsy lotus
#

ohh

#

man i was tryna get bad apple on discord messages

paper sluice
#

!e

import os
print(os.listdir('.'))
unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

['requirements', 'config', 'user_base']
drowsy lotus
#

and now its leading to 1 error left

paper sluice
#

use that if you want to get all files in the directory

slate swan
paper sluice
#

discord

#

discord.py is the name of the file, while importing you remove the .py

slate swan
#

I need a custom bot

vale wing
#

Make one

drowsy lotus
vale wing
#

πŸ˜‰

slate swan
#

ah ok

drowsy lotus
robust fulcrum
#

How can I make a chatbot without ml? In dpy

drowsy lotus
#

thats you exenifix

vale wing
#

Yeah so what

paper sluice
drowsy lotus
vale wing
#

Who tf is gonna make a bot for someone here

drowsy lotus
#

yea

robust fulcrum
drowsy lotus
#

tbh

vale wing
paper sluice
drowsy lotus
#

i have a question for discord bots

slate swan
#

just get on fiverr if you want one duh

drowsy lotus
#

is playing bad apple (music video btw) frame by frame with 15 bots to avoid rate limiting api abuse?

slate swan
#

I'd say so

drowsy lotus
#

FUCK

slate swan
#

it's bypassing the rate limits

#

which is not really recommended at all

drowsy lotus
#

i saved myself from getting banned

#

nice

paper sluice
#

oh 15 bots, i thought 15 fps for some reason

slate swan
#

just use webhooks maybe idk

#

they have better/higher rate limits

drowsy lotus
drowsy lotus
slate swan
#

higher means more messages (edits) per second

drowsy lotus
#

ohh

#

oh and uhh

#

im confused but uh

#

i saw someone post bad apple on discord messages in real time

#

should i report them

slate swan
#

if they respect the rate limits it's fine

#

if they don't they will end up getting rate limited with the time so no need to do anything

drowsy lotus
#

but they said "this is api abuse, however there where no spikes on discord api status"

#

idk what to think at this point

slate swan
#

KEKW a single bot would definitely not affect the overall api status

drowsy lotus
#

15

#

fuxoingt

slate swan
#

still need more power than that

drowsy lotus
#

bots

#

ohh

slate swan
#

but yeah if ya want you can report to discord, don't know if they take any actions on that

drowsy lotus
#

i once reported an underage kid 4 times

#

because they kept making new accounts

#

and keep using vpns

#

and discord cared

#

so maybe they can care about that too

slate swan
#

dunno

drowsy lotus
#

wait

#

can i still do the 15 bot avoid rate limiting doe?

#

on an alt

slate swan
#

that's just bypassing the api rate limits

#

you'll probably end up using the same IP

#

and your ip will just get banned

drowsy lotus
#

FUCK

#

so no vpn?

slate swan
#

bascially what usually happens with bots hosted on replit

#

ips are shared among multiple users

#

they all host their bot, and get the ip banned

drowsy lotus
#

i host my bots with visual studio code

slate swan
#

yeah no you don't

#

you code with it

drowsy lotus
#

no like

slate swan
#

How to create a webhook set it’s avatar and send a message with it via a command

drowsy lotus
#

theres run

slate swan
#

hosting you do on your computer terminal

brave flint
#

XD, hosting with notepad++

#

PROgrammer

slate swan
#

docs probably?

drowsy lotus
#

idk what u on rn

brave flint
slate swan
#

yeah you still don't host on vsc

velvet compass
#

Lets not discuss things that can run into rule 5

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the webhook has.

If the webhook does not have a traditional avatar, `None` is returned. If you want the avatar that a webhook has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.display_avatar "discord.Webhook.display_avatar").
vale wing
#

Is this settable

drowsy lotus
slate swan
velvet compass
#

Bypassing rate limits

drowsy lotus
#

i host it for testing

drowsy lotus
slate swan
#

Well that's what I'm explaining, saying they shouldn't do it

drowsy lotus
#

its not like mao zedong is watching me

vale wing
#

!d discord.Webhook.edit should be

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.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
drowsy lotus
#

if i talk about it

#

its no harm

paper sluice
velvet compass
unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

you can set avatar while creating the webhook cant you

drowsy lotus
paper sluice
#

i think you can do it, but if you want to do it for an existing one you need to edit

vale wing
#

Does it even have a constructor

slate swan
vale wing
#

There's only from_url classmethod

#

And partial

slate swan
#

you can fetch using its ID

slate swan
unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
slate swan
#

what's the thing for on the bot joining the server

drowsy lotus
#

!d help

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
slate swan
slate swan
#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
slate swan
#

i want the bot to get a list of the channels and find something like " general " " lounge " then send the help message

#

it has a guild object

#

!d discord.Guild.channels gives you list of channel objects ( which includes text, voice, stage and category channels ), utilise it

#

You can then use guild.channels to get a list of all channels as objects

unkempt canyonBOT
slate swan
#

Then a loop will help ya to do what you want probably

#

thanks i will look into it

slate swan
cloud dawn
#

Don't recommend using the name

slate swan
#
@bot.command()
async def sudo(ctx,member: discord.Member,*,content):
  await send(content=content, username=member.name, avatar_url=member.avatar.url)

error:

sour basalt
#

raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: spin() takes 1 positional argument but 2 were given

cloud dawn
unkempt canyonBOT
#

property system_channel```
Returns the guild’s channel used for system messages.

If no channel is set, then this returns `None`.
vale wing
cloud dawn
#

!d filter

unkempt canyonBOT
#

filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.

Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.

See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
slate swan
vale wing
#

Sorry I forgor πŸ’€

slate swan
#

what should i use, i can't use ctx ig?

slate swan
#
@bot.command()
async def sudo(ctx,member: discord.Member,*,content):
  await ctx.send(content=content, username=member.name, avatar_url=member.avatar.url)
#

@slate swan

slate swan
#

username and avatar_url and arent valid kwargs

paper sluice
#

send is an instance method, not classmethod, so you can't use it like that

cloud dawn
#

!d discord.TextChannel.create_webhook

unkempt canyonBOT
#

await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a webhook for this channel.

Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.

Changed in version 1.1: Added the `reason` keyword-only parameter.
cloud dawn
#

I recommend either keeping it in cache for an hour or something or delete it instantly

slate swan
#
@<commands/bot>.command(name="<webhook>")
async def _webhook(<self>, ctx: commands.Context) -> None:
  webhook = await ctx.channel.create_webhook(name="uwu")
  await webhook.send("uwu", avatar_url="<>")
cloud dawn
#

πŸ₯„

slate swan
#

🧁

slate swan
onyx surge
#

can anyone help?

slate swan
#

great

slate swan
#

sended

paper sluice
#

you are make the string lowercase then comparing it with a capitalized string

onyx surge
#

how to fix it

paper sluice
#

lower makes everything lowercase, so if i do 'Ryuga'.lower() it becomes 'ryuga'
so if the message contains 'Hello' then you apply lower to it, it becomes 'hello' but then you are checking if 'hello' == 'Hello' which it is not

onyx surge
#

huh

#

how to fix it

paper sluice
#

make the right side lowercase as well

slate swan
#

!e
print("hello".lower())

unkempt canyonBOT
#

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

hello
sour basalt
#

https://mystb.in/JonEnclosureProposed.python
``2022-07-15 17:20:32 ERROR discord.ext.commands.bot Ignoring exception in command spin
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 987, in invoke
await self.prepare(ctx)
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 904, in prepare
await self._parse_arguments(ctx)
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 811, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 663, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: bot is a required argument that is missing.

i added ,bot but i get this

slate swan
#

Compare with what you have to the right of your ==

wanton cipher
#

Hey all, I know this is probably a stupid question, but... Is there a way I can combine these two and have them in just a single class?```py
class VoteDropdown(disnake.ui.Select):
def init(self, test: list):
options = [disnake.SelectOption(label=entry.get('label'), description=entry.get('desc'), emoji=entry.get('emoji'), value=entry.get('user').id) for entry in test if entry.get('user') is not None]
super().init(
placeholder="Select one",
min_values=1,
max_values=1,
options=options
)

async def callback(self, interaction: disnake.MessageInteraction):
    ...

class VoteView(disnake.ui.View):
message: Optional[disnake.Message]

def __init__(self, users, **options):
    super().__init__(**options)
    self.votes = {}
    self.add_item(
        VoteDropdown(users)
    )

async def on_timeout(self) -> None:
    ...
slate swan
#
@bot.command(name="sudo")
async def _sudo(ctx,member: discord.Member,*,content):
  await ctx.message.delete()
  e = discord.Embed(title=f"Sudo By {ctx.author.name}", description=f"Ivoker: {ctx.author.name} ({ctx.author.id}) \n \nInvoked on: {member.name} ({member.id}) \n \nContent: ||{content}||",color=discord.Colour.dark_theme())
  e.set_footer(text="Please view content on your own risk.")
  webhook = await ctx.channel.create_webhook(name=member.name)
  await webhook.send(content,avatar_url=member.avatar.url)

  chn = bot.fetch_channel(997525777161650306)
  await chn.send(embed=e)
#

webhook works fine but the message isn't sent

maiden fable
#

await bot.fetch_channel()

cloud dawn
# wanton cipher Hey all, I know this is probably a stupid question, but... Is there a way I can ...

You asked for it ```py
class VoteView(disnake.ui.View):
message: Optional[disnake.Message]

def __init__(self, users, **options):
    super().__init__(**options)
    self.votes = {}

    self.votedrop = disnake.ui.Select(
        placeholder="Select one",
        min_values=1,
        max_values=1,
        options=[disnake.SelectOption(label=entry.get('label'), description=entry.get('desc'), emoji=entry.get('emoji'), value=entry.get('user').id) for entry in users if entry.get('user') is not None]))
    self.votedrop.callback = self.vote_callback
    
    
    self.add_item(
        self.votedrop
    )
    
async def vote_callback(self, interaction: disnake.MessageInteraction):
    ...

async def on_timeout(self) -> None:
    ...
#

Also min and max values are default 1

wanton cipher
cloud dawn
wanton cipher
#

oh

#

welp, I guess we both about to find out xD

cloud dawn
#

I'm debating if self.votedrop needs a () or not

#

With myself.

wanton cipher
#

I don't think so...?

#

I'm not the best with classes, but to my understanding it shouldn't

cloud dawn
#

I mean you could make the Select class in a nice function looks kinda ugly right now.

wanton cipher
#

maybe

#

the main reason I wanted to merge the two was because I thought if they in the same class, I won't have two classes with only one use case

cloud dawn
#

I think classes like that look way better.

wanton cipher
#

honestly...

#

I am starting to think that too xD

#

but thank you for the help either way!

cloud dawn
#

It depends if you got like a good Select create function it can be better if you got a short selection.

#

But imagine in some cases selection could be really complicated.

wanton cipher
#

ig...

#

I'm still new to all the newer stuff

#

so I'm still trying to figure out how to use them all

slate swan
#

new to the newer stuff

wanton cipher
#

mhm, sense has been made

cloud dawn
#

Same I just made a ui a week ago dw.

slate swan
#

,

wanton cipher
#

xD

slate swan
cloud dawn
#

Because people smol brain

slate swan
#

like us

wanton cipher
#

damb

cloud dawn
#

Our brains may be smaller but they work more efficient.

wanton cipher
#

we reduced the size for more storage for other non important stuff brainmon

wanton cipher
#

mhm

#

same

cloud dawn
#

"Please remember this ..." forgets

wanton cipher
#

mhm

#

πŸ“ 

slate swan
#

!ot

unkempt canyonBOT
paper sluice
cloud dawn
#

Ryuga is always ot

placid skiff
slate swan
#

hi guys how to add cooldown to discord command reset in one time every day? for example 00:00 ECT

placid skiff
#

!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/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
warped mirage
#
@client.command()
@commands.has_permissions(ban_members = True)
async def ban(interaction: discord.Interaction, member: discord.Member, *, reason: str):
        try:
            await  member.send(f"You have been banned in {interaction.guild} for {reason}, Would you like to appeal? Join this server: ")
            await  interaction.response.send_message(f"{member.name} has been banned for {reason}")
        except:
            await interaction.reply(f"The user you are trying to ban has DM's closed", ephemeral = True)
        if not member:
            await interaction.send("Please specify a username")
        await member.ban(reason=reason)``` any ideas?
#

when i do !ban it doesnt return the message

#

like please specify a username

slate swan
#

how to make my bot auto restart at one time a day? (00:00 ECT)

slate swan
#

!pypi apscheduler

unkempt canyonBOT
slate swan
#

why would anyone want it in the first place.....

#

To keep their uptime low πŸ’€

#

...

glad cradle
#

or maybe coz he's using replit

warped mirage
#

Can someone help me ****

cloud dawn
#

This will also raise missing required argument first.

slate swan
#

TypeError: send() got an unexpected keyword argument 'end' is this error fixable?

#

await ctx.send(timer, end="\r")

paper sluice
#

well, you can't do end= in send

sick birch
#

I believe \r is the carriage return?

#

Discord doesn't respect such characters, so just leave that part out entirely

slate swan
#

ok

#

so i remove it

sick birch
#

That's correct

slate swan
#

ok

#

and something else

#

I made a converter which converts seconds to days, hours, minutes and seconds but when i type the command, the bot just spams the message and thats the way it counts. Is there a way to edit that message so the bot doesnt spam ?

#

I think this can be solved with fetch

unkempt canyonBOT
#

await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
sick birch
#

Also you're probably going to get ratelimited

slate swan
#

awkward is it just me who's too lazy to make a time converter

#

!pip time-str i just use this

unkempt canyonBOT
sick birch
#

Something like this might be better: <t:1657908120:R>

slate swan
#

unix timestamps best

#

Does anyone know how I do it so when I run the ban command (or kick, whatever), the user can't ban the bot from the server?

sick birch
slate swan
vale wing
#

No user can ban themselves

sick birch
slate swan
#

if they use a bot and the bot doesn't have an if preventing it, they can ban themselves yes

slate swan
cloud dawn
#

1

vale wing
#

Bot can't ban itself as well

#

Only other bot probably

slate swan
#

well here i go try it to show

vale wing
#

Idk what you are doing anyway

cloud dawn
vale wing
#

The what

cloud dawn
#

Well not technically

vale wing
#

What about roles hierarchy

#

You can't ban users that have higher or same top role with you

slate swan
smoky marsh
#

recommended places to get started?

sick birch
smoky marsh
cloud dawn
# vale wing What about roles hierarchy
@commands.command()
@commands.has_permissions(ban_members=True)
async def ban_member(self, ctx: Context, member: Member) -> None:
    if ctx.bot.user.id == member.id:
        return await ctx.guild.leave()

    ...
``` lmao
vale wing
#

Lmao

livid hedge
#

hello, how can I use discord components (such as Button etc...) in discord.py?

paper sluice
livid hedge
#

how can I get the repo?

paper sluice
#

python -m pip install git+https://github.com/rapptz/discord.py

livid hedge
#

isn't it unofficial?

paper sluice
#

no.

livid hedge
#

ok

#

ty

#

now how can I make sure that I am using the 2.0 version?
import discord

paper sluice
#

you can do python -m pip show discord.py in ur terminal to see which version you have installed

#

in code you can do discord.__version__ for the same

livid hedge
#

it's the correct one, thank you

#

and now, where do I find documentation to finally start to code with components?

paper sluice
glad cradle
paper sluice
#

it is, but i dont think the ui part is

#

stuff related to buttons and menus arent for now

livid hedge
#

it basically explains why I came asking here

glad cradle
livid hedge
#

thank you, Ryuga

sick birch
#

!d discord.ui.Button for example

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
paper sluice
#

its under interaction ok, my bad

livid hedge
#

just found something like that

warped mirage
cloud dawn
warped mirage
cloud dawn
#

Yes.

warped mirage
#

Ok

livid hedge
# unkempt canyon

but where should I add that?
example

await ctx.send("Message") #where to add the button instance?
paper sluice
slate swan
#

what is the diffeence between client and botp

paper sluice
#

you dont have prefix commands in discord.Client

slate swan
paper sluice
sick birch
slate swan
#

i seee

sick birch
#

Keep your usecase in mind though. For interaction bots that don't work with prefix commands, discord.Client will work

livid hedge
torn sail
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

torn sail
slate swan
#

I have function which converts seconds into days, hours, minutes and seconds and then i want the bot to countdown that time but I dont want to use while loop

#

Any ideas?

livid hedge
#

you have to create a task

#

but you have to use a while loop

#

( as I know )

#

Is there a way to use nested buttons callbacks?

channel = bot.get_channel(int(id))
        
        view = View()
        button = Button(label="Open ticket", style=discord.ButtonStyle.green, emoji="🎟️")
        async def button_callback(interaction):
            category = await ctx.guild.create_category(f"ticket {ctx.author.name}")
            await category.set_permissions(ctx.author, view_channel=True)
            await category.set_permissions(get(ctx.guild.roles, id=996392936197599243), view_channel=True)
            await category.set_permissions(ctx.guild.get_role(ctx.guild.id), view_channel=False)
            channel = await ctx.guild.create_text_channel("chat", category=category, sync_permissions=True)
            embed=discord.Embed(title="Ticket ", description="Welcome, this is a private chat with founders.")
            embed.add_field(name="You can ask us everything", value="Enjoy!", inline=True)

            quit_view = View()
            quit_button = Button(label="Close ticket", style=discord.ButtonStyle.red, emoji="🎟️")
            async def button_callback(interaction):
                print("program doesnt reach this part of code")
                category = interaction.response.message.channel
                if "ticket" in category.name.lower():
                    for ch in category.channels:
                        try:
                            await ch.delete()
                        except AttributeError:
                            pass
                    await category.delete()

            quit_view.add_item(quit_button)
            await channel.send(embed=embed, view=view)

        view.add_item(button)
        embed=discord.Embed(title="Contact us")
        embed.add_field(name="You can privately talk to us", value="Ask anything you need to!", inline=False)
        await channel.send(embed=embed, view=view)
        await ctx.send(f"Message successfully sent. {channel.mention}")
paper sluice
#

why do you want nested callbacks?

livid hedge
#

because one button creates a channel where the bot writes another message in. That new message has a button to delete that channel

paper sluice
#

then make the callback of the new button delete the message

livid hedge
#

button1 -> creates -> channel "A" -> bot adds a message that has button2 into channel "A"
button2 -> deletes channel "A"

#

that's the flow i want to get

#

basically i just need the second callback to work

paper sluice
#

like this:

def cllback_button1(...):
      ...
      view = discord.ui.View().add_item(new-button)
      interaction.response.send_message(..., view=view)
def callback_new_button(...):
    # ur code
livid hedge
#

and how can I refer to code to specific go to that func?

paper sluice
livid hedge
#

yeah

paper sluice
#

to the view and send it

livid hedge
#

but I have to do it inside the first callback

paper sluice
#

why?

livid hedge
#

the first callback creates the possibility to run the second one

paper sluice
#

yea but that doesn't mean you have to make the callback there

livid hedge
#

okay

paper sluice
#

you can just make two buttons, then in the callback of the first button send the new button when you want

livid hedge
#

i dont know the syntax to do that

#

I am using
async def button_callback(interaction):

#

i never specified that the button callback function has to be that one

#

it does it automatically because it's inside the command

#

is there a way to do something like that? button = Button(label="button" ecc, callback=myFunc)

paper sluice
#
def callback_button1(...):
      ...
      view = discord.ui.View().add_item(button2) # you add the new button to the view and send it
      interaction.response.send_message(..., view=view)

def callback_new_button(...):
    # ur code

button1 = discord.ui.Button(...)
button1.callback = callback_button1

button2 = discord.ui.Button(...)
button2.callback = callback_new_button

like this

livid hedge
#

perfect

#

exactly what I was looking for

#

thanks

paper sluice
#

πŸ‘

livid hedge
#

TypeError: create_text_channel() got an unexpected keyword argument 'sync_permissions' always worked for me. Not working in the new version

vocal snow
#

Oh wait, it seems to have been removed altogether

livid hedge
#

so how can I sync permission?

vocal snow
#

If you don't provide any overwrites it will sync automatically

livid hedge
#

okay lemme check

#

you are right, it syncs automatically

#

thanks

vocal fossil
#

hey guys'

#

who can fix it?

#

import discord
import time
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix ='!', help_command=None, case_insensitive=True, intents=intents)

@bot.event
async def on_member_join(member):
channel = member.guild.get_channel("970649770555244584")
embed = discord.Embed(color=0x4a3d9a)
embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
embed.set_image(url="https://newgitlab.elaztek.com/NewHorizon-Development/discord-bots/Leha/-/raw/master/res/welcome.gif""")
await channel.send(embed=embed)

bot.run('')

sour basalt
#

error for cooldown command??
i want sent when cooldown expires

idle sparrow
#

πŸ‘€

#

Whats popping here

slate swan
#
    async def claim(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        embed = nextcord.Embed(title="This ticket has been claimed.", color=nextcord.Color.blurple())
        embed.add_field(name = "e", value = f"e")
        await interaction.response.send_message(f"<@{interaction.user.id}>" , embed=embed)```

How do i change the label name upon interaction (DM ME IF YOU KNOW )
fallow mauve
#

inside an on_message listener how do i detect if the message is sent in dms

slate swan
fallow mauve
vocal snow
#

!d discord.Message.guild

unkempt canyonBOT
slate swan
#

πŸ₯Ί

vocal snow
#

Or, check the type.of message.channel

fallow mauve
#

pls explain that one

slate swan
#
    async def claim(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        embed = nextcord.Embed(title="This ticket has been claimed.", color=nextcord.Color.blurple())
        embed.add_field(name = "e", value = f"e")
        await interaction.response.send_message(f"<@{interaction.user.id}>" , embed=embed)```

How do i change the label name upon interaction (DM ME IF YOU KNOW )
vocal snow
#

isinstance(message.channel, DMChannel)

fallow mauve
slate swan
#
if message.guild is None:
    ...
if not message.guild:
    ...
if isinstance(message.channel, DMChannel):
    ...
#

many ways

vocal snow
unkempt canyonBOT
#

class discord.DMChannel```
Represents a Discord direct message channel.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the channel’s hash.

str(x) Returns a string representation of the channel
fallow mauve
#

ok

slate swan
#

just use the module object to access the class lol

fallow mauve
#

sry i havent used python in like 3 months...

fallow mauve
#

or no ctx

slate swan
#

no context

fallow mauve
#

then it would be await message.channel.send("???") right?

#

@slate swan

slate swan
#

yes

fallow mauve
#

thx, it works

slate swan
#

AttributeError: 'NoneType' object has no attribute 'edit' why i get this error?

#

await msg2.edit(embed=winning)

#

as you can see i am trying to edit an embed that has been already edited

pallid meadow
#

πŸ₯š

fallow mauve
#

how do i make it so that the bot has a set message made, but then waits for 2 seconds, and while its waiting on discord it shows "botName is typing..." and then sends it after 2 seconds

#

this is inside commands.Cog.listener btw

austere vale
#

can someone help me with this?

sick birch
#

E.g if they deleted this message:

#

_ _

austere vale
#

oh okay thank you

cloud dawn
sick birch
#

No. but discord won't let you have that as a field

cloud dawn
#

It does

#

launching his debug bot

winter gull
#

I have to check if a message sent is in a specific channel, i know how to do this using on_message function and checking if it falls under a specific channel but that seems inefficient.

visual island
#

you can use a decorator for more advanced thing

sleek gyro
#

Is it possible to have an on_message inside a slash command?
something like this:

visual island
#

no

#

you would have to use wait_for()

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
sleek gyro
#

so, the on_message would be outside the command and wait for the command to start?

visual island
#

also no

#

use the wait_for() to wait for a message to be sent

#

open the link and see the examples

sleek gyro
#

this is the whole code (the cog at least) and what is not working is everything after "say something"

#

yes, i am using the command, the bot responds "say something" and nothing more after i type other things

#

oh, i think i forgot the @commands.Cog.listener()

#

let me see

#

basically, i want it so my command is used to start receiving the messages people type, and if the message is what i want, the bot responds to them

#

i dont know if on_message is supposed to be inside the command or not, the guy before said that it doesn't need to be outside

patent lark
#

on_message in a command????

sleek gyro
#

it worked, thank you!

#

the examples of wait_for made me think that it should be used inside an on_message event

vale wing
#

No

#

Why is this dead for 6+ hours

slate swan
#

ive moved to python general and networking so i dont go ot with sarth and ash or sarth or others anymore πŸ˜”

#

imagine

austere vale
#

does anyone know where i can learn how to have my bot display different embeds depending on whether the user reacts with ◀️or▢️?

slate swan
slate swan
#

ot

slate swan
sleek gyro
# austere vale does anyone know where i can learn how to have my bot display different embeds d...

you have to make the embed in a function outside the class where your command is in, and return the embed, then in the command you use embed=Name_of_your_function(), the same in the buttons
example:

def embed(page):
    embed = discord.Embed(title='title',description='description',color=discord.Colour.blue())
    return embed

class Buttons(discord.ui.View):
    def __init__(self, page:int):
        self.page=page
    
    #YOUR BUTTON
    self.page+=1 
    await interaction.response.edit_message(embed=embed(self.page))
class Command(commands.Cog):


    #YOUR COMMAND
        page= 0
        view = Butttons()
        await interaction.response.send_message(embed=embed(page), view=view)
austere vale
#

i'll try to use this, thank you

slate swan
#

overkill

#

and bad

sleek gyro
#

thats how a friend told me to do in my code, is there a better way to do this? i would like to know

slate swan
#

that's not even a paginator

#

and that embed function makes it extra hellish

sleek gyro
#

when the person press the button i make it so the embed func is called again with new arguments

slate swan
#

what

#

doesnt work that way

#

you are simply stating an example of sending a view within a slash command

sleek gyro
#

like:
page = 0
the command makes the embed in page 0, when i press the button page+=1 and embed=embed(page)

slate swan
#

what your like: states and the example states is completely differeny, no offence

#

different*
phone smh

sleek gyro
#

maybe i explained it poorly then, but how i explained in the like: is it still bad(the command)?

slate swan
#

yes.

#

no offence

sleek gyro
#

can you explain how to make it better?

slate swan
#

I'm on my phone rn soooo, too much work ps typos, I'll either mention later

sleek gyro
#

its ok, thank you!

slate swan
#

imma need some help

#
def setup(client):
   await client.add_cog(image(client))
shrewd apex
unkempt canyonBOT
#

A library to create a discord paginator. Supports pagination with Discords Buttons feature and reactions.

slate swan
#

error, but i did it without and it didnt work

shrewd apex
slate swan
#

tysm simple and ez man

#

fr means alot

#

uh

#

new error ommand raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url_as'

#

code py @commands.command(name = "wanted") @commands.cooldown(1, 10, commands.BucketType.user) async def wanted(self,ctx,Member: discord.Member = None): if Member == None: Member = ctx.author wanted = Image.open("wanted.jpeg") asset = Member.avatar_url_as(size = 128) data = BytesIO(await asset.read()) pfp = Image.open(data) pfp = pfp.resize((241,238)) wanted.paste(pfp, (106,210)) wanted.save("profile.png") await ctx.reply(file= discord.File("profile.png"),mention_author = False)

bitter depot
#

Iirc .avatar.url_as(...)

slate swan
#

oh

slate swan
bitter depot
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
bitter depot
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
slate swan
bitter depot
#

It's None when you don't have a custom pfp

#

And you have a default pfp so it's None

slate swan
#

im trying to do it for other ppl not just me

bitter depot
#

You just need to check whether it's None first

slate swan
#

can you help me?

bitter depot
#

Altho you resize later anyway so don't really see the point in that line

slate swan
#

yeah

#

so what do i make it?

#

@bitter depot

kind trellis
#

Anyone have any idea on how I can install slash commands? I have already tried python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py

slate swan
#
    async def claim(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        embed = nextcord.Embed(title="This ticket has been claimed.", color=nextcord.Color.blurple())
        embed.add_field(name = "e", value = f"e")
        await interaction.response.send_message(f"<@{interaction.user.id}>" , embed=embed)```

How do i change the label name upon interaction (DM ME IF YOU KNOW )
robust fulcrum
#

Guys i ahve loaded a cog called helpinfo.py and the comand in it is not working what can be the reason?

robust fulcrum
#

I made a error handler and it eat up errro

#

But i still have error can you help

robust fulcrum
#

How to fix it?

vocal snow
#

fix what

robust fulcrum
#

The error

#

The error is in the image

vocal snow
#

send the full error

dusky pine
#

supposed to be json.loads(f.read())

vocal snow
#

should use json.load instead

robust fulcrum
#

Oh

robust fulcrum
dusky pine
robust fulcrum
#

Hmm

robust fulcrum
#

It's like this is it wrong?

shrewd apex
#

u forgot a , somewhere

#

at end of a Line

robust fulcrum
#

I not put , anywhere

#

Is it important to put ,?

shrewd apex
#

0-0

#

absolutely

slate swan
#
    async def claim(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        embed = nextcord.Embed(title="This ticket has been claimed.", color=nextcord.Color.blurple())
        embed.add_field(name = "e", value = f"e")
        await interaction.response.send_message(f"<@{interaction.user.id}>" , embed=embed)```

How do i change the label name upon interaction (DM ME IF YOU KNOW )
vale wing
shell wing
#

So i want to make a basic command, the work flow :

when we mention a user while running the cmd:
bot sends "ok"

when we dont mention a user while running the cmd:
bot send ("not ok")```
can anyone tell me how to make it ?
#

like how to make a check in the arguments of the cmd

sick panther
west elk
#

hello guys hope you are good. Can anyone tell where to learn about making discord bots

shell wing
#

tysm

#

?tag resources

novel apexBOT
#

This is not a Modmail thread.

sick panther
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

west elk
#

and its project

shell wing
#

https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
https://automatetheboringstuff.com/ (for complete beginners to programming)
http://greenteapress.com/wp/think-python-2e/ (another decent book)
See also:
http://www.codeabbey.com/ (exercises for beginners)
https://realpython.com/ (good articles on specific topics)
https://learnxinyminutes.com/docs/python3/ (cheatsheet)

#

here

sick panther
west elk
#

ok thanks for helping me i will check it out

sick panther
#

No problem, good luck πŸ‘

west elk
#

you have made brother

slate swan
#

"you have made brother" awkward1

shell wing
#

we cant mention users in the embed title right ?

shell wing
#

cool

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UndefinedTableError: relation "suggestionchannel" does not exist

#

does anyone know how to fix it?

sick panther
winter gull
odd mango
#

quick question, how often does tasks.loop() runs when no time kwarg is provided

visual island
visual island
odd mango
#

no, just @ionic gateks.loop()

#

f

visual island
#

infinite times/sec

odd mango
#

i am asking the interval

#

like how often will it run

#

every 1 sec?

visual island
#

no

odd mango
swift pumice
#

hi guys

#

i have a question

#

how can i do to my bot that it will send every 120 minutes a message?

visual island
odd mango
#

cool sure

odd mango
swift pumice
#

wait

#

it says task is not defindes

visual island
swift pumice
#
async def test(ctx):
    await ctx.send("hi")
    tasks.loop(minutes=120) ```
#

would this work?

odd mango
#

from discord.ext import tasks

swift pumice
#

oh ok

swift pumice
odd mango
odd mango
#

np

odd mango
visual island
odd mango
#

☠️

swift pumice
#

@odd mango ```@tasks.loop(minutes=120)
async def bump(ctx):
channel = bot.get_channel(992511703155740712)
await channel.send("@fair kite bump")

@bot.event
async def on_ready():
bump.start()
```this will work right?

slate swan
#

this works but i'll suggest to add a await bot.wait_until_ready() in the first line of the bump coro

odd mango
#

^^^

slate swan
#

it waits for the bot to fill its cache before executing the next line

odd mango
#

its the event name to be looped

slate swan
#

savvy pro

odd mango
#

it will start as soon as your bot starts

swift pumice
#

what

odd mango
swift pumice
#

yes

#

wait

visual island
odd mango
swift pumice
#

so when it starts the @ionic gateks.loop will start

#

?

swift pumice
odd mango
#

when your bot starts the loop will start

#

so no ctx is needed there

swift pumice
#

okay

slate swan
#

more like no Context will be passed there since its a task, Context is meant for commands.

odd mango
#

yes

swift pumice
#

ok, i removed it

odd mango
swift pumice
#

google

#

i removed it

#

AttributeError: 'NoneType' object has no attribute 'send'

#

what

slate swan
#

did you add the bot.wait_until_ready()?

swift pumice
#
@tasks.loop(minutes=1)
async def bump():
    channel = bot.get_channel(992511703155740712)
    await channel.send("@fair kite bump")

bump.start()```
swift pumice
#

wait where do i add that?

#

at bump.start?

odd mango
#

bot wont get the cached channel until its ready

slate swan
#

1st line of the bump coro

swift pumice
odd mango
#
@tasks.loop(minutes=120)
async def bump():
    await bot.wait_until_ready()

    channel = bot.get_channel(992511703155740712)
    await channel.send("@fair kite bump")

bump.start()```
swift pumice
#

thank you

#

btw, what means coro?

slate swan
#

an async function

odd mango
#

coroutine

swift pumice
#

okay

slate swan
#
async def foo(): ...
``` `foo` is a coro/coroutine here
swift pumice
#

thanks

robust fulcrum
#

Guys any comamnd idea for me?

#

||Not much hard || πŸ₯΅

slate swan
#

make a command handler glasses

robust fulcrum
visual island
robust fulcrum
#

Whats this?

odd mango
#

server info

slate swan
#

serverinfo and stats command.

odd mango
#

member count creation date and all

slate swan
#

for some stats parts you may need a db, its optional tho

odd mango
#

i bet asher would use dict

visual island
robust fulcrum
#

Hmmmm

#

I'll try

odd mango
#

or

#

make an economy bot if you're bored

#

😳

robust fulcrum
#

😫

slate swan
#

economy bots are boring. just rip-offs of dank memer.

odd mango
robust fulcrum
#

Rpg bot?

sour basalt
#

raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice

The above exception was the direct cause of the following exception:

how install discord.py 2.0 [voice]

robust fulcrum
#

My brain would blast

odd mango
#

its pain but if you want to then okay

sour basalt
#

please

odd mango
robust fulcrum
slate swan
#

!pip pynacl

unkempt canyonBOT
#

Python binding to the Networking and Cryptography (NaCl) library

odd mango
#

they asked how to install dpy after knowing they need pynacl

#

πŸ§‘β€πŸ¦―

slate swan
#
$ git clone https://github.com/Rapptz/discord.py
$ cd discord.py
$ python3 -m pip install -U .[voice]
odd mango
slate swan
#

nope

odd mango
#

oof

slate swan
odd mango
#

sarth how do i get db latency

slate swan
#

just calculate the time taken to execute an query

odd mango
#

hm ok

sour basalt
robust fulcrum
#

I not helped tho

winter gull
#

Also if may I ask is there any list of errors that a command can give and i can put them

#

Like in the @function.error

sour basalt
#

import PyNaCl
ModuleNotFoundError: No module named 'PyNaCl'

odd mango
#

after that pip install -U .[voice]

sour basalt
#

not work

shrewd apex
slate swan
shrewd apex
#

u can I think

#

wait a sec lemme check

slate swan
#

you would have to clone and install to install the master voice support

sour basalt
swift pumice
#

is making a bump reminder hard?

shrewd apex
#

nah

swift pumice
#

what is the skill level?

#

easy med or hard?

shrewd apex
#

intermediate

swift pumice
#

oh okay

shrewd apex
#

u just need bit of logic and problem solving ability with python

swift pumice
#

okay

slate swan
maiden fable
slate swan
#

AnyaWTF what if someone doesnt ping at exact 2hr time

shrewd apex
swift pumice
shrewd apex
#

sarth just gonna make another 1000 line SQL for them then

sour basalt
swift pumice
slate swan
#

cache yes

shrewd apex
shrewd apex
slate swan
#

pichu_v20 cries in mongodb

maiden fable
#

Just use text files dude

shrewd apex
#

today's ot channel

maiden fable
#

Or .cache files

shrewd apex
#

json-derulo

maiden fable
#

Indeed

shrewd apex
#

made my morning brighter

slate swan
#

use sqlite3 in memory

swift pumice
#

@rugged tulip

maiden fable
swift pumice
#

@rugged tulip

slate swan
#

πŸ₯‚ just dont make bots

shrewd apex
#

ikr just study chemistry

swift pumice
shrewd apex
#

organic i am gonna die πŸ‘€ πŸ’€

swift pumice
#

@rugged tulip

shrewd apex
#

y are u pinging

inland venture
#

I need help

#

so basically, i created multiple files that has commands without prefix, embed and stuff separetely. idk why but only one of my file would work

hot basin
#

I have a bot that is in three servers when i wrote this code

@client.command(name='serverids', aliases=['si'])
async def serverids(ctx):
    for guild in client.guilds:
        await ctx.send(guild.id)```
I got those three server's ids all of them
but just like this i wanted to add these ids into database(mysql) with a command so i wrote this
```py
@client.command()
async def insertTables(ctx):
    for guildid in client.guilds:

        cur.execute(f"INSERT INTO Servers(serverid,sub,subdate) VALUES({guildid.id},0,CURDATE());") 
        conn.commit()```
but i got one of the server's id three times and saved in three rows in data base instead of getting three server's id what is the problem?
swift pumice
#
async def on_message(ctx):
    if ctx.content() == "/bump":
        asyncio.sleep(1)
        await("<@&984101784719069184> you can bump again")
        await bot.process_commands()
    else:
        await bot.process_commands()
``` hi guys why isnt this working? nothing in the console
#

nvm

#

error is: File "e:\Users\elias\PycharmProjects\Python irgendwas\venv\discord bot\bot.py", line 717, in on_message
if ctx.content() == "/bump":
TypeError: 'str' object is not callable

swift pumice
honest shoal
#

also just use the command decorator

honest shoal
swift pumice
#

oh

swift pumice
#
async def on_message(ctx):
    if ctx.content == "/bump":
        asyncio.sleep(1)
        print(asyncio.sleep)
        await("<@&984101784719069184> you can bump again")
        await bot.process_commands()
    else:
        await bot.process_commands()```so like this?
honest shoal
swift pumice
#

oh okay

visual island
hot basin
#

I mean it should loop through client.guilds and add them into db one by one

swift pumice
#

@honest shoal ```@bot.command()
async def bumpreminder(ctx):
if ctx.content == "/bump":
asyncio.sleep(1)
print(asyncio.sleep)
await("<@&984101784719069184> you can bump again")