Skip to content

burnLight/telegram-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Node.js module to interact with official Telegram Bot API. A bot token is needed, to obtain one, talk to @botfather and create a new bot. Based on Yagop node-telegram-bot-api project.

npm install burnLight/telegram-bot
var TelegramBot = require('./telegramBot');

// create new TelegramBot
var bot = new TelegramBot('YOUR_BOT_TOKEN_HERE');

// set WebHook with url and certificate
bot.setWebHook('IP:PORT/botBOT_TOKEN', __dirname+'/crt.pem');

// Matches /echo [whatever]
bot.onText(/echo (.+)/, function (msg, match) {
    var fromId = msg.from.id;
    var answer = {
        type: 'text',
        content: match[1]
    }
    bot.send(fromId, answer);
});

// Any kind of message
bot.on('message', function (msg) {
    var chatId = msg.chat.id;
    // media answer example
    var answer = {
        type: 'photo',
        content: __dirname+'/photo.jpg',
        options: {
            caption: 'great photo !' // options like caption here. 
            // See https://core.telegram.org/bots/api#available-methods for further info about options
        }
    }
    bot.send(chatId, answer);
});

Events

Every time TelegramBot receives a message, it emits a message. Depending on which message was received, emits an event from this ones: text, audio, document, photo, sticker, video, voice, contact, location, new_chat_participant, left_chat_participant, new_chat_title, new_chat_photo, delete_chat_photo, group_chat_created. Its much better to listen a specific event rather than a message in order to stay safe from the content. TelegramBot emits inline_query when receives an Inline Query and chosen_inline_result when receives a ChosenInlineResult. Bot must be enabled on inline mode By Yagop project

WebHooks

Telegram only supports HTTPS connections to WebHooks, in order to set a WebHook a private key file and public certificate must be used. Since August 29, 2015 Telegram supports self signed ones, to generate them:

# Our private cert will be key.pem, keep in private this file.
openssl genrsa -out key.pem 2048
# Our public certificate will be crt.pem
openssl req -new -sha256 -key key.pem -out crt.pem

Once they are generated, the crt.pem can be provided to telegramBot.setWebHook(url, crt) as crt. By Yagop project

API Reference

TelegramBot

TelegramBot

Kind: global class
See: https://core.telegram.org/bots/api

new TelegramBot(token, [options])

Param Type Default Description
token String Bot Token
[options] Object
[options.webHook] Boolean | Object false Set true to enable WebHook or set options
[options.webHook.key] String PEM private key to webHook server.
[options.webHook.cert] String PEM certificate (public) to webHook server.
[options.requestRate] String 25 Request rate limit per second

telegramBot.requestRate ⇒ Boolean

Set max number of request to telegram server per second

Kind: instance property of TelegramBot
Returns: Boolean - false in case of wrong param
See: https://core.telegram.org/bots/faq#broadcasting-to-users

Param Type Description
rate Number new request rate number

telegramBot.setFilter(...filter) ⇒ Boolean

Set message functions to filter receiving updates

Kind: instance method of TelegramBot
Returns: Boolean - false in case of wrong param, true if no errors occur
See: https://core.telegram.org/bots/api#update

Param Type Description
...filter function function to be used to filter message passing to it the update obj received

telegramBot.getMe() ⇒ Promise

Returns basic information about the bot in form of a User object.

Kind: instance method of TelegramBot
See: https://core.telegram.org/bots/api#getme

telegramBot.setWebHook(url, [cert])

Specify an url to receive incoming updates via an outgoing webHook.

Kind: instance method of TelegramBot
See: https://core.telegram.org/bots/api#setwebhook

Param Type Description
url String URL where Telegram will make HTTP Post. Leave empty to delete webHook.
[cert] String | stream.Stream PEM certificate key (public).

telegramBot.getUpdates([timeout], [limit], [offset]) ⇒ Promise

Use this method to receive incoming updates using long polling

Kind: instance method of TelegramBot
Returns: Promise - Updates
See: https://core.telegram.org/bots/api#getupdates

Param Type Description
[timeout] Number | String Timeout in seconds for long polling.
[limit] Number | String Limits the number of updates to be retrieved.
[offset] Number | String Identifier of the first update to be returned.

telegramBot.answerInlineQuery(inlineQueryId, results, [options]) ⇒ Promise

Send answers to an inline query.

Kind: instance method of TelegramBot
See: https://core.telegram.org/bots/api#answerinlinequery

Param Type Description
inlineQueryId String Unique identifier of the query
results Array.<InlineQueryResult> An array of results for the inline query
[options] Object Additional Telegram query options

telegramBot.forwardMessage(chatId, fromChatId, messageId) ⇒ Promise

Forward messages of any kind.

Kind: instance method of TelegramBot

Param Type Description
chatId Number | String Unique identifier for the message recipient
fromChatId Number | String Unique identifier for the chat where the original message was sent
messageId Number | String Unique message identifier

telegramBot.getUserProfilePhotos(userId, [offset], [limit]) ⇒ Promise

Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.

Kind: instance method of TelegramBot
See: https://core.telegram.org/bots/api#getuserprofilephotos

Param Type Description
userId Number | String Unique identifier of the target user
[offset] Number Sequential number of the first photo to be returned. By default, all photos are returned.
[limit] Number Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.

telegramBot.getFile(fileId) ⇒ Promise

Get file. Use this method to get basic info about a file and prepare it for downloading. Attention: link will be valid for 1 hour.

Kind: instance method of TelegramBot
See: https://core.telegram.org/bots/api#getfile

Param Type Description
fileId String File identifier to get info about

telegramBot.getFileLink(fileId) ⇒ Promise

Get link for file. Use this method to get link for file for subsequent use. Attention: link will be valid for 1 hour.

This method is a sugar extension of the (getFile)[#getfilefileid] method, which returns just path to file on remote server (you will have to manually build full uri after that).

Kind: instance method of TelegramBot
Returns: Promise - promise Promise which will have fileURI in resolve callback
See: https://core.telegram.org/bots/api#getfile

Param Type Description
fileId String File identifier to get info about

telegramBot.downloadFile(fileId, downloadDir) ⇒ Promise

Downloads file in the specified folder. This is just a sugar for (getFile)[#getfilefiled] method

Kind: instance method of TelegramBot
Returns: Promise - promise Promise, which will have filePath of downloaded file in resolve callback

Param Type Description
fileId String File identifier to get info about
downloadDir String Absolute path to the folder in which file will be saved

telegramBot.onText(regexp, callback, [execNext])

Register a RegExp to test against an incomming text message

Kind: instance method of TelegramBot

Param Type Description
regexp RegExp RegExp to be executed with exec.
callback function Callback will be called with 2 parameters, the msg and the result of executing regexp.exec on message text.
[execNext] Boolean flag that allow multiple regex match

telegramBot.onReplyToMessage(chatId, messageId, callback, [execNext])

Register a reply to wait for a message response

Kind: instance method of TelegramBot

Param Type Description
chatId Number | String The chat id where the message cames from.
messageId Number | String The message id to be replied.
callback function Callback will be called with the reply message.
[execNext] Boolean flag that allow next regex match

telegramBot.send(chatId, answer) ⇒ Array

Send answer (or a answer array) to a given id (or a ids array)

Kind: instance method of TelegramBot
Returns: Array - Array of promises of each send effected
See: https://core.telegram.org/bots/api#available-methods info about format and contents

Param Type Description
chatId Number | Array Unique identifier of target chat or a array of them
answer Object | Array
answer.type String Type of data to be sent
answer.content Any The data to be sent (it changes based on the type)
[answer.options] Object Additional Telegram query options

License

telegram-bot is available under the MIT license