#discord-bots

1 messages · Page 345 of 1

dense swallow
#

yeah true

#

so this should work ```py
for reaction in message.reactions:
if not reaction.count:
msg = await star_channel.fetch_message(em_id) # type:ignore
await msg.delete()
(
await self.bot.db.execute(
"DELETE FROM star_info WHERE guild_id=$1 AND bot_msg_id=$2",
guild.id,
em_id,
)
if self.bot.db and guild
else None
)

                elif reaction.count < star_count:
                    if not self_star:
                        if message.author == payload.member:
                            return await message.remove_reaction(payload.emoji, payload.member)  # type: ignore

                    star_embed = await star_channel.fetch_message(em_id)  # type: ignore
                    await star_embed.edit(content=f"⭐ **{reaction.count}** | {channel.mention}")  # type: ignore
hushed galleon
#

?

#

thats still basically the same

#

if the last reaction was removed, there won't be any ⭐ reaction listed in message.reactions

#

you can only tell if it has 0 stars by seeing if a reaction with that emoji exists

dense swallow
#

yes

#

im exiting the event if the emoji is not ⭐

hushed galleon
#

but your for loop still assumes that the reaction object exists

#

once the last reaction is removed, message.reactions will return an empty list [], so do you get what happens when your for-loop tries to iterate over that list?

dense swallow
hushed galleon
#

dont you want to delete the starboard message once the reaction's gone though?

dense swallow
#

hm, i can do that before that return

#

but this is what u were saying right?

#

if this any of this is true, it exits

hushed galleon
#

^ this point stands too, technically the message can have other reactions besides a ⭐ so you want to be mindful of that

dense swallow
#

ahh

dense swallow
#

if its only star, it will work

hushed galleon
#

message.reactions can still return other emojis

dense swallow
#

or i can put that as another if statement

#
        if message.author.bot or payload.emoji.name != "⭐":
            return
        
        if not message.reactions:
            msg = await star_channel.fetch_message(em_id)  # type:ignore
            await msg.delete()
            (
                await self.bot.db.execute(
                    "DELETE FROM star_info WHERE guild_id=$1 AND bot_msg_id=$2",
                    guild.id,
                    em_id,
                )
                if self.bot.db and guild
                else None
            )
            return
hushed galleon
#

if you had a message with two reactions, 🤖 and ⭐, and the ⭐ gets removed, you are still left with 🤖 so message.reactions will not be an empty list even though there are 0 stars

dense swallow
#

so what'd u suggest

hushed galleon
#

this

#

find the reaction object for ⭐, if it doesn't exist then you know there are 0 stars, if it does exist then there is at least 1 user that still has a star

dense swallow
#
        emoji = discord.utils.get(message.reactions, emoji="⭐")

        if message.author.bot or not emoji:
            return
#

good?

hushed galleon
#

do you still want to delete the starboard message after 0 stars?

dense swallow
#

yeah

#
    @Cog.listener(name="on_raw_reaction_remove")
    async def starboard_reaction_remove(self, payload: discord.RawReactionActionEvent):
        guild = self.bot.get_guild(payload.guild_id) if payload.guild_id else None
        channel = guild.get_channel(payload.channel_id) if guild else None
        message = await channel.fetch_message(payload.message_id)  # type: ignore
        emoji = discord.utils.get(message.reactions, emoji="⭐")

        if message.author.bot or not emoji:
            return
        
        em_id = (
            await self.bot.db.fetchval(
                "SELECT bot_msg_id FROM star_info WHERE guild_id=$1 AND user_msg_id=$2",
                guild.id,
                payload.message_id,
            )
            if self.bot.db and guild
            else None
        )
        
        if not message.reactions:
            msg = await star_channel.fetch_message(em_id)  # type:ignore
            await msg.delete()
            (
                await self.bot.db.execute(
                    "DELETE FROM star_info WHERE guild_id=$1 AND bot_msg_id=$2",
                    guild.id,
                    em_id,
                )
                if self.bot.db and guild
                else None
            )
            return

hushed galleon
#

then dont return early yet

#

you can replace the not message.reactions condition with your emoji check for that

dense swallow
#

if not emoji?

hushed galleon
#

sure?

dense swallow
#

so i can replace all occurences of message.reactions with emoji ?

red blade
#

inside an app commands group, how would you do a subgroup?

hushed galleon
hushed galleon
#

oh right you said inside a group

#

for subclassing ya, that example works too

dense swallow
hushed galleon
#

your if message.author.bot or not emoji: return line is going to prevent it from reaching the message deletion

red blade
#

ok ty

dense swallow
#

ping me when ur back

young dagger
#

How do I deploy changes with Docker? Do I need to stop the container, remove it, rebuild it with the new .py code, and then run to apply the changes?

young dagger
#

I mean I could create a shell script

#!/bin/bash

docker stop blitzcrank
wait
docker rm blitzcrank
wait
docker rmi blitzcrank
wait
docker build -t blitzcrank .
wait
docker run -d --name blitzcrank --restart always -t blitzcrank```
#

And run it in the current directory

#

Or is there any better way to do it?

fallow python
#

Given this function async def _alarm(interaction, hour: int = -1, min: int = -1):
Can I specify that I either need no arguments or both hour and min?

#

(discordpy command)

#

I guess basically an object or tuple argument in the function signature

hushed galleon
fallow python
#

Ah okay. I was hoping there was a way to say "Either no argument to trigger one overload, or these 2 arguments if you need the other version"

#

But if that isn't possible I'll have to rethink

fallow python
#

Using this from discord.ext tasks only runs once. I was under the impression it would run every 0.1 seconds?

@tasks.loop(seconds=0.1)
async def _check_alarms_loop():
    print('tick')
#

Ah I got it. Forgot to call start

fallow python
#

Is it possible to get some sort of context from a Client? (client = discord.Client(intents=intents))
Or do I have to manually go through the guild list and channel list to find the right channel to send to?
I don't have a context object in my thread, but I need to send a message to my channel.

hushed galleon
fallow python
#

What if the resulting message that comes from that alarm should be sent in a different channel than where it was created?

#

Do I just designate a channel to that and save the channel with that id?

red blade
#

can you use context menus in a cog?

fallow python
#

My problem currently, is that I don't know how to include a context with this looping task:

@tasks.loop(seconds=0.5)
async def _check_alarms_loop():
#

Because that looping task will eventually trigger a function that requires a context of some kind to send a message

#
async def _broadcast_alarm(user_id, ctx = None):
    if isinstance(ctx, discord.interactions.Interaction):
        await ctx.channel.send(<message>)
        await ctx.response.send_message('', ephemeral=True, delete_after=0.01)
    else:
        await ctx.channel.send(<message>)
hushed galleon
hushed galleon
#

oops

#

i recommend refactoring it so you only need the timestamp, channel ID, and message content for each alarm

fallow python
#

What would the timestamp do for me?

hushed galleon
#

also interactions have to be responded to within 3s and the followup webhook it provides will only last for 15min so they won't be of much use for your long-running alarms

hushed galleon
fallow python
#

I have a bunch of datetimes for that. Works as expected.
My biggest issue is how I get a context. Because the background task that checks every alarm and whether they should trigger or not has no context to send messages through

#

So I'm unsure how your suggestion would help there as I would still need a context

hushed galleon
#

the channel ID can be used with the bot object to retrieve the channel object that'll let you send messages to

#

i guess you could store a context object in said list, but designing your code around a context makes it difficult to make your alarms persistent in a database

fallow python
#

I tried making a bot instead of a client.
The get_guild() function returned an empty channel list when I then called get_channel() or when trying to iterate over guild.channels

hushed galleon
#

did you not enable the guilds intent?

fallow python
#

I did online, but I probably forgot in code.

#

should do it like this?
intents = discord.Intents(messages=True, guild=True)

hushed galleon
#

its not a privileged intent so you dont need to enable it in the dashboard

#

for simplicity you can use discord.Intents.default() and then tack on whatever privileged intents you do need, like: py intents = discord.Intents.default() intents.message_content = True but if you want to be explicit, you should be careful about which intents you leave out because some like guilds= affect many features of dpy

fallow python
#

But so for this particluar issue, I do need guilds right?

hushed galleon
#

yes

fallow python
#

Okay.

hushed galleon
fallow python
#

Yeah doing the intent thing worked. Thanks @hushed galleon
I was going insane for a bit there 🥲

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @nimble timber until <t:1709867414:f> (10 minutes) (reason: emoji spam - sent 23 emojis).

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

nimble timber
#

So, I wanted to know if there is a way to make a command in a discord bot with what is described below:

I'm making an rpg bot for discord using python. I want to make a command with the name "h!profile", this command will send the following message in embed:

**╭┄┄┄┄┄┄⇢ Profile ⇠┄┄┄┄┄┄╮**

  **This Will Show Your Information.** 

**⊱⋅ ────── ❴ • ✿ • ❵ ────── ⋅⊰**

**❪  ❫ Name. . . ⇢ User**

**❪  ❫ Title. . . ⇢ Not defined**

**❪  ❫ Element. . . ⇢ Not defined**

**❪  ❫ Race. . . ⇢ Not defined**

**❪  ️ ❫ Class. . . ⇢ Not defined**

**❪  ❫ Rank. . . ⇢ Not defined**

**❪  ❫ Mastery. . . ⇢ Not defined**

**❪  ️ ❫ Cardinal Hero. . . ⇢ Not defined**

**❪  ❫ Unique Skill. . . ⇢ Not defined**

**❪  ❫ Blessing. . . ⇢ Not defined**

**❪  ❫ Curse. . . ⇢ Not defined**

**❪  ❫ Buffs/Debuffs. . . ⇢ Not defined**

**⊱⋅ ────── ❴ • ✿ • ❵ ────── ⋅⊰**

**❪  ❫ HP. . . ⇢ Not defined**

**❪  ❫ Ikari. . . ⇢ Not defined**

**❪  ❫ Core. . . ⇢ Not defined**

**❪  ❫ Strength. . . ⇢ Not defined**

**❪  ❫ Physical Defense. . . ⇢ Not defined**

**❪  ❫ Magic Defense. . . ⇢ Not defined**

**❪  ❫ Speed. . . ⇢ Not defined**

**❪  ❫ Melee Weapons. . . ⇢ Not defined**

**⊱⋅ ────── ❴ • ✿ • ❵ ────── ⋅⊰**

  **Read The Status System!**

**╰┄┄┄┄┄┄⇢ Status ⇠┄┄┄┄┄┄╯**
#

however, the "not defined" in the message will be replaced by variables, these variables will already have a defined value, for example: hp variable with a value of 5,000. These variables can be modified by the command "h!set-<variable> <user> <quantity>", example: h!set-hp roger 6,000", then when roger uses "h!perfil" it will show 6,000 instead of "5,000" or "not defined". This command can only be used by specific positions and it will only change the status of the person mentioned, that is, if roger has his hp changed to 6,000 and christian uses "h!perfil" it will show on christian's profile that he has 5,000 and roger's 6,000

shadow vigil
#

other than that, i am not sure what are you asking for

vapid parcel
#

Okay, so I am trying to make something like DiscordGSM, but I can't find a good API that is kinda fast. The one I have rn, when a server goes offline, it takes like 30 minutes to even update.

The games I am mainly looking for are

  • Unturned
  • Minecraft (2009)

If there is a better way of doing this without an API please let me know!

vapid parcel
#

Its a bot that monitors game servers.

shadow vigil
#

if so, that should be easy

vapid parcel
#

I am looking for a good API that will do it for me. Because the current API that I have, it doesn't refresh its data until after 30 minutes, which isn't really good.

Or I am asking if there is a way to do it without an api. Which I don't think there is.

#

But their api takes 30 minutes to refresh, which isn't really good because by the time it refreshes, the server would be back up, showing the server never went down, even tho it did.

hushed galleon
#

i use that endpoint for my bot's arma server status and it updates fairly quickly, at least quick enough for 1 minute refreshes

faint rapids
#

Is there any way to edit the "about me" section using discord.py?

faint rapids
upbeat otter
#

yes

faint rapids
#

How?

upbeat otter
faint rapids
#

ah

upbeat otter
faint rapids
#

I understand, but this method is manual. I want to automate it with code.

north kiln
#

why?

#

why not use something like rich presence?

pine veldt
#
for s in self.bot.guilds:
   embed=discord.Embed(title="Guild that are bot is join", description=f"""**Server name** :- {c}
**Server ID** :- {c.id}
**Server Owner** :- {c.owner}""")
   await ctx.send(embed=embed)```
Why this not working
#

This is not sending anything

pine veldt
#

I changed the description of embed then it's working

vestal acorn
#

?

pine veldt
vestal acorn
#

oh ok

#

and what was the problem?

pine veldt
#

@vestal acorn

#

I found that

#

@vestal acorn

vestal acorn
#

yup

#

show me

pine veldt
#

I Said for s
And sending {c}

#

Lol

#

@vestal acorn

#

Check the code

vestal acorn
#

oh

clear harness
#

Mm

vestal acorn
#

I see

vapid parcel
#

Not to be rude either, just truly asking ^^

finite salmon
jovial talon
#
from discord.ext import commands
from discord import Intents

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

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

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

@bot.tree.command(name="hello", description="Says hello to the user")
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message(f"Hello, {interaction.user.display_name}!")

bot.run('')```

Can someone explain why my bots slash commands won't show up?
sick silo
#

hello all, where you using server to discord-bot? Are on cloud or your computer?

naive briar
#

Self-host

upbeat otter
cyan jolt
#

i want to make a python bot with discord.py, if i want to make a lot of commands do i need to make them all on the same file?

pine veldt
cyan jolt
pine veldt
cyan jolt
pine veldt
#

?tag cogs

novel apexBOT
#

This is not a Modmail thread.

pine veldt
#

Hmm

pine veldt
pine veldt
#

And also you have to add that file in your bot main file by using
await bot.load_extension("cogs file path")

dusk ermine
#

i need help

pine veldt
jovial talon
dusk ermine
#

what I do

vestal acorn
dusk ermine
#

do I then from discord.ui import Button, etc?

vestal acorn
slate swan
#

examples ^

steady acorn
#

Hello, I am trying to get my discord bot to send out a command after a certain amount of time that another command has happened.

async def handleCheckin(interaction):
    await asyncio.sleep(600)

    global isCheckinActive
    if isCheckinActive:
        isCheckinActive = False
        await getPreviousMessageAndDelete()
        await volunteercheck(interaction)

however when I tried to do it that way, it spits out the error, "'Command' object is not callable"

(code for volunteercheck)

async def volunteercheck(interaction):
    view = volunteerButtons()
    await interaction.response.send_message('The Volunteer check has started! You have 10 minutes to volunteer if you wish to sit out', view = view)
#

Could someone help me with this?

civic sparrow
#

How can i have an appcommand argument perform a lookup on disk with an sql database for a big dataset?

storm zodiac
#

is there any "slash" only package ?

cloud dawn
cloud dawn
#

Extensions and reloading, loading, unloading are pretty doable things to re-create and worth it in my opinion to do to get the desired behaviour.

slate swan
#

hello

civic sparrow
#

how would i be able to get any extra information inside my auto complete func

#

like i need to know what table i want to search in when performing the search in my autocomplete func

#

nevermind figured it out

slate swan
#

Im getting this error message below

Traceback (most recent call last):
File "main.py", line 20, in <module>
Intents.messages.content = True
AttributeError: 'bool' object has no attribute 'content'

#

hello

vapid parcel
vapid parcel
hushed galleon
#

does it say the same on the battlemetrics dashboard for that server?

vapid parcel
#

huh?

#

Server clearly offline on my end tho.

hushed galleon
vapid parcel
#

Yeah

#

thats what I said, which I have no clue how to up that

#

I mentioned the api was slow with it, so thats why I was wondering if there was another API

#

I did explain poorly, but I was really tired lol

hushed galleon
#

i know there's that yellow button that lets you manually refresh, but you probably should ask in battlemetrics's discord server for a way to increase the query frequency
https://www.battlemetrics.com/contact

there's also the Server Force Update endpoint but it says that's "limited to subscribers and users who belong to the organization that owns the server if it is claimed" (not sure if that means you can use it on unclaimed servers or as a separate party from the owning organization)
(also returns 202 Accepted so it probably won't be updated immediately)

vapid parcel
hushed galleon
#

oh you're using it for a server you own? should be good then

vapid parcel
#

Yeah

#

well, not for a server I own, but my friend owns, so this will go easy

vapid parcel
stark ingot
stark ingot
# steady acorn Hello, I am trying to get my discord bot to send out a command after a certain a...

You need to invoke it in a special way. https://docs.pycord.dev/en/stable/api/application_commands.html#discord.ApplicationContext.invoke
Note this would be something like ctx.invoke() or interaction.invoke()

slate panther
#

how can i learn to make a discord bot

slate swan
#

hello

shrewd apex
#

and official discord.py docs are a good place to start

#

u can also ask any doubts you have here

slate swan
#

hello i currently have a bot that generates a challonge tournament link based off the people in the vc and sends it in a channel, how do i make it send an image of the challonge link?

formal valve
formal valve
slate swan
formal valve
slate swan
#

thats what i need help with

#

i dont know what to do to create the image

formal valve
#

Are you coding in python?

slate swan
#

yes

formal valve
#

Then it has nothing to do with the discord. You need to make a function to return you with an image and call that function inside your discord bot function.

quartz junco
#

is there anyone already tried to use discord as a c2 server

#

is that work?

warm lotus
#

Hey guys, im looking for a discord bot that can run with discord.py. the only finctionality it needs to be able to do is log in, and post a message that the py script will generate

#

any ideas?

pine veldt
#

How to use topggpy

#

Some basic

warm lotus
pine veldt
pine veldt
#

@hushed galleon

formal valve
quartz junco
formal valve
hot solar
red blade
#

how can i get a list of all slash commands?

#

including slash commands in groups

slate panther
shrewd apex
#

all the videos are pretty outdated

#

for api docs u can look at discord devs api documentation

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1709993382:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

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

slate swan
#

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

!d discord.app_commands.CommandTree.walk_commands

unkempt canyonBOT
mild token
#
from discord.ext import commands

import discord
import traceback

class CounterBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')

class Feedback(discord.ui.Modal, title='Feedback'):

    name = discord.ui.TextInput(
        label='Name',
        placeholder='Your name here...',
    )

    feedback = discord.ui.TextInput(
        label='What do you think of this new feature?',
        style=discord.TextStyle.long,
        placeholder='Type your feedback here...',
        required=False,
        max_length=300,
    )

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)

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

        traceback.print_exception(type(error), error, error.__traceback__)



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


    
    @discord.ui.button(label='Verify', style=discord.ButtonStyle.red)
    async def count(self, interaction: discord.Interaction, button: discord.ui.Button):

        await interaction.response.send_modal(Feedback())




bot = CounterBot()


@bot.command()
async def test(ctx: commands.Context):
    """Starts a counter for pressing."""

    await ctx.send('Press!', view=Counter())


bot.run('BOT TOKEN')

i want bot button dont expire

mild token
#

anyone?

uncut remnant
#

has someone nice functions about i want to create a Security bot

vestal acorn
#

these are just some ideas

vestal acorn
#

you're welcome

civic sparrow
#

Anyone know how to resolve when i have two choices in a list with the same name but different values they both result in the same value when selected in an app command?

#
choices = []
choices.append(app_commands.Choice(name="Foo", value=1))
choices.append(app_commands.Choice(name="Foo", value=2))

@bot.tree.command(name="abc", description="123")
@app_commands.choices(myarg=choices)
async def abc(ctx: discord.Interaction, myarg: int):
     assert(myarg==1) # will always be triggered
``` this is basically what im doing, it will always result in `1` no matter which `Foo` i choose
dusk ermine
#
  File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\lucia\Desktop\Bot Discord\Python\Bready Bot Totali\BreadyMC General\main.py", line 212, in ticket
    await ctx.send(embed=embed, components=[select])
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Context.send() got an unexpected keyword argument 'components'

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

Traceback (most recent call last):
  File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Context.send() got an unexpected keyword argument 'components'```
civic sparrow
slate swan
#

can anyone help with my selfbot

#

i just need config file for it

dusk ermine
#

@civic sparrow
Hi, I was wondering if you could help me with just one thing:
Is this part of the code ok or does it need to be changed? Because it gives me an error
await

ctx.send(embed=embed, components=[select])

slate swan
#

Then show the error

civic sparrow
#

you need to find and use the fork that allows that

#

or use views like th above examples

#

i wouldnt use forks for some layer of abstraction and learn properly, especially since it can become desynced with the origin dpy

sick birch
unkempt canyonBOT
#

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

sick birch
#

We don't help with self bots

autumn pumice
#

Hoy

#

do you know if Im able to get a bot to blacklist a server

#

from joining another server

ebon ocean
#

Got question I feel some of y'all might know.

ctx.author.display_name <-- Will show secondary discord user name in profile.

ctx.author.display_avatar <-- Will show discord user profile picture icon.

??? <-- Will show discord user name as seen directly in posts.

??? <-- Will show user id number.

Anybody know what the missing ones are called?

sick birch
ebon ocean
#

Finally. Thank, some good news.

ebon ocean
#

ctx.author = robinj#0
ctx.author.display_name = robinj

How do you get it to show the actual user name shown?!

#

I been trying to figure this out for months!

What is used to show "TailsTellsTales" instead of "tailstellstales" for example.

naive briar
#

What

vestal acorn
#

Iirc

slate swan
#

but if this doesnt work you can try author.nick or author.name

pine veldt
#

?tag author

novel apexBOT
#

This is not a Modmail thread.

dusk ermine
#

Hi, when I put options=options it gives me an error, why? The error is with has not been defined.

red blade
#
    @discord.ui.button(label = "Quit", style = discord.ButtonStyle.danger)
    async def quit(self, interaction: discord.Interaction, button: discord.ui.Button):
        if await self.check(interaction):
            for child in self.children:
                child.disabled = True
            self.stop()``` am i missing something here?
potent light
potent light
naive briar
#

If so, you'd have to edit the message with the view again to update the buttons' states

potent light
red blade
#
import discord
from typing import Union

class Pagination(discord.ui.View):
    def __init__(self,
                 interaction: discord.Interaction,
                 messages: Union[list, tuple],
                 embed_title: str,
                 embed_color: discord.Color = discord.Color.default()):
        super().__init__()
        self.interaction = interaction
        self.messages = messages
        self.embed_title = embed_title
        self.embed_color = embed_color
        self.current_page = 0

    async def check(self, interaction):
        if interaction.user == self.interaction.user:
            return True
        else:
            await interaction.response.send_message(
                embed = discord.Embed(description = ":x: You cannot interact with this message",
                                                                          color = discord.Color.red()))
            
    def update_message(self):
        embed = discord.Embed(title = self.embed_title,
                              color = self.embed_color,
                              description = f"Page {self.current_page + 1} / {len(self.messages) + 1}\n\n{self.messages[self.current_page]}")
        return embed

    @discord.ui.Button(label = 'Next')
    async def next(self, interaction: discord.Interaction, button: discord.ui.Button):
        if await self.check(interaction):
            if self.current_page == len(self.messages):
                self.current_page = 0
                self.update_message()
            else:
                self.current_page += 1
                self.update_message()``` why am i getting `Button` object not callable?
red blade
#

@discord.ui.Button(label = 'Next')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Button' object is not callable

#

wait im an idiot 😭

dusk ermine
potent light
shadow vigil
feral burrow
#

hi guys , i have been studying python and i know the basic , but i want to get the things to the next level , someone can gie me advices ?<3

golden portal
slate swan
#

.topic

lament depotBOT
#
**What unique features does your bot contain, if any?**

Suggest more topics here!

onyx ether
#

hello . i have question. im still learning and trying to make macro bot, for few aplication on same time, did anyone know how to inject 1 script to many aplication

rugged shadow
#

!rule 5

unkempt canyonBOT
#

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

red blade
#

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In data.components: Must be between 1 and 5 in length. why could i be getting this in a modal?

hushed galleon
#

well, modals are limited to 5 text inputs...

#

what does your modal look like?

red blade
#

i have one input 😭

hushed galleon
#

what does your code look like? it might getting duplicated unintentionally

red blade
#
class GoToPage(discord.ui.Modal, title = "Go To Page"):
    def __init__(self, pagination):
        super().__init__(timeout=None)
        self.pagination = pagination
        self.page_input = discord.ui.TextInput(style = discord.TextStyle.short, label = "Enter a page", placeholder = f"Enter page number")```
It is this and then I handle the input underneath
hushed galleon
#

oh, you haven't added the text input

red blade
#

huh?

hushed galleon
#

its like views, if you create a button inside init then you need to call self.add_item(component) to add it

#

though for modals i recommend defining them as class attributes so its automatically added

#

i.e. ```py
class MyModal(discord.ui.Modal, title="..."):
my_input = discord.ui.TextInput(...)

async def on_submit(self, interaction):
    await interaction.response.send_message(f"You submitted: {self.my_input.value}")```
red blade
#

so like this should work self.page_input = self.add_item(discord.ui.TextInput(style = discord.TextStyle.short, label = "Enter a page", placeholder = f"Enter page number"))

hushed galleon
#

err, not in the way you think it will

red blade
#

oh its because i need to be accessing the self

hushed galleon
#

that technically adds it, but add_item always returns None so self.page_input won't actually contain the text input

red blade
#

oh

hushed galleon
#

i'd just add it on a separate line, as in: py self.page_input = discord.TextInput(...) self.add_item(self.page_input)

red blade
#

oh thank you that works

glossy topaz
#

how can i get my bots message id after using py await interaction.response.send_message(embed=em, view=view)

hushed galleon
unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
glossy topaz
#

thanks

mossy jacinth
#

How do I add a description to arguments?

slate swan
unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
mossy jacinth
#

thanks

slate swan
#

Trying to force a layout like this by entering a fake 'release date' field within the value of 'length'.

However, if you look closely at the images below you can see bold characters are a tiny bit different from actual field names. Is this as close as I can get? or is there a different way to approach this?

#

If it's too hard to see, the fake field name is slightly thicker than the real field name

safe stag
#

Hello dear community, I need your help. How can I have the database retrieve the name and then insert it here?

options = [
     discord.SelectOption(label="test", emoji=":ticket:"),
]```
 I have everything in the database but I don't know how to transfer the names into the option
safe stag
# upbeat otter what db are you using?
class TicketDB(ezcord.DBHandler):
    def __init__(self):
        super().__init__("db/ticket.db")

    async def setup(self):
        await self.execute(
            """CREATE TABLE IF NOT EXISTS ticket(
            server_id INTEGER PRIMARY KEY,
            category_id INTEGER DEFAULT 0,
            teamrole_id INTEGER DEFAULT 0,
            logs_channel_id INTEGER DEFAULT 0,
            ticket_channel_id INTEGER DEFAULT 0,
            set_name_count INTEGER DEFAULT 0,
            panel_name TEXT DEFAULT NULL
            )"""
        )

    async def set_category(self, server_id, category_id):
        await self.execute(
            "INSERT INTO ticket (server_id, category_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET category_id = ?",
            (server_id, category_id, category_id)
        )

    async def get_category(self, server_id):
        return await self.one("SELECT category_id FROM ticket WHERE server_id = ?", (server_id,))

    async def set_teamrole(self, server_id, teamrole_id):
        await self.execute(
            "INSERT INTO ticket (server_id, teamrole_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET teamrole_id = ?",
            (server_id, teamrole_id, teamrole_id)
        )

    async def get_teamrole(self, server_id):
        return await self.one("SELECT teamrole_id FROM ticket WHERE server_id = ?", (server_id,))

    async def set_logs_channel(self, server_id, logs_channel_id):
        await self.execute(
            "INSERT INTO ticket (server_id, logs_channel_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET logs_channel_id = ?",
            (server_id, logs_channel_id, logs_channel_id)
        )

    async def get_logs_channel(self, server_id):
        return await self.one("SELECT logs_channel_id FROM ticket WHERE server_id = ?", (server_id,))

    async def set_ticket_channel(self, server_id, ticket_channel_id):
        await self.execute(
            "INSERT INTO ticket (server_id, ticket_channel_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET ticket_channel_id = ?",
            (server_id, ticket_channel_id, ticket_channel_id)
        )

    async def get_ticket_channel(self, server_id):
        return await self.one("SELECT ticket_channel_id FROM ticket WHERE server_id = ?", (server_id,))

    async def get_press_count(self, server_id):
        result = await self.one("SELECT set_name_count FROM ticket WHERE server_id = ?", (server_id,))
        return result if result is not None else 0

    async def increment_press_count(self, server_id):
        current_count = await self.get_press_count(server_id)
        new_count = current_count + 1
        await self.execute("UPDATE ticket SET set_name_count = ? WHERE server_id = ?", (new_count, server_id))

    async def set_panel_name(self, server_id, panel_name):
        await self.execute(
            "UPDATE ticket SET panel_name = ? WHERE server_id = ?",
            (panel_name, server_id)
        )

    async def get_panel_name(self, server_id):
        return await self.one("SELECT panel_name FROM ticket WHERE server_id = ?", (server_id,))


db = TicketDB()```
hushed galleon
# safe stag Hello dear community, I need your help. How can I have the database retrieve the...

generally you add your own parameters to the View/Select constructor and then pass whatever data it needs to produce the desired options, for example: ```py
class ToyView(discord.ui.View):
def init(self, toys):
super().init()

    self.toy_select.options = [
        discord.SelectOption(label=toy, ...)
        for toy in toys
    ]

@discord.ui.select()
async def toy_select(self, interaction, select):
    ...

Fetch the data from your database then pass it to your view:

toys = await db.get_toys()
view = ToyView(toys)```

safe stag
#

ah thx

jolly lagoon
#

Anyone know how to make data save even when the bot turns off?

red blade
#

Does anybody know how to do this: I saw a bot in a different server, and i ran a slash command. I didnt have permission and it sent an error message, not customised but looks like a default message from discord. Could this have been a glitch and I shouldnt have been able to run it in the server integrations?

red blade
jolly lagoon
red blade
jolly lagoon
red blade
#

yes

#

that will save when the bot is off

#

just make sure you connect to the database before trying to retrieve data

jolly lagoon
jolly lagoon
red blade
# jolly lagoon It doesn't seem to work maybe im doing it wrong?

well because storing data in anything other than variables in the source code should stay when you stop running the code. I don't use SQL, I use Mongo so i'm not too sure, but I know when done correctly all data will stay in the database. Sorry for not being able to help

slate swan
#

i keep getting this error can anyone help

slate swan
unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

can i send to you and you maybe do it

#

No cause we are here to help you not code for you

jolly lagoon
#

I've got a questions for some reason my code keep saying user id is not defined.

slate swan
#

i keep getting this now

vale anvil
jolly lagoon
vale anvil
#

it might be an issue with get_profile, which appears to override the argument variable user_id with another value. but from what i can tell there is no undefined user_id variable in the code

latent jay
#

I keep getting ClientConnectorError on one of my bots, after a while

errant wind
#

intents = Discord.Intents.(default(all))

#

Something like that ig

upbeat otter
slate swan
slate swan
pale zenith
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
#

sec

pale zenith
slate swan
pale zenith
slate swan
#

oh

#

so i delete that?

slate swan
pale zenith
#

if your config file does have the intended users then yes, deleting the second definition would fix that

slate swan
#

lemme try

slate swan
#

44 43

pale zenith
#

consider taking a bit of time to learn the basics of python before diving right into something like discord.py (it is not super beginner friendly)

pale zenith
slate swan
pale zenith
#

and, does it work now?

slate swan
#

i was asking something ban_cry

pale zenith
pale zenith
#

!rule 5

unkempt canyonBOT
#

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

slate swan
#

ah

pale zenith
#

I shall step out of this conversation now. Adios

slate swan
slate swan
cloud dawn
pale zenith
#

yeah ik

#

removed in v2.0 iirc

#

non-functioning since v1.7 (?)

untold bear
#
@commands.Cog.listener()
    async def on_message(self, message):
        banned_words = ["shit"]
        print(message.content)
        for word in banned_words:
            if word in message.content.lower():
                await message.delete()
                await message.channel.send("That is a banned word!")
        await self.bot.process_commands()

Any reason for why this isnt printing anything? I have intents enabled for everything as well

untold bear
#

on_message_edit and on_message_delete work normally for me, im only having a problem with on_message

pale zenith
untold bear
untold bear
#

nvm i found the issue, there was some other on_message event in my code which was overriding this

slate swan
#

nothing

brazen raft
#

@slate swan #python-discussion message Are you using discord.py? What version? Since 2.0, you should do member.avatar.url and not member.avatar_url. Also, instead of whatever you're doing at the top there to default to the author, you can do this:

@client.command()
async def avatar(ctx, member: discord.Member = commands.Author):
    ...
slate swan
#

If someone wanna do a chatbot with custom data dm me for join the project

halcyon cosmos
#

I had a bit of a funny joke idea. Basically listen to voices for specific movie quotes then play that sound byte from the movie

weary citrus
#

maybe you're missing intents?

weary citrus
#

can you show the part of your code where you make the Bot?

#

so it works for that command but none of the others?

merry cliff
#

There’s no point enabling all intents if you override it with default intents again

weary citrus
#

can u show all of your code?

#

Oh it's your on message

#

make @client.event into @client.listen()

#

for on_message

weary citrus
#

does it not work when you pass in member or only when you pass it in?

winter lodge
#

I want to write a discord bot that is unique and provides practicality but I am not able to come up with an idea. Any suggestions?

#

It's better to ask the people themselves what they prefer/would use

sick birch
winter lodge
#

Actually I was thinking of:

  1. A forum management bot that manages the forums channels on discord. As well as being able to enable "macros" that adds more functionality to the forum.

For example, a macro that will add "upvotes" and "downvotes" to a post. And some commands within the macro that will display the stats of a post.

  1. Kind of an experiment tbh, a discord bot that manipulates the server using AI. The user will be able to just ping the bot and type in their request, something like "@bot create a text channel of name 'general', add the default permissions" or "@bot create a new channel 'replica' and replicate 'general' channel".

As I mentioned, I want to try it out as an experiment to see if it's actually more efficient.

  1. Open Source bot, basically the bot can be hosted by anyone. This bot will have an interactive dashboard that will allow user to add/remove "plugins", these plugins will be features for the bot. Basically anyone can write and publish their plugin.

I would like to know your input on these ideas. And if you have any criticism/feedback please share it.

vestal acorn
#

at first, there are only a few plugins built in, like some classic moderation, tickets or other, and then functionnalities of the bot would improve with time

winter lodge
vapid parcel
#

How to make nsfw commands only show up in nsfw channels?

#

I think there is a way to do that right?

#

This is all I have found, which is for cogs, I am kinda just trying to do it for commands?

upbeat otter
vapid parcel
#

Yes ^

#

Trying to do it for sub commands, which I can't find anything, or Im looking in the wrong spot

upbeat otter
vapid parcel
upbeat otter
vapid parcel
#

Yes

upbeat otter
#

and restart your client

vapid parcel
#

Yes

upbeat otter
#

that's weird hmm. I'm not quite sure if you can do that then

vapid parcel
#

I mean you can with cogs, but the issue with me doing just the cog is it also has SFW not just only NSFW, meaning the SFW would have to be in a NSFW channel, I am not really trying to seperate the cogs when there should just be a way to have a check on it..

#

Put it true inside of the command itself, and I also put it true inside of the group

#

It seems to just not be a thing, unless there is a differen't way of doing it.

#

Here it shows nothing abt NSFW argument, so I am just going to fully assume that only cogs can do it and not commands or groups maybe?

Same with here, shows nothing related to NSFW as an argument.

upbeat otter
#

but app_commands.Command does have a nsfw argument that is set to False by default

#

oh you're using hybrid commands

vapid parcel
#

Yes

upbeat otter
#

that doesn't matter it should work

vapid parcel
#

It doesn't work tho

#

I showed you a screenshot lol

upbeat otter
#

wait for some time after you sync the commands using nsfw set to true

vapid parcel
#

I do a manual sync, so then after I sync I just do ctrl + r which should completely refresh discord, and it should be updated

upbeat otter
#

hmm yeah I know. just wait for like 5 minutes and refresh

#

it takes some time for discord to act up

vapid parcel
#

Idk, that shouldn't matter imo. But Ill wait lol

vapid parcel
upbeat otter
#

yes

#

!d discord.app_commands.Command

unkempt canyonBOT
#

class discord.app_commands.Command(*, name, description, callback, nsfw=False, parent=None, guild_ids=None, auto_locale_strings=True, extras=...)```
A class that implements an application command.

These are usually not created manually, instead they are created using one of the following decorators:

• [`command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.command)

• [`Group.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group.command)

• [`CommandTree.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command)...
vapid parcel
#

ty

#

Thats weird, it should work then

#

Glad I read it, it will not work on sub commands, which makes sense now

upbeat otter
#

oh 💀

vapid parcel
#

Well that makes sense why it isn't working 😭

upbeat otter
#

don't use subcomands then

vapid parcel
#

hm

#

I guess 😭

upbeat otter
#

or don't make nsfw commands. become good boi

vapid parcel
#

I don't think it even works, because when I have it on, the nsfw commands show anywhere, and I can run the commands anywhere too. So I think I can just continue with a simple check of if the channel is nsfw.

I just wanted to hide the commands unless you were in a nsfw channel, but I see its not really working.

So its fine, but thanks for the help.

random obsidian
#

Guys
i'm using discord.py and mysql
Doing queries through bot
After running bot and some hours , when i execute an query , it gimme :

discord.app_commands.errors.CommandInvokeError: Command 'create' raised an exception: OperationalError: 2055: Lost connection to MySQL server at 'serverip:3306', system error: 10053 An established connection was aborted by the software in your host machine
amber tusk
#

Who could help me ?

slate swan
#

how I can set max bitrate? (problem by boosts)

red blade
#

when using a custom check for a discord app command, is there a direct way to make it not raise an error when returning False?

grand pike
#

What is custom command for Discord and where to find it ?

red blade
#

custom command?

#

@grand pike

upbeat otter
upbeat otter
amber tusk
grand pike
red blade
#

what do you mean like being able to make custom commands for a specific server?

pale zenith
#

make your own language

#

(see lark - a parser for context-free grammars)

red blade
#

how do you link a slash command in an embed?

pale zenith
#

</full command name:command id>

red blade
#

how do you get the command id?

pale zenith
#

CommandTree.fetch_commands and CommandTree.sync both return list[discord.AppCommand], then you access the AppCommand.id

red blade
#

ok thx

pale zenith
storm zodiac
#

how do you make a command, that repeats other commands for a specific amount of given times,

#

i already have wrote the command and arguments of it, but i don't know what should i write for the functionality of it

pale zenith
storm zodiac
#

yup

pale zenith
storm zodiac
#
for _ in range(1, time+1):
    command = self.bot.get_command(text)
    print(command)
await ctx.reply(F"Repeated `{text}` - `{time}` times")
``` i'm trying to use the get_command method but it only returns None
pale zenith
storm zodiac
#

i am only writing the command without the prefix...?

pale zenith
#

🤔

storm zodiac
#

and i totally forgot that jishaku existed

pale zenith
#

hold on wait a minute

#

ctx.reply
jishaku doesn't work for anything but discord.py

storm zodiac
#

even jishaku doesn't recognize the command

storm zodiac
pale zenith
#

oh wait I misread something

#

I somehow read ctx.respond which is from some other library

#

my bad

storm zodiac
#

it's ok

storm zodiac
pale zenith
#

this is not a slash command right?

#

and dm.waifu works right?

#

if it does, then that's pretty weird

storm zodiac
#

i figured it, i had 2 different commands have the same "function name"

#

and now also my command works, it won't return None anymore, but i don't know how to run the command

#

also figured that out, used await command.__call__(ctx)

#

ty for reminding me about jsk tho, leonardo

pale zenith
#

no problem

pale zenith
storm zodiac
#

oh didn't know

pale zenith
slate swan
#

are boost bot against discord tos

slate swan
#

yes

onyx elk
#

why does it say improper token?

#

its literally copied from the thingy

hollow kraken
#

To pass local function variables into nested bot.event() functions like on_reaction_add I created a global "temp" variable that holds data inbetween the nested functions, now I"m wondering if this will be a problem if two people use a command that alters this global variable. What would happen?

upbeat otter
upbeat otter
hollow kraken
upbeat otter
#

So you would of course have multiple ids to store

hollow kraken
#

i really just need a way to pass local variables to the nested bot event functions

unkempt canyonBOT
#
Bot variables

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

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

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

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

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

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

onyx elk
formal valve
#

So anyone here has any idea about ephemerals? Mines not working

#

Also my cooldown isnt working either.
I am using multiple functions inside my discord function.

foggy zealot
#

i found out that you can mute/unmue the client using the rpc api. wanted to test it out to work on a script for electron wayland users of discor (like me) that dont have native support for keybinds... so how to use it with pypresence?

formal valve
#

And any idea how to enable slow mode?

thin beacon
#

If I try to cache a function that takes ctx as a parameter, will it work?

Every time ctx object will be different. So it won't really work the way I expect it to be, right? Or am I wrong?

naive briar
#

You can store and use contexts later, yes

#

Maybe except for interaction-based ones, not sure

formal valve
sick birch
#

if you don't do that you get false negatives with cache hit which is bad

thin beacon
#

Hmm...

naive briar
karmic moon
#

Hey! I'm currently using nextcord, and I want a opionon on smthing. Should i seperate each command into a diff file (Like for discord.js) or group them together (so like ping.py help.py vs utils.py moderation.py)

thin beacon
#

Of course, you should group the related commands together.

karmic moon
#

alr thanks, i was messing around with discord.js and it made me think lol

white citrus
#
Old XP Count 0
Total Message Xp 0.09999999999999999```

It is always displayed in db 0, even overwrite the new xp
slate swan
#

anyone know a good vps to use when developing with other people?

ancient raven
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 659, in connect
    await self.ws.poll_event()
  File "/usr/local/lib/python3.10/dist-packages/discord/gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000

This is due to network right ?

red blade
#

is it just me because im trying to block commands in dm's. i thought it worked before, but now it doesn't. I have:

    @commands.guild_only()
    @discord.app_commands.guild_only()```
Only recently I have realised that they still try to work in DM's, when it shouldnt
abstract fox
#

My bot won't ever seem to find the users in the guild, is there any way someone is able to help me?

novel apexBOT
#

This is not a Modmail thread.

red blade
#

wrong one 😦

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.

abstract fox
red blade
red blade
abstract fox
#
import discord
from discord.ext import commands
from discord import Intents
intents = Intents.default()
intents.members = True ```
red blade
#

and then i take it you added intents = intents on the end of the line where you declare the Bot

red blade
abstract fox
#
@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")


@client.command()
async def warn(ctx, member: discord.Member, *, reason=None):
    if reason is None:
        await ctx.send(f"{ctx.author.mention}, please provide a reason for the warn.")
        return

    # Send a warning message to the specified user
    await ctx.send(f"{member.mention} has been warned for: {reason}")```
this can never seem to find a user
abstract fox
red blade
#

no worrys

#

what happens when you do it and ping someone, what error?

abstract fox
red blade
abstract fox
#

Very odd.

red blade
# abstract fox Very odd.

Try and put another command, just a test one, just something simple like

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

And just check if that works

abstract fox
#

It's saying priviledged message content is gone

#

but i'm like 100% certain it's enabled

red blade
#

oh right i see

#

but you only enabled members intents in the code

abstract fox
#

okay

sleek oyster
#

can somebody have a look at my bot and see where things are going wrong. it's aim is to allow a discord user to connect their twitter account and assign a role respectively:
https://paste.pythondiscord.com/BVWA

abstract fox
#

what do i need to add

red blade
abstract fox
#

let me try now

red blade
#

ok

abstract fox
#

ty ty it works

abstract fox
red blade
abstract fox
#

a warnings command ironically

red blade
#

do you get an error?

abstract fox
#

it think it's just full of errors lol

red blade
#

can i see it

abstract fox
#
@bot.command()
async def warnings(ctx, member: discord.Member):
  # Check if the user has the necessary permissions to view warnings
  if ctx.author.guild_permissions.kick_members:
      # Get the user's warnings
      user_warnings = warnings.get(member.id, [])
      if user_warnings:
          await ctx.send(f"{member.mention} has {len(user_warnings)} warnings:\n{', '.join(user_warnings)}")
      else:
          await ctx.send(f"{member.mention} has no warnings.")
  else:
      await ctx.send("You don't have the necessary permissions to view warnings.")```
this is the code, i can grab the error if it's needed
red blade
abstract fox
#

Attribute Error: 'Command' has no attribute get

red blade
abstract fox
#

i would probs need help to set that up

red blade
#

then what is warnings.get()

abstract fox
#

a thing made with the assistance of AI

red blade
#

right, well 1, warnings is the same name as the command, so it will think you are trying to run .get on a command which you can't do, and 2. it will need to be a dictionary or something to use .get

#

so the dictionary would need a different name, however that would not be advisable to use

#

a database would be more suitable

abstract fox
#

can you help me to set either of those up?

#

i've changed it to warningslog.get

#

how would i make a database?

red blade
# abstract fox how would i make a database?

databases can be difficult if you haven't used one before, for small bots, SQLITE is ok and for larger bots, ones like POSTGRESQL are better. For a small bot, you can try and find a youtube video for it. However, i would recommend using aiosqlite and not just sqlite. This is because it is AsyncIO so other coroutines can run simultaneously

abstract fox
red blade
#

😭 and no problem

sleek oyster
#

i am having problems with the twitter callback i believe

flat solstice
flat solstice
#

Also, am I able to nest groups like this?

parentgroup = bot.create_group("parent", "parent group commands.")

childgroup = parentgroup.create_group("child", "child group commands.")
slate swan
#

you can nest groups but not like this

#

the .create_group method has been removed in 2.0 version

flat solstice
abstract fox
#

Hey! is anyone free to give me a hand real quick/

#

smth with embeds if possible

hollow kraken
analog hinge
calm stratus
#

hi, i'm trying to write a bot that checks messages for a specific regex pattern, and then send a message if it matches - but I can't seem to actually get it to match to anything? even sending message that should match (and match when testing in other things), any help would be appreciated <3

@client.event
async def on_message(message):
    match = re.match(r"/\d+,\d+/gm", message.content)
    print(f"{match}")
    print(f"{message.content}")
    if match is not None:
        await message.channel.send("stop using decimal comma!!")

edit: screenshot is terminal output of it sending stuff after me sending messages

slate swan
#

how to make the bot ping someone

naive briar
#

!e it'd match things like these

import re
pattern = r"/\d+,\d+/gm"

print(re.match(pattern, r"/1,1/gm"))
print(re.match(pattern, r"/12,14/gm"))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | <re.Match object; span=(0, 7), match='/1,1/gm'>
002 | <re.Match object; span=(0, 9), match='/12,14/gm'>
calm stratus
#

oh crap yeah, my bad lmao I forgot that it doesn't use flags or open/close things in the pattern - thank you!

naive briar
#

🐈

calm stratus
#

🐱

vapid parcel
#

Hey, I am making a status page for my bot, and it seems to never load on my server, it loads on local host but never on my website host, can someone help me with the issue?

It works fine on local host but then fails when I upload it to the actual website host, the website works, its just the status page, it takes ages to load, and I am confused on why. Yes I understand this is for python only, but the website is in JS, so hopefully that isn't an issue!

Code: https://paste.pythondiscord.com/G4DA

deep basalt
#

Anybody know why I'm getting an indentation error on "**@**bot.event"?

disnake latest & py


@bot.event
async def on_modal_submit(modal_inter):
    
    url = modal_inter.text_values["banner_url"]
    code = modal_inter.text_values["code"]
    channel = modal_inter.text_values["channel"]
    admin_role = modal_inter.text_values["admin_role"] 
    loa_role = modal_inter.text_values["loa_role"]

    with open(file) as f:
        data = json.load(f)

    if str(modal_inter.guild_id) not in data:
        data[str(modal_inter.guild_id)] = {}

    data[str(modal_inter.guild_id)]["banner_url"] = url
    data[str(modal_inter.guild_id)]["code"] = code
    data[str(modal_inter.guild_id)]["channel"] = channel
    data[str(modal_inter.guild_id)]["admin_role"] = admin_role
    data[str(modal_inter.guild_id)]["loa_role"] = loa_role

    with open(file, "w") as f:
        json.dump(data, f)
    
    await modal_inter.response.send_message("Setup complete!")


@bot.slash_command()
async def setup(inter):

    # Create and send button  

@bot.event
async def on_button_click(inter):

    components = [
        TextInput(label="Banner URL", custom_id="banner_url"),
        TextInput(label="Game Code", custom_id="code"),
        TextInput(label="Guidelines Channel", custom_id="channel"),
        TextInput(label="Admin Role", custom_id="admin_role"),
        TextInput(label="LOA Role", custom_id="loa_role")
    ]

    modal = Modal(title="Setup", components=components) 

    await inter.response.send_modal(modal)```
naive briar
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.

deep basalt
dry fractal
#

Hey guys

abstract fox
#

Anything able to help me to figure out why this bot is coming up with an error? It's seemingly unable to find such thing as a role.

abstract fox
wicked jungle
abstract fox
wicked jungle
#

the full error

#

and if what you blacked out is anything other then the actual name of the file on your computer send that to pls

abstract fox
#

it's just the file name

pale zenith
# abstract fox

You passed the discord.role module (discord/role.py) and not the discord.Role class from it. Uppercase that R

abstract fox
abstract fox
#
@bot.command()
async def modbind(ctx, role: discord.Role):
    if role is discord.Role:
        await ctx.send("Binded successfully to {role.mention}")
        
    else:
        await ctx.send("Improper role.")```
this always seems to come up with Improper Role.
pale zenith
#
  1. The check you would use is called isinstance, if isinstance(role, discord.Role)
  2. that check is useless, because it will always be that class. When it fails to convert it will raise an error, and not execute the command's body. If you want to send that message when an improper role has been passed, you need to create an error handler
abstract fox
#

Okay.

#

I've just removed the check, thanks for informing me.

abstract fox
#

Is there a way for me to reference that role in another command?

pale zenith
#

As in?

abstract fox
#

As in mentioning the role in another command, to ping it.

pale zenith
#

You'd have to store it somewhere, but yeah

#

Say a variable, like a dict of server -> role

#

Or if you need permanence across restarts, then a database.

abstract fox
#

I theorectically would need it to remember but for the purpose of testing there is no need.

#
@bot.command()
async def modbind(ctx, role: discord.Role):
    await ctx.send(f"Binded successfully to {role.mention}")
    mod = role.mention
@bot.command()
async def mod(ctx):
    await ctx.send(f"{mod.mention}")```
and it doesn't mention, is there any way i can do this?
naive briar
#

You might want to learn about function scopes (!scope) and bot variables (!botvar)

slate swan
#

how do we make like this?

naive briar
#

Buttons?

slate swan
naive briar
#

What is it, then?

slate swan
#

when we click on it we get the following things

golden portal
#

sooo, buttons?

#

🤔

upbeat otter
#
@ui.button()
async def button(...):
  embed = discord.Embed()
  await interaction.response.send_message(embed=embed, view=View())

Something like this would suffice

vague junco
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

upbeat otter
# vague junco !rule 4

This is a channel to help people develop discord bots. You should use #bot-commands to use the bots

mossy jacinth
#

How do other bots have space in the command name? When I tried it it gave me a big silly error

naive briar
#

Those are called groups

mossy jacinth
#

and how do i create such groups?

naive briar
#

!d discord.app_commands.Group

unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.

These are usually inherited rather than created manually.

Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:

```py
from discord import app_commands

@app_commands.guild_only()
class MyGroup(app_commands.Group):
    pass
```...
naive briar
#

An example:

from discord import app_commands

class MyGroup(app_commands.Group, name="something"):
    @app_commands.command(name="subcommand")
    async def callback(...):
        ...
#

(maybe? I just typed that live)

mossy jacinth
#

and that would then lets say be shown as /ticket something ?

naive briar
#

Yes

mossy jacinth
#

okay thank you

white citrus
#
Old XP Count 0
Total Message Xp 0.09999999999999999```

It is displayed but the DB always says 0 😱 I round it off with `round(new_xp_count, 2)`
pale zenith
ancient raven
#

Once in a day imo

#

Or less

pale zenith
#

ehhhhhh safe to ignore probably

#

this means that hey, you unexpectedly disconnected from the websocket

#

could be network issues, blocking code, [random discord outage - unlikely], other stuff?

ancient raven
#

Ye so prolly due to unstable vps network ?

pale zenith
#

¯_(ツ)_/¯

ancient raven
#

Oh welp

#

Thanks

vapid parcel
flat pier
#

from experience 😩

pale zenith
flat pier
pale zenith
#

yea same

flat pier
#

though 99% of the time someone already got their questions answered

pale zenith
#

and the other 1% is one of those questions that make me roll my eyes so backwards I can see my brain hiding away

#

but I try to be helpful anyway, because thats the point

flat pier
#

fr

round knoll
#

hello, ive been running this script for a while, probably close to 3 years. minor bugs, bug usually i can quick fix it. but with that one im not sure how. can anyone point me in the direction for a fix? traceback shared in this pastebin

https://paste.pythondiscord.com/OYOQ

flat pier
#

is this the entire traceback

round knoll
flat pier
round knoll
flat pier
#

either that or throw up a venv and edit the file yourself for now

#

just to see

round knoll
flat pier
#

i mean changing the lines in gateway.py from

elif msg.type is aiohttp.WSMsgType.ERROR:
    _log.debug('Received %s', msg)
    raise msg.data

to this instead

elif msg.type is aiohttp.WSMsgType.ERROR:
    _log.debug('Received error %s', msg)
    raise WebSocketClosure
round knoll
#

alright, ill try it out thanks

eternal harness
#

Hello i have how could I create application commands (slash command)? With the discord.py library

sick birch
jovial talon
unkempt canyonBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

#
Command Help

!pep <pep_number>
Can also use: get_pep, p

Fetches information about a PEP and sends it to the channel.

golden portal
# eternal harness Hello i have how could I create application commands (slash command)? With the d...

https://about.abstractumbra.dev/discord.py/2023/01/30/app-command-examples.html#free-form-definition-of-commands

then after you create them, CommandTree.sync to register to discord
https://about.abstractumbra.dev/discord.py/2023/01/30/app-command-basics.html#syncing

To cut all the yapping, basically

@bot.tree.command()
async def my_command(interaction: discord.Interaction):
    await interaction.response.send_message("Hello from my command!")

Then register

await bot.tree.sync() # global
# OR
guild_id = 267624335836053506
await bot.tree.sync(guild=discord.Object(guild_id)) # guild specific
flat solstice
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "/home/modmail/auxiliarius/cogs/events.py", line 230, in on_member_join
    await file.save(embed.to_dict(), welcome-output)
AttributeError: '_io.BytesIO' object has no attribute 'save'

Hi I'm getting this error with this code and I'm not sure what I'm doing wrong, I don't usually use files with bots or python in general so my understanding of the io module isn't great

embed = discord.Embed(...)
await member.send(embed=embed)
file = io.BytesIO()
await file.save(embed.to_dict(), welcome-output)
admin_commands = await self.bot.fetch_channel(710336551967522887)
await admin_commands.send(file=file)
golden portal
flat solstice
# golden portal firstly why are you saving embed as a file and sending as a file? is there a rea...

I have someone who wants to edit multiple sections of the embed but they don't have access to the code. Want I want to do is write the embed dict to a json file, which I can then give to them for edits and then either directly load that file or manually transfer the sections.
This isn't the best solution to this situation but it seems the most convenient solution
Edit: please ping on replies because I'm going to be a bit busy and may miss messages

golden portal
#

o

golden portal
#

since embed.to_dict is json serializable, you can use json.dump w/ stringIO since json.dump give str to .write, also the stringio.seek(0) is important, so it reset the cursor for discord.File to read

flat solstice
#

Sorry for the ping if there was one, your followup answered my question

golden portal
#

oke

thin raft
#
class Shop(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @app_commands.command(
        name="shop",
        description="Check your shop"
    )
    async def shop(self, interaction: discord.Interaction, user: str, password: str) -> None:
        val = Valorant(user, password)

        embeds = list()
        for skin in val.get_daily_skins():
            embed = discord.Embed(description=f"Price {skin.price}")
            embed.set_author(name=skin.name)
            embed.set_image(url=skin.image)
            embeds.append(embed)

        await interaction.response.send_message(embeds=embeds)

Any reason this is raising interaction not found?

shrewd apex
#

also make sure get_daily_skins() and valorant stuff isn't blocking

thin raft
twilit whale
#

or that's what it thinks.

white citrus
versed zodiac
#
2024-03-15 21:54:37 WARNING  discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
2024-03-15 21:54:37 INFO     discord.client logging in using static token
2024-03-15 21:54:39 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 77b93e2be17055c83b454973b8618554).
Krack#8887 has connected to Discord!
C:\Users\Risinplays\Projects\Krack\commands\example.py:13: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
  bot.add_cog(Example(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Example cog successfully loaded.
Failed to load extension example: Extension 'commands.example' raised an error: TypeError: object NoneType can't be used in 'await' expression
Failed to load extension __init__: Extension 'commands.__init__' has no 'setup' function.```
#
from discord.ext import commands
from dotenv import load_dotenv
import os

# Load environment variables from .env file
load_dotenv()

# Initialize Discord intents
intents = discord.Intents.default()
intents.messages = True  # Enable message related events
intents.guilds = True  # Enable guild related events

# Create bot instance with command prefix and intents
bot = commands.Bot(command_prefix='!', intents=intents)

# Event handler for bot ready event
@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')
    for filename in os.listdir('./commands'):
        if filename.endswith('.py'):
            # Remove the file extension
            cog_name = filename[:-3]
            try:
                # Load the extension and print the return value
                extension = await bot.load_extension(f'commands.{cog_name}')
                print(f'Loaded extension: {cog_name}, return value: {extension}')
            except Exception as e:
                print(f'Failed to load extension {cog_name}: {e}')

# Run the bot with token from environment variable
bot.run(os.getenv('DISCORD_BOT_TOKEN'))
#

why am i getting that error pls explain , ping me pls

versed zodiac
#

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

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

async def setup(bot):
    await bot.add_cog(Example(bot))```
#

and also @north kiln i am still getting this error

WARNING discord.ext.commands.bot Privileged message content intent is missing...

even if i have enabled it in the developer portal

north kiln
#

intents.message_content = True

slate swan
#

!mcintent

north kiln
versed zodiac
#

my example extension got loaded

north kiln
#

don't load init

versed zodiac
north kiln
#

just check the name

#

there are some other ways but it is the simplest

#

?

versed zodiac
#

what?

north kiln
#

why send the code again

versed zodiac
#

by mistake

abstract fox
#

How do I make it so that a field on a command takes all the text after that point into it?

abstract fox
pale zenith
#

lol, no problem :)

slate swan
#
import discord
from discord.ext import commands

prefix = "!"

intents = discord.Intents.default()

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

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')

@bot.command(name='test')
async def ping(ctx):
    await ctx.send('TEST!')

bot.run('the token')
#

why does this not work?

#

the bot comes online but the command doesnt work

#

im using 3.12

hot sparrow
pale zenith
slate swan
#

k

hot sparrow
#

i havent seen a bot using prefixes since like 2020

cloud dawn
slate swan
#

Time to set banners to your bots

ancient raven
#

Hello there,
I wanted to ask if it's a good idea to screen all messages for keywords and if it matches the bot sends a custom message. It's a moderately active server I would say so I'm not really sure if it's a good idea. Lmk

white citrus
#

my yaml


commands:
  join:
    name:
      en: "join"
      de: "beitreten"
    description:
      en: "The bot joins your voice channel."
      de: "Der Bot tritt Ihrem Sprachkanal bei"```


and the code 
```py
    with open("commands.yaml", encoding="utf-8") as file:
        localizations = yaml.safe_load(file)

    @nextcord.slash_command(name="voice")
    async def voice(self, inter: Interaction):
        pass


    @voice.subcommand(name="join", description="The bot joins your voice channel.",
                      name_localizations=localizations["commands"]["join"]["name"],
                      description_localizations=localizations["commands"]["join"]["description"])
    async def voice_join(self, inter: Interaction):```
#

Error

  File "C:\VSCode\Python\Lib\site-packages\nextcord\client.py", line 497, in _run_event
    await coro(*args, **kwargs)
  File "C:\VSCode\Python\Lib\site-packages\nextcord\client.py", line 2536, in on_connect
    await self.sync_application_commands(
  File "C:\VSCode\Python\Lib\site-packages\nextcord\client.py", line 2350, in sync_application_commands
    await self._connection.sync_application_commands(
  File "C:\VSCode\Python\Lib\site-packages\nextcord\state.py", line 794, in sync_application_commands
    await self.discover_application_commands(
  File "C:\VSCode\Python\Lib\site-packages\nextcord\state.py", line 870, in discover_application_commands
    await self.register_application_command(app_cmd, guild_id)
  File "C:\VSCode\Python\Lib\site-packages\nextcord\state.py", line 1038, in register_application_command
    raise e
  File "C:\VSCode\Python\Lib\site-packages\nextcord\state.py", line 1034, in register_application_command
    raw_response = await self.http.upsert_global_command(self.application_id, payload)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\VSCode\Python\Lib\site-packages\nextcord\http.py", line 399, in request
    raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.0.name_localizations.en: Value "en" is not a valid enum value.
In options.0.description_localizations.en: Value "en" is not a valid enum value.```
hushed galleon
hushed galleon
#

maybe, i dont use nextcord so i wouldnt know of a better approach

dense topaz
#

Only the prefixed command works, and the slash one doesn't even sync

@commands.hybrid_command()
async def test(self, ctx: commands.Context):
    await ctx.send('test')```
pale zenith
#

did the output of sync return an empty list?

flat solstice
#

I can do this when making embeds right?

embed=discord.Embed()
embed.title="..."
embed.description="..."

Or something like this

embed=discord.Embed()
...
embed.from_dict(data)
fading marlin
#

discord.Embed has a title and a description argument in its constructor. You don't have to add those fields post-init. Embed.from_dict is a classmethod, so you don't need an instance to use it

dense topaz
flat solstice
fading marlin
#

Sure. from_embed returns an instance of Embed

#

You don't need to declare data above the context manager btw

flat solstice
#

okay thanks for clarifying that for me

orchid moat
#

Would someone code a discord bot for me? I would make it worth your time.

stark ingot
#

You were already linked rule nine and given alternative options.

severe sonnet
#

like, i'm new to sqlite so i changed my database but it's not working as intended and i get not tracebacks

elfin kindle
#

hey

dense roost
#

was anyone successful in creating discordpy bot with django server? I'm planning on creating one and would appreaciate tips from more experienced people.
my plan is to run them in docker containers side by side and comunicate via the django api

marble gust
#

**Hi everyone! **
Can anyone tell me how to create multi-sessions so that you can run 10 or more applications.. [python]
And so that you can control them, for example, turn them off and on separately.

golden portal
#

that sounds like a job for a process manager not just python, i usually just use systemd

golden portal
vapid parcel
#
class Topgg(commands.Cog):
    """For on_message"""

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.allowed_server_id = 1156172652629737532
        self.allowed_channel_id = 1156190630603661313
        self.allowed_user_id = 302050872383242240


    @commands.Cog.listener()
    async def on_ready(self):
        pass
    async def cog_load(self):
        print(f'{self.__class__.__name__} has been loaded.')

    @commands.Cog.listener()
    async def on_message(self, message):
        if not message.guild:
            return
        if (
                message.guild.id == self.allowed_server_id
                and message.channel.id == self.allowed_channel_id
                and message.author.id == self.allowed_user_id
                and message.embeds
        ):
            for embed in message.embeds:
                if embed.description.startswith("Bump done! :thumbsup:"):
                    response_embed = discord.Embed(
                        title="Bump Detected!",
                        description=(
                            "Thanks for the bump!\n"
                            "If you don't mind, please upvote UniBot on Top.gg!\n\n"
                            "*If you don't mind, please leave a review too!*"
                        ),
                        timestamp=discord.utils.utcnow(),
                        color=config.main_color,
                    )
                    view = discord.ui.View()
                    button = discord.ui.Button(label="Upvote UniBot", style=discord.ButtonStyle.link, url='https://top.gg/bot/1156134562418663585')
                    view.add_item(button)

                    response_embed.set_thumbnail(url=self.bot.user.avatar.url)
                    response_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
                    await message.channel.send(embed=response_embed, view=view)
                    break```
#

So I have this cog for bumps inside of my server, I am wondering if its possible to get who ran the command from another bot? Like who ran the bump command from disboard.

naive briar
#

Use channel.history to get the message that called the bump command

#

Or just have a check to detect one

vapid parcel
#

Its a slash command tho?

#

Would that work with channel.history?

naive briar
#

Right

#

I'll see

vapid parcel
#

Disboard stopped doing prefix, so that means you gotta do something for slash. I mean discord shows who ran the command, but I wish they would let bots access that some how maybe?

#

If you find anything, please ping me!

naive briar
unkempt canyonBOT
naive briar
#

!d discord.MessageInteraction.user

unkempt canyonBOT
vapid parcel
#

oh thank you. This should work for if the slash is ran by another bot?

naive briar
#

I guess so

#

Never tried it myself though

vapid parcel
#

Okay!

#

Thank you, I will do some testing before doing this!

vapid parcel
#

Thank you for getting me the information!

naive briar
#

🐈

zenith yarrow
#

I have to use message link or is there a way to use message id

versed zodiac
#
import discord
import asyncio
import os
from dotenv import load_dotenv
from discord.ext import commands

load_dotenv()


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


@commands.command()
@commands.is_owner()
async def restart(self, ctx):
    await ctx.send("Restarting...")
    await self.bot.logout()
    await asyncio.sleep(5)  
    await self.bot.start(token=os.getenv('DISCORD_BOT_TOKEN'))  


async def setup(bot):
 await bot.add_cog(Restart(bot)) ```
#
2024-03-16 11:27:51 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: f6517a7f486781470d573ef0121093c4).
Krack#8887 has connected to Discord!
Loaded extension: example, return value: None
Loaded extension: restart, return value: None
2024-03-16 11:28:53 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "restart" is not found
2024-03-16 11:29:02 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "Restart" is not found
#

why its not recognising the command?\

golden portal
zenith yarrow
golden portal
golden portal
versed zodiac
vapid parcel
#

How to make app commands? Or whatever they are called.

And is it true, they can't be in cogs?

golden portal
#

yea, because danny didnt bother to implement it, since you can only have 5 context menus, and implementing them in a cog is overcomplicated

vapid parcel
#

Alr, so how to do them?

golden portal
#

if you do it in a cog you have to manually add the context menu inside the init

vapid parcel
#

Okay, but how to make the context menu?

#

With context menus

#

do you have to sync them?

golden portal
#

:yes:

vapid parcel
#

alr

vapid parcel
#

Can you use modals inside of context menus?

naive briar
#

Use the interaction to send the modal 🫠

mossy jacinth
#

how can i get a sum number of total slash commands? I've tried everything but it either returns set() or 0...
I tried:
len(bot.get_all_application_commands),
len(bot.commands),
len(bot.all_commands) and everything returns the same

zenith yarrow
#

When I react with this emoji it says no reaction please help

@bot.event
async def on_raw_reaction_add(payload):
  if payload.emoji == "👍":
    print("reaction added")
    print(payload.message_id)
  else:
    print("no reaction ")
mossy jacinth
naive briar
#

I don't know about that

mossy jacinth
naive briar
#

No, not at all

naive briar
#

You need to convert the emoji into a string with str(), then compare

abstract fox
#

Is anyone able to help me to do / commands? I'm quite confused.

naive briar
#

What's the question/problem? Just ask right away

abstract fox
naive briar
#

In what library?

abstract fox
abstract fox
zenith yarrow
naive briar
abstract fox
naive briar
#

... is used as a placeholder for the actual arguments

#

commands.Bot's required arguments are: intents, command_prefix

abstract fox
#

Okay

abstract fox
pale zenith
#

That isn't how that works.

#

Prefix-based commands and slash commands are two different things

abstract fox
#

mhmm

pale zenith
#

set whatever prefix you want for your message commands. It won't change anything in regard to slash commands

abstract fox
#

Okay

#
@bot.tree.command(name="echo", description="Echoes a message.")
@app_commands.describe(message="The message to echo.")
async def echo(interaction: discord.Interaction, message: str) -> None:
    await interaction.response.send_message(message)```
ive taken this code snippet from the first guide, to give myself an example, and it doesn't show up, how can i resolvve this?
naive briar
# abstract fox ```py @bot.tree.command(name="echo", description="Echoes a message.") @app_comma...

To use the slash commands registered in the CommandTree, you also need to sync them with Discord. This is done by calling CommandTree.sync(). When you sync your commands, the metadata for the commands is sent to Discord and Discord will create the commands for you which you can access from the Discord client.

...

When you call CommandTree.sync, you sync one scope of the CommandTree, either the list of global commands (sync()) or the list for one guild (sync(guild=discord.Object(...)))`

You can read more about how to sync commands in the Syncing Commands section.

#

Please read the guide thoroughly

abstract fox
#

ty

abstract fox
naive briar
#

Did you invite the bot with the application command scope?

abstract fox
pale zenith
#

bots get that scope by default, and you cannot disable it (and it got added retroactively to all guilds)

abstract fox
#

oh okay, do you have any clue why it might be that it's not showing up then?

pale zenith
#

press CTRL+R

#

if that doesn't fix it, can you print(await bot.tree.fetch_commands())

abstract fox
#

Okay!

abstract fox
pale zenith
#

:)

#

(also, this is one of the reasons you shouldn't automatically sync your commandtree, since discord is fucky)

#

(the other is rate limits- sync in a prefix command instead)

abstract fox
#

(discord is very funky, i've done a _ command for it since it seems better anyway)

pale zenith
#

yup! prettythumbsup

naive briar
abstract fox
pale zenith
#

and more importantly, show your code (and errors)

abstract fox
pale zenith
#

that section seems mostly correct*

abstract fox
naive briar
#

lol

pale zenith
#

this is unfortunately one of the disadvantages about guides that aren't reviewed by many people. Errors sometimes slip through the cracks

#

by the looks of things its @shrewd apex's guide, so ^^^

#

(also if people are interested like in writing discord.py guides n stuff, see this)

abstract fox
pale zenith
#

!d discord.TextChannel.purge with a limit of 1

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
abstract fox
#

or now it just does nothing

#

it's saying attribute error

#

for it and won't work

ivory falcon
#

im trying to make the bot send a message whenever its active but i keep getting this error, can someone explain why is this happening and how can i fix it?


intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
channel = client.get_channel('1138787209735045191')

@client.event
async def on_ready():
    print(f'{client.user} | {client.user.id} has connected to Discord!')
    await channel.send('The bot is online')

client.run('token')```

error: 

2024-03-16 14:05:45 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Yido\AppData\Roaming\Python\Python312\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Yido\Desktop\yidoBot\bot.py", line 14, in on_ready
await channel.send('The bot is online')
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'send'```

abstract fox
#

might work based on my minimal knowledge

naive briar
#

There is no context object there

naive briar
#

Also, it gets an int (integer) object, not str (string)

ivory falcon
#

so what can i do about it, what should i change in the code to fix this

naive briar
#

Get the channel after the bot is ready 🤷

#

(I guess it works too in on_ready)

ivory falcon
slate swan
#

tias

shrewd apex
#

ah rip indeed the guide does need some reviewing

#

fixed the typo

proper egret
#

I need help with a logs tracker

#

using webhook

#
async def on_member_join(member):
    if member.bot:
        return

    specified_invite_link = 'your-invite-link-here'
    if member.invite and member.invite.url == specified_invite_link:
        server = member.guild

        # Create an embed to send in the logs channel
        embed = discord.Embed(title="Server Joined!", color=0x00ff00)
        embed.add_field(name="Server Name", value=server.name, inline=False)
        embed.add_field(name="Server ID", value=server.id, inline=False)
        embed.add_field(name="Owner", value=server.owner.name, inline=False)
        embed.add_field(name="Member Count", value=server.member_count, inline=False)
        embed.add_field(name="Channel Count", value=len(server.channels), inline=False)
        embed.add_field(name="Bot Count", value=len(list(filter(lambda m: m.bot, server.members))), inline=False)

        # Get the logs channel and send the embed
        webhook_url = 'your-webhook-url-here'
        webhook = discord.Webhook.from_url(webhook_url, adapter=discord.RequestsWebhookAdapter())
        await webhook.send(embed=embed)```
#

help

shrewd apex
proper egret
#

It dont send anything

#

I have put the webhook and the channel id

shrewd apex
#

do u have members intent enabled?

#

alsu u sure ur invite link is correct?

#

do u get any errors?

proper egret
proper egret
proper egret
shrewd apex
#

add a bunch of debug print statements inside the function and the if condition to see if everything is working as expected

proper egret
#

I did that but It didn't send anything in the terminal

shrewd apex
#

!paste can u paste all of ur code

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
#

send full code then

shrewd apex
#

its likely the event is not even being triggered

proper egret
slate swan
#

Not sure what you're trying to check and compare, but discord.Member.invite doesn't exist

proper egret
# slate swan send full code then

import os
import discord
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
client = commands.Bot(command_prefix='-', intents=intents)
intents.members = True

@client.event
async def on_member_join(member):
print(f"Member {member.name} joined the server.")
if member.bot:
print(f"{member.name} is a bot, ignoring.")
return

specified_invite_link = 'https://discord.com/oauth2/authorize?client_id=1216825929054158858&permissions=8&scope=bot+applications.commands'
if member.invite and member.invite.url == specified_invite_link:
    server = member.guild
    print(f"Member {member.name} joined using the specified invite link.")

    # Create an embed to send in the logs channel
    embed = discord.Embed(title="Server Joined!", color=0x00ff00)
    embed.add_field(name="Server Name", value=server.name, inline=False)
    embed.add_field(name="Server ID", value=server.id, inline=False)
    embed.add_field(name="Owner", value=server.owner.name, inline=False)
    embed.add_field(name="Member Count", value=server.member_count, inline=False)
    embed.add_field(name="Channel Count", value=len(server.channels), inline=False)
    embed.add_field(name="Bot Count", value=len(list(filter(lambda m: m.bot, server.members))), inline=False)

    # Get the logs channel and send the embed
    webhook_url = '
    webhook = discord.Webhook.from_url(webhook_url, adapter=discord.RequestsWebhookAdapter())
    await webhook.send(embed=embed)
    print(f"Sent embed to logs channel: {embed}")
else:
    print(f"Member {member.name} did not join using the specified invite link.")

client.run(os.getenv('TOKEN'))

slate swan
#

print(f"Member {member.name} joined the server.") does this print

proper egret
#

No nothing prints in the console only Bot is online

slate swan
#

try @client.listen() instead

finite salmon
#

Is there any way to find out whether the discord.Member / discord.User object is a deleted user or not

proper egret
slate swan
#

!d discord.User.public_flags

unkempt canyonBOT
slate swan
#

!d discord.PublicUserFlags.spammer

unkempt canyonBOT
slate swan
#

you can try reading descriptions of other ones and see if it matches what you need

proper egret
#

@client.listen()
async def on_member_join(member):
print(f"Member {member.name} joined the server.")
if member.bot:
print(f"{member.name} is a bot, ignoring.")
return

specified_invite_link = 'https://discord.com/oauth2/authorize?client_id=1216825929054158858&permissions=8&scope=bot+applications.commands'
if member.invite and member.invite.url == specified_invite_link:
    server = member.guild
    print(f"Member {member.name} joined using the specified invite link.")

    # Create an embed to send in the logs channel
    embed = discord.Embed(title="Server Joined!", color=0x00ff00)
    embed.add_field(name="Server Name", value=server.name, inline=False)
    embed.add_field(name="Server ID", value=server.id, inline=False)
    embed.add_field(name="Owner", value=server.owner.name, inline=False)
    embed.add_field(name="Member Count", value=server.member_count, inline=False)
    embed.add_field(name="Channel Count", value=len(server.channels), inline=False)
    embed.add_field(name="Bot Count", value=len(list(filter(lambda m: m.bot, server.members))), inline=False)

    # Get the logs channel and send the embed
    webhook_url = ''
    webhook = discord.Webhook.from_url(webhook_url, adapter=discord.RequestsWebhookAdapter())
    await webhook.send(embed=embed)
    print(f"Sent embed to logs channel: {embed}")
else:
    print(f"Member {member.name} did not join using the specified invite link.")
slate swan
#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

slate swan
#

also like Krypton said there is no thing like member.invite

proper egret
#

Oh but is there any way I can track server using invite link

shrewd apex
#

is any member even joining the server lol cause the first print should still work

slate swan
#

what you mean by that

shrewd apex
#

https://discord.com/oauth2/authorize?client_id=1216825929054158858&permissions=8&scope=bot+applications.commands also isnt this bot link?

proper egret
#

It is

finite salmon
slate swan
finite salmon
#

Alr thanks

tacit oar
#

please help i am using winserver 2022

gritty mantle
#

hi im making a bot, if anyone would like to join and help work on it then please let me know

leaden olive
#

guys why arent my commands appearing when restarting the bot, i use pycord

leaden olive
#

whattt why is it like that

vale stone
#

when i play music like 15-20seconde i have this error

#
[tls @ 0000012cd8020000] Unable to read from socket
[mov,mp4,m4a,3gp,3g2,mj2 @ 0000012cd8063380] Packet corrupt (stream = 0, dts = 1290240).
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 0000012cd804b940] corrupt input packet in stream 0
[mov,mp4,m4a,3gp,3g2,mj2 @ 0000012cd8063380] stream 0, offset 0x2c044: partial file
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 0000012cd804b940] Error during demuxing: Error number -10054 occurred
[aac @ 0000012cd8085640] decode_band_types: Input buffer exhausted before END element found
[aist#0:0/aac @ 0000012cd807e200] [dec:aac @ 0000012cd80ccb40] Error submitting packet to decoder: Invalid data found when processing input
[tls @ 0000012cd8020000] Failed to send close message
[2024-03-16 15:27:48] [INFO    ] discord.player: ffmpeg process 20892 successfully terminated with return code of 0.
flat solstice
#

Hi so I'm getting this error when I'm trying to setup some command groups and subgroups using pycord and I'm not finding the error to be very informative of the issue, it also seems to be repeating the same error at least 3 times as part "during the handling of this error..."

management-bot | Ignoring exception in on_interaction
management-bot | Traceback (most recent call last):
management-bot |   File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
management-bot |     ret = await coro(arg)
management-bot |   File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 1312, in _invoke
management-bot |     await command.invoke(ctx)
management-bot |   File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 372, in invoke
management-bot |     await self.prepare(ctx)
management-bot |   File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 292, in prepare
management-bot |     if not await self.can_run(ctx):
management-bot |   File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 390, in can_run
management-bot |     local_check = cog._get_overridden_method(cog.cog_check)
management-bot | AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
parentgroup = bot.create_group("parent", "parent group commands.")
childgroup = parentgroup.create_subgroup("child", "child group commands.")

@parentgroup.command()
async def parenttest(ctx: discord.ApplicationContext):
        await ctx.respond("Testng if child group commands work at the parent level")

@childgroup.command()
async def childtest(ctx: discord.ApplicationContext):
        await ctx.respond("Testng if child group commands work at the child level")
misty widget
#

I create a telegram bot

#

But I am facing a problem whenever I run this I play my first game smoothly and after that my second games does not work properly