A_normal_guy
A_normal_guy

Reputation: 45

Trouble with Slash Command Previews in Discord Bot Development

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):

Screenshot

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")

Upvotes: 0

Views: 323

Answers (1)

No767
No767

Reputation: 16

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.

  1. Discord.py natively supports all application commands (aka slash commands). This guide should be able to help with it.

  2. 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.

  3. 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

Upvotes: 0

Related Questions