#discord-bots

1 messages · Page 241 of 1

twilit grotto
#

pretty sure it needs to be awaited as well

timber spire
twilit grotto
#

yeah bro where are you even defining client???? 💀 you didnt have it defined in the code you originally sent

timber spire
#

@twilit grotto wdym?

twilit grotto
#

you don't have client defined brodie

timber spire
#

can u send me code defining client, it is making me confuse a lot

#

@twilit grotto

wintry pebble
#
import discord

client = discord.Client()
#

If you're using prefix cmds (So you need the message intent):

import discord

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

client = discord.Client(intents=intents)

Just make sure this is enabled in the discord developer application settings

twilit grotto
#

^

timber spire
#

@wintry pebble it says wrong token passes

#

but same token works well in another code

twilit grotto
timber spire
wintry pebble
timber spire
#

@wintry pebble

#

token works with this code

#

not with this

#

u here ? @wintry pebble

wintry pebble
timber spire
#

thx ❤️

sturdy dragon
#

Hey guys how do you protects your api keys? Right now I’m adding them to a seperate config module which is added to git ignore. What is best practice ?

timber spire
#

@wintry pebble

#

whats this error now? 😭

slate swan
#

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

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.

past prism
#

I am facing this error, idk why

#
  File "C:\Users\jashv\OneDrive\Desktop\Discord Bot\main.py", line 3, in <module>
    from discord import app_commands
  File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\__init__.py", line 12, in <module>
    from .commands import *
  File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 50, in <module>
    from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)```
slate swan
frank willow
#

it responding with 404 indicates that it's up, no?

slate swan
#

i am making a command to timeout ppl which searches if the author has required perms but i am faced with an error

#
 if not ctx.author.guild_permissions.timeout_members:
        embed = discord.Embed(
            title="Missing Perms",
            description=f"{ctx.author.mention}, you don't have enough perms."
        )
...```
#

timeout_members does not exist

#

i understand the problem but don't know the solution

#
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\user\PycharmProjects\pythonProject\all projects\Mod bot\Mod bot.py", line 129, in mute
    if not ctx.author.guild_permissions.timeout_members:
AttributeError: 'Permissions' object has no attribute 'timeout_members'

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

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\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: AttributeError: 'Permissions' object has no attribute 'timeout_members'
#

here's full error

reef gazelle
slate swan
#

you are importing a name, which doesn't exist in the discord library. so either discord py isn't fully installed or the name doesn't exist

unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

thin raft
#

let me check docs

past prism
#

alright

thin raft
#

!d discord.app_commands.Choice

unkempt canyonBOT
#

class discord.app_commands.Choice(*, name, value)```
Represents an application command argument choice.

New in version 2.0.

x == y Checks if two choices are equal.

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

hash(x) Returns the choice’s hash.
thin raft
#

send code

#

which dpy version do you have?

slate swan
thin raft
slate swan
thin raft
#

I won't

slate swan
#

bruh

#

its a meme

reef gazelle
#

the ending 💀 ahah

slate swan
#

i edited it

reef gazelle
#

not bad

south burrow
lean harbor
#

!pastebin

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.

zenith robin
polar lichen
#

I would like to have several discord bots online at the same time I am programming on pycharm can someone tell me how to do it

slate swan
twilit grotto
reef gazelle
#

Can I use on_ready in an extension?

slate swan
reef gazelle
#
from discord.ext import commands

@commands.command()
async def economy_base(self):
    pass

async def setup(bot):
    bot.add_command(economy_base)

    ```
#

This sound? Gonna use it to contain the DB setup

polar lichen
#

Yes*

thin raft
#

or if you just need to send api calls I would just use discord's api

thin trout
#

im using ffmpeg on a ubuntu server and it didn't work, can someone help me?

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") for the *coro* to run in. The current context copy is created when no *context* is provided.

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

Note

[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task "asyncio.TaskGroup.create_task") is a newer alternative that allows for convenient waiting for a group of related tasks.
vale wing
molten hare
#

!d asyncio

unkempt canyonBOT
#

Hello World!

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

asyncio.run(main())
```...
molten hare
#

!d PIL

tired notch
#

from my understanding you can make buttons like this in discord.py

class Example(View):
  def __init__(self):
    super().__init__()
  @discord.ui.button(label="test", style=discord.ButtonStyle.blurple)
  async def test(self, interaction: discord.Interaction, button_object: discord.ui.Button):
    await interaction.response.send_message("hello")```
i'm wondering if its possible to have a button stored in a variable like an object? also im not sure exactly how this works behind the scene
molten hare
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

lavish cradle
#

sombody know how to make (try my command)??
discord.py

upbeat gust
tired notch
#

how

upbeat gust
#

Heres an example

class CounterButton(discord.ui.Button):
  def __init__(self, label='0', **kwargs):
    super().__init__(label=label, **kwargs)
    self.counter = 0

  async def callback(self, interaction: discord.Interaction):
    self.counter += 1
    self.label = self.counter
    await interaction.response.edit_message(view=self.view)

view = discord.ui.View()
view.add_item(CounterButton(style=discord.ButtonStyle.primary))
view.add_item(CounterButton(style=discord.ButtonStyle.success))
view.add_item(CounterButton(style=discord.ButtonStyle.danger))

await ctx.send('Click counter button below', view=view)```
#

You can subclass ui.Button

lavish cradle
smoky sinew
echo wasp
#

How do you make the bot return with only you can see this message with slash commands?

upbeat gust
echo wasp
#

Never seen that

upbeat gust
echo wasp
north kiln
#
interaction.response.send_message('Some message', ephemeral=True)
echo wasp
#

Nvm found it in the docs

sturdy dragon
sturdy dragon
#

I couldnt figure it out

echo wasp
sturdy dragon
#

ahhh yeah,

#

the only way I could find was permissions

#

I guess its impossible in a text channel where others can read messages

lean harbor
slate swan
#

Why is it showing this stuff when I try to install

#

@echo wasp

mossy bluff
#

How do I send a link to a command?

#

Like when someone clicks the link the command is typed for them

white fiber
#

Send a link in chat which when clicked, it writes the command in their text box?

#

I don't think that's possible.

mossy bluff
#

I think in some descriptions

north kiln
mossy bluff
#

That /help link types it out in chat when I click it

north kiln
#

read that

mossy bluff
#

So you cant?

white fiber
#

I guess it is possible. I have no idea how you'd do that. Discord never had functionality like that

#

What I notice is what the command seems to be in, it is like an opened spoiler thing which works like the epoch timestamp.

#

Unless you can set up a slash command and have it some sort of </help> format

#

Not sure how they achieved this, but, it is smart.

north kiln
#

well there's a way to do it but it doesn't work on every platform

#

like on browser

#

</some_command_name:0>

#

</some_command_name:0>

white fiber
#

slash command name with its respective id

#

so I was sorta right lol

sturdy fractal
#

guild_subscription_options=discord.GuildSubscriptionOptions.off())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'GuildSubscriptionOptions'

i m getting this error help

slate swan
#

As the error says

#

GuildSubscriptionOptions doesn't exist in discord.py or any other library out there

slate swan
#

It doesn't exist, don't write things that don't exist.

#

So, remove it.

sturdy fractal
#

pithink kk

sturdy fractal
thin raft
#

!d discord.Client.run

unkempt canyonBOT
#

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
sturdy fractal
thin raft
#

do you know python?

sturdy fractal
#

yes

sturdy fractal
twilit grotto
#

show your entire bit of code but be sure to censor your token out

thin raft
#

let him think a bit

thin raft
#

search that exact error in google @sturdy fractal

sturdy fractal
thin raft
#

then I'd personally recommend learning python first

twilit grotto
#

lmfao i just realized.

sturdy fractal
thin raft
#

yeah maybe that's why it doesn't work

sturdy fractal
#

pls help i m getting annoyed now

dim cosmos
thin raft
dim cosmos
#

or is it an actual token

sturdy fractal
sturdy fractal
north kiln
#

if you actually have a token variable then it wouldn't say it is missing

sturdy fractal
#

i m calling it
client.run(TOKEN)

sturdy fractal
#

TOKEN ="MTEwNjQ3NDM3NT6CQSpsipHEadA"

north kiln
#

reset it now

sturdy fractal
north kiln
#

fine

thin raft
#

not a valid token

sturdy fractal
#

....

twilit grotto
#

yeah, tgat part of the token is public from snowflake id

dim cosmos
thin raft
sturdy fractal
thin raft
#

no

dim cosmos
#

wtf are u thinking decoding it with base64

thin raft
twilit grotto
sturdy fractal
twilit grotto
#

or beginning of it

north kiln
#

then perhaps show your code

thin raft
#

u literally can

dim cosmos
#

what's the point in decoding it

sturdy fractal
#

i can just reset it bruh

twilit grotto
#

no shit sherlock…

sturdy fractal
#

just help me with this sh*t

#

i m tired\

thin raft
north kiln
thin raft
#

see, first part of the token should be the bot id

sturdy fractal
thin raft
#

and his first part isn't that

#

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

thin raft
#

paste your code without token

sturdy fractal
thin raft
#

reset the token

sturdy fractal
#

alr

north kiln
#

the last part is the actual secret

twilit grotto
#

oh boy.

dim cosmos
#

bro some people

#

😭

thin raft
sturdy fractal
# thin raft

which this logic people can actually make token gen

thin raft
thin raft
#

?

sturdy fractal
#

check dm

thin trout
thin raft
golden portal
#

your setup function at test.py should be async

#

welcome

vale wing
vapid geode
#

Hi, I'm trying to follow how the discord py bot runs step by step. I cant figure out how to change the default logging level. The default bot_trace_loggers in constants is already set to *.

north kiln
#

I don't recall there's anything called bot_trace_loggers

#

have you read the docs on setting up logging?

vapid geode
molten hare
#

that _ at beginning it's a convention or what?

quasi pawn
#

Hi, I have a question.
Let's say I have a command /command [option1] [option2]. I want the choices for the option2 to change, depending on the value of option 1, Is it possible to access the value of option1, then use it for the option2?

north kiln
#

you can get it using Interaction.namespace['option1']

north kiln
vapid geode
#

At the moment just trying to read the code

#

I'm following the start up "process" for lack of a better term to see how it works

#

as I'm looking throught the code I've seen a few log calls which are being filtered out.

north kiln
vapid geode
#

Ah set from level_filter = constants.Bot.trace_loggers

vapid notch
#

i wanted some help with some code

#

when i try to fetch id using this
host = ctx.guild.get_member(host_id)
it returns me none even tho the id exists and is present in the server

naive briar
#

Do you have members intent

#

Weird

#

!d discord.Intents.members

unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

vapid notch
#

I just added that to the code but still same thing

naive briar
#

Show the code

vapid notch
#

I’ll dm you if thats okay?

naive briar
#

No

vapid notch
#

okay i’ll send it here

#

gimme a bit

#

``bot = commands.Bot(command_prefix='.')
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)

@bot.command()
@commands.has_role(1014148557634289674)

async def winner(ctx, host_id: int, message_id: int):
temp_role = discord.utils.get(ctx.guild.roles, name="commgw cooldown")
host = ctx.guild.get_member(host_id) # Get the Member object
giveaway_message = await ctx.channel.fetch_message(message_id)
giveaway_embed = giveaway_message.embeds[0]

if giveaway_message:
    reactions = [reaction for reaction in giveaway_message.reactions if str(reaction.emoji) == '![bccake](https://cdn.discordapp.com/emojis/1107551026506109039.webp?size=128 "bccake")']
    if len(reactions) > 0:
        participants = []
        for reaction in reactions:
            async for user in reaction.users():
                if not user.bot:
                    participants.append(user)
        if participants:
            winner = choice(participants)
            prize = giveaway_message.embeds[0].description.split('`')[1]
            giveaway_embed.add_field(name="winner", value=winner.mention)
            giveaway_embed.color = 0x3C0C0C
            giveaway_embed.set_footer(text=f'giveaway ended')
            await giveaway_message.edit(embed=giveaway_embed)
            await host.remove_roles(temp_role)                
            await ctx.send(f'Congratulations {winner.mention} ! You won the giveaway of **{prize}** hosted by {host.mention} ![bccake](https://cdn.discordapp.com/emojis/1107551026506109039.webp?size=128 "bccake")')
        else:
            await ctx.send('No one participated in the giveaway.')
    else:
        await ctx.send('No one reacted to the giveaway message.')
else:
    await ctx.send('Invalid message ID.')``
north kiln
#

why don't just typehint discord.Member for host_id

#

It will give you a list of member to choose from

vapid notch
#

im not sure how to do that 😭

#

and what is wrong with this code anyway?
i always get NoneType error

north kiln
#

oh it was a text command

#

you can still @ the user as the input tho

#

or user id whatsoever

#

also the message id can be discord.Message

south burrow
#

whats this
C:\Users\WIN 7\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.15) or chardet (3.0.4) doesn't match a supported version!

lean harbor
#

Anyone know how to sync a / command

thin raft
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

thin raft
#

wtf

lean harbor
thin raft
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
thin raft
#

then .sync

lean harbor
#

What's this

thin raft
#

idk why it doesn0t detect it

lean harbor
thin raft
#

send code

south burrow
# lean harbor Anyone know how to sync a / command

@bot.event async def on_ready(): print(f"We have logged in as {bot.user} and are serving at {len(bot.guilds)} Guilds!") try: synced = await bot.tree.sync() print(f"Synced {len(synced)} command(s)") except Exception as e: print(e)

south burrow
#

yup

north kiln
#

don't sync on ready

#

sync manually with like a text command

south burrow
thin raft
#

sync on setup hook

north kiln
#

you can but only sync when you have changed something

#

but what if you changed the command params during dev

#

then you need to restart the bot

thin raft
#

then restart it?

north kiln
#

you can use a normal command so you don't have to

lean harbor
lean harbor
north kiln
#

it will be called every time you resumed a section

#

making useless calls as you didn't change anything yet trying to sync

lean harbor
#

I'm not gonna type a command to sync it. My bot is ont 24/7 once its synced once there's no need to sync it again

thin raft
lean harbor
#

That

lean harbor
#

How would you make a database? and be able to change the value in the database

proven pendant
#

@stiff fern Hey,, sorry for the ping, I saw that you had asked bout why ur "commands.Cog.listener()" wasnt catching any error

it was cuz we had to pass our app_commands error handler to commandTree
I was wondering if you figured how to pass app_commands error handler to commandTree as I needed help with it

|| p.s. Im so so sorry for the ping, I hope i wasnt disturbing you!||

sick birch
#

(I don't have the full context from your earlier question, BTW)

next quarry
slate swan
harsh marsh
#

My commans is : ```py
@client.command()
async def warstars(ctx, townhall, country):
country = country.lower()
if country in data:
country_code = data[country]
else:
await ctx.send("Invalid country")

url = f"https://www.clashofstats.com/rankings/players/war-stars/{country_code}/{townhall}/1"
response = requests.get(url)
html_content = response.text

soup = BeautifulSoup(html_content, 'html.parser')
elements = soup.find_all("a", class_="no-link", href=lambda href: href and href.startswith("/players/"))

if len(elements) >= 3:
   random_a_elements = random.sample(elements, 3)
   
   #embed = discord.Embed(title=f"3 WarStars accounts local {country}, townhall {townhall}", description=None)
   await ctx.send(f"3 WarStars accounts local {country}, townhall {townhall}")
   for a_element in random_a_elements:
       tags = a_element['href']
       pattern = r"/players/(?:.*\-|)([^-]*?)\/"
       matches = re.findall(pattern, tags)
       for match in matches:
           #embed.add_field(name=None, value=match)
           await ctx.send(match)
           #await ctx.send(embed=embed)
else:
       await ctx.send("Pas assez d'éléments <a> trouvés.")```
twilit grotto
#

you can make a list of embeds to send iirc

#
await ctx.send([listofembeds])
harsh marsh
#

i want to send just 1 embed

#

with the 3 generated values

twilit grotto
#

ahh ok one sec

#
@client.command()
async def warstars(ctx, townhall, country):
    country = country.lower()
    if country in data:
        country_code = data[country]
    else:
        await ctx.send("Invalid country")
    
    url = f"https://www.clashofstats.com/rankings/players/war-stars/{country_code}/{townhall}/1"
    response = requests.get(url)
    html_content = response.text
    
    soup = BeautifulSoup(html_content, 'html.parser')
    elements = soup.find_all("a", class_="no-link", href=lambda href: href and href.startswith("/players/"))
    
    if len(elements) >= 3:
        random_a_elements = random.sample(elements, 3)
        
        embed = discord.Embed(title=f"3 WarStars accounts local {country}, townhall {townhall}")
        description = ""
        for a_element in random_a_elements:
            tags = a_element['href']
            pattern = r"/players/(?:.*\-|)([^-]*?)\/"
            matches = re.findall(pattern, tags)
            for match in matches:
                description += match + "\n"
        
        embed.description = description
        await ctx.send(embed=embed)
    else:
        await ctx.send("Pas assez d'éléments <a> trouvés.")

```try this
harsh marsh
harsh marsh
twilit grotto
harsh marsh
twilit grotto
#

bro what?

harsh marsh
#

i have no idea

#

i want the last embed to be smthg like value1 = tag1
value2 = tag2
value3 = tag3

twilit grotto
#

yea i know what you want, the code i sent should only be sending 1 embed with all 3 values in it thats why im confused lmao

simple plume
#

So my BOT is storing is own messages, I tried that but isn't working and I don't have any idea why.. Can somebody explain and help me?

smoky sinew
#

especially since your commands might not have been loaded by the time setup_hook is called

thin raft
#

i've been doing it wrong this whole time then

tired notch
#

whats an ephemeral message

smoky sinew
tired notch
#

does it always have to be after an interaction

finite abyss
#

so when i try to do a command that's not in my python code or whatever it shows me this thing

#

does anyone know how to rename it and make it my own?

smoky sinew
unkempt canyonBOT
#

class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).

This means that relying on the state of this class to be the same between command invocations would not work as expected.
smoky sinew
#

extend this and set bot.help_command

finite abyss
#

ok ty

slate swan
finite abyss
smoky sinew
#

you can also just remove the default help command and make your own

rain stream
vale wing
#

Being in Sam's shoe mustn't be very pleasant 🥶

naive briar
#

🐈

lean harbor
#

how to fix this?

vale wing
#

Afraid that's lib issue you can't really fix, maybe there are type stubs you could search for

thin raft
#

just ignore it

surreal ridge
#

heyy

#

anyone know about discord bots?

vocal snow
surreal ridge
#

yes

#

my client wants me to retrieve some data from discord based on some keywords

#

like if he enters "crypto" he should get servers related to crypto

#

I need an API service for this

vocal snow
vale wing
#

It does exactly that and is embedded into discord interface

surreal ridge
#

nah, he needs it in his website: polkadotspace.netlify.app

#

so, only API

honest shoal
#

can bots read embed content?

honest shoal
#

I use disnake

vocal snow
#

all the attributes are listed in the docs

honest shoal
#

Oh alright

#

thanks!

primal maple
#

Hi

slate swan
#

Hi

slate swan
#

how do i read this with json?

idle lantern
slate swan
#

why do hyperlinks not work

#

oh nvm oops

slate swan
#

Hello can you help me for this error

sick birch
#

Create slash commands?

slate swan
#

I try to run the bot but it gives me this problem

#

@sick birch

sick birch
#

Yeah, but what's the purpose of the bot? What's it supposed to do?

slate swan
#

verify paypal purchase

sick birch
#

With slash commands?

slate swan
#

yes

sick birch
#

You don't need all that for slash commands, discordpy has native built in support

#

I can't get the link at the moment but the GitHub has a bunch of examples

slate swan
#

how to fix this error?

slate swan
keen talon
slate swan
slate swan
#

And? Read

#

That's how you make the most basic slash commands

#

i need fix error

#

i dont need slash commands

#

No need of Client and no need of SlashCommand thingy that is some weird third party library

slate swan
#

You don't know yourself what you want apparently

#

this bot has slash commands, the problem is that when I try to run the bot it doesn't work, there is a problem

#

Error says it all

#

Missing intents kwarg

#

Also you don't need bot and client

#

It's either bot or client

#

Not both

#

So delete the entire client line

#

And add intents=... in our bot instance you create

#

As well as replace client to bot in that weird and useless SlashCommand thing

#

right?

#

No?

#

I told you

#

So delete the entire client line

#

And add intents=... in our bot instance you create

#

E.g.

bot = Bot("!", intents=whatever)
#

think_blob intents = bot

#

do you guys help with javascript too or

cloud dawn
#

What even is a slashcommand object?

slate swan
#

Just like you have in client at the moment

slate swan
#

Then you know the answer bravemmlol

slate swan
cloud dawn
slate swan
#

Not a JS server

#

python isnt the only language yk

slate swan
#

multiple people can know it

#

There are JavaScript servers

#

Python servers are for Python related questions

cloud dawn
slate swan
#

or just

slate swan
#

Do you know Python or are you copying that code from somewhere without knowing what it does at all?

#

Stragar homie I mean this in the nicest way possible but I think you have some Python practicing to do before Discord bots

#

bro

#

Because it doesn't seem like you know, as you just copied whatever in your code without knowing I mean the entire discord.Intents.all() thing

#

the bot is not mine

#

!resources then

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.

slate swan
#

discord.py is not meant for beginners, that's mentioned in their README as well

#

Take the time to learn at least the basics of Python

turbid condor
cloud dawn
slate swan
slate swan
#

Then you can open an issue on the GitHub repository where you got the bot

turbid condor
cloud dawn
slate swan
slate swan
turbid condor
#

XD

slate swan
#

Open an issue there if you don't know how to fix it

turbid condor
#

There is nothing as slash_command in dpy

cloud dawn
# slate swan

Replace bot = Bot("!") with bot = Bot("!", intents=discord.Intents.all())

slate swan
#

There isn't, that's why the bot used some random third party library to have it and be able to use slash_command

#

So yes, in their case it exists

#

Worth noting the last commit date - which explains the use of outdated things

slate swan
#

My point again, that's 2 years old code that won't work with the current discord.py 2.x version

turbid condor
#

Zz the code is out dated

cloud dawn
slate swan
#

Open an issue on the repository to get the author to migrate it to 2.x version

#

Fix it yourself by learning basic Python beforehand, or find something different

cloud dawn
#

This code was written in the dark days of discord.py

slate swan
slate swan
# slate swan
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

client.run(TOKEN)```
turbid condor
#

His code is pretty old

slate swan
#

just replace bot = Bot("!") with what i sent

turbid condor
#

I'd say recheck the code

slate swan
#

how i integrate the db into my discord bot?

#

i don't know how i do it, i'm seeing a tutorial that uses psycopg2, but someone that seems experient is teeling me to use asyncpg, well, i will need to learn it (thought it makes sense since discord bot uses asynchronous function)

cloud dawn
slate swan
slate swan
#

guys, anyone have a sample to implement my database as a fundamental cog (or just as cog)?

slate swan
#

guess now i can see how i can implement it

#

but first i need to know something about discord bot

#

that is an @twilit aspen that i could use to make it auto-run

#

like when it initiate the cog it already runs the database thing

#

maybe in __init__?

digital sentinel
#

Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\main bot\main.py", line 33, in <module>
bot = commands.Bot(prefix="prefix")
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'

#

i'm having this error can some1 help me?

slate swan
#

bot = commands.Bot(prefix="-", intents=discord.Intents.all())

digital sentinel
#

same error

#

Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\main bot\main.py", line 33, in <module>
bot = commands.Bot(prefix="-", intents=discord.Intents.all())
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix

slate swan
#

mb

#

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

digital sentinel
#

it's worked

slate swan
#

good job

digital sentinel
#

thanks

slate swan
#

np

plucky sun
#
Traceback (most recent call last):
  File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\KokoG\PycharmProjects\Logger\main.py", line 84, in button_callback
    await interaction.channel.send(MyModal(title="Modal via Button"))
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\KokoG\PycharmProjects\Logger\main.py", line 72, in __init__
    self.add_item(discord.ui.InputText(label="Short Input"))
                  ^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.ui' has no attribute 'InputText'

``` how to fix error ?
#

code: ```class MyModal(discord.ui.Modal):
def init(self, *args, **kwargs) -> None:
super().init(*args, **kwargs)

    self.add_item(discord.ui.InputText(label="Short Input"))
    self.add_item(discord.ui.InputText(label="Long Input", style=discord.InputTextStyle.long))

async def callback(self, interaction: discord.Interaction):
    embed = discord.Embed(title="Modal Results")
    embed.add_field(name="Short Input", value=self.children[0].value)
    embed.add_field(name="Long Input", value=self.children[1].value)
    await interaction.response.send_message(embeds=[embed])

class MyView(discord.ui.View):
@discord.ui.button(label="Send Modal")
async def button_callback(self,interaction: discord.Interaction, button: discord.Button):
await interaction.channel.send(MyModal(title="Modal via Button"))

@bot.command()
async def send_modal(ctx):
await ctx.reply(view=MyView())

slate swan
#

i did something wrong here:

#

did you install it?

#

nevermind, Jackpot:

slate swan
whole shoal
#

Is there a way to wait_for for an interaction?

idle lantern
#

How can I make a system to check if a user is already registered without putting a function before every command to check if they do?

slate swan
#

okay, it's almost close for me to finally implement:

idle lantern
#

Rename your files

slate swan
#

my file... uhmm, strange

#

okay, it's kinda confuse

#

you mean my .py files?

#

like bot.py to sometihng else and shit?

#

@idle lantern

whole shoal
#

So I'm making something in which the users will have their turn to press a button and as soon as the button is pressed, the program will continue, until then it will be paused? Any way of doing it?

hushed galleon
#

!d discord.ui.View.wait

unkempt canyonBOT
#

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

Waits until the view has finished interacting.

A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop "discord.ui.View.stop") is called or it times out.
whole shoal
#

Let me check thanks

hushed galleon
#

or perhaps an easier solution, depending on what you're doing, is to run whatever code is necessary in the callback of your button

idle lantern
#

Because there are some modules with files by those names such as database

hushed galleon
#

their error is a circular import though

slate swan
hushed galleon
#

i would recommend using a context manager to open your database pool instead, that way you cant forget to close it afterwards ```py
async def main():
async with asyncpg.create_pool(...) as pool:
bot.db = pool
await bot.start(token)

asyncio.run(main())```

slate swan
#

the problem is me removing theload thing, but let me see this

idle lantern
#

I made a file called discord.py and when i imported discord module into it I got circular error

hushed galleon
#

right, because if you use import discord inside a script named discord.py, its going to try importing itself

slate swan
hushed galleon
#

well you already have half the work done there, you just need to connect your database

slate swan
hushed galleon
#

do you see how my example connects to the database?

slate swan
#

oh, now i see

#

like this:

#

the bot starting would be at the own bot, but i don't know if i need to make the bot.start thing

#

okay, another error:

#

you need to assign the .db to the bot varriable not bot module

hushed galleon
#

handling the connection in the same place as your main() function is going to be more convenient than trying to write it in a separate module

slate swan
#

i'm planning to make the database thing in a separated class

#

you should move it to the main file

#

like, it's to prevent spagetti code

#

cus my bot will use a lot of database

#

you can have database logic outside but connect to it in main file

#

oh i see

hushed galleon
#

so how does moving a couple of lines from your bot.py file to a separate file make it less spaghetti?

slate swan
#

and how do i disconect after stopping the bot?

hushed galleon
#

if you use async with, it automatically cleans up the connections for you

slate swan
hushed galleon
#

if you really wanted to put the function elsewhere, the easier option is adding a parameter to your create_db_pool() function to pass your bot instance, rather than trying to import it from the same file that wants to call it

slate swan
#

parameter... uhmm, i don't knw if it's about public, private thing

#

or protected

#

but i guess protected would be saifier

#

who knows?

hushed galleon
#

those concepts dont exist in python, and those are related to class members, not function parameters

#
def setup_bot_db(bot):
    #            ^^^ parameter, i.e. an input to your function
    pool = await asyncpg.create_pool(...)
    bot.db = pool```
slate swan
#

i see, it don't use async

hushed galleon
#

oops

slate swan
#

nevermind then

slate swan
hushed galleon
#

what object do you want to assign your database pool to?

#

also it was a demonstration, i still recommend writing the async with syntax in your bot.py file

slate swan
#

XD, completely lost, i'm like the a child in a forest

#

here goes nothing:

desert imp
#

Hello, wondering if somebody knows what I've done here,
I wrote some code, quite some time ago, to prevent people that aren't developers on my project from running specific commands. Only I find that now I don't remember why I wrote it like this, I put a function inside of a function to test for these users. The code works, I just wondered if it's written like this because it needs to be, or if there is a tidier way of writing this function.

#

Developer only command example:

hushed galleon
#

i would additionally sync your command to one guild where only your devs can see it

desert imp
#

Oh? That's possible?

hushed galleon
#

!d discord.app_commands.guilds

unkempt canyonBOT
#

@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.

When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree"), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.

Note

Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command") or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu "discord.app_commands.CommandTree.context_menu") decorator then this must go below that decorator.

Example...
hushed galleon
desert imp
#

Well well, learning something new once again, thank you very much

slate swan
#

okay trying those ones:

#

but fail:

twilit grotto
# slate swan but fail:

right click on 'rpudb' and see if it takes you back to your class, if not then somethings interfering & also, its an async function in your class, you need to await it when calling it

slate swan
#

if i click to go to definition it get me back to my class

hushed galleon
#

you have a module named rpudb.py and a class inside it named rpudb, but you are incorrectly referencing the module rpudb instead of the class rpudb.rpudb

#

also you're closing the pool right afterwards by leaving the indented async with block

twilit grotto
#

ah yeah i didn't realize that

slate swan
#

if that's the case how i can prevent it from closing?

#

i'm planning to use the db in cogs

#

guess that part i would need to implement in cogs instead of in bot

hushed galleon
#

thats a different error meaning you're trying to use a variable that isnt yet defined

slate swan
#

if your way it worked:

hushed galleon
#

seriously, why not use create_pool() inside main()?

slate swan
hushed galleon
#

er, you're still closing the pool before your bot has even started

slate swan
#

i see

#

guess the starting thing i need to put inside the async thing

#

imnw

#

in this way i got into an eternal loop

#

now i had an idea, instead of opening the database directly through my main, the database could be momentaneously opened once a person wants to create a character, edit a character, and etc

#

it would economize in processing time

#

oh, now i got you

#

you mean that need to declare it before initiating it inside

#

but the problem is in which i need to declare it?

#

as a string?

#

number?

#

list?

#

well, in doubt improvise

#

time to search for wild variable declaration

hushed galleon
slate swan
#

well, now i need to declare the rpu_db before the async thing

#

but since i don't know which declaration is correct (cus i don't know if it's a list, number or string) i will search to turn that variable a wildcard

hushed galleon
#

i have no idea what you're talking about

slate swan
#

the box here:

hushed galleon
#

you're assigning the pool to rpu_db which is a local variable, so you will be unable to access it outside of main()

slate swan
#

yes, that's why i want to declare it before

#

i want to declare rpu_db as something that it is compatible

hushed galleon
#

i dont see how that would fix your issue

slate swan
#

string, number or list

hushed galleon
#

you mean you want to define rpu_db as a global variable?

slate swan
#

but as compatible to the thing

#

string, number or list

hushed galleon
#

variables are dynamically typed so it doesnt matter what you assign it to, and i wouldnt bother mocking your connection pool object anyway since it should be an error to try using the database before its connected

slate swan
#

hi

hushed galleon
#

a global rpu_db statement would be sufficient to assign it as a global variable, though "bot vars" are usually a better choice since you can access them from anywhere you have the bot instance

slate swan
hushed galleon
#

e.g. use client.pool = pool, then anywhere you have the client you can acquire a connection with async with client.pool.acquire() as conn

finite abyss
#

hi so im trying to do a game similar to russian roulette and this is the code and the error i've been getting

#

TypeError: Client.event() missing 1 required positional argument: 'coro'

#

does anyone know how to fix this?

slate swan
#

also the game cracker, if you want you can mock, since it's a beginner error, i would even make a meme about it

#

like: when it's your first time learning postgresql

dry kelp
#

I think you should use TORTOISE_ORM to load all your data

#
from os import getenv
from typing import Any, cast

from dotenv import load_dotenv
from dynaconf import Dynaconf

load_dotenv()


class Settings:
    """# Global settings file
    Fields:
        => bot
           -> token
           -> env
        => log
           -> level"""

    class Bot:
        token: str
        env: str

    class Log:
        level: str

    emojis: Any
    partialemojis: Any
    colors: Any
    log: Log


settings = cast(
    Settings,
    Dynaconf(
        envvar_prefix="SPOOKY",
        load_dotenv=True,
        merge_enabled=True,
        settings_files=[
            "assets/settings/colors.toml",
            "assets/settings/emojis.toml",
        ],
    ),
)

TORTOISE_ORM = {
    "connections": {
        "default": {
            "engine": "tortoise.backends.asyncpg",
            "credentials": {
                "host": getenv("DB_HOST"),
                "port": getenv("DB_PORT"),
                "user": getenv("DB_USER"),
                "password": getenv("DB_PASS"),
                "database": getenv("DB_NAME"),
            },
        }
    },
    "apps": {
        "Bot": {
            "default_connection": "default",
            "models": ["aerich.models", "spooky.models"],
        }
    },
}
#

This is how i load my data, I think it will help you for a better logic

slate swan
finite abyss
#

i removed the brackets and wrote choice bcs i wrote it wrong

#

program?

#

pycharm

slate swan
#

like what pip did you run to get this?

#

like pip install xxxxx

#

what did you install for this package

finite abyss
#

uhh pip install discord

#

and some other stuff

slate swan
#

okay so discordpy

finite abyss
#

yes

slate swan
#

Honestly that's not how commands should work. Don't do an event, there are already built in functions for commands.

finite abyss
#

oh

#

so how should i write it

#

im a beginner

slate swan
#

Yeah that's fine.

pulsar elbow
#

thats the error

slate swan
#

Yeah that, but you shouldn't even use an event.

slate swan
pulsar elbow
#

idk why hes not using discord.ext.commands.bot

#

thats the error

finite abyss
#

from discord.ext import commands

pulsar elbow
#

i know dpy, i use it

finite abyss
#

i have this

pulsar elbow
#

sebass

slate swan
pulsar elbow
#

remove the () from @client.event

finite abyss
#

i did

slate swan
#

Yes but still, don't do commands like that dude

finite abyss
#

i just stared like 2 days ago xd

dry kelp
#

@finite abyss could you send me your entire code?

pulsar elbow
#

use @bot.command()

slate swan
#

@finite abyss can you show me your whole code without the token? I'll show you how you do it with commands.

finite abyss
#

dm or here?

pulsar elbow
#

post it here

finite abyss
#

should i just copy paste?

pulsar elbow
#

tes

slate swan
#

put it in in code

#

Put it in code man

finite abyss
#

oh

pulsar elbow
#

why are u randomly using on_message for that

#

and only that command

finite abyss
#
import discord
from discord.ext import commands
import random


client = discord.Client(intents=discord.Intents.default())
bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())

@bot.event
async def on_ready():
    print('The bot is now online!')

@bot.command()
async def hello(ctx):
    await ctx.send('Hello!')

@bot.command()
async def alex(ctx):
    await ctx.send('Alex e prost!')

@bot.command()
async def stramb(ctx):
    await ctx.send('Darius o are stramba rau de tort')

@bot.command()
async def dacian(ctx):
    await ctx.send('But does this hurt Ciolos?')

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

@bot.command()
async def roll(ctx):
    await ctx.send(random.randint(1, 1000))

@bot.command()
async def helpme(ctx):
    await ctx.send('`Come here for more help!: https://www.youtube.com/watch?v=dQw4w9WgXcQ`')

@client.event
async def on_message(message):
    if message.content.startswith('.chance'):
        chambers = [0, 0, 0, 0, 0, 1]
        random.shuffle(chambers)

        player_chamber = random.choice(chambers)
        chambers.remove(player_chamber)

        await message.channel.send('`The trigger is pulled...`')

        if player_chamber == 1:
            await message.channel.send('`Ops, you are dead! Better luck next time!`')
        else:
            await message.channel.send('`Click! You survived!. You can try again if u dare!')
pulsar elbow
#

tell us why

finite abyss
#

idk

#

i told u i just stared

#

idk how this works at all

slate swan
#

look, you know how to use bot.command() when you use it for everything else.

pulsar elbow
#

btw on_message will break all ur other commands

#

if u dont have a bot.process_commands()

slate swan
#

wtf....

pulsar elbow
#

nvm he used client and bot

slate swan
#

u define bot and client.

pulsar elbow
#

that code is cursed bro.

slate swan
#

ikr

finite abyss
#

XDDD

slate swan
finite abyss
#

ohh

#

okok

pulsar elbow
#

theres no reason to be using discord.Client()

#
@bot.command()
async def chance(ctx):
    chambers = [0, 0, 0, 0, 0, 1]
    random.shuffle(chambers)

    player_chamber = random.choice(chambers)
    chambers.remove(player_chamber)

    await ctx.send('The trigger is pulled...')

    if player_chamber == 1:
        await ctx.send('Oops, you are dead! Better luck next time!')
    else:
        await ctx.send('`Click! You survived!. You can try again if u dare!')
#

use this instead @finite abyss

finite abyss
#

ohh

#

so the same as the other commands

slate swan
#

yep

#

Yes ofcourse

finite abyss
#

ohhhh now i get it

#

it was so obvious wtf

slate swan
#

This command is a command just llike the others, there is no need to make it distinct.

finite abyss
#

im dumb af

slate swan
#

you're not.

#

Just read docs man.

pulsar elbow
#

wait

finite abyss
#

ty

pulsar elbow
#

wouldnt u have to define player_chamber outside

#

the command

#

wouldnt it just reset every time

slate swan
pulsar elbow
#

the player_chamber

slate swan
#

oh wait yeah

pulsar elbow
#

yeah

#

he needs to make it a global

slate swan
#

there is no point of removing it from the chamber, it will be redefined before that logic does anything.

pulsar elbow
#

and have a separate function choose a random one

slate swan
#

wonkey donkey code

finite abyss
#

im ashamed of my code

slate swan
#

lol y so rude

pulsar elbow
#

make a dict that stores their userid as the key and the list of chambers they have as the value

slate swan
#
import random
from discord.ext import commands

chambers = [0, 0, 0, 0, 0, 1]

@bot.command()
async def chance(ctx):
    global chambers
    random.shuffle(chambers)

    player_chamber = random.choice(chambers)
    chambers.remove(player_chamber)

    await ctx.send('The trigger is pulled...')

    if player_chamber == 1:
        await ctx.send('Oops, you are dead! Better luck next time!')
    else:
        await ctx.send('`Click! You survived!. You can try again if you dare!')

    if len(chambers) == 0:
        chambers = [0, 0, 0, 0, 0, 1]  # Reset the chambers if all have been used
#

boom, fortnite gamer in the building.

glad cradle
#

!global

unkempt canyonBOT
#
Globals

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

pulsar elbow
#

would be better to have a per guild or per user one

slate swan
#

why else would he remove it from the chamber? Russian roullete is a group game, you go around and eventually one gets shot.

#

but yeah, per server is probably ideal.

pulsar elbow
#

server is called guild in dpy right

slate swan
#

yes

pulsar elbow
#

ok wait

smoky sinew
#

why global

pulsar elbow
#

because otherwise it would reset

smoky sinew
pulsar elbow
#

every time the command is called

smoky sinew
pulsar elbow
#

then whats the solution

slate swan
#

Here's a solution

pulsar elbow
#

yeah theres a solution

slate swan
#

(shamelessly plugging my own website in a solution)

#

@finite abyss this works.

pulsar elbow
#

i think its best to use a set instead of a list

#

so its more intense odds

slate swan
#

👍

pulsar elbow
#

nvm i forgot random.choice() doesnt work on sets

slate swan
#

I'm not telling you how to do it, this is merely a demo, do with it as you work.

finite abyss
#

fine

slate swan
#

sick

slate swan
#

it works but its probably not guild-specific

finite abyss
#

how can i change the bot text colour?

smoky sinew
slate swan
#

okay since i can't create folders into my database and neither create dynamically new tables for it i'm gonna discard the idea of using database

#

time to use the good old json files

slate swan
#

You can most definitely do this

sick birch
#

If you tell us more about what you're doing, we can help you sort out a database model

slate swan
#

giving it tools for roleplayers and roleplay discord servers

#

like creating characters, delete characters, edit characters

#

create template, delete template, edit template

sick birch
#

This is pretty common. Why do you need dynamic tables for this?

slate swan
#

and also have macros

slate swan
sick birch
#

I'm still not seeing a problem

slate swan
#

sometimes the template can look like this:

Name:
Age:
Gender:
Alignment:
Strenght:
Weaknesses

or like this:

Name:
Age:
Gender:
Alignment:

Height:
Weight:
Eye Color:
Hair Color:
...
#

like, many servers can create their own templates from their own multiple minds

#

and my plan is to make it unique

sick birch
#

Oh I see

slate swan
#

and really versatile to many servers

sick birch
#

I believe postgres has a JSONB type you can use for unstructured data

slate swan
#

well, anyways i'm gonna get back to json files

#

it would be more organized

sick birch
#

I really doubt that, JSON as a database is a terrible idea

#

Would 100% recommend postgres + jsob blob type

slate swan
#

can i create folders using json postgres?

sick birch
#

What do you need folders for?

slate swan
#

to separate macros, template and characters by folders and inside those folders it has each player's id with their own stuff

sick birch
#

E.g a player_id column

slate swan
#

that can work, but it would be messy though... But can work

gloomy meadow
#
import discord
import discord.ext.commands
from discord.ext.commands.context import Context
from utils import Control
import utils

intents = discord.Intents.default()
bot = discord.ext.commands.Bot(command_prefix=['!'], intents=intents)


class Bot:
    TOKEN = utils.PASSWORD

    def __init__(self):
        Bot.mcr = Control()
        Bot.command_await: bool = False
        Bot.status_requested: bool = False

    def run(self):
        bot.run(Bot.TOKEN)

    @bot.command(name='help')
    async def get_status(self, ctx: Context):
        await ctx.send('...')


def launch():
    bot_mgr = Bot()
    bot_mgr.run()


if __name__ == '__main__':
    launch()

I seriously can't figure why the bot doesn't do anything when I type !help

#

what am I doing wrong?

smoky sinew
gloomy meadow
naive briar
#

Subclass the bot class

gloomy meadow
#

great to know it's a thing

naive briar
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
gloomy meadow
#

hah

#

question btw

smoky sinew
#
INTENTS = discord.Intents.default()
INTENTS.message_content = True

class Bot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(
            command_prefix="!",
            intents=intents,
        )

bot = Bot()

@bot.command(name="help")
async def get_status(ctx: commands.Context) -> None:
    ...
gloomy meadow
#

if I want to have the bot handle commands asynchronously, meaning not blocking, what should I do? Because if one command is in execution another command won't execute until the one before finishes

smoky sinew
#

it already is asynchronous

gloomy meadow
#
import discord
import discord.ext.commands
import discord.ext.commands as commands

import utils


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


@bot.event
async def on_ready() -> None:
    print(f'Logged in as {bot.user.name}')


@bot.command(name='test')
async def test(ctx: commands.Context) -> None:
    await ctx.send('test')


if __name__ == '__main__':
    bot.run(utils.PASSWORD)

I'm trying to write a bot as simple as that and it literally doesn't output anything when typing !test. I don't know what causes that, can anyone help me please?

upbeat gust
#

you should have a warning about that in your terminal-

gloomy meadow
upbeat gust
#

exactly

gloomy meadow
#

right. I'll read about it then. Thanks

gloomy meadow
smoky sinew
gloomy meadow
tranquil badge
#
@commands.hybrid_command(name='img', description='High quality images of the ships.')
    async def img(self, ctx: commands.Context, ship: str):
        s_obj = process.extractOne(ship, sql_ship_obj())
        ship_embed_title = f"{customemoji(ctx, s_obj['rarity'])} {s_obj['name']}"
        col = int(s_obj['colour'], 16)
        embed = discord.Embed(
            title=ship_embed_title,
            colour=col)
        embed.set_image(url=get_ship_image(s_obj['number']))
        await ctx.send(embed=embed)
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'int' has no len()```
Not exactly sure what i need to fix with this. The issue seems to not be with the code cause the traceback is saying theres an error happening with rapidfuzz process. Background is that it gets all from a db table and i need it to make a match with the given argument. after that everything is based off of that matched result.
timid spade
#

How can i add slash commands to cogs?

naive briar
#

Yes

smoky sinew
#

!d discord.app_commands.command

unkempt canyonBOT
#

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

not completely

#

let me get it

#
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "<blah file path>/Dev-Bot/cogs/img.py", line 76, in img
    s_obj = process.extractOne(ship, sql_ship_obj())
  File "process_cpp.pyx", line 694, in rapidfuzz.process_cpp.extractOne
  File "process_cpp.pyx", line 450, in rapidfuzz.process_cpp.extractOne_list
  File "process_cpp.pyx", line 360, in rapidfuzz.process_cpp.extractOne_list_f64
  File "utils_cpp.pyx", line 44, in rapidfuzz.utils_cpp.default_process_capi
  File "cpp_common.pxd", line 331, in cpp_common.conv_sequence
  File "cpp_common.pxd", line 301, in cpp_common.hash_sequence
TypeError: object of type 'int' has no len()```
timid spade
tranquil badge
smoky sinew
naive briar
#

It's already answered

smoky sinew
#

you put the decorator on a command in your cog class

timid spade
#

oh, ouch, i thought you were talkng to Ninja

#

mb

tranquil badge
#

pretty much an entire sql table

naive briar
#

It looks like it returned an int

tranquil badge
#

yea im having a brain fart rn

naive briar
#

Add self as the first parameter

timid spade
#

oh

#

yeahh

#

thanks

tranquil badge
naive briar
#

The type of thing that the sql_ship_object returns

#

Looking at the rapidfuzz package you're using, it seems like the second argument of the extractOne method should be a list

#

Or sequence, whatever

slate swan
#

whats wrong with this code it says interaction failed and not creating an embed```@bot.command()
async def verify(ctx):
button = Button(label="Verify", style=discord.ButtonStyle.green, emoji=":white_check_mark:")
view = View()
view.add_item(button)
await ctx.send("Please Verify", view=view)

async def button_callback(interaction):
    role = discord.object(1108567412594458634)
    user = interaction.user
    await user.add_roles(role)
    await ctx.reply('You are now Verifed!', mention_author=True)

    button.callback = button_callback```
tranquil badge
#

i think it returns it as list indices

naive briar
#

You did not set a callback for the button

slate swan
naive briar
#

Set the button.callback attribute to your callback

tranquil badge
#

"tuple indices must be integers or slices, not string"

naive briar
#

!traceback

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.

tranquil badge
#

are you saying post traceback?

naive briar
#

The traceback of the tuple indices must be integers or slices, not string you just sent

#

Or is it not an error

tranquil badge
#
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "<file path>/Dev-Bot/cogs/img.py", line 79, in img
    ship_embed_title = f"{customemoji(ctx, s_obj['rarity'])} {s_obj['name']}"
TypeError: tuple indices must be integers or slices, not str

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

Traceback (most recent call last):
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: tuple indices must be integers or slices, not str```
naive briar
#

Well, isn't it obvious

tranquil badge
#

yea i ran into this issue before and dont know a way around

naive briar
#

!e

a_tuple = ("Meow",)

print(a_tuple[0]) # correct
print(a_tuple["uwu"]) # incorrect
unkempt canyonBOT
#

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

001 | Meow
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 4, in <module>
004 |     print(a_tuple["uwu"]) # incorrect
005 |           ~~~~~~~^^^^^^^
006 | TypeError: tuple indices must be integers or slices, not str
naive briar
#

You have to get an item from a tuple by the item's index

compact raven
#

!e

unkempt canyonBOT
#
Missing required argument

code

smoky sinew
#

@compact raven #bot-commands

compact raven
timid spade
#

you dont see slash commands when you run the default help command? right?

timid spade
#

oh

#

also how can i add an event in Cog?

turbid condor
#

Mb for the ping

tranquil badge
#

() on the end

vale wing
smoky sinew
#

true

#

also @slate swan i have said that classes start with a capital letter

vale wing
smoky sinew
#

also add a @commands.guild_only check because your command will fail in other servers or in dms

vale wing
#

Yea I use those views in many cases

#

Not applicable for persistent views and views that are meant to be interacted with more than once tho

smoky sinew
#

i know it's possible to acknowledge a menu interaction without sending a message i forgot how

glad cradle
#

disnake epic moment

smoky sinew
#

snipy rewrite leaf in hikari???

glad cradle
#

never used hikari

#

and

#

Well I could try but I need to finish first a pr for Pokelore

smoky sinew
#

lmao

glad cradle
smoky sinew
#

that's weird

vale wing
glad cradle
smoky sinew
#

i am not collaborating with a bot named bobux

vale wing
#

💀

glad cradle
# smoky sinew that's weird

they parse slash commmands arguments and if there's GuildCommandOnly they set that attribute for the slash command

#

ik coz i cried for a pr regarding type hints

smoky sinew
#

what do arguments have to do with checking if a command can be ran in private messages

vale wing
#

@glad cradle leaf or bobux??!2?

glad cradle
glad cradle
vale wing
#

🧐

glad cradle
# smoky sinew what do arguments have to do with checking if a command can be ran in private me...

@commands.guild_only works too in disnake but when you try to access interaction's attributes that are available only for certain type of interaction classes (disnake interaction classes moment) you'll get a warning from pyright: attributes that may be not available are typehinted as Optional

so using the decorator works but doesn't fix your type errors now if you use GuildCommandInteraction disnake will make your slash command guild only and you won't even have typing warnings

#

epic

#

yes you could use @commands.guild_only and GuildCommandInteraction but heh, imagine doing it for all your commands

smoky sinew
#

oh that makes sense

#

but normal interaction still has guild attribute

glad cradle
#

yes but the interaction could come from DMs

#

ApplicationCommandInteraction type is any interaction coming from application command invokations

so it could come from guilds, DMs etc..

glad cradle
smoky sinew
#

true

#

ok i will switch disnake.

glad cradle
#

disnake supremacy

smoky sinew
#

is there a disnake hybrid commands library

glad cradle
#

also idk if you know how great the stateless components thing is

smoky sinew
#

yes i hate view states

#

hybrid commands, interactions and views are the worst things in discord.py

glad cradle
vocal snow
smoky sinew
#

no that's for my other bot

vocal snow
#

I think ur a coward

vale wing
smoky sinew
#

once i figure out how rest api works

glad cradle
#

interactions and application commands are implemented really well in disnake with the interaction types subclasses

#

also soon™ disnake-ext-components will reach it's stable version

it's an extension to manage stateless components

smoky sinew
#

why do you need an extension

glad cradle
smoky sinew
#

discord sucks i think we should switch to revolt.

glad cradle
#

but if you want you could also not use it

#

and just cry

glad cradle
smoky sinew
#

why two ui classes

glad cradle
#

because one is used for components coming from the API, they're components that you haven't created, and the other is used to manage a components from your perspective

#

makes sense ™

smoky sinew
#

yeah but you could at least rename them to be different or merge them

#

RawTextInput or TextInputComponent

glad cradle
#

yes

#

mhm no

#

because raw things in disnake are, basically, payloads coming from the Api and they're used mainly for events

#

TextInput is an object not a dict nor a payload

smoky sinew
#

there's already APISlashCommand

slate swan
smoky sinew
#

self-bots are against this server's rules

slate swan
#

ah sorry

slate swan
#

me when i saw good at coding

slate swan
# smoky sinew whyy

it's the same thing as discord.Button and discord.ui.Button, the second class derives from the first one, with a callback and simpler constructor. the ui class is to "create" those components while the other one is ready only data from the API

timid spade
#

How can i make a context menu command in a Cog?

timid spade
slate swan
timid spade
#

oh

#

makes sense

quasi pawn
#

is it possible to trigger a modal through on_message?

vocal snow
#

No

vale wing
thin raft
#

it's actually good you need to interact with something in order to open a modal

#

imagine spamming modals to someone lol

timid spade
#

sounds fun

quasi pawn
#

Hi, how about replying to the user from on_message?

naive briar
#

!d discord.Message.reply

unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
quasi pawn
#

Thank you

timid spade
#

my bot is responding to every command 2 times
i dont get it why

vocal snow
#

do you have an on_message listener?

timid spade
#

yes i have it in my code

vocal snow
#

don't call process_commands in it

timid spade
#

this is what my on_message lsiterr looks like

#

i dont think so this is causing it

vocal snow
timid spade
#

sorry but what is a process_commands here?

#

oh

#

ok nvm

#

i made this listener one a while ago so didnt saw it

#

i dont even know why i added it there

#

okay its fixed, thanks @vocal snow

slate swan
#

i got this weird error in my warning system

#

my code is:

#

Seems like you've never defined the warnings custom bot variable

naive briar
slate swan
#

You should watch their tutorial again and pay more attention to it

unkempt canyonBOT
#

episodes/episode-12.py line 8

bot.warnings = {} # guild_id : {member_id: [count, [(admin_id, reason)]]}```
slate swan
#

so what should i do

#

im new to python

#
  • Learn Python, at least the basics - discord.py is not meant for beginners, even less for new people
  • Copy that line in your code, just like the tutorial?
slate swan
#

Just like the turorial????