Git Product home page Git Product logo

telebot's Introduction

The easy way to write Telegram bots.

Build Status Dependency Status Node.js Version

TeleBot 2.0 TeleBot Examples TeleBot Bot TeleBot Group

Library features:

🔨 Installation

npm install telebot

Or using yarn package manager:

yarn add telebot

🕹 Usage

Import telebot module and create a new bot object:

const TeleBot = require('telebot');

const bot = new TeleBot({
    token: TELEGRAM_BOT_TOKEN, // Required. Telegram Bot API token.
    polling: { // Optional. Use polling.
        interval: 1000, // Optional. How often check updates (in ms).
        timeout: 0, // Optional. Update polling timeout (0 - short polling).
        limit: 100, // Optional. Limits the number of updates to be retrieved.
        retryTimeout: 5000, // Optional. Reconnecting timeout (in ms).
        proxy: 'http://username:[email protected]:8080' // Optional. An HTTP proxy to be used.
    },
    webhook: { // Optional. Use webhook instead of polling.
        key: 'key.pem', // Optional. Private key for server.
        cert: 'cert.pem', // Optional. Public key.
        url: 'https://....', // HTTPS url to send updates to.
        host: '0.0.0.0', // Webhook server host.
        port: 443, // Server port.
        maxConnections: 40 // Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery
    },
    allowedUpdates: [], // Optional. List the types of updates you want your bot to receive. Specify an empty list to receive all updates.
    usePlugins: ['askUser'], // Optional. Use user plugins from pluginFolder.
    pluginFolder: '../plugins/', // Optional. Plugin folder location.
    pluginConfig: { // Optional. Plugin configuration.
        // myPluginName: {
        //   data: 'my custom value'
        // }
    }
});

Or just:

const TeleBot = require('telebot');
const bot = new TeleBot(TELEGRAM_BOT_TOKEN);

Don't forget to insert your Telegram Bot API token key.

To start polling updates, use bot.start().

bot.on('text', (msg) => msg.reply.text(msg.text));

bot.start();

We just created echo bot!

🌱 Quick examples

Send text on /start or /hello command:

bot.on(['/start', '/hello'], (msg) => msg.reply.text('Welcome!'));

When sticker received, reply back:

bot.on('sticker', (msg) => {
    return msg.reply.sticker('http://i.imgur.com/VRYdhuD.png', { asReply: true });
});

Sends photo on "show kitty" or "kitty" text message (using RegExp):

bot.on(/(show\s)?kitty*/, (msg) => {
    return msg.reply.photo('http://thecatapi.com/api/images/get');
});

Command with arguments /say <your message>:

bot.on(/^\/say (.+)$/, (msg, props) => {
    const text = props.match[1];
    return bot.sendMessage(msg.from.id, text, { replyToMessage: msg.message_id });
});

When message was edited:

bot.on('edit', (msg) => {
    return msg.reply.text('I saw it! You edited message!', { asReply: true });
});

Note: msg.reply is a bot method shortcut, part of shortReply build-in plugin.

See more examples!

⏰ Events

Use bot.on(<event>, <function>) to handle all possible TeleBot events.

For example, to catch a command, just add a slash:

bot.on('/hello', (msg) => {
  return bot.sendMessage(msg.from.id, `Hello, ${ msg.from.first_name }!`);
});

Also, you can catch multiple events:

bot.on(['/start', 'audio', 'sticker'], msg => {
  return bot.sendMessage(msg.from.id, 'Bam!');
});

TeleBot events:

  • /* – any user command
  • /<cmd> – on specific command
  • start – bot started
  • stop – bot stopped
  • reconnecting – bot reconnecting
  • reconnected – bot successfully reconnected
  • update - on update
  • tick – on bot tick
  • error – an error occurred
  • inlineQuery - inline query data
  • chosenInlineResult - inline query chosen result
  • callbackQuery - button callback data
  • shippingQuery - incoming shipping query
  • preShippingQuery - incoming pre-checkout query

Events:

keyboard, button, inlineKeyboard, inlineQueryKeyboard, inlineButton, answerList, getMe, sendMessage, deleteMessage, forwardMessage, sendPhoto, sendAudio, sendDocument, sendSticker, sendVideo, sendVideoNote, sendVoice, sendLocation, sendVenue, sendContact, sendChatAction, getUserProfilePhotos, getFile, kickChatMember, unbanChatMember, answerInlineQuery, answerCallbackQuery, answerShippingQuery, answerPreCheckoutQuery, editMessageText, editMessageMedia, editMessageCaption, editMessageReplyMarkup, setWebhook

Telegram message events:

  • * - any type of message
  • text – text message
  • audio – audio file
  • voice – voice message
  • document – document file (any kind)
  • photo – photo
  • sticker – sticker
  • video – video file
  • videoNote - video note
  • animation – animation data
  • contact – contact data
  • location – location data
  • venue – venue data
  • game - game data
  • invoice - invoice for a payment
  • edit – edited message
  • forward – forwarded message
  • pinnedMessage – message was pinned
  • newChatMembers - new members that were added to the group or supergroup
  • leftChatMember – member was removed
  • newChatTitle – new chat title
  • newChatPhoto – new chat photo
  • deleteChatPhoto – chat photo was deleted
  • groupChatCreated – group has been created
  • channelChatCreated – channel has been created
  • supergroupChatCreated – supergroup has been created
  • migrateToChat – group has been migrated to a supergroup
  • migrateFromChat – supergroup has been migrated from a group
  • successfulPayment – message is a service message about a successful payment
  • passportData – Telegram Passport data

Read more about Telegram Bot API response types: https://core.telegram.org/bots/api#available-types

🚜 Modifiers

You can add modifier to process data before passing it to event.

bot.mod('text', (data) => {
  let msg = data.message;
  msg.text = `📢 ${ msg.text }`;
  return data;
});

This code adds emoji to every text message.

TeleBot modifiers:

  • property - mod form properties
  • updateList - list of updates in one tick
  • update - every update
  • message - process any type of message
  • <type> - specific type of message

🔌 Plugins

Use usePlugins config option to load plugins from pluginFolder directory:

const bot = new TeleBot({
    token: 'TELEGRAM_BOT_TOKEN',
    usePlugins: ['askUser', 'commandButtons'],
    pluginFolder: '../plugins/',
    pluginConfig: {
        // Plugin configs
    }
});

Or use plug(require(<plugin_path>)) to plug an external plugin.

Check out build-in plugin folder!

Plugin structure

module.exports = {
    id: 'myPlugin', // Unique plugin name
    defaultConfig: {
        // Default plugin config
        key: 'value'
    },
    plugin(bot, pluginConfig) {
        // Plugin code
    }
};

⚙️ Methods

TeleBot methods:

on(<events>, <function>)

Handles events.

event(<event>, <data>)

Invokes the event handlers.

mod(<name>, <fn>)

Add data modifier.

modRun(<names>, <data>)

Run data modifiers.

plug(<plugin function>)

Use plugin function.

keyboard([array of arrays], {resize, once, remove, selective})

Creates ReplyKeyboardMarkup keyboard replyMarkup object.

button(<location | contact>, <text>)

Creates KeyboardButton button.

inlineButton(<text>, {url | callback | game | inline | inlineCurrent | pay})

Creates InlineKeyboardButton button object.

inlineKeyboard([array of arrays])

Creates inlineKeyboard object for normal bot messages.

answerList(<inline_query_id>, {nextOffset, cacheTime, personal, pmText, pmParameter})

Creates answerInlineQuery answer list object.

inlineQueryKeyboard([array of arrays])

Creates inlineKeyboard object for answerList articles.

start()

Start polling updates.

stop(<message>)

Stop polling updates.

receiveUpdates([<update>])

Handle Telegram update

Telegram methods:

TeleBot use standard Telegram Bot API method names.

getMe()

A simple method for testing your bot's auth token.

answerQuery(<answerList>)

Use this method to send answerList to an inline query.

getFile(<file_id>)

Use this method to get basic info about a file and prepare it for downloading.

sendMessage(<chat_id>, <text>, {parseMode, replyToMessage, replyMarkup, notification, webPreview})

Use this method to send text messages.

forwardMessage(<chat_id>, <from_chat_id>, <message_id>, {notification})

Use this method to forward messages of any kind.

deleteMessage(<chat_id>, <from_message_id>)

Use this method to delete a message. A message can only be deleted if it was sent less than 48 hours ago. Any such sent outgoing message may be deleted. Additionally, if the bot is an administrator in a group chat, it can delete any message. If the bot is an administrator of a supergroup or channel, it can delete ordinary messages from any other user, including service messages about people added or removed from the chat. Returns True on success.

sendPhoto(<chat_id>, <file_id | path | url | buffer | stream>, {caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})

Use this method to send photos.

sendAudio(<chat_id>, <file_id | path | url | buffer | stream>, {title, performer, duration, caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message.

sendDocument(<chat_id>, <file_id | path | url | buffer | stream>, {caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})

Use this method to send general files.

sendAnimation(<chat_id>, <animation>, {caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).

sendSticker(<chat_id>, <file_id | path | url | buffer | stream>, {fileName, serverDownload, replyToMessage, replyMarkup, notification})

Use this method to send .webp stickers.

sendVideo(<chat_id>, <file_id | path | url | buffer | stream>, {duration, width, height, caption, fileName, serverDownload, replyToMessage, replyMarkup, notification, supportsStreaming})

Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).

sendVideoNote(<chat_id>, <file_id | path | url | buffer | stream>, {duration, length, fileName, serverDownload, replyToMessage, replyMarkup, notification})

Use this method to send video messages.

sendMediaGroup(<chat_id>, <mediaList: InputMedia[]>)

Use this method to send a group of photos or videos as an album. (Min. 2)

sendVoice(<chat_id>, <file_id | path | url | buffer | stream>, {duration, caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message.

sendLocation(<chat_id>, [<latitude>, <longitude>], {replyToMessage, replyMarkup, notification})

Use this method to send point on the map.

sendLocation(<chat_id>, [<latitude>, <longitude>], {replyToMessage, replyMarkup, notification})

Use this method to send point on the map.

editMessageLiveLocation({chatId + messageId | inlineMessageId, latitude, longitude}, {replyMarkup})

Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation.

stopMessageLiveLocation({chatId + messageId | inlineMessageId}, {replyMarkup})

Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires.

sendVenue(<chat_id>, [<latitude>, <longitude>], <title>, <address>, {foursquareId, foursquareType, replyToMessage, replyMarkup, notification})

Use this method to send information about a venue.

getStickerSet(<name>)

Use this method to get a sticker set.

uploadStickerFile(<user_id>, <file_id | path | url | buffer | stream>)

Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times).

createNewStickerSet(<user_id>, <name>, <file_id | path | url | buffer | stream>, <emojis>, {containsMasks, maskPosition})

Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.

setChatStickerSet(<chat_id>, <sticker_set_name>)

Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

deleteChatStickerSet(<chat_id>)

Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

addStickerToSet(<user_id>, <name>, <file_id | path | url | buffer | stream>, <emojis>, {maskPosition})

Use this method to add a new sticker to a set created by the bot.

setStickerPositionInSet(<sticker>, <position>)

Use this method to move a sticker in a set created by the bot to a specific position.

deleteStickerFromSet(<sticker>)

Use this method to delete a sticker from a set created by the bot.

sendContact(<chat_id>, <number>, <firstName>, <lastName>, { replyToMessage, replyMarkup, notification})

Use this method to send phone contacts.

sendAction(<chat_id>, <action>)

Use this method when you need to tell the user that something is happening on the bot's side. Choose one, depending on what the user is about to receive: 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, record_video_note or upload_video_note for video notes.

sendGame(<chat_id>, <game_short_name>, {notification, replyToMessage, replyMarkup})

Use this method to send a game.

setGameScore(<user_id>, <score>, {force, disableEditMessage, chatId, messageId, inlineMessageId})

Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.

getGameHighScores(<user_id>, {chatId, messageId, inlineMessageId})

Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbours in a game. On success, returns an Array of GameHighScore objects.

getUserProfilePhotos(<user_id>, {offset, limit})

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

getFile(<file_id>)

Use this method to get basic info about a file and prepare it for downloading.

sendInvoice(<chat_id>, {title, description, payload, providerToken, startParameter, currency, sendPhoneNumberToProvider, sendEmailToProvider, prices, providerData, photo: {url, width, height}, need: {name, phoneNumber, email, shippingAddress}, isFlexible, notification, replyToMessage, replyMarkup})

Use this method to send invoices.

getChat(<chat_id>)

Use this method to get up to date information about the chat.

leaveChat(<chat_id>)

Use this method for your bot to leave a group, supergroup or channel.

getChatAdministrators(<chat_id>)

Use this method to get a list of administrators in a chat.

getChatMembersCount(<chat_id>)

Use this method to get the number of members in a chat.

getChatMember(<chat_id>, <user_id>)

Use this method to get information about a member of a chat.

kickChatMember(<chat_id>, <user_id>, {untilDate})

Use this method to kick a user from a group or a supergroup.

unbanChatMember(<chat_id>, <user_id>)

Use this method to unban a previously kicked user in a supergroup.

restrictChatMember(<chat_id>, <user_id>, {untilDate, canSendMessages, canSendMediaMessages, canSendOtherMessages, canAddWebPagePreviews})

Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights.

promoteChatMember(<chat_id>, <user_id>, {canChangeInfo, canPostMessages, canEditMessages, canDeleteMessages, canInviteUsers, canRestrictMembers, canPinMessages, canPromoteMembers})

Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

exportChatInviteLink(<chat_id>)

Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

setChatPhoto(<chat_id>, <file_id | path | url | buffer | stream>)

Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

deleteChatPhoto(<chat_id>)

Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

setChatTitle(<chat_id>, <title>)

Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

setChatDescription(<chat_id>, <description>)

Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

pinChatMessage(<chat_id>, <message_id>)

Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

editMessageText({chatId & messageId | inlineMsgId}, <text>)

Use this method to edit text messages sent by the bot or via the bot (for inline bots).

editMessageMedia({chatId | messageId | inlineMessageId, media: InputMedia, replyMarkup: inlineKeyboard})

Use this method to edit animation, audio, document, photo, or video messages.

editMessageCaption({chatId & messageId | inlineMsgId}, <caption>)

Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).

editMessageReplyMarkup({chatId & messageId | inlineMsgId}, <replyMarkup>)

Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).

answerCallbackQuery(<callback_query_id>, {text, url, showAlert, cacheTime})

Use this method to send answers to callback queries sent from inline keyboards.

answerShippingQuery(<shipping_query_id>, <ok> {shippingOptions, errorMessage})

Use this method to reply to shipping queries.

answerPreCheckoutQuery(<pre_checkout_query_id>, <ok> {errorMessage})

Use this method to respond to such pre-checkout queries.

setWebhook(<url>, <certificate>, <allowed_updates>, <max_connections>)

Use this method to specify a url and receive incoming updates via an outgoing webhook.

getWebhookInfo()

Use this method to get current webhook status.

deleteWebhook()

Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.

sendDice(<chatId>, <emoji>)

Use this method to send a dynamic emoji. Examples: 🎲 (default), 🎯 or 🏀.

telebot's People

Contributors

11-a-11 avatar andriy2 avatar dependabot[bot] avatar eko24 avatar flaplim avatar fuzzyma avatar g07cha avatar kosmodrey avatar mullwar avatar noplanman avatar phfaster avatar pyriaxis avatar rene-demonsters avatar s-a-y avatar shah-smit avatar shemesh avatar suntrustdev avatar switool avatar vrumger 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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar

telebot's Issues

' instead of ` for Europe

Hello, in Europe we don't have on keyboard the ` key, we just have ' or " ...is there a way to let strings like

Hello, ${ firstName } ${ lastName }!

work?

I tried with
'Hello, '+${ firstName }!
and
'Hello, ${ firstName }!'

but it doesn't work!

How can I get Location data back from a keyboard?

I have a bot that does a series of interaction with the user. The user will first provide some info and as a response to the user reply, my bot asks for location using the button object wrapped inside keyboard object as follows:

bot.on('/test', msg => {
  
  let fromId = msg.from.id;
  let firstName = msg.from.first_name;
  let reply = msg.message_id;
  //the bot.keyboard() takes first argument as array of arrays
  let markup = bot.keyboard([[bot.button('location','Send your location')]],"once"); 
  //console.log(markup);
  return bot.sendMessage(fromId, "Send location" , { markup });
});

I cannot figure out where can I put the callback method that will get the location sent by the user. I found out that the "update" event can be listened to. But I guess there is a more convenient way of getting this done. Could you please suggest something on this?

return inlineQuery with HTML markup

how to return html markup in inlineQuery?

bot.on('inlineQuery', msg => {

  let query = msg.query;
  console.log(`inline query: ${ query }`);
  // Create a new answer list object
  var answers = bot.answerList(msg.id);

  answers.addArticle({
    id: '121212',
    title: 'What is Function?',
    description: 'huha',
    message_text: '`<a href="aa">a</a>`'
  }, {
    parse: 'html'
  });

  return bot.answerQuery(answers);
});

Local testing

I write the bot on my computer.
How i can the bot testing local on my computer?

image

here my settings.

Is it possible to have http proxy support ?

Hello,

First of all, I really appreciate your work.
Is it possible to add proxy support ?

exemple :

const bot: TeleBot = new TeleBot( {
    token: botToken,
    http_proxy: {
        host: "[MyProxy]",
        port: 8080,
        username: "[MyUsername]",
        password: "[MyPwd]"
    },
    polling: {
        ...
    }
});

Thank you !

pooling vs. polling

Hi, I noticed that your config has a "pooling" option.
Shouldn't this be "polling"?

sendPhoto with notification disabled throws an error

Using bot.sendPhoto with the notify: false option throws the following error:

_http_outgoing.js:456
    throw new TypeError('First argument must be a string or Buffer');
    ^

TypeError: First argument must be a string or Buffer
    at ClientRequest.OutgoingMessage.write (_http_outgoing.js:456:11)
    at Request.write (/tmp/telebot/node_modules/request/request.js:1387:27)
    at FormData.ondata (stream.js:31:26)
    at emitOne (events.js:96:13)
    at FormData.emit (events.js:188:7)
    at FormData.CombinedStream.write (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:118:8)
    at FormData.CombinedStream._pipeNext (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:106:8)
    at FormData.CombinedStream._getNext (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:79:10)
    at FormData.CombinedStream._pipeNext (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:107:8)
    at FormData.CombinedStream._getNext (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:79:10)

I tracked the error down to methods.js#L289 where form gets passed as data instead of form (according to telebot.js#L262). Changing the line to

return this.request(`/${ url }`, form);

will result in the request going through and the photo being send like expected, but will make the tests fail so i'm sure that's not the root cause. Unfortunately, i'm not familiar enough with the lib to pinpoint it myself.

To reproduce:

const TeleBot = require('telebot');
let t = new TeleBot("TOKEN");
t.sendPhoto("CHAT_ID", "https://telegram.org/img/t_logo.png", {
    notify: false
});

I'm using node v6.7.0, npm v3.10.8 & telebot v1.0.6.

acess list

Hello Kosmodrey,

How could I create a way to only users listed by name @example in a TXT file would have access to start the bot ? And if the user does not have the list , appear a message Access denied .

I have an example?

[ask] telegram message gateway

is it possible to make telebot become message gateway?
so the id is my phone number but act like bot...
if someone message me(my phone number), my account will auto reply like bot...
is it possible?
pardon me if i ask here... :D

Parse_mode

Hi! How I can set parse_mod to 'HTML' in sendMessage function or other?

Node 0.10.33

I did also another change to the code, which adds support for older node.
Do you need it? It uglifies the code a bit and adds dependency to Promise library

Failed to reproduce inlineKeyboard/button example

I checked out the examples at:
https://github.com/mullwar/telebot/blob/master/examples/keyboard.js

but unfortunately, could not get the bot to render an inline keyboard or button.

Env: Mac OS. Telegram Desktop v 1.1.2

e.g.

bot.on('/inlineKeyboard', msg => {

    let replyMarkup = bot.inlineKeyboard([
        [
            bot.inlineButton('callback', {callback: 'this_is_data'}),
            bot.inlineButton('inline', {inline: 'some query'})
        ], [
            bot.inlineButton('url', {url: 'https://telegram.org'})
        ]
    ]);

    return bot.sendMessage(msg.from.id, 'Inline keyboard example.', {replyMarkup});

});

image

== or ==

bot.on('/buttons', msg => {

    let replyMarkup = bot.keyboard([
        [bot.button('contact', 'Your contact'), bot.button('location', 'Your location')],
        ['/back', '/hide']
    ], {resize: true});

    return bot.sendMessage(msg.from.id, 'Button example.', {replyMarkup});

});

image

Question: Shall I activate any option setting in order to allow the bot to reply with buttons/keyboards?
It seems simple and straightforward, but I got stuck.
My other custom commands work just fine.

P.S:
The only time I partially succeeded was the code sample from this issue:
#29 (comment)

bot.on('/testkeys', msg => {
  const chatId = msg.chat.id;

  let markup = bot.keyboard([
      ['hello button']
    ], { resize: true, once: true });

    return bot.sendMessage(chatId, 'Hello :)', { markup });

});

image

Thank you in advance 🍻

Не работает webhook

Добрый день!

Не работает webhook.js из примера (ngrok работает).

Вставил token,ip и поменял название для сгенерированных ключей. Ключи с другими библиотеками работают (проверял для Telegram под Nodejs и Python).

const bot = new TeleBot({
token: '12345678:FGGRGRGfcdefefUIOPbbb',
webhook: {
// Self-signed certificate:
key: './webhook_pkey.pem',
cert: './webhook_cert.pem',
url: 'https://95.12.34.56',
host: '0.0.0.0',
port: 443
}
});

В консоли показывается установка webhook и старт безопасного сервера, а дальше тишина. На присланные команды не отвечает.

[bot.webhook] set to "https://95.12.34.56/12345678:FGGRGRGfcdefefUIOPbbb"
[bot.webhook] started secure server on "0.0.0.0:443"

Override 'text' event

i got two events, one for /hello command, and one for text message type. But every time i use the /hello command, the response from text events also called. How can i avoid this?

Cannot send image as buffer

When I'm sending the image as buffer server returns 400 code with an error like: "Incorrect format, image must be .png .jpg .tiff...", I've tried to fix it by myself by adding "mime type" and filename with extension but it's didn't worked for me.

Minimum amount of code to reproduce(requies valid image named "node-small.jpg" in "data" folder):

const fs = require('fs');

let buffer = fs.readFileSync(`${__dirname}/data/node-small.jpg`);
bot.sendPhoto(USER, buffer).catch(err => console.log(err));

bug? title ignored in Audio Messages

This is the example where I am trying to "change"/write the title of the audio file:

bot.on(['/material'], (msg) => {
var maxNumberElements = 20;
var index = randomIntInc(0,maxNumberElements);
var groupID = '113,129';
var endpoint = 'http://mydomain.com/api/podcast/bygroup?active=true&group=' +
groupID + '&limit=' + maxNumberElements + '&radio=' + radioID + '&sort=startDate%20DESC';
var urlPodcast = '';
var titlePodcast = '';

request
    .get(endpoint)
    .set('Accept', 'application/json')
    .set('Authorization', 'Bearer ' + token4API)
    .end(function(error, response) {
        if (error) {
            console.log('MaratonRadioBot error: ' + error);
        }
        urlPodcast = webAddrRoot4mp3 + response.body[index].mp3Url;
        titlePodcast = response.body[index].title;
        console.log('Titulo del ultimo podcast: ' + titlePodcast);
        console.log('URL del ultimo podcast: ' + urlPodcast);
        bot.sendMessage(msg.from.id, "Descargando el podcast: " + titlePodcast + "...");
        return bot.sendAudio(msg.from.id, urlPodcast, {title: titlePodcast});
});

});

In the console I can see the title and the url of the mp3, but when this code is executed, the title is always took from the metadata of the mp3, not from my variable "titlePodcast".
Could you give me some insight?
Thanks in advaced!

How to distinguish location event from a reply to an ask for location?

I my code I need to ask a location for a specific purpose, so I use the ask plugin with something like :

...
bot.sendMessage(id, 'Please attach your location here!', {ask: 'location'});
...
bot.on('ask.location', msg => { ... } );
...

It works perfectly, however I also have another piece of code that trigger on every 'location' event at the same time of the 'ask.location' event :

bot.on('location', msg => { ... } );

Is there a way to avoid the last when the location is in reply of a question ('ask.location')? What is your advice?

Sending silent messages is not working

I'm trying to send a message without it sending a notification, I use the code below. It doesn't matter if I set notification to true or false, a notification will always be send. Am I using the wrong name for the object key or is it in fact failing?

bot.sendMessage(config.telegramGroupID, "Some message", {parseMode: "markdown", replyToMessage: null, replyMarkup: null, notification: false, webPreview: true});

Message Identified Not specified

I have this event:

bot.on('/help', msg => {
    
    return bot.sendMessage(msg.from.id, 'Getting time...').then(re => {
        var chatId = msg.from.id;
        var msgId = re.result.message_id;
        bot.editText(
            { chatId , msgId }, `edited`,
            { parse: 'html' }
        ).catch(error => console.log('Error:', error));   
    });
});

i want to edit the response of my bot, but I always receive this message error:
Bad Request: Message Identified Not specified

But when I print in console the message_id of the response it exists!.

Is Something wrong with the code?

keyboardbutton on chat when pressed

is it possible when i click button then what i press is show on chat field,
for example
if there is a button keyboard [1] [2] [3]
when i click on [1], 1 is shown on chat field not on chat screen as default
and when i click [3][2][1], chat field become 321 and when i press enter 321 is shown
on the screen...
and is it possible?
@kosmodrey @G07cha @Pyriaxis

cannot find module

hmm, when i add new module like this on script
bot.use(require('modules/ask.js')) and running it;

it say error : cannot find module 'modules/ask.js' anyone ever got this error?

channel created and info about channel

hi.tnx in advance for ur amazing telebot.
in message event we have 'channelCreated' event.i think that it doesn't work properly.what is that and how to use it.
suppose my bot added to channel how can i access to their info like admin user, membercount, title,...
how can i authorize admin user of channel send pv to me.

Context

Hi there,

let's say I have the following code:

bot.on('/start', msg => {
  let markup = bot.inlineKeyboard([
    [
      bot.inlineButton('Search by name', { callback: '/search_name' }),
      bot.inlineButton('Search by fullname, { callback: '/search_fullname' }),
    ]
  ]);

  return bot.sendMessage(msg.from.id, `Please choose one option`, { markup });
});

bot.on('callbackQuery', function(msg) {

  // Send confirm
  bot.answerCallback(msg.id);

  let response;
  if(msg.data === '/search_name') {
    response = `Please enter a name`;
  } else if(msg.data === '/search_fullname') {
    response = `Please enter a full name`;
  }

  return bot.sendMessage(msg.from.id, response);
});

bot.on('text', msg => {

   // How can I know here is it a name or full name search?
});

I need to know the user's context, what did he choose on previous step

Is it possible with this library?

Instance of Bot

Can u explain me how can I call the connection of the bot in multiple js files?
I have two routes, telegram.js and ask.js that uses the telebot library
I have a connection to the bot in a file:

const TeleBot = require('telebot');
const telegramConstants = require("../../config/config");
const bot = new TeleBot({
    token: telegramConstants.botToken,
    polling: { // Optional. Use polling.
        interval: 60, // Optional. How often check updates (in ms).
        timeout: 0, // Optional. Update polling timeout (0 - short polling).
        limit: 100, // Optional. Limits the number of updates to be retrieved.
        retryTimeout: 1000, // Optional. Reconnecting timeout (in ms).
        allowedUpdates: [] // Optional. List the types of updates you want your bot to receive. Specify an empty list to receive all updates regardless of type.
    }
});

bot.connect();
module.exports = bot;

And I call it in my two js files but it creates a new instance for every call.

sin titulo

Its possible to use one instance of the telebot in my two files?

Send own contact via inline buttons and button labels without '/'

Two simple questions:

  1. is it possible to send my own contact via an inline buttons? Something like
        let markup = bot.inlineKeyboard([
          [
            // Button in first row with command callback
            bot.inlineButton('Send Contact', { callback: 'contact' }),
          ],
          [
            // Second row with regular command button
            bot.inlineButton('back', { callback: '/back' })
          ]
        ]);
  1. is it possible to have button labels without the '/' bar? Like
let markup = bot.keyboard(
          [
            [bot.button("contact", "send contact")],
            ["back"]
          ]
          , { resize: true }
        );

bot.on( ["/back"]  , msg => {
    let markup = ....;
  return bot.sendMessage(msg.from.id, "Menu", {markup});
});

Thanks!

how to get contact number with bot.on event 'contact' ?

how can i get user phone number with bot on event contact ?
is it a way to get it ?

bot.on('contact', (msg,info)=>{
const id = msg.from.id;
let day = msg.text;
console.log(info);
return bot.sendMessage(
id, 'thanks for contact number'
);
});

Name button

Hi,

I would like to change the name of the buttons , so that when the user clicks the button is passed to the BOT button command .

Example

...

bot.on('/buttons', msg => {


  let markup = bot.keyboard([
    [bot.button ('/ex1','/ex1'), bot.button('/ex2', '/ex2')],

...

necessary that the button is called button1 and the command to be sent is /ex1
There is this possibility ?

Thank you

Send Message without Event

Hi mullwar

Many thanks for your awesome API!

I'm trying to use your API to send simple notifications without an event and I'm using following code:
bot.sendMessage(<user-id>, "message");

But I get following error:
(node:5735) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): [object Object]

I've created the bot object as following:
const TeleBot = require('telebot'); const bot = new TeleBot({ token: '<token>, // Required. Telegram Bot API token. webhook: { // Optional. Use webhook instead of polling. key: './cert/key.pem', // Optional. Private key for server. cert: './cert/cert.pem', // Optional. Public key. url: 'https://127.0.0.1', // HTTPS url to send updates to. host: '127.0.0.1', // Webhook server host. port: 88 // Server port. } });

I'm listening via an express server.

Could you help me out?

Thank you very much!!

Download a document

I want to download a document. I'm using bot.getFile method but the result object does not have "file_path". how can i do this? (I'm new to node)

Hi, help me

/home/ubuntu/workspace/node_modules/telebot/index.js:165
for (var update of data) {
^^
SyntaxError: Unexpected identifier
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/home/ubuntu/workspace/telebot/server.js:1:77)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)

is markup only avaliable for one event only?

i wonder is it true that telebot just accept one markup on one event only?
this is work for first markup but dont with other markup on else statement....

for example
bot.on('text', msg =>{
if (msg.text=="yes")
{ let markup = bot.keyboard([
['test yoyow']
], { resize: true})
return bot.sendMessage(
msg.from.id, 'yoyow' ,{ask : 'day', markup, parse: 'html'}
}
else
{
let markup = bot.keyboard([
['test yayai']
], { resize: true})
return bot.sendMessage(
msg.from.id, 'yayai' ,{ask : 'day', markup, parse: 'html'}
}
}
})

Unexpected Character {

When I launch my script that requires Telebot I keep getting:

/node_modules/telebot/lib/telebot.js:86
      let { url, cert } = this.webhook;
          ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/renevlugt/Development/albys_bot/index.js:4:17)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)

bot.start

TypeError: bot.start is not a function

Help me, I am newbie at all...

Keyboard & Button

Здравствуй,
не мог бы ты привести пример кода для формирования клавиатуры и кнопок, использующий твои кастомные методы?

Метод getFile возвращает неправильный url

Мой код

bot.on('photo', msg => {
  console.log(msg);
  let id = msg.from.id;
  let file_id = msg.photo[0].file_id;
  console.log('file_id', file_id);
  
  return bot.getFile(file_id).then(x => {
    console.log("GetFileResp", x);
    bot.sendMessage(id, 'File Link: ${ x.fileLink }');
  });
});

Вывод

{ message_id: 48,
  from: { id: ******, first_name: 'Pavel', last_name: '*' },
  chat: 
   { id: ******,
     first_name: 'Pavel',
     last_name: '*',
     type: 'private' },
  date: 1491734458,
  photo: 
   [ { file_id: 'AgADAgADyqcxGxMUUUu8UWjZauY_gQFNtw0ABKdvTbkKjg0KHP0BAAEC',
       file_size: 310,
       width: 90,
       height: 48 },
     { file_id: 'AgADAgADyqcxGxMUUUu8UWjZauY_gQFNtw0ABCOUaDKWXy_jG_0BAAEC',
       file_size: 326,
       width: 106,
       height: 56 } ] }
file_id AgADAgADyqcxGxMUUUu8UWjZauY_gQFNtw0ABKdvTbkKjg0KHP0BAAEC
GetFileResp { file_id: 'AgADAgADyqcxGxMUUUu8UWjZauY_gQFNtw0ABKdvTbkKjg0KHP0BAAEC',
  file_size: 310,
  file_path: 'photos/file_1.jpg',
  fileLink: 'undefinedphotos/file_1.jpg' }

Community Group

mullwar than you.
You wrapper is great.
What do you think about create telegram group when developers can talk with each other?

Double on server

hii, i think i got some issue,

when i upload my bot on server the output is always double, but when it come to localhost the bot is run normaly...
someone got issue with me?

UnhandledPromiseRejectionWarning: Unhandled promise rejection

Hi!

I use that method bot.on('callbackQuery', (msg) => {...}) to update inlineButtons, but if set same buttons like last time - I catch nodejs error:
(node:11721) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): [object Object] (node:11721) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Could you help to resolve this issue?

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.