Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/grammy/composer.ts>Composer#command

The Telegram Bot Framework.
Very Popular
Go to Latest
method Composer.prototype.command
import { Composer } from "https://deno.land/x/grammy@v1.12.4/composer.ts";

Registers some middleware that will only be executed when a certain command is found.

// Reacts to /start commands
bot.command('start', ctx => { ... })
// Reacts to /help commands
bot.command('help', ctx => { ... })

The rest of the message (excluding the command, and trimmed) is provided via ctx.match.

Did you know? You can use deep linking (https://core.telegram.org/bots#deep-linking) to let users start your bot with a custom payload. As an example, send someone the link https://t.me/name-of-your-bot?start=custom-payload and register a start command handler on your bot with grammY. As soon as the user starts your bot, you will receive custom-payload in the ctx.match property!

bot.command('start', ctx => {
  const payload = ctx.match // will be 'custom-payload'
})

Note that commands are not matched in captions or in the middle of the text.

bot.command('start', ctx => { ... })
// ... does not match:
// A message saying: “some text /start some more text”
// A photo message with the caption “/start”

By default, commands are detected in channel posts, too. This means that ctx.message is potentially undefined, so you should use ctx.msg instead to grab both messages and channel posts. Alternatively, if you want to limit your bot to finding commands only in private and group chats, you can use bot.on('message').command('start', ctx => { ... }), or even store a message-only version of your bot in a variable like so:

const m = bot.on('message')

m.command('start', ctx => { ... })
m.command('help', ctx => { ... })
// etc

If you need more freedom matching your commands, check out the command-filter plugin.

Type Parameters

S extends string

Parameters

command: MaybeArray<StringWithSuggestions<
| S
| "start"
| "help"
| "settings"
>>

The command to look for

...middleware: Array<CommandMiddleware<C>>

The middleware to register