1.0.6 • Published 7 years ago

telegram-node-singlebot v1.0.6

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

telegram-node-singlebot

Very powerful module for creating Telegram Single Bot.

Base on telegram-node-bot

Installation

To install the stable version:

npm install --save telegram-node-singlebot

This assumes you are using npm as your package manager. If you don’t, you can access these files on unpkg, download them, or point your package manager to them.

Specificity

  • One active message for dialog with user
  • Powerfull form (cancel, back, confirm and etc.)
  • Powerfull menu
  • Smart Session

Get started

First of all you need to create your bot and get Token, you can do it right in telegram, just write to @BotFather.

Now let's write simple bot!

'use strict'

const Telegram = require('telegram-node-singlebot')
const TelegramBaseController = Telegram.TelegramBaseController
const TextCommand = Telegram.TextCommand
const tg = new Telegram.Telegram('YOUR_TOKEN')

// word

    global.lg = {
    cancel: 'cancel',
    back: 'back',
    confirm: 'confirm'
    }

class Main extends TelegramBaseController {
    handle($) {
    
    
    }
}

tg.router
    .otherwise(new main())

That's it!

Introduction

I'm using something like MVC, so we have router and controllers. First you need to declare your commands and which controller will handle it. Then you need to write controllers and handle specific commands in it.

Getting updates

You can use long-pooling or webhooks to get updates. Long-pooling used by default. To use webhooks you need to init library like this:

const tg = new Telegram.Telegram('YOUR_TOKEN', {
    webhook: {
        url: 'https://61f66256.ngrok.io',
        port: 3000,
        host: 'localhost'
    }
})

You can also create any other custom update fetcher: just extend Telegram.BaseUpdateFetcher and pass it to library:

const tg = new Telegram.Telegram('YOUR_TOKEN', {
    updateFetcher: new MyUpdateFetcher()
})

Clustering

By default library will create one worker per cpu. You can change it like this:

const tg = new Telegram.Telegram('YOUR_TOKEN', {
    workers: 1
})

If you want run some code on main process use tg.onMaster method:

const tg = new Telegram.Telegram('YOUR_TOKEN', {
    workers: 1
})

tg.sendMessage(123, 'test message') //will be sent 2 times (one time on master and one time on worker)

tg.onMaster(() => {
    tg.sendMessage(123, 'test message') //will be sent one time
})

Web admin

By default library will start web admin at localhost:7777, to change that use webAdmin properpty:

const tg = new Telegram.Telegram('YOUR_TOKEN', {
    webAdmin: {
        port: 1234,
        host: 'localhost'
    }
})

API

You can call api methods two ways:

Directly from tg:

tg.api.sendMessage(chatId, 'Hi')

Or if you using controllers controller will pass you context $ that already knows current chat id, so it's more easy to use:

$.sendMessage('Hi')

All methods have required parameters and optional parameters, you can find them in api documentation If you want to pass optional parameters you should pass them as an object:

$.sendMessage('Hi', { disable_notification: true })

Scope

There is two types of scope:

  • scope for message controllers - Scope
  • scope for inline mode controller - InlineScope

Message controllers scope:

scope will be passed to handle method or to your methods defined in routes

Main feature of scope is that scope already knows current chat id, so there is no need to pass that parameter. Scope have all api methods that have chatId as their first parameter already filled.

Scope also contains some information about update.

Inline controllers scope also has all api methods filled with userId.

Forms

In message controllers scope has runForm method.

With $.runForm method you can create forms:

var form = {
            title: 'Покупка телефона Item', // Title Form 
            cancel: ($) => {
            // event for cancel form
            },
            confirm: (result) => {
                return '<b>Покупка телефона Item</b>\n<i>Модель</i>: %s\n<i>Ваше имя</i>: %s\nКоментарий к заказу: %s'.format(result.model, result.name, result.commit) // message for confirm form
            },
            finish: (result) => {
                return '<b>%s</b>, Вы заказали: %s\nКоментарий к заказу: %s'.format(result.name, result.model, result.commit) // message for finish form
            },
            form: {
                model: {
                    text: 'Какую модель телефона выхотите купить',
                    error: 'Выберите правельную модель',
                    keyboard: [
                        ['Item 5s'],
                        ['Item 6'],
                        ['Item 6s'],
                        ['Item 7']
                    ],
                    keyboardonly: true // only keybord word
                    // auto valid, only text
                },
                name: {
                    text: 'Ваше Имя',
                    error: 'Имя введенно не правельно',
                    keyboard: [
                        [$.firstName]
                    ],
                    keyboardonly: false // anythink word
                    // auto valid, only text
                },
                location: {
                    text: 'Куда привезти телефон',
                    error: 'Вы отправили не гео локацию',
                    // valid for location
                    validator: (message, callback) => {
                        if(message.location) {
                            callback(true, message.location)
                            return
                        }
                        callback(false)
                    }
                },
                commit: {
                    text: 'Введите коментарий',
                    error: 'Коментарий введен не правельно'
                    validator: (message, callback) => {
                           if(message.text) {
                           callback(true, message.text)
                              return
                          }
                          callback(false)
                          }
                }
            }

        }

$.runForm(form, (result) => {
	console.log(result)
})

Bot will send the 'q' message to user, wait for message, validate it with your validator function and save the answer, if validation fails bot will ask again that question. You can also do some filtering in your validator, so you can pass the result as second parameter to callback. You can also pass keyboard to keyboard field.

Menu

You can create menu with $.runMenu function:

$.runMenu({
                      title: 'Shop',
                      message: 'Бот магазин товаров от shop',
                      menu: [
                          [{text: 'Item1', action: ($) => {
                          // Event
                          }}],
                          [{text: 'Item2', action: ($) => {
                          // Event
                          }}],
                          [{text: 'Зарегистрироваться', action: ($) => {
                          // Event
                          }}]
                      ]
                  })

Sessions

For user:

$.setUserSession('someKey', 'some data')
    .then(() => {
        return $.getUserSession('someKey')
    })
    .then(data => {
        console.log(data)
    })

For chat:

$.setChatSession('someKey', 'some data')
    .then(() => {
        return $.getChatSession('someKey')
    })
    .then(data => {
        console.log(data)
    })

By default sessions are stored in memory, but you can store them anywhere, you need to extend BaseStorage and pass instance of your storage to Telegram:

const tg = new Telegram.Telegram('YOUR_TOKEN',{
    storage: new MyStorage()
})

Logging

Module makes some logs during work, by default logs are written to console, but you can create your own logger if you want, you must extend BaseLogger and pass instance of your logger to Telegram:

const tg = new Telegram.Telegram('YOUR_TOKEN', {
    logger: new MyLogger()
})

Localization

To use localization you need to pass your localization files to Telegram, they must be like this:

{
  "lang": "Ru",
  "phrases": {
    "startMessage": "тест"
  }
}

after creating your files you need to pass them to Telegram:

const tg = new Telegram.Telegram('YOUR_TOKEN', {
    localization: [require('./Ru.json')]
})

Now you can use them in controllers like this:

console.log(this._localization.Ru.startMessage)

You can even set the language for specific user:

this._localization.setLanguageForUser(123456, 'Ru')

Or get phrases for user:

this._localization.forUser(123456)

Scope extensions:

Lets say you have some function that you want to be in scope, now you can do that like this:

'use strict'

const Telegram = require('telegram-node-bot')
const TelegramBaseController = Telegram.TelegramBaseController
const BaseScopeExtension = Telegram.BaseScopeExtension
const tg = new Telegram.Telegram('YOUR_TOKEN')

class SumScopeExtension extends BaseScopeExtension {
    process(num1, num2) {
        return num1 + num2
    }

    get name() {
        return 'sum'
    }
}

class SumController extends TelegramBaseController {
    /**
     * @param {Scope} $
     */
    sumHandler($) {
        $.sendMessage($.sum($.query.num1, $.query.num2))
    }

    get routes() {
        return {
            '/sum :num1 :num2': 'sumHandler'
        }
    }
}

tg.router
    .when(['/sum :num1 :num2'], new SumController())

tg.addScopeExtension(SumScopeExtension)

Sending files

From file id:

$.sendPhoto(InputFile.byId('ID')) or $.sendPhoto('ID')

From url:

$.sendPhoto(InputFile.byUrl('URL', 'image.jpg')) or $.sendPhoto({ url: 'URL', filename: 'image.jpg'})

By path:

$.sendPhoto(InputFile.byFilePath('path/to/file')) or $.sendPhoto({ path: 'path/to/file'})

License

Copyright (c) 2016 Fonov Sergei

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1.0.6

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago