How to Store Telegram Bot User Data Safely
Bots may work in PM, in groups, and in channels—depending on their purpose. These kinds of chats work by different rules, so the book has separate pages for each chat type.
However, your bot will always interact with users in one way or another. Use this page to decide what user data is safe to store and which fields can change.
Store users by ID
Users may have no username or no last name—keep this in mind while storing their profile info. In groups, this means the bot can't always mention a user by username (see mentions by ID).
In addition, first name, username, and other profile data except for user ID can change over time, so ID is probably the only reliable way to identify a user. User IDs will be explained in more detail later in the book.
A correct way to get a user's display name would be:
if user.last_name is None:
full_name = user.first_name
else:
full_name = f'{user.first_name} {user.last_name}'Cache language when Telegram provides it
Use the user's language setting when Telegram includes it in an update. This allows your bot to communicate in users' native languages.
However, the user's language is not always included in all updates. If your bot supports multiple languages, Telegram recommends using the last known language preference when this information is missing from an update.
user.lang_code # Sometimes is NoneDon't act on unknown users
Before mentioning a user by ID or performing similar user-related actions, make sure the bot has seen that user. The bot sees a user when, for example, it receives a message from the user or retrieves their information by username.
“Seeing” users is not an official term, but rather a conceptual explanation of how Telegram's API works. In technical terms, API requests must include not only the user ID but also a corresponding access hash. The API provides these access hashes along with other user information in updates. Both Bot API and well-designed Telegram API libraries handle access hash caching automatically, so you typically don't need to manage them directly.
