Giter Site home page Giter Site logo

telegraf-flow's Introduction

logo

telegraf.js

Modern Telegram Bot API framework for Node.js

Bot API Version install size GitHub top language English chat

For 3.x users

Introduction

Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server.

Telegraf is a library that makes it simple for you to develop your own Telegram bots using JavaScript or TypeScript.

Features

Example

const { Telegraf } = require('telegraf')
const { message } = require('telegraf/filters')

const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start((ctx) => ctx.reply('Welcome'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on(message('sticker'), (ctx) => ctx.reply('馃憤'))
bot.hears('hi', (ctx) => ctx.reply('Hey there'))
bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))
const { Telegraf } = require('telegraf')

const bot = new Telegraf(process.env.BOT_TOKEN)
bot.command('oldschool', (ctx) => ctx.reply('Hello'))
bot.command('hipster', Telegraf.reply('位'))
bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))

For additional bot examples see the new docs repo.

Resources

Getting started

Telegram token

To use the Telegram Bot API, you first have to get a bot account by chatting with BotFather.

BotFather will give you a token, something like 123456789:AbCdefGhIJKlmNoPQRsTUVwxyZ.

Installation

$ npm install telegraf

or

$ yarn add telegraf

or

$ pnpm add telegraf

Telegraf class

Telegraf instance represents your bot. It's responsible for obtaining updates and passing them to your handlers.

Start by listening to commands and launching your bot.

Context class

ctx you can see in every example is a Context instance. Telegraf creates one for each incoming update and passes it to your middleware. It contains the update, botInfo, and telegram for making arbitrary Bot API requests, as well as shorthand methods and getters.

This is probably the class you'll be using the most.

Shorthand methods

import { Telegraf } from 'telegraf'
import { message } from 'telegraf/filters'

const bot = new Telegraf(process.env.BOT_TOKEN)

bot.command('quit', async (ctx) => {
  // Explicit usage
  await ctx.telegram.leaveChat(ctx.message.chat.id)

  // Using context shortcut
  await ctx.leaveChat()
})

bot.on(message('text'), async (ctx) => {
  // Explicit usage
  await ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`)

  // Using context shortcut
  await ctx.reply(`Hello ${ctx.state.role}`)
})

bot.on('callback_query', async (ctx) => {
  // Explicit usage
  await ctx.telegram.answerCbQuery(ctx.callbackQuery.id)

  // Using context shortcut
  await ctx.answerCbQuery()
})

bot.on('inline_query', async (ctx) => {
  const result = []
  // Explicit usage
  await ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result)

  // Using context shortcut
  await ctx.answerInlineQuery(result)
})

bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))

Production

Webhooks

import { Telegraf } from "telegraf";
import { message } from 'telegraf/filters';

const bot = new Telegraf(token);

bot.on(message("text"), ctx => ctx.reply("Hello"));

// Start webhook via launch method (preferred)
bot.launch({
  webhook: {
    // Public domain for webhook; e.g.: example.com
    domain: webhookDomain,

    // Port to listen on; e.g.: 8080
    port: port,

    // Optional path to listen for.
    // `bot.secretPathComponent()` will be used by default
    path: webhookPath,

    // Optional secret to be sent back in a header for security.
    // e.g.: `crypto.randomBytes(64).toString("hex")`
    secretToken: randomAlphaNumericString,
  },
});

Use createWebhook() if you want to attach Telegraf to an existing http server.

import { createServer } from "http";

createServer(await bot.createWebhook({ domain: "example.com" })).listen(3000);
import { createServer } from "https";

createServer(tlsOptions, await bot.createWebhook({ domain: "example.com" })).listen(8443);

Error handling

If middleware throws an error or times out, Telegraf calls bot.handleError. If it rethrows, update source closes, and then the error is printed to console and process terminates. If it does not rethrow, the error is swallowed.

Default bot.handleError always rethrows. You can overwrite it using bot.catch if you need to.

鈿狅笍 Swallowing unknown errors might leave the process in invalid state!

鈩癸笍 In production, systemd or pm2 can restart your bot if it exits for any reason.

Advanced topics

Working with files

Supported file sources:

  • Existing file_id
  • File path
  • Url
  • Buffer
  • ReadStream

Also, you can provide an optional name of a file as filename when you send the file.

bot.on('message', async (ctx) => {
  // resend existing file by file_id
  await ctx.replyWithSticker('123123jkbhj6b')

  // send file
  await ctx.replyWithVideo(Input.fromLocalFile('/path/to/video.mp4'))

  // send stream
  await ctx.replyWithVideo(
    Input.fromReadableStream(fs.createReadStream('/path/to/video.mp4'))
  )

  // send buffer
  await ctx.replyWithVoice(Input.fromBuffer(Buffer.alloc()))

  // send url via Telegram server
  await ctx.replyWithPhoto(Input.fromURL('https://picsum.photos/200/300/'))

  // pipe url content
  await ctx.replyWithPhoto(
    Input.fromURLStream('https://picsum.photos/200/300/?random', 'kitten.jpg')
  )
})

Middleware

In addition to ctx: Context, each middleware receives next: () => Promise<void>.

As in Koa and some other middleware-based libraries, await next() will call next middleware and wait for it to finish:

import { Telegraf } from 'telegraf';
import { message } from 'telegraf/filters';

const bot = new Telegraf(process.env.BOT_TOKEN);

bot.use(async (ctx, next) => {
  console.time(`Processing update ${ctx.update.update_id}`);
  await next() // runs next middleware
  // runs after next middleware finishes
  console.timeEnd(`Processing update ${ctx.update.update_id}`);
})

bot.on(message('text'), (ctx) => ctx.reply('Hello World'));
bot.launch();

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));

With this simple ability, you can:

Usage with TypeScript

Telegraf is written in TypeScript and therefore ships with declaration files for the entire library. Moreover, it includes types for the complete Telegram API via the typegram package. While most types of Telegraf's API surface are self-explanatory, there's some notable things to keep in mind.

Extending Context

The exact shape of ctx can vary based on the installed middleware. Some custom middleware might register properties on the context object that Telegraf is not aware of. Consequently, you can change the type of ctx to fit your needs in order for you to have proper TypeScript types for your data. This is done through Generics:

import { Context, Telegraf } from 'telegraf'

// Define your own context type
interface MyContext extends Context {
  myProp?: string
  myOtherProp?: number
}

// Create your bot and tell it about your context type
const bot = new Telegraf<MyContext>('SECRET TOKEN')

// Register middleware and launch your bot as usual
bot.use((ctx, next) => {
  // Yay, `myProp` is now available here as `string | undefined`!
  ctx.myProp = ctx.chat?.first_name?.toUpperCase()
  return next()
})
// ...

telegraf-flow's People

Contributors

dotcypress avatar ofstudio avatar piterden avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

telegraf-flow's Issues

Question: correct way to handle lost session?

Hi. I guess It's not a problem when using some persistent storage, but when using memory session user can "stuck" in a scene after restart of Node.js.
For example, in a bot with only "start" command and navigation by buttons I tried doing something like this:

app.use(Telegraf.memorySession())
app.use(flow.middleware())

app.command('start', ctx => {
  ctx.reply('Hi!')
    .then(() => ctx.flow.enter('main'))
})

app.on('message', ctx => {
  ctx.reply('Bot was restarted! Please try again')
    .then(() => ctx.flow.enter('main'))
})

But this way bot sends message about restart for any message not handled inside scene.

Thank you!

Scene's inline_query listener throws an error

I would like to use different inline query answers in different scenes, but it throws an error:

const bot = new Telegraf();
const flow = new TelegrafFlow();
const testScene = new Scene('test_scene');


bot.use(Telegraf.memorySession());
flow.register(testScene);

flow.command('test', ctx => {
  ctx.flow.enter('test_scene');
});

testScene.command('cancel', ctx => {
  ctx.flow.leave();
  ctx.reply('Canceled');
});

testScene.on('inline_query', ctx => { // throws Error: telegraf-flow: Can't find session.
  ctx.telegram.sendMessage(ctx.from.id, 'inline query answer from test_scene');
});

testScene.enter(ctx => {
  ctx.reply('Your inline query... /cancel');
});

bot.use(flow.middleware());

bot.on('inline_query', ctx => { // works well without flow.middleware
  ctx.telegram.sendMessage(ctx.from.id, 'global inline query answer');
});

flow.middleware prevents invoking the next middleware

Hi. I need to define ontext listener after all the command listeners, but it will never get invoked.

Here is my code:

const bot = new Telegraf();
const flow = new TelegrafFlow();
const testScene = new Scene('test_scene');

bot.use(Telegraf.memorySession());
flow.register(testScene);

flow.command('test', ctx => {
  ctx.flow.enter('test_scene');
});

testScene.command('cancel', ctx => {
  ctx.flow.leave();
  ctx.reply('Canceled');
});

testScene.enter(ctx => {
  ctx.reply('Say something... /cancel');
});

testScene.on('text', ctx => {
  ctx.reply('Answer is from test_scene'); // works well
});

bot.use(flow.middleware(), (ctx, next) => {
  console.log('TEST'); // doesn't invoke
  next();
});

bot.on('text', ctx => {
  ctx.reply('Answer is not from scene'); // doesn't work
});

How to reply with text not from the scene?

How can i perform validation?

Hi,

How can i perform validation and repeat the question if validation fails. Does anyone have an example? Thanks.

How to leave WizardScene?

I've tried different ways and it's not works.

const wizardOne = WizardScene(...).hears(/end/gi, leave()); // not works

What the right way to do it?

Session timeout

Hi. Congralations by package.
I'd like use a timeout on each flow in my chatbot.

For example, my Wizard Scene has 5 questions. In 3潞, the user close telegram. In the other day, he talks with bot, and the flow continue in the same stage.

Do you have some issue or backlog to implement it?

If don't, can I create a pull request?

Thanks

Back to previous step

Hi,

How can I get back to the previous step in wizard mode?
Is there any method like previous() that working with context?
Something like ctx.flow.wizard.previous().

Thanks.

How to handle cumulative answers?

Hi there, thanks for the middleware!

I was trying to understand one thing, maybe there's a better way to do it...

const addItemToListScene = new WizardScene('addItemToListScene',
(ctx) => {

       const existingListMenu = Extra
		.markdown()
		.markup((m) => {
			var existingLists = [];
			for (list in ctx.session.lists) {
				existingLists.push(m.callbackButton(list))
			}
			return m.keyboard(existingLists).oneTime().resize()
		})

	ctx.reply('Ok. To which list would you like o add an item?', existingListMenu, Extra.markup(Markup.forceReply()))
	ctx.flow.wizard.next();
},
(ctx) => {
	 const listName = ctx.message.text
	 ctx.reply('Give me the name of the item you wish to add to list ' + listName, Extra.markup(Markup.forceReply()))
 	 ctx.flow.wizard.next();
},
(ctx) => {
	const item = ctx.message.text
	ctx.session.lists[listName].push(item)
	ctx.reply(item + ' added!'))
	ctx.flow.leave()
})

Basically, what I wanted was to have that listName in the last step accessible, even tough it is not in the user's answer. This way I could perform step-by-step selection of lists, then item to be added.

Is it possible without storing the list name outside in another variable? I would love if I could pass it in something like the .next() function :(

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    馃枛 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 馃搳馃搱馃帀

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google 鉂わ笍 Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.