Teabot allows you to create highly interactive Telegram bot for Node.js with some additional cool features.
- Written for creating interactive bots
- Data storage in Redis, Aerospike (more in the future)
- Built-in support analytics botan.io
- Supports deep linking mechanism
- Supports /command@BotName commands
- Has own wrapper over Telegram API to enhance existing functionality
npm install teabot
var TeaBot = require('teabot');
var token = 'YOUR_TELEGRAM_BOT_TOKEN';
var name = 'YOUR_TELEGRAM_BOT_NAME';
var Bot = new TeaBot(token, name);
Bot.defineCommand(function(dialog) {
var message = dialog.message;
dialog.sendMessage('Echo: ' + message.text);
});
Bot.startPooling();
- Methods
- Bot object
- Dialog object
- Action
- User data
- Temp data
- Telegram API
- sendMessage(text, [options])
- forwardMessage(fromChatId, messageId)
- sendPhoto(photo, [options])
- sendAudio(audio, [options])
- sendDocument(document, [options])
- sendSticker(sticker, [options])
- sendVideo(video, [options])
- sendVoice(audio, [options])
- sendLocation(latitude, longitude, [options])
- sendChatAction(action)
- getUserProfilePhotos()[offset], [limit]
- Extra
- Message object
- Databases
- Analytics
- Weird stuff
- Examples
- Documentation
Bot object stores all commands, actions, settings, and also all the dialogues bot.
- token (String) - Telegram Bot token.
- name (String) - Telegram Bot name.
- [options] (Object) - Config options:
- db (Object) - DB config.
- analytics (Object) - Analytics config.
var TeaBot = require('teabot');
var Bot = new TeaBot(token, name);
Commands always start with /.
- command (String|Array) - Command or an array of commands.
- callback (Function) - Callback which is invoked for this command/commands.
- callback (Function) - Callback which is invoked if the given command is not defined or is not available.
var Bot = new TeaBot(token, name);
Bot
.defineCommand(['/start', '/help'], function(dialog) {
var message = dialog.message;
dialog.sendMessage('Hi there. This is a ' + message.getCommand() + ' command.');
})
.defineCommand(function(dialog) {
dialog.sendMessage('Send me /help for more information.');
});
Actions are singly linked list of unlimited length.
The first action is always set using defineAction
, and all others using the defineSubAction
in the previous action.
- action (String|Array) - Action or an array of actions.
- callback (Function) - Callback which is invoked for this action/actions.
- [subAction] (Function) - Callback is used to determine the sub-action.
- action (String|Array) - Sub-action.
- callback (Function) - Callback which is invoked for this sub-action.
- [subAction] (Function) - Callback is used to determine the sub-action.
var Bot = new TeaBot(token, name);
Bot
.defineCommand('/start', function(dialog) {
dialog.startAction('/start').sendMessage('This is /start command');
})
.defineCommand(function(dialog) {
dialog.sendMessage('Send me /help for more information.');
});
Bot
.defineAction('/start', function(dialog) {
dialog.startAction('subaction 1').sendMessage('This is /start action');
}, function(action) {
action.defineSubAction('subaction 1', function(dialog) {
dialog.startAction('subaction 2').sendMessage('This is subaction 1');
}, function(action) {
action.defineSubAction('subaction 2', function(dialog) {
dialog.endAction().sendMessage('This is subaction 2');
})
})
});
Depending on what type of connection with Telegram is used (webhook or long pooling), there are 2 methods to start the bot.
To work with webhook.
- message (Object) - Message object received from Telegram using the webhook.
To work with long pooling.
- [options] (Object) - Pooling options:
- offset (Integer) - Identifier of the first update to be returned.
- timeout (Integer) - Timeout in seconds for long polling.
- limit (Integer) - Limits the number of updates to be retrieved.
- interval (Integer) - Interval request updates from Telegram. In milliseconds (2000 by default).
- userId (Integer) - User id to track.
- message (Object) - Message object.
- event (String) - Event name.
Dialog object stores bot current dialogue with the user, as well as commands for communication.
It can be obtained in defineCommand
, defineAction
, defineSubAction
callbacks, or directly from Bot object.
It is an object that contains a list of actions in the form of linked list.
Checks whether the user is in a state of action, and if so action will returned, otherwise false.
Start the action. Then all processes occur in defineAction
or defineSubAction
callbacks.
- action (String) - Name of action defined in
defineAction
ordefineSubAction
for start. - [perform] (Boolean) - If true, the action callback will be called immediately. Otherwise, it will happen at the next incoming message.
Ends the action and clears dialog.tempData
.
- [saveTemp] (Boolean) - If true, then
dialog.tempData
will not be cleared.
Example with action: 1st way
Example with action: 2nd way
It is an object that can store user data (such as the bot settings).
Gets user data on the property name.
- property (String) - Property name.
Sets the user data.
- property (String) - Property name.
- data (Mixed) - User data.
Deletes user data on the property name.
- property (String) - Property name.
Clears the user data.
It is an object that can store temporary data to be transmitted between the actions.
Deleted automatically when calling endAction()
.
Gets temporary data on the property name.
- property (String) - Property name.
Sets the temporary data.
- property (String) - Property name.
- data (Mixed) - Temporary data.
Deletes temporary data on the property name.
- property (String) - Property name.
Clears the temporary data.
All methods return a Promise
, unless otherwise indicated. All methods are sent to the current chat/user.
Send text message.
- text (String) - Text of the message to be sent.
- [options] (Object) - Message options:
- parse_mode (String) - Send
Markdown
, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. - disable_web_page_preview (Boolean) - Disables link previews for links in this message.
- reply_to_message_id (Integer) - If the message is a reply, ID of the original message.
- reply_markup - Additional interface options.
- parse_mode (String) - Send
Forward messages of any kind.
- fromChatId (Integer) - Unique identifier for the chat where the original message was sent.
- messageId (Integer) - Unique message identifier.
Send photo.
- photo (String|Object) - Object with file path, Stream, Buffer or
file_id
. See InputFile object for more info. - [options] (Object) - Photo options:
- caption (String) - Photo caption.
- reply_to_message_id (Integer) - If the message is a reply, ID of the original message.
- reply_markup - Additional interface options.
Send audio.
- audio (String|Object) - Object with file path, Stream, Buffer or
file_id
. See InputFile object for more info. - [options] (Object) - Audio options:
- duration (Integer) - Duration of sent audio in seconds.
- performer (String) - Performer of sent audio.
- title (String) - Title of sent audio.
- reply_to_message_id (Integer) - If the message is a reply, ID of the original message.
- reply_markup - Additional interface options.
Send document.
- document (String|Object) - Object with file path, Stream, Buffer or
file_id
. See InputFile object for more info. - [options] (Object) - Document options:
- reply_to_message_id (Integer) - If the message is a reply, ID of the original message.
- reply_markup - Additional interface options.
Send .webp stickers.
- sticker (String|Object) - Object with file path, Stream, Buffer or
file_id
. See InputFile object for more info. - [options] (Object) - Sticker options:
- reply_to_message_id (Integer) - If the message is a reply, ID of the original message.
- reply_markup - Additional interface options.
Send video.
- video (String|Object) - Object with file path, Stream, Buffer or
file_id
. See InputFile object for more info. - [options] (Object) - Video options:
- duration (Integer) - Duration of sent video in seconds.
- caption (String) - Video caption.
- reply_to_message_id (Integer) - If the message is a reply, ID of the original message.
- reply_markup - Additional interface options.
Send voice.
- audio (String|Object) - Object with file path, Stream, Buffer or
file_id
. See InputFile object for more info. - [options] (Object) - Voice options:
- duration (Integer) - Duration of sent video in seconds.
- reply_to_message_id (Integer) - If the message is a reply, ID of the original message.
- reply_markup - Additional interface options.
Send location.
- latitude (Float) - Latitude of location.
- longitude (Float) - Longitude of location.
- [options] (Object) - Location options:
- reply_to_message_id (Integer) - If the message is a reply, ID of the original message.
- reply_markup - Additional interface options.
Send chat action.
typing
for text messages, upload_photo
for photos, record_video
or upload_video
for videos, record_audio
or upload_audio
for audio files, upload_document
for general files, find_location
for location data.
- action (String) - Type of action to broadcast.
Use this method to get a list of profile pictures for a user.
- [offset] (Integer) - Sequential number of the first photo to be returned. By default, all photos are returned.
- [limit] (Integer) - Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.
Custom keyboard.
- keyboard (Array of Array of Strings) - Array of button rows, each represented by an Array of Strings.
- [resize] (Boolean) - Requests clients to resize the keyboard vertically for optimal fit.
- [once] (Boolean) - Requests clients to hide the keyboard as soon as it's been used.
- [selective] (Boolean) - Use this parameter if you want to show the keyboard to specific users only.
Hide custom keyboard.
- [hide_keyboard] (True) - Requests clients to hide the custom keyboard.
- [selective] (Boolean) - Use this parameter if you want to show the keyboard to specific users only.
If you just want to hide the keyboard, then do this:
dialog.setKeyboard().sendMessage('Text');
//or
dialog.setKeyboard(true);
dialog.sendMessage('Text');
If you want to hide the keyboard to specific users only, then do this:
dialog.setKeyboard(true, true).sendMessage('Text');
//or
dialog.setKeyboard(true, true);
dialog.sendMessage('Text');
If buffer:
var inputFile = {
buffer: new Buffer(),
fileName: 'file.png'
};
If stream:
var inputFile = {
stream: fs.createReadStream('file.png'),
fileName: 'file.png'
};
If path:
var inputFile = 'file.png';
If file_id
:
var inputFile = 'file_id';
//or
var inputFile = {fileId: 'file_id'};
Message object stores processed incoming message, as well as its original copy.
It can be obtained from dialog.message
.
Returns the type of message: text
, audio
, document
, photo
, sticker
, video
, contact
, location
, voice
or other
.
If is message is command returns true
else false
.
Returns command.
It returns the rest of the message, if it contains a command or the entire message.
By default, all data is stored in memory, but for synchronization between servers or nodes, you may need a database.
By default key = 'app:teabot'
.
var redis = require('redis');
var client = redis.createClient();
var config = {
db: {
type: 'redis',
client: client,
key: 'bot:telegram'
}
};
var Bot = new TeaBot(token, name, config);
By default key = {ns: 'app', set: 'teabot'}
.
var aerospike = require('aerospike');
var client = aerospike.client({
hosts: [{
addr: '127.0.0.1',
port: 4000,
}]
}).connect(function(response) {
if (response.code == 0) {
console.log('Connection to Aerospike cluster succeeded!');
}
});
var config = {
db: {
type: 'aerospike',
client: client,
key: {
ns: 'bot', set: 'telegram'
}
}
};
var Bot = new TeaBot(token, name, config);
TeaBot has built-in support analytics from botan.io.
By default, all events are sent automatically at the defineCommand
, defineAction
, defineSubAction
.
And it looks like this:
But you can send they manually using the Bot.track, if you specify manualMode
property to true.
var config = {
analytics: {
key: 'KEY',
manualMode: true
}
};
var Bot = new TeaBot(token, name, config);
Bot
.defineCommand(['/start', '/help'], function(dialog) {
var message = dialog.message;
dialog.sendMessage('Hi there. This is a ' + message.getCommand() + ' command.');
Bot.track(dialog.userId, message, message.getCommand());
})
.defineCommand(function(dialog) {
dialog.sendMessage('Send me /help for more information.');
Bot.track(dialog.userId, message, 'Default');
});
It's weird but you can even let your users create their own command!
Note: Currently it'll correctly work only with default memory storage in single node environment.
Bot
.defineCommand('/add', function(dialog) {
dialog.startAction('/add').sendMessage('Send me new command');
})
.defineCommand('/cancel', function(dialog) {
dialog.endAction().sendMessage('Ok, now you can try something else.');
})
.defineCommand(function(dialog) {
dialog.sendMessage('Send me /help for more information.');
});
Bot
.defineAction('/add', function(dialog) {
dialog.setTempData('command', dialog.message.text);
dialog.startAction('message').sendMessage('Send me message for new command');
}, function(action) {
action.defineSubAction('message', function(dialog) {
var message = dialog.message.text;
Bot.defineCommand(dialog.getTempData('command'), function(dialog) {
dialog.sendMessage(message);
});
dialog.sendMessage('New command ' + dialog.getTempData('command') + ' was successfully added!');
dialog.endAction();
})
});
-
Webhook - ex1.webhook.js
-
Long pooling - ex2.pooling.js
-
Action: 1st way - ex3-1.action.js
-
Action: 2nd way - ex3-2.action.js
-
User data - ex4.userData.js
-
Message - ex5.message.js
-
Weird stuff - ex6.userCommand.js
Coming soon.
The MIT License (MIT)
Copyright (c) 2015 Alexey Bystrov