#discord-bots

1 messages · Page 180 of 1

shut elk
#

um

vale wing
#

@shut elk so in your subclass add an attribute user_id and check if the interaction author's ID is the same

class MyView(discord.ui.View):
    def __init__(self, user_id: int):
        super().__init__(...)
        self.user_id = user_id

    async def interaction_check(self, interaction: discord.Interaction) -> bool:
        if interaction.user.id == self.user.id:
            return True
        await interaction.response.send_message("This button is not for you", ephemeral=True)
        return False
shut elk
#

im dumb sorry thanks 😭

fair magnet
#
import discord
from discord.ext import commands
from snipes3 import scrape_snipes

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='?', intents=intents, help_command=None)

@bot.command()
async def snipes(ctx, *args):
    # Delete command message
    

    # Validate args
    if len(args) < 1:
        msg = await ctx.send("Invalid arguments. Please use the following format: `snipes <ID>`")
        await asyncio.sleep(5)
        await msg.delete()
        return

    msg1 = await ctx.send("Scraping stock...")

    # Scrape stock
    sku = args[0]
    embed = scrape_snipes(SKU=sku)

    if embed != None:
        await msg1.edit(content="", embed=embed)
    else:
        msg = await msg1.edit(content="An error occured. Please try again later.")
        
        # Sleep for 5 seconds and delete message
        await asyncio.sleep(5)
        await msg.delete()

bot.run``` so i have two files snipes3.py and this in my snipes3.py file i have a input where you put the product id you need to scrape but if i use the command my bot is not passing it to my function why ?
shut elk
#

or am i missing something

vale wing
shut elk
#

it says error for the user_id not being provided

#

so like am i supposed to do myView(id) but that only does the previous one that creates the button

vale wing
#

You can do logic you need by yourself

#

I don't quite understand who's supposed to press that button

shut elk
#

but right now, it gives an error of positional arguments not being given since there is an extra parameter, so how is that going to be the user_id of the person who presses the button, if you have to provide the parameter when creating the button

#

I have a command that creates the button and uses the view, using view = myView(), and in the button function, if I click a button it should create another one

vale wing
#

Because it's the ID of user who is supposed to press the button, the user who actually presses the button is in interaction_check()

shut elk
#

there is no one that is supposed to press the button, anyone can

vale wing
#

A wait I misunderstood your question

shut elk
#

ok

vale wing
#

!d discord.ui.View.stop just this

unkempt canyonBOT
#

stop()```
Stops listening to interaction events from this view.

This operation cannot be undone.
shut elk
vale wing
#
async def some_button_callback(self, ...):
    self.stop()
    ...  # do callback```
shut elk
#

mk

shut elk
#

hold up

#

wrong testing channel

vale wing
#

You said "anyone can press the button"

shut elk
#

i tested the wrong channel

icy meadow
#

Hello,I'm trying to import a Button class from my bot to another file function (it's not cog file),I need to load it somehow before I import it?

slate swan
#

why do people ask this question so much

#

I've see the same one for like 4 times in this channel

#

tho it doesn't make sense

#

how to make more than one response as ephemeral

#

the same message have to be ephemeral for more than one member

#

which library

slate swan
#

you cannot control it

#

check pins in this channel, 3rd message

slate swan
#

if you'll send in channel it won't be ephemeral
only responses can be ephemeral

slate swan
#

it should be visible only to you

#

if someone else is seeing it they did the same thing as you did

#

no it's a vote message , which is visible to a team

#

which one? the 1st 2nd or 3rd message

#

the third

#

what do you think the message means by "Only you can see this" below the buttons

slate swan
#

noone other than you can see that

#

the other uses probably used the same cmd as you...

slate swan
#

ofcourse

#

is it possible to 'response' many times to the same interaction ?

#

you can use follups

#

*followups

#

cool

#

!d discord.Interaction.followup

unkempt canyonBOT
slate swan
#

i know thank you

slate swan
#

delete_original_response ?

#

i guess, im not too familiar with discord.py interaction system

#

:/

heady coyote
#

is there a way to use command buy_q ? I tried this and didnt work

#

from .buy import buy_q is init.py file

slate swan
#

hello i need help please

#

i cant import app_commands

#

@bot.command() async def on_guild_channel_create(channel): # Code.. if not u != guild.owner and not u.id in wl_list: await print("PM-Beta: (Анти краш)Создание каналов") await channel.delete()
Bot ignores

slate swan
heady coyote
#

we can go pv to explain it better

cloud dawn
# heady coyote from buy.py
  1. Show the file structure and what file you execute to start the program.

  2. What file do you want to import?

  3. Where are you importing from?

cold sonnet
#

I think he showed all that

heady coyote
#

yes

cloud dawn
#

So you are executing buy to run the program?

heady coyote
slate swan
heady coyote
#

to run

cloud dawn
cold sonnet
#

maybe not all of it

heady coyote
unkempt canyonBOT
slate swan
heady coyote
cloud dawn
heady coyote
#

Pv bro

#

I sent you everything you need

cloud dawn
#

Right-

heady coyote
#

i got this

#

i had to client.tree.add_command(buy_q)

tired notch
#

is it possible to supply more information to a discord button callback? i am trying to make a list of embeds and a button that will edit the embed to the next embed in the list

slate swan
#

subclass view and override the init to provide extra arguments and attributes

tired notch
#

ah, thanks

autumn helm
#

How can I make that this checkmark doesn't appear and you can use the same option twice?

limpid otter
#

Is it possible to take the distance of selected cities using aiohttp from the site?

hushed galleon
upper root
#

Hello guys is it normal that I have created a slash command and it prompt the user to enter a suit of number like 012345 but when i print my variable that I ask the user to fill. It do not show the 0

potent spear
#

!e

int shit = 0125
print(shit)```
unkempt canyonBOT
#

@potent spear :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     int shit = 0125
003 |                ^
004 | SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
upper root
#
@client.tree.command(name="math", description="math")
async def math(itr: discord.Interaction, pid: int):
    print(pid)
    pidss = str(0) + pid
    print(pidss)
    math_url = f".."
    response = req.get(math_url)
    product = response.json()
    await itr.response.send_message(math_url)
potent spear
#

that's how python works...

rare echo
#

why would you need that zero though

upper root
#

so how can i do to add A 0 the number the person is using

potent spear
#

make it a string I guess

upper root
upper root
potent spear
#

an int with a leading 0 is not an octal number...

upper root
#

@potent spear I finally did that pid = format(pid, '08d') was easier tbh

potent spear
#

that's one way

edgy thorn
#

hey Im trying to chain together menu selections in a View()

#

this is the code

#

but I keep getting this error and not sure why

#
  File "D:\repos\Scrimbot\env\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "D:\repos\Scrimbot\cogs\scrim.py", line 27, in cap_callback
    await picks(self)
  File "D:\repos\Scrimbot\cogs\scrim.py", line 62, in picks
    message = await ctx.send("Select Picks", view=self.view)
  File "D:\repos\Scrimbot\env\lib\site-packages\discord\ext\commands\context.py", line 842, in send
    return await super().send(
  File "D:\repos\Scrimbot\env\lib\site-packages\discord\abc.py", line 1522, in send
    with handle_message_parameters(
  File "D:\repos\Scrimbot\env\lib\site-packages\discord\http.py", line 187, in handle_message_parameters
    payload['components'] = view.to_components()
  File "D:\repos\Scrimbot\env\lib\site-packages\discord\ui\view.py", line 219, in to_components
    children = [item.to_component_dict() for item in group]
  File "D:\repos\Scrimbot\env\lib\site-packages\discord\ui\view.py", line 219, in <listcomp>
    children = [item.to_component_dict() for item in group]
  File "D:\repos\Scrimbot\env\lib\site-packages\discord\ui\select.py", line 214, in to_component_dict
    return self._underlying.to_dict()
  File "D:\repos\Scrimbot\env\lib\site-packages\discord\components.py", line 291, in to_dict
    payload['options'] = [op.to_dict() for op in self.options]
TypeError: 'coroutine' object is not iterable```
jaunty hare
#

hi! someone can help me to fix this error?

blazing condor
#

with the code i could be able to assist u better

jaunty hare
#

yeh give me a sec

slate swan
# jaunty hare

@discord.ui.button with a lower-case b to create a new button object. Also your params should be self, interaction, button in that order I think.

jaunty hare
#

thnak u bro

#

like this i guess

shrewd apex
#

replace the = with :

slate swan
#

https://paste.pythondiscord.com/dimiguqeze
someone
Please help me with the error
main.py", line 14, in <module> from discord_slash import SlashCommand, SlashContext ModuleNotFoundError: No module named 'discord_slash'

jaunty hare
blazing condor
blazing condor
#

added

tired notch
#

in discord.py how do i make so someone can only enter a certain range of numbers or only some certain strings as options for a command

blazing condor
#

check that the input is a number within a certain range, you can use the isnumeric() method and check if it is within the range.

tired notch
#

aight hanks

slate swan
#

hey i mistakely add my test application on discord developer badge soo how i switch to my main bot
😢

blazing condor
slate swan
#

from developer portal

blazing condor
slate swan
blazing condor
#

as that is out of my reach at that point

slate swan
blazing condor
#

np

slate swan
open vapor
#

can someone help with my bot something is not working
(like dm me and I'll show you on stream the problem)

#

?

blazing condor
#

u legit just posted that someone will respond, why can't u just talk about it here

#

@open vapor

open vapor
#

cuz my problem is weird but I'll try to explain it.
I did pip install discord but when I tried to run the program it did this

blazing condor
#

send your code in chat brother it helps me

open vapor
#

ok

#

import bot

if name == 'main':
bot.run_discord_bot()

#

import discord

def run_discord_bot():
TOKEN = 'my token is here but i will not show it '
client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user}is now running!')


 client.run(TOKEN)
#

and there's another code that is not related

#

@blazing condor ?

blazing condor
#
import discord

def run_discord_bot():
    TOKEN = 'my token is here but i will not show it '
    client = discord.Client()

    @client.event
    async def on_ready():
        print(f'{client.user}is now running!')

    client.run(TOKEN)

if __name__ == '__main__':
  run_discord_bot()

You put the if statement in the wrong place, used the wrong name in it, didn't import the module before calling the function, and didn't indent the last line properly.

tawny mantle
#
  File "C:\Users\hackt\Desktop\desktop\Exile\main.py", line 5, in <module>
    from views.contact import Confirm
ModuleNotFoundError: No module named 'views.contact'; 'views' is not a package```

Help 🙂
#

@blazing condor

blazing condor
tawny mantle
blazing condor
#

in the main.py file, you should use the following import statement to import the Confirm class you mentioned above

shut elk
#

https://paste.pythondiscord.com/hifogicoyo
This is a button view that I call using a command, but when I call the button, I want it so that only one person can press the button at a time. Although I am making the button disabled, it loads too slow and allows time for multiple people to press the button and enter the code. I am wondering how I can prevent this from happening, since I cannot really do anything with the init, and everything has to be done within this button function. I tried 3 ways: button disable, self.stop(), and using the list append checking if the interaction user id was the first in the list. However, all these methods failed to work and still, multiple people are able to press the button at the same time. Please let me know (with a ping) how I can potentially fix this problem, thanks!

wide whale
#

need to embed an emoji in a response message (pycord), given the emoji name
how 2.

tawny mantle
#
  File "C:\Users\hackt\Desktop\desktop\Exile\main.py", line 5, in <module>
    from views.contact import Confirm
ModuleNotFoundError: No module named 'views.contact'; 'views' is not a package```

Help 🙂
upbeat gust
# wide whale need to embed an emoji in a response message (pycord), given the emoji name how ...

How to show emotions for robots:
Custom emotes are represented internally in the following format:
<:name:id>
Where the name is the name of the custom emote, and the ID is the id of the custom emote.
For example, :python3: is the name:id for :python3:

When sending standard unicode/discord emojis, you just send the unicode character. This is handled differently from language to language, but in python, you can send \N{NAME}, the codepoint, \uFFFF, or just the unicode char itself: 🇦 You can get info on this by using the ?charinfo command

You can quickly obtain the <:name:id> format by putting a backslash in front of the custom emoji when you put it in your client.
Example: \:python3: would give you the <:name:id> format.

When adding reactions, you can either send the unicode for standard emojis, or send name:id, not <:name:id> for custom emojis.
New in 1.1.0 You can use <:name:id>

Animated emojis are the same as above but have an a before the name- ie: <a:name:id>

wide whale
#

danke

rancid vine
#

anyone got a good discord bot tutorial that explains everything?

eager hill
#
voted_users = set()
vote_count = {"Astro": 0}


@bot.tree.command(name="poll", description="Poll")
@app_commands.describe(vote='Your vote')
async def vote(interaction: discord.Interaction, vote: Literal['Duwap', 'Astro']):
    if vote == "Astro":
        if interaction.message.author.id in voted_users:
            await interaction.response.send_message("You have already voted")
            return
        astroID = '@eager hill'
        voted_users.add(interaction.message.author.id)
        vote_count["Astro"] += 1
        await interaction.response.send_message(f'You voted for Astro! Total votes for Astro: {vote_count["Astro"]}')

I am recieving the error py discord.app_commands.errors.CommandInvokeError: Command 'poll' raised an exception: AttributeError: 'NoneType' object has no attribute 'author'
anyone know why and how can i fix it?

shut elk
#

how do you install schedule module?

#

Like where in visual studio code

naive briar
unkempt canyonBOT
naive briar
shut elk
#

or like what is it

naive briar
#

!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").
shut elk
#

like what if i only wanted it to schedule once

ionic garden
#

so i've this function here:

    @commands.hybrid_command(brief="Mock the bot's creator.")
    async def birb(self, ctx: commands.Context, stuff: str = "1 + 1 = 3"):
        """Mock the bot's creator."""
        a_id = ctx.message.author.id
        img = Image.open("resources/img/birb_logic.png")
        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype("resources/fonts/whitneysemibold.ttf", 12)
        draw.text((64, 28), stuff, (200, 200, 200), font=font)
        img.save(f"resources/img/{a_id}.png")
        await ctx.send(file=discord.File(f"resources/img/{a_id}.png"))
        os.remove(f"resources/img/{a_id}.png")
```and right now the problem is at the end, with `os.remove`
windows is telling me it's used by another process whenever i try to call the command
but idk what process could be using it?
naive briar
unkempt canyonBOT
#

stop()```
Gracefully stops the task from running.

Unlike [`cancel()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.cancel "discord.ext.tasks.Loop.cancel"), this allows the task to finish its current iteration before gracefully exiting.

Note

If the internal function raises an error that can be handled before finishing then it will retry until it succeeds.

If this is undesirable, either remove the error handling before stopping via [`clear_exception_types()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.clear_exception_types "discord.ext.tasks.Loop.clear_exception_types") or use [`cancel()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.cancel "discord.ext.tasks.Loop.cancel") instead.

Changed in version 2.0: Calling this method in [`before_loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.before_loop "discord.ext.tasks.Loop.before_loop") will stop the loop before the initial iteration is run...
naive briar
#

Requires minimum effort of research

naive briar
ionic garden
#

could you elaborate?

naive briar
#

Since the discord.File's fp argument can be a bytes-like object, you can use something like io.BytesIO buffer to create an instance from it.

# assuming that you've already edited the image
buffer = io.BytesIO()
image.save(buffer, format="PNG") # save/write the image data to the buffer
buffer.seek(0)

file = discord.File(fp=buffer, filename="out.png") # use the buffer to create a file instance
await ctx.send(file=file)
ionic garden
#

uh

#

what does buffer.seek(0) do?

#

and should i preferably use with, given that it's a file context?

shut elk
#

@naive briar

naive briar
# ionic garden what does `buffer.seek(0)` do?

Change the bytes stream position; after the image was saved, the stream position is changed to the end of the bytes that were saved or written, and you need to seek back to the start of the buffer to read the data that was saved or written.

#

!e

import io

buffer = io.BytesIO()

buffer.write(b"Cat")
buffer.write(b"Meow")

print(buffer.read()) # <-- returns "None"

buffer.seek(0) # seek back to the beginning
print(buffer.read())
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | b''
002 | b'CatMeow'
shut elk
#

ok

shut elk
#

oh wait nvm i didnt import tasks 💀

naive briar
#

You can if you want to make sure that the buffer will be closed

#

But I think Python will get rid of it after it's used anyway

shut elk
#

is there a specific reason why it didnt loop through

naive briar
#

What are you even trying to do with it

shut elk
#

so i have a button that sends when the view is called as per usual

#

and I want to make it so when 10 seconds of the button being sent out, the code will execute and the button will be disabled

shut elk
naive briar
#

Just use asyncio.sleep then yert

#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
shut elk
#

await asyncio.sleep(10), but it will run multiple times right

naive briar
#

No

shut elk
#

Like multiple button presses = multiple instances of asyncio sleep..

ionic garden
#

why does message.edit not have a file= argument and instead requires you to put stuff in a list

naive briar
#

Probably API limitations

shut elk
naive briar
#

What

#

It's just a normal coroutine

shut elk
#

aight thx

shut elk
# naive briar It's just a normal coroutine

also, i have this error where when multiple people click this button in the same time, it lets them do so and the code executes multiple times. I tried making some gateways for the function but it does not work somehow. How would I make this only run once and pressed once, by the first person that presses it?

torn sail
naive briar
#

I think he is talking about io.BytesIO

#

!d io.BytesIO

unkempt canyonBOT
#

class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
delicate moat
#

I'm trying to make a website with a discord login using OAuth2. Everything works but when i print out the user id of the user on my flask website it is different from my actual id. Does somebody know why

delicate moat
# sick birch Could it be your bot's ID?

ok turns out it was some sort of rounding error. I have a flask program and i tried to send in the id with this: flask.rendertemplate("htmlfile", id={{user_id}})

turns out in my html file i hda to do this:

var userId = {{ id |tojson|safe}};
#

the "tojson|safe" part makes it round safely

potent spear
#

the good ol piping

torn kelp
#

hi, who can help me with my bot code? i have a problem with discord.py

naive briar
#

Just ask about your problem

sick birch
#

Might anybody know if discord.py dispatches on_guild_join for the initial connection?

#

I know discord sends out all of your guilds in a massive GUILD_CREATE payload

#

Not sure if discord.py counts that as "on_guild_join"

pliant gulch
sick birch
#

Gotcha. So on_guild_join is not dispatched before on_ready?

pliant gulch
#

Then for each future it'll dispatch on_guild_join per each guild that is AVAILABLE

#

Since guilds can be un-available as well which yields another diff event

sick birch
#

And which is that?

pliant gulch
#

holdon

sick birch
#

Ah, on_guild_join being discord.py's own event explains all of it haha

pliant gulch
pliant gulch
#

And probably the main example would be READY

#
READY (DISCORD API) => `on_connect` (DISCORD.PY)
chunking guilds => `on_ready` (DISCORD.PY)
sick birch
#

Yeah, I thought on_guild_join was one of Discord's events (GUILD_CREATE) but as you explained, it doesn't seem to be

pliant gulch
#

Yeop

#

nevermind I read a double negative

sweet ore
#

Hello, I am making a streak tracker. How can I scheduled messages?

#

Let's say I want the bot to send me the message at 9 pm

naive briar
#

!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").
sweet ore
#

Well, that's loop

#

It will work tho

#

but... it won't have the same functionality as a message schedule

#

Wait, there's time

#

My bad, Thanks! @naive briar

sick birch
#

Yes it's a 2.0 feature

#

Pass in a datetime object

#

It'll be ran at that time every day

sweet ore
#

Right

slate swan
#

Hello!

I am trying to make a command in my bot that if 1 role is present it runs the function or if another role is present it does it, but if not, return an error

How would I do something like that?

#

And I want to be able to get the roles via there ids

sweet ore
#

To create buttons I used discord.ui

#

Is there any official library?

#

i should read the docs

#

If anyone can tell that'd be great (i dont have to read docs...)

torn sail
sweet ore
slate swan
sweet ore
#

bad 👁️

#

Oh okay, Thank you for clearing the confusion

sweet ore
#

The discord.ui is not a module of the discord.py library and it is not an official package.

slate swan
#

chatgpt isn't always necessarily right, its just an AI afterall lol

#

!d discord.ui.View it exists in dpy

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.
sweet ore
#

I am messing with it

#

tho it is useful

sweet ore
slate swan
#

in most cases, yes

sweet ore
slate swan
#

tho for discord.py you'll always get wrong/bad answers

sweet ore
#

Quite often

vale wing
slate swan
#

Hello!

I am trying to make a command in my bot that if 1 role is present it runs the function or if another role is present it does it, but if not, return an error

How would I do something like that?
And I want to be able to get the roles via there ids

#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
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 **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, 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 [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") 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
#

use this check

loud junco
#

i can do ?

stats = Stats.value(ctx)
await ctx.send(stats.area)
naive briar
#

What

loud junco
slate swan
#

no

#

you need an instance of Stats, not the class

loud junco
#

this is what i do for non-async

#

and it works

naive briar
#

I literally just explained like yesterday

#

Or at least not even 5 days ago

loud junco
naive briar
#

OOP moment

loud junco
#
import asyncio


class J:
    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2

        print(self.var1, self.var2, sep="\n")

    @classmethod
    async def new(cls):
        # do some async things
        var1 = await asyncio.sleep(0, result="Variable 1: Cat")
        var2 = await asyncio.sleep(0, result="Variable 2: Meow")

        return cls(var1=var1, var2=var2)

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

ins = loop.run_until_complete(J.new())
loud junco
#

or are there some other better ways to get this done

#

i just want to import the whole chunk of variable one time instead of calling it one by one

#

the variable is in my database

slate swan
unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | 2
002 | Traceback (most recent call last):
003 |   File "<string>", line 9, in <module>
004 | AttributeError: type object 'Stats' has no attribute 'a'
slate swan
#

same goes for your your Stats class, you add the bot attribute when the class is initialised

#

so trying to use it will raise an error

loud junco
#

but i cant async the init either

#

i dont even know how to search solution for this online 💀

slate swan
#

you dont need a class if its just for returning a value

#

just use a simple async function

loud junco
loud junco
naive briar
#

You need to await the coroutine an async function returns

loud junco
loud junco
naive briar
#

Learn OOP

loud junco
cunning pasture
#

Has there been a poll done on if people prefer slash commands or prefix/traditional commands?

naive briar
#

Prefix command >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Sl*sh command

vocal burrow
#

how to fix this

#

AttributeError: module 'discord.ext.commands' has no attribute 'Cogs'

naive briar
#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
cunning pasture
#

I have a 3 param command

vocal burrow
#

ok

cunning pasture
#

Slash command seems really convenient for that

#

@naive briar do you have a discord bot? You seem fairly active in this channel..

naive briar
#

I'm just doing it for fun

loud junco
#

dont ask about the if-else loop that works for that

cunning pasture
#

LOL.

loud junco
cunning pasture
#

Mine is complicated param

sweet ore
#

I want to email my monthly progress, is it possible to email using discord.py? If so, are there any cons?

unkempt canyonBOT
#

Source code: Lib/email/__init__.py

The email package is a library for managing email messages. It is specifically not designed to do any sending of email messages to SMTP (RFC 2821), NNTP, or other servers; those are functions of modules such as smtplib and nntplib. The email package attempts to be as RFC-compliant as possible, supporting RFC 5322 and RFC 6532, as well as such MIME-related RFCs as RFC 2045, RFC 2046, RFC 2047, RFC 2183, and RFC 2231.

The overall structure of the email package can be divided into three major components, plus a fourth component that controls the behavior of the other components.

loud junco
#

WAIT THERE IS???

sweet ore
#

Thank you

cunning pasture
# loud junco rpm trade buy hydro a 123
    @app_commands.command(name = "imagine", description = "Generate an anime image!")
    @app_commands.choices(quality=[
            app_commands.Choice(name="low", value="fast"),
            app_commands.Choice(name="medium", value="medium"),
            app_commands.Choice(name="high", value="slow"),
            ])
    async def imagine(self, interaction, prompt : str, negative_prompt : str, quality: app_commands.Choice[str]):

This is mine, the reason slash commands might be better for me is because prompt and negative prompt can be like “Sail boat, flying, sky”

cunning pasture
#

Amazing command

cunning pasture
loud junco
#

!paste

cunning pasture
#

why

loud junco
cunning pasture
#

I clicked into it

loud junco
#

?

cunning pasture
#

it’s just…

#

so much.

loud junco
#

ahem

daring adder
#

Good afternoon sir, I have a question sir, can anyone help me to guide me on making the auto aap game growtopia and create bots from bot discord sir

cunning pasture
# loud junco ahem
        loop = asyncio.get_event_loop()
        loop.run_in_executor(None, waifudiffuser.imagine, prompt, negative_prompt, ctx, loop, msg)
cunning pasture
#

(Quality isn’t used because image generation is computationally expensive and I can’t afford a host XD.)

cunning pasture
loud junco
#

waifu diff user or waifu diffuser

cunning pasture
#

Diffusion -> diffuser something that diffuses something

#

So it diffuses waifus

#

XD

#

Want to see some of the horrible results and progress??

loud junco
#

horrible results are always good when u end up like me
name 'bot' is not defined
name 'bot' is not defined
name 'bot' is not defined
name 'bot' is not defined

daring adder
daring adder
loud junco
#

u are trying to make a growtopia game on discord?

#

shessssssh

cunning pasture
#

It can do hands now which is good

loud junco
#

wait

#

can u show me them without hands

#

but dm
they are going to go rage if u flood more

cunning pasture
#

whoops

daring adder
cloud dawn
#

Most action I've seen here in years.

slate swan
#

How to display linked youtube video thumbnails in embeds?

upbeat gust
slate swan
#

I figured it out anyway.

icy meadow
#

how i can import a view from file1 to file2 ?

from extensions.Dashboard import CopyDropDownView

ImportError: cannot import name 'CopyDropDownView' from 'extensions.Dashboard'

class DashboardDropdown(discord.ui.Select):
    def __init__(self, emoji_list=list):
        self.emoji_list = emoji_list      
        
        options = []
        super().__init__(placeholder='Select Extension To Setup...',
                         min_values=1, max_values=1, options=options)
        
    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == 'welcome_goodbye':
            await WelcomeGoodByeDashboardEmbed(interaction=interaction,guild=interaction.guild)

class CopyDropDownView(discord.ui.View):
    def __init__(self, emoji_list:list):
        super().__init__(timeout=None)
        self.emoji_list = emoji_list
        
        self.add_item(DashboardDropdown(emoji_list=self.emoji_list)
robust fulcrum
slate swan
#

running user account as a bot

pastel basin
#

hey, wheenver i restart my bot i cant interact with the buttons

#

How to make buttons persistent?

pastel basin
slate swan
#
@client.event
async def on_member_join(member):
    channel = client.get.channel("1064291777072337026")
    await channel.send("Hallo")

why is there no message when someone joins the server

kind trellis
#

Can modals have a description?

tame gazelle
#

Any1 can make a code that runs on pc/vps that acts as a discord account not as a bot

naive briar
#

!d discord.Client.get_channel

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
naive briar
#

What

slate swan
#

how should I do that

#

ducky_devil ```py
import dataclasses

@dataclasses.dataclass
class Getter:
bot: "Bot"

@property
def channel(self):
    return self.bot.get_channel

bot.get = Getter(bot)

slate swan
#

and the ID should be an integer

#

Ah ok

slate swan
#
 channel = client.get_channel(1064291777072337026)

so? @slate swan

#

not the id,

#

without id?

#

it's the name of the argument, you don't type that out there lol

slate swan
#

just replace the dot with _

slate swan
fair magnet
#
async def snipes(ctx, *args):
    if "staff" not in [role.name for role in ctx.author.roles]:
        return````
#

is it wrong that way i only want that staff can use the role

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

My bot has admin perms, how can I remove the messages?

#

of a channel

#

i dont want to recreate the channel

#

it will change the channel id and other bad stuff will happen

white citrus
#

you can't get the channel id again, it's unique for each channel

pastel basin
#

That's why im asking "how can i remove\delete messages"

white citrus
#

A normal message?

pastel basin
#

ye...

white citrus
#

ctx.message.delete()

pastel basin
#

like !clear 1000

white citrus
pastel basin
white citrus
pastel basin
#

To delete 200 msgs, should I use a for loop?

#
for _ in range(201):
  ctx.message.delete()
slate swan
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
white citrus
#

I got some error

pastel basin
pastel basin
lament depotBOT
slate swan
#

@slate swan I've tested it now and there's still no message when someone joins

#

you need member intents

naive briar
#

!d discord.Intents.members

unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

slate swan
#

so what do i have to add i.e. code

#

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

slate swan
#

something like this, but you set members to true instead of message_content

#
intents.members = True

?

#

@slate swan

heady verge
#

how do i get the banner and guild_avatar of the user

#

when i use {user.guild_avatar} it replies with none and {user.banner} returns with none
but if i use {user.guild_avatar.url} it says AttributeError: 'NoneType' object has no attribute 'url'

naive briar
#

What's so confusing about it

heady verge
#

mhm, then what abt banner

#

i have banner, but it replies with none

naive briar
#

Then they also don't have a banner

heady verge
#

i do have banner and i used the cmd

naive briar
unkempt canyonBOT
#

property banner```
Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
fair magnet
#

at what do i have to look if i want to make a ch

#

ping backup channel

slate swan
#

I have now managed that when someone joins the server, a message comes, but the commands no longer work can anyone help

slate swan
#

do you need the code?

hardy cloak
#

yeah, but not with ctx beacuse for some reason it doesnt work for me

#

If you use ctx then i cant help you

#

lets go to dms alright @slate swan ?

#

@slate swan Just dont send the token alright?

waxen basin
#

Where can i learn to code bots?

cold sonnet
slate swan
#
@app_commands.describe()
async def ea(interaction:discord.Interaction):
    def check(reaction, user):
        return user == interaction.user
    await interaction.response.send_message('**Please react to this message with the emoji you want to add**', ephemeral=False)
    the_reaction = await bot.wait_for('reaction_add', check=check)
    await the_reaction[0].emoji.save(the_reaction[0].emoji.name+".png")
    img = discord.File(the_reaction[0].emoji.name+".png")```
young dagger
#

What's wrong with this code?

        timestamp = member.joined_at.strftime("%b %d, %Y %H:%M")["timestamp"]
        fmt_time = discord.utils.format_dt(timestamp, "f")

        embed.add_field(name="Join Date:", value=f"{fmt_time}", inline=True)```
naive briar
#

What's wrong with it then

cold sonnet
#

retiring from this channel was the right choice

naive briar
#

Send the whole error / code then

#

I can't see where in the code or error that is connected

unkempt canyonBOT
slate swan
slate swan
young dagger
naive briar
#

!d discord.Guild.create_custom_emoji

unkempt canyonBOT
#

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

Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.

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

The image kwarg needs to a bytes object

#

Not str

naive briar
#

In line 97

slate swan
naive briar
#

Just read the file bytes?

#

This is literally basic Python

naive briar
# slate swan it is
File "C:\Users\user\Desktop\Other\Bots_For_Sell\cleevno\bot.py", line 97, in ea
await interaction.guild.create_custom_emoji(name=the_reaction[0].emoji.name,image=str(the_reaction[0].emoji.name)+".png")
#

Seems like it, huh?

#

It's literally in the error

slate swan
#

ah i forgot the last line

#

to do a slash commands inside a cogs file i use @lavish micamands.command or @bot.tree.commands?

naive briar
unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
slate swan
naive briar
#

With .command()

slate swan
#

app is stll underlined

naive briar
#
@app_commands.command()
slate swan
#

ahh

slate swan
#

mb

#

i have 2 ()

#

deleted them

#

still an error

naive briar
#

What's the error then

slate swan
#

@strange knoll.commands.command()

#

its not an error but underlined

#

it is an error

#

app.commands isnt definied

#

you can't use an object without importing it.

#

i have to import app_commands in the cog file too?

#

ofcourse, if you're using it

naive briar
#

That's just how Python works

slate swan
#

ye sorry i had forgotten lol

#

if i have 50 cogs file i have to import all of them here?

#

for all my cogs

naive briar
#

Use for loops

ionic garden
#

should i store discord user id as string or int in my discord bot db, or does my question not have enough context

naive briar
#

Integer, at least that's what I do

#

Why did you think about storing it as string anyway

ionic garden
#

the existing codebase stores uids as strings

young dagger
#

Can someone tell me what's wrong with this code please?

@client.command(name = 'whois')
async def whois(ctx, member: discord.Member = None):
    # Check if the command was used in the correct channel
    if ctx.channel.id == 745832741135712386:
        if member is None:
            await ctx.send("Please provide a user.")
            return

        # Get the URL of the modnoted user's avatar
        avatar_url = member.display_avatar.url

        embed = discord.Embed(title=f"", description=f"", timestamp=datetime.datetime.now(), color=discord.Color.blue())
        embed.set_author(name=f"{member.name}#{member.discriminator}", icon_url=avatar_url)
        embed.add_field(name="User", value=member.mention, inline=True)

        # Send the embed to the channel
        await channel.send(embed=embed)```
ionic garden
#

we're gonna need some errors or smth

young dagger
#

There is no errors

naive briar
#

And setup logging to log the errors

peak loom
#

I'm trying to make a mute command, but I keep getting this error.

Traceback (most recent call last):
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 46, in mute
    await member.add_roles(mutedRole, reason=reason)
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/member.py", line 1018, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/http.py", line 738, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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

Traceback (most recent call last):
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
naive briar
#

Your bot just don't have to permission to edit the roles of the target member

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
peak loom
#

And I have it aswell.

young dagger
naive briar
#

Are you really sure?

peak loom
#

Now it gives me this.

#
Traceback (most recent call last):
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 46, in mute
    await member.add_roles(mutedRole, reason=reason)
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/member.py", line 1018, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/http.py", line 738, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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

Traceback (most recent call last):
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/juicebotw/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
slate swan
#

When command is run or on bot run?

peak loom
peak loom
slate swan
peak loom
#

.*

slate swan
naive briar
peak loom
slate swan
#

We rocking slash 💪

peak loom
#

F**k.

#

I just realized that.

peak loom
#

still*

naive briar
#

Is the mute role still higher than the bot's highest role

naive briar
#

Also Discord has timeout command built-in btw

peak loom
#

!hastebin

#

!paste

cerulean elbow
#

Hi 👋 I'm trying to add a embed.set_thumbnail {image_url} but I keep getting a syntax error. Help pls

static holly
#

i try help you

cerulean elbow
# static holly i try help you

Thanks, & here's a snippet embed.set_thumbnail(url={string}) I replace string with the image url, but I get a syntax error 🤔

hollow gazelle
#

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

hollow gazelle
#

how do i do it for py cord

cerulean elbow
static holly
# cerulean elbow Prob url 🤔
embed.set_thumbnail(url=ctx.author.avatar.url)

or

embed.set_thumbnail(url=https://......)

or

file = discord.File(choose_image, filename="image.gif")
        embed.set_image(url="attachment://image.gif")
static holly
peak loom
#

How do I make a slash command?

cerulean elbow
cerulean elbow
static holly
cerulean elbow
peak loom
cerulean elbow
static holly
cerulean elbow
static holly
#

you can

cerulean elbow
slate swan
#

HI, how to make something like @novel apex ?

hollow gazelle
#

Anyone have a base drop down menu code

slate swan
#

@bot.event
async def on_webhook_create():
How do I remove a webhook?

peak loom
slate swan
#

hey i have some problem in host bot with discloud
when i upload my codes in it it show

#Traceback (most recent call last):
D  File "/home/user_974333490105552897/main.py", line 2, in <module>
*    from discord import SlashCommandGroup
�ImportError: cannot import name 'SlashCommandGroup' from 'discord' (/usr/local/lib/python3.11/site-packages/discord/__init__.py)```
#

but it work in vs codes

young dagger
#

How can I make this work?

        timestamp = member.joined_at
        fmt_time = timestamp.strftime(timestamp, "f")
        embed.add_field(name="Joined Server", value=f"{fmt_time}", inline=True)```
#

The result should show a different time and date for each person based on their time zone

tawny mantle
#

Who can help me to fix my code? Paying with nitro or PayPal… DM ME

young dagger
#

This is not what I'm looking for. I want it to be displayed as this example <t:1673976900:f>

#

But instead of current time, use the time when the member actually joined the server

young dagger
slate swan
slate swan
# young dagger No
timestamp = member.joined_at.strftime('%d %B %Y %I:%M %p'))
embed.add_field(name="Joined Server", value=f"{timestamp}", inline=True)```
rare echo
slate swan
#

here now try

slate swan
#
async def on_webhook_create(message):
    webhooks = await message.channel.webhooks()
    for webhook in webhooks:
        await webhook.delete()```
ignore
young dagger
#

I want it to be showed as this

slate swan
slate swan
slate swan
slate swan
#

try now

young dagger
slate swan
#

just try

#

and see

young dagger
slate swan
#

wait lemme show you

young dagger
static holly
#

what is the problem please?
from liste_bjr import reponse_description
ModuleNotFoundError: No module named 'liste_bjr'

slate swan
young dagger
slate swan
#

oh 24 hrs format

young dagger
#

I told you I want it to appear using this format
<t:1673979360:f>

slate swan
#

lemme try in my bot & show you

slate swan
mental hollow
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
mental hollow
#

@young dagger that’s what ur looking for

young dagger
#

Yeah

slate swan
#

😮

young dagger
mental hollow
#

instead of just f

young dagger
mental hollow
#

do you know what a kwarg is?

young dagger
fading marlin
#

Looks like it should work pithink

#

Why do you say it's not working?

young dagger
static holly
#

please i need help 😕 i'm lost...

young dagger
fading marlin
young dagger
fading marlin
#

Did the bot respond before you added that line?

young dagger
#

Yes

fading marlin
#

Then you have an error handler that's eating your errors

young dagger
#

Wait

#

No it worked :/

#

My bad, thanks guys

fading marlin
#

Huh?

#

Oh ok

young dagger
static holly
#

i'm lost...

young dagger
#

@mental hollow @fading marlin My second question. How can I use the same method for Account Created when timestamp = member.joined_at?

mental hollow
#

!d discord.User.created_at

unkempt canyonBOT
#

property created_at```
Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.
young dagger
#

Right?

fading marlin
#

You can have multiple timestamps 🤷

mental hollow
#

^

sick birch
#

Just call the variables different things

young dagger
mental hollow
#

much easier

#

and you would know what timestamp is for what

young dagger
static holly
#

i have a XX folder and yy.py in this folder. in yy.py i have a variable.
Now when code with:
from XX.yy import variable, i got the error "No module named "variable"...

mental hollow
#

dont create the variable in the first place

slate swan
#

My code:

async def on_webhook_create(message):
    webhooks = await message.channel.webhooks()
    for webhook in webhooks:
        w = await webhook.delete()
        print(w)```
#

Error

#

Pls help

sick birch
young dagger
slate swan
sick birch
#

What does it say in your console?

slate swan
slate swan
slate swan
mental hollow
mental hollow
sick birch
#

Doesn't seem like there's an event to detect webhook creates

slate swan
#

:/

mental hollow
mental hollow
#

.

#

that’s an attribute

#

not an event

slate swan
#

!d discord.on_integration_create

unkempt canyonBOT
#

discord.on_integration_create(integration)```
Called when an integration is created.

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

New in version 2.0.
slate swan
#

webhooks are integrations.

young dagger
#

Well it didn't work

mental hollow
#

do you know what variables are?

slate swan
#

@mental hollow@slate swan@sick birch discord.AuditLogAction?

slate swan
mental hollow
#

my bad

slate swan
#

(

young dagger
coral flicker
#

!rule 6 this is not allowed

unkempt canyonBOT
#

6. Do not post unapproved advertising.

slate swan
#

How can I delete a newly created webhook

mental hollow
# young dagger Yes

great, so when using discord.utils.format_dt, replace the timestamp variable with its actual value

slate swan
#

Hmm

#

on_guild_channel_update ?

young dagger
mental hollow
#
        timestamp = member.joined_at
        fmt_time = discord.utils.format_dt(timestamp, "f")
        embed.add_field(name="Joined Server", value=f"{fmt_time}", inline=True)```
#

that was the code you provided us with

#

with what I said, you should pretty easily be able to do what you wanted

#

if you can’t, you clearly don’t know what variables are, and in that case, you should probably try to work on a smaller project before creating a discord bot, creating a discord bot is quite difficult / not straightforward and it would help you massively if you knew basic Python

young dagger
young dagger
#

Thanks

young dagger
#

Makes sense

steep totem
#

Hey! What can be the problem here? The server id correct, 100%, but i only get "You don't have a license."

authorized_server_id = "id"

@client.event
async def on_message(message):

    if message.author == client.user:
        return

    if message.content.startswith('$statsimportant'):
        if message.guild.id == authorized_server_id:
            await message.channel.send("Hello!")
        else:
            await message.channel.send("You don't have a license.")
sick birch
#

A string will never equal an integer

#

!e print("12345" == 12345)

unkempt canyonBOT
#

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

False
slate swan
#

Might anyone know why my bot is instantly giving exit code 0 when I try to run it?

sick birch
#

Not without code

steep totem
sick birch
#

Code 0 is success

slate swan
#

**Error:
TypeError: on_guild_channel_update() takes 0 positional arguments but 2 were given
My code:

async def on_guild_channel_update():
    print("Text")```**
#

?

sick birch
#

!d discord.on_guild_channel_update

unkempt canyonBOT
#

discord.on_guild_channel_update(before, after)```
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.

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

It takes before and after

slate swan
# sick birch Code 0 is success

Well yeah, but the bot itself is not coming online Shrug Not made any major changes to the code recently.

async def main():
    for filename in os.listdir(cogs_folderpath):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')
    await bot.start(TOKEN)

asyncio.run(main())

You know what, it's probably an issue with my Python or my IDE actually.

(edit: pycharm issue, works fine when I run it in terminal)

slate swan
#

Thank you

steep totem
#

Hey!


first_server_id = "1043898005767598153"
second_server_id = "69"

@client.event
async def on_message(message):

    if message.author == client.user:
        return

    if message.content.startswith('$statsimportant'):
        if str(message.guild.id) == first_server_id:
            await message.channel.send("statsimportant embed first")

        if str(message.guild.id) == second_server_id:
            await message.channel.send("statsimportant embed second")

        else:
            await message.channel.send("You don't have a license.")

When i try using the $statsimportant in the first server, then i got both "statsimportant embed first" and "You don't have a license." why is this?

slate swan
#
async def on_guild_channel_update(before, after):
    await after.edit(name=before.name)

Ignore

cedar turret
#

idk what to do\

slate swan
cedar turret
cedar turret
peak loom
#
@bot.command(name='hello')
async def _hello(ctx):
    await ctx.send('Hello!')
#

This isn't working.

slate swan
cedar turret
peak loom
slate swan
peak loom
#

No .py

slate swan
static holly
#

would someone be kind enough to help me please?

slate swan
#

Puthon install

slate swan
hushed galleon
slate swan
#

!d python -m

unkempt canyonBOT
#

Python Runtime Services

The modules described in this chapter provide a wide range of services related to the Python interpreter and its interaction with its environment. Here’s an overview:

cedar turret
cedar turret
peak loom
slate swan
#

You must run the file that you installed from python website

static holly
hushed galleon
#

if you dont tick the option to add python to path, python and pip wont be usable in the command line, but on windows you're given the py launcher by default which works as an alternative

cedar turret
#

i have it downloaded and i runned it

hushed galleon
#

assuming the web installer included the python launcher, you would run py -m pip install discord.py

static holly
# slate swan ?

but the topic is closed... and i can't open it. I need help i'm locked on my project

cedar turret
#

i tried downloading python again in ubuntu and this time it worked ithink

#

if this is right thing

hushed galleon
hushed galleon
cedar turret
#

@copper yarrows

static holly
#

@hushed galleon you can see the code again

sick birch
static holly
#

on cmd windows

hollow gazelle
#
@bot.slash_command()
async def banner(ctx, user:discord.Member):
    user = await bot.fetch_user(user.id)
    banner_url = user.banner.url
    await ctx.respond("{}".format(banner_url))
``` how would i make this code send like this
#

nvm ive got it

shrewd apex
shrewd apex
unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
hollow gazelle
#

so i do /banner {user} and comes up with an embed but how to i mention that user or have it put ther name i want it to say {user} banner

#
@bot.slash_command()
async def banner(ctx, user:discord.Member):
    user = await bot.fetch_user(user.id)
    banner_url = user.banner.url
    embed = discord.Embed(title="Users Banner", color=0xFF0000)
    embed.set_image(url='{}'.format(banner_url))
    await ctx.send(embed=embed)
``` this the code
slate swan
young dagger
#

From my understanding

slate swan
slate swan
#

How can I make it so that you can only run a specific command if you have admin rights?

vague fiber
#

There is no way to see a users connections via bots is there?

young dagger
vague fiber
vague fiber
#

Are you trying to create a bot to play audio?

shut elk
young dagger
lusty smelt
#

Then you wouldnt need to "check" if pressed because a button has a callback method.

lusty smelt
young dagger
lusty smelt
vivid gate
#

Hello do anyone know where can I learn python discord library?

vivid gate
lusty smelt
#

If you check the Github they have examples in their repo.

shut elk
#

i meant the other one for c1

vivid gate
shut elk
#

oh wait

#

it is the right ss 1 sec

lusty smelt
vivid gate
shut elk
lusty smelt
#

Absolutely; I will do my best to support. I may be away~

shut elk
#

should i send u my code

shut elk
lusty smelt
# shut elk what is inheritance? i dont get what u mean by question

I may be referencing it wrong; but I personally call it sub-classing.. its essentially when you do
class my_view(discord.ui.View):

the "my_view" object is a copy of discord.ui.View and knows everything it knows. But the twist is I can now either overwrite its defined methods/attrs or add my own.

#

There is way more to it then what I just described though.

sick birch
#

Inheritance is one of the pillar of object oriented programming, I'd recommend reading up on it online as it's quite important to know

lusty smelt
#

Yes!

#

Thanks Robin ❤️

sly token
#

I'm going to ask a little question with discord, I want to show these boost winners on a certain channel, how do I do it?

sick birch
#

Can you elaborate on what you mean by "boost winner"?

shut elk
#

and u can see with my code right? i sent it

sly token
#

the one with the boost pressed

lusty smelt
#

I did see your code; either; A. the Interaction timed out (took longer than 3 seconds to reply/defer) or B. Your view/setup is not correct and I would print the interaction parameter and see what it is.

#

It should be an object; but again. I would follow Robin's instructions first. It will serve you better than solving your current situation ever could.

lusty smelt
#

Learn class Inheritance; It is a very strong skill to have.

spiral crypt
#

hellloo

@client.event
async def on_raw_reaction_add(payload):
    if payload.emoji == starboard_emoji:
        print("we made it here")

I have this bit of code here, and i want it so that if it detects that soemone added a specific emoji to a message itll print that message but it isnt printing it for some reason, anyone know why?

shut elk
#

How can I fix my error tho?

lusty smelt
lusty smelt
spiral crypt
#

i looked up how to check for reactions earlier on on google and that was one of the options so i just went with it, it worked for my other need for it so i didnt wanna touch it xd

lusty smelt
shut elk
#

wait why would i create another subclass for that tho

lusty smelt
shut elk
#

But then I also have a problem where when multiple people press in the same time, it registers multiple

lusty smelt
shut elk
#

even if I implemented ways to stop it from happening, I tried like lots of ways but none worked

lusty smelt
#

Okay so you want a button to only be clicked once? Once per user?

#

Maybe only a specific user? I can teach you that.

lusty smelt
shut elk
#

that i think i can do but multiple users, I implemented many ways that should've worked but there seems to be like poeple slipping in

#

and resulting in multiple buttons being created from that

#

cuz its supposed to be 1 click --> make 1 button

lusty smelt
#

People dont "slip in" code does what it is written to do

shut elk
#

but it becomes 2 clicks on one button ---> makes 2 buttons

shut elk
lusty smelt
#

Okay you can disable a button after it is clicked.

shut elk
shut elk
shut elk
spiral crypt
shut elk
#

i did it later on, but there is always going to be people that are able to slip in, that's why i made the gateway of the self.pressed, along with trying to do the self.stop, list way, etc

lusty smelt
spiral crypt
#

im using @client.event, andd im assuming im outside

shut elk
#

I've had this problem for a bit, but ig now I limit the amt of ppl that can click it so not many people are going to press it at once, but if there ends up being too many people anyways, i just wanna know how I can prevent it if there's no solution then its fine

spiral crypt
#

regardless my other thing thats also in the on_war_reaction_add is working just fine, its just the if statement comparing the payload.emoji to the starboard_emoji isnt responding with True and I dont know why

lusty smelt
spiral crypt
#

im comparing payload.emoji and "⭐"

young dagger
# lusty smelt I would check your code; you may be failing to close a cursor position in your c...

I suspect that I am getting CursorNotFound error with the following code:

class MyClient(commands.Bot):
    async def setup_hook(self):

@tasks.loop(hours=24)
async def update_elo_ratings():
    # Get all the users in the collection
    users = collection.find()
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        await asyncio.sleep(10)```
spiral crypt
#

i put a print(payload.emoji) and it does print ⭐

lusty smelt
#

Right; payload.emoji is an object. You are comparing an object to a unicode char.

spiral crypt
#

Ouh

young dagger
lusty smelt
spiral crypt
#

is there a type conversion for that?

#

or is it just str()

lusty smelt
#

So payload.emoji returns a Partialemoji object. Which you may be able to use the .name attr of it to compare as validation. Could even use an id

spiral crypt
#

oh pog that fixed it

#

i just did if (str(payload.emoji))

lusty smelt
#

Ah nice!

#

I wonder how its converting it.. thats cool.

shut elk
lusty smelt
shut elk
#

ah, i already have it in my code

lusty smelt
shut elk
#

i disabled the button with button.disabled=True

lusty smelt
#

Did you re-send the view?

shut elk
#

and edit original response but it's not going to fit all users unfortunately, since some are going to slip in

#

yes, my issue isn't disabaling the button it already works, but it's the slim margin that people get in when there is like 3 people spamming the button, it obviously won't disable in time, and will allow some people to click it before it becomes disabled

lusty smelt
#

Store a counter?

shut elk
#

that causes multiple people to enter the code at once and is why I made the gateway that I was talking about..

lusty smelt
#

I would have left it inside the button subclass imo and implemented a counter to prevent that issue.

shut elk
# lusty smelt Store a counter?

Well, I was talking about my self.pressed=True if you saw in the code, and many other similar ways that are supposed to stop this from happening, but despite all of this, there are still people that somehow manage to get in

shut elk
#

I tried many other implementations such as self.stop() to stop all other views from ever happening again but i dont think that did anything either, as well as the list way if u saw I talked abt it earlier but ye

#

the list way is similar to the self.pressed boolean way but using a list, but they all don't always work

lusty smelt
#

Okay. So you've tried the other path. Got it.

shut elk
#

yes

lusty smelt
#

Verify your interaction object regardless and print it

shut elk
#

sure

#

Right now, it's completely fine because I limited the views so there wont be multiple people clicking hopefully, but in the future there might be

#

Should i print the interaction object on the top?

#

isn't it just going to be an object of the discord interactions

lusty smelt
#

Yes.

shut elk
#

K

lusty smelt
#

Do you always get that 404 error or is it intermittent?

shut elk
shut elk
#

it is literally discord interaction

lusty smelt
shut elk
young dagger
lusty smelt
shut elk
#

ok

lusty smelt
young dagger
# lusty smelt Right; but somehow you are passing in an "id" that doesn't exist.

Should I add the close() method to close the cursor?

@tasks.loop(hours=24)
async def update_elo_ratings():
    print("Updating all users from the database...")
    # Get all the users in the collection
    users = collection.find()
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rat>
        await asyncio.sleep(2)
    users.close()```
lusty smelt
young dagger
shut elk
#

wait how would the other buttons affect the current button though? Are you saying that the buttons because I didn't make them unique, they will cause trouble with each other? Because there aren't multiple buttons at once, i dont think it will affect anything if only one of the buttons will be clicked at a time. But still, it might be which might mean that I would have to switch to the other way of making buttons, instead of a decorator, I do it the other way directly to a variable. Is there a way to do this without changing the way I make them? And for the sleep, shouldnt it only affect these msgs:

        d=emojis[random.randint(0,len(emojis)-1)]
        embed=discord.Embed(title=f"{d} Grind Channel 1 {d}", description=f"• Click the button below to earn 1-5 points (boosters receive 1-6)!\n• The event ends <t:1674529200:R> | <t:1674529200:f>\n• Use {com} for all commands including status check", color=color) 
        await interaction.channel.send(view=chan1(), embed=embed)```

which the only one that might be causing problems is the next view? So how would I fix this one if you know what I mean like what is the problem with having async sleep / how should I like structure this without changing ways of making my buttons
#

I probably can make the buttosn the other way but haven't done it so far, since I don't specifically know how to do that and dont want to change too many things but yeah

lusty smelt
#

That long number I copied earlier; it is failing to find it.

scarlet aurora
#
                async def checks():
                    while True:
                        await self.bot.wait_for('message', check=check)
                        await echannel.send("Confirmed")

                async def checks2():
                    while True:
                        await self.bot.wait_for('message', check=check2)
                        await echannel.send("Declined")


                asyncio.run(await checks())
                asyncio.run(await checks2())```Does this mean that both functions are being ran at the same time?
sick birch
#

You shouldn't be using asyncio.run() like that

#

It should be used only once and should be used to kickstart the entire application

young dagger
scarlet aurora
#
                async def checks():
                    while True:
                        await self.bot.wait_for('message', check=check)
                        await echannel.send("Confirmed")

                async def checks2():
                    while True:
                        await self.bot.wait_for('message', check=check2)
                        await echannel.send("Declined")```How can I run both these functions simultaneously?
shut elk
#

also is it fine if u provided an example of how I can make a button the other way and apply it to the view

lusty smelt
#

Which would cause a interaction timeout..

shut elk
#

and how can sleep block clicks, i thought it was just blocking the coroutine functions after it

#

am a bit confused sry

young dagger
#

Btw how do you know that the error is caused because I passed in an invalid summoner_id?

lusty smelt
#

I am not entirely sure how they are getting passed your Gateway. I would print vars and see what is going on.

lusty smelt
#

Could be some edge case that my lack of understanding for d.py is not aware of.

shut elk
#

also should i do my gateway first or defer