#discord-bots

1 messages · Page 310 of 1

grim echo
#

hello how can i make a code listen for keywords to trigger a bot to make an action for example like muting them , banning, or just simply reply to the key word?

coral cradle
#

have a look at the event section of the docs

grim echo
sick birch
#

Looks like TOKEN was not defined

grim echo
sage otter
#

you would do await message.author.kick()

grim echo
#

thank you

upbeat basin
#

I need a help

#

I need a code which helps me check if a bot has sent me a message including "has uploaded a new video" on discord in a channel, and it has a usertoken not a bot token in it, like i am using my account's token for checking if anyone has uploaded a video so i get notified by myself.

sage otter
#

that’s definitely not allowed

upbeat basin
#

What is not allowed actually?

glad cradle
#

Hi, I'm making a PUT request to this endpoint /channels/{channel.id}/recipients/{user.id}

now the problem is that with the following headers:

{
    "Authorization": "Bot XXXX",
    "Content-Type": "application/json"
}

and with the following json encoded body:

{"access_token": "XXXX", "nick": "XXXX"}

I'm getting as response a 400 bad request code and an api error with the code 50035 and the following message "Cannot execute action on this channel type". Now the type of the channel_id is Group DM (3) indeed this endpoint /channels/{channel.id}/recipients/{user.id} returns a different code error:
50013 Missing Permissions

so now my question is, am i missing something?

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.

upbeat basin
#

Try this

token=os.environ['TOKEN']

client.run(token)```
sage otter
upbeat basin
#

Oh lol i didnt even read the api docs sorry

raven iron
buoyant quail
#

Just put is as a string

#

Without env

abstract kindle
#

What's the proper way to use a custom emoji in an embed with a bot?

sage otter
#

especially if he wants to make the source code open source

unkempt canyonBOT
#

class discord.Emoji```
Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of `None`...
abstract kindle
abstract kindle
#

Oh yoooo, I always skip over that part of the docs lol

#

Thanks very much

#

I feel dumb lol

hollow zinc
#

main.py

import discord
from discord.ext import commands
from dotenv import load_dotenv
import os

load_dotenv()

TOKEN = os.getenv('DISCORD_TOKEN')

intents = discord.Intents.all()

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

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

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')
    print(f'Bot ID: {bot.user.id}')

bot.run(TOKEN)

cogs/ping.py

import discord
from discord.ext import commands

class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')

def setup(bot):
    bot.add_cog(Ping(bot))

Warning when running

RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension(f'cogs.{filename[:-3]}')

Error after commanding

2023-10-08 01:11:04 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found

young dagger
#

What is wrong?

#

Why do I need Microsoft Visual C++ to install discord.py for python?

night crater
final iron
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
night crater
final iron
#

Therefore, you're also getting errors in your console that you're not sharing for some reason

night crater
#

Basically Discord.py depends on libraries which use C/C++ internally for speed

young dagger
#

@night crater Thank you prayge

young dagger
night crater
#

maybe I cant remember which ones you need exactly

#

but I would probably not delete them

final iron
#

tbh I wouldn't be deleting them

#

They have such a minimal impact and have a possibility to break like basically everything

hollow zinc
#
# Load Cogs
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')

using nextcord
command in 'cog' folder
how to make commands working if i put them in another folder in the cog folder.
for example: cogs/on_ready/Ready.py but not cogs/Ready.py

shrewd vapor
#

Hello everyone

#

I need help for make a command

#

I try to make a command use chatgpt for chatgpt provide a response to the prompt enter in the command

#
@bot.command()
async def ai(ctx, prompt):
        if config["use_ai"] == "yes":
            if config["ai_key"] == "":
                print(f"{Fore.RED}[{datetime.datetime.now()}] [ERROR] No API key OpenAI found in config{Fore.RESET}")
                print(f"{Fore.YELLOW}[{datetime.datetime.now()}] [TIPS] Set API key OpenAI in config.json, you will find it in the same folder{Fore.RESET}")
                return
            else:
                openai.api_key = config["ai_key"]
                prompt = prompt
                response = openai.Completion.create(
                  model="text-davinci-003",
                  prompt=prompt,
                  max_tokens=300,
                  temperature=0.9
                )
                if response.choices[0].text:
                    await ctx.send(response.choices[0].text)
                    print(f"{Fore.GREEN}[{datetime.datetime.now()}] [AI] Response sent{Fore.RESET}")
                else:
                    print(f"{Fore.RED}[{datetime.datetime.now()}] [ERROR] Empty response from OpenAI{Fore.RESET}")
        else:
            print(f"{Fore.RED}[{datetime.datetime.now()}] [ERROR] You have disabled the AI{Fore.RESET}")```
#

This is my code

#

When he answers, he answers totally nonsense

#

And when i put the same thing in on_message event i don't have this problem

golden portal
shrewd vapor
#

Thanks for remember me that

#

I have miss since a long time i don't have make command with prefix

hollow zinc
#

Cogs.

golden portal
#

just read the second folder like you did with Cogs there?

hollow zinc
#

./cogs/.../ ?

#

I want to open some

#

many for example

#

Not cogs/one folder/all the commands

golden portal
#

could just use glob.glob

#

!d glob.glob

unkempt canyonBOT
#

glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)```
Return a possibly empty list of path names that match *pathname*, which must be a string containing a path specification. *pathname* can be either absolute (like `/usr/src/Python-1.5/Makefile`) or relative (like `../../Tools/*/*.gif`), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file will be included is unspecified.
golden portal
#

/cogs/**/*.py, then just convert the / to . when loading the extension, and exclude .py

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @agile spade until <t:1696731065:f> (10 minutes) (reason: newlines spam - sent 110 newlines).

The <@&831776746206265384> have been alerted for review.

visual yarrow
#

!unmute 741403526152061039

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction timeout for @agile spade.

visual yarrow
#

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

agile spade
final iron
#

From F to A prob like a C/C+

#

I would definitely look at pep8 first

#

!pep8

unkempt canyonBOT
#
PEP 8

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

agile spade
#

hm, ill have to look into that, thanks for letting me know tho!

final iron
# agile spade hm, ill have to look into that, thanks for letting me know tho!

So just generally,

  1. General pep8 and formatting
  2. See below
  3. def getavg(list=list): not sure what you're doing here tbh
  4. Here as well, name=str, des=str, color=nextcord.Colour. Are you trying to typehint? = assigns a default value. You would use : for typehinting: def foo(string: str)
  5. No need to return a tuple return(embed)
  6. You're naming your commnads.Bot() instance client instead of bot
  7. Using json as a db instead of a proper one, like sql
  8. Would fix this naming: async def serverstats(ctx : Interaction)
  9. This as well: async def messagessent(ctx : Interaction, member : nextcord.User):
  10. Bare try and except
  11. I don't really see a point to makeembed at all as you could just use nextcord.Embed()
  12. You should only be using Intents.all() if you really need all the intents, especially privileged ones

You could just use with open() and you won't need file.close() for

file = open('messagelengthavg.txt', 'r')
for messagelengthvalue in str(file.read()).split('-'):
    lengths.append(int(messagelengthvalue))
file.close()
#

There's more stuff, but that's just surface-level imo

#

I gotta cook so I can't fully analyze it

slate swan
#

you did this for literally every channel. wow

hushed galleon
# agile spade anyone mind ***Grading*** my discord bot code (made with nextcord, not discord.p...

i would say there is a lack of documentation and lots of inefficient practices which will gradually make your code uglier and harder to maintain as you develop your bot, but at the same time you don't have too much code right now so you can easily make major changes, and trying to understand all the best practices at once is difficult if you aren't applying them to new features or projects

with that being said, i would suggest learning SQL and SQLite to store any data that changes often rather than in JSON/text files; it's fairly easy to learn and is a handy tool to know in general for other projects you might write

silent copper
#

Hello

slate swan
#

how to make app command like this

silent copper
#

Yes just like this thankyou!

#

it keeps trying ask questions in channel or in DM.

#

making clutter.

#

it want it to cycle through the questions in the text area then once it has all the relevant information create an embed using it.

#

Or are you asking for the same thing ? lol

#

I thought you had seen my question in main discussion.. that would be one hell of a coincidence.

twilit grotto
silent copper
#

I am currently having issues with my Discord bot asking the questions either in the channel itself creating mess or sending a DM.

silent copper
#

I have seen other bots ask the relevant questions from within the text area after similar to the above screenshot.

silent copper
#

So for example where I've typed this I would put !newlisting.

#

In the message area it would then ask Name: with a box I could enter the name.

#

It would then move on to Age with another box...

#

and so on... sometimes it will have +1 when you want to add more than one reply.

#

you'd click the +1 to add another box to enter information into.

final iron
#

Sounds like a modal

#

Could you show an example?

silent copper
#

I've been searching Google images to see if I could find one.

#

the user above posted something similar.

#

without the drop file part.

final iron
#

Sounds like just regular slash commands

#

Like this right

silent copper
#

That is exactly it spot on mate.

#

a Modal it is then.

final iron
#

Nah that's just normal slash commands lol

#

This is a modal

silent copper
#

Arghhh for some reason I keep either getting the bot to either ask the questions directly in the channel for everyone to see or in a personal DM.

#

and want it to ask like above.

final iron
silent copper
#

the country/weight part above.

final iron
#

Yeah so that's just a regular slash command

silent copper
#

where I could type USA and 20kg into the fields.

final iron
#

It's not possible with a prefixed command

silent copper
#

Okay cheers for the help.

final iron
#

👍

old vine
#

HOW TO LOCK A THREAD USING PYTHON?

#

like how to set the perms?

naive briar
unkempt canyonBOT
#

await edit(*, name=..., archived=..., locked=..., invitable=..., pinned=..., slowmode_delay=..., auto_archive_duration=..., applied_tags=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the thread.

Editing the thread requires [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads). The thread creator can also edit `name`, `archived` or `auto_archive_duration`. Note that if the thread is locked then only those with [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads) can unarchive a thread.

The thread must be unarchived to be edited.
naive briar
#

Set the archived argument

obsidian fable
#

how can I get the ID of a slash command?

silent copper
#

Trying to get started with building a Discord bot, installed python, installed vitrual studio code.

#

When I go to install pip install discord I get the following error.

#
      copying yarl\__init__.pyi -> build\lib.win-amd64-cpython-312\yarl
      copying yarl\_quoting_c.pyi -> build\lib.win-amd64-cpython-312\yarl
      copying yarl\_quoting_c.pyx -> build\lib.win-amd64-cpython-312\yarl
      copying yarl\py.typed -> build\lib.win-amd64-cpython-312\yarl
      running build_ext
      building 'yarl._quoting_c' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for yarl
Failed to build aiohttp frozenlist multidict yarl
ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projectss```
#

I've then visited the site and installed the visual studio build tools 2022. But still get the same error.

old vine
naive briar
unkempt canyonBOT
naive briar
old vine
#

can you check it and let me know how you do it

naive briar
#

You set the archived argument:

await thread.edit(archived=True) # 🤷
#

Unless you're using a different lib, not discord.py

old vine
naive briar
silent copper
naive briar
#

Yeah, you can downgrade Python for now

silent copper
#

Sweet just the previous version is enough ? or further back.

naive briar
#

Python 3.11 works fine

silent copper
#

Thanking you :).

naive briar
#

🐈

slate swan
#

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

shrewd fjord
#

catty catty .-.

hollow zinc
#
Cogs
   |
   ├─── Folder1
   |      |
   |      └─── cog1.py
   |
   ├─── Folder2
   |      |
   |      └─── cog2.py
   |
   ├─── Folder3
   |      |
   |      └─── cog3.py
   |
   └─── Folder4
          |
          └─── cog4.py
  • Is it possible to do something like this? ^
  • I want to make it automatically, without adding the path again and again.
  • using nextcord
  • I guess I have to do something with that:
# Load Cogs
for filename in os.listdir('./Cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')
proper tendon
#

making my first discord bot currently, any tips?

loud junco
loud junco
loud junco
loud junco
#

just add another for loop its going to be fine

vale wing
#

You can use pathlib.Path("./cogs").glob("**/*.py") and it will list all .py files

#

Pathlib is actually pretty convenient, worth looking at

loud junco
#

anyone here host their bot with the help of github student dev pack? i need help ;-; still cant fix the problem

slate swan
#

well if you don't ask any questions, it's quite hard - we unfortunately ran out of crystal balls

loud junco
slate swan
#

well, nothing we can help you with then - we won't give a credit card to some random users online LULW ask your parents or something

loud junco
slate swan
#

All services will require a credit card, so no

loud junco
#

ok thanks

proper tendon
#

anyone know how to make a modal without using the / command

slate swan
#

With what do you want one to be done

proper tendon
#

sort of like a verify command

slate swan
#

Yeah, then use slash commands and you can send a modal

proper tendon
slate swan
#

Stay?

proper tendon
#

let me show you

#

what i mean

slate swan
#

A modal gets sent once a user has an interaction

#

Which can be for example using a slash command or clicking a button

proper tendon
#

oh

#

wait so what is this called?

slate swan
#

Then obviously it'll be gone once the user has filled the info and submitted it

#

That's an embed with a button

proper tendon
proper tendon
#

@slate swan im trying to recreate something that my friend made, hes trying to make me learn

#

from scratch

slate swan
#

Well we'll help with issues you're facing, not code for you or similar

#

So if you have a concrete issue with your code, go ahead

proper tendon
#

👍

vale wing
#

What a politically biased company

turbid condor
#

I tried creating a ticket but no response

slate swan
#

average DO

hollow zinc
#

Hosting in Google Cloud platform cost any money?

turbid condor
#

It gives 300 credits and if u use them wisely u can host for around 3-6 months i think

#

But it also requires a credit card to claim the free credits

loud junco
vale wing
vale wing
#

Because they banned users from Russia and Belarus from editing it

#

I had a beef with them

loud junco
#

went through all of that just to shit to the toilet because i dont have a cc

restive wind
#

hey,is it possible to send a .txt file with smtplib in python?

shrewd apex
glad cradle
vale wing
brazen raft
glad cradle
#

iirc it depends where the society has the legal offices or the HQ

slate swan
#

Hello everyone, I need help with this command which should create an Embed with several information on the server, but when I execute the command nothing happens

And I would also like to place it in slash commande but I can't do it either, thank you

Source Link : https://paste.pythondiscord.com/PITQ

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.

gilded cedar
slate swan
#

What is wrong here? trying to learn how to create threads

gilded cedar
slate swan
gilded cedar
slate swan
gilded cedar
slate swan
#

🤦

#

so did you try printing out emoji to console?

gilded cedar
#

i asked them about it on nextcord official server

slate swan
#

How can I make an timer and if I respond to the interaction, interrupt this timer? Something similar to this example

slate swan
#

Hey guys, is there a way to get username using A userid?

brazen raft
#

I'm new to interactions so I don't know how responding to interactions works

#

It's been a while

slate swan
#

How can i make this embed look better

nova vessel
#

Does a user's Discord user ID ever change?

shrewd apex
#

no

slate swan
slate swan
slate swan
#

but I don't sure that possible get username

#

how can i create a thread in forum channel?

slate swan
#

look at my screen shot. i used it and id deosnt work

slate swan
#

and try delete auto_archive_dur, maybe you write wrong int

#

still not working

#

also, bot.get_channel(id)

#

where channel_id?

#

above this

#

Then I do not know how to help you

#

this is what it get:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'

sick birch
# slate swan still not working

If the cache lookup there is top level, I'm assuming the cache is not yet populated at that point so there are no cache hits

sick birch
slate swan
#

still not working bro

sick birch
#

Can you show us what you've got?

slate swan
#

get_ returns None if it's not in cache so you'd have to use

x = bot.get_channel(...) or await bot.fetch_channel(...)
#

Would be nice if you could share errors and not just say "Not working"

slate swan
#

.get_channel is not awaitable

slate swan
final iron
# slate swan

get_channel just searches the bots cache, so it’s not a coro

final iron
slate swan
slate swan
#

i can create thread in new created text channel, but when i try to do it in forum channel i get attribute error

final iron
#

How should I go about dynamically creating inputs for modals? Since it's just based off the variables, how would I do it with a loop? I've tried [discord.ui.TextInput(label=second) for first, second in modal_item_text.items()], but they're not registering

#

So I see add_item, how would I use that?

#

Oop figured it out

#

I had to use add_item in the __init__

final iron
#

If I needed a user to send a day in a specific format, how would you guys recommend I do it? Just use wait_for, and show the format I want i.e. 17/9/2023 or is there a better way? Should I use select menus instead?

sick birch
#

Doing it in text is probably the best way, and regexing it

final iron
final iron
vale prairie
#
@tree.command(guild= discord.Object(id=id_do_servidor), name="efetivo", description="Atualizar Efetivo.")
async def setup(interaction: discord.integrations):
    try:
        role_id = int(#id do cargo)

        role = discord.utils.get(interaction.guild.roles, id=role_id)

        if role is None:
            await interaction.response.send_message(f"Função com o ID '{role_id}' não encontrada.")
            return

        members_with_role = [member.mention for member in interaction.guild.members if role_id in [r.id for r in member.roles]]

        if members_with_role:
            members_list = " ".join(members_with_role)
            await interaction.response.send_message(f"{role.mencion}\n>>> {members_list}")
        else:
            await interaction.response.send_message(f"Nenhum membro possui a função {role.mention} no servidor.")
    except ValueError:
        await interaction.response.send_message("ID de função inválido. Por favor, forneça um ID de função válido.")
```  It's showing that there's no one with that role, but my friend and I have it. Where could I have gone wrong?
vale prairie
#

?

final iron
#

What about the question do you not understand

vale prairie
#

I think so, because it was working before.

final iron
#

Show how you enable them

#

What

#

What library are you using

vale prairie
#

import discord
from discord import app_commands
from discord.ext import commands
from decouple import config

final iron
#

Oh you're typehinting a file lmfao

#

Anyway, show how you're enabling them

vale prairie
#

Permissions for the bot?

final iron
#

No, intents lol

vale prairie
#

I'm sorry, I don't understand anything because I'm using Google Translate, I don't know English.

final iron
#

intents.members = True

#

Show that line, and the lines around it

vale prairie
#

"I don't have that line, should I show you the entire code?

final iron
#

Sure

#

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

vale prairie
#

Just a little bit messy, haha.

final iron
#

So you don’t have it

#

You’ll need it to receive information about members

vale prairie
#

I understand, thank you.

tepid dagger
#
channel = client.get_channel(ID)
await channel.send('stuff')

when i run this code it says
AttributeError: 'NoneType' object has no attribute 'send' why?

#

cus i've done the same thing before

#

and it worked

final iron
#

Consider using

#

!d discord.Client.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), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#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/api.html#discord.Client.get_channel) instead.

New in version 1.2.

Changed in version 2.0: `channel_id` parameter is now positional-only.
tepid dagger
#

so channel = await client.fetch_channel(id)

final iron
#

Try it and see

shrewd fjord
#

from dateutils

#

!d dateutil.parser.parse

unkempt canyonBOT
#

parser.parse(parserinfo=None, **kwargs)```
Parse a string in one of the supported formats, using the `parserinfo` parameters.

| Parameters: | • **timestr** – A string containing a date/time stamp.
• **parserinfo** – A [`parserinfo`](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parserinfo) object containing parameters for the parser. If `None`, the default arguments to the [`parserinfo`](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parserinfo) constructor are used.
 |

The `**kwargs` parameter takes the following keyword arguments:
shrewd fjord
#

this ^

final iron
#

I'll look into it

shrewd fjord
#

oh nvm its not in python bot

#

!pip pendulum

unkempt canyonBOT
final iron
#

I was more looking on how I should do it though

#

Have 3 select menus, 1 for year, one for month, one for day, or just use wait_for with a given example (or the parser you gave)

#

Or if there's any options I'm missing

#

The parser will be useful though, help minimize user error

sick birch
#

So it's not an ideal interface

#

Same thing with year, obviously

final iron
#

Well for year it'll only be like 3, but yeah, I get your point

#

That's my whole position, there aren't any good formats for this

sick birch
#

Another option is slash command with choice for month, and int inputs for day and year

final iron
#

Actually, how many buttons can you attach to a message?

sick birch
#

25

final iron
#

Nah wouldn't work as well

sick birch
#

A native interface for selecting datetimes would be really nice

final iron
final iron
sick birch
#

They're already pretty close tbh

#

Literally just copy paste this as a new slash command option type

final iron
#

Only if it was available to bots 😭

#

Discord needs to put more love into their bot devs

#

Bots are literally the backbone of Discord, and for 5 years they we're really the only thing that prevent servers from being constantly raided

#

And nuked etc

slate swan
#

It's already been a few months since it was data mined that datetime options are under work and would come

#

People got hyped, and now still nothing

vale wing
slate swan
#

hey

#

i need some help

#
  @commands.command(aliases=['r','grole'])
  @commands.has_permissions(manage_roles=True)
  async def role(self,ctx, member: discord.Member, role_name: discord.Role):
    await member.add_roles(role_name)
    embed = discord.Embed(description = f'{emoji.check} **{role_name}** has been `given` to {member.mention}', color=color.color)
    await ctx.reply(embed=embed,mention_author=False)

gives role fine but if the role is 2 words it dont

#

@final iron

shrewd fjord
#

put a *

slate swan
#

ty i shouulve knew

hallow kernel
vale wing
#

I suspect that's because of noip

wheat adder
vale wing
#

Like pendulum, pathlib and durations-nlp

cold oyster
#

Is it possible to send epheral messages not with slash commands?

wheat adder
#

So you have to create a button view.

cold oyster
wheat adder
mystic marsh
#

No you can't

cold oyster
#

Alr

wheat adder
# cold oyster Nah not even buttons

You could make a wrap-around, you could create a button view, but this gets triggered "Interacted" by a command (the command you want to get an epheral from).

#

an from that InteractionResponse that gets triggered by the command, you can send the epheral

cold oyster
#

Its alr

cyan quarry
#

yo just wanted to ask if we can access the list of banned members with our bot and revoke the ban?

#

nvm found it

slate swan
#

<@member_id> or if you have the Member object you can use its .mention property

#

!d discord.Member.mention

unkempt canyonBOT
slate swan
#

i dont see the <>

unkempt canyonBOT
#

discord/member.py lines 582 to 585

@property
def mention(self) -> str:
    """:class:`​str`​: Returns a string that allows you to mention the member."""
    return f'<@{self._user.id}>'```
slate swan
#

yeah for whatever reason you removing the messages xd?

slate swan
#

average people asking for help but don't want to show they're newbies to everyone

#

but be a big gigachad saying they fixed the issue themselves

vale prairie
#
@tree.command(guild=discord.Object(id=id_do_servidor), name="efetivo", description="Atualizar Efetivo.")
async def setup(interaction: discord.interactions):
    try:
        intents = discord.Intents.default()
        intents.members = True
        intents.guilds = True
        role_id = int(1160986660218089485)

        role = discord.utils.get(interaction.guild.roles, id=role_id)

        if role is None:
            await interaction.response.send_message(f"Função com o ID '{role_id}' não encontrada.")
            return

        members_with_role = [member.mention for member in interaction.guild.members if role_id in [r.id for r in member.roles]]

        if members_with_role:
            members_list = "\n".join(members_with_role)
            await interaction.response.send_message(f"{role.mention}\n>>> {members_list}")
        else:
            await interaction.response.send_message(f"Nenhum membro possui a função {role.mention} no servidor.")
    except ValueError:
        await interaction.response.send_message("ID de função inválido. Por favor, forneça um ID de função válido.") 
``` It's only fetching the bot's roles and listing only them, not those of other members.
weary pendant
#

!e

data = [1,2,3,-2,5,0,7]
def selection_sort(list):
    n = len(list)
    for i in range (n):
        for j in range(i+1, n):
            if list[j] > list[j+1]:
                list[j], list[j+1] = list[j+1], list[j]
    return list
a = selection_sort(data)
print (a)
unkempt canyonBOT
#

@weary pendant :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 9, in <module>
003 |     a = selection_sort(data)
004 |         ^^^^^^^^^^^^^^^^^^^^
005 |   File "/home/main.py", line 6, in selection_sort
006 |     if list[j] > list[j+1]:
007 |                  ~~~~^^^^^
008 | IndexError: list index out of range
ionic vessel
#

Can discord bots be programed with python 3.12?

slate swan
#

Not yet

#

Libraries will take a few days/weeks to be upgraded to be usable with 3.12

ionic vessel
#

Is there any quick way to tell what latest version of python can be used to develop discrod bots?

glad cradle
ionic vessel
#

Thanks

burnt coral
burnt coral
#

you sure? maybe i missed it, where?

glad cradle
unkempt canyonBOT
#

setup.py lines 95 to 98

'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',```
unkempt canyonBOT
#

pyproject.toml lines 26 to 29

"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",```
vale prairie
vale prairie
#

It only retrieves the roles of the bot itself.

final iron
vale prairie
#

@final iron

final iron
vale prairie
#

Only this part of the code that I pulled the intents.

final iron
#

When you enable intents, you need to pass them into your bot constructor

#

You’re not doing that in the code you showed

naive briar
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

final iron
unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

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

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
final iron
#

intents arg

mystic marsh
#

Does anyone have a list of all @discord.Clinet.event list?

#

!d discord.Client.event

vale prairie
#
class client(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.synced = False

    async def setup_hook(self) -> None:
        self.add_view(DropdownView())

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild=discord.Object(id=id_do_servidor))
            self.synced = True
        print(f"Entramos como {self.user}.") 
``` But am I not already passing it like this? @final iron ```super().__init__(intents=discord.Intents.default())```
final iron
#

Blud is mixing 2 tutorials

#

No, default is only non privileged intents

#

You need members to be enabled

naive briar
unkempt canyonBOT
#

@event```
A decorator that registers an event to listen to.

You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events).

The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) is raised.

Example

```py
@client.event
async def on_ready():
    print('Ready!')
```...
naive briar
mystic marsh
slate swan
#

can i get some help @final iron

slate swan
#
Traceback (most recent call last):
  File "/home/runner/scare1/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/scare1/cogs/lookup.py", line 20, in roblox
    followers=str(requests.get(f"https://friends.roblox.com/v1/users/{id}/followers/count").json()['count'])
KeyError: 'count'

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

traceback

#
      followers=str(requests.get(f"https://friends.roblox.com/v1/users/{id}/followers/count").json()['count'])
      friends=str(requests.get(f"https://friends.roblox.com/v1/users/{id}/friends/count").json()['count'])
      following=str(requests.get(f"https://friends.roblox.com/v1/users/{id}/followings/count").json()['count'])
#

@final iron

slate swan
#

check the id is correct and print the full json data to see what's going on I guess

#

and consider using aiohttp in place of requests since discord bots are asynchronous applications

#

yeah i fixxed it

marble rampart
#

so im having problems with my discord dashboard for my bot i always get the invalid redirect_uri oauth2 error can anyone help me?
this is my code and the uri i have on discord for the app is http://localhost:5000/authorized

from flask import *
from debuger import Debugger
from flask import Flask, redirect, request, url_for, session
from flask_oauthlib.client import OAuth


oauth = OAuth(app)

discord = oauth.remote_app(
    'discord',
    consumer_key='my app id ',
    consumer_secret='my app secret',
    request_token_params={'scope': 'identify'},
    base_url='https://discord.com/api/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://discord.com/api/oauth2/token',
    authorize_url='https://discord.com/api/oauth2/authorize',
)
debugger = Debugger()



@app.route('/')
def index():
    if 'discord_token' in session:
        return 'Logged in as: ' + session['discord_user']['username']
    return 'Not logged in.'

@app.route('/login')
def login():
    return discord.authorize(callback=url_for('authorized', _external=True))

@app.route('/logout')
def logout():
    session.pop('discord_token', None)
    session.pop('discord_user', None)
    return redirect(url_for('index'))

@app.route('/authorized')
def authorized():
    print("Inside the authorized function")
    response = discord.authorized_response()

    if response is None or response.get('access_token') is None:
        return 'Access denied: reason={} error={}'.format(
            request.args['error_reason'],
            request.args['error_description']
        )

    session['discord_token'] = (response['access_token'], '')
    user_info = discord.get('users/@me').data
    session['discord_user'] = user_info

    return 'Logged in as: ' + user_info['username']

@discord.tokengetter
def get_discord_oauth_token():
    return session.get('discord_token')
slate swan
#

hiiiiiiii

#

who know a channel where can i learn how to create a python discord bot?

stark nexus
#

Hi
I was progress on a fuction in bot that could recieve images + text from api
This is the result (unfinished)

#

I was curious how can i let the text (brinewater springs) in that text box (text change every 2 hour) is it possible let it in box everytime?

fiery girder
#

!e dm

unkempt canyonBOT
#

@fiery girder :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     dm
004 | NameError: name 'dm' is not defined
fiery girder
unkempt canyonBOT
#

@fiery girder :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     discord.dm
004 |     ^^^^^^^
005 | NameError: name 'discord' is not defined
fiery girder
#

i am using the wrong ciommand lol

knotty agate
#

!e

try:
    import discord
    print("success")
except Exception: print("epic fail")
unkempt canyonBOT
#

@knotty agate :white_check_mark: Your 3.12 eval job has completed with return code 0.

epic fail
maiden fable
unkempt canyonBOT
#

class discord.DMChannel```
Represents a Discord direct message channel.

x == y Checks if two channels are equal.

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

hash(x) Returns the channel’s hash.

str(x) Returns a string representation of the channel
cold oyster
#

Where and how should I host my discord bot?

stark nexus
cold oyster
turbid condor
unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

cold oyster
#

kk thx

cold oyster
turbid condor
#

Welp then you can use some spare device or pc

cold oyster
#

Can I use netlify? Will it work?

turbid condor
#

You can try I'm not sure

cold oyster
turbid condor
#

I'd rather spend some money than going for free

#

And I don't think 2-5$ per month is too much

cold oyster
#

¯_(ツ)_/¯

mystic marsh
#

Lol

fiery girder
#

i need someone for testing my bot can anyone volunteer?

mystic marsh
#

sure

fiery girder
#

ok ill send invite

mystic marsh
#

aight

cold oyster
#

dm me it

sage otter
white citrus
#
class TicketMain_One(nc.ui.View):
    def __init__(self, header, textbox, button_one):
        super().__init__()

        self.header = header
        self.textbox = textbox
        self.button_one = button_one
        print("--------")
        print(button_one)
        print(self.button_one)
        print("---------")
        self.b_one = nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)

    #@nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)
    async def b_one(self, button: nc.ui.Button, inter: nc.Interaction):
        inter.response.send_message("HI")```
He is not sending the button
final iron
#

Also, interaction should be first unless nextcord is different

white citrus
naive briar
#

Bit?

final iron
#

I never mentioned button_one

#

Your button decorator is commented out

glossy ruin
#

how do i test discord bot?

#

some commands need to communicate with discord so mainly how do i test that

shrewd apex
#

like unit tests for discord bots?

glossy ruin
shrewd apex
#

tbh not really any way since to test u would need to automate the discord process too from a browser page generally this part is not too hard but then invoking commands would make it self botting

#

u can mostly only automate the non discord parts as testing

glossy ruin
#

...

#

my mind stopped

#

okay got it

vale wing
#

Since you mostly need to test messages that are sent back and actions the bot takes

#

Imagine like

@command()
async def hi(ctx):
    await ctx.send(f"Hi, {ctx.author.mention}!")


async def test_hi():
    ctx = VirtualContext(author=discord.Object(69420))
    await hi(ctx)

    ctx.assert_last_message(content="Hi, @onyx raven")```
slate swan
#

not like i mentioned that while ago

#

😭

vale wing
#

Fr why won't libs do that

#

I suddenly feel the urge to contribute to disnake

glossy ruin
#

so no emulation exist?

slate swan
#

no

vale wing
glossy ruin
#

time to make one 💪

vale wing
#

Sure after my fellow team of bobux developers finally gets to v1.2

glossy ruin
#

i didnt get it

vale wing
#

You wouldn't ☺️

glossy ruin
#

coming from roblox my brain thinks bobux means robux

#

economy bot but name is sus 😄

shrewd apex
#

u would probably have to spin up instances of ur own discord api and event systems to emulate it

vale wing
#

As I see it you just replace objects that interact discord API with virtual objects or test objects that interact with themselves

#

That's most likely not going to be 100% accurate but better than nothing

sage otter
#

how is it going to be actually emulating. whats it going to look like

glossy ruin
sage otter
#

that made no sense at all

glossy ruin
#

🤦

#

your program acts like discord

#

bot will connect to ur your program

sage otter
#

thats not what you said the first time lol

#

whats the overall point of this emulator

glossy ruin
# sage otter whats the overall point of this emulator

what i saw

  • some actions in discords are irreversilble like banning people or something (sure you can unban the user but user need to rejoin back so breaking automatic testing?)
  • ratelimiting (i am not sure how much this will effect)
#

i am beginner so an experienced person will have more and better points

sage otter
#

ratelimiting wont be relevant if you're just testing

#

i can somewhat see the first point though

#

i feel like the amount of effort for the implementation into the library will be huge

#

but the pay off wont be

#

you wouldnt really need that to test most of the features bots have these days

glossy ruin
#

🤷‍♂️

#

is it possible to send button click?

#

i dont know

fiery girder
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

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

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
fiery girder
#

what command is for creating channels??

shrewd fjord
unkempt canyonBOT
#
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

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

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite) as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit) will be required to update the position of the channel in the channel list...
fiery girder
#

thanks

shrewd fjord
#

np

fiery girder
#

can i set a variable for a await command?

#
            await bot.get_guild(payload.guild_id).get_category(appeal_category).create_text_channel(f"Banned-Appeal-{payload.user_id}")

#

like this i just put a var so maybe i can store the text channel?

hushed galleon
#

according to the docs, yes

fiery girder
#

oh ok

glossy ruin
fiery girder
#

i saw the message

glossy ruin
#

why not pycord (i am curious)

fiery girder
#

idk

#

ask discord

#

go to support

glossy ruin
#

??

fiery girder
#

prob because of discord.js

#

so it would be same

glossy ruin
#

oh i mean why did this server choose discord.py over pycord 🤦

glossy ruin
fiery girder
#

it is made by discord i think

#

its not made by random people

glossy ruin
#

which one?

fiery girder
#

they dont have access to the things needed to make it

glossy ruin
#

yes they do

fiery girder
#

the API docs the API the developer portal

#

all made by discord

glossy ruin
#

🤦

fiery girder
#

ok man

#

i am working on bots rn

glossy ruin
#

what does it do? (i mean feature you are aiming to add)

fiery girder
#

ban appeals

#

and normal appeals

glossy ruin
#

okay

fiery girder
#

this code is a mess i wish there was a prettier for python lol

glossy ruin
#

black formatter

#

autopep8?

fiery girder
#

for example??

glossy ruin
#

black, autopep8

slate swan
#

ruff
black

fiery girder
#

black?

glossy ruin
#

yea

slate swan
#

or for example for sorting imports isort

fiery girder
#

which is best?

slate swan
glossy ruin
#

i use black

slate swan
#

!pip ruff

unkempt canyonBOT
fiery girder
#

i guess ill give it a try

#

it just tells me whats wrong it doesnt fix it

slate swan
#

what were you expecting

fiery girder
#

i am lazy af i aint gonna manually do things thats not important

slate swan
#

you can try black then

fiery girder
#

ok lemme try that

slate swan
#

i belive it can be used as linter in vscode

#

you can try enabling Format on Save also

glossy ruin
#

and chooose the default formatter too

slate swan
#

i belive you need to install extensions for Black or Ruff

fiery girder
#

as they say
"once you go black, you never go back"

fiery girder
#

in vs code marketplace

glossy ruin
#

and also available in pip

sage otter
glossy ruin
fiery girder
#

is there a shortcrut option to use a command in powershell without opening it in vscode

glossy ruin
fiery girder
#

ik the command dude

#

i just wanna press a button and it automattically format the code

#

what is the command for changing channel name

slate swan
#

!d discord.TextChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
glad cradle
hushed galleon
#

^ install the black formatter extension and alt+shift+f to format

glossy ruin
#

i saw that

harsh orbit
#
                    roleprice = role1price
                    if role in interaction.user.roles:
                        await interaction.response.send_message("** لا يمكنك شراء رول تمتلكها بالفعل**",ephemeral=True)

                    else:
                        tax = ceil(roleprice / 0.95)
                        embed = discord.Embed(title=role1.name, description=f"""قم بتحويل {roleprice} ل {bank.mention} 

What is this

compact lion
#

@bot.command()
async def ping(ctx):
    await ctx.send('pong')
#

code doesn't work help

glossy ruin
#

?

compact lion
#

the command not work

glossy ruin
#

can you share full code using pastebin?

slate swan
#

my command isnt getting registered in bot section plz help and bot comes online

#

anyone plz help

#

@glossy ruin

slate swan
#

Remember to:
• Ask your Python question, not if you can ask or if there's an expert who can help.
• Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
• Explain what you expect to happen and what actually happens.

compact lion
shrewd fjord
#

!pep 8

unkempt canyonBOT
shrewd fjord
#

mb, wrong channel

slate swan
shrewd fjord
slate swan
compact lion
slate swan
# compact lion bot.command() doesn't work

• Ask your Python question, not if you can ask or if there's an expert who can help.
• Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
Explain what you expect to happen and what actually happens.

slate swan
slate swan
compact lion
slate swan
#

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

compact lion
#

I'll send to dm

#
import discord
from discord.ext import commands
import lists

engel_ac = False

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

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

@bot.event
async def on_ready():
    print("Bot hazır!")


@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    

    
    for x in lists.kufurler:
        if message.content.lower().startswith(x) or x in message.content.lower():
            await message.delete()
            print(f'\nKüfürlü mesaj: {message.content} \nKullanıcı: {message.author} \n')
            await message.channel.send(f'{message.author.mention} küfür etmek yasak!')


@bot.command()
async def qwe(ctx):
    global engel_ac
    engel_ac = True
    await ctx.send('Küfür engeli açtım, şimdi küfür etmeyi deneyin!')

@bot.command()
async def ping(ctx):
    await ctx.send('pong')





unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

slate swan
shrewd fjord
#

bring danny bot here

slate swan
unkempt canyonBOT
#
The discord.py `on_message` event

Registering the on_message event with @bot.event will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message event handler.

Instead, use @bot.listen to add a listener. Listeners get added alongside the default on_message handler which allows you to have multiple handlers for the same event. This means prefix commands can still be invoked as usual. Here's an example:

@bot.listen()
async def on_message(message):
    ...  # do stuff here

# Or...

@bot.listen('on_message')
async def message_listener(message):
    ...  # do stuff here

You can also tell discord.py to process the message for commands as usual at the end of the on_message handler with bot.process_commands(). However, this method isn't recommended as it does not allow you to add multiple on_message handlers.

If your prefix commands are still not working, it may be because you haven't enabled the message_content intent. See /tag message_content for more info.

shrewd fjord
compact lion
#

what is process_commands()

slate swan
compact lion
#

ok

shrewd fjord
compact lion
#

tysm!

slate swan
#

@shrewd fjord still commands not registered

shrewd fjord
slate swan
#

!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
# shrewd fjord provide code

@bot.hybrid_command(name="whitelist", description="Whitelist a user", with_app_command=True)
@commands.has_permissions(administrator=True)
async def whitelist(ctx, name: str):
whitelist = addwhitelist(name) # You may need to implement this function
await ctx.send(content=f"Added {name} to Whitelist: {whitelist}")

shrewd fjord
#

down lurking bad

slate swan
#

@shrewd fjord

shrewd fjord
#

;-;

#

did you sync?

slate swan
#

like .sync?

#

blud forgor app_commands

shrewd fjord
#

oh man, whatever sync your commands in setup_hook using await bot.tree.sync()

slate swan
shrewd fjord
slate swan
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
shrewd fjord
#

sob

gray grotto
#

i have created my own discord AI bot. I dont want anyone from my server to Dm my bot but they can acces it only from my server is there any settings in discord or something like that.

slate swan
#

tyyyyyyyyyyyyyyyyssssssssssmmmmmmmmmm

#

worked lol

sage otter
#

!d discord.ext.commands.guild_only

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

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

If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only) decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
sage otter
#

@gray grotto ^

gray grotto
slate swan
gray grotto
#

is am in wrong channel ?

slate swan
#

no thats the decorator you need to add above command to be only available in guilds

compact lion
#

@slate swan when I make kufur_engel_ac the engel_ac be True but
this code not work

if engel_ac:
        for x in lists.kufurler:
            if message.content.lower().startswith(x) or x in message.content.lower():
                await message.delete()
                print(f'\nKüfürlü mesaj: {message.content} \nKullanıcı: {message.author} \n')
                await message.channel.send(f'{message.author.mention} küfür etmek yasak!')
#

sry for ping

#

(solved, I forgot to delete qwe argument)

slate swan
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
last gyro
#

hi if someone could help me create a twitter bot i would really appreciate that

spark nimbus
#

hello, I'm trying to work on logs channel. I got to the point of edit messages and I get an error th i dont know ho to work with (The error: NameError: name 'message' is not defined)
What can i do?

@bot.event
async def on_message_edit(message_before, message_after):
    embed = discord.Embed(title = f"{message_before.author.name} has edited a message (user id: {message_before.author.id})", description = f"{message.content}")
    embed.add_field(name = "Before Message", value = f"{message_before.content}", inline = False)
    embed.add_field(name = "Aftr Message", value = f"{message_after.content}", inline = False)
    embed.set_footer(text ="This bot was made by _mr3x. ")
    channel = bot.get_channel(logs channel)
    await channel.send(embed = embed)
glad cradle
#

well you're trying to use message.content but message is not defined, it should be message_before.content (if you want to show the content before the message edit - AKA the old content)

spark nimbus
#

let me try

glad cradle
slate swan
#
    def __init__(self, client):
        self.client = client


    @bot.event()
    async def on_guild_channel_create(self, channel):
        if "ticket" not in channel.name:
            return
   
        class ButtonView(discord.ui.View):
            def __init__(self):
                super().__init__(timeout=None)
                self.add_item(discord.ui.Button(label="Placeholder 1", style=discord.ButtonStyle.grey, custom_id="1"))
                self.add_item(discord.ui.Button(label="Placeholder 2", style=discord.ButtonStyle.grey, custom_id="2"))
                self.add_item(discord.ui.Button(label="Placeholder 3", style=discord.ButtonStyle.grey, custom_id="3"))
                self.add_item(discord.ui.Button(label="Placeholder 4", style=discord.ButtonStyle.grey, custom_id="4"))
                self.add_item(discord.ui.Button(label="Placeholder 5", style=discord.ButtonStyle.grey, custom_id="5"))
                self.add_item(discord.ui.Button(label="Placeholder 6", style=discord.ButtonStyle.grey, custom_id="6"))
                self.add_item(discord.ui.Button(label="Placeholder 7", style=discord.ButtonStyle.grey, custom_id="7"))
                self.add_item(discord.ui.Button(label="Placeholder 8", style=discord.ButtonStyle.grey, custom_id="8"))

        emb = discord.Embed(title="Placeholder", description="Placeholder", colour=discord.Colour.light_grey())
        await channel.send(embed=emb, view=ButtonView())
        return```
        
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\Recoding Soul\main.py", line 1670, in <module>
    class ButtonCommands(commands.Cog):
  File "C:\Users\Administrator\Desktop\Recoding Soul\main.py", line 1675, in ButtonCommands
    @bot.event()
     ^^^^^^^^^^^
TypeError: Client.event() missing 1 required positional argument: 'coro'
desert kiln
#

Question, is having a live ping command, i.e, the bot ping keeps updating after every X amount of seconds good to have, for debugging, or network errors, or just something usefull a whole

final iron
#

Just setup logging and it'll capture any useful debugging information

graceful temple
#

@final iron

#

hey, i need ur helppppppp

graceful temple
slate swan
graceful temple
#

sorry..

slate swan
#

And other people may also find the answer useful for them if you ask here, which is a bit the purpose

graceful temple
#

ur righ

#
Traceback (most recent call last):
  File "/home/runner/stakeus/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/stakeus/main.py", line 49, in tt
    Json = json.loads('{' + response.text.split('crossorigin="anonymous">{')[1].split('</script><script')[0])
IndexError: list index out of range

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

Traceback (most recent call last):
  File "/home/runner/stakeus/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/stakeus/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/stakeus/.pythonlibs/lib/python3.10/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: IndexError: list index out of range
#

this is the eror

slate swan
#

I doubt TikTok allows scraping

#

Yep they don't

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

graceful temple
#

sh i didnt even know that

#

ok lemme get this code out

graceful temple
#

can u help me with welcome messgage config for every server

naive briar
#

Yes

compact lion
#

why this code not working?

#

@slate swan

unkempt canyonBOT
#
The or-gotcha

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
turbid condor
#

Idk why it wasn't responding

#

In other channel the command is working

cinder horizon
#

im starting with slash commands today......wut all shud i know?

meager rock
cinder horizon
turbid condor
#

Only get into discord bots if you have at least intermediate level understanding of python

#

Otherwise start with something simpler

cinder horizon
#

hell i evn had music commands up n running....good ol days

turbid condor
#

Welp dpy went some changes from v2.0+ so you will need to get updated with it

compact lion
#

yo guys how to fix this error


@bot.command()
async def mute(ctx, user:discord.Member, time, reason):
    guild = ctx.guild
    muteRole = discord.utils.get(guild.roles, name="Muted")

    if not muteRole:
        muteRole = await guild.create_role(name="Muted")

    for channel in guild.channels:
        await channel.set_permissions(muteRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
        await user.add_roles(muteRole, reason=reason)
        await user.send(f'{reason} sebebi ile {time} boyunca mutelendin')
    
    while time > 0:
        t.sleep(1)
        time -= 1
        if time == 0:
            await user.remove_roles(muteRole)
            break
cinder horizon
turbid condor
cinder horizon
#

ahh thenks fo dis

turbid condor
compact lion
turbid condor
#

You will need to convert the time to either int or float depending on your use case

compact lion
#

ok wait

compact lion
turbid condor
#

You will need to check the time string for the respective words and then strip the digit from it and do calculation on it to convert it seconds

compact lion
#

ok ty

unkempt canyonBOT
#
Error handling

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

cold oyster
#

How do I get channel ID by mentioning in like for example I use the command -log_channel #welcome , In my json file it dumps as <#channel_id>

How do I make it dump as channel_id

unkempt canyonBOT
cold oyster
shrewd fjord
cold oyster
#

What I wrote:

@client.command()
@commands.has_permissions(administrator=True)
async def log_channel(ctx, channel):   
    server_id = str(ctx.guild.id)
    server_settings[server_id] = channel
    with open('logs.json', 'w') as logs_file:
        json.dump(server_settings, logs_file)

    await ctx.send(f"Log channel updated to: {channel} for this server.")```
shrewd fjord
#

typehint it

cold oyster
#

wa-

shrewd fjord
#

channel: discord.TextChannel

cold oyster
shrewd fjord
cold oyster
#

Ooo

#

@shrewd fjord

@client.command()
async def credits(ctx):
    creation = 1696967769
    with open("logs.json", "r") as f:
        logs = json.load(f)
    logs = logs[str(ctx.guild.id)]
    channel = logs
    await channel.send("Test")
    await ctx.send(f"Bot was created on <t:{creation}>")```

Give this error:
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'send'```
#

The other command worked

shrewd fjord
#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
cold oyster
#

tysm

shrewd fjord
#

so
channel = ctx.guild.get_channel(logs)

slate swan
#

python bot.py
Traceback (most recent call last):
File "C:\Users\frrrrnamexdbot.py", line 3, in <module>
from discord_interactions import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_interactions'

bro holy shit iim not able to fix this shit im doing all stuff of fixing from 1hr help me plz 😭

#

@shrewd fjord

#

help plz anyone

shrewd fjord
#

follow this gist, if u want to use slash cmd using dpy

lament lily
#

hey im trynig to solve a problem on my telegram bot where should i ask

shrewd fjord
lament lily
#

my telegram bot script*

shrewd fjord
pulsar lance
#

Can someone help me how to make discord bot

lament lily
pulsar lance
#

Can someone help me how to make discord bot

sick birch
pulsar lance
#

Bro I want make bot for my discord server but I don’t know how to make one

lament lily
# shrewd fjord create a post here

I want to create my own Telegram bot. I am not an expert in programming. This is my first project and I am facing this error
C:\Users\dlç\Desktop\TelegramBot>python telegram_bot.py
Traceback (most recent call last):
File "C:\Users\dlç\Desktop\TelegramBot\telegram_bot.py", line 14, in <module>
updater = Updater(token=TOKEN, bot=bot, workers=4)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Updater.init() got an unexpected keyword argument 'token'

this is the script i have :
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, filters

import queue  # Import the queue module

# Replace "YOUR_API_TOKEN" with your actual API token
TOKEN = "API"
CHANNEL_USERNAME = "@username"  # Replace with your channel username

bot = telegram.Bot(token=TOKEN)
update_queue = queue.Queue()  # Initialize the update queue

# Initialize the Updater class with both bot and update_queue 

arguments
updater = Updater(token=TOKEN, bot=bot, workers=4)
dispatcher = updater.dispatcher

# Dictionary to store groups of images with their chat IDs
image_groups = {}

 def store_images(update, context):
chat_id = update.message.chat_id
# Get the list of photos sent by the user
photos = update.message.photo

# Store the images in the dictionary with the chat ID as the key
if chat_id not in image_groups:
    image_groups[chat_id] = []
image_groups[chat_id].append(photos[-1].file_id)
update.message.reply_text("Group of images stored successfully!")
lament lily
# lament lily I want to create my own Telegram bot. I am not an expert in programming. This is...

Register the handler for storing images

dispatcher.add_handler(MessageHandler(filters.photo, store_images))

def send_next_group(context: CallbackContext):
for chat_id, image_group in image_groups.items():
    # If there are images to send
    if image_group:
        # Get the oldest group of images for this chat
        group_to_send = image_group.pop(0)
        # Send the group of images to the channel
        bot.send_media_group(chat_id=CHANNEL_USERNAME, media= 

[telegram.InputMediaPhoto(media=image_id) for image_id in group_to_send])

# Schedule sending the next group of images at the beginning of every 
hour from 9am to 8pm in Morocco time
morocco_tz = pytz.timezone('Africa/Casablanca')
morocco_schedule = 
schedule.every().hour.at(":00").do(send_next_group)
morocco_schedule.run_every(1).day.at("08:00").do(lambda: 
schedule.clear(morocco_schedule))

# Start the bot
updater.start_polling()
updater.idle()
pulsar lance
#

What is this

#

Omg

lament lily
#

is it not alwed ??

pulsar lance
#

I don’t know

sick birch
#

I think it's fine. It's just using the telegram API

lament lily
pulsar lance
#

How can I make one

#

Yea

#

It’s fine

lament lily
pulsar lance
#

How

#

Do you use python

#

Or something else

#

How old are you bro

lament lily
#

yes

pulsar lance
#

Ok

#

Is python good to make bot or js

slate swan
#

Both are, use what you know

sick birch
#

Both are fine. Though discord.py is a bit more advanced IMO

pulsar lance
#

I know both

#

And c++

#

I make this in python edit

#

Bro can I make ai with py

slate swan
pulsar lance
#

Ok

white citrus
#
class TicketMain_One(nc.ui.View):
    def __init__(self, header, textbox, button_one):
        super().__init__()

        self.header = header
        self.textbox = textbox
        self.button_one = button_one
        print("--------")
        print(button_one)
        print(self.button_one)
        print("---------")
        self.b_one = nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)

    #@nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)
    async def b_one(self, button: nc.ui.Button, inter: nc.Interaction):
        inter.response.send_message("HI")```
He is not sending the button
slate swan
#

well you're defining your b_one method then re-defining it inside your constructor method

pulsar lance
#

Bro what app should I use

final iron
shrewd fjord
pulsar lance
#

For

#

Py

pulsar lance
#

Guys can someone send me kick command for discord .py

#

I need one

sick birch
pulsar lance
#

I need kick commands

sick birch
slate swan
# pulsar lance I need kick commands

@bot.command() async def kick(ctx, member: discord.Member, *, reason=None): if ctx.author.guild_permissions.kick_members: await member.kick(reason=reason) await ctx.send(f'{member.mention} has been kicked.') else: await ctx.send('You do not have the required permissions to use this command.')

#

just adjust ur stuff

#

{ "choices": [ "Option1", "Option2", "Option3", "Option4", // Add more options as needed ] }

#

go acc to what ever u need @umbral bay

#

I think autocomplete is called whenever the user edits their input (which can be very often) so opening your file every time is less than ideal

#

might as well open once and cache the results

slate swan
unkempt canyonBOT
#

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

Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.kick).
shrewd fjord
#

I have linked a gist, follow that

slate swan
#

!d discord.app_commands.autocomplete There's an example implementation on the docs. Essentially you're just writing a function that returns a list of choices depending on the user's current input

unkempt canyonBOT
#

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

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

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

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

Warning

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

My previous point simply was that you don't wanna be doing anything too heavy in your autocomplete callback, such as opening files or other blocking tasks, since it can potentially be called very often

sick birch
#

Autocomplete lends very well to memoization and caching btw

#

since it's incremental

vale wing
slate swan
slate swan
nova vessel
#

Can a Discord Bot display video in a VC?

sick birch
nova vessel
# sick birch no

Is there a way around this (not an exploit) but could I do it through an activity?

sick birch
#

no

nova vessel
#

Ouch

sick birch
#

Did you try it and see?

#

Try it out and let us know if there are any errors then

#

Make sure to include full traceback

final iron
#

You have a slash command decorator on an autocomplete function…

#

fruit isn’t defined as well

#

The first issue still persists

pulsar lance
#

Tex

#

❤️❤️

slate swan
#

python bot.py
Traceback (most recent call last):
File "C:\Users\frrrrnamexdbot.py", line 3, in <module>
from discord_interactions import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_interactions'

bro holy shit iim not able to fix this shit im doing all stuff of fixing from 1hr help me plz 😭

final iron
#

It’s basic python

final iron
slate swan
final iron
#

Well you’re not using discord.pys native slash command support

#

You’re using a 3rd party library

slate swan
final iron
#

?

#

Which one of what

slate swan
#

nvm

final iron
#

Auto complete functions generally shoudnt have any decorators

naive briar
#

Why is that? pithink

final iron
#

Probably should rephrase. They shouldn’t have decorators from the discord.py library

#

If you need your own custom decorators it’s fine

#

No

slate swan
# final iron discord.py has built in slash command support

@slash.slash(
name="create-ticket-panel",
description="Create a ticket panel"
)
@commands.has_permissions(administrator=True)
async def create_ticket_panel(ctx: SlashContext):
# Implement logic to create a ticket panel
await ctx.send('Creating a ticket panel.')

im using this rn it stills show same error lmao

python bot.py
Traceback (most recent call last):
bot\bot.py", line 3, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'

#

@final iron

umbral bay
#

is this from chatgpt?

#

because only gpt will suggest you discord_slash

slate swan
brazen raft
umbral bay
#

oh yea i forgot about that

brazen raft
slate swan
#

is it ext.commands.Bot??

brazen raft
#

It's under discord.app_commands and you should already have it if you installed discord.py version 2+

umbral bay
#

from discord import app_commands

brazen raft
#

Bots should have a tree attribute which you can use like @bot.tree.command() to create application commands

#

I think every bot has one initialized but I'm not sure

slate swan
brazen raft
#

I'm guessing what it's called

#

Look it up or wait for me to do it (I'm unreliable)

slate swan
brazen raft
#

In any case, you also need to sync application commands with a guild or wait an hour for them to show up or update

slate swan
slate swan
umbral bay
#

For syncing

async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')
    
    try:
        synced = await bot.tree.sync()
        print(f"Synced {synced} slash commands.")
    except Exception as e:
        print(e)```
slate swan
#

`

Event when the bot is ready

@bot.event
async def on_ready():
try:
await bot.change_presence(activity=discord.Game("Made by melon"))
print(f'Logged in as {bot.user.name}')
except Exception as e:
print(f'Error in on_ready: {e}')`

#

ikr

slate swan
#

slash = SlashCommand(bot, sync_commands=True) ^^^^^^^^^^^^ NameError: name 'SlashCommand' is not defined

wtf

#

holy i hate these errors lmao

#

Why do you even use that outdated stuff

slate swan
#

Step 1: You don't use it as you don't need it

umbral bay
slate swan
#

No need to get some third party stuff

brazen raft
slate swan
umbral bay
#

also that's not syncing anything

brazen raft
final iron
brazen raft
slate swan
final iron
umbral bay
final iron
brazen raft
#

It is possible but I think the client classes provide zero command handling whatsoever

final iron
#

Nah

slate swan
umbral bay
#

also melon this code will not work since it does not have the code of creating the panel

final iron
#

Same as Bot, expect you have to initialise the tree yourself

#

Using Bot automatically does it

slate swan
final iron
brazen raft
#

I guess so. The client classes do have interaction handling, right?

final iron
#

They do

umbral bay
final iron
slate swan
#

again dat fricking error

final iron
#

Here is a short example of how to use discord.py's slash commands as well as general information on them:

https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f

This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.

NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.

slate swan
final iron
#

You’re using a 3rd party library

brazen raft
umbral bay
#

melon send your code

slate swan
slate swan
brazen raft
#

Remove line number eleven

slate swan
slate swan
final iron
slate swan
final iron
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

brazen raft
slate swan
#

line 51, in <module> @bot.tree.command( ^^^^^^^^^^^^^^^^^ TypeError: CommandTree.command() got an unexpected keyword argument 'options'

😭

final iron
brazen raft
#

Well yeah a lot of steps need to be done

final iron
# slate swan wtf?

This isn’t how coding works. You can’t just randomly add things and expect it to work. Read the guide

brazen raft
#

@slate swan change your bot's token now

slate swan
#

what command should i use tho?? @bot.tree.command or what?

slate swan
slate swan
final iron
#

It literally explains everything

slate swan
final iron
#

It’s not

slate swan
final iron
#

It’ll be way faster than completely restarting your code, and having somebody spoonfeed everything to you

slate swan
final iron
slate swan
#

sorry im too irritating xd

final iron
slate swan
#

python bot.py
[2023-10-11 23:20:40] [INFO ] discord.client: logging in using static token
[2023-10-11 23:20:43] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: e917732981d7690bdf7ea63a667650b9).
Logged in as BotX-acc-lister

holy

#

lol

final iron
#

What are you asking for specifically? How to create options?

#

What are the files? Python files?

shrewd fjord
#

What your code rn?

slate swan
final iron
#

I have a dict with the select option as the key, and a function as the value

#

Well the function object

shrewd fjord