#discord-bots

1 messages · Page 351 of 1

tulip ice
#
async def command_autocomplete(
    self,
    interaction: discord.Interaction,
    current: str,
):
    return [
        app_commands.Choice(name=slash_command.name, value=slash_command.name)
        for slash_command in interaction.client.tree.walk_commands() if current.lower() in slash_command.name.lower()
    ]

@app_commands.command()
@app_commands.autocomplete(command=command_autocomplete)
async def commands(self, interaction: discord.Interaction, command: str):
    await interaction.response.send_message(f'The command you chose is {command}.')

All I can get is this

swift acorn
#

Got it! Thank you so much appreciate it

neat heath
#

mm

untold bear
#

Thanks

tulip ice
#

anyway to get author id ffrom app command?

drifting arrow
#

Hey

#

has the new polls feature been added to discordpy yet?

fierce ridge
#

what is the website in which it helps with embeds?

fierce ridge
#

@solid kestrel

pale zenith
tulip ice
#

is there way to make option not required for app_commands?

pale zenith
#

give it a default value (then sync)

tulip ice
#

what if it is file?

#
async def some_command(interaction, file: discord.Attachment):
pale zenith
#

= None or something

#

you can also use file: typing.Optional[discord.Attachment] if you don't want your editor to complain

merry ember
#

can anyone help me please with bot

#

@pale zenith

tulip ice
merry ember
digital current
#

Hi! is there any tutorial on guessing games with words... I recently started and want to make something like that with a views and buttons...
I did find some while googling, but those were about numbers and direct message reading instead of an interaction/buttons

slate swan
#

hello, anyone know how to fix tickets not working once restarting bot? i need it to like grab the mesage id of the ticket so it can attach

leaden olive
#

how can i set the "innodb_force_recovery = 3" to "innodb_force_recovery = 0"
i alreadddy tried openinng my my.ini file and trying to change it from there but there isnt any "innodb_force_recovery"

golden portal
naive briar
slate swan
#

so slash commands are now into py 2.0? been trying to figure out how they work. but when i do it , i get no errors just dont see the slash command popping up.

hushed galleon
slate swan
#

i have not

#

ill try

slate swan
hushed galleon
slate swan
#

whats the features?

hushed galleon
#

cogs/extensions for code organization and hot-reloading, event listeners, a free command tree by default, and ye olden prefix commands

slate swan
#

ohhh

#

thats why i couldnt use cogs

#

my code is so messy ive always used client, since when i started my friend did and i always did

#

do i have to use bot for cogs rather than client?

hushed galleon
#

yes, commands.Bot is the only class that supports it

slate swan
#

ohh ok, i needa do that then

#

i forgot the button, but i know theres a way to like replace all found words on vs like client to bot. do you happen to know how

#

rather not go down all my code replacing manually

#

nevermind just winged it pepetoilet

#

only 1.4k lines

hushed galleon
slate swan
#

bet bet

slate swan
#

just says not found

hushed galleon
slate swan
#

nono, i just changed client to bot. every other command works

#

it couldve been broken before that but from what i remember it was working just fine

hushed galleon
#

o, do you have more than one Bot() defined?

#

if so, dpy can only process events and commands from whichever bot you called run() on, so you should only have one defined

#

also if you werent using commands.Bot before, how did you have all these commands already?

#

this isnt pycord right

#

well, i guess even in pycord discord.Client wouldnt have the command() decorator, just discord.Bot

slate swan
#

i had it as client, so i just renamed

#

and then did bot = commands.Bot etc

hushed galleon
#

hmm did you set case_insensitive=True in your bot constructor?

#

your commands have capitalized names

slate swan
#

-_- i got rid of that when changing it to bot ill put it in

#

thank you! works

slate swan
hushed galleon
slate swan
#

ok ok

hushed galleon
solid kestrel
#

What is it

fierce ridge
#

how to make a embed like dis

hushed galleon
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
hushed galleon
#

in the case of that image, it looks like it consists of a __Vouched__ title, a thumbnail, and one field with inline=False, followed by two inline fields

leaden elbow
#

can someone send me a webhook to test my tool? i want to check if it works the same when im not the owner

bleak flower
#

im new to python and am wondering the problem as i cant seem to find it

leaden elbow
bleak flower
#

idk what that means?

leaden elbow
#

i guess the docs cover the intents

bleak flower
#

i started using python yesterday

leaden elbow
#

like message content, guild members and so on

bleak flower
#

oh okay

leaden elbow
bleak flower
#

is there an easy fix?

leaden elbow
#

read the docs ig

#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True  # Enable the privileged members intent

# Create a bot instance with intents
bot = commands.Bot(command_prefix='!', intents=intents)

# Event: Bot is ready
@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')

# Command: Ping
@bot.command()
async def ping(ctx):
    await ctx.send('Pong!')

# Command: Say
@bot.command()
async def say(ctx, *, message):
    await ctx.send(message)

# Run the bot with your token
bot.run('YOUR_DISCORD_BOT_TOKEN')

created by chatGPT

leaden elbow
blazing beacon
#

horrible question because its only been a day since discord's announced user apps but this code raises the following exception ClientException This client already has an associated command tree.
the code in question

import discord
from discord import app_commands
from discord.ext import commands

bot = commands.Bot(command_prefix="?", intents=discord.Intents.all())
tree = app_commands.CommandTree(bot)

@bot.tree.command()
@app_commands.allowed_installs(guilds=False, users=True) # users only, no guilds for install
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True) # all allowed
async def hello(interaction: discord.Interaction) -> None:
    await interaction.response.send_message(f"Hello {interaction.user.mention}!")

@bot.command()
async def synccommands(ctx):
    await ctx.send("Syncing commands")
    await bot.tree.sync()

bot.run("My token")

skidded example and adapted slightly

hushed galleon
hushed galleon
blazing beacon
#

so remove this? tree = app_commands.CommandTree(bot)

hushed galleon
#

mhm

blazing beacon
#

cool it worked, now time to try the userapp

#

noice it worked

#

🦾 thanks

#

wait, can i use context menus in the same way?

hushed galleon
#

dunno, im barely following discord's feature previews

blazing beacon
#

and follow up question can i make these commands in cogs

#

oh me too i just saw this and decided it was cool enough for me to try spin up

hushed galleon
#

judging from Rapptz/discord.py#9760, the install decorators seem to just store some flags on the command so i think it would work fine in cogs

lament depotBOT
blazing beacon
#

lovely

#

guess who's adapting another bot 😭

leaden elbow
#

bot doesnt exist anymore

outer violet
#

hello, so i have a problem here. ive been trying to get the user who initiated the ban to display in the author but whatever i do, it always displays the user who got banned instead. is my code wrong? idk what to do anymore. here's my code: https://pastes.dev/byHKQvroBW

vapid parcel
#

Will bots be able to ever access polls like this?

I see no reason for them too, but I am just asking smilee

outer violet
pale zenith
#

XDD

#

man I've never heard of this hikari thing, sorry I can't help more D:

vapid parcel
outer violet
#

i have to get the user who initiated the ban from the audit logs which is on lines 8-10, which ive done but idk how to get it show on the author

vapid parcel
outer violet
#

i like hikari better

vapid parcel
#

or even pycord?

sick birch
#

nothing wrong with using something else

vapid parcel
#

Well I recommend, go into their support server, and ask there! This is for dpy, or pycord, or maybe even disnake

vapid parcel
outer violet
#

i did ask but no one answered so

sick birch
#

nah we support hikari here as well

vapid parcel
sick birch
#

yes

vapid parcel
#

I didn't know that lmao

sick birch
#

though you've gotta wait for someone who knows it to help

pale zenith
#

just that 99% of users use d.py so it's hard finding hikari help

vapid parcel
#

my bad

outer violet
vapid parcel
#

Well thats my fault, I apologize.

blazing beacon
#

although that is for context menus i dont know how to adapt the code

pale zenith
#

oh based. Umbra released a user installable apps guide

blazing beacon
#

frfr

pale zenith
blazing beacon
#

sorry im not trying to use ctx menus im trying to use slash commands

pale zenith
#

all those decorators explained there work the exact same inside a cog

blazing beacon
#

oh okay thanks

#

ill try harder and be back

pale zenith
#

did ya sync?

blazing beacon
#

i need to write the command first lAMOAOA

pale zenith
#

💀

pale zenith
#

you should use the AuditLog.entries attribute instead

#
async for log in [that bullshit]:
    for entry in log.entries.values():
        print(entry.user_id, entry.target_id, entry.reason)
outer violet
#

oh

#

wait can you send the doc link

sick birch
pale zenith
outer violet
#

i will try that and get back to you

pale zenith
#

sorry, a mapping*

vapid parcel
pale zenith
#

edited the code above to account for that**

#

@outer violet ^

pale zenith
#

the explanation given is reasonable but yeah, pain

#

the oher option is just doing it the normal way without cogs

blazing beacon
#

wait cogs are classes

vapid parcel
blazing beacon
#

im like the best coder fr (far from it)

pale zenith
#
@app_commands.context_menu()
async def foo(interaction: Interaction[YourBot], message: discord.Message):
    ...

async def setup(bot: YourBot):
    bot.tree.add_command(foo)

async def teardown(bot):
    bot.tree.remove_command(foo)
#

I suppose this should work just fine. I haven't tested it tho

vapid parcel
#

Idk, context menus in cogs aren't that hard imo

pale zenith
#

they're not. they're just a bit more annoying than I would hope them to be

vapid parcel
#
        self.ctx_menu = app_commands.ContextMenu(
            name="Profile",
            callback=self.profile,
        )
        self.bot.tree.add_command(self.ctx_menu)```
#

I mean all you really do is add this

blazing beacon
#

behold my eye cancer

vapid parcel
blazing beacon
#

well tbh honest that's the least of my worries rn BUT that is useful in my other bot

vapid parcel
#

Lol

blazing beacon
#

oh nvm

outer violet
#

@pale zenith it worked

#

i might cry fr

pale zenith
#

nice

#

the pains of hikari frfr

outer violet
#

THANK YOU LMFAO

pale zenith
#

No problem :)

blazing beacon
#

this doesnt raise errors but it also doesnt work

pale zenith
#

did ya sync?

blazing beacon
#

yup

#

i even crashed my client and reloaded it

#

lemme try canary

#

yeah nothings there

pale zenith
#

how does it not work btw?

#

it should only show up in the the bot's DM

blazing beacon
#

OHHHHHHHHHHHH

#

hold on ill be RIGHT back

#

IT WORKS

pale zenith
#

nice

blazing beacon
pale zenith
#

interesting

#

actually, probably because the private_channels= defaults to TRue

blazing beacon
quick lagoon
#

hey guys i cant figure out how to fix this it jusy keeps saying command "ping" not found

import discord
from discord.ext import commands
import asyncio

intents = discord.Intents.all()

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

@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.online, activity=discord.Game(name="Kaizen Battlegrounds", type=1))
print("Bot is up!")

@bot.command()
async def ping(ctx):
await ctx.send(f"The ping is {round(bot.latency * 1000)}ms")

bot.run("your_token")

pale zenith
blazing beacon
#

no leonardo you were right it only shows up in the bot dms

pale zenith
#

makes sense

#

shoutout to @hallow pulsar who was watching my live stream whilst I helped you and helped me xD

blazing beacon
#

thanks fretgfr ur a real one too 🦾

pale zenith
#

so true fret so true

untold bear
quick lagoon
untold bear
#

Even restarted the IDE

pale zenith
#

did you save the file?

blazing beacon
#

the ide saves the file upon restart right?

untold bear
#

Yea

pale zenith
#

VSCode doesn't

untold bear
#

It's pycharm

pale zenith
#

it does like a pseudo-save thing

blazing beacon
#

but it does save it when you rerun it

untold bear
#

Pycharm saves it the second u edit it

pale zenith
#

I do suggest pressing CTRL+S nonetheless

untold bear
#

I think I told him to save it and it still didn't work

untold bear
#

Never in my life have I ever encountered an error like this

blazing beacon
#

restart pc 😭

#

last resort

pale zenith
#

what console command are you using to run the bot?

untold bear
pale zenith
#

replace "python"/"python3"/"py" or whatever with cat

untold bear
#

Wha

blazing beacon
#

so like you run the file with python3 <filename>.py right just replace python3 with cat and send the output here

untold bear
#

Seems like he just had 2 python files and he didn't know which one he was running 💀

quick lagoon
#

😭

blazing beacon
#

I KNEW IT ahahHA

quick lagoon
#

lol

blazing beacon
#

well happens to all of us man

pale zenith
blazing beacon
#

goodluck 🦾

quick lagoon
#

thanks guys

torn solar
#

how do i grab all channels

viscid hornet
torn solar
#

nvm figured it out

#

was being dumb

torn solar
#
        await channel.delete()```
viscid hornet
torn solar
#

no

#

server cleaner bot

#

kinda weird to explain

viscid hornet
viscid hornet
torn solar
#

lol

latent jay
#

I wonder, can bots send the new polls discord implemented?

hushed galleon
# latent jay I wonder, can bots send the new polls discord implemented?

this was the last comment in discord/discord-api-docs#6746

Seeing that this is getting closer to completion, can the general poll restriction for bots be lifted? Or is that being saved until the complete release, kinda hard to test library implementations with it in the way
so apparently you can't
nvm apparently tpcstld just resolved it
FML. Should be available for bots now.

lament depotBOT
hushed galleon
#

discord.py hasnt made a new release yet, but you can clone from Rapptz/discord.py#9759 and test the pending implementation if you want

lament depotBOT
latent jay
#

Ohh sweet

viscid hornet
#

you already made a help post for this

blazing beacon
#

is there a way to only have a task being called like once for the entire time the bot is on

#

i figured it out

#

just write an async function and call it with asyncio

drifting mantle
#

yeah it does

#

if ur using dpy which i assume so

viscid hornet
blazing beacon
blazing beacon
drifting mantle
#

yup just set count=1

blazing beacon
#

mhm, now i can finally stop loading cogs on_ready 🙏

viscid hornet
blazing beacon
#

setup_hook?

vapid parcel
#
    @commands.Cog.listener()
    async def on_ready(self):
        self.status_task.start()

    async def cog_load(self):
        print(f"Cog: {self.__class__.__name__} has been loaded.")


    @tasks.loop(seconds=600.0)  # Changes status every 10 minutes
    async def status_task(self) -> None:
        await self.bot.wait_until_ready()```

Which is better, to put the `self.status_task.start()` inside of `on_ready` or inside of `cog_load`?
unkempt canyonBOT
#

examples/advanced_startup.py line 34

async def setup_hook(self) -> None:```
drifting mantle
#

this example actually shows loading cogs/extensions inside the hook

blazing beacon
#

ohh sweet

#

hehe now i can just skid it

drifting mantle
blazing beacon
#

oh and it has tree sync in the snippet too

vapid parcel
blazing beacon
#

whats wrong with autosync if its a private bot with its only user being me

vapid parcel
#

Well, if you restart the bot a lot for testing, the auto sync will get rate limited.

#

Then you will be rate limited and it will take awhile to test again, you only get a certain amount of syncs to discords api

blazing beacon
#

wouldnt it still get r8limited if i do the custom sync?

vapid parcel
#

No

drifting mantle
#

he saying to only sync when u need to not everytime u start the bot

vapid parcel
#

Cuz you only need to sync when you add a new command or change the name or something, but if you are changing something in an embed, then restart the bot, you are syncing for no reason

#

aka auto sync

blazing beacon
#

ah i get it

#

thanks for the insight

vapid parcel
#

Here you go on a good sync command!

blazing beacon
vapid parcel
blazing beacon
blazing beacon
#

no need to overengineer 🦾

drifting mantle
vapid parcel
#

Ive always been told to not use on_ready, but I truly just want an answer on it

drifting mantle
#

yeaaa ppl scream it all the time

vapid parcel
#

Because maybe there is something I don't know

drifting mantle
#

cause it can fire multiple times

vapid parcel
#

Yeah cuz of reconnects

drifting mantle
#

if u want ppl to not scream at u just put it in setup hook after cogs get loaded

vapid parcel
#

Well, I was using cog_load, but my friend says to use on_ready. But he says it doesn't matter cuz of the await self.bot.wait_until_ready()

#

But I want an answer which would technically be better

#

on_ready or cog_load

upbeat otter
# vapid parcel on_ready or cog_load

There's no point. Even if you have the method that stops execution until ready. It again comes down to the point that on_ready can be fired multiple times which means that it may return True in some cases

#

And what's the problem in using a setup_hook anyway 💀

vapid parcel
#

I just needed to make sure.

upbeat otter
vapid parcel
#

they will talk shit on you if you do NOT understand what you are doing, but in here they won't talk shit, they will actually help you lol

#

But sometimes in here, there is no help, so you truly need to go to the dpy server sometimes lol

drifting mantle
#

lmao dpy is by far the most toxic discord lib server

#

i was once t imed out by a mod for answering someones question only for them to turn around and repeat what i said

vapid parcel
#

😭 nah I was confused on something one time about how to the defers, and they showed me an example, but I asked where at, this was when I was new, and they were just fucking talking shit. It was annoying, but now they are nice cuz I understand shit lol

upbeat otter
upbeat otter
#

True

vapid parcel
#

They chill now tho, like they aren't dicks to me no more.

#

If you are new, DON'T GO THERE lmao

upbeat otter
#

True true

vapid parcel
#

You are better off here if you are truly new..

upbeat otter
#

They'll simply tell you to learn python over again 💀like what

blazing beacon
viscid hornet
blazing beacon
#

how do i check if an interaction has failed?

#

i tried using my gigabrain and cooked this
but as expected it didnt work as intended

sick birch
#

Don't think you can

blazing beacon
#

damn.

hushed galleon
#

do you mean if your slash command raised an error or if it literally shows up as failed on the user's client?

blazing beacon
#

the former

hushed galleon
blazing beacon
#

but i think that also kinda bleeds into the second one too so

hushed galleon
blazing beacon
#

handy but i kinda just want a global exception handler(? sorry for terminology im not good with that)

hushed galleon
#

ergh, there's no event for it

blazing beacon
#

sadly, thanks though

hushed galleon
#

you'll have to use @tree.error which only allows one handler at a time

#

though i guess you can make it dispatch your own event and use that with listeners

blazing beacon
#

does that require me having to patch the library for this one case

hushed galleon
#

er, no?

blazing beacon
#

or does dpy let me dispatch my own events

#

oh cool i never knew it was this easy to manipulate

hushed galleon
#

hmm its not actually documented

unkempt canyonBOT
#

discord/client.py line 461

def dispatch(self, event: str, /, *args: Any, **kwargs: Any) -> None:```
hushed galleon
blazing beacon
#

oooh lovely

#

thank you for the sample too, i wont just skid it this time ill read the code and then look at how they already dispatch events

hushed galleon
slate swan
#

sometimes i get this error discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000

well i do have when its on_ready a task thats on loop

slate swan
#

I have tried many ways, but it keeps returning 'server not found', and this is quite annoying because this problem has been going on for a long time.

@commands.command()
async def checkserver(self, ctx, server_name):
    server_info = self.servers.get(server_name)
    if not server_info:
        await ctx.send(f"Server {server_name} not found.")
        return

    url = server_info['url']

    
    screenshot_api_key = "YOUR_SCREENSHOT_LAYER_API_KEY"  
    screenshot_url = f"https://api.screenshotlayer.com/api/capture?access_key={screenshot_api_key}&url={url}&fullpage=1&viewport=1440x900&format=PNG"

    webhook_url = "WEBHOOK_URL"

    try:
                response = requests.get(screenshot_url, timeout=10)
        response.raise_for_status()

        
        embed = discord.Embed(title=f"Screenshot of the server link {server_name}", color=0x00ff00)
        embed.set_image(url=screenshot_url)

       
        webhook = discord.Webhook.from_url(webhook_url, adapter=discord.RequestsWebhookAdapter())
        await webhook.send(embed=embed)

    except requests.exceptions.RequestException as e:
        await ctx.send(f"Error while retrieving the screenshot: {e}")
slate swan
naive briar
#

So much context 🤯

slate swan
vocal plover
civic reef
#

bot listeners are for bot events, right? can't use for bot commands?

#

idk

civic reef
#

cool

viscid hornet
#

commands and cog listeners are different

civic reef
#

cog listeners?

viscid hornet
viscid hornet
#

events are for your main file

civic reef
#

ok

faint rapids
#

Does anyone know how to do this "today at 3:10 AM" thing?

vocal plover
#

it uses the timestamp field of an Embed object, if you have an embed you can do something like embed.timestamp = your_datetime_object or you can pass it to the timestamp= keyword arg of the Embed(...) constructor

faint rapids
#

Thanks

tulip ice
#
class ErrorModal(discord.ui.Modal, title='Error'):
        error_msg = ''
        # modal = None
        def __init__(self, error):
            self.error_msg = error
            # self.modal = modal
            print('A1A', self.error_msg)
            super().__init__()
        
        print('A2A', error_msg)
        message = discord.ui.TextInput(
            label='Error Message',
            default=error_msg,
            style=discord.TextStyle.long
        )

        async def on_submit(self, interaction: discord.Interaction):
            await interaction.response.send_message('helllo')

        async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
            await interaction.response.send_message('Oops! Something went wrong with an Error Modal.', ephemeral=True)
            traceback.print_exception(type(error), error, error.__traceback__)

why error_msg not show up? it stays as empty string when the popup opens up? why?

lyric sky
#

you set error_msg to '', then you set self.error_msg to error

#

self.error_msg is not the same as error_msg

tulip ice
#

oh

#

how do i access self.error_msg?

viscid hornet
tulip ice
#
NameError: name 'self' is not defined
viscid hornet
tulip ice
#

i want to send error to the modal

#
@bot.tree.error
async def on_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError) -> None:
    await interaction.response.send_modal(ErrorModal(error=error))
viscid hornet
tulip ice
#

and default text

viscid hornet
viscid hornet
#

just use an embed at that point

slate swan
#

@viscid hornet

tulip ice
viscid hornet
viscid hornet
fathom wind
#

attribute error module 'discord' has no attribute 'bot' does anyone know how to fix this?

naive briar
#

'discord' has no attribute 'bot', so you cannot get 'bot' from 'discord', because 'bot' doesn't exist in 'discord'

#

Maybe you're looking for discord.Client or discord.ext.commands.Bot?

fathom wind
#

i think its a pip error since i have a new pc

slate swan
#

can you show us error logs

fathom wind
#

ok

#

the code is completely fine

slate swan
#

error: bot = discord.Bot() you forgot intents

fathom wind
#

ohhhh

slate swan
#
import discord

intents = discord.Intents.default()
bot = discord.Bot(intents=intents)
fathom wind
#

k ty

#

hm its still saying the same thing

#

its a pip error

#

cuz the code always works

#

but i just got a new pc

full lily
full lily
dense kestrel
#

Hi guys

full lily
#

hey!

dense kestrel
#

Bones

slate swan
dense kestrel
#

Y'all look pretty cute fr

#

Ngl

robust fulcrum
#

Hi

slate swan
dense kestrel
#

Hola Juan Carlos pablos

slate swan
#

basic script

import discord

# Define intents
intents = discord.Intents.default()

# Create bot instance
bot = discord.Bot(intents=intents)

# Event decorator for bot ready event
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

# Run the bot with your token
bot.run('YOUR_BOT_TOKEN')
dense kestrel
#

bota

robust fulcrum
#

Isn't it discord.ext.commands.Bot?

dense kestrel
#

Guys

robust fulcrum
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
full lily
#

^^^!

full lily
#

^^^^^^^^

#

discord.Bot isn't a thing

dense kestrel
#

ABC if U are looking for friend

dense kestrel
slate swan
# full lily discord.Bot isn't a thing

Basic script

import discord

# Create a new Discord client
client = discord.Client()

# Event handler for when the bot is ready
@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

# Event handler for when the bot receives a message
@client.event
async def on_message(message):
    # Ignore messages from the bot itself
    if message.author == client.user:
        return

    # Check if the message starts with the command prefix
    if message.content.startswith('!hello'):
        # Respond to the command
        await message.channel.send('Hello!')

# Run the bot with the Discord token
client.run('YOUR_DISCORD_TOKEN')
full lily
#

yeah discord.Client works but then you can't make commands

#

you have to rely on the on_message event

slate swan
#

Because Client is for event and not commands

full lily
slate swan
#

you can use this one

import discord
from discord.ext import commands

# Create a new Discord bot instance
bot = commands.Bot(command_prefix='!')

# Event handler for when the bot is ready
@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

# Command decorator for the !hello command
@bot.command()
async def hello(ctx):
    # Respond to the command
    await ctx.send('Hello!')

# Run the bot with the Discord token
bot.run('YOUR_DISCORD_TOKEN')
full lily
#

@fathom windyou getting all this?

robust fulcrum
#

tbh the Bot must be in discord package not ext.commands, which doesn't makes sense to me

pale zenith
#

opens chat
AI generated "help"

steel steppe
#

hold up

#

.rule 10

slate swan
#

you only need to convert the code decorator

steel steppe
#

.RULE 10

#

!RULE 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

steel steppe
#

ayo mods get him

#

get him rn

slate swan
#

for what a stupid rule ?

steel steppe
#

AYO HES RESISTING ARREST

slate swan
#

i'm helping so what ? what's wrong with it?

steel steppe
#

wdym ur literally using

#

CHATGPT

#

ur tryna bypass the rules rn

slate swan
#

it's helping him understand how code work , are you that dumb ?

robust fulcrum
#

nvm but its getting offtopic

steel steppe
#

without considering the legal repercussions like

steel steppe
viscid hornet
steel steppe
#

UR THE ONE USING CHATGPT LMFAOOOOOOO

slate swan
#

yes and ?

viscid hornet
steel steppe
slate swan
#

don't care it'a a help discord

viscid hornet
fathom wind
viscid hornet
#

and you shouldnt use it here especially because it can be misleading

viscid hornet
steel steppe
viscid hornet
#

@slate swan the rules literally state you cant use AI help

#

!rule 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

slate swan
#

such boring rule if we cant help others

full lily
steel steppe
#

WHY ARE U USING CHATGPT

#

WHY ARE U UNORIGINAL BRU

full lily
#

In discord.py you need to import it from discord.ext.commands

slate swan
#

WHY ARE YOU SHOUTING ?

steel steppe
#

wdym

#

how am i shouting

slate swan
#

you talk with capital letters

steel steppe
#

and?

robust fulcrum
#

pls stop doing this, go to offtopic to fight

slate swan
#

it's shouting

steel steppe
#

watchu gonna do bout it

slate swan
#

nothing but very arrogangtof yyours.

full lily
#

can you end this

steel steppe
#

ur literally tryna change the topic rn

full lily
#

@fathom winddid you try the import I suggested?

robust fulcrum
#

import it? and call function?

fathom wind
#

already

full lily
#

and how'd that go

fathom wind
#

import discord
from discord.ext import commands
import random
import requests
import json
import time
intents = discord.Intents.default()
bot = discord.Bot(intents=intents)

fathom wind
full lily
#

like pycord for example

#

discord.py is the most maintained fork, so that's the one I would suggest

#

you will have to change your imports to what I suggested above

steel steppe
#

hold up why is there a 6 sec slowmode here

steel steppe
fathom wind
steel steppe
#

lemme fix ur code rq

fathom wind
fathom wind
steel steppe
#
import discord, random, requests, json, time
from discord.ext import commands
intents = discord.Intents.default()
bot = discord.Bot(intents=intents)
fathom wind
#

lemme try installing pycord

steel steppe
#

nah i fixed ur code just now

steel steppe
#

yo @pale zenith what are u doing rn

#

???

pale zenith
#

Sorry, what?

full lily
fathom wind
steel steppe
#

?????????????????????????

pale zenith
#

I'd rather not, as it was already explained above by the helper

steel steppe
#

exactly

robust fulcrum
#

its a bad practive to keep them on one line, it decreases readability

steel steppe
full lily
#

@steel steppeYou gotta relax or you're going to find yourself in trouble

steel steppe
#

wdym

steel steppe
#

NO ERRORS????

pale zenith
full lily
#

pep8 is the bible when it comes to code style

#

sure it works, but that doesn't mean that it's right

robust fulcrum
#

ye, its really good

full lily
robust fulcrum
#

black makes my ugly code pretty following pep8

full lily
#

!zen

unkempt canyonBOT
#
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

viscid hornet
pale zenith
#

[insert image here]

naive briar
viscid hornet
naive briar
#

Yes

tulip ice
#

is it opssible to clear message with given restrictions? i want to clear message by user

hushed galleon
tulip ice
#

yea, deleting

hushed galleon
#

yeah, your bot will need the manage messages permission for await message.delete() to succeed

tulip ice
#

yeah, i got that enabled

tulip ice
hushed galleon
#

oh, unfortunately discord doesn't have a public endpoint to get messages from just one user

tulip ice
#

oh

#

anyway to get a bunch of messages? and check user id?

hushed galleon
#

i guess the most optimal way would be to record messages sent from every user within the guild via on_message, then you can filter through that to bulk delete their messages

#

the worst option would be fetching the history of every channel to find their messages, which would need an excessive number of API requests (1 per 100 messages)
(fyi TextChannel.purge() internally uses history() as well)

tulip ice
#

oh yikes, alright, uh

hushed galleon
# hushed galleon i guess the most optimal way would be to record messages sent from every user wi...

if you want to save on memory you can store just the guild ID, channel ID, user ID, and message ID rather than storing every message object, then use TextChannel.get_partial_message() + PartialMessage.delete() and/or TextChannel.delete_messages(), whichever is permitted by the API

or alternatively you can loop through Client.cached_messages which stores the last 1000 messages by default, and is kept up-to-date by dpy

tulip ice
hushed galleon
tulip ice
#

oh

hushed galleon
#

unless you only want to delete messages in one channel, in which case it won't be too bad

#

forgot what the typical ratelimits are on channel history

(based on a 403 response, it seems to be 5/1s)

tulip ice
#

so the only way to make it efficient is to have a local storage of every message, from each user, in every channel in every server?

drifting arrow
drifting arrow
#

The private repo has my tokens and shit so I dont need to manually add them each time or whatever. im lazy AF

viscid hornet
modern valve
#

How does anyone do something like this?

drifting arrow
#

oh

hushed galleon
viscid hornet
modern valve
viscid hornet
modern valve
#

ok

viscid hornet
# modern valve ok

Context Menus are a way to run an application command without typing anything. They are accessed in the "Apps" section when right clicking a user or message.

When you right click a message, they are called message commands. In discord.py 2.0 you can implement them as such:

@tree.context_menu(name='Translate with Google', guild=discord.Object(id=MY_GUILD_ID))
async def translate(interaction: discord.Interaction, message: discord.Message):  # An annotation of discord.Message makes this a message command
    ...

Likewise when you right click a user or member, they are called user commands. You can change the annotation from discord.Message to discord.Member accordingly:

@tree.context_menu(name='Ban User', guild=discord.Object(id=MY_GUILD_ID))
async def ban_user(interaction: discord.Interaction, member: discord.Member):  # An annotation of discord.Member makes this a user command
    ...

You can also annotate this with discord.User, but because context menus are only applicable in guilds, they'll probably always be members.

Documentation: https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu
Note: Context menus cannot be used inside of cogs (in the way you'd normally expect) - see the issue here: https://github.com/Rapptz/discord.py/issues/7823#issuecomment-1086830458

modern valve
#

okay

#

imma try that

viscid hornet
modern valve
#

if i dont specify guild id, does it apply everywhere

modern valve
#

sick

#

i made it work

#

thanks, i appreciate it

#

i made it work epicly

viscid hornet
modern valve
#

i had to use @bot.tree.context_menu()

#

cuz like

#

i felt like it

#

imma check what are all the @bot.tree. things

viscid hornet
modern valve
#

where do i find the @tree. things

viscid hornet
modern valve
modern valve
viscid hornet
modern valve
viscid hornet
viscid hornet
modern valve
viscid hornet
modern valve
#

im good

viscid hornet
modern valve
#

I'M GOOD. 😀

viscid hornet
#

it takes zero learning

viscid hornet
#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

modern valve
viscid hornet
#

put your code in the pastebin

modern valve
viscid hornet
viscid hornet
modern valve
#

but like

#

why

viscid hornet
#

remove the token and any api keys and you’ll be fine

modern valve
viscid hornet
modern valve
#

cuz i feel like it

#

i have like 3 dictionaries to save constantly

viscid hornet
#

talk to someone 🙏🏽

viscid hornet
modern valve
#

are you gonna force me to rewrite me code ?

modern valve
viscid hornet
modern valve
#

but like

#

i dont wanna :(

viscid hornet
modern valve
#

i no no wanna

viscid hornet
#

it will change your life to make these small changes

modern valve
#

but like

viscid hornet
#

imagine 15k lines in just one file

modern valve
#

that would be hilarious

viscid hornet
viscid hornet
modern valve
#

and coding is the reason why

viscid hornet
viscid hornet
viscid hornet
modern valve
#

i dont mind clicking 253 times

#

plus it just shows

viscid hornet
modern valve
#

oh gorsh

modern valve
#

38 prefix commands, 24 slash commands

viscid hornet
viscid hornet
modern valve
#

I DONT WANT TO USE COGS

viscid hornet
modern valve
#

#1 rule of programming: if it works, dont change it

#

anyway

#

yea this bot is my biggest project, i dont code often

viscid hornet
modern valve
#

haha no

viscid hornet
modern valve
#

but like i dont wanna :(

tulip ice
#

there is bot that can somehow clear message from a message id. when i type the amount to clear as 1 and then select a message from a fair time ago, it can somehow remove that message.

i tried doing the samething, but my pronlem is that limit=amount will restrict how many messages i can view. so if i enter 1, i only get the first message and no more than that.

how is the discord bot able to delete message from a message fair back in time without that same restriction?

viscid hornet
#

!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) 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) is also needed to retrieve message history.

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

Examples

Deleting bot’s messages...
viscid hornet
#

oh ok no brackets

tulip ice
#

they existed the whole time 😭

viscid hornet
tulip ice
#

i checked the docs and didnt even see them 😑

#

i should learn to read more carefully

viscid hornet
#

what the hell was that message

tulip ice
#

no idea

#

is it a scam that is being deleted as it is sent?

viscid hornet
blazing beacon
#

how do i make my interaction fail

slate swan
#

Hello

blazing beacon
#

right now im using an original gamer strategy by doing this

tulip ice
naive briar
#

Sure

slate swan
#

Can sm1 help with a python project if u have experience please just dm me and just so u know its an not so friendly project so if u want to help id appreciate it

tulip ice
fathom wind
#

guys how do i fix AttributeError: module 'discord' has no attribute 'Bot' the code is fine its just that i got a new pc so it might be something with the pip

steel steppe
#

SHOW YOUR CODE BRO

#

HOW DO U EXPECT PPL TO HELP IF U DONT SHOW UR CODE

#

and discord.Bot aint a thing

#

so WHAT DO YOU MEAN???

fathom wind
#

omd did u not here what i said

#

"The code is fine"

#

also ur the one who told me to informat my stuff

blazing beacon
#

if you have any more issues send your code so we can diagnose your issue with better accuracy

sick birch
sick birch
blazing beacon
#

i infinity iron have cooked up the only solution to loading cogs in on_ready behold my magnum opus, my peak all my neurons have been activated for this one moment

sick birch
blazing beacon
#

i know about setup hook i just dont know how to use it ( havent tried yet but i have an idea ) and i made this for lolz

fading marlin
#

It's kind of the same as on_ready, only that it's called setup_hook and is far more reliable

blazing beacon
#

its an event?

hushed galleon
#

its not actually an event, but you can abuse the event decorator to define your own function for it: py @bot.event async def setup_hook(): await bot.load_extension("path.to.extension")

#

and the "correct" way to define it would be using inheritance: py class MyClient(discord.Client): async def setup_hook(self): await self.load_extension("path.to.extension")

blazing beacon
hushed galleon
#

only the event decorator works since it re-assigns the setup_hook method on the bot instance

unkempt canyonBOT
#

discord/client.py lines 1985 to 1990

if not asyncio.iscoroutinefunction(coro):
    raise TypeError('event registered must be a coroutine function')

setattr(self, coro.__name__, coro)
_log.debug('%s has successfully been registered as an event', coro.__name__)
return coro```
blazing beacon
#

im not gonna try understand this because its out of the scope of this project

#

also, to have a slash command with multiple types is possible right? and if so is this the correct way to do it?

#

or do i need to make another command that can only accept a certain message type

hushed galleon
blazing beacon
#

oh sweet, thanks

#

im just realizing how active ive suddenly become in this discord and especially this channel 😭

quick gust
#

when can User.default_avatar return None?

hushed galleon
quick gust
#

thats... weird

url=inter.author.avatar.url or inter.author.default_avatar.url,
AttributeError: 'NoneType' object has no attribute 'url'
hushed galleon
#

prob means avatar is None, not default_avatar

#

you should use display_avatar which figures it out for you instead

quick gust
#

ooh alright thanks!

quick gust
#

how can I create a function to be executed before any command is invoked?
basically i need an example of before_slash_command_invoke being used (disnake)

hushed galleon
# quick gust how can I create a function to be executed before any command is invoked? basic...

i guess there'sCommandTree.interaction_check, but judging from source code, it doesn't fill in the Interaction.command property before calling this, so you can't easily tell which command it's for, plus the method runs before checks which might not be what you want: ```py
class MyCommandTree(app_commands.CommandTree):
async def interaction_check(self, interaction):
...
return True

bot = commands.Bot(..., tree_cls=MyCommandTree)```
you could make a check function and decorate every command with it, but that's inconvenient...

quick gust
#

that's disnake?

hushed galleon
#

oh oops, i thought you meant you were looking for an equivalent to disnake's method

quick gust
#

aah my bad, phrased it wrong

#

I just need an example using before_invoke in disnake

#

for slash commands

hushed galleon
#

seems basically the same as before_invoke, and that was already part of dpy py @bot.before_slash_command_invoke async def before_slash_command_invoke(interaction: disnake.ApplicationCommandInteraction): ...

#

or in the case of a cog, it'd be a regular method: py class MyCog(commands.Cog): async def cog_before_slash_command_invoke(self, interaction: disnake.CmdInter): ...

quick gust
#

in case I've subclassed Bot, it will be a regular method
before_slash_command_invoke right?

hushed galleon
#

err i dont think you can define it as a regular method

quick gust
#

ah, how then?

#

I want it to b executed for all cogs all commands so I think having it in my bot subclass is probably better

hushed galleon
#

i guess you can use the decorator as a normal function during init...

#
class MyBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.before_slash_command_invoke(self.handle_before_slash_command_invoke)

    async def handle_before_slash_command_invoke(self, interaction: disnake.AppCmdInter):
        ...```
quick gust
#

great thank you!

hushed galleon
unkempt canyonBOT
#

disnake/ext/commands/base_core.py lines 467 to 478

if inter.data.type is ApplicationCommandType.chat_input:
    partial_attr_name = "slash_command"
elif inter.data.type is ApplicationCommandType.user:
    partial_attr_name = "user_command"
elif inter.data.type is ApplicationCommandType.message:
    partial_attr_name = "message_command"
else:
    return

# call the cog local hook if applicable:
if cog is not None:
    meth = getattr(cog, f"cog_before_{partial_attr_name}_invoke", None)```
blazing beacon
#

how do i set an image in a thumbnail from a local image?

quick gust
#

the set_thumbnail has a file kwarg iirc

blazing beacon
#

oh i meant image

#

sorry 😭

quick gust
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing `None` removes the thumbnail.
blazing beacon
#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
hushed galleon
blazing beacon
#

oh damn

#

thanks 🦾

#

this user app tag bot is coming together nicely

slate swan
#

Hmm ggs

outer violet
#

hi again, so i have a little problem with the permissions displaying in the embed. im trying to make the permission changes to display like the photo in the right but its saying "Unknown" and not displaying the changes (photo on the left). i know my code is wrong but idk what part and idk how to fix it. heres my code: https://pastes.dev/FYpIp4It1x

vapid parcel
#

How to let slash commands support files?

#

I forgot how to do it

golden portal
#

typehint it to discord.Attachment

blazing beacon
soft grove
#

getting ssl errors looked everything up and tried installing the correct certs still nothing

golden portal
# blazing beacon any improvements? https://paste.pythondiscord.com/EBMQ

for tag class, you may wanna check dataclasses library, also PEP 8 specify you to use CamelCase for class names, so Tag should be the name instead, (that pass keyword is useless btw)

for database you should use a proper one instead of using json, at the very least use sqlite for filebased database

#

also, bool typehint exist btw, no need hidden: int then bool(hidden)

golden portal
soft grove
#

windows server 2022

golden portal
#

did you check for windows updates?

soft grove
radiant bough
#

What is the attribute for member icon?
I tried member.icon and member.icon_url

#

Mention me please

golden portal
unkempt canyonBOT
#

property display_icon```
A property that returns the role icon that is rendered for this member. If no icon is shown then `None` is returned.

New in version 2.0.
radiant bough
#

Thank you

viscid hornet
soft grove
radiant bough
#

I can’t get the code rn but I’ll elaborate the error I’m facing rn

So I have a sub command add (a.grinder add <user> <time>)
And whenever I run the command there’s no output, the user and time isn’t saved in the database, the embed in response to the command isn’t sent.

I don’t get any errors and I don’t have any on_message events in that specific cog.

If you want the code I’ll provide it in a few hours but can’t do it rn

quick gust
#

yeah we will need the code

slate swan
#

is it possible to add autocomplete but not show it if its return []

hushed galleon
# outer violet hi again, so i have a little problem with the permissions displaying in the embe...

i dont use hikari, but i suspect that your direct usage of the PermissionOverwrite class isn't valid (... if hikari.PermissionOverwrite.allow else ...) - channel.permission_overwrites gives you a mapping of snowflakes to PermissionOverwrite, so you'll probably want to use multiple for-loops to generate your message

or, ideally, figure out exactly what changed (snowflakes added/removed, permissions added/removed)

glossy flame
#
Username_API = "https://users.roblox.com/v1/users/search?keyword={user}&limit=100"
Headshot_API = "https://thumbnails.roblox.com/v1/users/avatar-headshot?userIds={user_id}&size=420x420&format=Png&isCircular=false"


@bot.command()
async def avatar(ctx, username):

    response = requests.get(Username_API.format(user=username))
    print(response)
    if response.status_code == 200:
        user_data = response.json()
        print(user_data)

        gotten_user_id = user_data["data"][0]["id"]
        print(gotten_user_id)
        new_user_data_response = requests.get(Headshot_API.format(user_id=gotten_user_id))
        new_user_data = new_user_data_response.json()
        avatar_url = new_user_data["data"][0]["imageUrl"]

        embed = discord.Embed(title=f"Avatar of {username}", color=0xFFC0CB)
        embed.set_image(url=avatar_url)

        await ctx.send(embed=embed)
    else:
        await ctx.send(f"API Error: {response.status_code}")

Is there any way I can better my code to prevent error 429 because it happens if you run the same command immediately after, or do I just implement a cooldown

golden portal
#

for command cooldown you can use a cooldown check

#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)

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

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

A command can only have a single cooldown.
glossy flame
#

ty

glossy flame
# golden portal you would just implement a cooldown on your command and also implement a retry a...

it doesn't show the amount of time and instead just says [429 Too Many Requests)
and also gives this humongous thing
<CIMultiDictProxy('Content-Type': 'application/json; charset=utf-8', 'Date': 'Sun, 14 Apr 2024 14:08:00 GMT', 'Server': 'Kestrel', 'Cache-Control': 'no-cache', 'Transfer-Encoding': 'chunked', 'strict-transport-security': 'max-age=3600', 'x-frame-options': 'SAMEORIGIN', 'roblox-machine-id': '1c849c45-f92f-41ad-d049-d2eaaf24bb9b', 'x-roblox-region': 'us-central', 'x-roblox-edge': 'lhr2', 'report-to': '{"group":"network-errors","max_age":604800,"endpoints":[{"url":"https://ncs.roblox.com/upload"}]}', 'nel': '{"report_to":"network-errors","max_age":604800,"success_fraction":0.001,"failure_fraction":1}')>

#

thats when I print the response

golden portal
#

what API is this

glossy flame
#

roll bocks

golden portal
#

hmm i guess it doesnt have a X-ratelimit header, so you have to guess how long to wait, usually people do a backoff sleep, for example, retry after 1 seconds, then 2 seconds, then 4 seconds, 12 seconds, N seconds. This is what discord.py is doing too, though discord have X-ratelimit that tells you the remaining time.

glossy flame
#

ok ty

blazing beacon
#

i decided to use json as db becsuse it has kv structure very easy to implement

#

but thanks for the input ill take it into consideration on the next version of this

golden portal
#

well it's not just that, consider learning about inline Transformer and autocomplete

#

json has no concurrency control and easier to get corrupted, if you want a key value format maybe just find a good nosql db like mongo or whatev

blazing beacon
blazing beacon
slate swan
#

is it possible to add autocomplete but not show it if its return []

tawdry tendon
#

im bored and want to code a discord bot, any ideas?

viscid hornet
#

blackjack, slots, pass the parcel, idfk

viscid hornet
slate swan
#

ye but can i make it just not show the options then?

untold remnant
#

Hi! I'm new on this discord.

I've a problem about my bot.
I'll give roles on my discord server with my bot but I've a problem about giving role... Can you help me?

[Sorry for my english but I'm from poland 😅]

signal turret
#

guys i bored im lf for someone make bot with me or do anything to get fun

viscid hornet
#

it just wont

viscid hornet
untold remnant
#

I find what's the problem

viscid hornet
untold remnant
# viscid hornet can you rephrase?

I found the problem at my place like something, so I don't need any more help. Sorry for the previous message 🤣 as I wrote this I am from Poland and sometimes I get confused how it should sound

untold remnant
#

😃

slate swan
#

Any one know how code a discord bot like I have my own web and any other person has set his product so how it's send a webhook to my discord server.
Anyone know language is python

#

Like website logs go to webhook

viscid hornet
slate swan
#

Can you explain please

viscid hornet
viscid hornet
slate swan
#

😅

viscid hornet
#

(and dont use that code. dpy has its own .run())

slate swan
#

Ok

#
import requests
import aiohttp
import asyncio

TOKEN = ''

# Webhook URL for sending messages to Discord
WEBHOOK_URL = ''

# Website URL to monitor
website_url = ''

# Initialize intents
intents = discord.Intents.all()
intents.typing = False  # Disable typing event to reduce unnecessary events

# Initialize Discord client with intents
client = discord.Client(intents=intents)

# Function to check for new products on the website
async def check_website():
    # Send HTTP GET request to the website
    response = requests.get(website_url)

    # Check if request was successful
    if response.status_code == 200:
        # Assuming product information is in a specific HTML element
        product_element = 'New product found'

        # Check if product element exists and if it's a new product
        if product_element:
            # Send product information to Discord channel via webhook
            async with aiohttp.ClientSession() as session:
                webhook_url = f"{WEBHOOK_URL}/messages"
                payload = {"content": product_element}
                async with session.post(webhook_url, json=payload):
                    pass

# Event handler for bot's ready event
@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')
 
    while True:
        await check_website()
        await asyncio.sleep(60)  

@client.event
async def on_message(message):
    if message.content == '/logenable':
   
        await message.channel.send('Website monitoring enabled!')
       
        while True:
            await check_website()
            await asyncio.sleep(60)  

client.run(TOKEN
#

@viscid hornet this code is right?

#

I try it's working but he not sending the logs

viscid hornet
unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

slate swan
viscid hornet
slate swan
#

Please help me

slate swan
#

Iam dead frr

viscid hornet
#

i'll show you

slate swan
#

Yes please 🙏

viscid hornet
# slate swan Yes please 🙏
@bot.command()
async def test(ctx: commands.Context):
    webhook = await ctx.channel.create_webhook(name = 'test')
    await webhook.send('test')```
slate swan
#

Hm

#

Brother ik this 😅

#

Like this 😀

viscid hornet
#

and send that: py await webhook.send(embed = your_embed)

slate swan
#

W8 a sec lemme explain you.

viscid hornet
viscid hornet
#

!d discord.Embed | read this and take notes

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

I need a Discord bot that will display notifications on my Discord server whenever a seller adds a product to my eCommerce website . The notification should include the product name, product link, and product description, all neatly formatted within an embed message.

#

@viscid hornet now you understand?

viscid hornet
viscid hornet
slate swan
#

How I convert test
Mt mean if user add a product on my website so the webhook detect the messege and copy it and send in my server with a embed

viscid hornet
slate swan
#

But the game is scrapper yk?

viscid hornet
slate swan
#

Can you do and give me the code?

#

I sent you a web for testing

#

@viscid hornet

viscid hornet
#

you came here for help and i gave it to you 😭

slate swan
viscid hornet
slate swan
#

But answer don't have sol

viscid hornet
slate swan
viscid hornet
slate swan
#

But iam creating a embed

#

But it do auto by bot he scrape messege and send with webbook

viscid hornet
slate swan
#

@viscid hornet

blazing beacon
#

if youre talking about sending an embedded message try reading this

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
viscid hornet
viscid hornet
blazing beacon
#

not to sound rude but it might be a language barrier

slate swan
#

😂😭💀☠️

viscid hornet
viscid hornet
slate swan
#

English or hindi

viscid hornet
slate swan
#

Yes

#

Right thanks a lot

#

Thanks

viscid hornet
#

if needs be, you can use tasks.loop(minutes = 1) to loop something every minute

slate swan
#

Very very thanks

#

Thanks a lot

viscid hornet
#

👍🏽

blazing beacon
#

what else can i do with user apps

viscid hornet
blazing beacon
#

user installable applications

#

like these

steel steppe
#

hold up

#

what happens if u run commands with ur bot here

#

in this server

#

??????????????

blazing beacon
golden portal
unkempt canyonBOT
#

class discord.app_commands.Transformer```
The base class that allows a type annotation in an application command parameter to map into a [`AppCommandOptionType`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType) and transform the raw value into one from this type.

This class is customisable through the overriding of methods and properties in the class and by using it as the second type parameter of the [`Transform`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transform) class. For example, to convert a string into a custom pair type:
golden portal
#

!d discord.app_commands.autocomplete

unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.

Warning

The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
golden portal
#

both of those

blazing beacon
#

neat thanks ill implememt them whenever im free from these exams 🦾

#

saved message jump link in TODO note

torn solar
#

hey so my bot decided to shit itself while i was using gspread to generate 1000 coins with a custom id

#

its not gspread that shit itself because im only generating 2 coins a minute but idk what this error means

hushed galleon
torn solar
#

how can i make it so that it doesnt happen again?

#

the code is supposed to run for about 8 and half hours and i dont want it crashing in the middle and having to restart

hushed galleon
#

generally you should only use await asyncio.sleep(...) with asyncio

torn solar
#

so replace time.sleep with that?

#

and that will fix it?

hushed galleon
#

maybe, i havent seen the rest of your code

torn solar
#
@bot.command()
async def setupCoin1(ctx):
    if any(role.name == "CEO" for role in ctx.author.roles):
        for i in range(1,1001):
            id = random.randint(0,9999)
            cn = getNextEmptyRow(wks1)
            num = cn - 1
            wks1.update_cell(cn, 1, f"COIN {num}")
            wks1.update_cell(cn, 2, str(id))
            await asyncio.sleep(30)```
hushed galleon
#

hmm, gspread is a sync library so in theory it could excessively block your event loop too

torn solar
#

i just want this to work so when i wake up its done generating all the coins 😭

hushed galleon
#

i guess it'd be fine with few usages

torn solar
#

oh shit i just realised i can do =randbetween in google sheets

#

and stop wasint all this time

hushed galleon
#

does it have to be a google sheet tho? relational databases are usually more suitable

torn solar
#

i dont wanna spend money on a database

#

this is for a fun project

hushed galleon
#

you might be able to host one on the same machine as the bot, or more simply use sqlite which is file-based

rustic tiger
#

can anyone look at this please

slate swan
#

what does this mean

naive briar
#

Bot not found

slate swan
eager drift
slate swan
eager drift
#

Can you send the code of it

#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

eager drift
#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

slate swan
#

why would i set my bot to say that shit

eager drift
#

Send code

eager drift
west shuttle
#

I got a ticket system which is currently running on my computer and my WiFi is pretty bad so after you click the button of creating ticket it creates the channel in such a delay and end up members with 10 tickets....

Also,

await interaction.response.defer(ephemeral=True)
            # Create ticket channel
            pfp = interaction.user.avatar.url if interaction.user.avatar else interaction.user.default_avatar.url
            category = interaction.guild.get_channel(1216399233918439535)
            channel = await category.create_text_channel(f'ticket-{self.ticket_counter}')
            self.ticket_counter += 1
            self.save_ticket_counter()  # Save the updated counter to the JSON file
            await interaction.followup.send(content=f"ticket created! {channel.mention}", ephemeral=True)

(not the full code)

await interaction.followup.send(content=f"ticket created! {channel.mention}

Wont work....

Im using disnake

#

ohh right i forgot it exists for a sec lmao thx

#

I mean the python help thread

rugged shadow
west shuttle
rugged shadow
west shuttle
#

Lmao yes

#

But lets not talk bout that

How do i add cooldown to it

rugged shadow
#

not sure

#

but i don't think that's the solution either

#

do you want users to make multiple tickets at once

rugged shadow
#

thatll solve two of ur problems

west shuttle
#

they wont listen

rugged shadow
#

then dont allow them to make one if they have

west shuttle
#

OHHHHHHHHHHH

#

you got a point

slate swan
#

How to i get all notification on my discord server if any person add new product on my website language python for bot

robust fulcrum
drifting arrow
drifting arrow
drifting arrow
robust fulcrum
#

guys i wana make a help command in my bot buts its very hard writing string for every command and hard coding would be bad practice, is there any good way i can make a goog help command , like i can document my commands in cogs and help commands uses that, and use my type annotations to generate help command

west shuttle
viscid hornet