#discord-bots

1 messages ¡ Page 237 of 1

vocal snow
#

nextcord supports slash commands

old ibex
#

!followup

slate swan
#

.........

slate swan
#

🙂 expecting i will not get ignored

#

can u explain sir? pls

#

to make my code organised can i make another file in the main.py folder for data storage by the use of mysql

#

ty for replying sirthis

opaque elk
#

Why doesn’t my pip install work on python windows?

opaque elk
#

Not really, I already created multiple bots but I always installed modules by doing -py -3 -m install (module)

slate swan
#

ic

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

slate swan
#

help sir?

#

not gonna ping this time

fiery hare
#

anyone know how to make purge command

slate swan
slate swan
opaque elk
slate swan
slate swan
hushed galleon
# opaque elk

the >>> prompt means you're in the python interpreter, not your regular terminal

opaque elk
#

Ohhh mb mb

hushed galleon
#

ctrl+z then enter to exit the interpreter, then run your py command

opaque elk
#

Ty guys

slate swan
#

sry for wasting ur time sir

slate swan
opaque elk
#

Im also wondering how I can separate my stuff between multiple files

#

I never really done that before. I got a like 500 lines code

opaque elk
slate swan
opaque elk
#

Alright imma check that out ty

slate swan
#

what you want to separate

#

database logic?

#

like there is the main code for strt command but when i want to make my data storage code in vs code in a diffrent file

#

what do you mean by data storage

#

show code or example maybe i will understand

fiery hare
#

what should i put in 'config'

twilit grotto
slate swan
slate swan
#

leave ty for ur time sir

fiery hare
twilit grotto
#

i assume you're trying to create malware so im not even gonna bother to help u

hushed galleon
slate swan
# fiery hare

what is the point of creating the config file to not show your token in the code and still put it as default value

unkempt canyonBOT
#
Using .env files in Python

.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.

Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.

In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:

TOKEN=a00418c85bff087b49f23923efe40aa5

Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:

from dotenv import load_dotenv()

load_dotenv(".env")

The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:

from os import getenv

my_token = getenv("TOKEN")

For further reading about tokens and secrets, please read this explanation.

twilit grotto
#

whats the detection on the antivirus

slate swan
twilit grotto
#

what are you compiling your python file into an exe with, pyarmor?

slate swan
#

Mind explaining how that is related to the channel's topic what

twilit grotto
#

^

#

bad channel to ask ur question in tbf

slate swan
#

By asking in the correct channel first

old ibex
#

Command 'clear' raised an exception: InteractionResponded: This interaction has already been responded to before

    @app_commands.command()
    async def clear(self, interaction: discord.Interaction, amount: int) -> None:
        await interaction.response.defer(thinking=True) 
        cleared = await interaction.channel.purge(limit=amount, bulk=True)
        clearembed=discord.Embed(
            title="",
            description=f"Successfully cleared {cleared} message(s).",
            color=0x313338
        )
        await interaction.response.send_message(embed=clearembed)```
#

hmmmmm

slate swan
#

interaction.followup.send

#

You don't use interaction.response.send_message after deferring a message

old ibex
#

Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message

#

hmmmm

slate swan
#

God these 'hmmmm' are so superfluous

old ibex
#

mhmm

slate swan
#

@slate swan

#

wht is help cooldow btw

earnest swift
#

Is there a way i can do my own commands like instead of greet i can do greet {user}or something

opaque elk
polar scroll
#

can someone help?

slate swan
#

slash_command

#

There's no "s"

polar scroll
#

oh ok, thanks

polar scroll
#

why is it giving me interaction error ._.

slate swan
#

send_message not send

polar scroll
#

which one is better? disnake nextcord or discord.py?

earnest swift
opaque elk
#

Same

earnest swift
#

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

you might find more help with discord.py here, but online guides are lacking for dpy's newer features afaik, particularly app_commands

opaque elk
earnest swift
#

How do i make the bot send sever emojis like this rival_check in a discord embed?

polar scroll
earnest swift
sick birch
#

yup

polar scroll
hushed galleon
# polar scroll i undestand, but i cant seem to replicate this, with discord.py, as it looks WAY...

equivalent: ```py
bot = commands.Bot(command_prefix="whyisthisstillneeded", intents=...)

@bot.tree.command(name="hello", description="This is a hello command")
async def test(interaction: discord.Interaction):
"""This is a hello command"""
# ^ A docstring can be used instead of description=
await interaction.response.send_message("Sup")

@bot.event
async def setup_hook():
# Sync global commands on startup
await bot.tree.sync()```

polar scroll
#

c_SeriousCat that is such a big line of code for no reason

slate swan
#

Not really "for no reason"

hushed galleon
#

well did you want me to give 0 context instead? for the goal of defining a slash command within the same file as your bot definition, it looks almost identical to disnake py @bot.slash_command(name="hello", description="This is a hello command") async def test(interaction: disnake.ApplicationCommandInteraction): await interaction.response.send_message("Sup") py @bot.tree.command(name="hello", description="This is a hello command") async def test(interaction: discord.Interaction): await interaction.response.send_message("Sup")

#

although disnake has interaction.send() which simplifies followup messages, so its got that going for it

polar scroll
#

and if green line is equal to red line, whats the point of that

slate swan
#

It's called proper documentation

polar scroll
#

so i can use description and it will be ok?

slate swan
#

Try it and see

polar scroll
#

its giving me this error

hushed galleon
#

docstrings are a standard way of documenting functions so i would recommend using it

#

plus, dpy can parse google/sphinx-style parameter descriptions from the docstring too

polar scroll
#

why do we need to use command_prefix if its outdated

hushed galleon
#

dunno, if you really want to disable it then use an on_message event that doesnt call process_commands()

honest shoal
#

that's bad

hushed galleon
#

personally i use slash and prefix commands but with commands.when_mentioned() to allow @mentioning the bot, it'll still work regardless of message content

polar scroll
#

i see, but if in case i wanna do it like you, commands.when_mentioned() how wold that work?

slate swan
#

command_prefix=commands.when_mentioned()

hushed galleon
#

command_prefix=commands.when_mentioned, without the parentheses

hushed galleon
#

ya i forgot you didnt need them

#

!d discord.ext.commands.when_mentioned

unkempt canyonBOT
#

discord.ext.commands.when_mentioned(bot, msg, /)```
A callable that implements a command prefix equivalent to being mentioned.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

>   Changed in version 2.0: `bot` and `msg` parameters are now positional-only.
> 
>
hushed galleon
#

nice formatting

slate swan
#

oh this is taken as the callback you can create on your own

polar scroll
slate swan
fiery hare
#

guys help
PS C:\Users\Sakura\Discord Bot> & C:/Users/Sakura/AppData/Local/Microsoft/WindowsApps/python3.10.exe "c:/Users/Sakura/Discord Bot/bot.py"
Traceback (most recent call last):
File "c:\Users\Sakura\Discord Bot\bot.py", line 43, in <module>
os.chdir(r'C:\Users\Sakura\Discord Bot\bot.py')
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\Sakura\Discord Bot\bot.py'

glad cradle
#

the space

hushed galleon
#

naw the filename

polar scroll
slate swan
#

file is not a directory

fiery hare
#

thxz for explaining

hushed galleon
polar scroll
hushed galleon
#

@lament depot how you doing

polar scroll
hushed galleon
#

also a good idea to have an error handler for catching commands.CommandNotFound, usually to do nothing but lancelot tried autocompleting the command

polar scroll
hushed galleon
#

technically you can define standalone commands in separate files and manually add them to your bot, but cogs will still be more convenient to write

opaque elk
hushed galleon
# hushed galleon technically you can define standalone commands in separate files and manually ad...

here's a pretty minimal example:
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html
https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html ```py

main.py

bot = commands.Bot(...)

@bot.event
async def setup_hook(): # called exactly once after your bot logs in
await bot.load_extension("path.to.my_extension") py

path/to/my_extension.py

from discord import app_commands

class MyCog(commands.Cog):
@app_commands.command()
async def my_command(self, interaction: discord.Interaction):
await ctx.send("Hello world!")

the setup() here gets called when load_extension() is used

async def setup(bot):
await bot.add_cog(MyCog())``` see also online guides to object-oriented programming so you can make the most out of classes
https://www.youtube.com/playlist?list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc
https://realpython.com/python3-object-oriented-programming/

hushed galleon
opaque elk
hushed galleon
#

can you try printing the message content when your on_message event receives it?

opaque elk
opaque elk
#

I tried with 3 different print messages

hushed galleon
#

and your bot shows up as online right after you run your script?

#

or rather idle in your case

opaque elk
#

Yep and both "Bot is ready" and "Bot is online" print shows up

#

Im not really familiar with using extensions like sqlite 3 but maybe I can show you the database inside when I try sending a message and you tell me what’s wrong

hushed galleon
#

if you put a print right on top of on_message but it didnt run, aiosqlite probably isnt your issue

opaque elk
#

I see

hushed galleon
#

unless aiosqlite is somehow blocking your event loop, but you can check that by terminating it early with ctrl+c and looking for a traceback

opaque elk
#

Yes ok I see, when I send an introduction message, which is on_message i little bit further into my code, it doesn’t work either now

#

It used to work but it doesn’t anymore

#

Do you want to see my integrate code?

opaque elk
opaque elk
#

That might be because I have 2 times the on_message event in my script?

hushed galleon
#

oh thats definitely the cause

opaque elk
#

So I should put the introduction on message in my other event

hushed galleon
#

only the last on_message applies if you're using the @bot.event decorator

#

combine them together or use @bot.listen("on_message") instead

hushed galleon
#

though tbf chatgpt said "it seems" that way so its not overconfident about that answer

opaque elk
#

Na still even with the bot.listen doesn’t work

#

Let me send my full code

hushed galleon
#

@bot.listen is not how that decorator's meant to be used, and you also dont need to use process_commands() if all your on_message handlers are listeners

#

for example: ```py
@bot.listen("on_message")
async def on_message_experience(message):
async with bot.db.cursor() as c:
...

@bot.listen("on_message")
async def on_message_introduction_thread(message):
...```

opaque elk
slate swan
#

you're missing the braces, also the argument there should be a message not ctx for the sake of naming

opaque elk
#

Oh woops ty

polar scroll
#

how can i do a /ping and the the answer in ms

slate swan
#

!d discord.Client.latency

unkempt canyonBOT
#

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

This could be referred to as the Discord WebSocket protocol latency.
slate swan
#

multiply it with 1000 to get in ms

unkempt canyonBOT
#
Bot variables

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

thin raft
#

guys how could I make so the bot var gets type hinted on cogs?

hushed galleon
#

use a bot subclass and define them as instance attributes, then typehint with your bot subclass

glad cradle
thin raft
#

hmm

hushed galleon
#

although it will be a bit inconvenient with Context/Interaction since their bot/client attribute assumes a regular bot/client

thin raft
#

i mean

#

if I type self.bot.config

#

it auto detects that is from the Config class

hushed galleon
#

ya thats one workaround

thin raft
#

it does the job I wanted

#

ill leave it like that

hushed galleon
#

at least with Context you could set the generic typevar yourself, or make a subclass that fills in the generic typevar: py class Context(commands.Context[MyBot]): ... but with dpy's app_commands.command() decorator your type checker would complain if you tried writing discord.Interaction[MyBot]

white citrus
#

Hey @hushed galleon can i ask you something about mysql
I know this stuff must be placed in #databases but you give the best answers

hushed galleon
#

why me

#

plus it sounds more appropriate for #databases, just ask whatever question you have there

polar scroll
#

can someone help?

#

im trying to get the bots latency, but i cant seem to get it to work

slate swan
#

bot.latency

#

Just like magic

polar scroll
#

how exactly should i use it?

slate swan
#

bot.latency, like that

polar scroll
slate swan
#

Multiply by 1000 and you get the ms, then round that

polar scroll
#

if im not mistaken is it something like {:2f}

slate swan
#

You end up with

round(bot.latency*1000)
polar scroll
#

but it didnt work

slate swan
#

I also have something not working on my screen, maybe you can help me without knowing the error :)

#

hey can someone help me out. I'm a beginner in python. I have learnt the basic stuffs. I was tryna create a discord which can stream music in order to learn about the discord.py module. But it wont run for some reason. Please help me out.

slate swan
#

My point is, give the error

polar scroll
slate swan
#

the error its showing is it doesnt have the command "play"

slate swan
unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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

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

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

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

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

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

TL;DR you're breaching YouTube's Terms of Services and won't be getting help for doing it

slate swan
slate swan
#

Use f-strings or convert your integer to a string

#

!e "hi" + 5

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     "hi" + 5
004 |     ~~~~~^~~
005 | TypeError: can only concatenate str (not "int") to str
slate swan
#

!f-strings

unkempt canyonBOT
#
Format-strings

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

polar scroll
#

Great, i forgot. Thanks

polar scroll
smoky sinew
unkempt canyonBOT
#

@hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
polar scroll
#

wat

slate swan
#

Max app commands are 100 or 50? Can't find on the docs

opaque elk
slate swan
#

"Member "enable" not found."

opaque elk
wicked atlas
# slate swan Max app commands are 100 or 50? Can't find on the docs

An app can have the following number of commands:

100 global CHAT_INPUT commands
5 global USER commands
5 global MESSAGE commands

https://discord.com/developers/docs/interactions/application-commands#registering-a-command

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

slate swan
#

I mean it basically told you whats wrong

opaque elk
#

Its my first time dealing with this error

wicked atlas
#

s running the lvl command. You have a seperate handler for lvl enable, but the way you made it, the bot thinks you're trying to run the lvl command and passing in 'enable' as an argument for the member

opaque elk
wicked atlas
#

I'd suggest taking a look at command groups

#

I don't remember where the docs for them are though 💀

opaque elk
#

Will do, its my first time dealing with them ngl

opaque elk
#

Oh ty!

gusty flax
polar scroll
#

are there any good new hosting sites?

gusty flax
slate swan
#

TypeError: CommandTree.command() missing 1 required positional argument: 'self'

I'm trying to use

    @app_commands.tree.CommandTree.command()
    @app_commands.describe()

inside a class ClassName(commands.Cog)
I pass self, in the initializer and super initializer, but i still get the error? 🤷‍♀️

fading marlin
#

use @app_commands.command() instead of the tree thingy you've got going

slate swan
#

ty!

#

then would it still be

async def function(self, bot)
    self.tree = app_commands.CommandTree(self)
    await self.tree.sync()
gusty flax
#

Write your own syncing command, so you don't have to rely on any of that.

#

I can send you one.

#

Whereas for the command, it shld be: py @app_commands.command(name="play", decsription="A command that plays games") async def play(interaction: discord.Interaction) -> None: ...

smoky sinew
slate swan
#

but they need to be synced to be registered. no?

smoky sinew
#

yes but you're syncing in the command

#

just use jishaku's sync

#
@commands.is_owner()
@commands.command()
async def sync(self, ctx: commands.Context) -> None:
    await self.bot.tree.sync()
    await ctx.send("Synced the command tree.")

or write something like this

slate swan
#

ohhhh and sync via command

#

ok ty

gusty flax
#

Having control over global and local syncing.

opaque elk
#

I have a question about something. The command I set earlier in my group was =lvl enable and =lvl disable. I just changed them to =enable and =disable and it says Command "enable" is bot found.

#

And the old one gives me an error code

#

Even after restarting my file and creating a new db

opaque elk
slate swan
#

AttributeError: 'TestSlashCommands' object has no attribute 'http' I'm not passing http? or is it because my bot's being passed as discord.ext.commands.bot.Bot?

gusty flax
gusty flax
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.

opaque elk
#

Command used to be =lvl enable and =lvl disable

#

I changed it to =enable and =disable

gusty flax
#

If you are getting aerror, there should be a traceback.

gusty flax
opaque elk
#

Prefix

sick birch
#

Prefix probably

gusty flax
#

Oh

opaque elk
#

The new command doesn’t work

#

Its not recognized

#

The old ones are tho,

gusty flax
#

No traceback, no nothing?

opaque elk
#

But I changed them

opaque elk
#

Mb

#

No traceback only error

gusty flax
#

If you just want =enable, why do you have slvl.comamand()?

opaque elk
slate swan
slate swan
gusty flax
#

You could just do @bot.command().

opaque elk
#

Lemme test

#

So no group, no nothing?

gusty flax
#

Yup.

#

If you just want =enable, don't provide a group.

#

A group is for grouping commands.

opaque elk
#

I want =disable too

gusty flax
#

Then do @bot.command() for that as well.

opaque elk
#

Alright lemme test

#

Ok someone help me, Idk but that’s not supposed to happen

gusty flax
#

Well, now it's being triggered.

#

Seems like levelsys[0] isn't None.

#

Is ur db reset?

opaque elk
#

Ye

gusty flax
opaque elk
#

Lemme try to reset again

gusty flax
#

R u using smth like db browser.

#

Wait, print what is returend @opaque elk

#

Print the type, and whatever value.

opaque elk
gusty flax
#

print(type(levelsys[0]))

opaque elk
gusty flax
opaque elk
#

aiosqlite ye

gusty flax
#

I would download db browser.

#

You can visually see if there is anything in ur db.

slate swan
#

or the dbviewer in vscode

opaque elk
#

I can see it with an extention

gusty flax
opaque elk
#

I see the xp stuff

#

But I dont see where enable/disable is located

#

Ok wait

#

There’s also this

#

Im pretty sure we need the second one

slate swan
#

it shows 0 instead of true/false? o.O

mighty pilot
#

Anybody in here familiar with payment methods for premium discord bots? Wondering if any particular one is better than others

opaque elk
sick birch
mighty pilot
#

Thought that was just premium discord servers?? I missed that update I guess

gusty flax
sick birch
#

I dunno. I like the way the button looks.

gusty flax
#

IIRC it is very restricted.

mighty pilot
#

It looks to be available to verified bots only

gusty flax
mighty pilot
#

I'm aware lol

#

Guess I'll compare and contrast the bigger name api like patreon and PayPal for my stuff

opaque elk
#

Ig patreon and ko-fi are good options for you

sick birch
opaque elk
#

Yes but you cant use paypal

mighty pilot
#

Someone mentioned that when I asked in general chat. Gonna look into stripe as well

opaque elk
slate swan
#

What's the best way to make a giveaway command? (with buttons)

mighty pilot
slate swan
gusty flax
opaque elk
#

This? print(type(levelsys[0]))

mighty pilot
gusty flax
slate swan
gusty flax
mighty pilot
opaque elk
gusty flax
opaque elk
#

No no I know that

#

Do I put it right before cursor.fetchone() ?

#

Or its the wrong positionnement

gusty flax
opaque elk
#

Alright

#

On both commands?

gusty flax
opaque elk
#

ok so by doing enable, I got <class 'int'> printed

slate swan
# slate swan `AttributeError: 'TestSlashCommands' object has no attribute 'http'` I'm not pas...

so... which of these, or whatever solution, would fix this?

class MyBot(commands.AutoShardedBot):
    def __init__(
        self,
        *args,
        initial_extensions: List[str],
        db_pool: asyncpg.Pool,
        web_client: ClientSession,
        testing_guild_id: Optional[int] = None,
        **kwargs,
    ):
        super().__init__(*args, **kwargs)
        self.db_pool = db_pool
        self.web_client = web_client
        self.testing_guild_id = testing_guild_id
        self.initial_extensions = initial_extensions

class MyBot(Client):
    def __init__(self, *args, **kwargs):
        intents = discord.Intents.all()
        super().__init__(command_prefix="!", intents=intents, *args, **kwargs)

class MyBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        intents = discord.Intents.all()
        self.bot = commands.Bot(command_prefix="!", intents=intents)
        super().__init__(command_prefix="!", intents=intents, *args, **kwargs)
opaque elk
smoky sinew
#

but Client should be commands.Bot

#

and you don't need *args and **kwargs

opaque elk
#

Hey mud you got like 5-10 mins for me after?

smoky sinew
#
class MyBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(
            intents=discord.Intents.all(),
            command_prefix="!",
            ...
        )

@slate swan

#

then you can do your database stuff as an argument in MyBot.init

opaque elk
smoky sinew
#

make a helper function instead

#
async def _is_leveling_system_enabled(self) -> bool:
slate swan
smoky sinew
slate swan
# smoky sinew what does your main.py look like

    #@commands.is_owner() 
    @commands.has_any_role(settings.OWNER_ROLE, settings.ADMIN_ROLE, settings.MODERATOR_ROLE)
    @commands.command(name="load", aliases=["l"], hidden=True,)
    async def load(self, ctx, *, module):
        """Loads a module."""
        try:
            self.bot.load_extension(module)
            await ctx.send(f"Loaded {module}.")
        except Exception as e:
            await ctx.send(f"Failed to load {module}:\n{e}")


    async def load_modules(self):
        for root, dirs, files in os.walk("cog_extensions"):
            root = os.path.normpath(root)
            for file in files:
                if file.endswith('Cog.py') and file != '__init__.py':
                    module_name = file[:-3]
                    module_path = f"cog_extensions.{os.path.relpath(root, 'cog_extensions').replace(os.sep, '.')}.{module_name}"
                    try:
                        await  self.load_extension(module_path)
                        print(f"\n[{module_name}]( now loaded.)")
                    except Exception as e:
                        print(f"\n[{module_name}]( failed to load: {e}")
                    await asyncio.sleep(0.1)

i have these. commands for the cogs and then a for loop to autoload each.

smoky sinew
#

what

#

load_extension needs to be awaited but where are you using load_modules

gusty flax
slate swan
smoky sinew
#

load them in setup_hook instead

slate swan
#

then run it in the main()?

#

but again, don't i need to pass in self.bot in the init?

smoky sinew
#

what

#

pass bot to the init of bot? yert

slate swan
#

wouldn't this error? await self.bot.load_extension(module)

#

if it's not passed?

#

yeah cause it gives me AttributeError: 'MyBot' object has no attribute 'bot'

smoky sinew
#

mybot is extending bot though

#

so you would just use self.load_extension

slate swan
smoky sinew
#

you're doing change_presence before your bot has started

#

pass activity and status to super().__init__ instead

slate swan
#

won't they need to be awaited? i put them in the hook?

smoky sinew
#

what hook

#

no you put it it init

slate swan
#

ohhh its not asyncronous

#

im dumb 🤣

smoky sinew
#

no.. that's not what i said

slate swan
smoky sinew
#

coroutine means it's asynchronous

#

but you don't need to use change_presence

slate swan
#

so... to use it.. How would that go in the init? cause the init is syncronous. I'd have to await it right?

smoky sinew
#

no you don't use change_presence

#

creating an instance of a class is not asynchronous

#

and that's all you need to do

#
super().__init__(
    ...,
    activity=discord.Game("..."),
    status=discord.Status.dnd,
)
slate swan
#

like i made a function for the change presence and put that in the on_ready originally.


    async def set_profile(self):
        activity = (discord.Streaming(
        ...
        )
        )
        await self.change_presence(activity=activity)

ohhh.. ok.
so define it prior

activity = (discord.Streaming(
...
)
)  
super().__init__(
    ...,
    activity=activity,
)
#

then passing into the super would just initialize it when the bot starts.

#

ok. awesome. that solves that... now i just need to go back to figuring out why my cog for slash commands errors 'TestSlashCommands' object has no attribute 'http'

smoky sinew
#

you don't need to

#

just define discord.Streaming inline

#

and you don't need the extra paranthesis around it

gilded oxide
#
    state = self._connection
    if state._activity is not None or state._status is not None:
        payload["d"]["presence"] = {
            "status": state._dnd,
            "game": state._activity,
            "since": 0,
            "afk": False,
        }``` am i doing something wrong w/ the status?
smoky sinew
#

why are you accessing _connection yert

gilded oxide
gilded oxide
# smoky sinew what
import json  # For json
from pathlib import Path  # For paths
import discord  # For discord
from discord.gateway import DiscordWebSocket # For Discord Mobile
from utils.data import Bot # This loads the cogs
import logging # Shows important information of something goes wrong in the connection

cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f'-----')

async def identify(self):
    payload = {
        "op": self.IDENTIFY,
        "d": {
            "token": self.token,
            "properties": {
                "$os": "Discord iOS",
                "$browser": "Discord iOS",
                "$device": "iOS",
                "$referrer": "",
                "$referring_domain": "",
            },
            "compress": True,
            "large_threshold": 250,
        },
    }

    if self.shard_id is not None and self.shard_count is not None:
        payload["d"]["shard"] = [self.shard_id, self.shard_count]

    state = self._connection
    if state._activity is not None or state._status is not None:
        payload["d"]["presence"] = {
        "status": state._dnd,
        "game": state._activity,
        "since": 0,
        "afk": False,
        }

    if state._intents is not None:
        payload["d"]["intents"] = state._intents.value

    await self.call_hooks(
        "before_identify", self.shard_id, initial=self._initial_identify
    )
    await self.send_as_json(payload)


DiscordWebSocket.identify = identify

bot = Bot(
    intents=discord.Intents.all(),
    command_prefix=',',
    case_insensitive=True,
    owner_id=924820612545916948
)

logging.basicConfig(level=logging.INFO)
config_file = json.load(open(cwd + '/config/config.json'))
bot.config_token = config_file['token']

@bot.event
async def on_ready():
    print(f"-----\nlogged in as: {bot.user} : {bot.user.id}\n-----")

@bot.listen()
async def on_message(msg):
  if "@crisp sail" in msg.content:
    await msg.channel.send('my prefix is `,`')


bot.run(bot.config_token, reconnect=True)```
old ibex
#

    @app_commands.describe(
            amount="The amount of messages to clear."
    )
    @app_commands.checks.has_permissions(manage_messages=True)
    @app_commands.command()
    async def clear(self, interaction: discord.Interaction, amount: int) -> None:
        await interaction.response.defer(thinking=True) 
        cleared = await interaction.channel.purge(limit=amount, bulk=True)
        clearembed=discord.Embed(
            title="",
            description=f"Successfully cleared {cleared} message(s).",
            color=0x313338
        )
        await interaction.response.send_message(embed=clearembed)```
#

How I make worky

vocal snow
#

it already works

smoky sinew
#

what is the issue with my code

smoky sinew
unkempt canyonBOT
glad cradle
smoky sinew
vocal snow
smoky sinew
vocal snow
#

oh yes 100%

eternal shuttle
#

so this is my ban command, and i cant use it somehow

#

here's the traceback that i got

2023-05-08 14:04:29 ERROR discord.ext.commands.bot Ignoring exception in command ban
Traceback (most recent call last):
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\user123\Desktop\Akairo Project\bot.py", line 39, in ban
await member.ban(reason=reason)
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 736, in ban
await self.guild.ban(
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 3467, in ban
await self._state.http.ban(user.id, self.id, delete_message_seconds, reason=reason)
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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

Traceback (most recent call last):
File "C:\Users\User123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\User123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\User123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

smoky sinew
#

also make sure this is true before banning the user:

if (
    ctx.author.top_role > member.top_role
    and ctx.guild.me.top_role > member.top_role
):
eternal shuttle
#

alrighty thankss

rugged shadow
gilded cedar
#

Do we really have to use bot instead of client and commands when using dotenv?

gilded cedar
#

When i try to do it the code needed str i went on several tutorials but nothing what am i doing wrong?

slate swan
#

dotenv just loads your token in a file

formal basin
#

how can a bot detect pictures

#

or images

slate swan
#

message.attachments

distant hare
#

Пон

blissful notch
#

This is a soft ban right?

slate swan
#

This means the token you gave is of type None

#

Whereas it should be a string

eternal shuttle
#

why does all of my kick, ban, and unban command doesn't work?

#

here's my code

slate swan
#

my code is returning an error "discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions"

#

This is the code

#

Error says it all

#

Missing Permissions

#

how do u turn on permission

#

i have turned on almost everything in server

#

Thank you sm bro i was sending the command in the wrong channel i just noticed it.

slate swan
tawdry marsh
#

Hello bot tamers, is there any way to extract the user's timezone from the interaction? I've seen something about locale but it's no use. I need this for a event scheduler and I currently do time management relative to the server's timezone by specifying to the user the timezone needed. I would like to have access to the user's timezone, so the setup is relative their time.

formal basin
formal basin
naive briar
#

Yes?

formal basin
#

Would this work?

#

Nope

#

I got this error

slate swan
#

!d discord.Message.attachments

unkempt canyonBOT
eternal shuttle
#

why does all of my kick, ban, and unban command doesn't work?

#

here's my code

#

so this is my ban command, and i cant use it somehow
Image
here's the traceback that i got

2023-05-08 14:04:29 ERROR discord.ext.commands.bot Ignoring exception in command ban
Traceback (most recent call last):
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(args, **kwargs)
File "C:\Users\user123\Desktop\Akairo Project\bot.py", line 39, in ban
await member.ban(reason=reason)
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 736, in ban
await self.guild.ban(
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 3467, in ban
await self._state.http.ban(user.id, self.id, delete_message_seconds, reason=reason)
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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

Traceback (most recent call last):
File "C:\Users\User123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\User123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\User123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

slate swan
#

it litrally tells you Missing Permissions

eternal shuttle
#

how do u fix it

slate swan
eternal shuttle
#

i gave the bot all the ban and kick permission

formal basin
eternal shuttle
#

i tried giving it the administrator perm but still it doesn't work

eternal shuttle
#

its role is already on top of all roles

tawdry marsh
#

Default can't ban or kick if I remember correctly

formal basin
eternal shuttle
slate swan
unkempt canyonBOT
#

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

Removes attachments from the message.

New in version 2.0.
slate swan
#

You give the attachments to delete

#
await message.remove_attachments(...)
#

Where ... are the attachments to delete

formal basin
#

but don’t it need to detect attachments first

slate swan
#

Then do it.

formal basin
#

how?

#

it need to detect it first then delete it?

slate swan
#

Think

#

Most of the time coding is about thinking about not being given the answer to every question and getting spoonfed

#

Try things, fail, try again

formal basin
#

ok

eternal shuttle
#

how do you make a !warn command?

formal basin
#

well you need a database

elder kettle
#

no

formal basin
#

for warning yeah\

elder kettle
#

warn command aint need a db

formal basin
#

how does it store warns

elder kettle
vocal snow
#

If you're planning on storing the warns, then yes

elder kettle
#

yea for storing you need

#

db

eternal shuttle
#

oh welp

tawdry marsh
# eternal shuttle alr imma check it rq

I don't recommend using discord.Intents.all() as it can throw errors sometimes, start with default() and build upon it as necessary. In your case, if I understood your bot's scope correctly, you might want to start with this:

intents.bans= True
intents.moderation= True```
vocal snow
#

intents are not permissions

elder kettle
#

i prefer .all()

#

to not get error

slate swan
#

Intents are not about errors

elder kettle
#

ik

slate swan
#

You won't face errors as you won't get the event you need

#

That's about it

elder kettle
#

oh

slate swan
#

And using .all() is most of the time absolutely useless and will consume more resources for nothing

#

Haven't seen any bot that requires all intents to be abled at all

slate swan
unkempt canyonBOT
#

discord/flags.py lines 727 to 736

@classmethod
def default(cls: Type[Intents]) -> Intents:
    """A factory method that creates a :class:`​Intents`​ with everything enabled
    except :attr:`​presences`​, :attr:`​members`​, and :attr:`​message_content`​.
    """
    self = cls.all()
    self.presences = False
    self.members = False
    self.message_content = False
    return self```
slate swan
#

for fetching messages and guild data for role reacts, what function would I need to use in a slash command?

vivid axle
#

i have this for my code

@commands.hybrid_group(with_app_command=True)
async def test(self, ctx: commands.Context):
  await ctx.reply('test group')

@test.command(with_app_command=True)
async def hello(self, ctx: commands.Context):
  await ctx.reply('test hello command')
``` i use await self.tree.sync() in the setup hook but /test doesnt show only /test hello
slate swan
#

That's how slash commands work

vivid axle
#

how do i get the test command then

slate swan
#

You don't

#

Discord doesn't let you do that, deal with it

vivid axle
#

no need to be rude

slate swan
#

I just told you that it's how slash commands work before

#

Can't do magic and say that now it's no longer how they work kek

hushed galleon
vivid axle
#

ok

viscid wren
#

Why my bot are not registering commands in a cog?

vocal snow
#

perhaps you aren't adding the cogs

viscid wren
#

yes i do

vocal snow
#

show how

#

you're loading the cogs after you sync the tree

viscid wren
#

🤦‍♂️

#

thanks

slate swan
#

helppppp

vocal snow
slate swan
#

;-;

vocal snow
#

jesus christ man

#

consider learning a language inside of just copy pasting from the internet

#

it will be much faster and much more worthwhile

glad cradle
#

lmaoooo

cold sonnet
#

this a different level already

glad cradle
#

as of today it's negative

vocal snow
#

lmao

#

steeper than a cow's face

glad cradle
#

nice simile

north kiln
#

I am trying to set autocomplete to show first few items from a list if the user didn't input anything and using this code

if len(current) == 0:
   return [Choice(name=l, value=l) for l in name_list][::3]

but it always show 10 choices for some reason

vocal snow
#

how many names are in name_list?

north kiln
#

like a hundred

vocal snow
#

why not slice name_list instead of making a new list and then slicing that?

vocal snow
north kiln
#

oh I am stupid

#

🙃

#

got one more :

formal basin
#

how do i detect the messages

tepid siren
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix = '/', intents=intents)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.command()
async def test(ctx):
    await ctx.send('test')

client.run('')```
hi could someone please explain to me why when i type /test the discord autocompleting thingy doesnt appear?
slate swan
#

cause those what you are talking about are slash commands not prefixed commands

tepid siren
#

oh

#

how can i make it a slash command?

slate swan
#

example how to create slash command

tepid siren
#

ty

slate swan
#

im getting this error when im trying to sync my slash commands.?
AttributeError: 'TestSlashCommands' object has no attribute 'client'
await self.bot.tree.sync()

#

this is in a cog btw^

#

did you set self.bot to bot? in __init__?

#

yup.

class TestSlashCommands(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot
        super().__init__()
slate swan
#

class TestSlashCommands(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot
        super().__init__()
    
    @app_commands.command(name='test', description='Test command')
    @app_commands.describe(arg1='Test')
    async def test(self, interaction: discord.Interaction, arg1: Optional[str]) -> None:
        await self.bot.tree.sync()
        if arg1 is not None:
            await interaction.response.send_message(f'Test command with arg1 {arg1}')
        else:
            await interaction.response.send_message('Test command')
    @commands.command(name='sync', description='Sync the commands')
    async def sync(self, ctx: commands.Context) -> None:
        await self.bot.tree.sync()
        await ctx.send(f'{self.bot.latency}Synced!')

tried it in the slash command and in a normal command. i get the same error. :/

#

can you show full traceback?

#
AttributeError: 'TestSlashCommands' object has no attribute 'client'
ERROR      - discord.app_commands.tree : Ignoring exception in command 'test'
Traceback (most recent call last):
  File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\commands.py", line 841, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "E:\!python\Kirakota\cog_extensions\commands\slashcommandCog.py", line 184, in test
    await interaction.response.send_message('Test command')
  File "E:\!python\Kirakota\.venv\lib\site-packages\discord\interactions.py", line 778, in send_message
#

doesnt look like full error traceback tho

#

try removing the super().__init__()

#
ERROR      - discord.ext.commands.bot : Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "sync" is not found
ERROR      - discord.app_commands.tree : Ignoring exception in command 'test'
Traceback (most recent call last):
  File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\commands.py", line 841, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "E:\!python\Kirakota\cog_extensions\commands\slashcommandCog.py", line 179, in test
    await interaction.response.send_message('Test command')
  File "E:\!python\Kirakota\.venv\lib\site-packages\discord\interactions.py", line 778, in send_message
    await adapter.create_interaction_response(
  File "E:\!python\Kirakota\.venv\lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

this the error you were looking for @slate swan

slate swan
#

do you load the cog?

#

it autoloads

#

i've reloaded the bot several times, i went through and got the slash command to work yesterday, but no luck getting the sync tree to.

buoyant quartz
#

Im trying to count all my commands but print(len(bot.commands)) only counts the commands that dont use / (im using nextcord)

naive briar
#

What do you mean by commands that dont use

buoyant quartz
#

it only counts commands that arent slash commands

slate swan
naive briar
#

That should be correct

buoyant quartz
#

it counts @bot.command() but not @bot.slash_command()

glad cradle
#

!d nextcord.ext.commands.Bot.get_all_application_commands

unkempt canyonBOT
slate swan
buoyant quartz
#

print(len(bot.get_application_commands()))

slate swan
#

get_**all_**application_commands()

buoyant quartz
slate swan
slate swan
#

I want to increase this timeout is there any way to do that?

#

in discord py v2

slate swan
vocal snow
slate swan
slate swan
vocal snow
#

you know you have to send heartbeats to the gateway to keep the connection alive

#

how are you going to do that?

sick birch
#

if your internet takes any longer than 45 seconds-ish to send a packet you unfortunately will not be able to use the discord API

spiral spoke
#

hey.. i need help

i want to create an event when a member join to the server but don't work

@client.event
async def on_member_join(member, ctx):
    channel = client.get_channel(1105137318253301770)  # welcome channel id
    message = f'Welcome to the Tree House, {member.mention}!'
    unverified_role = ctx.member.guild.get_role(
        1105137365095288884)  # unverified role id
    await member.add_roles(unverified_role)
    await channel.send(message)

#

message not send and role not applied

vocal snow
spiral spoke
#

yeah and this in my code

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

vocal snow
#

you haven't enabled member intents

spiral spoke
#

thanks

analog condor
#

i want a bot to run a function that returns a variable constantly, and then send the variable in a channel if its not empty, but i cant get it to work

#

does anyone know how to do this?

glad cradle
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

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

trying to use the discord api to retrieve all the reactions from a specific message but im not sure how so im trying to do it with a bot. and i get this error

2023-05-08 20:29:21 WARNING discord.state Member list scraping failed for 1085055846301573152 (Failed to automatically choose channels; please specify them manually).

heres my code py message = bot.get_channel(channel_id).fetch_message(message_id) for reaction in message.reactions: print(reaction)

naive briar
#

Sounds more like selfbot things

slate swan
#

im not trying to scrape a member list lmao

#

thats why im confused

#

just tryna recieve a list of reactions

naive briar
#

Discord would already provide that data

#

What library are you using

slate swan
naive briar
#

You sure?

slate swan
#

100% lol

plucky sun
#
@app_commands.describe(message="Type your text here to send the announcement !")
@commands.has_permissions(manage_messages=True)
async def say(interaction: discord.Interaction, message: str, tag: str):
    await interaction.message.delete()
    await interaction.send(f'{tag}')
    embed = discord.Embed(
        title='Ново Съобщение • MetaverceCraft',
        colour= discord.Colour.dark_purple()
    )
    image_path = os.path.abspath("static.png")
    embed.set_thumbnail(url=f"attachment://{os.path.basename(image_path)}")
    embed.add_field(name=f' **{message}** ', value='')
    embed.set_footer(text=f'{datetime.datetime.now()}')
    await interaction.send(embed=embed, file=discord.File(image_path))``` how to make slash commands
vivid axle
#

how can i add a view with two buttons to send?

vivid axle
#

thanks Hearts

tall temple
#

how to add slash command cooldown and ctx.respond for this cooldown

#

like i set 60s cooldown for command and i used it 2 times in 30s, i want to receive an error

slate swan
#

Define error handler and handle CommandOnTimeout exception or smth like that

#

!d discord.app_commands.CommandOnCooldown

unkempt canyonBOT
#

exception discord.app_commands.CommandOnCooldown(cooldown, retry_after)```
An exception raised when the command being invoked is on cooldown.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").

New in version 2.0.
slate swan
#

!d discord.app_commands.checks.cooldown

unkempt canyonBOT
#

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

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

The `key` function can optionally be a coroutine.

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.

Examples

Setting a one per 5 seconds per member cooldown on a command:
slate swan
#

@tall temple

tall temple
#

thanks

eager portal
#

Hello! I'm using discord.ui.View and select I want to know how I can create a ticket system that the user presses a Open ticket button then a drop down menu shows what the ticket reason is for

#

is this possible?

eager portal
#

anyone>

earnest swift
#

Show code

eager portal
#
import discord
from discord import app_commands, utils

id = discord.Object(id=1092591199300370473)

class ticket_launcher(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout = None)

    @discord.ui.button(label="Create a Ticket", style= discord.ButtonStyle.blurple, custom_id='openTicket')
    async def createticket(self, interaction: discord.Interaction, button: discord.ui.Button):
        ticket = utils.get(interaction.guild.text_channels, name = f"{interaction.user.name}-{interaction.user.discriminator}-ticket")
        if ticket is not None: await interaction.response.send_message(f"{interaction.user.mention}, You already have a ticket open! {ticket.mention}", ephemeral=True)
        else:
            overwrites = {
                interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
                interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
                interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
            }
            channel = await interaction.guild.create_text_channel(name = f"{interaction.user.name}-{interaction.user.discriminator}-ticket", overwrites=overwrites, reason=f"Ticket Opened for: {interaction.user}")
            await channel.send(f"{interaction.user.mention}, I have created a ticket for you!")
            await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}!", ephemeral=True)




class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.all())
        self.synced = False
        self.added = False
    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild=id)
            self.synced = True
            print("Synced")
        if not self.added:
            self.add_view(ticket_launcher())
            self.added = True
        print("Online.")


client = aclient()
tree = app_commands.CommandTree(client)

@tree.command(name="ticket", guild=id, description="Open a ticket!")
async def ticket(interaction: discord.Interaction):
    embed = discord.Embed(
        title="BotBean | Tickets",
        description="To open a ticket, click the button below!",
        color=discord.Color.green()
    )
    await interaction.response.send_message(embed=embed, view = ticket_launcher())
    await interaction.response.send_message("Tickets set!", ephemeral=True)

client.run(f"")
``` I have the basic command working, I just want to add my drop down menu from my other bot so the user has an option of ticket type
#

@earnest swift

smoky sinew
#

and why are you creating your own command tree

earnest swift
smoky sinew
earnest swift
#

Can u help me with it

smoky sinew
#

idk

earnest swift
#

??

eager portal
smoky sinew
earnest swift
smoky sinew
#

@eager portal which part are you having trouble with

earnest swift
#

Can someone help me add a image to my embed

eager portal
smoky sinew
#

!d discord.ui.select

unkempt canyonBOT
#

@discord.ui.select(*, cls=discord.ui.select.Select[+ V], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.

To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
eager portal
#

nvm duck got it

#

cheers

eager portal
#

why are my overwrites not working

#
        overwrites = {
                interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
                interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
                interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
        }
        if select_item.values[0] == "support":
            channel = await support.create_text_channel(name = f"{interaction.user.name}-{interaction.user.discriminator}-ticket", overwrites=overwrites, reason=f"Ticket Opened for: {interaction.user}")
#

anyone able to help me out

smoky sinew
surreal summit
#

Hey, is there an efficient way to make responses to commonly asked "questions" where the bot reads a message, and if the words "help" or "how" etc are in the sentence, it then checks the context such as "bot" or "commands" or something else and then response with some answer?

I know I can do that "if ["how"] in message.content: if ["bot"] in message.content:" and so on to get the context of the person needing help and what to specifically help with, but is there a better way of doing this?

#

This is just a personal project I would like to make, and if I can I want to include my own pretrained "ai" to answer since these questions could be server specific that (for example) the chatgpt couldnt answer

sick birch
surreal summit
#

i understand that

sick birch
#

AI LLMs like ChatGPT aim to solve this very issue, not sure how much luck you'd have with a rule-based pattern matcher

surreal summit
#

thats why I was thinking of hardcoding commonly based words for questions

#

like "how to enable this feature"

sick birch
#

If you're sure you want to do it, the code itself isn't all that difficult - just a bunch of if statements that are nested

surreal summit
#

i want to avoid that tbh

sick birch
#

bing_shrug usually it's atypical to do this so there's not much of an alternative

surreal summit
#

yea

#

thank you for the help though

sick birch
#

I've used it in the past and it did it's job pretty well for what I wanted it to do

ember glen
glad cradle
#

set_icon?

ember glen
naive briar
#

That's from set_author

ember glen
#

it will be inside the footer tho

glad cradle
#

yeah

#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

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

yeah this one

#

i made a lil mistake before, sorry 💀

#

Btw is there anything to check whether the interaction user has certain permissions or not?

glad cradle
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
glad cradle
#

iirc you can use this

ember glen
#

alright, thanks dude

glad cradle
#

you're welcome

smoky sinew
glad cradle
#

one that never expires

vocal snow
#

The Holy Interaction

glad cradle
#

every interaction descends from me

swift acorn
#

I'm trying to create a button but it's saying inconsistent use of tabs and indentations
Even though all tutorials do it like that

shrewd apex
#

lmfao

shrewd apex
#

what that means is u cant use both tabs and spaces for indentation

#

pick one

swift acorn
#

got it thanks

#
from typing import Optional
import discord
import discord
from discord.ext import commands
from discord import app_commands
from discord.ui import button, Button, View

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

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)!")
    except Exception as e:
        print(f"Sync Failed! {e}")
        

class applybutton(View):
    def __init__(self):
        super().__init__(timeout=None)
        
    @button(label="Apply", style=discord.ButtonStyle.blurple)
    async def creatorapply(self, interaction: discord.Interaction, button: Button):
        await interaction.response.defer(ephemeral=True)
        category: discord.CategoryChannel = discord.utils.get(interaction.guild.categories, id=1105378615299948575)
        for ch in category.text_channels:
            if ch.topic == f"Ticket for ID:{interaction.user.id}":
                await interaction.followup(f"{interaction.user.mention} You already have an active ticket!")
                return
                
        channel = await category.create_text_channel(
            name=interaction.user,
            topic=f"Ticket for ID:{interaction.user.id}"
        )
        await channel.send(
            embed=discord.Embed(
                title="Thanks for applying!",
                description="A staff member will be with you shortly."
            )
        )
        await interaction.followup(f"Your ticket has been created! Please head over to {channel.mention}")

        

@bot.command(name="creatorapply")
@commands.has_permissions(administrator=True)
async def creatorapply(ctx):
    await ctx.send(
        embed = discord.Embed(
        title="Click to apply",
        description="A ticket will open for your application"
        ),
        view = applybutton()
    )

bot.run(Token)

For some reason whenever I click the button it says interaction failed, the bot had admin perms and I do as well, and there's no errors in the terminal, does anyone know what the problem might be?

naive briar
#

You simply did not respond to the interaction

#

And interaction.followup is a property, not method

swift acorn
#

Oh so then I should use like, interaction.followup.send() ?

#

Even after that it says interaction failed, and it doesn't create the channel or anything

smoky sinew
#

show your code now

swift acorn
# smoky sinew show your code now
from typing import Optional
import discord
import discord
from discord.ext import commands
from discord import app_commands
from discord.ui import button, Button, View

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

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)!")
    except Exception as e:
        print(f"Sync Failed! {e}")
        

class applybutton(View):
    def __init__(self):
        super().__init__(timeout=None)
        
    @button(label="Apply", style=discord.ButtonStyle.blurple)
    async def creatorapply(self, interaction: discord.Interaction, button: Button):
        await interaction.response.defer(ephemeral=True)
        category: discord.CategoryChannel = discord.utils.get(interaction.guild.categories, id=1105378615299948575)
        for ch in category.text_channels:
            if ch.topic == f"Ticket for ID:{interaction.user.id}":
                await interaction.followup.send(f"{interaction.user.mention} You already have an active ticket!", ephemeral=True)
                return
                
        channel = await category.create_text_channel(
            name=interaction.user,
            topic=f"Ticket for ID:{interaction.user.id}"
        )
        await channel.send(
            embed=discord.Embed(
                title="Thanks for applying!",
                description="A staff member will be with you shortly."
            )
        )
        await interaction.followup.send(f"Your ticket has been created! Please head over to {channel.mention}", ephemeral=True)

        

@bot.command(name="creatorapply")
@commands.has_permissions(administrator=True)
async def creatorapply(ctx):
    await ctx.send(
        embed = discord.Embed(
        title="Click to apply",
        description="A ticket will open for your application"
        ),
        view = applybutton()
    )
smoky sinew
#

it doesn't create the channel and no errors

#

name=interaction.user

#

probably this part

swift acorn
#

Alr let me just try a random name

#
channel = await category.create_text_channel(
            name="name",
            topic=f"Ticket for ID:{interaction.user.id}"
        )

Changed it to this but same problem

vocal snow
#

Maybe add some print statements and see where the code is freezing

smoky sinew
#

print statement is the best debugger

vocal snow
#

Ideally your logger should be functional but

swift acorn
#

Yeah I did and it seems that none of the button code is working

smoky sinew
#

oh

#

are you reusing the same message

#

your view isn't persistent

swift acorn
smoky sinew
#

well that's why

swift acorn
smoky sinew
#

it means it doesn't keep working after your bot reloads

slate swan
#

does*

#

Oh isn't persistent

#

🗿

#

My bad

vocal snow
#

It's ok ur allowed to blame it on mudkip

smoky sinew
#

no

slate swan
swift acorn
#

Thank you guys so much!

vocal snow
#

He likes diet coke more than coke zero can you believe

slate swan
swift acorn
#

I tried with a new message and that works, I'll try and figure out how to do the persistent thing now

smoky sinew
#

it tastes better

#

and better than regular coke too

slate swan
#

No

swift acorn
smoky sinew
#

it's creamy 😋

vocal snow
#

Not docs in GitHub

smoky sinew
slate swan
#

There is one on GitHub

smoky sinew
#

it's an example though not docs

empty fable
#

yo can i ask if where to put a bot to stop swearing and a helpful bot in one python script would it work?

slate swan
empty fable
#

i rather learn to make it then using the given bots is more fun

robust fulcrum
#

Guys can user token be used for login in discord.py?

vocal snow
#

No, that's selfbotting which is not allowed by discord

vocal snow
#

What help do you need specifically

empty fable
#

to merge 2 bots

#

into 1 script

#

i just want to learn

vocal snow
#

So you have two existing discord bots which you want to merge?

empty fable
#

both

vocal snow
empty fable
#

i want to merge the moderation bot to the helpful bot

#

yeah in python

vocal snow
#

Then that should be possible

empty fable
#

tq so much man so i just need to change the async right?

vocal snow
#

Just use one instance of commands.Bot or discord.Client

#

For all commands and events

empty fable
robust fulcrum
stuck geode
#

How do I get stream permission in this server?

empty fable
#

@vocal snow can you help at discord bot problem

vocal snow
#

Yes

empty fable
#

at python problem the third one

#

it is me

empty fable
stuck geode
vocal snow
stuck geode
#

Yes

#

Zeffo

vocal snow
stuck geode
#

Oh ok thanks

slate swan
#

is there a way to extract a string from a message a user sent in discord using the command thingy
like( !vote "discord") i want to extract discord from this but i don't wanna use the on_message function. Is there any way for this?

naive briar
#

Command arguments

ember glen
eager portal
vivid axle
#

im trying to make an api to interact with my discord bot, just to get how many guilds, channels & users it has, how would i start this. im using dpy

north kiln
#

how could you setup logging such that my extension files that contain commands logs to the same file as my main bot entry file?

#

I added
logger = logging.getLogger(__name__)
but it doesn't log anything when I do logger.debug

vivid axle
#

if thats what u are looking for

north kiln
#

that's not

vivid axle
#

idk then

north kiln
#

and it was my main config

    logger = logging.getLogger("discord")
    logger.setLevel(logging.DEBUG)
    handler = logging.handlers.RotatingFileHandler(
        filename="./logs/discord.log", 
        encoding="utf-8", 
        maxBytes= 16 * 1024 * 1024,
        backupCount=2
    )
    dt_fmt = '%Y-%m-%d %H:%M:%S'
    handler.setFormatter(
        logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{')
    )
    logger.addHandler(handler)
abstract kindle
#

Heyo, so I'm kind of copying the file structure for this servers discord bot, and there is a directory called bot and then a file in that directory called bot.py. When I try to import the bot module in my main and the bot file file, it doesn't like it because it thinks its a circular import, and it gets fixed by changing the name of the bot.py file. How does this bot avoid that issue?

sick birch
#

The bot is laid out in such a way that this does not happen

abstract kindle
sick birch
#

So you have your own instance of @unkempt canyon running?

#

Did you git clone?

abstract kindle
#

No, just the couple of files (main.py, bot.py)

#

Let me get the error

sick birch
#

Do you have this uploaded to a github or something I can take a look at?

abstract kindle
#
Traceback (most recent call last):
  File "/Users/ellalbrys/CodingProjects/Python/coconut-capitalist/bot/__main__.py", line 13, in <module>
    import bot
  File "/Users/ellalbrys/CodingProjects/Python/coconut-capitalist/bot/bot.py", line 7, in <module>
    from bot import exts
ImportError: cannot import name 'exts' from partially initialized module 'bot' (most likely due to a circular import) (/Users/ellalbrys/CodingProjects/Python/coconut-capitalist/bot/bot.py)
#

Yeah, let me push the changes real quick

abstract kindle
sick birch
#

Yeah my GitHub username is Robin5605

abstract kindle
#

@sick birch also changes havent been pushed yet one sec

sick birch
#

👍

#

Reason I wanted to look at the git repo is I'd like to be able to see all the files, what's importing what, and the file structure

#

@abstract kindle would not recommend putting your commands in __main__.py

#

__main.py__ should be only for creating the bot constructor and starting the event loop

abstract kindle
#

Also, the changes are on the testing branch

sick birch
#

Yup found them

sick birch
#

Ideally cogs shouldn't be importing each other

abstract kindle
#

Got it. And core implies functionality that is necessary for the bot to run?

sick birch
#

Indeed

#

Stuff like your sync and cog management systems can go in there

abstract kindle
#

Okay. Those commands have been there since I made the bot, so it's definitely time for them to move

#

And what if the cogs aren't loading properly? How would I check if the "core" cog itself isn't loading?

#

I'm trying to switch over to the BotBase from the pydis_core library so that I can just run load_extensions in the setup_hook method, but I haven't got that all down yet

sick birch
#

Bot core is pretty great yeah. Use it in many of my own bot projects

sick birch
#

But generally you'd also add logging to say "Extension X was loaded"

abstract kindle
#

Right. I really want to get logging down. I've been using print statements for too long. I was looking at the logging library and it seems pretty self explanatory. For the different levels of logging though, would I have to setup the format and everything for each file? I know that the common logging setup is log = getLogger(__name__), but where would I define the default configuration for the logger?

abstract kindle
sick birch
abstract kindle
#

Sorry for all the questions lol, I am just so eager to learn GOOD development practices (file structure, modularizing, etc.) and I rarely get a chance to just ask away. Really appreciate it~~

sick birch
#

Yup. People overlook that aspect of bot development all too many times and the resources are quite limited

#

This sort of stuff you're asking is what takes you from a mediocre developer to an advanced software engineer 😄

abstract kindle
#

YESSS! Good to hear

#

This bot has been a project for about 2 years now, and it is absolutely giving me so many skills. Project management, I'm getting somewhat good at Github, I'm learning about user feedback from my friends who use the bot, etc. Looks great on a resume.

#

I'm hoping to learn Docker this summer so I can stop running my bot in a minimized terminal window on my PC and so that I can streamline development from my osx laptop and my windows pc

sick birch
#

With Docker comes a whole another field: devops

#

You can set up pipelines to automatically lint, test, and deploy pushes to github

abstract kindle
#

So much more to learn

#

Gets overwhelming sometimes, but its all good

sick birch
#

I've been doing this for a few years now and it's still overwhelming at times, if that's any consolation

abstract kindle
#

Definitely. Especially since I see you in here all the time helping so many different people. Still can make an impact even if you don't know everything

wary moat
#

If I have a discord bot which makes API calls, what's the recommended way to let the functions in the different cogs in separate files access the API key?

sick birch
wary moat
#

do I then need to call os.getenv in each cog?

#

how does this work

sick birch
wary moat
#

OK, it just seems a bit inefficient

sick birch
#

You could also build a aiohttp.ClientSession subclass that automatically adds the authorization headers and base URLs and stuff for the specific API you're using, that way you don't need to worry about auth in your cogs

wary moat
#

sure

#

well, in my case I'm using an API wrapper in Python, so it would be a bit different, but yeah

north kiln
potent spear
slate swan
#

which function would edit any message the bot sends? if I want to put in the channel and the message id? discord.Message.edit()?

potent spear
slate swan
#

so how would that work? lets say i pass the param message_id 1105512935746445312 with my bots message for ex. would i do something like
message = discord.Message(id=message_id) and it gets the object?

potent spear
#

there's a getfetch_message method

#

which is a method of a channel object

#

so you can get a message from a specific channel by its ID

slate swan
#

so i need to use discord.Channel first? or is it this Client.get_message

potent spear
#

so your order of doing things would be:

  • get a channel object
  • get a message object from that channel object by using getfetch_message
  • call the edit method on the message you just got
slate swan
#

so i'd need to use guard clauses to figure out which channel type first for the right channel object. ok

#

or wait..

potent spear
#

you could fetch a message from a user / channel / ...

slate swan
#

!d discord.Message.channel

unkempt canyonBOT
potent spear
#

they all have that method

slate swan
#

hmmm ok.

#

think i got it. ty

ember glen
#

Is there a method to send dm to a user through bot?

thin raft
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**.
north kiln
#

from the discord api I suppose

shrewd apex
potent spear
shrewd apex
#

or was that for channel purge

potent spear
#

28day period and then what?

shrewd apex
#

like u cant delete messages more than 28 days old or something wait a sec lemme check

potent spear
#

That wouldn’t make sense tbh

gleaming shore
#

Im trying to add chat gpt to my discord bot but im running into several issues, can someone take a quick look at my code ?

vocal snow
#

please send it here, along with the full traceback (if there is one)

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

potent spear
#

If you manage to get ChatGPT working outside a bot first, then I’d move on to integrating it in your bot

shrewd apex
#

hmm i think confused it with something else mb

white citrus
#

Can i add at search_targets a description?

eternal shuttle
#

how do i change the style of this original help command?

unkempt canyonBOT
#
Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

eternal shuttle
#

so i make a new command?

slate swan
eternal shuttle
#

alrighty

#

thank you

ember glen
#

What are webhooks 💀

slate swan
thin raft
#

wait what

ember glen
#

Ok, thanks a lot ❤

ember glen
#

Btw is there any module or something by which I can play music just by link or searching, in premium like sound quality

ember glen
#

Thank u :D

thin raft
ember glen
#

Thanks buddy
Much appreciated

thin raft
#

you will need to use that after it

thin raft
gleaming shore
#

is chat gpt API key free to use in a discord bot?

honest shoal
#

It's getting highlighted, I just want red font

slate swan
honest shoal
#

according to that, it shouldn't highlight unless I add another value using ;

slate swan
#
Solid

#

you cant use bold looks like

#

when you do normal format it works

#

@honest shoal ^

honest shoal
#

oh got it

#

ty

terse orchid
#

hello, how would I send a message to a channel at a particular time everyday? I've tried a few things using @tasks.loop but I haven't found a solution yet

vocal snow
#

A cron job with a webhook

slate swan
#

Can't you just use tasks and set a time for the next iteration and then change the interval to the next date once it get executed

#

E.g. initialize the task with the date and time to run set to tomorrow at 6pm

#

then once the task gets executed, change the interval and set the next date and time to run the day after tomorrow at 6pm

slate swan
vivid axle
#

im trying to make an api to interact with my discord bot, just to get how many guilds, channels & users it has, how would i start this. im using dpy

tall temple
#

how to get guild id by server name in bot joined servers pls ?

eager portal
slate swan
#

trying to use the embed.add_field(name='',value=self.value)
if I want the data to show

compact like this
whats the best
method...?

right now...

it sends like this :/

        for key, value in insert_list: 
            self.value += f"> {key}\n"
vale wing
vale wing
eager portal
#

cant you do ```py
for key, value in insert_list:
embed.add_field(name=name, value=value, inline=True/False)

slate swan
#

that would make new fields for each

#

it would give the same result

eager portal
#
        overwrites = {
                interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
                interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
                interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
        }
        if select_item.values[0] == "support":
            channel = await support.create_text_channel(name = f"{interaction.user.name}-{interaction.user.discriminator}-ticket", overwrites=overwrites, reason=f"Ticket Opened for: {interaction.user}")
``` Any one help, default role can still see new channel
vale wing
tall temple
#

okay

full lily
tall temple
#

that's what i thinked about but i thought there is simpler method :/

terse orchid
full lily
#

super

slate swan