Discord Bot 开发中的斜线命令预览出现问题

问题描述 投票:0回答:1

我刚刚开始使用 Python 编写 Discord 机器人,并且我已经成功让我的机器人启动并运行。但是,我遇到了斜杠命令预览的问题,我似乎无法解决。机器人功能正常,但斜杠命令预览未按预期工作。我正在寻找有关如何解决此问题的指导。

我已附上我所面临问题的屏幕截图(我看不到我的机器人命令):

Screenshot

为了启用斜杠命令预览,是否需要做一些特定的事情?我尝试在网上寻找解决方案,但找不到任何相关信息。由于我对 Discord 机器人开发还比较陌生,所以我不确定我是否错过了关键步骤,或者是否有一个我需要掌握的概念。

注意:我对 Python 编程有深入的了解,但我对 Discord 机器人编码还很陌生。

import discord
from discord.ext import commands
import os
import requests

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

@bot.event
async def on_ready():
    print("Bot connected to Discord")

@bot.command(name="weather")
async def weather(ctx, city):  
    base_url = "http://api.openweathermap.org/data/2.5/weather?"
    complete_url = base_url + "appid=" + os.getenv('weatherapi') + "&q=" + city
    response = requests.get(complete_url)
    data = response.json()

    location = data["name"]
    temp_c = (data["main"]["temp"]) - 273.15
    temp_f = (temp_c * 9 / 5) + 32  # Converts Celsius to Fahrenheit
    humidity = data["main"]["humidity"]
    wind_kph = data["wind"]["speed"]
    wind_mph = wind_kph * 0.621371  # Convert km/h to mph
    condition = data["weather"][0]["description"]
    image_url = "http://openweathermap.org/img/w/" + data["weather"][0]["icon"] + ".png"

    embed = discord.Embed(title=f"Weather for {location}", description=f"The condition in `{location}` is `{condition}`")
    embed.add_field(name="Temperature", value=f"C: {temp_c:.2f} | F: {temp_f:.2f}")
    embed.add_field(name="Humidity", value=f"Humidity: {humidity}%")
    embed.add_field(name="Wind Speeds", value=f"KPH: {wind_kph:.2f} | MPH: {wind_mph:.2f}")
    embed.set_thumbnail(url=image_url)

    await ctx.send(embed=embed) 

bot.run(os.getenv('TOKEN'))
python python-3.x discord discord.py openweathermap
1个回答
0
投票

您将 / 作为文本命令而不是斜杠,这样做

from discord import app_commands ##put this below the imports up there

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

然后将我要写的代码放在下面: bot - command.Bot(command_prefix="$",intents=discord.Intents.all()) 我传递给你的代码

class Bot(commands.Bot):
def __init__(self):
    intents = discord.Intents.default()
    intents.message_content = True
    super().__init__(command_prefix = "$", intents = intents)

async def setup_hook(self):
    await self.tree.sync(guild = discord.Object(id = SERVID))
    print(f"Synced slash commands for {self.user}.")

async def on_command_error(self, ctx, error):
    await ctx.reply(error, ephemeral = True)

然后将@bot.command更改为@bot.hybrid_command(name= "weather", with_app_command = True)

然后将 @bot.hybrid_command 放在此代码下方:

@app_commands.guilds(discord.Object(id = ID)) #change the ID to your server ID

应该看起来像这样:

@bot.hybrid_command(name="weather", with_app_command = True)
@app_commands.guilds(discord.Object(id = ID)) #change the ID to your server ID
async def weather(ctx, city):  

在此代码中,您可以使用 $ 前缀和斜杠命令。

© www.soinside.com 2019 - 2024. All rights reserved.