大家好。python 3.8 出现错误。有这样一个机器人代码可以显示不和谐的天气
import discord
import requests,json
from discord.ext import commands
bot = commands.Bot(command_prefix='>')
class MyClient(discord.Client):
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
@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
运行输入!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 88, in on_message
@client.command()
AttributeError: 'MyClient' object has no attribute 'command'
请告诉我如何解决这个问题
您声明
commands.Bot()但不在主类中使用它。您的主要课程使用discord.Client().该错误实际上表明客户端对象没有命令属性。
添加:
如果您是初学者,我认为如何工作对您来说并不重要 - 是否通过课程。
目前,您具有以下代码结构:
你可以做同样的事情,只是没有类:
关于您的代码,简而言之 - 有两种类型的机器人
discord.Client()- 客户端,机器人,不能执行命令(@client.command())commands.Bot(command_prefix='>')- 团队机器人您在代码中为命令声明了一个机器人:
bot = commands.Bot(command_prefix='>'),但不要使用它,因为您的主代码在类class MyClient(discord.Client)中,其对象(在括号中)是discord.Client(),不能执行命令。一般来说,在您的情况下,有两种选择:
去掉类,即把上面的代码带成下面的格式,和bot一起做命令。
继续使用类,但在括号中指定命令的bot对象,即
class MyClient(commands.Bot):调用时,指定前缀:client = MyClient(command_prefix='>')