#discord-bots

1 messages · Page 224 of 1

thin raft
#

just like you do in message command

slate swan
#

It needs a type hint tho

thin raft
#

it will just parse as string right?

slate swan
#

Nope

thin raft
#

it raises an error?

slate swan
#

You should type hint it

slate swan
thin raft
#

yo wth

#

!d discord

unkempt canyonBOT
#
thin raft
#

yo why disnake

slate swan
#

Lol

thin raft
#

!d discordpy.discord

unkempt canyonBOT
#

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

Creating a Bot account is a pretty straightforward process.

thin raft
#

man what the fuck is this

slate swan
#

Here

thin raft
#

but I remeber !d discord sent discordpy's

slate swan
unkempt canyonBOT
still obsidian
#

how do I do that

unkempt canyonBOT
#

Hey @uneven hearth!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

uneven hearth
still obsidian
slate swan
still obsidian
slate swan
#

For example channel: discord.TextChannel

still obsidian
#

ah ok thanks

slate swan
mint meadow
#

does anyone know what this is and how can i fix this?

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SpotifyException: http status: 400, code:-1 - Unsupported URL / URI., reason: None

still obsidian
slate swan
still obsidian
#

thanks :)

slate swan
#

Tho I don't think voice channels are mentionable

mint meadow
#

does anyone know what this is and how can i fix this?

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SpotifyException: http status: 400, code:-1 - Unsupported URL / URI., reason: None

smoky sinew
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
shrewd apex
#

wonder who selected the colors for discord themes poor taste

#

also embeds buttons and stuff still show up as prelavent to dark or light mode

smoky sinew
#

why is like all of your code duplicated three times

slate swan
#

yes

shrewd apex
#

use whichever u feel comfortable with

slate swan
#

why do you create Bot instance 2 times and Intents 4 times

#

so whats current code?

#

okay so you still create intents 3 times and those which you send to your bot are without message_content

#

you are just overriding the intents varriable

naive umbra
#

U have multiple of the same import

#

Did you write this?

shrewd apex
#

whats import B 😂

smoky sinew
#

are you asking this in a python server?

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

slate swan
#

you're asking in a python server lol

#

any help? (ping me)

smoky sinew
shrewd apex
unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
slate swan
#

what is the max duration for a mute?

smoky sinew
slate swan
#

yeah

smoky sinew
#

it should be like a month

slate swan
#

alright

smoky sinew
#

yes 28 days

slate swan
#

okay thanks

blazing flint
#

I am trying to convert an mp4 audio file to an mp3 for a command in my discord bot. How can I do this?

blazing flint
#

I have tried I cant get it to work

smoky sinew
#

ffmpeg -i filename.mp4 filename.mp3

#

it's just this

#

and make sure ffmpeg is in the path

blazing flint
#

and do I import it at the top of my ptohts,?

smoky sinew
#

it's not a module

blazing flint
#

oh

#

well Ive said before I use replit a lot

#

and this is one thingI am on replit for

smoky sinew
#

cool

blazing flint
#

so is it still possible on replit

smoky sinew
#

¯_(ツ)_/¯

#

try it and see

blazing flint
#

how do I install ffmpeg

smoky sinew
#

what distro?

blazing flint
#

idk

heavy swift
#
  • I have 3 buttons labeled "A" "B" "C"
  • When "A" is clicked the label should be changed to "1" (same msg) and the rest should be changed to "2" "3"
  • A button should then wait to be clicked again from the same msg id.
  • When button; let's say "1" for example is clicked, it should send 'good job'

I'm not sure how to have the button wait to be clicked again and I dont know how to make it so that only the user who activated the command can click it

#
class tictacAlpha(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.posC = discord.ui.Button(label='C', custom_id='ttt:C')
        self.add_item(self.posC)

        self.letter = None
        self.num = None

    mapLetters = {'A': '1', 'B': '2', 'C': '3'}

    @discord.ui.button(label='A', style=discord.ButtonStyle.grey)
    async def posA(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Choose `A1`, `A2` or `A3`', ephemeral=True)
        self.letter = 'A'
        self.num = '1'
        button.label = '1'
        
        self.posC.label = '3'
        self.stop()
          
        
        

    @discord.ui.button(label='B', style=discord.ButtonStyle.grey)
    async def posB(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('Choose `B1`, `B2` or `B3`', ephemeral=True)

        self.letter = 'B'
        self.num = '2'
        button.label = '2'

Func

 @commands.command(aliases=['ttt'])
    async def tictactoe(self, ctx, opp: discord.Member = None):
        embed = discord.Embed(title="Sample Embed")
        embed.set_image(url="https://picsum.photos/200/300")

        view = tictacAlpha()
        await ctx.channel.send(embed=embed, view=view)

        # Wait for the View to stop listening for input
        await view.wait()
        if view.letter is None:
            return await ctx.send('Timed out...')
        
        elif view.letter:
            print("yup")        
            # Check for a valid position
            for pos in ['A', 'B', 'C']:            
                if view.letter == pos:
                    await view.wait()
                    for num in ['1', '2', '3']:            
                        if view.num == num:
                            userPos = pos+num
                            await ctx.send(f'You chose {userPos}')
smoky sinew
#

anyone know how embed requirements work?

#

so like the embed needs either a title, or description, or footer or something like that

heavy swift
#

You can create a blank embed without a title or description if that's what you mean

#

add_field() requires you have a title and a value if you add it but you can set it to an empty string

smoky sinew
#

apparently it's just any part of the embed?

#

e.g. setting the thumbnail alone works

heavy swift
#

seems abt right, unless you add like a blank add_field() or blank footer anything should work. eg. calling an empty add_field would result in an error but an empty discord.Embed() is fine

smoky sinew
#

is there a way to check if an embed is valid?

#

i'd rather not check every field

heavy swift
#

The only way I can think of is using an error handler to check for a typeerror

#

or using isInstance

unkempt canyonBOT
#

discord/embeds.py line 275

def __bool__(self) -> bool:```
smoky sinew
#

awesome

#

i wish i knew that an hour ago

#
{
    "description": "welcome to my server",
    "color": 15255379,
    "image": {
        "url": "https://i.gifer.com/YnEO.gif"
    }
}

i know this is not related to discord.py but why does this webhook message fail

#

this is empty apparently?

fading marlin
#

weren't you a helper a second ago? or was that april fools?

smoky sinew
#

that was april fools

fading marlin
#

ah, my condolences

smoky sinew
#

still don't understand what was wrong

slate swan
#

whole error ``` File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 204, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```

#

how fix this?

fading marlin
#

you're not responding to the interaction fast enough

slate swan
#

await message8.edit("Deleteing Files...") sleep(0.5)i think bec i have sleep lol

fading marlin
#

sleep is blocking too

slate swan
#

so how fix it>?

#

i want it to wait

fading marlin
#

defer, asyncio.sleep, not even sure what you want to do in the first place 🤷

slate swan
#

:0 asyncio.sleep

smoky sinew
#

nvm

#

im dumb

uneven hearth
#

bruh

slate swan
#

guys what> AttributeError: 'int' object has no attribute 'delete'

uneven hearth
#

button_callback is not button.callback 💀

slate swan
#

i got channel id and i try delete it but it gives me errors D: await channel_id2.delete()

slate swan
uneven hearth
#

button_callback is a function it made

#

button.callback is built

slate swan
#

ok!

smoky sinew
#

apparently it's not the same as the button decorator

slate swan
#

Hello there!

I need help with my command I dont want any suggestions just please help.


@slash.slash(
    name='8ball',
    description='Ask the Magic 8-Ball a question',
    options=[
        {
            'name': 'question',
            'description': 'The question you want to ask',
            'type': 3,  # Type 3 represents a string input
            'required': True
        }
    ]
)
async def eight_ball(ctx, question: str):
    responses = [
        'It is certain.',
        'It is decidedly so.',
        'Without a doubt.',
        'Yes - definitely.',
        'You may rely on it.',
        'As I see it, yes.',
        'Most likely.',
        'Outlook good.',
        'Yes.',
        'Signs point to yes.',
        'Reply hazy, try again.',
        'Ask again later.',
        'Better not tell you now.',
        'Cannot predict now.',
        'Concentrate and ask again.',
        'Don\'t count on it.',
        'My reply is no.',
        'My sources say no.',
        'Outlook not so good.',
        'Very doubtful.'
    ]
    response = random.choice(responses)
    await ctx.send(response)

smoky sinew
#

and what's wrong exactly

#

also a separate question - how do i use a converter from a modal when i don't have a context pithink

hushed galleon
sick birch
#

Are you using a converter on the modal fields?

#

Maybe you'd be able to create a fake context from the interaction

hushed galleon
#

you could also transform your interaction into a context object, but then you have the weirdness of raising CommandErrors when there isnt actually a command

#

!d discord.ext.commands.Context.from_interaction

unkempt canyonBOT
#

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

Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.

On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.

In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.

New in version 2.0.
hushed galleon
#

oh nevermind thats not applicable to message components

smoky sinew
smoky sinew
hushed galleon
#

no formatting, autocompletion, or option type validation with modals 😔

smoky sinew
#

yeah

#

i switched to get_channel and get_role for now

#

but they are returning None

hushed galleon
#

you converted the modal contents to ints?

smoky sinew
#

ah

#

no i didn't lol

smoky sinew
#

can i get a bot instance from an interaction

#

oh interaction.client nvm

#

@hushed galleon do you know if there's a way to add all buttons using the button decorator at the very end instead of beginning since i am also using add_item

smoky sinew
#

cursed solution

#

basically just clearing and re-adding them to force them to appear at the end

hushed galleon
#

yeah thats what i would do

smoky sinew
#

now there's just one more issue of pings not pinging anyone despite allowed_mentions allowing it

#

looks like this is a bot-wide issue

#

even though i removed allowedmentions completely

hushed galleon
#

doesnt jsk apply its own allowed mentions?

#

does it work if you manually send a message

smoky sinew
#

uh

smoky sinew
#

now why wouldn't it work for the command

#

oh now it does work

#

magic

#

OH I'M STUPID BOT DOES NOT HAVE PERMISSIONS

modern furnace
mighty sun
#

Hello, I would like to add the permission for which the roles I authorize have the power to execute this command, how should I do?

#

With a Bot command()

pine plover
#

how to host my bot 24/7 free?

mighty sun
#

on the internet @pine plover

vale wing
unkempt canyonBOT
#
Not in my house!

No documentation found for the requested symbol.

vale wing
#

They moved it or what

#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
mighty sun
#

@vale wing item = rôles ?

#

exemple : @commands.has_permissions(⚔️ General🍻 )

#

is that it? and if I have more than one role?

shrewd apex
#

make ur custom check

brisk edge
# unkempt canyon

Is this a good implementation of it?

    @app_commands.command(name='test', description="test input")
    @commands.has_role('Test')
    async def test_command(self, int: discord.Interaction) -> None:
        await int.response.send_message('Hello!', ephemeral=True)
        
    @test_command.error
    async def gpt_handler_error(self, ctx, error):
        if isinstance(error, commands.MissingRole):
            embed = discord.Embed(title="Error", description="You don't have the necessary permissions to run this command", color=0xFF0000)
            await ctx.response.send_message(embed=embed)```
#

My bot seems to be ignoring the role restrictions :S

unkempt mauve
brisk edge
deft quartz
#

Up to how long do slash_commands take to update? For some reason mine stopped updating 2 hours ago, but the unupdated commands still function normally

unkempt mauve
#

someone help

vale wing
unkempt mauve
#

how do I await it lmao

vale wing
#

I don't even see where's asyncio.run in your code, you probably provided wrong module

unkempt mauve
#

no

#
async def main():
  for filename in os.listdir('./commands'):
      if filename.endswith('.py'):
        await bot.load_extension(f'commands.{filename[:-3]}')
  await bot.start("TOKEN")

discord.utils.setup_logging()

asyncio.run(main())```
deft quartz
#

asyncio.run(main())

vale wing
#

Are you running this script specifically

unkempt mauve
vale wing
#

Please screenshot your file structure

unkempt mauve
vale wing
unkempt mauve
vale wing
#

I mean like this

unkempt mauve
#

damn

#

ignore the dumb files

vale wing
#

Ok and your "command" file is one from commands folder right?

unkempt mauve
#

yes

vale wing
deft quartz
#

Make the main function a normal function instead of an async one

vale wing
#

I suspect you have a circular import

#

Do not import anything from entrypoint script, bring everything that needs to be imported into other module

#

@unkempt mauve

unkempt mauve
#
from main import bot```
#
import discord
from discord.ext import commands
from discord import app_commands
from main import bot #imported from main

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

    @app_commands.command(name='uptime', description='Get bot uptime!')
    async def uptime(self, interaction: discord.Interaction):
        ready_split = str(bot.ready_time).split('.')
        await interaction.response.send_message(ready_split[0])

async def setup(bot):
    await bot.add_cog(UptimeCog(bot))```
vale wing
deft quartz
#

The cog file is called with the load_extension in main.py which triggers the setup and passes the bot variable so you don't have to import main no?

unkempt mauve
#

oh thank you, its working

unkempt mauve
meager orchid
#

Hello, I have a problem with a loop. I need it to check the entire list and if there is 1 match, execute a certain piece of code once. And if after checking all the values, no match is found, then another piece of code should be executed once. But in my case, it executes as many times as there are values in the list. How can I fix this?

Code, but it's a command file, sorry, I cannot share the main file.
https://paste.pythondiscord.com/ososovojan

deft quartz
#

1 and True are the same thing

#

if found will return true in both cases

vale wing
# unkempt mauve then what do I do

Sorry for late response, recommended solution is to bring whatever you import to another module and import it from there, another is put whatever code that needs to be executed only on first run into if __name__ == "__main__"

vale wing
astral vector
#

I keep getting the application did not respond error to one of the slash commands I'm trying to make, i tried defer but it didn't help is there a solution for this error?

slate swan
#
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='>')

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

bot.run("token")

i actually don't understand

thin raft
#

and try again

slate swan
#

5 times

#

i tried using a vpn aswell doesn't change anything

thin raft
#

which discordpy version do you have

slate swan
#

pip install -U discord.py

#

and make sure you are giving a token

slate swan
slate swan
slate swan
#

ohh

slate swan
naive briar
#

You sure it's token and not client secret? 🧐

naive briar
#

Wait, what's that name

slate swan
slate swan
#

wierdest name ever

#

basically its main point is to ban everyone who is acting weird

slate swan
#

mostly genshin impact players

slate swan
#

ah yeah lmaooo

slate swan
astral vector
naive briar
#

Did you respond to the interaction

astral vector
#

i did

#

it is supposed to send a message

#

and updates the database before that

naive briar
#

Can you show the code

slate swan
#

wtf i uninstalled discord.py and i still get this error even tho i dont have the package??

#

Do you have any other third party discord libraries

#

Like nextcord, pycord, disnake?

slate swan
#

however

#
@bot.command()
async def hello(ctx):
    await ctx.send("hi")
#

why is this a slash command?

#

i actually dont understand i didnt touch discord.py for 6 months and nothing works like it used to

naive briar
#

Show the full code then

slate swan
# naive briar Show the full code then
import discord
from discord.ext import commands

intents = discord.Intents.default()

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

@bot.event
async def on_ready():
    print("worked yay")

@bot.command()
async def hello(ctx):
    await ctx.send("hi")

bot.run("token")

naive briar
astral vector
# naive briar Can you show the code
@app_commands.command()
    async def acceptmarriage(self, interaction:discord.Interaction, member:discord.Member):

        if c.execute(f"SELECT * FROM proposals WHERE userid = '{interaction.user.id}' AND memberid = '{member.id}'").fetchone():
            x = c.execute(
                f"SELECT SUM(count) FROM counter WHERE userid = '{interaction.user.id}' AND memberid = '{member.id}'").fetchone()
            z = c.execute(
                f"SELECT SUM(count) FROM counter WHERE userid = '{member.id}' AND memberid = '{interaction.user.id}'").fetchone()
            number = x[0]
            num = z[0]
            if number == None:
                number = 0
            if num == None:
                num = 0
                tot = number + num
                lvl = int(tot / 5)
                if lvl < 1:
                    lvl = 1
                    c.execute(f"DELETE FROM proposals WHERE userid='{interaction.user.id}' AND memberid = '{member.id}'")
                    c.execute(f"DELETE FROM proposals WHERE userid='{member.id}' AND memberid = '{interaction.user.id}'")
                    c.execute(f"INSERT INTO marriage VALUES ('{interaction.user.id}','{member.id}','{tot}','{lvl}')")
                    c.execute(f"INSERT INTO marriage VALUES ('{member.id}','{interaction.user.id}','{tot}','{lvl}')")
                    conn.commit()


                await interaction.response.send_message("You are now married!")
        else:
            embed = discord.Embed(title="Please check /proposals to see if they proposed to you!", color=discord.Colour.blue())

            await interaction.response.send_message(embed=embed)```
This is what it is like rn
left dew
#

i’ll trying to get the content of a message, e.g when a user says $confirm (name) i want it to get the name, i’ve tried message.content but i get an error

cold sonnet
left dew
wild kite
#

I would like to ask something, cause someone texted me to help him with self bot. How much is self bot against discord terms? Also when it is used as a farming bot.

cold sonnet
unkempt canyonBOT
cold sonnet
#

!pypi discord

unkempt canyonBOT
naive briar
thin raft
unkempt canyonBOT
#
Fat chance.

No documentation found for the requested symbol.

thin raft
#

fucking docs command

cold sonnet
#

huh

astral vector
cold sonnet
#

oh yeah it's not a class

thin raft
#

idk

shrewd vapor
#

How can I solve this problem
My bot infinitely reflected but performs the action

left dew
thin raft
#

read it pls.

left dew
#

i have

thin raft
#

there's a text block that it's impossible to miss man

#
import discord
from discord.ext import commands

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

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

@bot.command()
async def test(ctx):
    pass

# or:

@commands.command()
async def test(ctx):
    pass

bot.add_command(test)
left dew
#

i dont get why you've sent me the link, i know how to make commands

#

you've not answered what i want to do

thin raft
naive briar
shrewd vapor
left dew
#

i just want to get the message content of a command

naive briar
#

Or you don't know how

shrewd vapor
# naive briar Show the code
@bot.tree.command(name="ban", description="Ban member from guild")
async def ban(interaction, member_id : discord.User, *, reason : str):
    if (not interaction.user.guild_permissions.ban_members):
        await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
        return
    await interaction.response.defer()
    await member_id.send(f"You have been banned by {interaction.user} from {interaction.guild.name}.\nReason : {reason}.")
    await interaction.guild.ban (member_id, reason = reason)
    await interaction.response.send_message(f"{member_id.id} has been banned !")
    await interaction.followup.send("")```
naive briar
#

Why interaction.response.send_message

#

Replace it with interaction.followup.send

#

To correctly respond after deferring

shrewd vapor
#

Ok I try

left dew
#

like that?

naive briar
#

Yes

shrewd vapor
#

My command unban doesn't work

#
@bot.tree.command(name="unban", description="Unban a member")
async def unban(interaction: discord.Interaction, user: discord.User) -> None:

    if (not interaction.user.guild_permissions.ban_members):
        await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")

    await interaction.guild.unban(user)
    embed=discord.Embed(title=f"{user} as been unban", inline=False)
    embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
    await interaction.response.send_message(embed=embed)```
karmic nimbus
#

anyone know how to add @unkempt canyon bot from this server to my server?

naive briar
#

It's probably a private bot

naive briar
#

And what'sinteraction.reply

shrewd vapor
#

It only takes the members present on the server as parameters

naive briar
#

It should

#

Why would it display people that is not in the server

shrewd vapor
#

I want it to take as parameter the user#0000 or the id

naive briar
#

Then do it

#

Set the parameter's type hint ot str

#

But you would not be able to get the ID of a user from their names and their tags

#

If the bot doesn't have access to them anyway

shrewd vapor
#

But I enter the id if I don't have the name

viral stump
waxen summit
#

enecccbflrnlufuvblivdnetctlvdcbggetukcflikvt

potent spear
#

you're right ^

potent spear
slate swan
#

how to go down a line in discord py slash command???

vale wing
#

Another method is use some symbol for splitting lines and replace it with newlines when parsing to command, or use modal

waxen summit
#

enecccbflrnlrculdntnbdhhrifgbtllnkubektihjvk

sick birch
viral stump
shrewd apex
shrewd apex
viral stump
#

its same, i didnt update anything

#

3 days ago this bot was working perfectly

#

now its coming channel and doing nothing

shrewd apex
#

hmm

#

u dont get any errors?

viral stump
#

nope, if you want i can show you my screen too for debugging

shrewd apex
#

u have an error handler?

viral stump
#

i am trying vss debugging, thats it

shrewd apex
#

make an error handler for commands and events

hushed galleon
# shrewd apex shift enter maybe

i remember this doing nothing when i was figuring out how to transition my tags to app commands, and apparently it was planned but nothing new has come out

viral stump
#

and it doesn't go throught after line 30, final line is 30

#

it freezes after
voice_client: discord.VoiceClient = await voice_channel.connect()

slate swan
#

bruh how do i fix this?

#

@sick birch

plain pollen
#

where did you get a module called Crypto from? is it something you've made? is it some library you installed?

sick birch
#

Pretty sure you need to install pycrypto

gritty jasper
slate swan
gritty jasper
slate swan
torn panther
gritty jasper
frail ridge
#

Can anyone tell me how to online my bot 24/7?

slate swan
frail ridge
#

How can I host

slate swan
#

read pinned messages in thread i mentioned

frail ridge
#

I thought in free also it's available :;:

slate swan
#

no obviously its not free

#

to host a script running 24/7

blissful badge
#

Hey looking for some input....

My bot responds to mentions but I am trying to get it to NOT respond to replies.

I have tinkered with a second if statement like this

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message) -> None:
        if self.bot.user in message.mentions:
            print("SCNewsBot has been mentioned.")
            await message.channel.send(f"Hello! I am the NewsBot, say `&formats` for a list of the different news prompts I contain or `&embed` to start creating a news post! If you are having any issues with my functions please tag ian `@blissful badge`.")
        if message.author == self.bot.user:
            return

but that didn't work, I believe because its pulling the replied message not the message its replying to.

I also tried this but this option

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message) -> None:
        if self.bot.user in message.mentions and not discord.Message.author():
            print("SCNewsBot has been mentioned.")
            await message.channel.send(f"Hello! I am the NewsBot, say `&formats` for a list of the different news prompts I contain or `&embed` to start creating a news post! If you are having any issues with my functions please tag ian `@blissful badge`.")

but that pulls an issue with calling member

upbeat ice
#

!d discord.MessageType.reply

unkempt canyonBOT
blissful badge
upbeat ice
#

Yeah exactly

blissful badge
upbeat ice
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

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

This must be called for the application commands to show up.
meager orchid
#

Hello, is it possible to retrieve parameter values programmatically?

sick birch
#

Can you tell us more about what you're trying to do? @meager orchid

meager orchid
#

Yes, just a moment.

#

I want to create a slash command that will delete messages in a specified quantity. I have a parameter for the value, but I need to insert its value into the purge command and then output it to users. Honestly, I have recently started working with the library.
Here's the part with the command: https://paste.pythondiscord.com/pekicuqoce

meager orchid
#

(

#

Alright, thank you.

smoky sinew
#

if i use guild_only on a group, will it apply to all of its subcommands

burnt imp
#

how do I get a users username from a users id

upbeat ice
burnt imp
naive briar
#

No

burnt imp
blissful badge
#
    @commands.Cog.listener()
    async def on_message(self, message: discord.Message) -> None:
        if self.bot.user.mentioned_in(message) and not discord.MessageType.reply:
            print("SCNewsBot has been mentioned.")
            await message.channel.send(f"Hello! I am the NewsBot, say `&formats` for a list of the different news prompts I contain or `&embed` to start creating a news post! If you are having any issues with my functions please tag ian `@blissful badge`.")

am I doing something clearly wrong here @upbeat ice? Trying that reply type out

smoky sinew
smoky sinew
#

so you're basically doing if mentioned_in_message and false

blissful badge
#

ohhh

meager chasm
#

You can just check if self.bot.user in message.mentions, it doesn't count reply iirc

gilded oxide
#
        invoke_without_command=True)
    @commands.has_permissions(manage_roles=True)
    async def role(self, ctx, user: discord.Member, *, role: discord.Role):
        @role.group()
        @commands.has_permissions(manage_roles=True)
        async def add(self, ctx, user: discord.Member, *, role: discord.Role):``` first time working w/ sub commands what should I do next?
smoky sinew
gilded oxide
#
@commands.has_permissions(manage_roles=True)
async def role(self, ctx, user: discord.Member, *, role: discord.Role):
    pass

@role.group()
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, user: discord.Member, *, role: discord.Role):
    # Add role to user here
    pass```
#

but now im confused

vital glacier
#

!rftm discord.utils.get

#

!rftm get

smoky sinew
smoky sinew
vital glacier
#

@commands.group() -> @role.group()

naive briar
smoky sinew
#

group is the subcommand

naive briar
#

!d discord.ext.commands.Group.group

unkempt canyonBOT
#

@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
vital glacier
#

odd, cus thats why it works perfectly for me?

smoky sinew
#

that's because you have like 3-4 levels of nested subcommands

vital glacier
#

not for all my cmds

#

only for some, most commands that are subcommands use commands.group and then role.group for instance

smoky sinew
#

cool

vital glacier
#

only role humans remove and bots remove are subcommands of a subcommand

#

otherwise, the others are just regular subcmds

smoky sinew
#

!d discord.ext.commands.Group.command

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
smoky sinew
#

group.group is for creating a nested subcommand

shrewd vapor
#

It does not unban when returning user#0000 or id it tells me not found

@bot.tree.command(name="unban", description="Unban a member")
async def unban(interaction: discord.Interaction, user: str) -> None:

    if (not interaction.user.guild_permissions.ban_members):
        await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
    try:
        await interaction.guild.unban(user)
        embed=discord.Embed(title=f"{user} as been unban", inline=False)
        embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
        await interaction.response.send_message(embed=embed)
    except:
        await interaction.response.send_message(f"{user} was not found in the list of banned.")```
vale wing
#

If you want to unban member by name you should use a different method cause you aren't able to get ID of the user by their name if bot doesn't share servers with them

shrewd vapor
#

How to write snowflake ?

vale wing
#

!d discord.Guild.bans

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
vale wing
shrewd vapor
#

Imagine i write /unban member: member_id

#

He don't work

vale wing
shrewd vapor
#

And same for /unban member: user#0000

vale wing
slate swan
#
Traceback (most recent call last):
  File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'

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

Traceback (most recent call last):
  File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\jishaku\features\invocation.py", line 168, in jsk_debug
    await alt_ctx.command.invoke(alt_ctx)
  File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'

pls fix this

shrewd vapor
#

Show your code

slate swan
#

okay wait

vale wing
#

Seems like your custom method

slate swan
vale wing
#

Isn't it clear that you just need to parse ctx

slate swan
#
class BotInfo(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @bot.command()
    async def botinfo(self, ctx):
        guilds = len(self.bot.guilds)
        members = len(set(self.bot.get_all_members()))
        channels = len(set(self.bot.get_all_channels()))
        
        # Memory Usage
        process = psutil.Process()
        mem_info = process.memory_info()
        memory_usage = mem_info.rss / 1024 ** 2
        
        # CPU Usage
        cpu_percent = psutil.cpu_percent()
        
        # Disk Usage
        disk_info = psutil.disk_usage("/")
        disk_total = disk_info.total // (2**30)
        disk_used = disk_info.used // (2**30)
        disk_free = disk_info.free // (2**30)
        
        message = (
            f"**Bot Information**\n"
            f"- Name: {self.bot.user.name}\n"
            f"- ID: {self.bot.user.id}\n"
            f"- Guilds: {guilds}\n"
            f"- Members: {members}\n"
            f"- Channels: {channels}\n"
            f"- Latency: {round(self.bot.latency * 1000)}ms\n"
            f"- Developer: Your Name Here\n"
            f"- Library: discord.py\n"
            f"- Github Repository: https://github.com/YourUsername/YourRepo\n\n"
            
            f"**System Information**\n"
            f"- CPU Usage: {cpu_percent}%\n"
            f"- Memory Usage: {memory_usage:.2f} MB\n"
            f"- Disk Usage: {disk_used} GB / {disk_total} GB ({disk_info.percent}%)\n"
        )
        
        embed = discord.Embed(description=message, color=0x00ff00)
        await ctx.send(embed=embed)
        await BotInfo(ctx)
#

@shrewd vapor@vale winghere is my command code

vale wing
#

await BotInfo(ctx) what

#

You can't await an object

#

And what is this even supposed to do

slate swan
#

oh sryy my bad

#

but still getting this error @vale wing

 raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'
vale wing
#

What is your setup function in that extension

slate swan
vale wing
#

Python module where your cogs are

vocal snow
slate swan
vale wing
#

🗿

#

How do you add them

shrewd vapor
#

Your command requests +info lol I think

vale wing
slate swan
# vocal snow whats the full traceback
Traceback (most recent call last):
  File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'

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

Traceback (most recent call last):
  File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\jishaku\features\invocation.py", line 168, in jsk_debug
    await alt_ctx.command.invoke(alt_ctx)
  File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'
shrewd vapor
#

Your ctx requests one argument in the +info

#

try write {prefix}info lol

slate swan
#

its because you need to decorate it as @commands.command() in a cog

vocal snow
#

await BotInfo(ctx)
what dis is uspoesd to do

glad cradle
vale wing
#

do you seriously think they did that

glad cradle
#

¯_(ツ)_/¯

#

they've deleted the troll role 😭😭

vale wing
vocal snow
vale wing
#

You don't?

vocal snow
#

look closely

glad cradle
#

I'm looking closely and still you don't have it

vale wing
glad cradle
#

(looking very close to that cat)

echo wasp
#

how do i fetch a users display name or global name?

slate swan
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
slate swan
#

!d discord.Member.display_name

unkempt canyonBOT
#

property display_name```
Returns the user’s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
echo wasp
#

making an afk command

echo wasp
slate swan
unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
echo wasp
#

member i always used in a join message and user in commands but how does that apply?

slate swan
#

you use slash or prefixed commands?

echo wasp
#

that wouldbe in interaction

#

slash

echo wasp
slate swan
#

!d discord.Interaction.user

unkempt canyonBOT
echo wasp
slate swan
#

dont you want to get the user who invoked the command?

echo wasp
#

i can do that

slate swan
#

then interaction.user returns user who invoked command

#

then you can just do any methods that apply to discord.Member object

#

so you can edit his name get his name

#

anything

deft quartz
#

Hey guys, my slash commands stopped working like a day ago and haven't updated since.. The not updated versions of the commands are still there and functional but the changes aren't visible in discord. All my cogs are loaded, i tried to reset my discord token but still no changes any ideas?

cloud dawn
deft quartz
cloud dawn
#

There is no documentation if I can't determine the cause.

#

I'd have to see how you handle the sync.

weak quarry
# slate swan ```py Traceback (most recent call last): File "C:\Users\badbo\AppData\Local\Pa...

This error indicates that the BotInfo.botinfo() function is missing the required ctx argument when it is being called. ctx stands for the Context object which is a parameter passed by the discord.ext.commands framework to commands and event functions.

To fix this error, you need to make sure that the BotInfo.botinfo() function has the ctx parameter defined in its function signature. Here's an example of how you can modify the function definition to include the ctx parameter:

Code:

async def botinfo(self, ctx):
    # Your code here```

Make sure that the `ctx` parameter is the first argument of the function, and that the `@commands.command()` decorator is used to define the function as a command.

Once you've made the necessary changes, try running your bot again and see if the error has been resolved.
shrewd vapor
#

My bot is rate limit without me knowing why

deft quartz
#

How would I pass a function as a parameter to choices in Option?

async def faq(self, ctx, question: Option(str, choices=lambda: questionShorts(), required=False)

returns error

TypeError: 'function' object is not iterable
vale wing
vale wing
shrewd apex
slate swan
deft quartz
slate swan
#

So just pass choices=myFunc()

deft quartz
shrewd vapor
#

Is my own hoster

slate swan
shrewd vapor
#

Do not speak, when you do not know

slate swan
#

what ? I asked a question

#

its your own hoster so how would I know

vale wing
shrewd vapor
#

I have

#

I pay my own Vps for host project for others user

vale wing
#

Is it on cluster or on single machine

shrewd vapor
#

Cluster

slate swan
#

if multiple bots use the same ip they share the rate limits

vale wing
#

You should monitor the traffic of that node

slate swan
shrewd vapor
vale wing
#

That's single machine...

slate swan
shrewd vapor
#

No I have others for others node

slate swan
shrewd vapor
#

Others node is surcharged

vale wing
#

Okay then you should just check the traffic and see if it's ratelimited because of excessive amount of requests to discord API

slate swan
vale wing
#

Yeah

#

They can also check specific process

slate swan
#

so since they are hosting 3 bots using the same ip, they get rate limited with each other

#

and to prevent it best thing it to use different ips if possible else somehow use proxies for each one

full lily
#

How can you invoke a command from an event

#

with bot.invoke(), it wants you to pass in a context object. Should I create one myself? That doesn't seem right, discord.py takes care of that usually

#

ctx.invoke() would be good, but this would only work if I already have a ctx object. So going from a command to a command, not from an event to a command

vale wing
slate swan
#

commands.Bot has get_context

vale wing
#

!d discord.ext.commands.Bot.get_context

unkempt canyonBOT
#

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

Returns the invocation context from the message or interaction.

This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

Note

In order for the custom context to be used inside an interaction-based context (such as [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand")) then this method must be overridden to return that class...
slate swan
#

yeah this

#

then you get ctx

#

then you use ctx.invoke

full lily
#

alrighty and then I can just ctx.invoke()

slate swan
#

yes

full lily
#

thanks for that

slate swan
#

also

full lily
#

uwu

vale wing
slate swan
#

check if ctx.command is not None

#

if it is None it means the message is not a valid command

lethal rain
#

thumbs_up thank you guys

young pendant
deft quartz
#

Probably a stupid question but, how do I call a class method from a choices parameter in discord.Option?

class GameRelated(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot
    @classmethod
    def get_questions(cls):
        ...
        return questions # List
    @commands.slash_command(name="faq")
    async def faq(self, ctx, question: Option(str, choices=GameRelated.get_questions(),              required=False, description="")):
        ...

This command prints the error "GameRelated is not defined"

hushed galleon
#

are your questions statically defined? or do you expect them to change often

#

choices are intended for options that dont change, but if you're planning to update those questions somewhat frequently you should use autocompletion instead

#

for the latter i dunno how pycord implements it but i assume there's at least a technique similar to dpy

slate swan
#

Pls can anyone help

hushed galleon
#

^

slate swan
hushed galleon
blissful badge
#

Having a weird issue....

    @commands.command(name='commands')
    async def send_data(self, ctx):
        await ctx.send("__All commands use & prefix__ \nMention me directly to check my status\n**formats** - see the available formats I store\n**embed** - start creating a news post")
        channel = self.bot.get_channel(1086293466054656100)
        author = ctx.author.name
        await channel.send(f"Command list access by {author}")

So I can't tell for sure why this isn't working but it was working before I adjusted the text inside the ctx.send. This is the error, what could have introduced this?

AttributeError: 'NoneType' object has no attribute 'send'

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

Traceback (most recent call last):
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
shrewd apex
#

some ppl still dont know 😔

blissful badge
potent spear
#

also, why not create a custom help command?

#

seems more like what you need

blissful badge
#

I was told early on to ignore all the help stuff thats built in

#

And that it was dumb

#

So I've kinda been doing exactly that.

#

And theres only like 3 commands so its not a big deal

#

Plus this issue isn't with it sending the list of commands, its in its reporting function where it says an action was performed in a log channel

steel mango
#

USER_ID = '1054495095413555220'

@client.event
async def on_member_update(before, after):
if before.id == USER_ID and before.status == discord.Status.offline and after.status == discord.Status.online:
# Replace with your own message
message = f'{before.name} is now online!'
channel = client.get_channel('976797676714749986') # Replace with the ID of the channel where you want to send the message
await channel.send(message) I wrote this code to give a message when a certain user goes online but it isnt working can someone help me fix?

potent spear
steel mango
#

ok so thats the issue?

potent spear
#

correct

steel mango
#

so channel id should also be int

potent spear
potent spear
blissful badge
potent spear
blissful badge
#

Sorry that I didn't have it ready

#
2023-04-06 13:04:06 ERROR    discord.ext.commands.bot Ignoring exception in command previews
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Bots\SCNewsBot\responses.py", line 21, in previews
AttributeError: 'NoneType' object has no attribute 'send'

The above exception was the direct cause of the following exception:
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
potent spear
steel mango
potent spear
steel mango
#

yeah

#

maybe intents problem?

potent spear
#

it's not a yes - no type question

potent spear
#

in dev portal as well as in code
but you just said "not working" so I assumed errors, I guess it's not even running the event
that's the downside of being vague

steel mango
#

i already have all intents enabled

#

so its code

potent spear
#

proof?

steel mango
potent spear
#

alr, and in code?

steel mango
#

import os
from keeprunning import keep_alive
import random
import discord
from discord import Intents
from discord.ext import commands

TOKEN = os.environ['TOKEN']

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

client = commands.Bot(command_prefix=".", intents = intents)
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))

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

USER_ID = 1054495095413555220

@client.event
async def on_member_update(before, after):
if before.id == USER_ID and before.status == discord.Status.offline and after.status == discord.Status.online:

    message = f'{before.name} is now online!'
    channel = client.get_channel(976797676714749986) 
    await channel.send(message)

keep_alive()
client.run(TOKEN)

potent spear
#

you don't have presence intents enabled in code

steel mango
#

you have to enable in code too?

potent spear
#

so this part
after.status == discord.Status.online
will always be False

potent spear
steel mango
#

ok so whats the code to enable

potent spear
#

take a guess

#

you've figured out how to enable members intents, what would it be for presence?

steel mango
#

intents.presence?

potent spear
#

no, you're guessing

#

check the docs

#

I'll give you the link

steel mango
#

ok

steel mango
#

intents.presences

potent spear
#

yup

steel mango
#

ok thank you

potent spear
#

gl!

steel mango
potent spear
#

code?

steel mango
potent spear
#

also, how are you testing this?

steel mango
#

alt account

potent spear
steel mango
#

import os
from keeprunning import keep_alive
import random
import discord
from discord import Intents
from discord.ext import commands

TOKEN = os.environ['TOKEN']

intents = Intents.default()
intents.message_content = True
intents.members = True
intents.presences = True

client = commands.Bot(command_prefix=".", intents = intents)
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))

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

USER_ID = 1054495095413555220

@client.event
async def on_member_update(before, after):
if before.id == USER_ID and before.status == discord.Status.offline and after.status == discord.Status.online:

    message = f'{before.name} is now online!'
    channel = client.get_channel(976797676714749986) 
    await channel.send(message)
steel mango
steel mango
#

ill try

potent spear
#

in this case btw

intents = Intents.default()
intents.message_content = True
intents.members = True
intents.presences = True```
you can just use Intents.all()
steel mango
#

ok

#

also are you sure the ids should be int

potent spear
#

yup

steel mango
#

ok

potent spear
#

print something in the event, to confirm it triggers

steel mango
#

ok

slate swan
#

can someone help me pls ?

#
import time

time.sleep(2)
print("Welcome !")
time.sleep(2)

file = open("test.txt", "w")
file.append("Testttt")
slate swan
#

So you cant write

#

okay

slate swan
lusty karma
#

ok, so what is the issue? bot is not responding when i type something or ping it

slate swan
#

Do you know how to work with files?

slate swan
#

Do you know how to open a file in write mode?

#

yeah sure

cerulean ibex
#
@client.event
async def on_message(message):
    # Define the user whose messages you want to react to
    user_id = '503127565611958274'

    print(f'Message content: {message.content}')
    print(f'Message author ID: {message.author.id}')

    if message.author.id == user_id:
        # Define the list of emojis to randomly react with
        emojis = [":grinning:",":kissing_heart:",":kiss:",":heart_eyes:",":heart:"]

        # Choose a random emoji from the list
        emoji = random.choice(emojis)

        # React to the message with the chosen emoji
        await message.add_reaction(emoji)
        print(f'Reacted to message with emoji: {emoji}')```

I want my bot to react to all the messages user_id sends 
but for some reason it is reading them but not reacting to it
what am i doing wrong ?
slate swan
#

@slate swan

slate swan
#

Cause you never used it

slate swan
#

huh ?

#

You executed it as console command

cerulean ibex
slate swan
#

oh yeah

#

i'm so dumb2 sec

night agate
#

im having problems

my code isnt working at all or showing up as a embed and theres no errors

slate swan
#

@slate swan

night agate
# night agate im having problems my code isnt working at all or showing up as a embed and the...
from discord.ext import commands, menus

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

    @commands.Cog.listener()
    async def on_ready(self):
        print("Ping.py is loaded!")

    @commands.command()
    async def ping(self, ctx):
        bot_ping = round(self.bot.latency * 1000)

        await ctx.send(f"Pong! {bot_ping}ms")

    @commands.command()
    async def pages(self, ctx):
        pages = []
        for i in range(50):
            page = discord.Embed(title=f"Page {i+1}", description=f"This is page {i+1}.")
            pages.append(page)

        paginator = menus.MenuPages(source=menus.ListPageSource(pages, per_page=1), clear_reactions_after=True)

        await paginator.start(ctx)


async def setup(bot):
   await bot.add_cog(Ping(bot))
slate swan
#

That's true, I didn't close the file. Is there anything else I can help you with?

#

oh yeah my bad

#

No problem. Is there anything else I can help with?

#

looks like a bot

#

it worked noice

#

thanks @slate swan mababe

lusty karma
#

now it shows this

slate swan
lusty karma
#

wym read it 😄

#

im new to python, i just started the discord bot process

slate swan
#

read the error message?

#

there is a link to follow

lusty karma
#

that one i read, and i cant find anywhere to enable or disable intents

gilded oxide
#
    @commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
    async def banner(self, ctx, member: discord.Member = None):
        try:
            if member is None:
                member = ctx.author

            icon_url = member.banner.url

            bannerembed = discord.Embed(title=f"{member.name}'s banner",
                                        color=0xFFFFFF)

            bannerembed.set_image(url=f"{icon_url}")

            await ctx.send(embed=bannerembed)

        except Exception: 
            embed=discord.Embed(description=f"failed to load {member}'s banner")
        await ctx.send(embed=embed)``` when im doing my banner command the command itself won't load but itll say its failed to load my banner??
slate swan
#

there are intents

lusty karma
#

im enabled them

#

so i need to disable?

slate swan
#

enable those that you use in code

#

@slate swan the python program won't execute :

print("Welcome !")

file = open("file.txt", "w")
file.write("Testttt")
slate swan
#

what did you try

#

to launch the program with python

#

(double clicking on this file)

#

so it means there are some errors

#

why dont you use some ide to help you?

#

like VS Code

#

i'm using it

#

so why are you running a file from file explorer

#

bcz i can't run it from vscode

#

💀

#

and why is that?

#

idk how

#

did you install Python extension?

#

sure

#

then there is in top right start button

#

yeah i tryied

#

and?

#

i didn't get the python option beforce

#

before*

#

what is python option

ionic garden
#

when i try to respond to an interaction, why does python give this bug?

slate swan
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
vale wing
sick birch
burnt imp
vale wing
#

When I see ratelimit error in this channel I get neuron activation

#

Although I don't even remember how replit looks like

#

Why'd you scroll up and reply specifically to that message tho 🧐

slate swan
#

is this pycharm ?

night agate
#

im having problems

my code isnt working at all or showing up as a embed and theres no errors

from discord.ext import commands, menus

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

    @commands.Cog.listener()
    async def on_ready(self):
        print("Ping.py is loaded!")

    @commands.command()
    async def ping(self, ctx):
        bot_ping = round(self.bot.latency * 1000)

        await ctx.send(f"Pong! {bot_ping}ms")

    @commands.command()
    async def pages(self, ctx):
        pages = []
        for i in range(50):
            page = discord.Embed(title=f"Page {i+1}", description=f"This is page {i+1}.")
            pages.append(page)

        paginator = menus.MenuPages(source=menus.ListPageSource(pages, per_page=1), clear_reactions_after=True)

        await paginator.start(ctx)


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

can anyone help me thanks

gilded oxide
#
    @commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
    async def banner(self, ctx, member: discord.Member = None):
        try:
            if member is None:
                member = ctx.author

            icon_url = member.banner.url

            bannerembed = discord.Embed(title=f"{member.name}'s banner",
                                        color=0xFFFFFF)

            bannerembed.set_image(url=f"{icon_url}")

            await ctx.send(embed=bannerembed)

        except Exception: 
            embed=discord.Embed(description=f"failed to load {member}'s banner")
        await ctx.send(embed=embed)``` is there something wrong with my code? It won't send my banner but the embed will load bc thats what it says when i do the command
night agate
#

yes

potent spear
#

So you can read the on_ready print?

night agate
#

yes

#

i do the command it doesnt work

potent spear
#

No

#

Does any other command in the cog work? ( add a random one )

night agate
#

yes

gilded oxide
#

failed to load rott#0001's banner in the embed

cloud dawn
gilded oxide
#

how would I do that I haven't done that before ? (still getting py down while coding sorry!)

potent spear
night agate
potent spear
#

Not really?

night agate
#

not yet im saying

potent spear
#

That’s good…

#

So you’re calling the command but nothing gets sent nor are there errors?

night agate
#

here look

#

i added a error handler and i get this

#

added this

            raise error```
cloud dawn
night agate
#

oh nvm i got it@potent spear

#

Command raised an exception: NotImplementedError:

#

this is the error

potent spear
#

Full error is needed tho

gilded oxide
night agate
potent spear
#

Can’t be

#

Then you’re hosting it on some weird shit OR you have error handlers somewhere

cloud dawn
# gilded oxide still nothing for sum reason?
@commands.command(aliases=['bann'])
@commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
async def banner(self, ctx, member: discord.Member = None):
    member = await ctx.bot.fetch_user((member or ctx.author).id)

    banner_embed = discord.Embed(
        title=f"{member.name}'s banner",
        color=0xFFFFFF
    )
    banner_embed.set_image(url=member.banner.url)

    await ctx.send(embed=banner_embed)
upbeat ice
#

The error is being swallowed

cloud dawn
#

Let's try this...

upbeat ice
cloud dawn
potent spear
#

Don’t copy paste tho

potent spear
#

A member IS a user obj…

upbeat ice
#

No

gilded oxide
#

WORKED

upbeat ice
#

It's not

potent spear
#

I’m listening

cloud dawn
#

It takes an int

#

Not an object

potent spear
#

mhm, makes sense to fetch a user by passing an id

upbeat ice
#

!d discord.User

unkempt canyonBOT
#

class discord.User```
Represents a Discord user.

x == y Checks if two users are equal.

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

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
potent spear
#

Member inherits from User…

cloud dawn
gilded oxide
#

I couldn't find it lol

#

sorry

#

I should've tried that

cloud dawn
gilded oxide
#

i fixed it

cloud dawn
#

memebr lol

gilded oxide
#

lol

#

I wanted to use pinterest api but its so confusing so im not going to

potent spear
#

Try using it outside a discord bot first, then integrate

cloud dawn
#

Discord is prob more complicated lol

gilded oxide
#

bc I need a token and all of that but I can't

#

bc with the recruit_uri that takes a minute

#

and its apart of the code

#

link = pinterest.oauth2.authorization_url(app_id, redirect_uri) the app_id loads automatically but I need approved for redirect_uri

#

I'm just trying to make an auto pfp and banner command for where the bot fetches images of a certain style and drops it into the chat

cloud dawn
#
@commands.command(aliases=['bann'])
@commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
async def banner(self, ctx, member: discord.Member = None):
    await ctx.send(embed=(m:=await ctx.bot.fetch_user((member or ctx.author).id),discord.Embed(title=f"{m.name}'s banner",color=0xFFFFFF).set_image(url=m.banner.url))[1])
#

woops

potent spear
#

Oneliner 🫠

upbeat ice
ionic garden
potent spear
ionic garden
slate swan
cloud dawn
ionic garden
#

that's what i thought- vsc & python don't seem to complain

upbeat ice
#

it does take a user

sick birch
upbeat ice
#

you are probably just passing it incorrectly

cloud dawn
potent spear
#

agreed, the docs aren’t thát filled with examples too :/

cloud dawn
#

Well... not that pycharm is strict.. but it's getting there.

ionic garden
#

honestly 100% strict linting isn't the best either

gilded oxide
#

idk how else to make an auto pfp or banner command without pinterest api bc thats how most ppl make it

gilded oxide
#

wdym?

slate swan
runic nova
#

Do you have the discord rpg code for me?

slate swan
cloud dawn
gilded oxide
#

no

#

i haven't used api

#

I want to but I can't

cloud dawn
slate swan
cloud dawn
#

vscode etc require to install extensions for linting.

slate swan
#

kinda off topic

cloud dawn
gilded oxide
#

so how bots can fetch an image like and post it in the chat bc its from a website

slate swan
#

if its a direct link discord will put it there itself

gilded oxide
#

no the bot sent it

#

like they get it from pinterest and take the image link

cloud dawn
#

Why is it a discord url tough?

#

That's odd

gilded oxide
#

here ill show u

slate swan
#

I think they mean this :

they give the bot a pintrest link and it uploads it in chat

glad cradle
slate swan
gilded oxide
#

no look

#

like how does it upload the images

cloud dawn
#

Honestly if all you wanted to do is embed images i'd just use scraping to get the source url and then have the bot post that url.

gilded oxide
#

I mean that'd work if it can do multiple styles like male, female, and other stuff like that

cloud dawn
#

Pinterest doesn't really have an API capable of this.

gilded oxide
#

well we can do scraping ig

#

how would that even work

cloud dawn
#

You'd need to use aiohttp for the html data then use a package like beautifulsoup4 and get the info. Keep in mind that beautifulsoup is sync so you do want to run that in an async executer preferably.

gilded oxide
#

..

#

huh?

gilded oxide
# cloud dawn You'd need to use aiohttp for the html data then use a package like beautifulsou...
from bs4 import BeautifulSoup as bs4

root = "https://pfps.gg/pfp/"

query = input("search term: ")  # test query


def get_page(url):
    r = requests.get(url)
    return r.content


def scrape_page(url):
    pfps = []
    soup = bs4(get_page(url), "html.parser")
    scraped_pfps = soup.find_all("div", {"class": ["item-details", "text-center"]})
    for pfp in scraped_pfps:
        child = pfp.findChildren("a", recursive=False)
        if child:
            pfps.append(child[0])
    return pfp_dict(pfps)


def pfp_dict(l):
    pfps = {}
    for pfp in l:
        pfp = str(pfp)
        if pfp.split('href="')[1].split('">')[0].split("/")[-1][0:4].isdigit():
            pfps[pfp.split('>')[1].split("</")[0]] = pfp.split('href="')[1].split('">')[0]
    return pfps


search = scrape_page(f"{root}{query}")
print(search)``` like this?
cloud dawn
#

ewwie no

gilded oxide
#

THEN HOW?!

#

someone reccommended it to me when i had a forum open about the api

cloud dawn
#

You'd need to do more research on it. It's not like you can just make this in a day on the first go.

#

I recommend using the docs from the packages.

#

Both of them have decent docs.

gilded oxide
#

then ill js pass on doing that ill work on more mod, info, and stuff like that

#

i cant spend all day on a command

#

maybe when I'm close to finishing

cloud dawn
#

Lol

#

The eval command in this server has been ongoing for multiple years with numerous experienced programmers and it still has some issues.

#

Coding takes time.

gilded oxide
#

can we go into a forum and could u help me w/ a few commands?

cloud dawn
#

You can tag me.

gilded oxide
#

kk

#

wait in the forum?

#

or here

cloud dawn
#

idm

idle palm
#

do you guys think its ok to host a bot on a spare old laptop i have? It overheats so im gonna place a fan by it but im scared to keep it on charge 24/7 because it will drain the battery as it will be used 24/7

slate swan
#

I don't suggest you use a whole laptop for that because its bad both laptop and bots performance, usually bots are locally hosted on resbarry pis or desktop old computers

edgy zinc
#

there is services where you can host for 1dollar a month I think

#

I found one for 3euros a month

slate swan
#

1 dollar no I haven't seen but for 5-6 a month there are nice vps

edgy zinc
#

something named Pebble

slate swan
#

haven't heared of it, there are a lot of providers tho

#

and kind of off topic as well

edgy zinc
#

yeah..

whole shoal
#

Command 'gungame' raised an exception: TypeError: Button.init() got an unexpected keyword argument 'label'

#

button1=Button(label="Join!", style=discord.ButtonStyle.green)
join_but=View()
join_but.add_item(button1)

#

anyone has any idea

slate swan
#

how are you importing Button

whole shoal
#

from discord.ui import Button, View

edgy zinc
#

well why don't you use a decorator with a callback function instead

#

it's much easier `

whole shoal
#

ye trying that let me check

edgy zinc
#
@discord.ui.button(label="Join!", style=discord.ButtonStyle.green)
async def create_invoice(self, interaction: discord.Interaction, button: ui.Button):
  await interaction.response.send_message("Test")
#

and then put this into a view class

#

that's it

#

then you can instanciate the class :)

#
class JoinServerUI(ui.View):
  def __init__(self, timeout: int = None):
    super().__init__(timeout=timeout)

  @discord.ui.button(label="join", style=discord.ButtonStyle.green)
  async def join(self, interaction: discord.Interaction, button: ui.Button):
    await interaction.response.send_message("Test")
#

Then just send a message and write :
interaction.response.send_message(embed=embed_join, view=JoinServerUI())

#

:) @whole shoal

edgy zinc
#

btw label should be in lowercase

#

discordpy do not specify this in their errors because dumb error management :(

whole shoal
#

Oh 💀

#

The label keyboard or the content inside @edgy zinc

whole shoal
#

Yah no it's the same error

edgy zinc
#

damn can I see further code ?

#

btw come dm it will be more simple for me

slate swan
#

no dms please

thin raft
#

what would be better

#

check in the sql statement if it is alike or check it in the autocomplete?

slate swan
#

what do you mean

thin raft
#

I can do

#
    def get_similarities(self, check: str, limit: int = 20):
        result = self.c.execute("SELECT name FROM tags WHERE name LIKE %?% LIMIT ?", (check, limit))
        return result.fetchall()```
#

or do smt like this

**@fruits.autocomplete('fruit')
async def fruits_autocomplete(
    interaction: discord.Interaction,
    current: str,
) -> List[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    return [
        app_commands.Choice(name=fruit, value=fruit)
        for fruit in fruits if current.lower() in fruit.lower()
    ]**```
slate swan
#

probably better to do in autocomplete

thin raft
#

is there a limit for autocomplete optoins?

#

k nvm
The coroutine decorator must return a list of Choice objects. Only up to 25 objects are supported.

edgy zinc
#

like : Literal["banana", "pineapple" etc]

#

and it works just fine for me

thin raft
#

makes sense ngl

#

idk why they didn't made it a list or tuple

smoky sinew
#

i don't think that's how it works

#

[] uses the indexing syntax

#

() would be calling a method or class

thin raft
#

I think

#

idk how to search it

hushed galleon
# thin raft idk why they didn't made it a list or tuple

if you wanted to define the choices as a list, you could use the choices() decorator instead
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.choices py @app_commands.command() @app_commands.describe(fruits='fruits to choose from') @app_commands.choices(fruits=[ Choice(name='apple', value=1), Choice(name='banana', value=2), Choice(name='cherry', value=3), ]) async def fruit(interaction: discord.Interaction, fruits: Choice[int]):

thin raft
#

didn't meant that

#

I can't do that as the values may vary

hushed galleon
#

then what were you referring to by "making it" a list/tuple?

edgy zinc
#

by using Literal

hushed galleon
#

i know, im just asking them specifically what they meant

edgy zinc
#

yo can actually just write :

@app_commands.command()
@app_commands.describe(fruits='fruits to choose from')
async def fruit(interaction: discord.Interaction, fruits: Literal['apple', 'banana', 'cherry']):
#

oh ok sure

thin raft
#

btw

#

how does Literal handle the [] ?

hushed galleon
#

they implement __class_getitem__

thin raft
#

hmm

edgy zinc
edgy zinc
thin raft
#

ty <3

hushed galleon
thin raft
#

I am having issues with the spacingin my pc it looks like this

#

I was gettting a weird socket error

#

@edgy zinc

edgy zinc
thin raft
#

from the flask app

edgy zinc
#

may I help you ?

thin raft
#

I just executed the app from terminal instead of vsc

#

but my main issue is this one

edgy zinc
#

yes ?

thin raft
#

but it doesn't pre-wrap once deploying it on nginx

edgy zinc
#

so the problem is in style not logic ?

thin raft
#

yeah

edgy zinc
# thin raft yeah

go on the server I have in my description to not get the people from here angry because ouuuh against the rules to talk off topic

amber basalt
#

Hi