#discord-bots

1 messages · Page 247 of 1

desert kiln
#

ok

#

On github education do I need to be a student that a teacher teaches me how to use github?

north kiln
#

no

desert kiln
#

nice

chrome ivy
#

I've been trying to fix this for the past hour, please help.

Difficulties with this event:

@bot.event()
async def on_message_delete(message):
  z = bot.get_channel()
  embed = discord.Embed(title = f"{message.author}'s Message was Deleted", description = f"Deleted Message: {message.content}\nAuthor: {message.author.mention}\nLocation: {message.channel.mention}", colour=discord.Colour.red())
  await z.send(embed=embed)

Receiving this Error Message:

Traceback (most recent call last):
  File "main.py", line 41, in <module>
    @bot.event()
TypeError: Client.event() missing 1 required positional argument: 'coro'
north kiln
#

No () for the decorator

chrome ivy
#

Oh, that worked, thanks.

smoky sinew
#

only an hour i'm jealous

slate swan
dry kelp
#

if bool is False:
Should check if the bool is false right?

#

or if not bool:

#

nvm

slate swan
#

If your value is strictly Boolean then there's probably no need
If it can take the form of a different type of item (such as NoneType) then you should use is False

vague zephyr
vague zephyr
slate swan
smoky sinew
slate swan
smoky sinew
#

it should be member.guild without the paranthesis

slate swan
#

Oh, I see. I will try without parenthesis

smoky sinew
#
intents = nextcord.Intents.all() #allowing the bot to enter servers 
intents.members = True
intents.message_content = True

also what's the point of this, you set it to all so all intents are enabled but then you set it to True again when it's already True

#

and intents does not allow your bot to enter servers

slate swan
#

I’m still new to nextcord so I follow the docs and tutorials

smoky sinew
#

probably using the wrong library

#

did you copy and paste this code

snow coral
#

rahhhhhhhhhhh

#

how do i make a database and code it inn

#

im so confused

vale wing
snow coral
#

no

#

okay, thank you :)

smoky sinew
#

aiosqlite is a good library to connect

elfin mauve
#

Hi guys, I'm trying to make my bot, so I want some kinda word filter, and, actually I have code for that, but I want it to take words from txt file, but I don't know how to do that, can anyone assist?

smoky sinew
#

good luck making a word filter

#

unless you actually have some better system other than just a word list anyone will be able to bypass it

smoky sinew
#

then what

#

what if you have badword and then someone says badw0rd

elfin mauve
#

list will include different variations

#

I mean, I need to ban only one word, so list of words is enough for me

#

so, do u know how to deal with files ?

smoky sinew
#

bad.....word

#

as for your question you can just open the file and use readlines

#

and if you block bad.....word they can just use bad....1.word

slate swan
#

I can't figure out how to make a Roblox verification system for my discord bot it's so hard ive been trying for 7 hours

worthy heart
#

how many items can I add for a dropdown menu (select menu)?

worthy heart
slate swan
#

A Roblox account

#

Like they put a phrase that the bot generated in there about me

#

Snd when they say done

#

The bot checks

worthy heart
#

token verification?

naive briar
unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
worthy heart
naive briar
#

25 items

worthy heart
#

thx!

#

is it possible to do such a thing?

#

same function for 2 different buttons?

naive briar
#

I would just make a separate function

#

But yes

worthy heart
worthy heart
naive briar
#

Create two button objects inside your view's __init__ then set their callback to your wanted callback

#

And just add them to your view using view.add_item (or self)

#

!d discord.ui.View.add_item

unkempt canyonBOT
#

add_item(item)```
Adds an item to the view.

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

so if I dont have a constructor, I will create one?

naive briar
#

What constructor

worthy heart
#

__init__

gilded oxide
#

Can someone help me with voicemaster (vm)

naive briar
worthy heart
#

what do you mean by this

naive briar
#
class MyView(discord.ui.View): # <- 'MyView' is subclassing 'discord.ui.View'
    ...
worthy heart
#

yes

#

I inherit this class

naive briar
#

Then you can just add the __init__ function to it

worthy heart
#

this way?

naive briar
#

No

worthy heart
#

😮

gilded oxide
slate swan
#

I can't make. Roblox verification discord bot

#

Its way too hard to figure out

worthy heart
slate swan
# worthy heart depends on what you want to verify exactly

They use -verify "there Roblox username" the bot sends a random phrase and asks them to put in there Roblox about me and when the user says done it checks for the phrase in there about me if it finds it it says Great! And gives them the specified roles

worthy heart
#

it seems an easy task

#

wanna go on DMs?

slate swan
#

Sure see ya there

smoky sinew
#

if you don't say anything nobody can help

gilded oxide
#

Well I’m confused on the db part?

smoky sinew
#

what do you need a database for

gilded oxide
#

I don’t need ?

#

Ppl say I need one

smoky sinew
#

for..?

chrome ivy
#

When I use a command, it doesn't work, and there isn't any error message. Willing to go to DMs.

bot = commands.Bot(intents = intents, command_prefix=".")
bot.remove_command('help')
@bot.event
async def on_ready():
  activity = discord.Game(name=".help", type=3)
  await bot.change_presence(status=discord.Status.online, activity=activity)
  print(f"Logged into {bot.user}")
  print(f"Bot Id: {bot.user.id}")
@bot.command()
async def ping(ctx):
  latency = round(bot.latency, 1)
  await ctx.reply(f"Pong! {latency}ms")
naive briar
#

Have you enabled the message_content intent

chrome ivy
#

in the code or dev portal?

naive briar
#

Both

chrome ivy
#

This good?

intents.messages = True
naive briar
#

Pretty sure I said message_content very clearly

#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

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

slate swan
smoky sinew
#

also you don't have any checks to stop anyone from giving themselves admin role

slate swan
#

Wdym -_-

smoky sinew
#

anyone can do !role admin and it'll give them the admin role?

slate swan
#

No ig

slate swan
smoky sinew
smoky sinew
slate swan
#

Sorry for disturbance it's not working because I was not pinging role 😭

slate swan
smoky sinew
#

again not working does not say anything

slate swan
#

Huh nvm my English I am weak

slate swan
smoky sinew
#

show your error traceback

slate swan
#

Wait

smoky sinew
#

if you don't have any errors, explain what your code should be doing and what it actually does

slate swan
smoky sinew
#

explain what your code should be doing and what it actually does

#

also await member.edit(mute=False) does not exist

#

you have to use await member.timeout(None) and you can't sleep for long durations because your member will be stuck muted forever if your bot crashes or restarts

naive briar
#

Unless they have a database and can restart the schedule

slate swan
#

Oh ok

naive briar
#

It's basic persistent mute system

slate swan
#

Why you type too slowly ;-;

naive briar
#

I have something to do outside discord

slate swan
#

Oh ok

slate swan
rain pivot
slate swan
#

You know timeouts are handled by Discord and you don't need to un-timeout someone yourself, right?

#

Just like on the Discord UI, you specify the duration of the timeout and that's it, no need to remove the timeout yourself..

#

So no schedule restart, database is irrelevant, etc.

echo wasp
#

how do i use @bot.tree.command to describe an option because it is not like @app_commands

slate swan
#

You also use @app_commands.describe

pine nexus
worthy heart
pine nexus
#
import discord
from discord.ext import tasks, commands


def run_discord_bot():
    TOKEN = '###'
    intents = discord.Intents.default()
    intents.message_content = True
    global client
    client = discord.Client(intents=intents)
    bot = commands.Bot(command_prefix="!!", intents=intents)

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

    client.run(TOKEN)
#

literally does not register command, I tried as a hybrid as well and no slash option appeared

#

I have debugging on the full bot and it was parsing as a normal message

#

bot intents are all toggled on in the dev portal

#

I about gave up

worthy heart
#

example:

@client.tree.command(name="logout", description="Logout from the account you are currently logged in to")
async def logout(interaction: discord.Interaction):
    ....
north kiln
#

...

#

Did you sync your command

#

And why use both client and bot

naive briar
#

YouTube

pine nexus
#

I kinda thought they had to be separate ngl

#

discord.Client and discord.ext.commands.Bot

#

right?

north kiln
#

You only need one

pine nexus
#

bruh

north kiln
#

Use commands.Bot

north kiln
pine nexus
# north kiln And ^
    client = commands.Bot(command_prefix="!!", intents=intents)
    emojis = ['\N{WHITE HEAVY CHECK MARK}', "\N{BOMB}"]

    @client.tree.command(name="test", description="say hello to everyone")
    async def test(ctx):
        await ctx.send("hola")
#

not right?

north kiln
#

slash commands uses interactions instead of ctx

pine nexus
#

k bet ty

#

sorry I had tried reading discord py documentation and it was not helping lol

naive briar
#

It should be

#

Why couldn't it help you

azure trellis
#

@unkempt canyon !help

#

#bot-commands

pine nexus
#

well I copied the sync line for line,

    @client.command()
    @commands.guild_only()
    @commands.is_owner()
    async def sync(
            ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
        if not guilds:
            if spec == "~":
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "*":
                ctx.bot.tree.copy_global_to(guild=ctx.guild)
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "^":
                ctx.bot.tree.clear_commands(guild=ctx.guild)
                await ctx.bot.tree.sync(guild=ctx.guild)
                synced = []
            else:
                synced = await ctx.bot.tree.sync()

            await ctx.send(
                f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
            )
            return

        ret = 0
        for guild in guilds:
            try:
                await ctx.bot.tree.sync(guild=guild)
            except discord.HTTPException:
                pass
            else:
                ret += 1

        await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")

Nothing when I run !!sync

#

intents = discord.Intents.default()
intents.message_content = True
global client
client = commands.Bot(command_prefix="!!", intents=intents)

formal basin
#

What does this mean?

naive briar
#

It means exactly what it says

vale wing
#

Too many syncs

pine nexus
#

There is a ratelimit on syncing global commands which add commands. Updating commands (currently) has no ratelimit.

formal basin
pine nexus
#

it says 200 lol

vale wing
#

Does disnake autosync commands in a smart way (ie only ones that are missing or not in code or with different signature) or bulk overwrites them every time

formal basin
#

Actually this my 15th

pine nexus
#

not max number of commands

#

each time you run sync

naive briar
#

It stacks when you sync the commands

formal basin
#

Oh

#

So I can’t run it today?

pine nexus
#

you could create a bunch of commands and sync them all at the same time, but if you sync them one by one it'll eventually stop you

#

if it makes you feel any better, I still can't figure out why my command won't sync 😭

pine nexus
pine nexus
#

but if you run sync each time you're exhausting your usage

formal basin
pine nexus
#

well you do now

#

you only get 200 uses per day

formal basin
#

😞

#

At least all my other commands are ok

pine nexus
#

if your sync is in your "on_ready" section or similar where it's being run unnecessarily, I recommend moving it

#

you only wanna call sync when you need to

#

When you add a new command.
When you remove a command.
When a command's name or description changes.
When the callback's parameters change.
If you change a global to a guild command, or vice versa.

#

otherwise, it's pointless to run

formal basin
#

Is there an event when a tree command changes?

naive briar
#

Why

#

You should know if you make changes your commands

formal basin
#

So I can reduce the syncs

naive briar
#

What

formal basin
#

So I can reduce the syncs

naive briar
#

Sigh

formal basin
#

For example if I am editing an event and I run it’s gonna sync because it’s on the on_ready event

pine nexus
#

move it from the on ready

formal basin
naive briar
#

You should not blindingly sync automatically

#

Make a message command or something

pine nexus
#

speaking of which

#

I can't figure out how to run my sync

formal basin
naive briar
#

No

#

Why can't you know if you edited your commands

#

Your

Own

commands

pine nexus
#

you literally only need to run it when you make an edit/addition/removal, so just have a message command you can run in your server whenever you do one of those

pine nexus
#

ofc he listens to me who is not an expert FeelsMonkaWMan

formal basin
pine nexus
#

is owner

#

@client.command()
@commands.is_owner()

formal basin
pine nexus
#

don't quote me on that

#

I still can't figure out how to get my own sync to run

#

@naive briar any ideas lol

elfin mauve
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.

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

odd jasper
naive briar
#

You aren't enabling the message_content intent, so, there's no wonder that it wouldn't work

slate swan
#

They said message_content

naive briar
#

I said message_content very clearly

formal basin
odd jasper
formal basin
formal basin
odd jasper
#

Lol

#

xD

#

Ahh i saw it

#

it worked.. dumb.. Thanks lol

formal basin
#

There we go

mellow pollen
#

Is there a way to make sure I dont get rate limited. I have a bot that has 5 commands that i was trying to make for a clan event, all my slash commands are synced globally i guesss but i really just need it to work in two seprate discords technically.

Still pretty new to coding in general so please be nice 🙂

vocal snow
#

What do the commands do?

#

Which endpoint(s) are you afraid of getting ratelimited on?

mellow pollen
#

mainly it querys a local DB, some of the commands pull images from a wiki for the embeds. I added another command just now that only querys the DB and it gave us:
discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)

vocal snow
#

Are you syncing the commands globally everytime you run your code?

#

You only need to sync them when you change the metadata of the command, not the underlying function code

mellow pollen
#

Ok, so i guess i should pull that out of my code for when the bot turns on. we just started to host it on a friends homeserver, i think weve only restarted the bot a handful of times so i cant imagine we hit the 200 limit so quick.

#

we got the error when the bot was turning on.

north kiln
#

I have seen this error so many times today lol

#

Seems like a discord problem

worthy heart
#

I want to create a select menu

I have this

        select = Select(
            placeholder="Choose a color to apply it to your device",
            options=[
                discord.ButtonStyle(
                    label="Philippine Red",
                    value="d40f2b",
                    emoji=colors['d40f2b']['emoji']

                )
            ]
        )

but as I have many colors I was trying to do it like this without success

select = Select(
    placeholder="Choose a color to apply it to your device",
    options=[

        for color in colors:

            discord.ButtonStyle(
                label=color[color]['name'],
                value=color,
                emoji=colors[color]['emoji']
            )
    ]
)

any ideas?

slate swan
#

you need to use list comprehension for that

#

!list-comp

unkempt canyonBOT
#
List comprehensions

Do you ever find yourself writing something like this?

>>> squares = []
>>> for n in range(5):
...    squares.append(n ** 2)
[0, 1, 4, 9, 16]

Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:

>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]

List comprehensions also get an if clause:

>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]

For more info, see this pythonforbeginners.com post.

slate swan
#

try doing it with it and if you dont success ill help you

#

@worthy heart ^

worthy heart
#

how cool I cannot handle it

left dew
#

does anyone know how i would creste a channel once a modal has been submitted? I have this so far:

@bot.command()
async def test(ctx):
    class MyView(discord.ui.View):
        def __init__(self):
            super().__init__(timeout=None)
        @discord.ui.button(label="View Modal", style=discord.ButtonStyle.primary, custom_id="customid1")
        async def button_callback1(self, button, interaction:discord.Interaction):
            modal = WriteUserModal(title="Create a channel")
            await interaction.response.send_modal(modal)
    view = MyView()
    await ctx.reply(view=view)```
formal basin
#

Can json crash your bot?

knotty mountain
#

How can I check the reactions of a message?

slate swan
unkempt canyonBOT
formal basin
upbeat gust
formal basin
upbeat gust
#

what json? from a request? a file? wdym "crash"

robust fulcrum
formal basin
left dew
#

when a user clicks Submit on a modal, how do i make the bot reply with something after that?

robust fulcrum
left dew
#

no a modal

upbeat gust
left dew
#

thx!

robust fulcrum
#

Hi guys , can loading a lot of data or loading a lot of data from a api crashes our discord bot , if yes , how to make it not?

upbeat gust
naive briar
left dew
#

does anyone know why when i click submit on my modal it always says, Something went wrong! Try again, but i get no errors

left dew
# upbeat gust show your code
class StarterMM(Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        # add the questions:
        self.add_item(InputText(label="Paste your Discord ID or Full Tag.", min_length=2, max_length=32, required=True, style=discord.InputTextStyle.short))
        self.add_item(InputText(label="What's your problem", min_length=2, max_length=1000, required=True, style=discord.InputTextStyle.long))

    async def callback(self, interaction2: discord.Interaction): # once the submit button is clicked..
        user_id = self.children[0].value # thats the submitted answer to the 1st question
        prob_text = self.children[1].value # thats the submitted answer to the 2nd question
                
    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"Creating ticket..", ephemeral=True)
        guild = bot.get_guild(GUILD_ID)
        await guild.create_text_channel(f"mm {interaction.user.name}")

    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)

        # Make sure we know what the error actually is
        traceback.print_exception(type(error), error, error.__traceback__)```
upbeat gust
#

this doesn't exist

#

And why are you asking for the username lol, you can get that data

left dew
upbeat gust
left dew
#

but it is valid code

#

it does exist, because it's worked before

upbeat gust
left dew
#

from discord.ui import InputText, Modal

#

it does exist.

#

it's worked before

upbeat gust
#

You're welcome to find the source if you'd like

#

I, for one, know it doesnt exist

left dew
#

it does exist

#

because it works

upbeat gust
#

I'm not going to argue with you

left dew
#

it still works though

upbeat gust
#

It literally doesnt bruh

robust fulcrum
left dew
#

its worked on other projects though

upbeat gust
#

It never has and never will

#

unless you're using some super obscure third-party library that no one has used before

left dew
#

this is with the exact same code and it works

upbeat gust
#

show the code then

left dew
#
    class MyModal(Modal):
        def __init__(self, *args, **kwargs) -> None:
            super().__init__(*args, **kwargs)
            daa = datetime.now(timezone(timedelta(hours=3))).strftime("%d-%m-%Y")
            #self.add_item(InputText(label="Today's date in case you forgot..", required=False, style=discord.InputTextStyle.short, value=f"{daa}"))
            self.add_item(InputText(label="Day in numbers", placeholder="Example: 15", max_length=2, required=True, style=discord.InputTextStyle.short))
            self.add_item(InputText(label="Month in numbers", placeholder="Example: 3", max_length=2, required=True, style=discord.InputTextStyle.short))
            self.add_item(InputText(label="Year in numbers", placeholder="Example: 2022", max_length=4, required=True, style=discord.InputTextStyle.short, value="2022"))

        async def callback(self, interaction: discord.Interaction):
            if interaction.user.id != ctx.author.id:
                return await interaction.response.send_message(content="Only the user who ran the cmd can use this.", ephemeral=True)```
upbeat gust
#

Then you're using some third-party lib or a fork

#

can't help you with that

hushed galleon
left dew
#

yes

left dew
#

so it does exist

hushed galleon
#

it also looks like your on_error parameters are in the wrong order

upbeat gust
#

🤮 _ _

upbeat gust
left dew
upbeat gust
terse elbow
#

Is there a reason to create commands.command commands as well? Or just slash commands

#

for private discord bots

hushed galleon
#

for testing/debugging commands sure, or if you have something too advanced to be written in a slash command

slate swan
#

What do you mean by "too advanced to be written in a slash command"?

hushed galleon
#

like being able to use markdown formatting...

slate swan
#

Oh I think I'm with you now. Like the !e command?

worthy heart
#

Lets say I have an interaction

#

and that interaction has a button

#

how can I know that the clicker is also the interaction's author?

#

(so that he is permitted to click the button)

slate swan
#

There is something Like interaction_check i belive let me check docs

#

What lib do you use?

worthy heart
slate swan
#

!d discord.ui.View.interaction_check

unkempt canyonBOT
#

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

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
knotty mountain
#

Checking a message for reactions always returns nothing, even though the message does have reactions, the bot has admin priviledges and it doesn't recognise anyones reactions, even its own
Code: ```py
reactdict = {"\u0031\u20E3":1,"\u0032\u20E3":2,"\u0033\u20E3":3,"\u0034\u20E3":4,"\u0035\u20E3":5,
"\u0036\u20E3":6,"\u0037\u20E3":7,"\u0038\u20E3":8,"\u0039\u20E3":9,"\U0001F51F":10}

async def sendmessage(channel: TextChannel, starttime: time, duration: int): -> int
targettime = time(hour=(starttime.hour + duration), minute=starttime.minute)

# Send message
msg = await channel.send("How was your day?")

for react in reactdict.keys():
    await msg.add_reaction(react)
    # print(react)

while True:
    await asyncio.sleep(5)

    # Check reactions
    await checkreaction(msg)

    print(f"now: {datetime.now().time()}, target: {targettime}")
    if datetime.now().time() > targettime:
        break

# Things to do before quitting
print("quitting")

return 0

async def checkreaction(msg: Message):
print(f"reactions: {len(msg.reactions)}")


The bot successfully sends a messages and sends the reactions to its own message but can't check its reactions
worthy heart
#

it returns True
but how can I access the parent's interaction owner

slate swan
#

show your code now

worthy heart
# slate swan show your code now

class SimpleView(discord.ui.View):


    @discord.ui.button(label="Turn on", style=discord.ButtonStyle.success)
    async def turn_on(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:

        await interaction.response.defer()

        self.light_api.on = True

        status, emoji = br.device_status_to_word(self.light_api.on)

        self.embed.remove_field(3)
        self.embed.add_field(name=f'{emoji} Status', value=f"_Light is currently {status}_", inline=False)

        await self.message.edit(embed=self.embed)


    @discord.ui.button(label="Turn off", style=discord.ButtonStyle.secondary)
    async def turn_off(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:

        await interaction.response.defer()

        print(button)

        resp = await discord.ui.View.interaction_check(self, interaction)

        print(resp)

        print(interaction.user.id)
        print(interaction.user)

        self.light_api.on = False

        status, emoji = br.device_status_to_word(self.light_api.on)

        self.embed.remove_field(3)
        self.embed.add_field(name=f'{emoji} Status', value=f"_Light is currently {status}_", inline=False)

        await self.message.edit(embed=self.embed)

The turn_off function is what I am on right now

slate swan
#

okay so you have a View subclass

#

now you need to override interaction_check method

#

somehow manage to get id of user that invoked the command to the view

#

and in the interaction_check
check if ids match

#

if you are stuck at any point lmk

slate swan
worthy heart
#

let me see

slate swan
#

i dont know exactly for which user you want to check

#

the one that invoked the command right?

worthy heart
#

lets say I am doing the /list command

#

I want to make sure, that only I will be permitted to use the buttons

knotty mountain
slate swan
#

okay so yeah you can pass the id in the constructor then

#

since you have the id in the command already

worthy heart
#

so the buttons has a sub-interaction?

slate swan
#

yes but why does that matter now?

worthy heart
#

to understand how it works 😄

slate swan
worthy heart
#

thats also an idea

random umbra
#

can any one help

#

it's not working

naive briar
#

commands.Bot not commands.bot

random umbra
#

i changed it

#

still

naive briar
#

Still what

random umbra
naive briar
#

The error already told you exactly what's wrong

#

Read it

random umbra
#

oh

#

i dont understang istg

glad cradle
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.

random umbra
formal basin
#

400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)

violet canopy
#

Can Discord bots ever give bot commands to other bots? Or is it just part of how Discord works, that bots don’t listen to other bots

glad cradle
naive briar
#

They can't?

glad cradle
naive briar
#

Thought so

random umbra
#

i fixed the code but i really don't understand what is this

glad cradle
glad cradle
#

yeah? enable them

#

you can in your case

random umbra
#

alr

umbral basin
#

I am building a discord RPG, using Replit where people can create a profile and adventure etc. I want to connect to a database so their progress remains even when the bot gets restarted. Which db is recommended?

glad cradle
#

any db is ok but i would suggest postgres

umbral basin
#

I am reletively new in this, so the most friendly db

slate swan
#
Traceback (most recent call last):
  File "/home/runner/Atomic/venv/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "main.py", line 129, in my_callback
    created_channels.append(channel.id)
NameError: name 'created_channels' is not defined
#

Whats this error?

maiden fable
#

there is no list by that name

twilit grotto
slate swan
#

!e ```py
myList.append(1)

unkempt canyonBOT
#

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

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

I keep getting this error when submitting a response to my modal and then it responding to the interaction, thing is, it works sometimes and it worked perfectly fine before, but now with the same code it's causing this problem

discord.ui.modal Ignoring exception in modal <emailinputmodal timeout=None children=1>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ui/modal.py", line 187, in scheduled_task
await self.on_submit(interaction)
File "/home/container/creator_bot.py", line 961, in on_submit
await interaction.response.send_message(embed=embed, ephemeral=True)
File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 778, in send_message
await adapter.create_interaction_response(
File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async
.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

If I spam it, it works after like 10 tries

north kiln
#

Your spreadsheet operation takes longer than 3 seconds

#

interaction must be responded in 3 seconds so you first defer the interaction than follow up

formal basin
#

Is the discord bug fixed?

north kiln
#

Yes

formal basin
storm skiff
swift acorn
formal basin
#

Is there a better module than better_profanity?

pine nexus
#

ok I need help

#

idk if it's just not set up right, but I can't figure out how to sync a simple test command

#

😐

pine nexus
#

well idk if it's wrong or something but it just isn't working 🤷

pine nexus
#

I was already sent this and it wasn't helpful. Robin's helping me out atm and it's definitely a larger problem than just that

glad cradle
#

kipmud

pine nexus
#

well the initial problem was a conflict with my client.event on_message

#

but that was just hiding more problems

#

I will say, being sourced the proper resources is definitely the right idea, sometimes it's nice to actually be listened out first because that's like the third time someone's linked that for my problem and nobody actually talked it through with me for 12h

#

until Robin popped in

smoky sinew
meager chasm
#

It's simple, don't access attributes that don't exist

chrome ivy
#

How do I reply with the invite that was created?

@bot.command()
async def invite(ctx):
  channel = ctx.channel
  author = ctx.author
  await channel.create_invite(reason=f"{author} created an invite for {channel}!", max_age=0, max_uses=0, temporary=False, unique=True)
  await ctx.reply()
unkempt canyonBOT
smoky sinew
#
@commands.has_permissions(create_instant_invite=True)
@commands.bot_has_permissions(create_instant_invite=True)
@bot.command()
async def invite(ctx: commands.Context) -> None:
    invite = await ctx.channel.create_invite(reason=f"{ctx.author} created an invite.")
    await ctx.reply(invite.url)

this is all you need

#

max_age=0, max_uses=0, temporary=False, unique=True
these are the defaults so you don't need to include them

chrome ivy
#

thanks

smoky sinew
#
@commands.has_permissions(create_instant_invite=True)
@commands.bot_has_permissions(create_instant_invite=True)

also this is optional but a lot of servers deny members the permission to create invites

chrome ivy
#

This command always returns (when there aren't any boosters): "[ ]"
I've been troubleshooting this one for a few days.

@bot.command()
async def boosters(ctx):
  subs = ctx.guild.premium_subscribers
  if subs == None:
    await ctx.reply("There aren't any boosters! :(")
  else:
    await ctx.reply(subs)
smoky sinew
chrome ivy
#

ok

smoky sinew
#

and by the way when there are boosters, you shouldn't send the list

chrome ivy
#

?

smoky sinew
#

it will return something like [<Member id=998070081709932654 name="mudkip">, ...]

#

let me give an example

chrome ivy
#

ok

smoky sinew
#

!e ```py

ignore, pretend this is the discord.Member class

class Member:
def init(self, name: str) -> None:
self.name = name

def __str__(self) -> str:
    return f'<Member name="{self.name}">'

__repr__ = __str__

boosters = [Member("mudkip"), Member("littlebluefeline")]
print(boosters)
print([booster.name for booster in boosters])
print("\n".join(["- " + booster.name for booster in boosters]))

unkempt canyonBOT
#

@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | [<Member name="mudkip">, <Member name="littlebluefeline">]
002 | ['mudkip', 'littlebluefeline']
003 | - mudkip
004 | - littlebluefeline
smoky sinew
#

see the difference between the 3 of these

chrome ivy
#

yes

smoky sinew
#

you can also just do str(booster) instead of booster.name to get their discriminator as well

chrome ivy
#

ok

#

thanks

sturdy falcon
#

what does webhook.remove_embed() do?

smoky sinew
sturdy falcon
smoky sinew
#

in what library

sturdy falcon
#

discord_webhooks

smoky sinew
#

why are you using discord_webhooks?

#

are you talking about this library? this has not been updated in over 3 years

sturdy falcon
#

i wanted to know what it did since it seems to not be working

smoky sinew
#

so i don't know where you got that from

sturdy falcon
#

i typed in webhook. into visual studio code and looked at the auto completes

smoky sinew
#

well you're definitely using something else

sturdy falcon
#

yeah it seems the auto complete has remove_embed but only remove_embeds (with S) works

smoky sinew
#

huh???

sturdy falcon
#

idk i was looking around and that was the first thing that i saw. i have already fixed my problem so it's fine

gilded oxide
#

how would I define this (my friend coded it)

vocal snow
#

what is it supposed to do

#

and it would probably be better if you just asked your friend

gilded oxide
#

now im js having db issues..

unkempt locust
#

@smoky sinew Quick question, trying to do a moderation & configuration feature that uses one single webhook to send a message with (e.g. For Welcoming, Audit Log Changes, Moderation Commands such as timeouts, etc.) But for some reason when i try changing the avatar to the author's avatar, it says it can't do it due to it not passing as a string but its already a string? (Also its saying that im passing it at bytes, im lost right now & i kinda lost my brain functionality doing this)

        """Webhook configuration to set everything up"""
        try:
            check = await self.bot.db.fetchrow('SELECT * FROM Webhook WHERE Member = $1', ctx.author.id)
            webhook = str(check['webhook']) if check else await ctx.channel.create_webhook(name=name)
            async with ctx.typing():
                webhook_obj = discord.Webhook.from_url(webhook, session=aiohttp.ClientSession())
                avatar_url = str(ctx.author.display_avatar.url) if avatar is None else str(avatar)
                await webhook_obj.edit(name=name, avatar=avatar_url) # type: ignore
                await webhook_obj.send('Edited **username** & Avatar (Melaine Webhook Notification)')

                if check:
                    await self.bot.db.execute('UPDATE Webhook SET Name = $1, Avatar = $2 WHERE Member = $3', name, avatar_url, ctx.author.id)
                else:
                    await self.bot.db.execute('INSERT INTO Webhook (Member, Webhook, Name, Avatar) VALUES ($1, $2, $3, $4)', ctx.author.id, webhook, name, avatar_url)

            embed = discord.Embed(
                description=f"> {ctx.author.mention}: {'Updated' if check else 'Created'} **Webhook** with name **{name}** & Avatar **[Your Avatar]({avatar_url})**",
                color=Complexion.get_color(self, color_name='success')
            )
            await ctx.send(embed=embed)```
smoky sinew
#

first of all supabase is a firebase alternive

#

it has nothing to do with postgres itself

unkempt locust
# smoky sinew no..?

i know it has nothing to do with the error but its used alot for database collections & its efficient

smoky sinew
#

no

#

that's not what it does

unkempt locust
#

supabase is easier to use imo tho, thats just me, and its less code

#

aiosqlite is buggy & it does not have alot of functionalities like postgre

smoky sinew
#

supabase is a backend as a service, i don't see why you would use it for the database functionality alone when it's essentially just a wrapper around postgres

#

and i don't see why SQL would be less code than just using a document database

unkempt locust
smoky sinew
#

even mongodb is easier since you don't have to manage schemas

unkempt locust
#

if you ever switch to mongodb at that point, just use json its literally doing the same thing

smoky sinew
#

no

#

json is not a database

unkempt locust
#

i know, its a joke

smoky sinew
#

also if you can't manage tables why not just use pgadmin and that way you don't have to lock yourself into supabase?

unkempt locust
unkempt locust
smoky sinew
#

i don't see why you would want them to switch

unkempt locust
smoky sinew
#

why..???

unkempt locust
smoky sinew
#

okay???

smoky sinew
#

also why do you have webhooks in a database

unkempt locust
north kiln
#

how is aiosqlite buggy

unkempt locust
wispy pasture
#

so my bot** IS** replying to mentions when it should NOT...
i tried adding a conditional statement py if not bot.user.mentioned_in(ctx.message): in the code.. but the bot still replies on mentionss...
https://srcb.in/H3qbwVPZsr

the on_message (it is in main.py the above link):
https://srcb.in/65ihHfKw0y

north kiln
#

I didn't know the context but I never encountered such problem

wispy pasture
unkempt locust
unkempt locust
hushed galleon
north kiln
#

also one question

#

asqlite has a connection pool feature that I didn't see in aiosqlite nor sqlite3

#

not sure about the difference between using a pool and manually connecting each time

hushed galleon
#

last time i used asqlite it was before danny implemented pools, but it looks like it starts up X threaded connections as soon as you create the pool

unkempt locust
# wispy pasture this is the main.py i.e the whole code: https://srcb.in/H3qbwVPZsr

you're code is rather vauge.. its all of the place, i can recommend you to switch to cogs aswell, and i believe the issue with you're code is here:

        async def generate_response_in_thread(prompt):
            temp_message = await message.channel.send("https://cdn.discordapp.com/attachments/1098579202883735602/1113519006444429413/editor-0.6s-47px.gif")
            response = await generate_response(prompt)
            message_history[author_id].append(f"\n{bot.user.name} : {response}")
            chunks = split_response(response)
            for chunk in chunks:
                await message.reply(chunk)```

on the `for` function, you're not calling `mention_author=False`, the correct statement should be:
```py
for chunk in chunks:
    await message.reply(chunk, mention_author=False)```

i can't read all of the code since its all over the place so i really do recommend you switch to cogs & make you're own seperate cogs to do this (e.g. Make you're very own cog for you're management & proccessing codes)
smoky sinew
hushed galleon
smoky sinew
#

this is an issue with the bot replying to other user's replies

unkempt locust
smoky sinew
unkempt locust
smoky sinew
smoky sinew
#

@wispy pasture why do you have this check? ```py
is_replied = message.reference and message.reference.resolved.author == bot.user

slate swan
#

trying to find a dev team I have a vps

wispy pasture
smoky sinew
wispy pasture
smoky sinew
#

i think so

wispy pasture
#

😅

wispy pasture
north kiln
#

what is your bot's expected behaviour?

#

when should it be replying

#

and when it should not

wispy pasture
wispy pasture
smoky sinew
#

a reply is technically a mention

wispy pasture
#

in other words: when a user replies to the generated image (/imagine) with anything.. such as "nice" "cool" the bot should not reply, but if the user is talking with the bot in the channel set using /toggleactive the bot should reply...

wispy pasture
north kiln
#

it is replying is picture 2 tho?

wispy pasture
north kiln
#

yes?

wispy pasture
#

this is pic 1...

north kiln
#

the bot did reply to the prompt in 2?

wispy pasture
#

but it should not reply to the pic embed it sends: cause thats the image generating cmd not the AI chat

north kiln
#

is that channel the channel with ai chat toggled?

wispy pasture
#

nope...

north kiln
#

or is the channel in both pics same

wispy pasture
north kiln
#

you should probably check your active channels set or channels.txt to be sure

wispy pasture
#

alright lemme check again

wispy pasture
north kiln
#

try logging is_active_channel being True or not

wispy pasture
#

a;right

north kiln
#

oh you are using or

#

I was being stupid all the time

#

so if any of the condition is met it will reply

#

maybe something like

if is_active_channel and (is_allowed_dm or contains_trigger_word or is_bot_mentioned or is_replied or bot_name_in_message):
wispy pasture
#

ohhhhh

#

okay okay makes sense lemme try

wispy pasture
#

@north kiln
now the bot wont work without being mentioned even in the active channel

north kiln
#

You set it like so look at the conditions

wispy pasture
#

ah yes yes the and and or

#

makes sense....

north kiln
#

From what I see your on_mesaage is only used for ai chat so if you want every message in active channels to act as a prompt then you don't need those conditions

#

Only checking the channel is enough

wispy pasture
#

aha alright alright

mighty edge
#

my bot is spamming the logs command

#

can someone help me?

rugged shadow
#

if i'm understanding correctly you're not changing the length of ctx.member.roles in the loop

#

or i

mighty edge
#

I'm using it to filter the roles

slate swan
#

how do I recreate this welcome image from mee6 bot putting words over photo with py code

slate swan
unkempt canyonBOT
formal basin
#
@client.tree.command(name="random-colour", description="sends a random colour")
async def randomcolour(interaction: discord.Interaction):
    embed = discord.Embed(title="here is a random colour", color=discord.Color.random())
    embed.add_field(name=f"")``` how can i send the colour name and hex
slate swan
#

Something like that iirc

c = discord.Color.random()
print(c.r, c.g, c.b, c.value)
#

You'll get the integer representation of R, G & B and the overall integer value

#

Which you can convert to hex easily

formal basin
#

also how can I check for an author's perm in an on_message event?

slate swan
#
  • message.author.guild_permissions
  • message.channel.permissions_for(message.author)

All from a quick search in the documentation :)

slate swan
#

Next time you can try searching your own as well ^-^

slate swan
#

Not meaning it negatively, it's just good to search on your own sometimes, that way you learn and prepare yourself better for the future

merry spruce
#

hi, why i cannot import discord.ui

vocal magnet
#

what have you tried, and what's the error?

merry spruce
#

i dont know why

#

i have tried this one

north kiln
#

import discord.ui

merry spruce
north kiln
#

No

#

Literal import discord.ui

merry spruce
#

i have download the package

north kiln
#

What is your dpy version?

merry spruce
cold night
#

i want to make slash command in file test.py, i have my socket server in file named bot.py , and i want to send data to socket from test.py. could anyone tell me how can i do that?

vocal snow
merry spruce
#

here

merry spruce
vocal snow
#

you need to update

merry spruce
#

how to update

vocal snow
#

pip install -U discord.py

merry spruce
#

ok tks

merry spruce
vocal snow
#

cmd

merry spruce
merry spruce
vocal snow
merry spruce
vocal snow
#

what does pip show discord.py show the version as

vocal snow
#

ok, run pip -V and note the python interpreter version and path. Is it the same as the one VSC is using?

vocal snow
#

now check which python interpreter you've set in vscode

#

click on that in the bottom bar and make sure it's path is the same

merry spruce
#

how...

merry spruce
#

not the same, how can i make it same

vocal snow
#

click the Global one, that's the one linked to your pip command

merry spruce
#

okay

vocal snow
#

The recommended one is a venv, are you using a venv for this project?

merry spruce
#

yes

#

it works, thank you so much bro

vocal snow
#

then you should use that, activate the venv and then install discord.py there

#

using the global interpreter is more of a bandaid fix

merry spruce
#

okay

maiden fable
#

MS Store Python 😨

slate swan
#

pypypypypypy

cloud dawn
#

@manic wing

manic wing
# cloud dawn 🤔

Old code i found on one of my hhds, which were repositories i deleted at some point so i recreated them

#

I cant even remember writing it

manic wing
cloud dawn
#

Still recovering.

vocal snow
#

enjoy ☺️

slate swan
manic wing
#

I also made discorddb because i forgot completely about disdata

hexed pilot
#

?tag cogs

novel apexBOT
#

This is not a Modmail thread.

hexed pilot
#

guys there is a documentery or something can i get info about cogs?

upbeat gust
#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
hexed pilot
#

thanks i was searching that

naive briar
#

What library

olive raft
#

I have a small code for a Discord bot, but I don't fully understand how to edit a webhook. I want to add new text to the existing text in field 3. Can you please advise me on how to do it

north kiln
#

what is your expected result

olive raft
#

need to fix it. I don't understand how to do it.

merry spruce
thin raft
#

stop sending the same image

#

reply to what they ask you

thin raft
slate swan
#

It's probably been like the 4th or 5th time just sending the image with "help" beneath it and that's it 3HC_why

merry spruce
dry kelp
#

Here i am trying to check if the antinuke_setup is enabled

#

if it's false, return

#

But in my case it was true and still sending the error

#

for some reasons if database.antinuke_setup is still false even after being turned to true

#

issue fixed, using .save()

echo wasp
#

how do i make tax possible in python with precentages?

twilit grotto
#

ah wait it is my bad

smoky sinew
#

is there more

#

anything above it

#

what were you doing when the error showed up

frozen flame
#

this doesnt work for me for some reason im trying to change everyone's name to the argument name but it wont do it

slate swan
frozen flame
slate swan
#

There you go

#

The bot cannot edit the nickname of one or multiple users

frozen flame
#

but why is that

slate swan
#

Permissions are existing

frozen flame
#

yes they are

#

he can kick, ban and disconnect members in vc

smoky sinew
#

bot doesn't have permission to change the server owner's nickname

#

or any role above it

#

also you have no permissions checks

frozen flame
#

i gave him the highest role in the server but he didnt change other members that has lower roles

smoky sinew
#

maybe it errored and didn't finish

frozen flame
smoky sinew
#

why not just use has_permissions and bot_has_permissions

slate swan
#

If it tried to edit the first member and it didn't have permissions, it would entirely stop the loop

frozen flame
smoky sinew
#

to set anyone's nickname

frozen flame
#

right....

#

just checked it on an alt and youre right, he doesnt replay with on_command_erorr

#

so what should i do

gilded oxide
#
    @commands.command(help="whitelist a member", usage="[member]", description="antinuke")
    @commands.cooldown(1, 2, commands.BucketType.user)
    @commands.has_permissions(administrator=True)
    async def add(self, ctx: commands.Context, *, member: discord.Member=None): 
      if member is None: await self.commandhelp(ctx, "whitelist add")
      async with ctx.bot.db.cursor() as cursor: 
        await cursor.execute("SELECT * FROM whitelist WHERE guild_id = {} AND user_id = {}".format(ctx.guild.id, member.id))
        check = await cursor.fetchone()
        if check is not None: return await ctx.reply(embed=discord.Embed(color=0x2B2D31, description=f" {ctx.author.mention}: This user is already whitelisted"), mention_author=False)
        await cursor.execute("INSERT INTO whitelist VALUES (?,?)", (ctx.guild.id, member.id))
        await self.bot.db.commit()
        await ctx.reply(embed=discord.Embed(color=0x2B2D31, description=f" {ctx.author.mention}: Whitelisted {member.mention}"), mention_author=False)``` can someone help me fix an error with this code
#
2023-06-01 14:57:48 ERROR    discord.client Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/drake/Desktop/deadbot/cogs/mod.py", line 163, in add
    async with ctx.bot.db.cursor() as cursor:
              ^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'db'

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

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "/Users/drake/Desktop/deadbot/cogs/events.py", line 25, in on_command_error
    raise error
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/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: 'Bot' object has no attribute 'db'```
slate swan
#

The error says it all, Bot doesn't have a db attribute

gilded oxide
#

obviouslu

#

im js stuggling to fix it

slate swan
#

Create a bot variable named db

twilit grotto
#

and your SQL query is wrong i believe. (for inserting), i may be wrong im not too familiar with SQL

slate swan
#

Or create your custom bot class with that attribute and set it accordingly

gilded oxide
#

so py db = bot

twilit grotto
#

no. thats making a variable not a class

gilded oxide
slate swan
#

Yeah it's more something like

INSERT INTO table(col1, col2) VALUES(val1, val2)
twilit grotto
#

yeah i thought so

slate swan
#

Unless you put all columns

#

Then you don't need to specify, it's just better to always specify to prevent ambiguity

gilded oxide
#

I may js start using psql ppl keep telling me that

slate swan
frozen flame
gilded oxide
#
class mod(commands.Cog):

    def __init__(self, bot):
        self.bot = bot```
slate swan
#

That's not a custom bot class, no

gilded oxide
#

nvm

frozen flame
#

i added has_permissions but still not woking

#

someone please?

gilded oxide
#

idk as a db

smoky sinew
#

where did you get change_nickname from

#

you also need bot_has_permissions

gilded oxide
smoky sinew
#

yes

frozen flame
smoky sinew
#

?

frozen flame
#

does bot_has_permissions takes any arguments?

#

parameters ?

#

@smoky sinew did this

formal basin
smoky sinew
formal basin
#

no wait

smoky sinew
#

so everyone can change the nicknames again

frozen flame
smoky sinew
#

you don't need the aliases part either, you can just set your bot to case_insensitive=True

#
@commands.guild_only()
@commands.has_permissions(manage_nicknames=True)
@commands.bot_has_permissions(manage_nicknames=True)
@bot.command(description="Edits everyone's nickname in the current server.")
async def nickname(ctx: commands.Context, *, nickname: str) -> None:
    for member in ctx.guild.members:
        if (
            ctx.guild.owner == member
            or ctx.author.top_role <= member.top_role
            or ctx.guild.me.top_role <= member.top_role
        ):
            continue
    
        await member.edit(nick=nickname)
#

you need to check if the member is above the bot

#

and the person trying to edit the nicknames

formal basin
smoky sinew
#

client_has_permissions does not exist

formal basin
smoky sinew
#

only bot_has_permissions and has_permissions do

formal basin
#

oh ok never new

frozen flame
#

@smoky sinew what does the two ors mean

smoky sinew
#

to make sure the bot and the person running the command have permission to edit the person's nickname

frozen flame
#

got it

#

thanks!!!

#

@smoky sinewhow can i do it that only the owner of the server can do this command?

frozen flame
smoky sinew
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.
smoky sinew
#

oh it doesn't list it

#

anyway you put it in the bot arguments

dry kelp
#

midkup could u help me with a issue?

smoky sinew
#

my name is 6 letters 😭

dry kelp
#

Here i have this function that i'm calling in multiple commands

#

Basically a manager for all protection antinuke has

#

anyways, how could i get the guild.id inside of the database var ?

smoky sinew
#

huh

frozen flame
#

@smoky sinew i replaced has_premissions to commands_is_owner() is it good?

smoky sinew
#

that's only for the bot owner

formal basin
#

not server

dry kelp
#
class AntinukeSettings(Cog):
    @slash_command()
    @default_member_permissions(administrator=True)
    @is_guild_owner()
    async def antinuke(self, interaction: CommandInteraction):
        guild_id = interaction.guild_id
        database = await AntinukeConfig.get_or_none(guild_id=guild_id)

        if not database:
            logger.info(f"Creating antinuke config... for={guild_id}")
            database = await AntinukeConfig.create(guild_id=guild_id)
            logger.info("Created.")

    async def set_prop(self, group: str, prop: str, toggle: bool):
        logger.info(f"Trying to set {prop}...")

        key = f'{group}_{prop.lower().replace(" ", "_")}'

        database = await AntinukeConfig.get_or_none(guild_id=self.guild.id)

        setattr(database, key, toggle)
        logger.info("OK.")
frozen flame
#

oh 😦

dry kelp
#

here's an example of how i use the set_prop

smoky sinew
dry kelp
#

inside of antinuke creating self.guild = guild

#

but that doesn't matter cause it didn't really work

twilit grotto
#

u have to set it in your antinuke function like
self.guild_id =
not
guild_id =

formal basin
dry kelp
#

What i have to do is to get the guild id inside of the function

frozen flame
dry kelp
#

that has nothing to do with what im trying to do

smoky sinew
smoky sinew
#

if you set your bot as private it would work

dry kelp
#

mudkip this is what i tried to do

smoky sinew
#

but it would be hard to transfer to other servers

dry kelp
#

but it causes issues when the bot is running on prod

#

and also when invoking command multiple times

smoky sinew
#

oh wait

dry kelp
#

In all the commands where the protection configs are

smoky sinew
#

why not just pass guild into the method

dry kelp
#

That's the primary key

#

there is a existing guild id

smoky sinew
#

so why not add a new argument to set_prop

dry kelp
#

But in order to get_or_create i have to call the model using the primary key, to defer guilds

dry kelp
#

all i need is a function inside of the command, it's like a external that im calling

#

But the only problem is that i need to get the guild id

#

is it possible?

smoky sinew
#

from what i'm hearing

#

it sounds like you need to set a setting value for the current guild

dry kelp
#

Because to make my life easier i could just make this function inside of commands

#

But is not a good practice

formal basin
# frozen flame yea doing this for fun

you could do py @commands.has_permissions(administrator=True) which the command will only work for people with the admin perm and the owner already has it

smoky sinew
dry kelp
#

yeah that's the easiest way to do so

#

So look here is a thing that im thinking about

#

inside set_prop it will only be called if there's an existing guild id

#

it won't be called if there's not a existing guild id

#

So database will always be true

#

can't i fetch the guild id from model?

smoky sinew
#

what is the group argument

dry kelp
#

So group will be protections

smoky sinew
dry kelp
#

1 sec lemme explain

#

So look, here u can see this is anti_guild command

#

The items will be all possible securities for that certain command

#

So basically this is the group of "guild" protections

smoky sinew
#

oh

dry kelp
#

Yeah it was made to make my life easier

dry kelp
frozen flame
#

i am getting the error:

"discord.app_commands.errors.CommandAlreadyRegistered: Command 'help' already registered."
#

but i have this line:

client = commands.Bot(command_prefix='+', intents= discord.Intents.all(), help_command=None)
smoky sinew
spiral epoch
#

None

chrome ivy
#

Error is: unterminated string literal
I don't think there's anything wrong with my string though?

embed = discord.Embed(title = f"{message.author}", description = f"Message from {message.author.mention} deleted in ⁠{message.channel.mention}.", colour=discord.Colour.red())
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.

chrome ivy
#

!traceback embed = discord.Embed(title = f"{message.author}", description = f"Message from {message.author.mention} deleted in ⁠{message.channel.mention}.", colour=discord.Colour.red())

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.

potent spear
potent spear
chrome ivy
potent spear
#

aight, then it seems like the code you showed us didn't match your actual code, as that shouldn't happen

chrome ivy
#

I did copy and paste, so idk

potent spear
#

those strange quotations happen on mobile or by copy pasting code from somewhere sometimes

chrome ivy
#

ok

merry spruce
#

how can i make slash command...

smoky sinew
#

i wrote this basic example

merry spruce
smoky sinew
#

what is the error

merry spruce
# smoky sinew what is the error

idont know but it can not run the bot.tree command

@bot.event
async def on_ready():
    print('Bot is ready.')
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)



class TestMenuButton(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Join", style=discord.ButtonStyle.blurple)
    async def test(self, interaction:discord.Interaction, Button: discord.ui.Button):
        await interaction.channel.send(content="Joined")

    @discord.ui.button(label="Start", style=discord.ButtonStyle.green)
    async def start(self, interaction:discord.Interaction, Button: discord.ui.Button):
        await interaction.channel.send(content="Started")






@bot.tree.command(name="Play")
async def Play(interaction: discord.Interaction):
    await interaction.respond.send_message(content="Starting", view=TestMenuButton())
smoky sinew
#

i'm not sure what that means

merry spruce
#

cannot run

#

I just want to create a command when it runs will have to button

sick birch
sick birch
#

What's the tree command? What about it?

merry spruce
sick birch
merry spruce
smoky sinew
merry spruce
smoky sinew
#

and what actually happens?

#

does the slash command appear in your command list?

#

and if so, are you able to run it or do errors appear in the terminal? does the buttons and message appear?

smoky sinew
#

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

timber wren
#

how do I identify if a slash command is used as a reply to a message? and how do I fetch the details about that message... such as the author of the message or the message content?

merry spruce
vale wing
#

Since slash command itself is not one

timber wren
#

i forgot

#

but how do I make work this in in normal prefixed commands?

vale wing
#

You want to get a message the command replies to?

vale wing
#

ctx.message.reference.resolved

timber wren
#

is it a if, else

timber wren
#
@discord.slash_command(name='mock', description='🐒 DoNt mOcK mE!')
    async def mock(self, ctx: discord.ApplicationCommand):
        test_str = ctx.message.reference
        res = ""
        for idx in range(len(test_str)):
            if not idx % 2:
                res = res + test_str[idx].upper()
            else:
                res = res + test_str[idx].lower()
        await ctx.respond(res)
vale wing
#

If no reply the reference will be None iirc

timber wren
#

i tried smth like this

vale wing
#

No man there's no message in slash commands

timber wren
timber wren
vale wing
#

It will only work for prefix

timber wren
#

hmmm

vale wing
#

Instead you can just do message command lol

timber wren
#

yep!

#

but then what do I pass in ctx argument?

#

like I have it as ctx:discord.ApplicationCommand

#

what do I replace it with?

vale wing
#

First it's not even ctx

#

It's interaction

timber wren
#

mhm

#

okay thinkmon

#

then?

vale wing
#

Tf knows

timber wren
#

no lmao

vale wing
#

Then what is this

timber wren
#

pycord but yeah same shit

vale wing
#

I heard pycord is like the worst out of dpy forks

timber wren
#

iknow

#

pycord is shit

#

but its working for me so i don wanna touch it

#

one of the most important rules of programming... if it works dont touch it

vale wing
#

Tbh that's rule of beginners and non-professionals

north kiln
#

Does pycord auto sync slash commands ducky_sphere

vale wing
#

The program needs to be

  • working
  • readable
  • efficient
#

At least

#

Sometimes efficiency can be sacrificed for readability tho

smoky sinew
#

well ||you're right|| in my opinion

timber wren
slate swan
sour sand
#

Do you guys think that 2nd bot is ok ?

#

and wich utils / moderation commands should i add ?

#

(they are all functionnal, feel free to ask to see)

slate swan
#

Why do people create second, third, fourth, etc. bots instead of focusing on one and then those bots just have the same commands as all bots have. Come on, be original kek

sour sand
#

The seconde was juste trash, its just a utility bot dude, not more

#

a private one, just to not be unoriginal and not just having mee6 py_guido

naive briar
sour sand
#

mee6 is trash

#

but if someone have mor ideas, it would be great if you would give me

slate swan
#

Look what other bots have, copy

sour sand
#

i wanted to do a /code

slate swan
#

And bots don't have RPC

sour sand
slate swan
#

So you can't have a RPC command

sour sand
#

then i'll rename it statute

#

i want to do smth like this so bad

slate swan
#

then do it duh

sour sand
#

ye

#

but its not this util

naive briar
#

What

sour sand
#

like its cool

#

but i want somethin' that's util

wraith wing
#
    @discord.ui.button(label="Ban", style=discord.ButtonStyle.green, emoji=":hammer:")
    async def ban_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message("Sunucudan yasaklandı")
        await self.member.ban(reason="5 uyarı aldı")

AttributeError: 'Button' object has no attribute 'response' ```

I couldn't solve the error
rugged shadow
#

it's supposed to be interaction that comes first

wraith wing