Python Telegram新冠追踪机器人报错:'NoneType' object is not subscriptable
Let’s break down the root of your error first: the TypeError: 'NoneType' object is not subscriptable means the data variable in your stats function is returning None. This happens because covid.getByCountryCode('UA') isn’t pulling the expected dictionary of data—either the underlying API changed, the country code is no longer valid, there’s a temporary network issue, or the covid19 library you’re using has been updated in a breaking way.
Step 1: Add a Guard Clause for None Values
First, modify your stats function to handle cases where the API returns no data before trying to access its keys. This will stop the error and keep your bot running smoothly:
def stats(update, context): data = covid.getByCountryCode('UA') # Check if data is missing or empty if not data: update.message.reply_html( '<b>Oops!</b> Could not load COVID data for Ukraine right now. Please try again later.', reply_markup=buttons) return # Proceed with the normal message if data exists update.message.reply_html( ' <b>In Ukraine</b>\n \n<b>Infected:</b> {}\n<b>Recovered:</b> {}\n<b>Dead:</b> {}'. format( data['confirmed'], data['recovered'], data['deaths']), reply_markup=buttons)
Step 2: Verify API and Country Code Compatibility
Since this worked before, it’s likely a change with the covid19 library or its backend API:
- Test
covid.getByCountryCode('UA')in a standalone Python script to see what it actually returns. If it’s consistentlyNone, the API endpoint might be deprecated or require new authentication. - Double-check that 'UA' is still the valid ISO 3166-1 alpha-2 code for Ukraine (it should be, but some APIs switch to full country names or alpha-3 codes). Try
covid.getByCountry('Ukraine')if the library supports that method. - If the
covid19library is unmaintained, consider switching to a more reliable alternative (like using the official Johns Hopkins COVID dataset viapandas, or another active API wrapper).
Step 3: Add Robust Error Handling
To make your bot more resilient, wrap the API call in a try-except block to catch network errors or unexpected responses:
def stats(update, context): try: data = covid.getByCountryCode('UA') if not data: raise ValueError("No data available for Ukraine at this time") update.message.reply_html( ' <b>In Ukraine</b>\n \n<b>Infected:</b> {}\n<b>Recovered:</b> {}\n<b>Dead:</b> {}'. format( data['confirmed'], data['recovered'], data['deaths']), reply_markup=buttons) except Exception as e: update.message.reply_html( f'<b>Error!</b> Failed to load data: {str(e)}', reply_markup=buttons)
This way, even if the API times out or returns an unexpected format, your bot won’t crash—it’ll just inform the user of the issue.
内容的提问来源于stack exchange,提问作者Robert Makeev

