Telegram天气Bot输出多变量报错:list indices must be integers or slices, not str
问题修复方案
错误根源在于weather字段的取值方式。OpenWeatherMap的API返回数据里,weather是一个包含天气信息的列表(数组),不是单个字典,所以不能直接用字符串作为索引去访问main字段。
修改后的代码
import telebot import requests import json bot = telebot.TeleBot('...') api = '...' @bot.message_handler(commands=['start']) def start(message): bot.send_message(message.chat.id, 'Tell me the city name') @bot.message_handler(content_types=['text']) def get_weather(message): city = message.text.strip().lower() res = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api}&units=metric') if res.status_code == 200: data = json.loads(res.text) temp = data["main"]["temp"] # 核心修改:weather是列表,先取第一个元素再访问main字段 conditions = data["weather"][0]["main"] bot.reply_to(message, f'🌡️Current temperature is: {temp}\n Current weather is: {conditions}') else: bot.reply_to(message, 'City not found') bot.polling(none_stop=True)
关键说明
- 原代码里
data["weather"]["main"]触发报错,因为data["weather"]返回的是列表,必须用整数索引(比如[0])取出列表中的具体字典元素,之后才能访问该字典里的main字段。 - OpenWeatherMap的
weather列表通常仅包含一个元素,取索引0就能获取当前的天气状况。
内容的提问来源于stack exchange,提问作者hihoznik
相关产品推荐
相关产品推荐

