#discord-bots

1 messages · Page 116 of 1

slate swan
#

gotcha

#

can someone help me

#

i dont have colors

ripe blaze
#

Now I get this error: ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
The problem is SelectionOption doesn't have a custom_id.
Do you know what I could do to fix it?
Thanks!

hollow agate
#

member.send(‘1’)
member2.send(‘2’)

You just have to define the members

slate swan
hollow agate
#

You just have to get the member object

ripe blaze
deft hill
#

Along with this, when I enter the font into VSCode, it shows me this

The character U+026a "ɪ" could be confused with the character U+0069 "i", which is more common in source code. Adjust settings

Anyway to make sure it scanneds U+026a instead if U+0069?

#

By font I mean this as a string: sᴛʀɪᴋᴇ ɪᴛ ʙɪɢ

slate swan
deft hill
#

Same thing with this:

slate swan
#

!d discord.SelectOption

sick birch
#

just make sure it's unique

obtuse blaze
#

is there a way to make a certain role bypass slash commands cooldown?

mossy jacinth
#

I think i finally understood dicts but what do i do with the if self.name2.value == "blue":? Do I have to delete that? or with what do i have to replace that

sick birch
ripe blaze
sick birch
#

the string basically just has to be different

slate swan
#

my code ```py
@bot.command()
async def mines(ctx,round_id: str):
with open("ids.txt",'a') as ids:
if ctx.author.id in ids:
pass
else:
await ctx.send("You need to login to use that!")

mossy jacinth
ripe blaze
sick birch
ripe blaze
#
class area_selection(discord.ui.Select):
    def __init__(self):
        options = [
            discord.SelectOption(label="דרום"),
            discord.SelectOption(label="מרכז"),
            discord.SelectOption(label="צפון")
        ]
        super().__init__(placeholder="בחר אזור מגורים", max_values=1, min_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        print("callback")
        option_name = interaction.data['values'][0]
        user = interaction.user
        guild = interaction.guild
        roles = [role for role in guild.roles if role.name in area.values()]
        for role in roles:
            if role in user.roles:
                await user.remove_roles(role)
            elif role.name == option_name:
                await user.add_roles(role)
        await interaction.response.defer()


class area_selection_view(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_item(area_selection())

In my main file I called the area_selection_view function and did the persistent view bot but the error is from here
@sick birch

slate swan
#

you dont have a custom_id set to the Select?

mighty pilot
#

idk man thats about the extent of my knowledge lol

mossy jacinth
slate swan
#

DROP TABLE tablename

slate swan
# mighty pilot idk man thats about the extent of my knowledge lol

it's alright, thanks for tryna help lol

seems like the 'double down' works fine because I don't get timed out after doubling down

the stand button works fine as well, but if I draw 1 card then stand it will time me out

very weird results i'm getting and I have no idea how to fix it haha

ripe blaze
slate swan
#

nope just the table name

ripe blaze
# slate swan yessir

I still get ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout

ripe blaze
slate swan
#

could have passed timeout=None in the init itself

mighty pilot
#

how do you disable a button after its pressed? i tried self.button1.disabled = True inside the button interaction but that doesnt work and doesnt give errors

slate swan
#

that disables the button in code,

#

you gotta edit the message with the current view to disable on discord

mighty pilot
#

ah okay

#

is there an easy way or do i need to make a whole new view with disabled buttons lol

fading marlin
#

just pass your current view instance to the view kwarg

mighty pilot
#

so specify that the button is disabled after interaction, then edit the message with the same view=view and itll work?

sick birch
sick birch
slate swan
#

[Running] python -u "c:\Users\PC\Desktop\Noas Bot\main.py"
[2022-10-29 21:40:41] [INFO    ] discord.client: logging in using static token
Traceback (most recent call last):
  File "c:\Users\PC\Desktop\Noas Bot\main.py", line 496, in <module>
    bot.run("MY TOKEN")
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
    return future.result()
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 745, in start
    await self.login(token)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 589, in login
    await self.setup_hook()
TypeError: setup_hook() missing 1 required positional argument: 'self'
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000018E24179A60>
Traceback (most recent call last):
  File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 751, in call_soon
    self._check_closed()
  File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed``` wtf is that
#

TypeError: setup_hook() missing 1 required positional argument: 'self'

sick birch
slate swan
#

OH YES

#
class PersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label='Green', style=discord.ButtonStyle.green, custom_id='persistent_view:green')
    async def green(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is green.', ephemeral=True)

    @discord.ui.button(label='Red', style=discord.ButtonStyle.red, custom_id='persistent_view:red')
    async def red(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is red.', ephemeral=True)

    @discord.ui.button(label='Grey', style=discord.ButtonStyle.grey, custom_id='persistent_view:grey')
    async def grey(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is grey.', ephemeral=True)


class PersistentViewBot(commands.Bot):
  ...
  async def setup_hook(self) -> None:
    print("Setup hook called")
    self.add_view(PersistentView())

@bot.command()
async def prepare(ctx):
    await ctx.send("What's your favourite colour?", view=PersistentView())

``` doesnt work after i restart the bot
sick birch
slate swan
#

no

sick birch
#

ah

#

that's the issue

#

for some reason your setup hook isn't even being called

slate swan
#

cuz i have it twice

sick birch
#

ah

slate swan
sick birch
#

get rid of the other one

slate swan
#

but that prints that my bots onlinre

vocal snow
#

would be better if youi sent the full code

#

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

sick birch
slate swan
sick birch
#
async def setup_hook():
    print(f"{bot.user.name} is online!")
    try:
      synced = await bot.tree.sync()
      print(f"Synced {len(synced)} command(s)")
    except Exception as e:
      print (e)

is overwriting the other setup hook

slate swan
#

okay wait'

mighty pilot
zealous jay
#

Soo, does someone knows why this won't work?

fading marlin
#

any errors?

zealous jay
#

nope

#

that event is supposed to work when a slash command is used, right?

slate swan
# sick birch ```py async def setup_hook(): print(f"{bot.user.name} is online!") try: ...
class PersistentViewBot(commands.Bot):
async def setup_hook(self) -> None:
    print(f"{bot.user.name} is online!")
    try:
      synced = await bot.tree.sync()
      print(f"Synced {len(synced)} command(s)")
    except Exception as e:
      print (e)
    print("Setup hook called")
    self.add_view(PersistentView())```
```  File "c:\Users\PC\Desktop\Noas Bot\main.py", line 468
    async def setup_hook(self) -> None:
    ^
IndentationError: expected an indented block```
indigo pilot
#

hey does anyone got any ideas how to do a check for if the chat is active? like if theres at least 4 active chatters currenly, theres a few ideas i have to do this but thought id ask to see if theres a btter way

fading marlin
zealous jay
#

oh yeah well, its not working 🤷‍♂️

fading marlin
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") to do this.

Examples

Usage...
sick birch
indigo pilot
slate swan
#

ioh

slate swan
fading marlin
indigo pilot
#

oh that works

#

does it take a timestamp

#

or what

fading marlin
#

read the docs

slate swan
# sick birch your function needs to be indented so it's inside of the class
class PersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label='Green', style=discord.ButtonStyle.green, custom_id='persistent_view:green')
    async def green(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is green.', ephemeral=True)

    @discord.ui.button(label='Red', style=discord.ButtonStyle.red, custom_id='persistent_view:red')
    async def red(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is red.', ephemeral=True)

    @discord.ui.button(label='Grey', style=discord.ButtonStyle.grey, custom_id='persistent_view:grey')
    async def grey(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is grey.', ephemeral=True)

class PersistentViewBot(commands.Bot):
  async def setup_hook(self) -> None:
    print(f"{bot.user.name} is online!")
    try:
      synced = await bot.tree.sync()
      print(f"Synced {len(synced)} command(s)")
    except Exception as e:
      print (e)
    print("Setup hook called")
    self.add_view(PersistentView())


@bot.command()
async def prepare(ctx):
    await ctx.send("What's your favourite colour?", view=PersistentView())
zealous jay
#

maybe unix timestamps works

fading marlin
zealous jay
#

the cogs seems to load correctly and there's no error handler

naive briar
zealous jay
#

logs channel

vocal snow
sick birch
slate swan
vocal snow
#

use it?

#

I mean surely you created that class to use it right

#

on line 32

bot = commands.Bot(command_prefix="-", help_command=None, intents=discord.Intents.all())

mighty pilot
# sick birch just `interaction.edit_original_response(view=self)`

is there a way to do this in response to a message instead of an interaction? when a user sends a message, the bot sends a message in a seperate channel and if i try to edit the message it tries editing the message the user sent instead of the message sent by the bot

vocal snow
vocal snow
#

that's the bot you're running

slate swan
#

now i changed it to that

#

class PersistentViewBot(commands.Bot):
async def setup_hook(self) -> None:
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
print("Setup hook called")
self.add_view(PersistentView())

zealous jay
mighty pilot
#

it tries to but it cant do that. i want it to edit the bots own message that got sent with the view for buttons

zealous jay
#

if im not wrong, if you want to edit something the bot sent you can store it inside a variable before sending it

#

my_message = await interaction.followup.send(". . .")

slate swan
#

you cant

mighty pilot
#

user sends a message, levels up, the bot sends a message in a seperate channel with a view containing buttons. i want to disable one of the buttons upon interaction with it. i have interaction: discord.Interaction in the init then also self.interaction = interaction so it can be sent to the children through self. if i do self.interaction.edit(view=self) then it tries to edit the message the user sent instead of its own

zealous jay
#

oh

mighty pilot
#

i have it working when i use a different view from an interaction because i can use edit_original_response but that doesnt work because its not being sent in response to an interaction

zealous jay
#

hm how do you use interaction.followup.edit_message()?

crimson horizon
#

I have a json file with this structure:

{
id: {
  "message": "abc"
  "link": "www.www.www"
  ...
}
id2: {
  "message": "abc2"
  "link": "www.www.www2"
  ...
}
id3: {
  "message": "abc3"
  "link": "www.www.www3"
  ...
}
...
}

I want to access each message link and channel id and every other thing via for loop in pyhon, then send every message to every channel
I tried it like this:

with open("data.json", "r") as f:
  data = json.load(f)
print(data)
for channel in data:
  for message in data:
    print(channel)
    print(message)
    name = message[0]
    msg = message[1]
    inv = message[2]
    id = channel[3]
    print(name, msg, inv, id)
    c = client.get_channel(id)
    embed = nextcord.Embed(title=name, description=f"{msg}\n{inv}")
    c.send(embed=embed)

But it's just taking the ID and for example message[0] would be i because of the "id"
how do i do that?

#

and, what's that? Never heard of it

zealous jay
slate swan
crimson horizon
#

how does it look like? What is it?

slate swan
#

OH

#

OH NVM

mighty pilot
zealous jay
# slate swan you cant

this worked 🤔

    async def testing_command(self, interaction: discord.Interaction):
        await interaction.response.send_message("Test 1")
        message = await interaction.followup.send("Test 2")
        await asyncio.sleep(5)
        await interaction.followup.edit_message(message_id=message.id ,content="Test 3")
#

didn't mean to ping

slate swan
#

im okay with pings

zealous jay
#

oh yeah I sent the wrong message and edited it afterwards

slate swan
crimson horizon
#

oh oky

crimson horizon
crimson horizon
#

kk

obtuse blaze
#

is there a way to make a certain role bypass slash commands cooldown?

fading marlin
#

!d discord.app_commands.checks.dynamic_cooldown

unkempt canyonBOT
#

@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

Both `key` and `factory` can optionally be coroutines.
mighty pilot
zealous jay
#

oh nice

#

no problem 😄

mossy jacinth
#

How can I change my bots status to DND? I forgot

trim ocean
#

Can you set notifications for a channel?

mighty pilot
primal token
#

!d discord.Status.dnd

unkempt canyonBOT
mighty pilot
#

Yea that one

primal token
#

idle is the yello moon one!

mighty pilot
#

You right

slate swan
#
   await bot.get_channel(1034484568562081872).send(f"Welcome {user.mention} ! 👋 if you need any support [#1034471573383557261](/guild/267624335836053506/channel/1034471573383557261/)")

How would i fix this?

slate swan
sick birch
#

Can you send the entire function?

slate swan
sick birch
slate swan
sick birch
#

{member.mention} perhaps?

slate swan
#

like changing

sick birch
#

Like, on an interval?

mighty pilot
slate swan
#

if you have the member object that's unnecessary. most of the time u only do that when u just have the ID

#

member.mention works fine

#

so like 1 min it will be

watching many members another 1 min watching website

#

ect

magic portal
#

how would I be able to check if a json value = 1, so then It doesnt run a command

tame idol
#

hello

#

i need help for discord slash commands

#

i need get a channel with ID

winged coral
unkempt canyonBOT
dapper bluff
#

Am I supposed to be seeing an url here?

#

how do i get the invite url

mighty pilot
dapper bluff
#

nothing here

mighty pilot
#

The generated url at the bottom will appear if you put in a redirect url. Or select different options that don't require it

dapper bluff
#

whats a redirect url

#

what do i put there

#

i made a discord bot a couple years ago and i would just select the permissions and it would give me the url

#

this is all new to me

mighty pilot
#

I've only ever used it when making a bot on a serverless site. I'm assuming you have some scopes selected that you don't actually need

dapper bluff
#

well i need the bot to join the server

#

and do commands

mighty pilot
#

Unselect the guilds.join scope, it'll join your server when you follow the url

#

And you're gonna want to select the bot scope as well

dapper bluff
#

(its not in the server)

mighty pilot
dapper bluff
#

yes

mighty pilot
#

Is it listed at the top of members, where the active members would be

dapper bluff
#

no its not in the server

mighty pilot
#

Idkchu I've always selected applications.commands and bot then selected whatever permissions I need and have no issues with the bot joining any servers

dapper bluff
#

im not getting a captcha quiz if thats relevant

mighty pilot
#

That doesn't always show

dapper bluff
#

ill try tio make the bot again

#

yea its not joining

#

okay wait so @mighty pilot

#

i took this link and replaced the id with my id, the bot joined the server

#

but now i run the code i get an error

mighty pilot
#

What error

dapper bluff
unkempt canyonBOT
#

Hey @dapper bluff! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

dapper bluff
#
import discord
from discord.ext import commands

TOKEN = ''

description = 'bot'
bot = commands.Bot(intents=discord.Intents.all(), command_prefix='!', description=description)


@bot.event
async def on_message(msg):
    if msg == "test":
        await msg.channel.send("hi")

bot.run(TOKEN)```
#

is that a erro from this or bot

mighty pilot
#

Oh yea you need to enable priveleged intents in the developer portal

dapper bluff
#

where is that

#

oh i see

#

let me try again

#

im still getting that error

slate swan
#

u need to enable all 3

mighty pilot
#

Yup all 3 toggles

dapper bluff
#

k

mighty pilot
#

Because your code requests all 3

dapper bluff
#

ok so

#

the code is working and so is the bot but

#
import discord
from discord.ext import commands

TOKEN = ''

description = 'bot'
bot = commands.Bot(intents=discord.Intents.all(), command_prefix='!', description=description)


@bot.event
async def on_message(msg):
    if msg == "test":
        await msg.channel.send("hi")

bot.run(TOKEN)```
#

when i say !test it doesnt say hi

#

no errors

slate swan
#

u need msg.content and that's an event

mighty pilot
#

You're using on_message in place of a command

slate swan
#

no a command so no prefix

mighty pilot
#

If you just say test it'll sat hi

dapper bluff
#

what does @bot.X do

dapper bluff
#

@bot.command() ?

slate swan
#

i advise you follow a tutorial or just actually look at the docs especially if you are just starting. and then ask questions if you are stuck on something.

#

otherwise if ppl just keep telling u what to do you'll never learn

dapper bluff
#

i know python "fluently"

#

i just dont know this api, so theres no need for a whole tutorial for this

#

just pls tell me, instead of "@bot.event" what should i puyt

slate swan
#

then why not read docs if you know python fluently?

#

we aren't just going to keep spoon feeding u

dapper bluff
dapper bluff
#

what is this

slate swan
#

bot is missing permissions

mighty pilot
#

You need to give the bot proper permissions in the server

#

Usually accomplished with roles

mossy jacinth
#

why does the error handler not work?

#

i also got an exception for an KeyError but it also failed

mighty pilot
#

I don't use nextcord so I can't help with that one

mossy jacinth
#

its just like discord.py, just tell me how you would fix it in discord.py and I will try to make something out of it

mental quiver
#

do you guys know how to do subcommands with slash commands ?

vocal snow
#

which library?

mental quiver
dapper bluff
#
async def get_ip(ctx,user: discord.User):
    if ctx.content.startswith("!get ip"):
        randomIp = f"{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}"
        await ctx.channel.send(randomIp,user.mention)```
#

how can I check if their second message was a user ping?

#

this doesnt work

vocal snow
#

why are you doing all this instead of just using the commands extension

vocal snow
#

then why are you checking if ctx.content.startswith("!get ip"), there should be no need for you to ever do that

dapper bluff
#

i was messing around with bot.event and i forgot to remove

vocal snow
#

do you want the user parameter to either be a mention or the word ip?

dapper bluff
#

How can I do @command using spaces?

#

I would prefer !get ip @dapper bluff over !get_ip @dapper bluff

vocal snow
#

subcommands or use the name parameter in the decorator

dapper bluff
#

@bot.command()
async def get(ctx,args): #if args == "ip"

#

like that?

#

ok what about the third message, how can i get that?

vocal snow
#

just make another parameter

dapper bluff
#

oh thats how it works?

dapper bluff
#
@bot.command()
async def get(ctx,second,user: discord.User):
    if second == "ip":
        if user: 
            randomIp = f"{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}"
            await ctx.channel.send(randomIp)```

ok so this works but it errors if user is not a user
#

Its true I dont want it to run if user is not a User, but I would prefer if it didnt error (to keep the console clean)

#

so how can I check if user is a User so it wont error

#

if that makes sense

vocal snow
#

you can use an error handler

dapper bluff
#

ill try try

mighty pilot
#

man i want to seperate my 1300 lines into cogs so bad.. but i feel like something is going to break if i do Norow

slate swan
#

cant install discord or discord.py (idk if theres a difference) send help

vocal snow
#

that link will likely solve your issue

slate swan
#

now what

hushed galleon
# slate swan now what

pick the first option for C++ development and install it, or alternatively skip it and downgrade to 3.10 which has prebuilt wheels for the three packages listed in your error message

slate swan
#

downgrade to discord 3.10?

hushed galleon
#

no, python 3.10

slate swan
#

what version is the newest

hushed galleon
#

python 3.11, which is what you have installed

slate swan
#

oh calm with downgrading then

#

ez w now imma go figure out how to

#

ty for the help

#

back how tf do i downgrade

hushed galleon
slate swan
#

i just uninstall python then reinstall a older version right?

hushed galleon
#

you dont have to uninstall 3.11, but it can be confusing having both versions if you dont know how to choose between the two

slate swan
#

there any way to install 3.10 in the cmd?

hushed galleon
#

with the Chocolatey package manager i guess if you have that installed, you can ask more about it in a help channel

slate swan
#

this 1 right?

#

ok ill take that as a yes

slate swan
#

@hushed galleon it worked ily

#

anyone familiar w error handlers?

upbeat gust
slate swan
mighty pilot
slate swan
#

i'm still struggling with my stupid bot timing me out for no reason 😭

mighty pilot
#

Yea idk what's up with that. I have 2 button menus and don't have any problems with my timeouts

slate swan
#

if i draw once then stand it will time me out after the game ends

#

even though the very first line of code under my stand button is self.stop()

#

but it works properly if i dont draw and stand straight away

#

doubling down works fine

untold iron
#

Anyone know how i can have this kind of button under an embed?

upbeat gust
untold iron
#

Thank you

#

I have realised i needed to update to discordpy 2.0+, however now my code will not run. If i try the invite user command. I get this error saying unexpected 'value'

#

Not sure exactly what is the issue, i have a feeling its a deprecated value i used

#

Has await ctx() changed?

magic portal
#

is there a way I can make praw faster in sending something from Reddit?

#

because right now its really slow loading images

wicked atlas
untold iron
#

Oh thank you

#

Im not sure, but value was working for me on 1.7.3

slate swan
magic portal
# slate swan what exactly is slow?

after you type the command I have, the loading time for the image is slow. It will show the embed then just a loading picture for a while then after ~20-30 seconds it shows the image. I was wondering if I can just preload the images before hand maybe on_ready or smth

hushed galleon
slate swan
magic portal
#

at the same time

slate swan
#

its an embedded image link? or a discord embed with an image attached?

magic portal
slate swan
#

that's weird never seen that before.

#

i guess since it's a url link still it would be an issue with where the image is hosted then

#

not sure

wicked atlas
#

Is the URL itself a reddit link?

#

If so, it's probably reddit's problem

magic portal
#

it varies

slate swan
#

a shitty way to fix it would be defer the command download the img, then set the image as a file and send then

#

but if it takes long to load the image i would assume it takes a min to save it aswell

magic portal
slate swan
#

then yea i would suggest that.

magic portal
#

How would I go about doing that

slate swan
#

rather than the img sitting there loading for everyone

magic portal
#

im new to discordpy

#

I would much rather it take a second without posting then suddenly showing up loaded then it just sitting there loading

upbeat gust
slate swan
dapper bluff
#

@bot.command()
async def set(ctx,second,user: discord.User):

#

how can i make an arg which is everything else

#

a table

hollow agate
#

You can use * to consume everything.

dapper bluff
#

ok also

#

async def set(ctx,second,user: discord.User):

user: discord.User

#

How can I figure out if a message is a mention of a user

#

Because that works until I want a set command that doesnt relate to users

hollow agate
#

User.mentioned_in iirc

#
if user.mentioned_in:
...```
#

possibly

dapper bluff
#
@bot.command()
async def get(ctx,second,third):
  if discord.User.mentioned_in(third):
#

?

hollow agate
#

...no

dapper bluff
#

well thats what im trying to do

dapper bluff
hollow agate
#

Why don't you just require a user object instead of second,third stuff?

dapper bluff
#

what if i want a function that sets role name

#

!set rolename "hello"

#

well thats gonna cause an issue

dapper bluff
young pendant
#

Hey, I have a question

hollow agate
#

One sec, let me find it

young pendant
#

Hey, does someone have experience with discord.py?
If so, I have a bot, which has commands with custom prefix, I want to have the custom prefix removed and the commands should be slash-commands, since I'm to stupid to do it, I would like to know if someone can help me

hollow agate
#

Alright, you can use third.mentions to get the mentions of of the third value

hollow agate
#

Read that and you'll understand how to use slash commands.

#

Let me know if you're confused anywhere :)

dapper bluff
#
@bot.command() 
async def get(ctx,second,third):
    if second == "ip":
        user = third.mentions```
#

like this?

hollow agate
#

Let me show you, one sec

young pendant
#

@hollow agate
I`m confused with slash commands, the issue is, that it's my first time using python since 1 year

#

and I have never done something with slash commands

hollow agate
#

What I sent literally gives you examples

#

It's spoonfeeding, you can't get any more than that...?

#

You can genuinely copy and paste the code and it'll work

#

If not, what are you struggling with?

#

@dapper bluff there's no easy way to do it, just use separate commands.

#

It'll make your life 100x easier

dapper bluff
#

k

dapper bluff
#

is * a table?

hollow agate
#

Table? What?

dapper bluff
#

!say hello how are you today

#

*[1] = hello
*[2] = how
*[3] = are
etc...

#

thats a table

hollow agate
#

You can split the words by spaces

#
  • just consumes the rest
dapper bluff
#

thats what ive been trying to ask

#

I dont need every single word I just need the entire thing

hollow agate
#

Ex:

@client.command()
async def test(ctx, member: discord.Member, *, reason=None)```
If you use ".test @hollow agate hello how are you today"

`reason` will be `hello how are you today`
dapper bluff
#

let me give u an example of what i need

#

!set note @dapper bluff he is a user in this server who is a user

#

!get note @dapper bluff
--> he is a user in this server who is a user

hollow agate
#

Let me just give you the code

dapper bluff
#

I need to be able to get all of the words after the member argument

hollow agate
#
@client.command()
async def set(ctx, first, member: discord.Member, *, note=None)```
#

Then you have to store the note somewhere in a database and get it out of the database using the get command.

dapper bluff
#

so if i print * ill get he is a user in this server who is a user

dapper bluff
#

ah ok thats what ive been trying to ask

hollow agate
#

If you print note you will get it.

dapper bluff
#

but you defined note to None

hollow agate
#

That's if they just do "!set note @hollow agate" you can simply do

#
@client.command()
async def set(ctx, first, member: discord.Member, *, note=None):
    if note == None:
        await ctx.reply('Please provide a note!')
    else:
        ...put the note in the database
        await ctx.reply("I've added the note!")```
#

Consider learning basic Python before trying to do discord.py. Discord.py isn't beginner friendly at all

dapper bluff
#

excuse me? I know fucking python

#

Im asking about the arguments in a discord.py function dumbass

hollow agate
#

This is literally basic Python, is it not?

dapper bluff
hollow agate
#

😂 alright

dapper bluff
#

let me show u what i have already

unkempt canyonBOT
#

Hey @dapper bluff! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

dapper bluff
#

import discord
from random import randint
from discord.ext import commands
import json

def importData(location, data):
    filename = f"{location}.JSON"
    old_data = extractData(location)

    data = {**old_data, **data}
    with open(filename, "w") as f:
        json.dump(data, f)

def extractData(location):
    with open(f"{location}.JSON", "r") as read_file:
        return json.load(read_file)

TOKEN = ''

description = 'bot'
bot = commands.Bot(intents=discord.Intents.all(), command_prefix='!', description=description)

@bot.command() 
async def get(ctx,second,user: discord.User):
    if second == "ip":
        ipFound = False

        for id,ip in extractData("IPs").items():
            if id == str(user.id):
                ipFound = True
                await ctx.channel.send(ip)  
        
        if not ipFound:
            randomIp = f"{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}.{str(randint(1,255))}"
            userData = {str(user.id):str(randomIp)}
            importData("IPs",userData)
            await ctx.channel.send(randomIp)

@get.error
async def get_error(ctx,error):
    if isinstance(error, commands.BadArgument):
        await ctx.send("https://tenor.com/view/shoebill-bird-rain-beautiful-gif-18429868")
#

does this look like it was written by someone who "doesnt know basic python"

#

the question was never about python, it was about discord.py, read the channel name

hollow agate
#

That is pretty basic code, however, knowing how to consume all via * is pretty basic Python... along with setting a variable to None.

dapper bluff
#

guess what genius, the variable didnt need to be None

hollow agate
#

...but I can't argue, I don't know what you know shrug

dapper bluff
#

this worked exactly as intended, so fuck off with your "=None" bs

hollow agate
#

A heads up... if you don't have the =None and they don't add a note, it will raise an error.

#

You do you, I guess

dapper bluff
#

thats where @umbral peak.error comes in

#

oops

#

lmao

hollow agate
#

That works, but I personally wouldn't do it for a few reasons.

dapper bluff
#
@get.error
async def get_error(ctx,error):
    if isinstance(error, commands.BadArgument):
        await ctx.send("https://tenor.com/view/shoebill-bird-rain-beautiful-gif-18429868")```
hollow agate
#

In your case, it doesn't really matter

dapper bluff
#

as u can see here, i make the bot send a gif when the code errors

dapper bluff
#

exactly you have no definition

#

you just say shit to fit youre narrative

hollow agate
#

Well then, I help people... no good deed goes unpunished 😄

#

Good luck with your bot! 😊

dapper bluff
#

thank you

wary shadow
slate swan
#

Hey!

I have a purge command,

But I want it to purge all of the messages besides its own messages

How would i do something like that?

hollow agate
dapper bluff
#
for userId,note in extractData("notes").items():
            if userId == str(user.id):
                noteFound = True
                warning = await ctx.send("User already has a note, would you like to override it?") 
                await warning.add_reaction(":white_check_mark:")
                confirmation = await bot.wait_for("reaction_add", check=":white_check_mark:")```
hollow agate
#
def is_me(m):
    return m.author == client.user

deleted = await channel.purge(limit=100, check=is_me)
await channel.send(f'Deleted {len(deleted)} message(s)')``` You can view this example and edit the `is_me` to your liking!
dapper bluff
#

the warning message is being displayed, but no check mark is being added, why?

slate swan
ionic edge
#

then add the reaction to that variable

dapper bluff
#

whats what im doing

ionic edge
hollow agate
dapper bluff
#

oh wait im getting an error

#

Unknown Emoji

ionic edge
#

Windows + .

#

Then from there add the emoji

hollow agate
#

You need to use unicode if it's not a custom emoji iirc.

ionic edge
#

simple

dapper bluff
#

can i use "✅"

hollow agate
#

\✅

#

^ Copy this.

ionic edge
dapper bluff
#

ok thx

wary shadow
#

Might try removing the : from the emoji name. Looks like that method takes a string too.

ionic edge
#

?tag add_reaction

novel apexBOT
#

This is not a Modmail thread.

ionic edge
#

ah nvm

wary shadow
ionic edge
#

Different server

wary shadow
dapper bluff
#
                await warning.add_reaction("✅")
                await warning.add_reaction("❌")
                confirmation = await bot.wait_for("reaction_add")
#

how can I check to which the user responded too?

wary shadow
#

They are looking for the thumbs up but you can look for what you need.

dapper bluff
#

its not reognizing check

#

oh wait

dapper bluff
#

I dont know what to put for the last parameter, or why they are using a function

#

I dont need a function

dapper bluff
wary shadow
#

They are using a function because that third argument (check) is a callback. It's just the example I saw while here. Probably other ways of doing it.

dapper bluff
#

What is that peice of code doing?

#

idk what all the api functions do

#

just how would it look to a discord user

hollow agate
#

You're confused on the def check(reaction, user) part, right?

dapper bluff
#

i may of got it one sec

wary shadow
#

bot.wait_for("reaction_add") is going to return two values according to the documentation. The reaction object and the user object.
So, at the minimum, you need:
confirmation, user = await bot.wait_for("reaction_add")

confirmation here should be a Reaction object which you can pull the .emoji from and know which one it is. user is who clicked/added a reaction.

Beyond that, the logic is a bit more than I can help with. I've not done this with bots darkoLUL

dapper bluff
#
                warning = await ctx.send("User already has a note, would you like to override it?") 
                await warning.add_reaction("✅")
                
                def check(reaction, user):
                    return user == ctx.author and str(reaction.emoji) == '✅'


                try:
                    reaction,user = bot.wait_for('reaction_add', timeout=5.0, check=check)
                except asyncio.TimeoutError:
                    await ctx.send("Timed Out")            
                else:
                    await ctx.Send("Overriden")
                    importData("notes",msg)```
#

not workign

#

im getting an error

#

cannot unpack non-iterable coroutine object

#

reaction,user = bot.wait_for('reaction_add', timeout=5.0, check=check)

naive briar
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**...
dapper bluff
#
    elif second == "note":
        print("get note called")
        noteFound = False
        
        for id,note in extractData("notes").items():
            if id == str(user.id):
                noteFound = True
                await ctx.channel.send("[User Notes]",note)  
        print("here")

        if not noteFound:
            ctx.send("[ERROR] User has no notes.")
#

get note called does print, but nothing else does

#

No errors, just nothing happens, here does not print

#

Its almost like that loop is yielding the thread?

slate swan
#

you have an error handler that eats your errors

dapper bluff
#

oh yeah

#

@slate swan thanks! I found the issue

slate swan
#

no worries

#

you can use a f string there

#

f"[User Notes] {note}"

dapper bluff
#

yea i saw noticed lol

reef trail
#

im trying to run this task every 5 minutes on the minute: 1:05 > run, 3:25 > run, every 5th minute, run. I did it for ever hour on the hour: @tasks.loop(time=[datetime.time(hour=h, minute=0) for h in range(24)]) but idk how to do it for minutes. this is what i tried: @tasks.loop(time=[datetime.time(minute=h) for h in range(5)]) but this like never runs

#

ping on reply please :>

upbeat gust
#

instead of using the time param here

#

set the minutes to 5, and in before_loop, check the current time, and wait until the next multiple of 5

solemn flame
#

im trying to use youtube_dl and voice to stream youtube videos through the bot

#

but after ~3 mins it stops with this error

#

anyone know the cause of it?

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

Can't help you sorry

slate swan
#

hello ive had this serverinfo code for a while but now it recently stopped working and gave error 'Guild' object has no attribute 'region'

vale wing
#

So many str casts

hollow agate
sick birch
#

fetch = (await cursor.fetchall())[0]
the parens are important

slate swan
hollow agate
#

I don't think you can even change a server's region anymore?

slate swan
#

no

#

regions are voice specific now

hollow agate
#

Ah

slate swan
#

thi it was something like that, wait

slate swan
#

or just region

slate swan
#

yeah its rtc_region

hollow agate
#

Just remove the region part of the serverinfo command

naive briar
#

I have nothing to say

upbeat gust
slate swan
upbeat gust
#

What is ctx.member supposed to be

#

You didn't answer my question

#

What is ctx.member supposed to be? That doesn't exist

#

You have a param named member though

#

uhm?

slate swan
#
        await report.send(f"<@&1005078296729501796> {interaction.user.mention}", embed = embed, view = view)
        await interaction.response.send_message(f"Please head over to {report.mention}", ephemeral=True)
        await report.edit(locked = True)

yo so idk if im locking threads right but this aint working

#

Hello!

I am making a discord bot that checks to see if a user is staff

Code:

perms = json.load(open('perms.json', encoding='utf-8'))

def owner(ctx):
  return str(ctx.author.id) in perms['OWNER_ID']

@bot.slash_command()
async def command(ctx):
  if not owner(ctx):
    await ctx.respond("Invalid perms")

But instead of it checking data from a .json file I want it to check if a user has a specific role in my server

How would I do something like that

naive briar
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
slate swan
#

but then how would i return the error if they dont have owner?

naive briar
#

Hmmm

#

!d discord.on_error

unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)").

Note

`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").

It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").

Changed in version 2.0: The traceback is now logged rather than printed.
naive briar
#

You can check if the error argument is an instance of the discord.ext.commands.MissingRole or not

slate swan
slate swan
# naive briar !d discord.on_error

Found a work around!

def owner(ctx):
  role = ctx.guild.get_role(<role id>)

@bot.slash_command()
async def ping(ctx):
  if not owner(ctx):
    await ctx.respond("Error")
  else:
    await ctx.respond(f"Pong! `{round(bot.latency* 1000)}ms`")
crimson horizon
#

Hey

#

how can I set slash commands permissions in discord.py

slate swan
crimson horizon
#

Yeah, I tried that

#

it somehow didn't work

slate swan
#

can you send or put one of you commands on hastebin and send it here!

#

@crimson horizon

crimson horizon
#
@client.slash_command(name="start", description="Start your journey with many partners")
@commands.has_permissions(administrator=True)
async def start(interaction: Interaction):
  await interaction.response.send_modal(Modal1())
shrewd apex
unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
lucid latch
#
@bot.command(
    name="play",
    description="노래재생",
    options= [
        interactions.Option(
            name="query",
            description="노래이름",
            type=interactions.OptionType.STRING,
            required=True,
        ),
    ],
)

async def play(ctx: interactions.CommandContext, query: str):
    queue = []
    channel = ctx.author.voice.channel
    if bot.voice_bots[0].is_playing():
        queue.insert(len(queue), query)```
#

The HTTP client has exhausted a per-route ratelimit. Locking route for 1.0 seconds.

#

anyone knows why this error happen?

crimson horizon
#

what does this mean?

#

please help

slate swan
#

what this mean

crimson horizon
slate swan
#

also what u mean by that

spark mortar
silk fulcrum
# spark mortar help

Error clearly says that the connection to 127.0.0.1 has failed, it either works different on heroku, or some information that you are giving when connecting is not coorect

silk fulcrum
silk fulcrum
#

Can't tell which operation, since you only showed one line of an error

crimson horizon
#

it worked before without 2fa...

silk fulcrum
#

What "it"?

silk fulcrum
balmy bobcat
#

hi, how can I make my discord bot execute a command / send a message everyday? (it is hosted on an online server if this can help)

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").
balmy bobcat
#

thank you

slate swan
silk fulcrum
wise venture
#

hello, i'm quite kinda new for discord.py but since they migrated the discord.py api, can someone tell me how to not confuse two embeds using on_message(message):???

#

!d help

silk fulcrum
wise venture
silk fulcrum
#

try "to make the func ctx" what?

wise venture
#

and if i say like !embed it will work but the other embed will not respond

naive briar
#

What...

silk fulcrum
#

i cannot get what you are saying

wise venture
#

let me give example :

# embed 1
@client.evemt
async def on_message(message):
 if message.content.startswith('!firstembed')
 embed1 = discord.Embed(title='First Embed', description='First Embed', color=0x0001)
 await message.channel.send(embed=embed1)

# embed 2
@client.evemt
async def on_message(message):
 if message.content.startswith('!secondembed')
 embed1 = discord.Embed(title='second Embed', description='second Embed', color=0x0001)
 await message.channel.send(embed=embed1)
#

@silk fulcrum

#

like that\

naive briar
#

You're overriding the first one with the second one

silk fulcrum
#

wtf 🤢

#

Why are you making commands like that

#

that's like ancient 200 years ago method

naive briar
#

And for the love of God use the discord.ext.commands.Bot to make text commands

silk fulcrum
wise venture
#

oh?

flat pier
wise venture
#

so my funcs are like totally outdated??

#

like i need to switch

silk fulcrum
flat pier
#

technically not outdated, just not very good to use unless you're making something beyond basic and have no need to use commands.Bot

silk fulcrum
#

well they aren't TOTALLY outdated

upbeat gust
wise venture
silk fulcrum
#

"migrated" pithink

#

maybe that means the 2.0 update

balmy bobcat
#

It's client.event not client.evemt

slate swan
#

cliemt.evemt

humble lodge
#

bonjour il y a des français ?

balmy bobcat
#

Ouais

#

Passe en DM pour pas flood ici (come in DMS not to flood here)

slate swan
naive briar
#

!d discord.ext.commands.Group.group - then create a subgroup

unkempt canyonBOT
#

@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
slate swan
#

ASscary group.group.group.command

#

Hey!

I am making a discord bot with a help command

Code:

@bot.slash_command(description="Sends all current bot commands")
async def helpme(ctx):
    embed=discord.Embed(description=f"**SOME HELPFUL LINKS** \n\nasdfasdf", color=embedcolor, timestamp=times)
    embed.set_footer(text="Page (1/5)", icon_url=ctx.author.avatar)
    pages = 5
    button = Button(label="▶️")
    button2 = Button(label="◀️")
    async def button_call(interaction):
        await interaction.response.defer()
        if 'Page (1/5)' in embed.footer.text:
            embe=discord.Embed(description="OK")
            await ctx.edit(embed=embed)
    button.callback = button_call
    view = View(timeout=None)
    view.add_item(button2)
    view.add_item(button)
    await ctx.respond(embed=embed, view=view)
    if botlog == True:
        embed=discord.Embed(title=f"Command logging", color=embedcolor, timestamp=times)
        embed.add_field(name="Command ran", value="/help", inline=False)
        embed.add_field(name="Comman ran by", value=f"{ctx.author.mention} : {ctx.author.id}", inline=False)
        embed.add_field(name="Where", value=ctx.channel.mention, inline=False)
        await bot.get_channel(logcha).send(embed=embed)
        logweb.send(embed=embed)
    else:
        pass

But for the button_call

I want it to check the embeds footer to see what page its on and go to the next one

Is there a way i can read the text of a footer?

cunning iris
#

hello, I'm having issues with this command, it tells me Bot object has no attribute logout, though it worked the last time I launched it

@bot.command(name='stop')
async def logout(ctx):
    await ctx.message.channel.send("Bisous je m'envole")
    await bot.logout()```
cunning iris
glad cradle
#

!d discord.ext.commands.Bot.close

unkempt canyonBOT
#

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

Closes the connection to Discord.
cunning iris
#

oh so it's juste close() now

#

thanks

ionic edge
#
    @commands.Cog.listener()
    async def on_message_delete(self,message:discord.Message):
        if not message.guild or message.author.bot:
            return
        channel = message.channel
        content = message.content if message.content else "Content Unavailable"

        if not channel.type == discord.ChannelType.text:
            return
        cursor = self.client.db.cursor()
        time = discord.utils.utcnow()
        cursor.execute("CREATE TABLE IF NOT EXISTS deleted_messages (guild_id BIGINT, channel_id BIGINT, message_id BIGINT, author_id BIGINT, content TEXT, timestamp TIMESTAMP)")
        cursor.execute("INSERT INTO deleted_messages VALUES (?, ?, ?, ?, ?)", (message.guild.id, message.channel.id, message.id, message.author.id, content))
        print("hello")
        self.client.db.commit()
        cursor.close()
slate swan
#

for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
bot.load_extension(f"cogs.{fn[:-3]}")

and in the end of the cog
def setup(bot):
bot.add_cog(Logs(bot))

naive briar
#

!d discord.Webhook.url

unkempt canyonBOT
grand willow
#

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

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

Changed in version 1.1: Added the `reason` keyword-only parameter.
slate swan
#

and saying [Running] python -u "c:\Users\PC\Desktop\Noas Bot\main.py"
c:\Users\PC\Desktop\Noas Bot\main.py:48: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f"cogs.{fn[:-3]}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

naive briar
#

I can't know what's wrong with just it's not working

naive briar
#

Await it

slate swan
#

File "c:\Users\PC\Desktop\Noas Bot\main.py", line 48
await bot.load_extension(f"cogs.{fn[:-3]}")
^
SyntaxError: 'await' outside function

naive briar
#

You need to load the extensions in a async function

#

Like setup_hook

slate swan
#

oh

vale wing
#

Read dpy migration guide 2.0, seems like you just updated it and now are confused @slate swan

slate swan
#

i will try

grand willow
#

message.channel then the channel Attribute u wana use

slate swan
vale wing
#

That's not what I mean

grand willow
#

just ctx.channel

slate swan
# naive briar Like `setup_hook`

Traceback (most recent call last):
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 434, in <module>
bot.run("my token")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 589, in login
await self.setup_hook()
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 46, in setup_hook
await bot.load_extension(f"cogs.{fn[:-3]}")
NameError: name 'fn' is not defined

#

it tells u the issue

#

i did defined it

#

@bot.event
async def setup_hook():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
await bot.load_extension(f"cogs.{fn[:-3]}")

#

File "c:\Users\PC\Desktop\Noas Bot\main.py", line 47
if fn.endswith(".py"):
^
IndentationError: unindent does not match any outer indentation level WHAT

cloud dawn
#

!indention

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

cloud dawn
#

If it visually does look correct- then you are mixing tabs and spaces.

slate swan
#
@bot.event
async def setup_hook():
    print(f"{bot.user.name} is online!")
    try:
      synced = await bot.tree.sync()
      print(f"Synced {len(synced)} command(s)")
    except Exception as e:
      print (e)
      for fn in os.listdir("./cogs"):
    if fn.endswith(".py"):
    await bot.load_extension(f"cogs.{fn[:-3]}")

File "c:\Users\PC\Desktop\Noas Bot\main.py", line 47
if fn.endswith(".py"):
IndentationError: expected an indented block

slate swan
#

actual here it should be inside the for loop

cloud dawn
#

!d discord.Interaction.followup

unkempt canyonBOT
stoic apex
#
@client.event
async def on_message(message):
    if message.content == "test":
        print('test')

Anyone know why this isn't working?

cloud dawn
cloud dawn
stoic apex
cloud dawn
slate swan
#

channel.webhooks

cloud dawn
#

Now you are just assigning True to the variables intents and message content

stoic apex
grand willow
cloud dawn
stoic apex
stoic apex
grand willow
balmy bobcat
#

hey can someone help me with discord.ext.tasks ? I'm unsuccessfully trying to setup a tasks.loop

#

first I just tried to copy paste and edit a bit the example given in the docs

from discord.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self):
        self.index = 0
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        chan=self.client.get_channel(986077790296231997)
        await chan.send(f"{self.index}")
        self.index += 1

async def setup(client):
    await client.add_cog(MyCog(client))

but it doesn't work, the bot doesn't seem to like the setup function, but I need it in order to add the cog ?

mighty pilot
#

Is there a way to do something on reconnect? I don't think on_ready is called during reconnect

unkempt canyonBOT
#

discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") for that.

The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") also apply.
mighty pilot
#

Thanks

lucid latch
#

how can i make my bot to connect voice chat?

#

and checks if my bot is playing?

dawn gale
#

i had a discord.py bot a year ago but now it doesn't respond to commands

#

i havent changed anything so has the document updated or is it just buggy

vocal snow
dawn gale
#

waht does that mean

#

im new to this so i dont know much

vocal snow
unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
vocal snow
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

intents = Intents.default()
intents.members = True

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

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

dawn gale
#

ok ty

lucid latch
lucid latch
vocal snow
lucid latch
atomic creek
#

!e

import random
x = random.randint(0.1,0.5)
print(x)
unkempt canyonBOT
#

@atomic creek :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/usr/local/lib/python3.11/random.py", line 295, in randrange
003 |     istart = _index(start)
004 |              ^^^^^^^^^^^^^
005 | TypeError: 'float' object cannot be interpreted as an integer
006 | 
007 | During handling of the above exception, another exception occurred:
008 | 
009 | Traceback (most recent call last):
010 |   File "<string>", line 2, in <module>
011 |   File "/usr/local/lib/python3.11/random.py", line 362, in randint
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/uzalapusox.txt?noredirect

atomic creek
#

!e

print(np.random.uniform(0.55,0.8))
unkempt canyonBOT
#

@atomic creek :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'np' is not defined
atomic creek
#

!e

import random
import numpy as np
print(np.random.uniform(0.55,0.8))
unkempt canyonBOT
#

@atomic creek :white_check_mark: Your 3.11 eval job has completed with return code 0.

0.584142826020576
tough lance
#

@atomic creek #bot-commands

atomic creek
tough lance
alpine cove
atomic creek
#

hahaha

#

ok

alpine cove
#

show your code to sync the bit

#

*bot

sick birch
#

and doesn't work that way

alpine cove
#

!e
print(10 and 10)

unkempt canyonBOT
#

@alpine cove :white_check_mark: Your 3.11 eval job has completed with return code 0.

10
alpine cove
#

thats the reasob

sick birch
#

You can make it global by removing the copy global to line

#

And remove the guild kwargs in the sync function

#

Just be advised it may take up to 1 hour to apply

unkempt canyonBOT
#

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

10 10
sick birch
#

Delete the first line

#

Remove all the guild= stuff in 2nd line

#

Yes should be global after that

alpine cove
#

do:

for g_id in guild:
   bot.tree.sync(guild=discord.Object(id=g_id))
#

yea

sick birch
#

Aye

alpine cove
#

that would also work

slate swan
#

bot ideas please 🥹

slate swan
#

don't make bots without a python knowledge

lucid latch
#

Yes, I have no knowledge of Python, so please teach me. What's wrong with the above attachment?

lucid latch
slate swan
#

not so soon you'll realise that most people in this channel are self taught and student as well

honest shoal
#

There's a guild kwarg in @eternal girder

#

Or guild_ids
In some libraries

#

That's for slash command

#

Oh, I don't know about dpy

#

Let me check the docs

naive briar
#

!d discord.app_commands.CommandTree.command - it also have guild argument

unkempt canyonBOT
#

@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
naive briar
#

I don't understand your question

dawn gale
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

intents = Intents.default()
intents.members = True

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

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

dapper bluff
#
 elif arg == "ping": 
        if user == None: 
            await ctx.channel.send(f'Latency is ${Date.now() - ctx.createdTimestamp}ms. API Latency is ${round(bot.ws.ping)}ms')
#

I tried copying something I found online, but it says ctx.createdTimestamp doesnt exist

slate swan
#

but that's basic python

dapper bluff
#

heeeelp

slate swan
#
@bot.event
async def on_guild_channel_delete(channel):
    channel = bot.get_channel(1035829526766293043)
    embed = discord.Embed(title="Channel Has Been Removed", description=f" Channel: {str(channel.name)}", timestamp=datetime.now() , color=0x4e80cf)
    embed.set_footer(text=f"{channel.guild.name} | Channel System", icon_url="https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif")
    embed.set_thumbnail(url="https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif")
    await channel.send(embed=embed)

@bot.event
async def on_guild_channel_create(channel):
    channel = bot.get_channel(1035829526766293043)
    embed = discord.Embed(title="Channel Has Been Created", description=f" Channel: {str(channel.name)}\n Mention: <#{str(channel.id)}>", timestamp=datetime.now() , color=0x4e80cf)
    embed.set_footer(text=f"{channel.guild.name} | Channel System", icon_url="https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif")
    embed.set_thumbnail(url="https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif")
    await channel.send(embed=embed)```
how do i make it tag the deleted or created channel
rapid knoll
#

how do I check if someone has reacted to a reaction?

slate swan
#

what are u trying to do w that

slate swan
unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message "discord.Reaction.message").

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

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
slate swan
#

then created channel

slate swan
#

for the created one you can do channel.mention

dapper bluff
#

i was here first

slate swan
slate swan
dapper bluff
#

oh

slate swan
#

looks like djs

dapper bluff
#

ok so then how would i get ping

slate swan
slate swan
slate swan
#

OH WAIYT GOT IT TYSM

dapper bluff
#

how do i get client latency

slate swan
#

client.latency ;-;

dapper bluff
#

how do i get the client

#

ohhhh wait

dapper bluff
#
    elif arg == "ping": 
        if user == None:
            await ctx.channel.send(f'Latency is {bot.latency}')```
#

so like this?

slate swan
#

bot.latency*1000 if you want in milliseconds like normal people do yes

dapper bluff
#

@slate swan nononono

#

What im trying to get is how long it takes for a the bot to respond to a user

#

so if I have 50 ping and the bot has 100 it should be 150 ms or smth

#

basically just user ping

slate swan
#

you can't get your ping

dapper bluff
#

I can get when the message was sent and subtract it by the bots ping

#

The time it took for the bot to respond?

slate swan
#

yeah you can do that

dapper bluff
#

ah

slate swan
#

!d discord.Message.created_at

hollow agate
#

It’s not accurate as the API can be slow

unkempt canyonBOT
slate swan
#

this will tell you when the message was created

#

!d datetime.datetime.now this will get you current time

unkempt canyonBOT
#

classmethod datetime.now(tz=None)```
Return the current local date and time.

If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).

If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.

This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
dapper bluff
#

how do i get the message

slate swan
dapper bluff
#

ctx.message.created_at()?

slate swan
slate swan
dapper bluff
#

@slate swan await ctx.channel.send(f'Latency is {round(Date.now()-ctx.message.created_at,2)} ms')

slate swan
#

nope

dapper bluff
#

so what do i do

#

@slate swan

vocal snow
dapper bluff
#

user's latency

alpine cove
dapper bluff
#

wdym ?

alpine cove
#

you can't calculate the user's latency

dapper bluff
#

is that not what im doing there

alpine cove
#

not at all

mighty pilot
#

You can't interact with other users device, just your pc/server and discord

dapper bluff
#

nono let me put it this way

#

im trying to get how long it will take from, the message being sent, to the server responding

alpine cove
#

you are calculating the time it took the bot to receive the message

dapper bluff
#

yes

alpine cove
unkempt canyonBOT
#

property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
alpine cove
#

just use your bots latency

dapper bluff
#

await ctx.channel.send(f'Latency is {round(bot.latency-ctx.message.created_at,2)} ms')

#

?

alpine cove
#

its not exactly what you want but much mure convenient

#

await ctx.channel.send(f'Latency is {round(bot.latency, 2)} ms')

dapper bluff
#

thats not what i want though

alpine cove
#

ik

dapper bluff
#

hes in france, im in us, this shouldnt be giving me the same ms

alpine cove
#

its the bot's latency

dapper bluff
#

i dont want the bot's latency

alpine cove
#

as said

mighty pilot
#

It's still the same latency from discord to your program

dapper bluff
#

look

#

bot latency - the time the message was sent

vocal snow
#

How is that going to calculate the users latency

dapper bluff
#

lets say the message was created at 0:05

vocal snow
#

You want the time taken for a user to send a message and discord to receive it, yes?

dapper bluff
#

and the time now from the bot's perspective is 0:15

#

I can subtract that minus the time the message was made

#

and thats the latency

#

which is 0:10

#

100 ms latency

mighty pilot
#

All you can see is the time between the websocket and your bot

dapper bluff
#

yes thats what im trying to get

vocal snow
#

That's just the bot's latency then

#

Not the user's latency

mighty pilot
#

For user latency you would need access to the user's device. Which isn't a thing

dapper bluff
#

lets say the message was created at 0:05
and the time now from the bot's perspective is 0:15
I can subtract that minus the time the message was made
and thats the latency
which is 0:10
100 ms latency

so if i print this

then print bot.latency()

ill get the same value?

vocal snow
#

There's no way of knowing when the user actually sends the message

dapper bluff
#

there is

#

property created_at
The message’s creation time in UTC.

Type
datetime.datetime

vocal snow
#

How?

vocal snow
#

That's the time that discord receives the message

slate swan
mighty pilot
#

Yea that's when the message is posted on discord not when it was created on their device

dapper bluff
#

oh i thought every packet to the discord bot sent the creation time as a parameter, and that gets it

slate swan
#

discord respects users privacy and doesnt reveal their time zone

dapper bluff
#

I wouldn’t mind it revealing time zone

#

What are you gonna do with it

shrewd apex
torn sail
#

does using @default_permissions on a hybrid command also add a normal permissions check for the message based command?

dapper bluff
#

Over

slate swan
#

might as well expose your IP

shrewd apex
vocal snow
mighty pilot
#

Any piece to the puzzle is one step closer to not being anonymous

shrewd apex
mighty pilot
dapper bluff
#

If message.created_at returns the time the server got the message then what’s the difference between using that and datetime.now()

#

I still think you are wrong

#

await ctx.channel.send(f'Latency is {(Date.now(timezone.utcoffset(-6))-ctx.message.created_at)} ms')

#

how do i get est from utcoffset

#

await ctx.channel.send(f'Latency is { Date.now(timezone.utc) - ctx.message.created_at} ms')

#

this does what I want but I need timezone.utc to be est, how do i get it

sweet moat
#

hi hi! could someone help me figure how i could upload a PIL Editor canvas directly into Discord using discord.py? 😓

dapper bluff
#

not what im trying to do

silk fulcrum
#

having this error when initialising my db

silk fulcrum
#

if your canva is saving locally, then here's a way you could send it:

embed = discord.Embed(title="Title", description="Desc", color=0x00ff00) # creates an embed
file = discord.File("path/to/image/canva_file.png", filename="image.png")
embed.set_image(url="attachment://image.png")
await ctx.send(file=file, embed=embed)```
#

or you might just do await ctx.send(file=file)

#

without making an embed

zealous jay
#

where can I see an example of a slash command sub command?

slate swan
mighty pilot
#

Except you define (interaction: discord.Interaction) and use interaction.response.send_message(...)

#
@app_commands.describe(member='The user you want to see server level for')
async def level(interaction: discord.Interaction, member: discord.Member= None):
    '''Display your level on this server.'''
    if member==None:
        userid = interaction.user.id
        icon = interaction.user.display_avatar
        dname = interaction.user.display_name
    else:
        userid = member.id
        icon = member.display_avatar
        dname = member.display_name
#

Forgot I had some of my code on my phone. This is how I did my slash command sub commands

slate swan
#

what does this mean

#

@mighty pilot do u know

mighty pilot
zealous jay
mighty pilot
#

No problem

slate swan
#

show code for it

slate swan
#

thats not a view.

mighty pilot
#

view=SelectView() he wants to see the code for SelectView()

dapper bluff
#
async def get(ctx,arg,user=None):
    if arg == "ip":
        if user != None:
            if user == discord.User:```
#

how can i do smth like this

#

basically checking if the third arg is a mention

#

I could do async def get(ctx,arg,user:discord.User=None): but that would be inconvient in some circumstances

dapper bluff
# sick birch how so?

lets say I wanted to do !get total bots
or literally any get command with 2 arguments

slate swan
#

how do i fix guild object has no attreibute to icon_url

dapper bluff
#

The program will assume the third is a mention and will error

slate swan
#

i talked abt this last night but it was late

sick birch
dapper bluff
#

yea

sick birch
#

it doesn't need any typehints then, or : str if you want to be explicit

dapper bluff
#

but I also would like commands where the third argument is a mention

slate swan
sick birch
#

You can use typing.Union[] to indicate the 3rd arg can be one of it

dapper bluff
#

what?

dapper bluff
#

obv that doesnt work, but it gives an idea

chilly dove
#

@slate swanits guild.icon not guild.icon_url

slate swan
#

ohh yeah forgot about that

#

thanks ill try that

slate swan
dapper bluff
chilly dove
#

i think its the member intent that enables dpy to cache guild members

#

its just not in the cache

sick birch
# dapper bluff what?

For instance typing.Union[discord.TextChannel, discord.Member] would allow you to either mention a text channel ( #discord-bots ) or a member ( @dapper bluff )

dapper bluff
#

so i could do:

sick birch
#

You can also use typing.Literal in there to be even more precise

dapper bluff
#
async def get(ctx,arg,arg2=None):
    if arg == "ip":
        if arg2 != None:
            if arg2 == typing.Union[discord.User]:```
#

?

chilly dove
#

@slate swan you can enable it in the discord dev thing then pass it into your bot instance

hollow agate
#

typing.* goes in your async def structure.

dapper bluff
#

I just said thats what im not trying to do

hollow agate
#

Take a look at the documents and you’ll find it under Message.

dapper bluff
#

What?

dapper bluff
#

I dont get how this makes no sense to yall

#

What if I want to do !get notes @dapper bluff

#

but i also wanted to do !get server members

hollow agate
#

You can just make a Literal and force them to mention someone or do something else and if it’s neither of those, you check it

dapper bluff
#

im asking how I can check if a string is a mention

hollow agate
#

You can probably get a message out of your second variable with it, however, I’ve never done that so I’m not entirely sure.

dapper bluff
slate swan
#

even more why are u trying to make one cmd be used in multiple ways lol. just making it more complicated

sick birch
dapper bluff
#

More complicated to me sure, but I want it to be less complicated to the user

hollow agate
sick birch
#

You can get very specific with compounding your typehints in a certain way

hollow agate
#

Click API References to read the api docs

dapper bluff
#

which one do i go to

#

dude just link me to the specific attribute

hollow agate
dapper bluff
#

searching through docs is such a nightmare, i dont even know what im looking for

hollow agate
dapper bluff
#

Where now????

sick birch
dapper bluff
dapper bluff
#

Im at message where do I go now

primal token
dapper bluff
#

It was a yes or no question

hollow agate