If you want a better, more persistent, and scalable way to track the last message the bot sent to each user/chat without just using an in-memory variable like a dictionary (last_message_ids), here are some improved approaches:
1. Use a Lightweight Local Database (SQLite)
Store last sent message IDs per chat in a SQLite database. This way, the data persists even if the bot restarts or crashes.
Example:
import sqlite3
from telegram import Update
from telegram.ext import Updater, MessageHandler, Filters, CallbackContext
# Initialize (or open) SQLite DB and create table if not exists
conn = sqlite3.connect('bot_data.db', check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS last_messages (
chat_id INTEGER PRIMARY KEY,
message_id INTEGER
)
''')
conn.commit()
def get_last_message_id(chat_id: int):
cursor.execute('SELECT message_id FROM last_messages WHERE chat_id=?', (chat_id,))
row = cursor.fetchone()
return row[0] if row else None
def set_last_message_id(chat_id: int, message_id: int):
cursor.execute('''
INSERT INTO last_messages(chat_id, message_id) VALUES (?, ?)
ON CONFLICT(chat_id) DO UPDATE SET message_id=excluded.message_id
''', (chat_id, message_id))
conn.commit()
def on_user_message(update: Update, context: CallbackContext):
chat_id = update.effective_chat.id
last_msg_id = get_last_message_id(chat_id)
if last_msg_id:
# try to edit last bot message to "loading..."
try:
context.bot.edit_message_text(
chat_id=chat_id,
message_id=last_msg_id,
text="loading..."
)
except Exception as e:
print(f"Failed to edit last message: {e}")
# send new message with user input (simulate processing)
new_msg = update.message.reply_text(f"Received: {update.message.text}")
# store new message_id
set_last_message_id(chat_id, new_msg.message_id)
def main():
updater = Updater("YOUR_TELEGRAM_BOT_TOKEN", use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, on_user_message))
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
2. Use Redis or Other Key-Value Store (for distributed bots)
If your bot is deployed on several servers or you want faster access, Redis is a good choice to store chat_id ➡ message_id mapping.
import redis
from telegram import Update
from telegram.ext import Updater, MessageHandler, Filters, CallbackContext
r = redis.Redis(host='localhost', port=6379, db=0)
def on_user_message(update: Update, context: CallbackContext):
chat_id = update.effective_chat.id
last_msg_id = r.get(f"last_msg:{chat_id}")
if last_msg_id:
try:
context.bot.edit_message_text(
chat_id=chat_id,
message_id=int(last_msg_id),
text="loading..."
)
except Exception as e:
print(f"Failed to edit last message: {e}")
new_msg = update.message.reply_text(f"Received: {update.message.text}")
r.set(f"last_msg:{chat_id}", new_msg.message_id)
def main():
updater = Updater("YOUR_TELEGRAM_BOT_TOKEN", use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, on_user_message))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
3. Use Context User Data (context.user_data)
python-telegram-bot has built-in persistence with user_data and chat_data. You can use context.chat_data to store per-chat info that is kept during the bot's runtime (and optionally persistent if you configure Pickle persistence).
from telegram import Update
from telegram.ext import Updater, MessageHandler, Filters, CallbackContext, PicklePersistence
def on_user_message(update: Update, context: CallbackContext):
chat_data = context.chat_data
chat_id = update.effective_chat.id
last_msg_id = chat_data.get('last_message_id', None)
if last_msg_id:
try:
context.bot.edit_message_text(
chat_id=chat_id,
message_id=last_msg_id,
text="loading..."
)
except Exception as e:
print(f"Failed to edit message: {e}")
new_msg = update.message.reply_text(f"Received: {update.message.text}")
chat_data['last_message_id'] = new_msg.message_id
def main():
persistence = PicklePersistence(filename='bot_data_persistence')
updater = Updater("YOUR_TELEGRAM_BOT_TOKEN", persistence=persistence, use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, on_user_message))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
- This way, message IDs are saved automatically inside a local file and survive bot restarts.
- You don't have to manage DB or external services.
Summary
| Method | Persistence | Complexity | Good for |
|---|
| In-memory dict (your original) | No | Very simple | Small bot, single running session |
| SQLite database | Yes | Moderate | Lightweight persistence, simple deployment |
| Redis (or other KV store) | Yes + distributed | Moderate | Distributed environment/bot cluster |
context.chat_data + Pickle Persistence | Yes (local) | Simple with framework | Simple persistence without setting up DB |
If you want, I can help you build a full example with any of these based on your hosting and complexity needs!