我在生成斜杠命令时遇到问题。所以,我正在学习如何在discord.py中创建应用程序命令,但我的机器人不会响应这些命令。顺便说一下,我没有收到任何错误消息。
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
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())
附言:;嗨"命令运行良好,但其他命令不起作用
我检查了机器人的意图和权限,但一切都很好,命令仍然不起作用。
在discord.py 2中,您必须使用app_commands.CommandTree.sync自己同步命令(以便它们显示)。修改自discord.pyGitHub的示例。
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
您可以查看此常见问题解答以了解更多信息。