#discord-bots

1 messages Β· Page 279 of 1

slate swan
#

if you are using discord.py its not how you registed slash commands

upbeat mason
#

thats pycord isnt it

slate swan
#

cant use two at once

upbeat mason
upbeat mason
naive swan
#

I dont know what i did wrong, but it says "unexpected indent" on the last line of code

@client.command()
async def help(ctx):
 embed = discord.Embed(title="List of commands for this bot!")
embed.add_field(name="$help - this command!", value="Show this message.", inline=False)
embed.add_field(name="$show, $showpic - google images search!", value="Search for any image in Google!", inline=False)
embed.add_field(name="$snsfw - \U0001F51E", value="Same as $show, but with SafeSearch off... Works only in NSFW channels, though!", inline=False)
embed.add_field(name="$fox", value="Random fox!", inline=False)
embed.add_field(name="$meme", value="Random meme from r/memes!", inline=True)
embed.add_field(name="$ping", value="Pong!", inline=True)
 await ctx.send(embed=embed)
naive briar
#

!e

def a():
   b = 0
b+1
    return b
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 4
002 |     return b
003 | IndentationError: unexpected indent
hushed galleon
#

there's a lot of potential causes for a hanging program, but asyncio doesnt normally take a long time cancelling asynchronous tasks - do you have any code that involves threads? those can very easily hang programs indefinitely

feral frost
#

anyone knows why my imports are white ? they are normally like greenish

#

everything is white all of a sudden

turbid condor
#

It's your linter not an error

#

Change it back to the one you were previously using

#

That will revert the changes to the colors

slate swan
#

when creating Bot instance pass help=None

naive swan
#

let me try..

naive briar
#

!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 "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 "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 "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "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.
naive briar
#

help_command

slate swan
#

help_command

slate swan
feral frost
#

yes i like it

turbid condor
#

Wouldn't the help command throw an error?

#

As there are two help commands so isn't that command already exist

naive briar
#

If they made the command using on_message, no

turbid condor
#

I see

slate swan
#

me wondering how they modded the android client

#

for custom background

naive briar
#

Why would anyone want to change their background anyway

slate swan
#

idk

turbid condor
#

I'll stick to my dark theme

slate swan
#

Dusk theme top

turbid condor
#

Instead of custom bg and all that

finite geyser
#

also tell which package are u using

naive briar
finite geyser
naive briar
#

Attribute and syntax errors are not the same

finite geyser
#

I meant that's not how its done

finite geyser
#

damn Why am I paying for internet

#

jk

vale wing
naive briar
finite geyser
#

so ig he will be fine teacher for me

vale wing
#

You don't love them THAT much (look at his bio)

#

Gotta train hard

finite geyser
vale wing
#

Anyways I had some funny question actually related to disnake

finite geyser
vale wing
#

But uh I broke its internals (second time already) and I no longer have it

finite geyser
vale wing
#

Problem was it called on_timeout after actually stopping view but I use callback-less views and that caused code to get executed anyway

#

So had to overwrite _dispatch_timeout function

vale wing
#

Yall should try callback-less components fr

slate swan
#

you called .stop but it Timed out anyways?

finite geyser
vale wing
#

Nah it timed out, but library first stops, then calls on_timeout, but I needed it to be done in reverse order

finite geyser
#

not Will I am gonna try it now fr

#

I won't be able to remember later

vale wing
#

Lemme show

#

We have uh this piece of code

        for hero in heroes:
            embed.add_field(hero.name, hero.get_stats())
        await inter.send("Select your hero!", view=view, embed=embed)
        hero, inter = await view.get_result(inter, ResponseMode.EDIT)
        view = BossFightView(inter, hero, boss := get_random_boss())
        await view.start()
        bobux_bal = 0
        while True:
            await view.wait()
            if view.timed_out:
                await inter.send(
                    embed=FailEmbed(
                        inter.user,
                        "Bruh your hero fell asleep and got all earned bobux stolen. "
                        f"Please don't go away next time. Thank your **{hero.name}** they didn't leave you",
                    )
                )
                break
            elif not view.hero_won:
#

Sorry for bad indents

#

The thing is on_timeout set the timed_out attribute but since it stopped before, wait() actually exited before that attribute was set

vale wing
finite geyser
shrewd apex
#

atleast i handle complex logic as view extension in view itself

#

altho i like ur method in case of modals and views combined

vale wing
#

I don't like callbacks implementation because you split code which is like unified whole, putting some part into callbacks splits it for no reason and makes it difficult to navigate, although in some cases callbacks method is obviously better

shrewd apex
#

mhm

vale wing
#

Remember the BadModal

slate swan
#

man i need to learn typing features but dunno how and where

vale wing
#

Learn any statically typed language

slate swan
#

i know already c# or typescript but in python its not built in meaning its different

vale wing
#

It's different in syntax but not in concept

slate swan
#

and it has many classes i dont get like Type or any else like when im supposed to use it

vale wing
#

Just imagine python as statically typed

slate swan
vale wing
#

Guess function typehints is too broad

slate swan
#

function typehint easy

slate swan
#

yeah

vale wing
#

Well you positioned your sentence like you necessary need to use every single class from there

#

Which is probably not true

#

Cause you need only what you need

slate swan
vale wing
#

What I'm trying to say is you don't need to know what everything in typing does, but when you need to do something just learn about it

slate swan
#

Asher prolly now finding out i copied his code and modified it xd

slate swan
vale wing
slate swan
#

like i need to know something exists so i know i can use it

unkempt canyonBOT
#

src/env.py line 17

cast: t.Type[T] = MISSING```
slate swan
#

this im actually curious if this is correct way of typehinting that

#

typecheckers dont say antyhing

vale wing
#

Well so basically when you provide something to cast, T gets the type of that something and remembers it for instance. And when you use for example __get__ which returns T, it means it will return type of what the T was set to

#

Regarding that env thing I actually made a module πŸ€“

#

!pypi exenenv

unkempt canyonBOT
slate swan
#

it typehints it to type of int?

slate swan
vale wing
#

What you are probably missing is concept of metaclasses or "class of class"

slate swan
#

!E print(type(int))

unkempt canyonBOT
#

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

<class 'type'>
vale wing
#

Yeah this is the metaclass

slate swan
#

so it thinks that cast will be a type

#

so its actually correct isnt it

vale wing
#

When you typehint something as

a: MyClass

You expect a to be set to instance of that class

a: MyClass = MyClass()

But when you typehint it with Type

a: Type[MyClass]

You expect it to be class itself

a: Type[MyClass] = MyClass
slate swan
#

oh right

#

so it is correct

#

well now at least it makes sense

vale wing
#

Yeah your code is totally correct

#

I forgot what __get__ does tho

slate swan
#

when you access it its invoked i belive

vale wing
#

Like dict[key] syntax I think but what's __getitem__ for then

#

Gotta look at the docs

slate swan
vale wing
#

Ah so that's getattr

slate swan
#

!d typing.TypeVar

unkempt canyonBOT
#

class typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)```
Type variable.

Usage:

```py
T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes
```  Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic "typing.Generic") for more information on generic types. Generic functions work as follows:
slate swan
#

sadly you cant set default value for generic

vale wing
#

You don't need it

#

That kills purpose of generics imho

slate swan
slate swan
vale wing
slate swan
#

i asked how they would improve it

formal basin
#

how can I check if a slash command is used in a dm?

slate swan
formal basin
#

can I check if the id is None

slate swan
#

yes but why not just guild

formal basin
#

what else should I check?

#

channel id?

slate swan
#

no just guild

formal basin
#

oh

slate swan
#

if interaction.guild is None

formal basin
#

oh ok

unkempt canyonBOT
#

discord/ext/commands/core.py lines 2306 to 2311

def predicate(ctx: Context[BotT]) -> bool:
    if ctx.guild is not None:
        raise PrivateMessageOnly()
    return True

return check(predicate)```
formal basin
#

so not the id

slate swan
#

thats how the dm_only check works

formal basin
#

ah I see

#

thanks

nocturne root
#

I'm using discord.py, anybody know why message.attachments is yielding an empty list even though there's an image attached to the message?

slate swan
#

!d discord.Message.attachments

unkempt canyonBOT
slate swan
#

do you have message_content intent enabled?

nocturne root
#

ah shit a new intent

proven shale
#

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

somber sky
#

how would i make a command that makes multiple emojis at once? the emojis wouldnt be picked or anything it would be emojis i put in the code, so the emojis would always be the same ones

plush pond
#

why doesn't my app show up on this page after authorizing?
it once worked but now it doesn't

#

I removed it to test it with diffrent scopes but now it just won't show even with the same scopes

shrewd apex
#

iirc discord oauth has time limit set on tokens on which u have to refresh and re authorise ur application but that time limit is relatively large

subtle jolt
#

this modifies the view of the sent response, how do i modify the current view after a response message is sent?

await interaction.response.send_message(
    content='Confirm',
    view=ConfirmButton(),
    ephemeral=True
)
await interaction.edit_original_response(view=None)
slate swan
#

@ me if you can help

#

whats

#

you cant

#

there is not emoji format

#

πŸ’€

#

like nerdbot

slate swan
vocal magnet
#

we're not going to help you abuse stolen accounts here.

slate swan
#

what does that emoji mean

slate swan
slate swan
slate swan
alpine oar
#

Yo @slate swan may i get help?

#

So this keeps saying the x1 value is greater than x0 and i just dont get why it gives me the error ```def create_level_card_image(username, level, xp):
bg_image = Image.open("Pokemon.png")
bg_image = bg_image.resize((400, 200))

width, height = bg_image.size
img = Image.new("RGBA", (width, height), (255, 255, 255, 0))

img.paste(bg_image, (0, 0))

font = ImageFont.truetype("arial.ttf", 24)

draw = ImageDraw.Draw(img)
draw.text((30, 30), f"{username}'s Level", font=font, fill=(0, 0, 0, 255))
draw.text((30, 70), f"Level: {level}", font=font, fill=(0, 0, 0, 255))
draw.text((30, 100), f"XP: {xp}/100", font=font, fill=(0, 0, 0, 255))

xp_percent = xp / 100
progress_width = min(int(200 * xp_percent), 200)
draw.rectangle([30, 140, 30 + progress_width, 160], fill=(0, 255, 0, 255))
draw.rectangle([30 + progress_width, 140, 230, 160], fill=(255, 0, 0, 255))

return img```
#

Theres the code tryna code a lvl system

#

@buoyant quail U wanna help mabey? hehe

#

heres the error btw ```Traceback (most recent call last):
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users.BELUGHA\Downloads\Discord Bot\Luffy0102.py", line 309, in xp
img = create_level_card_image(user.display_name, level, xp)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users.BELUGHA\Downloads\Discord Bot\Luffy0102.py", line 280, in create_level_card_image
draw.rectangle([30, 140, 30 + progress_width, 160], fill=(0, 255, 0, 255))
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\PIL\ImageDraw.py", line 294, in rectangle
self.draw.draw_rectangle(xy, fill, 1)
ValueError: x1 must be greater than or equal to x0

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

Traceback (most recent call last):
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users.BELUGHA\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: x1 must be greater than or equal to x0```

#

@elfin island Wanna help me mabey? heh

#

anyone wanna help me?

naive briar
#

Have patience and just wait

alpine oar
alpine oar
slate swan
hasty pike
compact ruin
#

How do i print a users server nickname... the update seems to have changed it..

slate swan
#

!d discord.Member.nick

unkempt canyonBOT
#

The guild specific nickname of the user. Takes precedence over the global name.

compact ruin
umbral flame
#

hllo there im making my first ever discord bot, i just want to know how to even start coding it since im restarting it from scratch.

is this how i start the bot up to begin with?

import discord
import os
from discord.ext import commands
from keep_online import keepy_uppy

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

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

keepy_uppy()
bot.run(os.environ['TOKEN'])
#

im hosting on replit btw

#

and the TOKEN is my actual bot token

umbral flame
formal basin
#

but wont you need intents?

umbral flame
#

now how di i add commands?

umbral flame
formal basin
formal basin
umbral flame
umbral flame
formal basin
umbral flame
naive briar
umbral flame
#

yeah id go with / since its more memorable and has that pop up with a description

formal basin
umbral flame
slate swan
#

A guide you can see some examples and explaination but its not fully done yet

formal basin
#

so the member intents is needed

naive briar
#

What

#

!d discord.User.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
umbral flame
slate swan
#

You dont need members intent to send messages to users

naive briar
#

I don't know about you, but sending DMs don't require member intents

formal basin
#

oh.

naive briar
umbral flame
slate swan
formal basin
umbral flame
formal basin
#

ephemeral?

umbral flame
formal basin
#

like it sends a message that only that user can see

#

and it says dissmiss message

umbral flame
#

sorry for the confusion

formal basin
#

ok

#

well

rapid knoll
#

I have this code and it keeps telling me that,

TypeError: function() argument 'code' must be code, not str```


The Python Code is:

```py
import os, sys
import random, string, math, decimal
import re, struct
import uuid, hashlib, base64
import threading as thr
import _thread as thread
import asyncio, timeit, time
import socket, select, selectors, pickle
import csv, json
import numpy as np

import discord
from discord.ext import tasks, commands
from discord.utils import get
from discord import Intents

with open("bot.json", "r") as f:
   BOT = json.load(f)

token = BOT["token"]

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

bot = commands.Bot(command_prefix='$', intents=intents)

@bot.event
async def on_ready():
   print("{0} Online".format(bot.user.name))


if __name__ == "__main__":
   bot.run(token)
rapid knoll
# slate swan Full traceback?

Traceback (most recent call last):
File "C:\Users~\OneDrive\Desktop\Arcane\arcane.py", line 12, in <module>
import discord
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord_init_.py", line 23, in <module>
from .client import *
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 49, in <module>
import aiohttp
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp_init_.py", line 6, in <module>
from .client import (
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\client.py", line 35, in <module>
from . import hdrs, http, payload
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\http.py", line 7, in <module>
from .http_parser import (
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\http_parser.py", line 15, in <module>
from .helpers import NO_EXTENSIONS, BaseTimerContext
File "C:\Users~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiohttp\helpers.py", line 667, in <module>
class CeilTimeout(async_timeout.timeout):
TypeError: function() argument 'code' must be code, not str

umbral flame
rapid knoll
slate swan
#

What version you have

rapid knoll
slate swan
#

That's not latest version

unkempt canyonBOT
slate swan
#

do pip install -U discord.py

rapid knoll
slate swan
#

Yep

umbral flame
#

how can i check my discord version on my shell??

slate swan
umbral flame
#

thx

tall cypress
#

import discord
from discord.ext import commands

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

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

@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')

@bot.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'{member.mention} has been kicked.')

bot.run('TOKEN')

#

Why the command doesn't work?

slate swan
#

Cause you dont have message_content intent enabled

#

!mcintent

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

weak ingot
#

i want to make a discord bot with slash commands how to i do it in discord.py version 2.3.1

#

!mcintent

weak ingot
slate swan
#

So subclass a Bot

umbral flame
#

is there a way i can make my bot go offline when a command is run via discord?

fading marlin
#

!d discord.Client.close

unkempt canyonBOT
#

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

Closes the connection to Discord.
umbral flame
#

is there a way for me to turn off my bot then turn it on again?

#

bascially a restart

meager rock
slate swan
#

Where we can hire people?

meager rock
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.
meager rock
#

With extensions

#

This allows you to hot reload your commands without restarting the bot

sick birch
unkempt canyonBOT
#

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

Atomically reloads an extension.

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

so this is my code:

    async def create_ticket(self, interaction: discord.Interaction):
        global ticket_count
        # Check if the ticket count has reached the limit (50)
        if ticket_count >= 2:
            await interaction.followup.send("Sorry, the ticket limit has been reached. Please try again later.", ephemeral=True)
            return```
and i am getting the following errror:
https://srcb.in/ym7MLuBRKr

and the message "Sorry, the ticket limit has been reached. Please try again later." is not being sent
slate swan
#

Can someone dm me to code me a bot robotmoney_with_wingsmoney_with_wings

slate swan
#

!rule 9

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

slate swan
#

Yeah we also dont code for people but we help them solve their problems with code

torn solar
#

iim probably just being dumb, but why does it say bot has no attribute tree

vocal snow
#

Which library are you using?

torn solar
vocal snow
#

Version?

torn solar
#

lemme check

#

whats the command again

vocal snow
torn solar
#

version 1.7.3

vocal snow
#

Update then

torn solar
graceful basin
#

hey, need some help with an unban command for a slash bot..

slate swan
#

ok

twilit grotto
graceful basin
torn sail
# graceful basin it doesnt work...

instead of doing all the for loop stuff you could just do this

typehint user_id as int
then just do await interaction.guild.unban(discord.Object(id=user_id))
because you don't need the full user object to ban, just the id

still phoenix
#

Hey there. Im new to programming. Is anyone here, that has knowledge about SQL-Injection? Wanted to ask a few small things in dm ^^ (pymongo + discordpy)

meager rock
#

!sql-fstrings

unkempt canyonBOT
#
SQL & f-strings

Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
β€’ Python sqlite3 docs - How to use placeholders to bind values in SQL queries
β€’ PEP-249 - A specification of how database libraries in Python should work

meager rock
#

^ SQL injections

#

If that what you mean

naive briar
#

async generator can't be awaited

#

!d discord.Guild.bans

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
naive briar
#

There's an example in the docs

still phoenix
#

Only check if it is a youtube link. Maybe I add regex later on

glad cradle
#

are you using the async library?

#

it's called motor iirc

#

!pypi motor

meager rock
unkempt canyonBOT
still phoenix
torn solar
#

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

torn solar
#
@bot.tree.command(name="purge", description="Purge messages in a channel")
async def purge(ctx: discord.Interaction, amount: int):
    await ctx.channel.purge(limit=(amount + 1))
    embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
                          
                          Sucessfully purge `{amount}` messages.
                          
                          """)
    time = datetime.now().strftime("%c")
    embed2 = discord.Embed(title="Purge")
    embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
    embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
    embed2.set_footer(text=time)
    await ctx.response.send_message(embed=embed)
    await log_channel.send(embed=embed2)```
#

sorry sending error, i had to delete paste i accidentally sent bot token

slate swan
#

You purge, so you delete the interaction, so the bot cannot send a response to a deleted interaction

naive briar
torn solar
#

your right

torn solar
#

even though it worked

#

so how can i respond if the interaction is being deleted

#

log_channel = bot.get_channel(1136515581550530710) also it says that is a NoneType and doesnt have method .send

graceful basin
graceful basin
torn solar
#

yeah

#

it is an interaction i just named it ctx

graceful basin
torn solar
#

ints cant start with 0

graceful basin
torn solar
#

keep that in mind

graceful basin
#

but the id starts with 1

wispy pasture
#

so this is my code:

    async def create_ticket(self, interaction: discord.Interaction):
        global ticket_count
        # Check if the ticket count has reached the limit (50)
        if ticket_count >= 2:
            await interaction.followup.send("Sorry, the ticket limit has been reached. Please try again later.", ephemeral=True)
            return```
and i am getting the following errror:
https://srcb.in/ym7MLuBRKr

and the message "Sorry, the ticket limit has been reached. Please try again later." is not being sent

someone told me:

looks like you didn't respond first
you have to responded before you can send followups```

can someone tell what did he meant by respond before followups?

slate swan
#

@wispy pasture Do py return await interaction.followup.send("Sorry, the ticket limit has been reached. Please try again later.", ephemeral=True)

wispy pasture
#

oooo okay

graceful basin
wispy pasture
naive briar
graceful basin
naive briar
#

Show your entire code

naive briar
naive briar
graceful basin
naive briar
#

You mean you can't see these giant code blocks?

#

Wrong one, this

graceful basin
#

what does the limit thing mean?

#

and i can change that correct?

graceful basin
formal basin
#

!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...
naive briar
graceful basin
#

im sorry, i dont understand what you mean by yielded

shrewd apex
wispy pasture
naive briar
#

Show your full code

plush pond
cyan grove
#

just wanted to know what these stuffs are called?

#

i wanna add these to my bot

sterile fulcrum
#

Can someone tell me how to make a code that sends an embed with a Button UI and when I press that button it sends a modal after i completed the modal it sends an embed with another ui and when I press it sends another modal

sterile fulcrum
cyan grove
#

GL with you finding it

sterile fulcrum
#

You too

feral sinew
#

you can use interaction.response.send_message and supply it with a new view that contains the buttons you want, its been a while since i did this so i could be missing a detail

grim robin
#

When I'm trying to get info on an embed, if its sidebar color is set to discord.Colour.default() or has otherwise a value of 0, the result I get from quering Embed.color is None. All other values return fine. My issue is that values of None and 0 when you sent an embed are 2 different colors and only having None as a return value makes you unable to distinguish between the two

feral sinew
#

i feel that is intended or is a bug

grim robin
still phoenix
#

run_bot Is my main function and im using asyncio.get_event_loop().create_task(run_bot()).
Now the bot seems to work but I get thefollowing message in the terminal. :

  • RuntimeWarning: coroutine 'run_bot' was never awaited self._ready.clear()

How do I await this?

glad cradle
#

pls share the core and the full error

still phoenix
# glad cradle pls share the core and the full error

task: <Task pending name='Task-1' coro=<run_bot() running at D:\dc bot\prayer_times.py:97>>
C:\Users...\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py:671: RuntimeWarning: coroutine 'run_bot' was never awaited
self._ready.clear()

unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

copper gulch
#

    @app_commands.command(name="user")
    async def user(self, interaction:discord.Interaction, user: discord.Member):
        Userdiscord = await self.bot.fetch_user(user.id)
        """Gets info on a member, such as their ID."""
        embed = discord.Embed(title=user.name, colour=user.colour)
        embed.set_image(url = Userdiscord.banner)
        embed.add_field(name="Name:", value=user.name)
        embed.add_field(name="ID:", value=user.id)
        embed.add_field(name="Status:", value=user.status)
        embed.add_field(name="Highest role:", value=user.top_role)
        embed.add_field(name="Joined:", value=user.joined_at)
        embed.set_thumbnail(url=user.avatar)
        await interaction.response.send_message(embed=embed)

How do I make this slash command only show to admin and not all members

naive briar
grim robin
weak ingot
#

how to make a dicord py bot with slash commannd annd runn it like a bot not client

copper gulch
#
    @app_commands.command(name = "confess", description = "Confess something")
    async def confess(self, Interaction:discord.Interaction, confession:str):
        await Interaction.response.send_message("Confession sent", hidden = True)

anyone know how I can make the response only visible to the person who did the slash command?

weak ingot
#

@copper gulch is that a slash command

golden portal
copper gulch
#

yea

golden portal
#

you can check this by seeing the API response [when you fetch], both of them results in no color field given for their embeds

copper gulch
weak ingot
#

like a bot or a cliet??

#

client**

#

and @copper gulch can you send me the code to make a slash command

slate swan
unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
slate swan
#

ephemeral (bool) – Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.

copper gulch
#

thank you

weak ingot
#

how to run this

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

class MyCog(commands.Cog):
  def __init__(self, bot: commands.Bot) -> None:
    self.bot = bot
    
  @app_commands.command(name="command-1")
  async def my_command(self, interaction: discord.Interaction) -> None:
    """ /command-1 """
    await interaction.response.send_message("Hello from command 1!", ephemeral=True)

  @app_commands.command(name="command-2")
  @app_commands.guilds(discord.Object(id=...), ...)
  async def my_private_command(self, interaction: discord.Interaction) -> None:
    """ /command-2 """
    await interaction.response.send_message("Hello from private command!", ephemeral=True)

async def setup(bot: commands.Bot) -> None:
  await bot.add_cog(MyCog(bot))
vale wing
#

You don't run it, you load it

weak ingot
#

how

vale wing
#

For example put that code into myextension.py file, then in your main do this

class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(...)  # whatever you put in constructor

    async def setup_hook(self):
        await self.load_extension("myextension")  # here we load it


bot = MyBot()
bot.run(...)
#

Also will need to sync the commands but idk how to do that in dpy

weak ingot
#

is there a way to make it all i onnnne file

vale wing
#

Probably self.tree.sync() in setup_hook

vale wing
#

Extensions are recommended way of organising dpy bots

weak ingot
#

ik

vale wing
#

You can ofc, just copy functions and change decorators

weak ingot
#

okay thanks

copper gulch
#
        embed33.set_footer(text=f'Type "/confess" to send a confession')
        await channel.send(embed=embed33)

anyone know how I can add timestamp here with UTC+08?

slate swan
#

!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...
slate swan
#

pass timestamp ^

weak ingot
#
import asyncio
import discord
from discord.ext import commands, app_commands

intents = discord.Intents.default()  # Default intents
intents.typing = False
intents.presences = False

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

@bot.command()
async def my_command(ctx: commands.Context):
    await ctx.send("Hello from my command!")

@bot.group(name="some-parent", description="description")
async def group(ctx: commands.Context):
    if ctx.invoked_subcommand is None:
        await ctx.send("Invalid subcommand.")

@group.command()
async def my_subcommand(ctx: commands.Context):
    await ctx.send("Hello from the subcommand!")

bot.add_command(group)

async def main():
    # Set up your commands here
    bot.remove_command("help")  # Optional, if you want to remove the default help command
    
    async with bot:
        await bot.start("MT...Xs")

if __name__ == "__main__":
    asyncio.run(main())

i get

python3 main.py 
Traceback (most recent call last):
  File "/home/***/Documents/Code/******/FlareMod/main.py", line 3, in <module>
    from discord.ext import commands, app_commands
ImportError: cannot import name 'app_commands' from 'discord.ext' (unknown location)
copper gulch
copper gulch
weak ingot
slate swan
weak ingot
#

okay thx

weak ingot
# slate swan `from discord import app_commands`

i got this

python3 main.py 
Traceback (most recent call last):
  File "/home/****/Documents/Code/******/FlareMod/main.py", line 25, in <module>
    bot.add_command(group)
  File "/home/****/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 246, in add_command
    super().add_command(command)
  File "/home/****/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1356, in add_command
    raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command some-parent is already an existing command or alias.
slate swan
weak ingot
# slate swan you already defined command with such name
import asyncio
import discord
from discord import app_commands
from discord.ext import commands

intents = discord.Intents.default()  # Default intents
intents.typing = False
intents.presences = False

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

@bot.command()
async def my_command(ctx: commands.Context):
    await ctx.send("Hello from my command!")

@bot.group(name="some-parent", description="description")
async def group(ctx: commands.Context):
    if ctx.invoked_subcommand is None:
        await ctx.send("Invalid subcommand.")

@group.command()
async def my_subcommand(ctx: commands.Context):
    await ctx.send("Hello from the subcommand!")

bot.add_command(group)

async def main():
    # Set up your commands here
    bot.remove_command("help")  # Optional, if you want to remove the default help command
    
    async with bot:
        await bot.start("MT...Xs")

if __name__ == "__main__":
    asyncio.run(main())
slate swan
weak ingot
#

i coped it for a gist

slate swan
#

well its not correct

weak ingot
slate swan
#

also this gist is for slash commands and you only have prefixed ones

weak ingot
slate swan
weak ingot
#

but that runs the bbot as i client

#

i wat to runn it as a bot

slate swan
#

so use bot

weak ingot
#

okay thannks

slate swan
#

anyone know a faster way of finding what channel a user last messaged in without looping through all channels?

upbeat ice
slate swan
upbeat ice
wispy pasture
#

so this is my code:

    async def create_ticket(self, interaction: discord.Interaction):
        global ticket_count
        # Check if the ticket count has reached the limit (50)
        if ticket_count >= 2:
            await interaction.followup.send("Sorry, the ticket limit has been reached. Please try again later.", ephemeral=True)
            return```
and i am getting the following errror:
https://srcb.in/ym7MLuBRKr

and the message "Sorry, the ticket limit has been reached. Please try again later." is not being sent

and i am using no webhook
formal basin
#

when I defer my slash commands my error handler doesnt send the embed

@tree.error
async def on_app_command_error(interaction: discord.Interaction, error: AppCommandError):
     await interaction.response.defer()
     command = interaction.command.name
     channel2 = client.get_channel(1112053260879147130)
     if isinstance(error, app_commands.CommandOnCooldown):
        await interaction.followup.send(error, ephemeral=True)
     else:
       button = Button(label="support server", url="url")
       view = View()
       view.add_item(button)
       embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server.", colour=discord.Colour.red)
       await interaction.followup.send(embed=embed, view=view)
       await channel2.send(f"{command} command used by {interaction.user} but an error occured")
       traceback.print_exc(limit=None, file=None, chain=True)
upbeat ice
slate swan
wispy pasture
wispy pasture
slate swan
#

i would recomment avoid using global

slate swan
#

but yeah you can followup when you defer interaction

wispy pasture
#

wait what now followup is webhook?

slate swan
#

!d discord.Interaction.followup

unkempt canyonBOT
wispy pasture
upbeat ice
formal basin
formal basin
# upbeat ice can you show the command that you are using to trigger this
@client.tree.command(name="kick", description="kicks a user (moderator only)")
@app_commands.default_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, *, reason: str = "no reason provided"):
 await interaction.response.defer()
 try:
  embed = discord.Embed(title=f"{member} was kicked by {interaction.user}", color=discord.Color.blue())
  embed.add_field(name= "Reason:", value = f"{reason}")
  await member.kick() 
  await interaction.followup.send(f"{member} was kicked.")
  log = r.get(f"logs:{interaction.guild.id}")
  log2 = int(log.decode("utf-8"))
  logging = client.get_channel(log2) or await client.fetch_channel(log2)
  await logging.send(embed=embed)
  await member.send(f"you were kicked from ``{interaction.guild.name}`` reason: {reason}")
 except KeyError:
   pass```
upbeat ice
#

so I think the issue is that you are defering the same interaction twice

slate swan
#

yeah why defer it inside error handler too

graceful basin
#

hey! for some reason, when i do /unban on a user, the ban still exists...how can i fix that?

graceful basin
unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

it accepts Snowflake

#

so you dont have to loop over all bans

#

you can just pass discord.Object(id=int(user_id))

formal basin
#
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
    await self._call(interaction)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1252, in _call
    await self.on_error(interaction, e)
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 1087, in on_app_command_error
    embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server. ", colour=discord.Colour.red)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/embeds.py", line 179, in __init__
    self.colour = colour if colour is not None else color
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/embeds.py", line 323, in colour
    raise TypeError(f'Expected discord.Colour, int, or None but received {value.__class__.__name__} instead.')
TypeError: Expected discord.Colour, int, or None but received method instead.

graceful basin
slate swan
graceful basin
#

do i use int or str

#

cus everything else in the method is str

slate swan
slate swan
unkempt canyonBOT
#

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

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

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

x == y Checks if two objects are equal.

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

hash(x) Returns the object’s hash.
slate swan
#

int

formal basin
#

it needs to be an id?

graceful basin
#

i did int but when i put it on the test it says need valid integer

#

even though its an valid id

slate swan
#

show what you tried?

upbeat ice
graceful basin
#
@bot.tree.command(name="unban", description="Unban a user from the server")
@commands.has_permissions(ban_members=True)
async def unban(interaction: discord.Interaction, user_id: int):
    # Fetch the banned users using async for loop
    banned_users = interaction.guild.bans()
    async for entry in banned_users:
        if entry.user.id == int(user_id):
            interaction.guild.unban(entry.user)
            embed = discord.Embed(title="User Unbanned", description=f"{entry.user.mention} has been unbanned.", color=0x40caf7)
            await interaction.response.send_message(embed=embed)
            return```
graceful basin
slate swan
#

cause you changed nothing

graceful basin
#

yeah, do you want me to put that in the async for?

slate swan
graceful basin
#

so

#

i put it in the async for loop

formal basin
#
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
    await self._call(interaction)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1252, in _call
    await self.on_error(interaction, e)
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 1088, in on_app_command_error
    await interaction.response.send_message(embed=embed, view=view)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/interactions.py", line 772, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
slate swan
#

no you dont use the loop

upbeat ice
#

you already responded before to that interaction so this needs to be a followup

graceful basin
#

dont you have to because the command is a coroutine?

formal basin
#

in the error handler

upbeat ice
#

you defered it in the command

formal basin
#

ok

upbeat ice
#

the error handler just recieves that interaction

formal basin
#

πŸ‘

graceful basin
#

you need to have "async for" in unbans right?

slate swan
#

why?

formal basin
slate swan
#

im telling you not to loop over each ban

#

its unnececary

graceful basin
#

you cant use async generator for unban command

slate swan
#

i have no idea why you want that for loop so bad

graceful basin
slate swan
#

yeah and what does that have to do with this

#

you dont need this at all

upbeat ice
#

try/except

graceful basin
#

so you're saying i can remove the async for part?

slate swan
#

yeah like 4th time

graceful basin
#

and so how should i replace it?

#

or just leave it be

slate swan
#

and pass discord.Object inside

#

with the id being user_id passed to command

graceful basin
#

oh alr

#

still getting that

#

why does it say input a valid int?

slate swan
#

cause you annotated it as int

#

go back to str

graceful basin
#

even the discord obj?

upbeat ice
#

an int should still work there

#

can you show your code now

graceful basin
#
@bot.tree.command(name="unban", description="Unban a user from the server")
@commands.has_permissions(ban_members=True)
async def unban(interaction: discord.Interaction, user_id: str):
    
    discord.Object(id=int(user_id))
    
    interaction.guild.unban(user_id)
    embed = discord.Embed(title="User Unbanned", description=f"{user_id.mention} has been unbanned.", color=0x40caf7)
    await interaction.response.send_message(embed=embed)
    return
upbeat ice
#

you can keep user_id as an int

#

you also need to await unbanning someone

#

and you dont need that discord.Object line

graceful basin
upbeat ice
#

yup

graceful basin
#

πŸ‘

upbeat ice
#

and you also should resync your commands

graceful basin
#

still says i need a valid integer

upbeat ice
#

did you resync

graceful basin
#

yea

upbeat ice
#

how sure are you πŸ˜›

graceful basin
#

very sure indeed

#

i get this error

upbeat ice
#

can you show the full error and update your code again

graceful basin
upbeat ice
#

and the code again?

graceful basin
#
@commands.has_permissions(ban_members=True)
async def unban(interaction: discord.Interaction, user_id: int):
    
    await interaction.guild.unban(user_id)
    embed = discord.Embed(title="User Unbanned", description=f"{user_id.mention} has been unbanned.", color=0x40caf7)
    await interaction.response.send_message(embed=embed)
    return```
upbeat ice
#

oh

#

you need to get a valid user object from that id

#

!d discord.Client.fetch_user

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
graceful basin
#

Oh, do I need to inlwcude that line

upbeat ice
#

also like suggested before you can go back to using discord.Object

graceful basin
#

In the method

upbeat ice
#

you can fetch the user or construct your own object but you need to pass that to the unban method

graceful basin
upbeat ice
#

not sure i understand your question but you can just do await interaction.guild.unban(discord.Object(id=user_id)))

graceful basin
upbeat ice
#

well its one or the other

graceful basin
#

I see, just need one?

upbeat ice
#

you either make the object yourself with what i just sent or you fetch the user from the api

graceful basin
#

Alright I will try it

#

Thank you so much for your patience and help:)

torn solar
#
@bot.tree.command(name="purge", description="Purge messages in a channel")
async def purge(ctx: discord.Interaction, amount: int):
    await ctx.channel.purge(limit=(amount + 1))
    embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
                          
                          Sucessfully purge `{amount}` messages.
                          
                          """)
    time = datetime.now().strftime("%c")
    embed2 = discord.Embed(title="Purge")
    embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
    embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
    embed2.set_footer(text=time)
    await ctx.channel.send(embed=embed)
    await bot.get_channel(1136515581550530710).send(embed2)```
How can i delay the interaction so i can respond to it
#

because if you dont respond it says interaction failed

upbeat ice
#

!d discord.InteractionResponse.defer

vale wing
#

You never actually respond to interaction

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
torn solar
#

how long does it defer for

upbeat ice
#

i wanna say like 15 minutes but i would have to look it up

torn solar
#

i want like 3 seconds

vale wing
#

You never actually respond to interaction telling once again

torn solar
#

its a purge command

vale wing
#

ctx.channel.send() sends a message, not responds

#

You need ctx.response.send_message()

#

And better call instance of Interaction interaction or inter

vale wing
torn solar
#

so how could i make it respond like in 3 seconds

#

also i prefer calling the interaction ctx

upbeat ice
torn solar
upbeat ice
#

defer response ----> followup

torn solar
#
@bot.tree.command(name="purge", description="Purge messages in a channel")
async def purge(ctx: discord.Interaction, amount: int):
    await ctx.response.defer(ephemeral=False,thinking=False)
    await ctx.channel.purge(limit=(amount + 1))
    embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
                          
                          Sucessfully purge `{amount}` messages.
                          
                          """)
    time = datetime.now().strftime("%c")
    embed2 = discord.Embed(title="Purge")
    embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
    embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
    embed2.set_footer(text=time)
    await ctx.response.send_message(embed=embed)
    await bot.get_channel(1136515581550530710).send(embed2)```
#

also the laste line wont work it saying NoneType has no attribute send

upbeat ice
#

you have to followup

torn solar
#

wdym followup

vale wing
#

ctx.followup.send_message

torn solar
#

ty

vale wing
torn solar
#

and for the last line?

#

its saying NoneType has no attribute send

vale wing
#

Last line is fine

#

Well then there's no such channel

torn solar
#

weird

vale wing
#

At least bot didn't find

#

!d discord.ext.commands.Bot.fetch_channel

unkempt canyonBOT
#

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

Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.

Note

This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.

New in version 1.2.

Changed in version 2.0: `channel_id` parameter is now positional-only.
vale wing
#

Try this

torn solar
#

there is a channel with that id tho

vale wing
#

Yeah might not be in bot's cache

torn solar
#

and ive been using the bot.get_channel method for all my bots

cloud dawn
#

A getch function would be much safer.

vale wing
#

Too bad dpy doesn't have it

cloud dawn
#

I mean you can make it pretty easily.

vale wing
#

Can make it yourself tho not a big deal

async def getch_channel(self, id: int):
    return self.get_channel(id) or await self.fetch_channel(id)
torn solar
#
    log.send(embed=embed)```
#

so like that?

vale wing
#

Yeah

cloud dawn
#

@vale wing wat

vale wing
#

Wat

vale wing
torn solar
#
  File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 130, in purge
    await ctx.followup.send_message(embed=embed)
AttributeError: 'Webhook' object has no attribute 'send_message'

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

Traceback (most recent call last):
  File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'Webhook' object has no attribute 'send_message'```
upbeat ice
#

its send

cloud dawn
torn solar
#
async def purge(ctx: discord.Interaction, amount: int):
    await ctx.response.defer(ephemeral=False,thinking=False)
    await ctx.channel.purge(limit=(amount + 1))
    embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
                          
                          Sucessfully purge `{amount}` messages.
                          
                          """)
    time = datetime.now().strftime("%c")
    embed2 = discord.Embed(title="Purge")
    embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
    embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
    embed2.set_footer(text=time)
    await ctx.followup.send_message(embed=embed)
    log = await bot.fetch_channel(channel_id=1136515581550530710)
    log.send(embed=embed)```
torn solar
#

no

vale wing
cloud dawn
#

Leak the lines

slate swan
#

Sorry for indent πŸ˜΅β€πŸ’«

torn solar
#

yay new error

torn solar
#

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

slate swan
torn solar
#

error ^^^

#
async def purge(ctx: discord.Interaction, amount: int):
    await ctx.response.defer(ephemeral=False,thinking=False)
    await ctx.channel.purge(limit=(amount + 1))
    embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
                          
                          Sucessfully purged `{amount}` message(s).
                          
                          """)
    time = datetime.now().strftime("%c")
    embed2 = discord.Embed(title="Purge")
    embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
    embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
    embed2.set_footer(text=time)
    await ctx.followup.send(embed=embed)
    log = await bot.fetch_channel(channel_id=1136515581550530710)
    log.send(embed=embed)```
slate swan
cloud dawn
vale wing
cloud dawn
vale wing
#

@cloud dawn hoW iS bOBuX DynAmiC uPDatE sySTeM/!?/12

slate swan
vale wing
#

@slate swan uh oh I just opened your gh and got jumpscared

slate swan
#

Is it cause hog rider is Black πŸ—Ώ

cloud dawn
vale wing
#

Okay thanks

slate swan
#

Whatever bobux is

#

I feel i wanna contribute

vale wing
#

Bot we are working on

torn solar
#
    await ctx.followup.send(embed=embed)```
cloud dawn
#

I'm not taking any credit for the bot base

vale wing
#

Quite uh we

torn solar
#

says unknown error

vale wing
torn solar
#
async def purge(ctx: discord.Interaction, amount: int):
    await ctx.response.defer(ephemeral=False,thinking=False)
    await ctx.channel.purge(limit=(amount + 1))
    embed = discord.Embed(title="Purge Results", color=rnp_color, timestamp=datetime.now(), description=f"""
                          
                          Sucessfully purged `{amount}` message(s).
                          
                          """)
    time = datetime.now().strftime("%c")
    embed2 = discord.Embed(title="Purge")
    embed2.add_field(name="Executor", value=f"`{ctx.user.display_name}`")
    embed2.add_field(name="Purge Amount", value=f"`{amount}`", inline=False)
    embed2.set_footer(text=time)
    await ctx.followup.send(embed=embed)
    log = await bot.get_channel(1136515581550530710) or await bot.fetch_channel(1136515581550530710)
    if log == None:
        print("Failed to fetch log channel")
        return
    log.send(embed=embed)```
Ive made other commands before why is purge so stingy
vale wing
#

== None ohnodisappear

torn solar
#

rip

#

my fault i like java

cloud dawn
#

Java does == None?

#

Cursed

vale wing
#

null

torn solar
#

its null in java

#

but yeah

vale wing
#

I forgot if java has is operator tho

vale wing
slate swan
torn solar
vale wing
#

Can invite you if you wish

torn solar
#

the error is in the followup.send

cloud dawn
slate swan
#

But since Asher is here i need to finish doing task for theirs repo

#

Xd

torn solar
#

someone help

vale wing
#

So try that

cloud dawn
#

Can webhooks send empty messages?

torn solar
#

try what?

vale wing
#

In your ctx.response.defer

slate swan
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
torn solar
#

okay we are making progress

#

its purging, but its not sending the logging embed

#
  File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 131, in purge
    log = await bot.get_channel(1136515581550530710) or await bot.fetch_channel(1136515581550530710)
TypeError: object TextChannel can't be used in 'await' expression

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

Traceback (most recent call last):
  File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/RNP-Discord-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: TypeError: object TextChannel can't be used in 'await' expression```
vale wing
#

Because you don't need first await

slate swan
#

@vale wing ill think about joining what the bot does though

vale wing
#

get_channel is sync

torn solar
#

oopsie

slate swan
#

Will check out when on pc

vale wing
#

Sure

#

I can dm you some details on project

slate swan
#

Sure

vale wing
slate swan
graceful basin
slate swan
graceful basin
#

oh...

cloud dawn
#

Just pass a user object

slate swan
#

Its unban command

#

But wondering if you can annotate it as discord.Object

upbeat ice
slate swan
cloud dawn
#

It's like 32 bit or smth

upbeat ice
#

i thought it was just the memory limit

cloud dawn
#

Yeah but I forgor the int naming

graceful basin
slate swan
cloud dawn
upbeat ice
#

is that not well within the id length?

slate swan
#

Nope

cloud dawn
#

!e print(2**53)

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.

9007199254740992
hushed galleon
#

2^53 is 16 digits, IDs now reach 19 digits

slate swan
#

!e print(1057126299623243797 < 2**53)

unkempt canyonBOT
#

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

False
cloud dawn
#

Discord skill issue

#

Regex for command rejection when

graceful basin
#

should i go w str?

cloud dawn
#

Yep but may I ask, why a unban command?

upbeat ice
graceful basin
cloud dawn
#

But the server has a ui for unbanning them..

graceful basin
#

ik but its easier for moderation

cloud dawn
#

Unless you make a whole moderation system with automated user history logging.

slate swan
formal basin
#

would await member.send work if the user is not in the server

slate swan
#

Member object is per guild basis so you cant have a Member object if the member is not inside guild

#

unless you meant User then it would work

formal basin
#

so I can use the user object instead of the Member object

#

so would user.kick work?

slate swan
#

no cause you can only kick member

formal basin
#

ok

slate swan
#

User represents a global Discord user and a GuildMember represents a Discord user on a specific server

#

you can kick someone from a guild so it must be per guild Member

formal basin
#

so how can I turn a user object into a member Object

slate swan
#

how do you get the User object

#

from where

formal basin
#

in a command

slate swan
#

then annotate it as Member

formal basin
slate swan
#

since he was in guild when you gathered the object

graceful basin
#

alrady

slate swan
graceful basin
#

wdym

#

in the .tree.command line right?

slate swan
#

no how you wanna put it in decorator

#

annotation to the command function param

#

user_id: discord.Object

graceful basin
formal basin
unkempt canyonBOT
#

property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.bot "discord.User.bot")
formal basin
slate swan
formal basin
#

πŸ‘

formal basin
slate swan
formal basin
upbeat ice
#

that will do

hasty pike
slate swan
#

if i wanted to get the ID members robux clothign games and games visit how would i get all those values?

right now the embed is in a embed object

sterile fulcrum
#

Can someone tell me why when I turn the bot on and I press my UI button it works but after a few minutes it doesn't and if i turn it off then back off it's working again
My code - https://paste.pythondiscord.com/7AQA

sick coyote
#

how would i enable all intents except message content and presence intent?

#

is it just discord.Intents.members?

slate swan
#

enable all and disable the ones you want

sick coyote
#

how

slate swan
#

!d discord.Intents.all

unkempt canyonBOT
#

classmethod all()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents "discord.Intents") with everything enabled.
sick coyote
#

well

#

how would i disable the ones i want

slate swan
#
intents = discord.Intents.all()
intents.something = False
intents.other_intent = False
sick coyote
#

oh bet

#

thanks forgot you can do that

#

if i dont got the message content intent i cant have custom prefixes right

slate swan
#

correct

sick coyote
#

damnnn

#

gotta migrate to slash cdommands

#

so annoying

glad cradle
#

they're not that bad though!

sick coyote
#

dont wanna write allat code tho

#

i need to test everything again

slate swan
#

Then move to hybrid commands

#

Probably won't need a lot of code changes besides the decorators

cloud dawn
#

We hate readability

sick coyote
#

and i wont switch to another library for sure

slate swan
sick coyote
#

btw what is wrong here?
In options.1.options.0.name: Command name is invalid


    @join.subcommand(description="Join kick")
    @commands.guild_only()
    @commands.cooldown(1, 2, BucketType.user)
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, Toggle: int = nextcord.SlashOption(choices={"on": 1, "off": 2}, required=False)):
sick coyote
#

i had that since the start ☠️

slate swan
#

im not playing i love nextcord too

sick coyote
#

really

slate swan
#

i use it in my projects too

sick coyote
#

oh nice

vale wing
#

Disnake monday

vale wing
#

Can't have spaces in slash cmds

sick coyote
#

wym

#

there arent any spaces

cloud dawn
slate swan
#

you cant have a command named super commadn unless its a sub command

slate swan
vale wing
#

You literally named your command Join kick

sick coyote
#

but its a sub command

vale wing
#

Sounds like john wick

sick coyote
#

its the description

vale wing
sick coyote
#

yes

vale wing
#

Don't name your child john wick ok

sick coyote
#

i will

cloud dawn
#

just John is fine

sick coyote
#

nah ima name him john dick

slate swan
#

there are many John's

cloud dawn
#

That's what a John would say

sick coyote
#

so

#

can anyone tell me whats wrong

slate swan
#

show how you define join

sick coyote
#

@nextcord.slash_command(guild_ids=[1103819860993118318])
@commands.guild_only()
@commands.cooldown(1, 2, BucketType.user)
@commands.has_permissions(manage_channels=True)
async def join(self, ctx):

vale wing
#
@command(name="john")
async def parent(...):
   ...

@parent.sub_comnand(name="wick")
async def josh_weam(...):
    ...
slate swan
#

.sub_comnand amegablobsweats

sick coyote
#

i just started migrating to slash commands

vale wing
sick coyote
#

its so weird

cloud dawn
#

How tough is your bot 3 years old?

vale wing
#

@slate swan you saw project details I sent you?

slate swan
vale wing
#

I am very annoying project manager

cloud dawn
#

Can confirm

slate swan
#

ill text you soon

sick coyote
#

can anyone help me now im confused

vale wing
#

Well I tried but you seemed to ignore that?

sick coyote
#

WHAT

cloud dawn
#

Same, I think I'm just gonna go to sleep. Confusion will still be there tomorrow.

sick coyote
#

im very confused now

vale wing
#

Don't include parent command name into child

sick coyote
#

where is it included

sick coyote
#

but it needs to be like this

vale wing
#

Source?

cloud dawn
sick coyote
#

i mean it says it there

vale wing
#

Well guess nextcord docs are fricked up

sick coyote
#

oh my god

vale wing
#

Nvm

#

If you look closer there's no parent command name in children

vale wing
#

We have patronymics

vale wing
# sick coyote wym

Well their parent command is main and children are called Subcommand n and yeah those are invalid names as well as they contain spaces

#

That's why it's fricked up

cloud dawn
blissful crane
#

Guys, do you know of any free hosts out there that I can use to host my bot? Idc if it's bad, anything will do

vale wing
#

@sick coyote listen just change the name of child command to kick I promise it will work

#

If it won't I will give you all my bobux

sick coyote
#

oooo

#

but its already kick

cloud dawn
vale wing
sick coyote
#

im very confused with this parent and child shit

vale wing
#

Engaging spoonfeeding

sick coyote
#

my main language is not english

sick coyote
cloud dawn
slate swan
cloud dawn
#

Basically to the top command owns the lower command

vale wing
#
@command(name="master")
async def master(...):
    ...

@master.subcommand(name="slave")
async def slave(...):
    ...

Then your command will be /master slave

cloud dawn
#
@command(name="white")
async def parent(...):
   ...

@parent.sub_comnand(name="black")
async def josh_weam(...):
    ...
#

Yeah same stuff

sick coyote
#

hm

#

alright ill try it

sick coyote
#

WHAT

#

its never gonna get called

cloud dawn
#

@vale wing have to get that first warning in 3 years.

sick coyote
#

i want to call my main command tho

vale wing
#

Report yourself

#

"racist code"

cloud dawn
#

lol sometimes I do think I near the very edge. But I do like it there.

slate swan
sick coyote
#

it still doesnt work wow

cloud dawn
vale wing
#

I once got banned for testing links regex

#

But at least it worked

slate swan
#

banned from?

cloud dawn
#

What kind of links?

#

For educational purposes

vale wing
#

Oh frick

cloud dawn
#

If there was no dollar sign I'd even fax it to him.

vale wing
#

35 BTC I can probably get myself a real bugatti

#

Bro is fricking andrew tate

slate swan
#

he said 35$ in btc

vale wing
#

Ah what a shame

#

Then to modmail he goes

slate swan
cloud dawn
#

He's not even in the server anymore.

slate swan
#

@slate swan

cloud dawn
#

Oh he is

slate swan
vale wing
#

I reported him alr

slate swan
#

hi lemon juice

cloud dawn
#

I even told him to not to offer money.

#

His price did increase 10 bucks

slate swan
#

oh i didnt even notice i got an offer too

#

gotcha

#

maybe cuz i got 7 message requests already

#

didn't read the rules

#

i shall leave peacefully, thanks guys

#

have a good one

#

πŸ‘‹

vale wing
#

Bye 😭

#

@cloud dawn bobux got 20 active users second time

slate swan
#

what you use for metrics?

sick coyote
#

i think i will give up and delete my discord bot

slate swan
#

giving up is worse than failing

sick coyote
#

im not happy with my bot

#

and i dont feel like migrating and stuff like that it takes too long

vale wing
vale wing
sick coyote
#

i thought i could make it in 2 hours

vale wing
#

The bot was quite big

sick coyote
#

how much commands does it have

vale wing
#

Not quantity but quality matters

#

It's very high sunglas

sick coyote
#

i mean yeah

#

you stil run it?

vale wing
#

Yeah

sick coyote
#

in how much servers is it

vale wing
#

Why not run it when we have such curves

sick coyote
#

oooo

vale wing
#

Currently in 268

sick coyote
#

nice

slate swan
#

just only 200 testing servers

sick coyote
#

☠️

vale wing
#

But those persons ain't my alts istg

sick coyote
#

the problem for my bot is it got custom prefix and i cant just sit down and take my time

#

without the slash commands my bot is unusable

vale wing
#

Migrating from text cmds to slash right?

sick coyote
#

exactly

vale wing
#

Yeah that's painful

sick coyote
#

very

keen trail
#

x infinite

sick coyote
#

im thinking about just completely coding a new bot for 1 specific module