Remember when we started with Botfather? We had to click the “Start” button.

This is common to all bots. Until you click start, nothing happens.

Using Telegraf we can set our bot to respond to this command by simply adding a callback function to the start() method:

bot.start(ctx => ctx.reply('Welcome'))

Then all we need to do to create a fully functional bot is to call

bot.startPolling()

so that it automatically listens for new messages and chats.

Now we can press the “Start” button on our bot profile in Telegram and it will reply “Welcome”!

If you already pressed it before, right-click the profile and press “Clear History”. You will then start from a clean slate.

The start() command only runs once. Now that we started our interaction with the bot, we can listen for other things that are sent in the chat.

Responding to /help

We can react to the /help command, which is a standard command you can send to any bot. Bots usually explain how to use them.

How do we do that? We add a callback to the help() method:

bot.help(ctx => ctx.reply('Here\'s all the help I can give!'))

The context

What is ctx? We saw it in start() as well. It’s the context object. Every request gets its own context object, and you can inspect it to gain more information about the message, including

  • ctx.message the received message
  • ctx.inlineQuery the received inline query (more on this later)
  • ctx.from the message sender info

The ctx object also exposes some methods we’ll use to interact with the chat, including:

  • ctx.reply() sends a message to the chat

Intercept any message

Using the on() method you can intercept any message coming in from the chat, and do something. In this case we reply “Hey!”:

bot.on('message', ctx => ctx.reply('Hey!'))

Intercept a specific message

You can listen for a specific message in the chat using

bot.hears('hi', ctx => ctx.reply('Hey there'))

Warning: this is case sensitive.

To respond to a command whatever the case is, use a regular expression:

bot.hears('/hi/i', ctx => ctx.reply('Hey there'))

Check out a guide to JavaScript Regular Expressions to know more about regular expressions.


Go to the next lesson