§Classes

  • Api

    This class provides access to the full Telegram Bot API. All methods of the API have an equivalent on this class, with the most important parameters pulled up into the function signature, and the other parameters captured by an object.

    In addition, this class has a property raw that provides raw access to the complete Telegram API, with the method signatures 1:1 represented as documented on the website (https://core.telegram.org/bots/api).

    Every method takes an optional AbortSignal object that allows you to cancel the request if desired.

    In advanced use cases, this class allows to install transformers that can modify the method and payload on the fly before sending it to the Telegram servers. Confer the config property for this.

  • Bot

    This is the single most important class of grammY. It represents your bot.

    First, you must create a bot by talking to @BotFather, check out https://t.me/BotFather. Once it is ready, you obtain a secret token for your bot. grammY will use that token to identify as your bot when talking to the Telegram servers. Got the token? You are now ready to write some code and run your bot!

    You should do three things to run your bot:

    // 1. Create a bot instance
    const bot = new Bot('<secret-token>')
    // 2. Listen for updates
    bot.on('message:text', ctx => ctx.reply('You wrote: ' + ctx.message.text))
    // 3. Launch it!
    bot.start()
    
  • BotError

    This error is thrown when middleware throws. It simply wraps the original error (accessible via the error property), but also provides access to the respective context object that was processed while the error occurred.

  • Composer

    The composer is the heart of the middleware system in grammY. It is also the superclass of Bot. Whenever you call use or on or some of the other methods on your bot, you are in fact using the underlying composer instance to register your middleware.

    If you're just getting started, you do not need to worry about what middleware is, or about how to use a composer.

    On the other hand, if you want to dig deeper into how grammY implements middleware, check out the documentation on the website.

  • Context

    When your bot receives a message, Telegram sends an update object to your bot. The update contains information about the chat, the user, and of course the message itself. There a numerous other updates, too: https://core.telegram.org/bots/api#update

    When grammY receives an update, it wraps this update into a context object for you. Context objects are commonly named ctx. A context object does two things:

    1. ctx.update holds the update object that you can use to process the message. This includes providing useful shortcuts for the update, for instance, ctx.msg is a shortcut that gives you the message object from the update—no matter whether it is contained in ctx.update.message, or ctx.update.edited_message, or ctx.update.channel_post, or ctx.update.edited_channel_post.
    2. ctx.api gives you access to the full Telegram Bot API so that you can directly call any method, such as responding via ctx.api.sendMessage. Also here, the context objects has some useful shortcuts for you. For instance, if you want to send a message to the same chat that a message comes from (i.e. just respond to a user) you can call ctx.reply. This is nothing but a wrapper for ctx.api.sendMessage with the right chat_id pre-filled for you. Almost all methods of the Telegram Bot API have their own shortcut directly on the context object, so you probably never really have to use ctx.api at all.

    This context object is then passed to all of the listeners (called middleware) that you register on your bot. Because this is so useful, the context object is often used to hold more information. One example are sessions (a chat-specific data storage that is stored in a database), and another example is ctx.match that is used by bot.command and other methods to keep information about how a regular expression was matched.

    Read up about middleware on the website if you want to know more about the powerful opportunities that lie in context objects, and about how grammY implements them.

  • GrammyError

    This class represents errors that are thrown by grammY because the Telegram Bot API responded with an error.

    Instances of this class hold the information that the Telegram backend returned.

    If this error is thrown, grammY could successfully communicate with the Telegram Bot API servers, however, an error code was returned for the respective method call.

  • HttpError

    This class represents errors that are thrown by grammY because an HTTP call to the Telegram Bot API failed.

    Instances of this class hold the error object that was created because the fetch call failed. It can be inspected to determine why exactly the network request failed.

    If an API transformer function throws an error, grammY will regard this as if the network request failed. The contained error will then be the error that was thrown by the transformer function.

  • InlineKeyboard

    Use this class to simplify building an inline keyboard (something like this: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating).

    // Build an inline keyboard:
    const keyboard = new InlineKeyboard()
      .text('A').text('B', 'callack-data').row()
      .text('C').text('D').row()
      .url('Telegram', 'telegram.org')
    
    // Send the keyboard:
    ctx.reply('Here is your inline keyboard!', {
      reply_markup: keyboard
    })
    

    Be sure to to check the documentation on inline keyboards in grammY.

  • InputFile

    An InputFile wraps a number of different sources for sending files.

    It corresponds to the InputFile type in the Telegram Bot API Reference.

  • Keyboard

    Use this class to simplify building a custom keyboard (something like this: https://core.telegram.org/bots#keyboards).

    // Build a custom keyboard:
    const keyboard = new Keyboard()
      .text('A').text('B').row()
      .text('C').text('D')
    
    // Now you can either pass it directly:
    ctx.reply('Here is your custom keyboard!', {
      reply_markup: keyboard
    })
    // Or if you need to specify more options in `reply_markup`:
    ctx.reply('Here is your custom keyboard!', {
      reply_markup: {
        keyboard: keyboard.build(), // note the `build` call
        one_time_keyboard: true,
      }
    })
    

    Be sure to check out the documentation on custom keyboards in grammY.

  • MemorySessionStorage

    The memory session storage is a built-in storage adapter that saves your session data in RAM using a regular JavaScript Map object. If you use this storage adapter, all sessions will be lost when your process terminates or restarts. Hence, you should only use it for short-lived data that is not important to persist.

    This class is used as default if you do not provide a storage adapter, e.g. to your database.

    This storage adapter features expiring sessions. When instatiating this class yourself, you can pass a time to live in milliseconds that will be used for each session object. If a session for a user expired, the session data will be discarded on its first read, and a fresh session object as returned by the inital option (or undefined) will be put into place.

§Functions

  • lazySession

    This is an advanced function of grammY.

    Generally speaking, lazy sessions work just like normal sessions—just they are loaded on demand. Except for a few asyncs and awaits here and there, their usage looks 100 % identical.

    Instead of directly querying the storage every time an update arrives, lazy sessions quickly do this once you access ctx.session. This can significantly reduce the database traffic (especially when your bot is added to group chats), because it skips a read and a wrote operation for all updates that the bot does not react to.

    // The options are identical
    bot.use(lazySession({ storage: ... }))
    
    bot.on('message', async ctx => {
      // The session object is persisted across updates!
      const session = await ctx.session
      //                        ^
      //                        |
      //                       This plain property access (no function call) will trigger the database query!
    })
    

    Check out the documentation on the website to know more about how lazy sessions work in grammY.

  • matchFilter

    This is an advanced function of grammY.

    Takes a filter query and turns it into a predicate function that can check in constant time whether a given context object satisfies the query. The created predicate can be passed to bot.filter and will narrow down the context accordingly.

    This function is used internally by bot.on but exposed for advanced usage like the following.

    // Listens for updates except forwards of messages or channel posts
    bot.drop(matchFilter(':forward_date'), ctx => { ... })
    

    Check out the documentation of bot.on for examples. In addition, the website contains more information about how filter queries work in grammY.

  • session

    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 ID 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 inital 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.

  • webhookCallback

    Creates a callback function that you can pass to a web framework (such as express) if you want to run your bot via webhooks. Use it like this:

    const app = express() // or whatever you're using
    const bot = new Bot('<token>')
    
    app.use(webhookCallback(bot, 'express'))
    

    Confer the grammY documentation to read more about how to run your bot with webhooks.

§Interfaces

  • ApiClientOptions

    Options to pass to the API client that eventually connects to the Telegram Bot API server and makes the HTTP requests.

  • BotConfig

    Options to pass the bot when creating it.

  • LazySessionFlavor

    A lazy session flavor is a context flavor that holds a promise of some session data under ctx.session.

    Lazy session middleware will provide this promise lazily on the context object. Once you access ctx.session, the storage will be queried and the session data becomes available. If you access ctx.session again for the same context object, the cached value will be used. Check out the documentation on lazy session middleware to know more, and read the section about lazy sessions on the website.

  • MiddlewareObj

    Middleware in the form of a container for a function.

  • PollingOptions

    Options that can be specified when running the bot via simple long polling.

  • SessionFlavor

    A session flavor is a context flavor that holds session data under ctx.session.

    Session middleware will load the session data of a specific chat from your storage solution, and make it available to you on the context object. Check out the documentation on session middleware to know more, and read the section about sessions on the website.

  • SessionOptions

    Options for session middleware.

  • StorageAdapter

    A storage adapter is an abstraction that provides read, write, and delete access to a storage solution of any kind. Storage adapters are used to keep session middleware independent of your database provider, and they allow you to pass your own storage solution.

  • TransformableApi

    A transformable API enhances the RawApi type by transformers.

  • WebhookReplyEnvelope

    Small utility interface that abstracts from webhook reply calls of different web frameworks.

§Type Aliases

  • ApiCallFn

    Type of a function that can perform an API call. Used for Transformers.

  • ErrorHandler

    Error handler that can be installed on a bot to catch error thrown by middleware.

  • Filter

    This type infers which properties will be present on the given context object provided it matches the given filter query. If the filter query is a union type, the produced context object will be a union of possible combinations, hence allowing you to narrow down manually which of the properties are present.

    In some sense, this type computes matchFilter on the type level.

  • FilterQuery

    Represents a filter query that can be passed to bot.on. There are three different kinds of filter queries: Level 1, Level 2, and Level 3. Check out the website to read about how filter queries work in grammY, and how to use them.

    Here are three brief examples:

    // Listen for messages of any type (Level 1)
    bot.on('message', ctx => { ... })
    // Listen for audio messages only (Level 2)
    bot.on('message:audio', ctx => { ... })
    // Listen for text messages that have a URL entity (Level 3)
    bot.on('message:entities:url', ctx => { ... })
    
  • FrameworkAdapter

    Middleware for a web framework. Creates a request-response handler for a request. The handler will be used to integrate with the compatible framework.

  • Middleware

    Middleware for grammY, either as a function or as a container for a function.

    Simply put, middleware is just a fancy term for a listener. You can register middleware on a bot to listen for updates. Example:

    bot.on('message', ctx => ctx.reply('I got your message!'))
    //                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //                ^
    //                |
    //               This is middleware!
    

    Middleware receives one object that we call the context object. This is another fancy term for a simple object that holds information about the update you're processing. For instance, the context object gives you access to the message that was sent to your bot (ctx.message), including the text (or photo or whatever message the user has sent). The context object is commonly named ctx.

    It also provides you with the ctx.api object that you also find on bot.api. As a result, you can call ctx.api.sendMessage instead of bot.api.sendMessage. This prevents you from having to pass around your bot instance all over your code.

    Most importantly, the context object gives you a handful of really useful shortcuts, such as a reply method (see above). This method is nothing else than a wrapper around ctx.api.sendMessage—but with some arguments pre-filled for you. As you can see above, you no longer have to specify a chat_id or anything; the context object knows which chat it belongs to, so when you call reply, the context will call sendMessage with the correct chat_id, namely the one for the same chat that the incoming message originates from. This makes it very convenient to reply to a message.

    Middleware is an extremely powerful concept and this short explanation only scratched the surface of what is possible with grammY. If you want to know more advanced things about middleware, check out the documentation on the website.

  • MiddlewareFn

    Middleware in the form of a function.

  • NextFunction

    A function of this type is passed as the second parameter to all middleware. Invoke it to call the downstream middleware and pass on the control flow.

    In other words, if your middleware is done handling the context object, and other middleware should take over, this function should be called and awaited.

    Once the Promise returned by this function resolves, the downstream middleware is done executing, hence returning the control.

  • RawApi

    Represents the raw Telegram Bot API with all methods specified 1:1 as documented on the website (https://core.telegram.org/bots/api).

    Every method takes an optional AbortSignal object that allows to cancel the API call if desired.

  • Transformer

    API call transformers are functions that can access and modify the method and payload of an API call on the fly. This can be useful if you want to implement rate limiting or other things against the Telegram Bot API.

    Confer the grammY documentation to read more about how to use transformers.