#discord-bots

1 messages · Page 191 of 1

pseudo saffron
#

but somehow it dont work than

#

the button

#
@bot.event
async def on_ready():
    await bot.setup_hook(main())``` setup hook like this ?
chilly dove
#
class MyBot(commands.Bot):
    async def setup_hook(self) -> None:
        # load cogs here

like this you make a subclass of commands.Bot then override setup_hook

clear elm
#

can anyone help? ^

pseudo saffron
#
class MyBot(commands.Bot):
    async def setup_hook(self) -> None:
      for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')``` so like this
chilly dove
#

yes

#

then you use the MyBot when creating a instance instead of commands.Bot

pseudo saffron
#
bot = MyBot(prefix, intents = intents, owner_id = owner_id,case_insensitive = True)```
chilly dove
#

yup now your cogs will auto load

pseudo saffron
chilly dove
#

you created a new bot file right? can you sent that file entirely

pseudo saffron
#
import discord
from discord.ext import commands,tasks
import discord.ui
import json


with open("configuration.json", "r") as config: 
    data = json.load(config)
    token = data["token"]
    prefix = data["prefix"]
    owner_id = data["owner_id"]
        

intents = discord.Intents.all()
bot = commands.Bot(prefix, intents = intents, owner_id = owner_id,case_insensitive = True)
bot.remove_command('help')
    
# Define a simple View that gives us a counter button
class Counter(discord.ui.View):

    # Define the actual button
    # When pressed, this increments the number displayed until it hits 5.
    # When it hits 5, the counter button is disabled and it turns green.
    # note: The name of the function does not matter to the library
    @discord.ui.button(label='0', style=discord.ButtonStyle.red)
    async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
        number = int(button.label) if button.label else 0
        if number + 1 >= 5:
            button.style = discord.ButtonStyle.green
            button.disabled = True
        button.label = str(number + 1)

        # Make sure to update the message with our updated selves
        await interaction.response.edit_message(view=self)


@bot.command()
async def counter(ctx: commands.Context):
    """Starts a counter for pressing."""
    await ctx.send('Press!', view=Counter())
    
    
    
    
bot.run(token)```
#

but even when i use the but it says interaction failed

chilly dove
#

works fine to me can you send the output of pip freeze

pseudo saffron
#

1 sec

#
aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
beautifulsoup4==4.11.2
bs4==0.0.1
certifi==2022.12.7
charset-normalizer==2.1.1
cookies-discord-components==3.0.0
discord.py==2.1.0
exchange==0.3
ffmpeg-python==0.2.0
frozenlist==1.3.3
future==0.18.3
idna==3.4
imageio-ffmpeg==0.4.8
multidict==6.0.4
numpy==1.24.1
pycord==0.1.1
requests==2.28.2
soupsieve==2.3.2.post1
urllib3==1.26.14
yarl==1.8.2```
chilly dove
#

pycord might be interacting with discordpy

pseudo saffron
#

how to uninstall with pip

chilly dove
#

pip uninstall pycord

pseudo saffron
#

so i try again

pseudo saffron
ionic garden
#

so, rn the way i'm implementing string arguments that can only be some strings (like only 'a' or 'b' ) is with typing.Literal
but i've recently learned that using enum works as well
is it a matter of personal preference, or is one generally better than the other?

chilly dove
pseudo saffron
#

whats venv

chilly dove
#

so in your project folder you can run python -m venv .venv which will create a fresh venv that will only contain basic packages then you can activate it and install what you need

#

its isolated to that project

clear elm
chilly dove
#

yes it will be like a fresh install of python

#

it will make sure there isnt anything interfering with discordpy

pseudo saffron
fading marlin
pseudo saffron
chilly dove
#

depending on what terminal you are using .\.venv\Scripts\Activate.ps1 that would activate it for powershell

#

.bat for command prompt

#

then you install like any other package

pseudo saffron
#

i dont understand

chilly dove
#

python -m venv .venv this creates a venv in the current directory named .venv which will be like a isolated python install
then you can activate that isolated install by using the command .\.venv\Scripts\Activate{.ps1,.bat} then you can install like normal using pip install discord.py

pseudo saffron
#

yes it worked

#

so now i only installed the libarys i needed

chilly dove
#

yes only ones you need specific to that bot

pseudo saffron
#

yes

#

should i try again the button ?

chilly dove
#

yes make sure that you are in the venv when you start the bot

pseudo saffron
#

how to make this sure

#

never used venv before it completely new to me

chilly dove
#

at the start of your terminal you should see (.venv) that signifies you are in a venv named .venv

pseudo saffron
#

my vsc says this

chilly dove
#

that should be fine yes

pseudo saffron
#

still not work

chilly dove
#

well assuming the latest code above is the same then nothing else i can think of would cause that

pseudo saffron
chilly dove
#

ran basically the same code as above and it works

pseudo saffron
#

for me it says interaction failed

chilly dove
#

did you add the bot with app_commands scope?

naive briar
#

That is not necessary if you're using buttons and not slash commands

pseudo saffron
chilly dove
#

well apparently you dont need it but in the url generator you can select applications.commands along side bot which will enable app commands when you invite

pseudo saffron
#

i gave my bot admin on my server

#

so he still needs ?

chilly dove
#

i think the scope is separate from permissions

pseudo saffron
#

i try 1 sec

#

it works

#

just 1 question

#

can i use buttons in dms ?

#

@chilly dove

chilly dove
#

yes you can

ionic garden
#

what if there's multiple choices?

#

would dpy know how to handle that?

fading marlin
#

!d discord.app_commands.choices they're working on commands.Choice too iirc

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
fading marlin
ionic garden
#

from what i see, how it works is a decorator followed by a type annotation in an argument

#

if i want two argument choices, do i just put...two decorators?

naive briar
#

You can put them in the same deco

#

It's like describe

#

I guess

ionic garden
#

could i have an example?

naive briar
#

There's an example in the docs

ionic garden
#

oh uh what i mean is like

#

if i want two arguments, and each is a choice

#

not one argument with two choices

pseudo saffron
#

@chilly dove how can i add multiple buttons to text

naive briar
#
@app_commands.choices(
    fruits=[
        Choice(name='apple', value=1),
        Choice(name='banana', value=2),
        Choice(name='cherry', value=3),
    ],
    animals=[
        Choice(name='cat', value=4),
        Choice(name='birb', value=5)
    ]
)

? pithink

chilly dove
pseudo saffron
#

@chilly dove

class spieler1game(discord.ui.View):
    global spieler1
    @discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
    async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'SCHERE'
    @discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
    async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'STEIN'
    @discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
    async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'PAPIER'

class spieler2game(discord.ui.View):
    global spieler2
    @discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
    async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler2 = 'SCHERE'
    @discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
    async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler2 = 'STEIN'
    @discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
    async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
        spiler2 = 'PAPIER'

@bot.command()
async def rps(ctx,member:discord.Member):
    global spieler1,spieler2
    await ctx.send(f'{ctx.message.author.name} hat eine runde Schere Stein Papier gegen {member.name} gestartet')
    await ctx.message.author.send('Wähle aus',view=spieler1game())
    await bot.wait_for("button_click",check=lambda message: message.author == ctx.author)
    await member.send('Wähle aus',view=spieler2game())
    await bot.wait_for("button_click",check=lambda message: message.author == member)```
#

i mad it like this

naive briar
#

Why are you using wait_for

#

The view already handles every items

pseudo saffron
#

so the code waits for input

naive briar
#

Just use view.wait then

#

!d discord.ui.View.wait

unkempt canyonBOT
#

await wait()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits until the view has finished interacting.

A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop "discord.ui.View.stop") is called or it times out.
pseudo saffron
#

where i need to use it

naive briar
#

In your button callback

#

Wait, no

#

After you sent the message with that view

#

And call self.stop in your button callback to make it stop waiting

ionic garden
naive briar
#

Slash commands, that why it's in app_commands module

pseudo saffron
# naive briar And call `self.stop` in your button callback to make it stop waiting
class spieler1game(discord.ui.View):
    global spieler1
    @discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
    async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'SCHERE'
        self.stop()
    @discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
    async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'STEIN'
        self.stop()
    @discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
    async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'PAPIER'
        self.stop()

class spieler2game(discord.ui.View):
    global spieler2
    @discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
    async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler2 = 'SCHERE'
        self.stop()
    @discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
    async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler2 = 'STEIN'
        self.stop()
    @discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
    async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
        spiler2 = 'PAPIER'
        self.stop()

@bot.command()
async def rps(ctx,member:discord.Member):
    global spieler1,spieler2
    await ctx.send(f'{ctx.message.author.name} hat eine runde Schere Stein Papier gegen {member.name} gestartet')
    await ctx.message.author.send('Wähle aus',view=spieler1game())
    await discord.ui.view.wait()
    await member.send('Wähle aus',view=spieler2game())
    await discord.ui.view.wait()```
ionic garden
#

fff

pseudo saffron
#

so like this

naive briar
#

No

#

You need an instance

pseudo saffron
#

what for an instance

#

what u mean with instance

#

sorry first time coding these buttons

#

and its kinda confusing

#

@naive briar

ionic garden
#

i have a discord.Member argument
how do i make it so it defaults to the sender of the message

pseudo saffron
#
class spieler1game(discord.ui.View):
    global spieler1
    @discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
    async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'SCHERE'
        self.stop()
    @discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
    async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'STEIN'
        self.stop()
    @discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
    async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler1 = 'PAPIER'
        self.stop()

class spieler2game(discord.ui.View):
    global spieler2
    @discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
    async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler2 = 'SCHERE'
        self.stop()
    @discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
    async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
        spieler2 = 'STEIN'
        self.stop()
    @discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
    async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
        spiler2 = 'PAPIER'
        self.stop()

@bot.command()
async def rps(ctx,member:discord.Member):
    global spieler1,spieler2
    await ctx.send(f'{ctx.message.author.name} hat eine runde Schere Stein Papier gegen {member.name} gestartet')
    await ctx.message.author.send('Wähle aus',view=spieler1game())
    await member.send('Wähle aus',view=spieler2game())```
interaction is failed can someone help
pseudo saffron
ionic garden
#

cool

chilly dove
ionic garden
#

wdym normal commands?

chilly dove
#

non app commands

ionic garden
#

oh i'm using hybrid commands

chilly dove
#

ya should work there too

#

member: discord.Member = commands.Author

#

that way it will be the author if none is specified

pseudo saffron
#

cuz can you help me on the buttons

#

its confuses me

pseudo saffron
chilly dove
#

not sure what your end goal with that view is but generally you should try to keep the logic within the view rather then some in the view and some outside

pseudo saffron
chilly dove
#

you should be using bot vars then if you want it global to your bot or if you need it just for command context you can set it on the view

pseudo saffron
#

yeah i forgot about them

#

so i changed the global vars to bot vats

#

@chilly dove

chilly dove
#

its giving you a interaction failed because you are not responding to the interaction after clicking the button

pseudo saffron
#

so should i send a text

#

with interaction.response ?

#

or something like this

chilly dove
#

in the button callback interaction: discord.Interaction has a .response attribute that you must use to respond rather then sending a message through the normal way

pseudo saffron
#

yes i know

#

the interaction.response.send_message

#

can i respond that way ?

chilly dove
#

yes that will send a message in response to the button click

pseudo saffron
#

and how can i wait for a button press

#

i read about wait bot.wait_for("button_click")

torn sail
#

You can change @bot.event to @bot.listen(). Event overrides the place where commands are processed

chilly dove
#

its because bot.process_commands is overridden from the built in event

pseudo saffron
chilly dove
pseudo saffron
#

in the docs its called like

#

discord.ui.view.wait

#

and in callback u use self.stop

pseudo saffron
shrewd fjord
#

Hewo guys :)

pseudo saffron
#

hey

shrewd fjord
#

Any problems?

chilly dove
#

view=spieler1game() you are creating the view instance here then passing in to send directly without setting it to anything

shrewd fjord
#

Ahh like any questions?

chilly dove
#

you need the instance to wait for that view

shrewd fjord
#

All knows regex, me don't, bro someone give regex docs 🗿

#

I am going to master regex today

chilly dove
#

if you are doing a game like that tho you should look into robodanny and how it handles prompting 2 players to play minigames

pseudo saffron
#

i have an plan

#

i just wait for a message of the bot

#

and send a message on response

shrewd fjord
#

Maybe tell me the prob?

#

Hm cool

pseudo saffron
pseudo saffron
shrewd fjord
torn sail
#

is there a way to set app command default permissions on the parent command of a group cog?

slate swan
#

for some reason my bot is not responding to anything

#

even tho I didnt change anything no commands seem to work

naive briar
slate swan
naive briar
#

What does doesnt work supposed to explain

#

No one can know your problem without seeing the code

slate swan
#

oh

#

it seems to work

naive briar
#

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

slate swan
#

It was a on_message funtion that I forgot to disable

torn sail
#

So @event overrides the internal on_message event and that is where commands get processed but listeners don’t override the internal event

clear elm
shrewd fjord
#

Your current code should work tho

raw quail
#

sup guys, anyone tried to make ai image generate bot via python?

slate swan
#

anyone online?

#
AttributeError: 'Intents' object has no attribute 'message_content' at line 22```
vocal snow
#

python -m pip install -U discord.py

slate swan
#

Okay

#

yeah that solved the issue but now it says that I am not passing the correct token

#

LoginFailure Error

naive briar
#

Then that token is invalid 🤷

slate swan
#

but it isnt

naive briar
#

Is it a user token

slate swan
#

copied from the discord dev portal and made a secret key to hold it

#

this one

#

even after resetting the token the issue still remain

#

here is the code and lengthy issue

naive briar
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

intents = Intents.default() is giving an error

#

undefined name Intents

#

changing this also didnt help

#

client = MyClient(command_prefix="!", intents=intents)

naive briar
slate swan
#

yes

naive briar
slate swan
#

actually I was searching if I have enabled privileged initents in developer portal or not

#

yup I had not enabled them

#

is it necessary that a bot works in a server only?

glossy flame
#

Kakarott606

fresh fern
#

help needed

#

AttributeError: 'Interaction' object has no attribute 'author'

#

embed = discord.Embed(title="MrWelcome's Help Menu", color=discord.Color.dark_red()) embed.add_field(name="Prefix", value="**Ping me for prefix**", inline=False) embed.add_field(name="Utility", value="Utility Commands", inline=False) embed.add_field(name="Fun and Games", value="Mini Games", inline=False) embed.add_field(name="Bot Setup", value="How to setup bot", inline=False) embed.set_footer(text=f"Requested By {ctx.author}")

#

this is a cog

vocal snow
unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
vocal snow
#

check the available attributes there ^

fresh fern
#

thanks :)

#

hey @vocal snow

#

there is no attribute to get the username

charred radish
fresh fern
#

like iam#0979

charred radish
#

hmm I’m not sure maybe it is interaction.user

fresh fern
#

no its not

#

tried it

charred radish
#

works for me..

fresh fern
#

oh

#

wait

#

i get this member 'user' of 'Interaction' objects

charred radish
fresh fern
#

embed.set_footer(text=f"Requested By {discord.Interaction.user}")

charred radish
#

slash commands?

fresh fern
#

yes

charred radish
#

Mhm wait

#

Error?

fresh fern
#

nope

#

get this member 'user' of 'Interaction' objects

charred radish
fresh fern
#

check dm

charred radish
#

mhm

charred radish
#

Use this instead

fresh fern
#

ohh

charred radish
#

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

fresh fern
#

dmed

naive briar
#

And send the whole error

#

!d discord.Interaction.user

unkempt canyonBOT
raw quail
#
class Test(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

        
    def get_data(self, stock, start_date, end_date):
        for retries in range(0,5):
            try:
                df = pdr.get_data_yahoo(self, stock, start=start_date, end=end_date)
                return df['Adj Close']
            except:
                print("[ERROR]")
                print ('yfinance JSONDecodeError, retyring: ' + str(retries))
                print ('ticker: ' + stock + 'start: ' + str(start_date) + ';end: ' + str(end_date) + ';')
        return []
    
    @commands.command(name="chart", help="Return stock performance over a period of 2 years time")
    async def chart(self, ctx, quo="msft"):

        now = datetime.now()

        old_year = now.year - 2

        current_date = datetime.today().strftime('%Y-%m-%d')

        current_date_arr = current_date.split('-')
        old_date = str(old_year) + '-' + current_date_arr[1] + '-' + current_date_arr[2]

        data = get_data(self, quo, old_date, current_date)
        # clear the graph before creating one
        plt.clf()
        
        ticker = quo.upper()

        # plot the graph and store it in a variable
        plot = data.plot(title=f"{ticker}\n Stock Price over 2 years")
        fig = plot.get_figure()
        filename = 'output.png'
        fig.savefig(filename)
        await ctx.send(file=discord.File(filename))
        
async def setup(bot):
    await bot.add_cog(Test(bot))

I'm trying to use the 'Cog' function, but I'm studying because I'm not familiar with 'class'. Is the code not working because I didn't type 'self' properly in the code above?

naive briar
#

What is the problem

raw quail
#

It doesn't work without any error code. if i don't use 'Cog' function, it's working well

#

I think it's because i didn't properly place 'self' in 'class', but i can't find the cause even though i've been watching basic python lecture videos for 2 hours. :((

naive briar
#

Did you load the extension

raw quail
#

yeah

fresh fern
#

did u do client.add_cog()

#

@raw quail

raw quail
#

yeahh

fresh fern
#

dont do async def setup

#

like

`
code...
code...

client.add_cog()

code....
code....
`

raw quail
#

ohh

#
async def load():
    for filename in os.listdir('cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')
            print(f"{filename} Load Successful")

async def main():
    async with bot:
        await load()
        await bot.start(TOKEN)

i using like this but other cogs are working well.

fresh fern
#

lemme see

raw quail
#

yeah

fresh fern
#

i do like this

#

lemme show u wait

raw quail
#

i think i should put 'self' but it seems that there is a part missing somewhere. so i'm checking.

fresh fern
#

from cogs.Ban.ban import ban from cogs.Ban.mrban import mrban from cogs.Clear.clear import clear from cogs.Clear.mrclear import mrclear from cogs.Help.help import help from cogs.Help.mrhelp import mrhelp from cogs.Kick.kick import kick from cogs.Kick.mrkick import mrkick from cogs.Ping.mrping import mrping from cogs.Ping.ping import ping from cogs.Roll.roll import roll from cogs.Roll.mrroll import mrroll from cogs.eBall.eball import eightball from cogs.eBall.mr8ball import mreightball from cogs.Unban.unban import unban from cogs.Unban.mrunban import mrunban from cogs.ToF.tof import tof from cogs.ToF.mrtof import mrtof

#

and then

raw quail
#

ohhhh

fresh fern
#

client.add_cog(ping(client)) client.add_cog(mrping(client)) client.add_cog(help(client)) client.add_cog(mrhelp(client)) client.add_cog(clear(client)) client.add_cog(mrclear(client)) client.add_cog(kick(client)) client.add_cog(mrkick(client)) client.add_cog(ban(client)) client.add_cog(mrban(client)) client.add_cog(roll(client)) client.add_cog(mrroll(client)) client.add_cog(eightball(client)) client.add_cog(mreightball(client)) client.add_cog(unban(client)) client.add_cog(mrunban(client)) client.add_cog(tof(client)) client.add_cog(mrtof(client))

naive briar
#

That defeats the whole point of extensions

#

Do not do this

fresh fern
#

me?

#

i think this is ez

#

so......😅

naive briar
fresh fern
#

ohh

#

so whats the difference

#

b/w both the ways

slate swan
fresh fern
#

hot reload?

slate swan
#

add the changes in the cog to bot without restarting it

fresh fern
#

OHHH

#

thats pretty useful

#

how to

#

do

#

this

slate swan
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
slate swan
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

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

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
fresh fern
#

damn

#

thanks

brisk oar
slate swan
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
slate swan
#

check examples/views folder in the discord.py GitHub repo

naive umbra
#

What would be the best way to dynamically configure a guild (including categories, channels, roles, all permisions, etc..)?

#

I currently have a config.yml file similar to @unkempt canyon's src code, but the configs are static, i need a dynamic configuraiton

slate swan
#

you;d need a simple database

naive umbra
# slate swan you;d need a simple database

it's kind of a mix, i dont need a database because the permissions are statically defined in a config file, similar to what roles, channels and categories that should exist, i just need to dynamically create and configure them

sand trout
#

Umm making bots in github will be smooth to use?

sand trout
#

We can making bots in github right? (Discord bots)

naive umbra
sand trout
#

Ye

naive umbra
#

i mean, sure but you have to pay

sand trout
#

💀 anyway to make bots for free? ( im ready to code though )

naive umbra
#

making bots are free?

#

hosting them might necessarily not be free

sand trout
#

Uh crep

naive umbra
#

i mean, i have a vps for $0.97 per month which is where i host my bots

#

its next to free

#

so why cant you just pay for a cheap vps?

sand trout
#

I just cant cuz in my country we dont have paypal ;-;

naive umbra
sand trout
#

Credit/dual currency debit cards wont come to help cuz ma parents wont help ;-;

mossy shadow
#

Just use github pages as a host 💀

sand trout
#

Oo

naive umbra
mossy shadow
naive umbra
#

discord bots needs a server, github pages is not one

mossy shadow
#

Serverless hosts sucky wacky

naive umbra
#

if you're gonna troll do it somewhere else

#

this is not the place for it

naive umbra
#

otherwise you can just self host

#

which is probably the best option if done correctly in contrast to other "free" solutions

sand trout
#

Oo

gentle nova
#

Hello, if i want put cooldown on command , how should i do it ?

await interaction.nextcord.ext.commands.Cooldown(5) (f' Slow down boy , this command limitless wait 5mins')
``` Something like this or not even close ?
dense coral
#

How can I do a button cooldown?

dense coral
gentle nova
#

how do with interactions

#

im not using ctx only interactions

young dagger
#

What does this mean? [WARNING ] discord.gateway: Can't keep up, shard ID None websocket is 43.7s behind.

dense coral
primal token
dense coral
young dagger
primal token
#

You should identify blocking io in your code

primal token
# dense coral Who's know?

!d discord.ui.View.interaction_check | Not sure if there's and abstraction for button cooldowns but you can probably make your own

unkempt canyonBOT
#

await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
dense coral
#

Thanks!

hushed galleon
young dagger
#

How can I fix this error? discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Int64' object has no attribute 'id'

async def revoke(ctx, case_id: int):```
naive briar
#

!traceback

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

young dagger
#

@naive briar

@client.command(name='revoke')
@commands.guild_only()
async def revoke(ctx, case_id: int):
    # Check if the command was used in the correct channel
    if ctx.channel.id == 745832741135712386 and any(
            role.id in [710241598348329080] for role in ctx.author.roles):
        collections = [warnings_collection, kicks_collection, bans_collection, mutes_collection]
        entries = [await collection.find_one({"case_id": case_id}) for collection in collections]

        entry = next((entry for entry in entries if entry is not None), None)
        if entry is not None:
            collection = collections[entries.index(entry)]
            if collection == bans_collection:
                banned_user = await ctx.guild.fetch_ban(entry['user_id'])
                await ctx.guild.unban(banned_user)```
#

I think the issue is:

banned_user = await ctx.guild.fetch_ban(entry['user_id'])
                await ctx.guild.unban(banned_user)```
vocal snow
#

fetch_ban takes an abc.Snowflake as per the docs

#

you're passing Int64

#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id, *, type=...)```
Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

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

hash(x) Returns the object’s hash.
vocal snow
#

you can pass the id to this, and then pass this to fetch_ban

young dagger
slate swan
#

why are you even trying to fetch the ban?

young dagger
slate swan
#

yes a discord.Object should work

light violet
#

How do i send a modal in a prefix cmd with ctx

tribal horizon
#

Is it possible to create Slash commands with Discord.py?

sick birch
young dagger
#

Unresolved attribute reference 'display_avatar' for class 'Object'

avatar_url = user.display_avatar.url```
#

You can't display the avatar of a user that is not in the guild?

tribal horizon
hushed galleon
young dagger
hushed galleon
hushed galleon
young dagger
chilly dove
gilded cedar
#

i want to make my discord bot send random images from folder but stack overflow confuses me a lot

chilly dove
#

there is no need for the object tho you just use the id

young dagger
chilly dove
#

get and fetch user takes one positional argument an id thats all you need

young dagger
#

@chilly dove Do you mean like this?

chilly dove
#

assuming entry['user_id'] returns a int of the user id yes

#

the user is usually cached tho so you should try get_user first

hushed galleon
#

if the user they're fetching is banned (as implied by their previous snippet), they probably wouldnt be cached

slate swan
smoky sinew
#

it's only for buttons and other UI things

quasi thorn
#

guys I'm getting started with bots and I don't get what I have to do with intents

smoky sinew
#

if you don't subscribe, discord will never notify your bot of that

quasi thorn
#

do I need to pass intents to the instance of the client?

smoky sinew
#

yes, there are privileged intents which you need to apply for if you are in over 100 servers or if you are under 100 servers you can just enable them in the developer portal

quasi thorn
#

mhmh

smoky sinew
#

there are also unprivileged intents which you do not have to apply for

#

you make a discord.Intents object and pass it to your client/bot

#

to enable all unprivileged intents, you can just do discord.Intents.default()

quasi thorn
#
intents = discord.Intents.default()
client = discord.Client(intents)

TypeError: Client.__init__() takes 1 positional argument but 2 were given

smoky sinew
#

it's a key word argument

#

so you need to do intents = intents

quasi thorn
#

ah

#

got it to work

#

ty

smoky sinew
#

no problem

foggy pond
#

how similar is the discord.py library to base python. Ive seen some code for discord bots and it looks like a whole new language. is this really the case?

#

i guess what im asking is how much of my current python knowlage would i use if i were to learn discord.py and make a bot with it.

hushed galleon
#

its mostly objects, decorators, typehints, and at minimum basic knowledge of async/await

#

also fundamental python stuff

keen junco
#

need help

#

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

@bot.command(name='play', help='Plays a song from YouTube')
async def play(ctx, url: str):
# Connect to voice channel
voice = await ctx.author.voice.channel.connect()

# Play audio from the URL
player = await voice.create_ytdl_player(url)
player.start()

bot.run('not telling you')

#

isnt working

chilly dove
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
quasi thorn
#

guys I pip installed discord-py-slash-command-4.2.1 but still can't import discord_slash

#

is that not the right module?

chilly dove
#

discord-py-slash-command is before v2 of discordpy

#

you shouldn't be using it

quasi thorn
#

ah I see

#

what should I use for slash commands then?

chilly dove
smoky sinew
#

how would i go about making a category system where i can assign a certain category to each command independent of its cog and then replace the cog help with category help?

#

if that made any sense

steep wedge
#

how do i add channel permissions for specific users

#

(not roles)

gusty flax
gusty flax
smoky sinew
#

and i want to make a help command that filters by category

ionic garden
#

is discord going to phase out prefixed commands in the future?

sick birch
ionic garden
#

how?

#

commands.command seems to work just like it did last time i checked

slate swan
# ionic garden is discord going to phase out prefixed commands in the future?

they are trying to do that indirectly

  • you can see the slash menu automatically popping up when you use a common prefix like ! ? etc
  • message_content intents are strictly unavailable for bots who don't have an actual use for it , things like prefix commands and snipe commands are not one of them...
  • slash commands provide features like autocompletes, choices and max_length etc which a prefix command never can (yet another reason to use slash)
#

it's not like they can just stop you from using prefix commands, but it is what it is

#

yo sarth can you show me an example with wait_for, like asking for name or something

#

ofc

#
ctx: commands.Context
client: commands.Bot/discord.Client

# getting input

await ctx.send("type your name")

def predicate(msg):
    if msg.author.id == ctx.author.id:
    # compare your condition for the message
      return True
    # the first message that will match condition and return True will be the value of `response`

response = await client.wait_for("message", check=predicate)

await ctx.send(f"hello {response.content}")
#

wait_for will take the event name with on_ removed

#

can you not do it all in one command? without defining a 2nd function

#

a lambda works just fine

sick birch
#

You can put it in a lambda if it's relatively simple

slate swan
#
check = lambda msg: msg.author == ctx.author
sick birch
#

if your check does complex logic you might want to consider extracting it out into it's own function

slate swan
#

What does the check do exactly? I just want to accept user input for multiple statements

#

i wanted to write comments for explaining so used a normal function

slate swan
#

yes

slate swan
sick birch
smoky sinew
slate swan
#
client.command()
async def name(ctx: discord.Context) -> None:
    await ctx.send("What's your name?")
    check = lambda msg: msg.author == ctx.author
    response = await client.wait_for("message", check=check)
    await ctx.send(f"Your name is {response.content}")

Something like this?

#

yep that should work

slate swan
smoky sinew
#

at the end of the function

slate swan
slate swan
slate swan
#

you'll have to reassign the variable for a new input ( i.e use wait_for again)

tawny junco
#

How does one use reactions as buttons in embeds for pagination?

#

Like when click on a reaction, it changes the page

slate swan
#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

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

Responds to this interaction by editing the original message of a component or modal interaction.
gusty flax
smoky sinew
#

i've explained everything to it

tawny junco
gusty flax
#

Do u mean an autocomplete function

ionic garden
smoky sinew
hushed galleon
slate swan
#

!d discord.ext.commands.command

unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
slate swan
#

the **attrs adds the provided attribute to your commands.Command class, you could use that maybe

hushed galleon
#

those attrs are passed to the constructor, not just assigned as attributes

#

there is an extras parameter you could use instead of the command subclassing, but the extras stuff feels like a hack

slate swan
#

the Command class is not slotted, so in theory assigning the category manually can work as well

gusty flax
ionic garden
#

so they're just going to nerf them & be done with it?

sick birch
smoky sinew
gusty flax
# smoky sinew

Alright, so u can make help a group and have a subcommand for all those things.

slate swan
#

@slate swan How do you do buttons that never timeout, like infinitely clickable by everyone

sick birch
#

Pass in timeout=None to the View

smoky sinew
#

i think there is an easier way

slate swan
sick birch
#

Why don't you want to subclass View?

slate swan
sick birch
#

I don't see how an if statement affects your ability to subclass something

slate swan
#

So I have if statements that decide whether an embed field is added or not, and I'm not sure how I'd do it within the subclass

sick birch
#

You pass required state down the "tree", so to speak

#

The root starting at your command callback and your leaves ending up at your individual component classes

slate swan
#

could you show me some psuedocode?

smoky sinew
#

like this maybe

slate swan
#

Don't think so?

smoky sinew
#

why not?

#

there is no difference between instantiating a subclass and instantiating View directly

slate swan
#

@sick birch ?

sick birch
smoky sinew
#

i know

#

¯_(ツ)_/¯

static holly
#

Good evening, I would like to create a command to make a kind of image gallery. I would like when members type the command they can attach an image with a title and description. and that everything is sent as an embed. I would like to know if this is possible. THANKS

static holly
smoky sinew
#

it's not possible to have multiple images within an embed, i don't think

static holly
#

i search a tutorial ...

sick birch
#

@slate swan

class MyView(ui.View):
  def __init__(self, response: str) -> None:
    super().__init__(...)
    self.response = response
  @ui.button(...)
  async def my_button_callback(self, interaction: discord.Interaction, _) -> None:
    await interaction.response.send_message(self.response)

@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
  view = MyView("Hello, world!")
  await ctx.send(..., view=view)

Here's an example of passing state down

slate swan
smoky sinew
sick birch
slate swan
#

my fault

slate swan
static holly
#

when you say users manuever around

slate swan
smoky sinew
sick birch
smoky sinew
#

if self is in scope

static holly
smoky sinew
#

you wouldn't be able to use it in the decorator

static holly
#

is there any tutorial for this?

slate swan
smoky sinew
#

it's not really advanced, you can do it in 30-35 lines of code maybe

smoky sinew
slate swan
static holly
#

I am a beginner

smoky sinew
#

i'll write it right now as an example

slate swan
# smoky sinew how so?

you need to create multiple embeds ```py
embed1 = discord.Embed(title="same title",url="same url")
embed1.set_image(...)
embed2 = discord.Embed(title="same title",url="same url")
embed2.set_image(...)

await send(embeds=[embed1, embed2])

#

that's how twitter embeds work

smoky sinew
#

yes but it was in one embed

slate swan
#

it will be in one embed....

slate swan
#

ill show an example, waitup

slate swan
sick birch
#

Probably

static holly
#

I don't think it's in my capacity to do that after all. shame

smoky sinew
# slate swan I mean one I did was 100 lines
class PaginatedView(discord.ui.View):
    def __init__(self, messages, index = 0):
        self.messages = messages
        self.index = 0
    
    @discord.ui.button(label = "Next")
    async def next(self, interaction, button):
        if index not in range(len(self.messages)):
            return
        
        index += 1
        await interaction.message.edit(messages[index])

await ctx.send(messages[0], view = PaginatedView(messages, 0))

here is a simple pagination example, it may be incorrect but you get the point

#

only 12 lines

slate swan
# sick birch Probably

How can I pass my variables within the command to the class? add them as self to the class then args to the command?

sick birch
#

That's what I showed you in the example

smoky sinew
#

you use self.response to access it

slate swan
smoky sinew
#

ok

#

fine

slate swan
#

yesir

#

respect

#

im on ubuntu rn got arch on my laptop

#

@sick birch what does self.stop() do?

sick birch
#

Stops listening for inputs

slate swan
#

thanks

smoky sinew
#

yes

slate swan
#

ty

#

hi guys :)

smoky sinew
#

hello

#

what's up

fading marlin
#

hi

unborn bluff
#

Hi c:

tawny junco
#

What I want is, instead of using the ui buttons, use reactions to control the page instead. For example

smoky sinew
#

you can use discord.ext.menus for that

#

what's wrong with buttons though?

fading marlin
#

buttons are a much better ux than reactions

smoky sinew
#

i agree

tawny junco
smoky sinew
#

you should use buttons though

tawny junco
smoky sinew
#

buttons do the same thing though

slate swan
smoky sinew
#

they're quicker and they're faster to send (reaction ratelimits)

slate swan
fading marlin
slate swan
#

!d discord.ui.Button the emoji kwarg

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.
smoky sinew
#

@tawny junco

tawny junco
# slate swan buttons work with emojis too...

But then there's a big box around the emoji. I think the single reaction emoji looks best for what I'm trying to do. Don't get me wrong, I use buttons for another embed. This time I wanna use an emoji

#

Also this is for learning experience. If i don't like it I'll just remove it

slate swan
#

I'll suggest discord-ext-menus

#

or make your own custom paginator

#

it will involve wait_fors for reaction_add/remove event

fading marlin
#

Reaction-based pagination is also considerably harder to make than a simple button pagination

smoky sinew
#

i have suggested ext.menus

tawny junco
tawny junco
fading marlin
#

Fair enough ¯_(ツ)_/¯

smoky sinew
#

how do i disable a button from another method inside the view?

slate swan
#

!d discord.ui.View.children

unkempt canyonBOT
slate swan
#

this will give you all components in the view, check your button and disable it

#

or self.button_callback.disabled = True should work too

#

im not too sure of this one

tawny junco
#

The bin emoji! However mine won't be a bin

#

Will my reaction look like that too? 🤔

fading marlin
#

Yes

slate swan
#

but nvm this is buttons

smoky sinew
#

you're just making a button to delete the message?

tawny junco
#

Noo

smoky sinew
#

so a reaction button then

#

then it isn't the same

tawny junco
#

It's for pagination

naive briar
#

There can be more than 1 reaction my friend

tawny junco
#

But it's only gonna be 1 emoji

#

I have a bot that translates using google translate's api. I want a single reaction button to show pronunciation. That's all

#

I would basically flip to the pronunciation page

#

Is what I imagine

smoky sinew
#

and then flip back?

tawny junco
#

Yes

fading marlin
#

!d discord.Client.wait_for and Message.add_reaction is what you're probably looking for then

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.11)"). 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.11)") 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.11)") 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**...
tawny junco
#

It works with embeds right?

naive briar
#

Any

fading marlin
#

Sure

tawny junco
#

I see

#

Was just about to pip install menus too lol. I'll check this out first

smoky sinew
#

it's pip install discord-ext-menus

#
def set_index(self, index: int):
    if not 0 <= index < len(self.embeds):
        return
        
    discord.utils.get(self.children, custom_id = "previous").disabled = (index == 0)
    discord.utils.get(self.children, custom_id = "next").disabled = (index == len(self.embeds) - 1)
    self.index = index

the buttons won't be disabled and i know discord.utils.get returns the correct button and the conditions are correct

naive briar
#

You're looping twice btw

#

Just use normal for-loop

smoky sinew
#

i know

#

it doesn't matter, there are only 3 children to be looped over

fading marlin
smoky sinew
#

yeah but im updating the message right after

#

wait nvm

#

i forgot to put view = self so it was still using the original view

smoky sinew
#

anyone have any tips to make this look cleaner?

#

it's currently used like this:

paginator = Paginator(embeds)
await paginator.start(ctx)
slate swan
#

What’s the recommended way to exit a function, like if a condition is met exit out of the function and don’t continue

slate swan
sick birch
#

Question for those that are regulars in this channel: what sort of common pitfalls or gotchas do you see discord bot developers stumble with? My current list includes:

  • Message content intent
  • Bots not responding to commands
    I'd like to be able to expand this 🙂
smoky sinew
#

following old/outdated youtube tutorials

#

removing the default help command instead of just subclassing it

fading marlin
#

doing anything in on_ready

sick birch
#

Oh, if any of you want to help with any of these mentioned issues I have oppurtunities open (see #dev-contrib ) 🙂

slate swan
#

difference between object types and instances, pretty common mistake people here make imo

slate swan
tawny junco
#

so the wait_for command only ends and goes to the new line when the check is True?

gusty flax
slate swan
#

it timeouts with an TimeoutError exception

gusty flax
slate swan
#

!d discord.Client.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.11)"). 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.11)") 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.11)") 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**...
sick birch
lament depotBOT
tawny junco
#

Is it safe to do a while loop?

slate swan
#

there's nothing specifically much wrong with that

tawny junco
#

Like

while True:
    wait_for ... 
slate swan
#

since thats the only way you'll do within the command

tawny junco
#

So I assume after the event is complete it would loop and reset any specified timeout time right?

slate swan
#

indeed

smoky sinew
slate swan
#

makes sense

#

classes in class just feels weird lol

smoky sinew
#

is it possible for a bot to get an emoji from a server they're not in

#

other than using the discord cdn

#

i want to steal the python discord online and offline emojis

#

!server

unkempt canyonBOT
#
Server Information

Created: <t:1483877013:R>
Roles: 99
Member status: status_online 42,091 status_offline 328,082

Members: 370,173

Helpers: 148
Moderation Team: 36
Admins: 13
Directors: 3
Contributors: 46
Leads: 12

Channels: 250

Category: 30
Forum: 3
News: 10
Staff: 71
Stage_Voice: 1
Text: 128
Voice: 7

slate swan
#

!d discord.PartialEmoji.read uses the cdn but its pretty much what you need

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.11)") object.
smoky sinew
#

how do i get the partialemoji

#

oh i can probably get it from a converter

#

apparently not

slate swan
#

!d discord.PartialEmoji.from_str

unkempt canyonBOT
#

classmethod from_str(value)```
Converts a Discord string representation of an emoji to a [`PartialEmoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialEmoji "discord.PartialEmoji").

The formats accepted are...
smoky sinew
#

i get partial emoji is not a custom emoji

slate swan
#

did you pass in the escaped form?

smoky sinew
#

470326266625785866

#

i passed in this

#

do i pass in the full thing?

slate swan
#

yessir

smoky sinew
#

ok

#

how do i escape it? whenever i type it in it just becomes the emoji name

slate swan
#

you can provide it without the <>

#

:name:id

smoky sinew
#

ok

slate swan
#

*name:id

slate swan
smoky sinew
#

now i get an error reading it

#

wrong paste

#

don't know how to paste stuff from this terminal tbh

slate swan
#

this is not a common error hm

smoky sinew
#
    @commands.is_owner()
    @commands.command(help = "Steal an emoji from another server.")
    async def stealemoji(self, ctx: commands.Context, emoji):
        emoji = discord.PartialEmoji.from_str(emoji)
        print(emoji)

        await ctx.guild.create_custom_emoji(
            name = emoji.name,
            image = await emoji.read()
        )
golden portal
#

you could just typehint your emoji argument with discord.PartialEmoji instead of that

#

that error happened because you're using from_str, so there isnt a connection state provided, the partial emoji converter should give you the state for the emoji.read

slate swan
#

discord.py being a weird one again
just use image= await bot.http.get_from_cdn(emoji.url)
( thats what read uses internally)

unkempt canyonBOT
#

discord/asset.py line 87

return await self._state.http.get_from_cdn(self.url)```
slate swan
#

🚶 reasons why i don't regret switching from dpy at all

smoky sinew
#

hold on

#

it can't convert status_online:470326266625785866 to partialemoji

golden portal
smoky sinew
#

the bot isn't in the server btw

smoky sinew
#

i only have a string to work with

golden portal
#

weird it should use the same regex as the partial emoji from str

smoky sinew
#

actually, i can supply a url

#

ok it worked finally

#
    @commands.is_owner()
    @commands.command(help = "Steal an emoji from another server.")
    async def stealemoji(self, ctx: commands.Context, emoji_id):
        emoji = await self.bot.http.get_from_cdn(f"https://cdn.discordapp.com/emojis/{emoji_id}.webp?size=128&quality=lossless")

        await ctx.guild.create_custom_emoji(
            name = emoji_id,
            image = emoji
        )

this is what i had to do

vestal snow
#

i need help

smoky sinew
#

ok

vestal snow
#

why when i put my openai api key in a .env file it does not detect it and says i need a the key

golden portal
# smoky sinew the bot isn't in the server btw

partialemoji doesnt really depends if the bot is in the server or not, the converter apparently requires you to set <emoji_name:emoji_id> thats why it didnt work for you for emoji_name:emoji_id

vestal snow
#

api_key =os.getenv("OPENAI")```
smoky sinew
#

blame @slate swan

vestal snow
#

openai.error.AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://onboard.openai.com for details, or email support@openai.com if you have any questions.

#

and it gives this error

smoky sinew
#

when i tried using it with the angle brackets it converted it to an emoji

vestal snow
#

its in my discord bot

smoky sinew
golden portal
slate swan
smoky sinew
#

when i typed <emoji_name:emoji_id> it converted it to :emoji_name:

golden portal
#

i see

#

actually yea that make sense

smoky sinew
slate swan
#

thats y I suggest from_str

gilded cedar
#

!d files

unkempt canyonBOT
#

Distribution files

You can also get the full set of files contained within a distribution. The files() function takes a Distribution Package name and returns all of the files installed by this distribution. Each file object returned is a PackagePath, a pathlib.PurePath derived object with additional dist, size, and hash properties as indicated by the metadata. For example...

slate swan
#

@slate swan is it possible to make my own command deco? Like that checks if server owner.

slate swan
#

!custom-checks

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

tawny junco
#

Thx for the help guys! Everything works fine

vale wing
smoky sinew
#

i wish people would read errors

#

😔

slate swan
#

i wish errors could fix themselves

vale wing
#

"Error occured while attempting to fix another error"

crude hinge
#

attempting to turn my bot on and it doesnt do anything, no error codes either

`import bot

def run_discord_bot():
print("Running the Discord bot...")`

#

Process finished with exit code 0

#

i have

@client_event async def on_ready(): print(f'{client.user} is now running!') in my bot.py file

so console shouldnt be ending in Process finished with exit code 0

glad cradle
#

wth

#

is there actually a library called bot?

glad cradle
crude hinge
glad cradle
#

show it's code

crude hinge
glad cradle
#

you're not running the Bot from what you've sent

glad cradle
crude hinge
#

one sec

glad cradle
#

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

crude hinge
glad cradle
#

do you know python's OOP? you're not creating a client instance, also the client will not run if send_message isn't called and client.run is a blocking call, everything below it will never run so it's useless how you're wrapping it inside a function

I would suggest to look at the example that I sent

crude hinge
#

got it to work

#

apreesh

slate swan
#

Holy crap.

gilded cedar
#

I want to make one to ten command but whether i win or lose it should send a message but i expected this

#

But reality hits me hard

#

Here's the actual code if you ask me

@client.command(aliases=['ott'])
async def onetoten(ctx):
  number_1 = ['1','2','3','4','5','6','7','8','9','10']
  number_2 = ['1','2','3','4','5','6','7','8','9','10']
  
  embed=discord.Embed(title='One To Ten', color=0xe0f9ff)
  embed.add_field(name='Your Number', value=(random.choice)(number_1), inline=False)
  embed.add_field(name='Bots Number', value=(random.choice(number_2)), inline=True)
  if number_1 > number_2:
   embed.set_footer(text="You Win!")
  if number_1 < number_2:
   embed.set_footer(text="You Lose")  
  await ctx.send(embed=embed)
gilded cedar
#

I hope this works

slate swan
#

I'm just fixing the code itself. Idk what you want.

unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
gilded cedar
unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
clear elm
#

but everything else works

clear elm
#

the help command doesn't even show up now

unkempt mauve
#

I am new to discord.py bots coding. I need a code that will register slash commands for the discord.py bot

gentle nova
#

minutes = random.randrange(1,4) and asyncio.sleep(minutes) not working together .. why ? Cuz im trying to make a command which is like slap, player get's permission edit on send messages , but after time permission not setting back

upbeat gust
#

Show your code for setting perms

gentle nova
#
    if chance > 3:
        await asyncio.sleep(minutes)
        embed = nextcord.Embed(description = f'{interaction.user.mention} smeigė gerą bankę į {user.mention} užverdamas jo kakarynę {minutes} min. {random_piso}') #user.mention
        random_piso = random.choice(nupiso)
        await interaction.response.send_message(embed = embed)
        #await interaction.response.send_message(f'{interaction.user.mention}Užsimojo')
        await channel.set_permissions(interaction.user, send_messages = False)
        #await interaction.channel.send(f'{interaction.user.mention} smeigė gerą bankę į {user.mention} užverdamas jo kakarynę {minutes} min.')
    if chance < 3:
        random_uzsipiso = random.choice(nusipiso)
        random_prasileido = random.choice(text_kai_nusipiso)
        await asyncio.sleep(minutes)
        embed = nextcord.Embed(description = f'{interaction.user.mention} Užsimojo į {user.mention} bet {random_prasileido} ir sukrito {minutes} min. {random_uzsipiso}') #user.mention
        #await interaction.channel.send(f'Bandė jobint į {user.mention}, bet {interaction.user.mention} {random_prasileido} {minutes} min. {random_gif}')
        #await interaction.response.send_message(f'Nusiplake')
        await channel.set_permissions(user, send_messages = False)
#

maybe should i add two more lines like this ```python
await asyncio.sleep(minutes)
await channel.set.permissions(user, send_messages = True)

lunar kayak
#

anyone knows why when i react to this msg doesnt work?

upbeat otter
lunar kayak
#

I try in private message but doesnt work

slate swan
gentle nova
#

Why sometimes command just not working ? In concole printing , but in discord just red text

glad cradle
#

discord isn't receiving a response to the interaction so it flags the slash command invokation as failed

#

maybe share your code

#

so I could tell what's the problem

gentle nova
#

@glad cradleI shared already, its at the top of messages

glad cradle
#

the second condition is bad indented plus you're not handling possible cases where chance is 3

#

it would be better if you upload the full code snippet

#

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

gentle nova
#

@glad cradle It should be something like that: If i write command slap and mention person, if im lucky im knocking down mentioned person with 1-4min mute, if not lucky i should get mute from 1-4 mins , and it should respond with random GIF's . But cant make it working . But mute should be send_message = false not role

glad cradle
#

why you let the Bot stop the command execution for 1-4 mins? that's not how you mute members

gentle nova
#

It should change only permissions for Send_message for 1-4 mins

#

But that command removing send message option for both

#

dont understand why it doing it

glad cradle
#

you're:

- picking random numbers
- sleeping for 1-4 mins
- editing the channel permissions
#

you should first edit the channel permissions later sleep and then re-edit channel permissions

#

though I don't think this is really ok

gentle nova
#

But other thing, both getting channel edit permission

#

if im typing command , im getting aswell

gentle nova
#
random_sukrito = random.choice(random_gif)
    random_prasileido = random.choice(text_kai_nusipiso)
    random_praleido = random.choice(random_gif1)
    random_pistelejo = random.choice(text_kai_nupiso)
    if chance > 3:
        embed = nextcord.Embed(description = f'{interaction.user.mention} {random_pistelejo} {user.mention} atjungė {minutes} minutėms. {random_praleido}') #user.mention
        await interaction.response.send_message(embed = embed)
        await channel.set_permissions(user, send_messages = False)
        await asyncio.sleep(minutes*60)
        await channel.set_permissions(user, send_messages = True)
    if chance < 3:
        embed = nextcord.Embed(description = f'{interaction.user.mention} Užsimojo į {user.mention} bet {random_prasileido} ir sukrito {minutes} minutėms. {random_sukrito}') #user.mention
        await interaction.response.send_message(embed = embed)
        await channel.set_permissions(interaction.user, send_messages = False)
        await asyncio.sleep(minutes*60)
        await channel.set_permissions(interaction.user, send_messages = True)
naive briar
#

GIFs don't load in embeds, except if it's was set by set_image

gentle nova
#

hmm

#

embed.set_image(url = random_gif)

#

like this ?

naive briar
#

🤷

gentle nova
#

Hmm not loading gif and showing link :/

naive briar
#

It needs to be a valid image URL

gentle nova
#

How valid url looks like ?

naive briar
#

That directly points to an image

gentle nova
#

but i put directly link

naive briar
#

If you click on tenor links, do you see only the image and nothing else?

gentle nova
#

Yesterday was working allg

naive briar
#

Then why it isn't now then

pastel basin
#

how can i make messages like koya bot

#

welcome messages*

naive briar
#

Pillow

#

Or just any image editing package

tidal plover
#

where do you guys run your bots? Are there any free services except Heroku and Replit?

pastel basin
tidal plover
#

tnx

sick birch
#

Very powerful

#

Practically free

pastel basin
#

u dont have power outages or internet porblems

silk fulcrum
#

I just noticed that PyPi says python 3.8 | 3.9 | 3.10, it won't hurt if I use discord.py with python 3.11 right?

pastel basin
#

which is rare

pastel basin
#

Also it gives many erros with 3.8

#

its 3.9 3.10 and so on

silk fulcrum
#

ok cool

slate swan
#

can someone help me w my discord bot code

hushed galleon
hushed galleon
silk fulcrum
slate swan
pastel basin
#

i dont py 3.8 atm

#

so i cant test, it was on a virtual machine

silk fulcrum
pastel basin
#

i remember having error, it could be 3.7
think before speak 😓

silk fulcrum
#

well, 3.8 is old either way

hushed galleon
hushed galleon
#

also this

hushed galleon
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
hushed galleon
#

if you scroll up that you'll see recipes on how to use it

slate swan
#

I think it's just Im pretty sleepy :D

hushed galleon
#

i just pointed out the tasks.loop() decorator, thats one way to handle it

slate swan
#

uhh

hushed galleon
#

btw pymongo is a synchronous/blocking library so its generally not what you should use in a discord bot, motor is an asynchronous wrapper for mongodb

slate swan
#

Can I just send my replit thingy

gentle nova
#

okay guys, now gifs in embed messages working, but why link not dissapearing ?

shrewd fjord
unkempt canyonBOT
#

discord/ext/tasks/__init__.py lines 765 to 769

def loop(
    *,
    seconds: float = MISSING,
    minutes: float = MISSING,
    hours: float = MISSING,```
`discord/ext/tasks/__init__.py` lines 739 to 741
```py
seconds = seconds or 0
minutes = minutes or 0
hours = hours or 0```
sinful thistle
#

yes

sick birch
#

How about CI/CD deployment pipelines for your production server?

#

People overlook these way too often in favor of new features

sick birch
#

Like this

sinful thistle
#

which file?

sick birch
#

All of em

fast flume
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user

#

does anyone know what part of this i'd need to include if i want to catch the error in a try/except

hushed galleon
#

are you just interested in handling the error in a specific command, or generally handling it across all commands?

#

if its the former you'd be try/excepting discord.Forbidden, latter would also involve unpacking the CommandInvokeError within your on_command_error event handler

fast flume
#

i think just this one, it happens if someone has their DMs closed and I just want it to try and send the DM to someone, and if they don't have their DMs open then stop everything and send a message out saying which user has them closed

hushed galleon
#

"which user"? is it just DMing 1/2 members, or many members?

fast flume
#

it DMs multiple people

hushed galleon
#

and is it for announcing something? if so just pinging them in one message would be more ideal, since you dont want to trip discord's anti spam

fast flume
#

for what i'm using it for i don't think that will be necessary

fast flume
sinful thistle
slate swan
#
@client.command()
async def userinfo(ctx, member: discord.Member=None):
    if not member:
        member = ctx.author

    embed = discord.Embed(title='User - {}'.format(member), description=f'ID: `{member.id}`', color=0x00ff00)
  
    if member.joined_at:
        embed.add_field(name='Joined to server:', value=member.joined_at.strftime('%Y-%m-%d %H:%M:%S'), inline=True)

    embed.add_field(name='Created at:', value=member.created_at.strftime('%Y-%m-%d %H:%M:%S'), inline=True)
  
    roles = [role.mention for role in member.roles if role.name != '@everyone']
    if roles:
        embed.add_field(name='Role:', value=', '.join(roles), inline=False)  

    user = await client.fetch_user(member.id)
    banner = user.banner
    if banner:
        embed.set_image(url = banner.url)

    await ctx.send(embed=embed)

How to make it show information such as: User, ID, created_at, banner if the person has it when it is not on the server

vocal snow
slate swan
#

hi

slate swan
#

i finallly fixed the problem i was having with discord bot

#

not it's finallly workin

#

'

slate swan
#

it happens this thing here:

#

what did i did wrong?

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

green jacinth
#

Is it possible to have more than 25?

sharp pawn
#

anyone got some cool discord bot ideas?

green jacinth
slate swan
slate swan
#

okay, i got this error message:

#

i don't know why this is not working

slate swan
#

finally, it's working. My baby get life

sick birch
slate swan
unborn bluff
#

Is there any good bot example out there? I would like to know how I should organize this :')

unborn bluff
#

Yes

slate swan
unborn bluff
#

Tysm, I'll take a look thx

smoky sinew
slate swan
#

it's more simply written

#

red is nice but pretty much overcomplicated

#

WeeeeeChair i like the cog system

pseudo saffron
#

hey i am coding a discord music bot and i am getting this error on my play command someone can help me
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: FFmpegAudio.init() missing 1 required keyword-only argument: 'args'

#
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegAudio(source=url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))```
smoky sinew
#

if it's a youtube music bot then we can't help

pseudo saffron
#

it is

smoky sinew
#

sorry

#

!rule 5

unkempt canyonBOT
#

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

static holly
#

good evening, I don't understand my mistake, I don't know what's wrong

    @commands.command()
    async def galerie(self, ctx, ID=1072237400547409971):
        channel = self.bot.get_channel(int(ID))
        if channel is None:
            await ctx.send("Je ne trouve pas ce salon...")
            return
        message = await channel.fetch_message(channel.last_message_id)
        if len(message.attachments) > 0:
            attachment = message.attachments[0]
            if attachment.filename.endswith(".jpg") or attachment.filename.endswith(".jpeg") or attachment.filename.endswith(".png") or attachment.filename.endswith(".webp") or attachment.filename.endswith(".gif"):
                self.image = attachment.url
            elif "https://images-ext-1.discordapp.net" in message.content or "https://tenor.com/view/" in message.content:
                self.image = message.content

            embed=discord.Embed(title=(message.content))
            file=self.image

        await ctx.send (embed=embed, file=file)
#

Command raised an exception: AttributeError: 'str' object has no attribute 'to_dict'

slate swan
#

what's the self.image var

static holly
#

@slate swan

slate swan
#

a url is not a file....

#
      self.image = attachment.url
``` -> ```py
      self.image = attachment.to_file()
#

!d discord.Attachment.to_file

unkempt canyonBOT
#

await to_file(*, filename=..., description=..., use_cached=False, spoiler=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Converts the attachment into a [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") suitable for sending via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send").

New in version 1.3.
static holly
# slate swan a url is not a file....

i resolve it with ```py
image_upload= attachment.url

        embed=discord.Embed(title="blabla", description="blablabla")
        embed.set_image(url=image_upload)

        await ctx.send (embed=embed)
#

now all i have to find is get the message count and display that count in the title of the embed

hushed galleon
#

@slate swan dont know if you've done it yet but you should reset your token since its revealed in one of your screenshots

slate swan
#

fixed

#

thanks for warning 😁

vocal snow
smoky sinew
#

no it's only for obsidian

static holly
#

please how to count the number of messages in a channel?

unborn bluff
unborn bluff
static holly