What's the optimal method for tracking the most recent command in a Telegram chatbot?

I’m working on a Telegram chatbot and I’m trying to figure out the best way to keep track of user commands. Here’s what I’m dealing with:

  • The bot uses webhooks for updates
  • It’s written in C# but I’m open to ideas in other languages too

Here’s the user flow I’m working with:

  1. User sends /SendPic some_info
  2. User sends a picture
  3. User sends another picture
  4. User sends a third picture

I need to make sure the bot knows the pictures are related to the /SendPic command. I’ve thought about saving each command to a database or using a cache system, but I’m worried about performance.

Is there a better way to do this? Maybe something built into the Telegram API that can help keep track of the last command without needing to query a database every time?

I’m really looking to optimize this process. Any ideas would be super helpful!

yo, have u considered using a simple dictionary in memory? just store the user ID as key and last command as value. it’s quick n easy. when a new msg comes in, check the dict. if the user’s there, u know what command they’re on. just clear it out after a set time or when they start a new command. works great for me!

From my experience, a solid approach for tracking recent commands in a Telegram bot is using Redis as a key-value store. It’s incredibly fast and can handle high loads efficiently.

For your use case, you could store the user’s ID as the key and the last command as the value. When processing incoming messages, check Redis first. If there’s a matching key, you know the context.

Redis also supports automatic expiration, so you can set a TTL for each entry. This way, you don’t need to manually clean up old data.

One advantage of Redis over in-memory solutions is persistence. If your bot restarts, you don’t lose the command history. It’s also easily scalable if you need to handle more users in the future.

Just remember to handle cases where the Redis connection might fail, perhaps falling back to a default behavior.

I’ve actually dealt with a similar issue in my Telegram bot project. What worked well for me was using an in-memory cache system, specifically MemoryCache in C#. It’s lightweight and fast, perfect for short-term data like recent commands.

When a user sends a command, I store it in the cache with the user’s ID as the key and set an expiration time (about 5 minutes) for each cache entry. For subsequent messages, I check the cache to see if there’s a recent command related to that user. This approach avoids the overhead of querying a database and scales nicely, as the expiration time automatically cleans up outdated entries.

One caveat is that if the bot restarts, the cached data is lost, but for most cases, this is an acceptable trade-off given the performance gain.