if 'Next' in message:
if counter.value == 0:
keyboard = create_keyboard('Next')
send_message(read_line('file.txt', 1))
counter.increment()
elif counter.value == 1:
keyboard = create_keyboard('Continue')
send_message(read_line('file.txt', 2))
counter.increment()
The issue I’m facing is that when a different user interacts with the bot, the counter may already be above 0 because it’s shared among users. I need to ensure that for every new user, the counter resets to 0 so each person starts from the first message when they send ‘Next’. Any suggestions on how to handle this?
To reset variables for each new user in your Telegram bot, you should use a dictionary to store user-specific data. Here’s how you can modify your approach:
Create a dictionary to store counters for each user, using their user ID as the key. When a user interacts with the bot, check if they have an entry in the dictionary. If not, create a new Counter instance for them.
Here’s a basic implementation:
user_counters = {}
def handle_message(update, context):
user_id = update.effective_user.id
if user_id not in user_counters:
user_counters[user_id] = Counter(0)
counter = user_counters[user_id]
# Your existing logic here, using the user-specific counter
This ensures each user starts fresh, regardless of other users’ interactions. Remember to handle potential memory issues if your bot serves a large number of users.
I’ve dealt with a similar issue in my Telegram bot projects. The key is to use a dictionary to store user-specific data. Here’s what worked for me:
Create a dictionary where the key is the user’s ID and the value is their individual Counter object. When a user interacts with the bot, check if they have an entry in the dictionary. If not, create a new Counter for them.
Something like this:
user_counters = {}
def handle_message(update, context):
user_id = update.effective_user.id
if user_id not in user_counters:
user_counters[user_id] = Counter(0)
counter = user_counters[user_id]
# Your existing logic here
This approach ensures each user starts fresh, regardless of others’ interactions. It’s simple and effective, but keep an eye on memory usage if your bot serves many users.