Еще одна проблема с ботом для погоды на discord.py

    import discord
    import requests,json
    
    from discord.ext import commands
    bot = commands.Bot (command_prefix='!')
    class MyClient(commands.Bot):
    
        async def on_ready(self):
            print('Logged on as', self.user)
    
        async def on_message(self, message):
            # don't respond to ourselves
            if message.author == self.user:
                return
    
            if message.content.startswith('hello'):
             await message.channel.send('Hello!')
            api_key = "7f1e23163b47cbf21184f339f5c8eaf9"
            base_url = "http://api.openweathermap.org/data/2.5/weather?"
    
            @client.command()
            async def weather(ctx, *, city: str):

           city_name = city
            complete_url = base_url + "appid=" + api_key + "&q=" + city_name
            response = requests.get(complete_url)
            x = response.json()
            channel = ctx.message.channel
            if x["cod"] != "404":
                async with channel.typing():
                    y = x["main"]
                    current_temperature = y["temp"]
                    current_temperature_celsiuis = str(round(current_temperature - 273.15))
                    current_pressure = y["pressure"]
                    current_humidity = y["humidity"]
                    z = x["weather"]
                    weather_description = z[0]["description"]
                    weather_description = z[0]["description"]
                    embed = discord.Embed(title=f"Weather in {city_name}",
                                          color=ctx.guild.me.top_role.color,
                                          timestamp=ctx.message.created_at, )
                    embed.add_field(name="Descripition", value=f"**{weather_description}**", inline=False)
                    embed.add_field(name="Temperature(C)", value=f"**{current_temperature_celsiuis}°C**", inline=False)
                    embed.add_field(name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
                    embed.add_field(name="Atmospheric Pressure(hPa)", value=f"**{current_pressure}hPa**", inline=False)
                    embed.set_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
                    embed.set_footer(text=f"Requested by {ctx.author.name}")
                    await channel.send(embed=embed)








client = MyClient(command_prefix='!')
client.run('my token')

Имеется такой код и при это при вводе команды !weather New Delhi выдает следующую ошибку

Ignoring exception in on_message
Traceback (most recent call last):
  File "D:\pythonProject16\venv\lib\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "D:/pythonProject16/discord-bot.py", line 93, in on_message
    async def weather(ctx, *, city: str):
  File "D:\pythonProject16\venv\lib\site-packages\discord\ext\commands\core.py", line 1246, in decorator
    self.add_command(result)
  File "D:\pythonProject16\venv\lib\site-packages\discord\ext\commands\core.py", line 1138, in add_command
    raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command weather is already an existing command or alias

Ответы (1 шт):

Автор решения: denisnumb

Удалось решить проблему, убрав из кода класс. Также, бот не распознавал команду из-за того, что постоянно анализировал поступающие сообщения на предмет содержания "hello". Перед этим нужно было добавить строку для обработки команд, чтобы бот сначала проверял, является ли сообщение командой: await bot.process_commands(message)

Не забудьте подставить свой токен в конце!

Теперь код работает :)

import discord
import requests,json
from discord.ext import commands

bot = commands.Bot (command_prefix='!')

@bot.event
async def on_ready():
    print('Logged on as', bot.user)

@bot.event  
async def on_message(message):
    # don't respond to ourselves

    if message.author == bot.user:
        return
    
    await bot.process_commands(message)

    if message.content.startswith('hello'):
        await message.channel.send('Hello!')
    
@bot.command()
async def weather(ctx, *, city: str):

    api_key = "7f1e23163b47cbf21184f339f5c8eaf9"
    base_url = "http://api.openweathermap.org/data/2.5/weather?"
        
    city_name = city
    complete_url = base_url + "appid=" + api_key + "&q=" + city_name
    response = requests.get(complete_url)
    x = response.json()

    if x["cod"] != "404":
        async with ctx.typing():
            y = x["main"]
            current_temperature = y["temp"]
            current_temperature_celsiuis = str(round(current_temperature - 273.15))
            current_pressure = y["pressure"]
            current_humidity = y["humidity"]
            z = x["weather"]
            weather_description = z[0]["description"]
            weather_description = z[0]["description"]
            embed = discord.Embed(title=f"Weather in {city_name}",
                                    color=ctx.guild.me.top_role.color,
                                    timestamp=ctx.message.created_at, )
            embed.add_field(name="Descripition", value=f"**{weather_description}**", inline=False)
            embed.add_field(name="Temperature(C)", value=f"**{current_temperature_celsiuis}°C**", inline=False)
            embed.add_field(name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
            embed.add_field(name="Atmospheric Pressure(hPa)", value=f"**{current_pressure}hPa**", inline=False)
            embed.set_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
            embed.set_footer(text=f"Requested by {ctx.author.name}")
            await ctx.send(embed=embed)

    else:
        print('error')


bot.run('token')
→ Ссылка