英文:
Trouble with Slash Command Previews in Discord Bot Development
问题
我刚刚开始使用Python编写Discord机器人,并且已经成功运行了我的机器人。然而,我遇到了一个关于斜杠命令预览的问题,我无法解决。机器人的功能是正常的,但是斜杠命令预览不按预期工作。我正在寻求关于如何解决这个问题的指导。
我附上了我面临问题的截图(我无法看到我的机器人命令):
是否有特定的操作需要不同地进行,以启用斜杠命令预览?我尝试在网上搜索解决方案,但是找不到相关的信息。由于我对Discord机器人开发相对较新,我不确定是否漏掉了关键步骤或需要掌握的概念。
注意:我对Python编程有高级理解,但对编写Discord机器人是新手。
更新的代码:
from typing import Optional
import os
import discord
from discord import app_commands
import requests
import json
import aiohttp
MY_GUILD = discord.Object(id=1137767005546610708)
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
intents = discord.Intents.default()
client = MyClient(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} (ID: {client.user.id})')
@client.tree.command()
async def weather(interaction: discord.Interaction, city: str):
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + "3bc3a9a3fc36a46b41d91d45e2b00392" + "&q=" + city
response = requests.get(complete_url)
data = response.json()
if data["cod"] != "404":
location = data["name"]
temp_k = data["main"]["temp"]
temp_c = temp_k - 273.15 # Convert Kelvin to Celsius
temp_f = (temp_c * 9/5) + 32 # Convert 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"K: {temp_k:.2f} | 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 interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message(content="City not found.")
client.run("MTEzODE4OTk4MTk3OTAwNTA3MA.GD0a5K.TwuG5H-urES9x_KAKZ3wUuPOl-DLjLFzMpMKiI")
英文:
I've just started coding Discord bots using Python, and I've managed to get my bot up and running. However, I've encountered an issue with slash command previews that I can't seem to resolve. The bot functions correctly, but the slash command previews aren't working as expected. I'm looking for guidance on how to fix this issue.
I've attached a screenshot of the problem I'm facing (I am not able to see my bots commands):
Is there something specific that needs to be done differently in order to enable slash command previews? I've tried searching for solutions online, but I couldn't find any relevant information. Since I'm relatively new to Discord bot development, I'm not sure if I'm missing a crucial step or if there's a concept I need to grasp.
Note: I have an advanced understanding of Python programming, but I'm new to coding Discord bots.
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'))
Updated code:
from typing import Optional
import os
import discord
from discord import app_commands
import requests
import json
import aiohttp
MY_GUILD = discord.Object(id=1137767005546610708)
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
intents = discord.Intents.default()
client = MyClient(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} (ID: {client.user.id})')
@client.tree.command()
async def weather(interaction: discord.Interaction, city: str):
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + "3bc3a9a3fc36a46b41d91d45e2b00392" + "&q=" + city
response = requests.get(complete_url)
data = response.json()
if data["cod"] != "404":
location = data["name"]
temp_k = data["main"]["temp"]
temp_c = temp_k - 273.15 # Convert Kelvin to Celsius
temp_f = (temp_c * 9/5) + 32 # Convert 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"K: {temp_k:.2f} | 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 interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message(content="City not found.")
client.run("MTEzODE4OTk4MTk3OTAwNTA3MA.GD0a5K.TwuG5H-urES9x_KAKZ3wUuPOl-DLjLFzMpMKiI")
答案1
得分: 0
我看到的最常见的错误之一是在commands.Bot
的command_prefix
属性中使用/
前缀,以为这样会给他们提供斜杠命令。事实并非如此。这里存在许多直接和间接的问题。
-
Discord.py原生支持所有应用程序命令(也称为斜杠命令)。这个指南应该能够帮助你。
-
你间接地引起了阻塞问题。简单来说,当你执行那个命令时,它会阻塞机器人需要完成的任何工作,直到你的命令执行完毕。建议使用AIOHTTP代替。
-
不要自动同步。而是使用命令手动同步。这是一个很好的同步命令示例:https://about.abstractumbra.dev/discord.py/2023/01/29/sync-command-example.html
英文:
One of the most common mistakes I see is using the /
prefix in the command_prefix
attrs in commands.Bot
, thinking that it will give them slash commands. It doesn't work that way. There are a lot of issues both directly and indirectly that exists here.
-
Discord.py natively supports all application commands (aka slash commands). This guide should be able to help with it.
-
You are indirectly causing blocking issues. In simple terms, when you execute that command, it will block any work that the bot needs to do until your command has finished. It is recommended to use AIOHTTP instead.
-
Don't auto-sync. Instead manually sync using a command. Here's a good syncing command: https://about.abstractumbra.dev/discord.py/2023/01/29/sync-command-example.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论