# Add Persistent Sessions to a grammY Telegram Bot With Redis

Yes. An agent swaps a grammY bot's in-memory session store for Redis, so session data survives a restart, tests it against a real Redis, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-persistent-sessions/grammy/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts by finding what the session holds, because that is what users lose today. In a bot like bot-base/telegram-bot-template, `src/bot/index.ts` passes `storage: new MemorySessionStorage()` to the session middleware and keys it by `ctx.chat?.id`. `SessionData` in `src/bot/context.ts` is an empty interface, which makes the session look unused, but `src/bot/i18n.ts` sets `useSession: true`, so the i18n plugin keeps each chat's chosen language there under `__language_code`. The effect is easy to show: pick a second language through the `/language` keyboard and `/start` answers in it; build a new bot instance, which is what a restart or a deploy does, and the same chat is greeted in the default language again.

The change is to make the storage a dependency and supply a durable one. The agent adds `@grammyjs/storage-redis` and `ioredis`, and an optional `redisUrl` to `baseConfigSchema` in `src/config.ts`, which already turns environment names like `REDIS_URL` into camel case before validating them with valibot. `createBot` takes its storage through the `Dependencies` object next to `config` and `logger`, so `src/main.ts` decides: with `REDIS_URL` set it constructs a client and a `RedisAdapter` with that `instance`, without it the bot keeps `MemorySessionStorage` and logs once that sessions will not survive a restart. Both `startPolling` and `startWebhook` get the same wiring, and their `onShutdown` handlers also close the Redis connection.

Three details come from reading the adapter and not assuming. It stores each session as JSON under the session key as given, so the agent sets the session middleware's `prefix` option to keep a bot's keys apart from anything else in the same Redis, where a bare chat id would collide. Keys have no expiry unless the adapter is given `ttl` in seconds; the agent leaves expiry off, since a language choice should not lapse, and says how to turn it on. And the data is now shared between processes, which the in-memory store never was: `sequentialize(getSessionKey)` is applied only in polling mode, so in webhook mode two updates from one chat can read and write the same session concurrently. The agent does not change that behaviour here, and the pull request names it as the thing to settle before running more than one webhook instance.

Testing needs a Redis, and the sandbox has no Docker, so the agent installs `redis-server` from the system packages and starts it. The repository has no test runner; its ESLint config points to Vitest, so the agent adds it with the alias and environment the `#root/*` imports and `src/config.ts` need. The tests drive the real bot with fake updates and a transformer that swallows outgoing API calls: choose a language on one bot instance, create a second instance on the same Redis, send `/start`, and expect the reply in the chosen language. A twin test with memory storage shows the reply reverting, which is the bug. Another reads the key from Redis directly to pin the prefix and the stored shape. It runs the tests, `npm run lint` and `npm run typecheck`, adds `REDIS_URL` to `.env.example` and the README's variable table, and gives the CI workflow a `redis` service for the new step.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Make session data in this grammY Telegram bot survive restarts by storing it in Redis. Read package.json, src/config.ts, src/main.ts, src/bot/index.ts, src/bot/context.ts, src/bot/middlewares/session.ts, src/bot/i18n.ts, src/bot/features/language.ts, .env.example, the environment variable table in README.md, eslint.config.js and .github/workflows/main.yml first, and say what is stored in the session today. Add @grammyjs/storage-redis and ioredis. Add an optional REDIS_URL to the valibot config schema. Pass the session storage into createBot through its dependencies; in src/main.ts use a RedisAdapter when REDIS_URL is set and MemorySessionStorage otherwise, logging which one is in use, for both polling and webhook start-up, and close the Redis connection in the existing shutdown handlers. Read the adapter's source for how it names keys and whether they expire; set a key prefix on the session middleware and leave expiry off. Do not change when sequentialize is applied, but explain in the pull request what concurrent updates in webhook mode mean for a shared store. There is no Docker here: install redis-server from the system packages and start it. Add the test runner the ESLint config expects and tests that use the real bot with fake updates and no Telegram access: a language chosen on one bot instance is still used by a second instance on the same Redis, and is lost with memory storage; the stored key has the prefix. Run the tests, npm run lint and npm run typecheck, document REDIS_URL, add a redis service to the workflow, and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request with the two new dependencies and the lockfile, the config field, the storage passed through `createBot`, the wiring and shutdown changes in `src/main.ts`, the Vitest setup and tests, and the documentation lines. The description opens with what was in the session before the change and the two test results side by side: the reply after a simulated restart with memory storage, and with Redis. It shows the key and value as read from Redis in the sandbox, names the adapter and client versions installed, and has a short section on webhook concurrency.

A reviewer checks the fallback first. With no `REDIS_URL` the bot must behave exactly as before, so that local development and the template's existing deployments keep working, and the log line should make the choice obvious. They look at the prefix, since changing it later orphans every stored session. They read the shutdown path to see that the connection closes after the runner or server has stopped and not before, so that an update still in flight can save its session.

## Run it on every Linear issue labelled bot

Persistence is a one-time change, but it is usually the first of several a growing bot needs, and they can share a trigger. In the console, add an automation on the Project that holds the bot with a `linear` trigger on `linear.issue.labeled` and the label `bot`, and a saved prompt that tells the agent to implement the issue with tests that use the fake-update helper and to keep `npm run lint` and `npm run typecheck` passing. When a person in your Rush org labels an issue such as "bot forgets my language after every deploy", the issue is added after the prompt and the run opens a pull request. The runner of the automation needs a Linear connection, made in the console under Settings → Connections.

## Why run it on Rush?

The claim in this pull request is about a restart, which is awkward to test by hand: start the bot, talk to it from a phone, stop it, start it, talk again. In a sandbox the agent can do the equivalent in a test, two bot instances over one Redis that it installed for the run, with no Telegram account involved. The run keeps the commands and their output, so the before and after replies in the description are what the tests printed.

It also checks the storage itself and not just the bot's behaviour. The agent reads the key back with the Redis client, so the prefix and the stored shape are observed facts, and it reads the adapter's source for expiry instead of guessing. Those are the two things that are painful to change once real sessions exist, and they come back verified before anything is deployed.

## Frequently asked questions

### Why Redis and not a file or a database?

grammY has storage adapters for several backends and the middleware does not care which one it is given. Redis suits a bot that may run more than one process or be redeployed often. For a single small bot, the file adapter needs no extra service.

### Do stored sessions ever expire?

Not by default. The Redis adapter writes keys without an expiry unless it is constructed with `ttl`, a number of seconds. The pull request leaves it off because the only data today is a preference, and the description shows the one-line change for a bot that should forget inactive chats.

### Is it safe to run several bot instances on one Redis?

For reads, yes; for concurrent writes to the same chat's session, not without care. The session middleware reads at the start of an update and writes at the end, so two updates handled at once can overwrite each other. Polling mode in this template already processes each chat's updates in order; webhook mode does not, and the pull request flags it.

## More grammY jobs

- [Add Rate Limiting to a grammY Telegram Bot](https://getrush.ai/run/add-rate-limiting/grammy/)
- [Migrate a grammY Bot From Long Polling to Webhooks](https://getrush.ai/run/migrate-polling-to-webhooks/grammy/)
- [Write Unit Tests for a grammY Telegram Bot](https://getrush.ai/run/write-unit-tests/grammy/)

## More jobs like this: Turn a Linear label into a PR

- [Add Persistent User Settings to an Electron App from a Linear Issue](https://getrush.ai/run/add-persistent-settings/electron/)
- [Persist User Settings in a Textual App](https://getrush.ai/run/add-persistent-settings/textual/)
- [Add PHPStan Static Analysis to a PHP Library](https://getrush.ai/run/add-phpstan/php/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
