pythondiscordpycord

How to remove interaction error on pycord?


How fix error interaction? I asked ChatGPT, but he led me in circles.

My code:

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

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

servers = \[1249591729171071077\]

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.slash_command(description="Приветствие от бота")
async def hello(ctx):
    await ctx.send("Привет! Я бот Discord!")

@bot.slash_command(guild_ids=servers, name="ping", description="Отправляет задержку бота.")
async def ping(ctx):
    await ctx.send(f"Pong! Задержка составляет {bot.latency} мс.")

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

change from ctx.send to ctx.respond()


Solution

  • In order to fix this, you will have to change ctx.send to ctx.respond, or else the command will error out. Discord Application Commands of which slash command are part, require you to respond to the interaction. So if you use ctx.send you will just send a message in the channel, without responding to the interaction.

    Also, you are setting the command_prefix="t." parameter in your bot, even tough it is never used since you are using slash_commands.

    If you still want to send a message, but don't want the error, you can also respond in ephemeral. You can see my example below:

    import os
    
    import discord
    from discord.ext import commands
    from dotenv import load_dotenv
    
    load_dotenv()
    intents = discord.Intents.all()
    bot = commands.Bot(command_prefix="t.", intents=intents)
    
    servers = [1249591729171071077]
    
    
    @bot.event
    async def on_ready():
        print(f"{bot.user} is ready and online!")
    
    
    @bot.slash_command(description="Приветствие от бота")
    async def hello(ctx):
        await ctx.respond("Command processed!", ephemeral=True)
        await ctx.send("Привет! Я бот Discord!")
    
    
    @bot.slash_command(guild_ids=servers, name="ping", description="Отправляет задержку бота.")
    async def ping(ctx):
        await ctx.respond("Command processed!", ephemeral=True)
        await ctx.send(f"Pong! Задержка составляет {bot.latency} мс.")
    
    
    bot.run(os.getenv('TOKEN'))