简体   繁体   English

(Discord.py) 斜线命令问题 (app_commands)

[英](Discord.py) Problem with slash commands (app_commands)

I'm having trouble with making slash commands.我在制作斜杠命令时遇到了麻烦。 So, I'm learning how to create app commands in discord.py, but my bot doesn't respond to the commands.所以,我正在学习如何在 discord.py 中创建应用程序命令,但我的机器人没有响应这些命令。 By the way, i didn't get any error messages.顺便说一句,我没有收到任何错误消息。

Cog齿轮

import time
import discord
from discord.ext import commands
from discord import app_commands
from discord.ext.commands import Context
from discord.ext.commands import Bot

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

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


    @commands.command()
    async def ping(self, ctx):
        yo = round(self.bot.latency * 1000)
        embed = discord.Embed(title="Pong! :ping_pong:", color=discord.Color.random())
        embed.add_field(name="Latency:", value=f"{yo}ms")
        await ctx.send(embed=embed)


    @app_commands.command(name="hi", description="Say hi!")
    async def hi(self, interaction: discord.Interaction, word:str):
        await interaction.response.send_message(f"Hi {word}!")

    @app_commands.command(name="num", description="Random numbers")
    async def num(self, interaction: discord.Interaction, *, first: int, second: int) -> None:
        szam = random.randint(first, second)
        embed = discord.Embed(title="Random number", color=discord.Color.random())
        embed.add_field(name=f"{context.author}'s number is:{szam}", value=f"Lowest:{first} | Highest:{second}",
                        inline=False)
        embed.timestamp = datetime.datetime.utcnow()
        await interaction.response.send_message(embed=embed)

    @app_commands.command(name="test", description="test")
    async def test(self, interaction: discord.Interaction, szam:str):
        await interaction.response.send_message(f"Szám:{szam}")

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

Main.py主.py

import os
import discord
from discord.ext import commands
import asyncio
import requests
import json
from discord.utils import get
from discord.utils import find
import datetime
import random
from discord import app_commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all(), help_command=None)

@bot.event
async def on_ready():
    print("Successfully connected to the server!")
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} server | !help"))


async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')

async def main():
    async with bot:
        await load()
        await bot.start("")


asyncio.run(main())

PS: The "hi" command works fine, but there others are not working. PS:“hi”命令工作正常,但其他人不工作。

I checked the bot's intents, and the bot's permissions, but everything is fine and the commands still not working.我检查了机器人的意图和机器人的权限,但一切正常,命令仍然无效。

In discord.py 2, you have to sync the commands (in order for them to show up) yourself using app_commands.CommandTree.sync .在 discord.py 2 中,您必须使用app_commands.CommandTree.sync自己同步命令(以便它们显示)。 Modified example from discord.py GitHub.来自 discord.py GitHub 的修改示例

MY_GUILD = discord.Object(id=0)  # replace with your guild id

# In this basic example, we just synchronize the app commands to one guild.
# Instead of specifying a guild to every command, we copy over our global commands instead.
# By doing so, we don't have to wait up to an hour until they are shown to the end-user.
async def setup_hook():
    # This copies the global commands over to your guild.
    bot.tree.copy_global_to(guild=MY_GUILD)
    await bot.tree.sync(guild=MY_GUILD)

bot.setup_hook = setup_hook

You can look at this FAQ for more information.您可以查看此常见问题解答以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM