import { session } from "https://deno.land/x/grammy_menu@v1.3.0/deps.deno.ts";
Session middleware provides a persistent data storage for your bot. You can
use it to let your bot remember any data you want, for example the messages
it sent or received in the past. This is done by attaching session data to
every chat. The stored data is then provided on the context object under
ctx.session
.
What is a session? Simply put, the session of a chat is a little persistent storage that is attached to it. As an example, your bot can send a message to a chat and store the identifier of that message in the corresponding session. The next time your bot receives an update from that chat, the session will still contain that ID.
Session data can be stored in a database, in a file, or simply in memory. grammY only supports memory sessions out of the box, but you can use third-party session middleware to connect to other storage solutions. Note that memory sessions will be lost when you stop your bot and the process exits, so they are usually not useful in production.
Whenever your bot receives an update, the first thing the session middleware
will do is to load the correct session from your storage solution. This
object is then provided on ctx.session
while your other middleware is
running. As soon as your bot is done handling the update, the middleware
takes over again and writes back the session object to your storage. This
allows you to modify the session object arbitrarily in your middleware, and
to stop worrying about the database.
bot.use(session())
bot.on('message', ctx => {
// The session object is persisted across updates!
const session = ctx.session
})
It is recommended to make use of the initial
option in the configuration
object, which correctly initializes session objects for new chats.
You can delete the session data by setting ctx.session
to null
or
undefined
.
Check out the documentation on the website to know more about how sessions work in grammY.
Type Parameters
Parameters
Optional configuration to pass to the session middleware