Giter VIP home page Giter VIP logo

node-telegram-bot-api's Introduction

Node.js Telegram Bot API

Node.js module to interact with the official Telegram Bot API.

Bot API npm package Build Status Coverage Status

https://telegram.me/node_telegram_bot_api https://t.me/+nc3A9Hs1S81mYzdk https://telegram.me/Yago_Perez

๐Ÿ“ฆ Install

npm i node-telegram-bot-api

โœ๏ธ Note: If you use Typescript you can install this package that contains type definitions for this library

npm install --save-dev @types/node-telegram-bot-api

๐Ÿš€ Usage

const TelegramBot = require('node-telegram-bot-api');

// replace the value below with the Telegram token you receive from @BotFather
const token = 'YOUR_TELEGRAM_BOT_TOKEN';

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});

// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;
  const resp = match[1]; // the captured "whatever"

  // send back the matched "whatever" to the chat
  bot.sendMessage(chatId, resp);
});

// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
  const chatId = msg.chat.id;

  // send a message to the chat acknowledging receipt of their message
  bot.sendMessage(chatId, 'Received your message');
});

๐Ÿ“š Documentation

Note: Development is done against the development branch. Code for the latest release resides on the master branch. Experimental features reside on the experimental branch.

๐Ÿ’ญ Community

We thank all the developers in the Open-Source community who continuously take their time and effort in advancing this project. See our list of contributors.

We have a Telegram channel where we post updates on the Project. Head over and subscribe!

We also have a Telegram group to discuss issues related to this library.

Some things built using this library that might interest you:

  • tgfancy: A fancy, higher-level wrapper for Telegram Bot API
  • node-telegram-bot-api-middleware: Middleware for node-telegram-bot-api
  • teleirc: A simple Telegram โ†” IRC gateway
  • bot-brother: Node.js library to help you easily create telegram bots
  • redbot: A Node-RED plugin to create telegram bots visually
  • node-telegram-keyboard-wrapper: A wrapper to improve keyboards structures creation through a more easy-to-see way (supports Inline Keyboards, Reply Keyboard, Remove Keyboard and Force Reply)
  • beetube-bot: A telegram bot for music, videos, movies, EDM tracks, torrent downloads, files and more.
  • telegram-inline-calendar: Date and time picker and inline calendar for Node.js telegram bots.
  • telegram-captcha: Telegram bot to protect Telegram groups from automatic bots.

๐Ÿ‘ฅ Contributors

License

The MIT License (MIT)

Copyright ยฉ 2019 Yago

node-telegram-bot-api's People

Contributors

alexandercerutti avatar avvs avatar capacitorset avatar chris54721 avatar coac avatar crisbal avatar danielperez9430 avatar desunit avatar evolun avatar exl avatar gochomugo avatar heavenvolkoff avatar iiroj avatar illyism avatar jishnu7 avatar kamikazechaser avatar knock-in avatar koloboid avatar preco21 avatar reyy avatar saeedhei avatar sp3rick avatar tinsaedev avatar tjhorner avatar tketa avatar toniop99 avatar universome avatar vds13 avatar waterloo avatar yagop 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  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

node-telegram-bot-api's Issues

The Offset Infinite Loop

Hi
My bot has been stuck in infinite loop and it's not responding anymore, what's problem?
here is the stack trace:

Unhandled rejection Error: 403 {"ok":false,"error_code":403,"description":"Error: Bot was kicked from a chat"}
    at /Users/vahid/Desktop/node_modules/node-telegram-bot-api/src/telegram.js:72:15
    at tryCatcher (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/util.js:26:23)
    at Promise._settlePromiseFromHandler (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:503:31)
    at Promise._settlePromiseAt (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:577:18)
    at Promise._settlePromises (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:693:14)
    at Async._drainQueue (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:123:16)
    at Async._drainQueues (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:133:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:15:14)
    at processImmediate [as _immediateCallback] (timers.js:367:17)
Unhandled rejection Error: 403 {"ok":false,"error_code":403,"description":"Error: Bot was kicked from a chat"}
    at /Users/vahid/Desktop/node_modules/node-telegram-bot-api/src/telegram.js:72:15
    at tryCatcher (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/util.js:26:23)
    at Promise._settlePromiseFromHandler (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:503:31)
    at Promise._settlePromiseAt (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:577:18)
    at Promise._settlePromises (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:693:14)
    at Async._drainQueue (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:123:16)
    at Async._drainQueues (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:133:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/Users/vahid/Desktop/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:15:14)
    at processImmediate [as _immediateCallback] (timers.js:367:17)

Send image as Buffer

I want send a photo from Buffer, but now, I must save it to a file and then send file path.

Webhook issue

Hi

I generated certificate
openssl genrsa -out key.pem 2048
openssl req -new -sha256 -key key.pem -out crt.pem

but my bot scratch with

_tls_common.js:132
c.context.setCert(options.cert);
^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Error (native)
at Object.createSecureContext (_tls_common.js:132:17)
at Server (_tls_wrap.js:598:25)
at new Server (https.js:36:14)
at Object.exports.createServer (https.js:56:10)
at new TelegramBotWebHook (/Users/cedricboussicaud/projects/packbot/node_modules/node-telegram-bot-api/src/telegramWebHook.js:23:29)
at new TelegramBot (/Users/cedricboussicaud/projects/packbot/node_modules/node-telegram-bot-api/src/telegram.js:53:21)
at Object. (/Users/cedricboussicaud/projects/packbot/app.js:20:11)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3

Thank you for helping

Enhancement for bad requests.

Wouldn't be useful to let the user handle in a different way the bad request on the server?

https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramWebHook.js#L42

Why this? in production with heroku you can't listen on more than one single port process.env.PORT. And this would be pretty useful if your app should handle also requests from client and not just the telegram webhooks.

My advice is to expose a new method like bot.onBadRequest(function(req, res) { ... }) that let the user handles all the non-matching HTTP requests.

sendMessage Callback

I would like to know if there is a way to setup a callback for the method sendMessage. This way i will know when the message was sent.

Thanks

SyntaxError on Raspberry Pi

Hi!
I tried to use my Raspberry Pi Model B (running raspbian and node v4.2.3) as telegram-bot but it won't work. When running the bot on Windows or Mac everything works just fine.

  1. Here's the error I am getting when sending a message via bot.sendMessage():
Unhandled rejection SyntaxError: Unexpected token <
    at Object.parse (native)
    at /home/development/DukesFotobot/node_modules/node-telegram-bot-api/src/telegram.js:113:23
    at tryCatcher (/home/development/DukesFotobot/node_modules/bluebird/js/main/util.js:26:23)
    at Promise._settlePromiseFromHandler (/home/development/DukesFotobot/node_modules/bluebird/js/main/promise.js:507:31)
    at Promise._settlePromiseAt (/home/development/DukesFotobot/node_modules/bluebird/js/main/promise.js:581:18)
    at Promise._settlePromises (/home/development/DukesFotobot/node_modules/bluebird/js/main/promise.js:697:14)
    at Async._drainQueue (/home/development/DukesFotobot/node_modules/bluebird/js/main/async.js:123:16)
    at Async._drainQueues (/home/development/DukesFotobot/node_modules/bluebird/js/main/async.js:133:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/home/development/DukesFotobot/node_modules/bluebird/js/main/async.js:15:14)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
  1. In addition to not being able to send messages, the bot won't even receive messages (onText is not being called).

If you have any ideas on this, I would be very thankful for a reply.

Cheers,
dj2bee

sendDocument returns 400 if URL has query param

I'm trying to send out a document/ photo/ audio file from a URL that query parameters behind its path (eg. http://example.com/getfile.php?id=101) and its returning me an Error 400.

bot.sendDocument(chatId, request('http://www.ilsny.com/mysite/viewfile.php?id=35'));
{
  "ok": false,
  "error_code": 400,
  "description": "Error: Bad Request: there is no document in request"
}

Conversely the same call with a URL that doesnt have parameters works just fine:

bot.sendDocument(chatId, request('http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg'));

The only work around I have is to make a request for the file, write to fs, and call sendDocument with that local filename. It works but its not ideal as its much slower and eats my bandwidth.

Stickers will crash!

Receiving a sticker will put the bot in an infinite loop. It will error with the offset, never update the offset position and continuously try and fail.

send BytesIO instead of file

I have a file that is stored in a <type '_io.BytesIO'> and try to send it with either sendDocument or sendPicture, but there is an error in
https://github.com/nickoala/telepot/blob/master/telepot/__init__.py#L198
The function only check if the type is a file and not other byteobjects.

image = io.BytesIO(get_image()) #pipes an image
print type(image)
#<type '_io.BytesIO'>
bot.sendDocument(user, image) # This doesn't work. Get the error below.

"""Output:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 379, in handle
    callback(update['message'])
  File "./telegram_daemon.py", line 133, in handle
    bot.sendDocument(user, image)
  File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 303, in sendDocument
    return self._sendFile(document, 'document', {'chat_id': chat_id, 'reply_to_message_id': reply_to_message_id, 'reply_markup': reply_markup})
  File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 294, in _sendFile
    return self._parse(r)
  File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 244, in _parse
    raise BadHTTPResponse(response.status_code, response.text)
BadHTTPResponse: (414, u'<html>\r\n<head><title>414 Request-URI Too Large</title></head>\r\n<body bgcolor="white">\r\n<center><h1>414 Request-URI Too Large</h1></center>\r\n<hr><center>nginx/1.9.1</center>\r\n</body>\r\n</html>\r\n')
"""

sendMessage happens before sendPhoto even it is nested.

Hello. I think I have encountered something interesting. If I write this:

bot.sendPhoto(user.chat_id, imagePath).then(
    bot.sendMessage(user.chat_id, responseMessage, options)
);

In telegram I receive first MESSAGE and then only PHOTO. Do I have misunderstanding of javascript promises? Or is there other method to send multiple messages from backend one after another?

Offset Issue if Error

If the first message received back has a problem (Such as a group chat that kicked the bot) the offset will not update.

You will be stuck in an endless loop with offset being 0.

As a temporary fix for myself, i edited the source and added my offset in and now my bot is working again. @ExcuseBot

on('message') issue

Hi, I'm using your code just to test my bot, and thanks for this!

Btw in method:

bot.on('message', function (msg) { ... }

arrives text message only, have you any idea?

sendPhoto issue

Hi,

I am facing issues with the sendPhoto method.

// line 83
bot.sendPhoto(msg.chat.id, 'xkcd.png', { caption: "hi" } ) 

I am getting the following error :

Unhandled rejection TypeError: undefined is not a function
  at FormData._multiPartHeader (C:\Users\Christophe\workspace\thousandbot\node_modules\request\node_modules\form-data\lib\form_data.js:185:47)
  at FormData.append (C:\Users\Christophe\workspace\thousandbot\node_modules\request\node_modules\form-data\lib\form_data.js:42:21)
  at appendFormValue (C:\Users\Christophe\workspace\thousandbot\node_modules\request\request.js:337:21)
  at Request.init (C:\Users\Christophe\workspace\thousandbot\node_modules\request\request.js:350:11)
  at new Request (C:\Users\Christophe\workspace\thousandbot\node_modules\request\request.js:140:8)
  at request (C:\Users\Christophe\workspace\thousandbot\node_modules\request\index.js:55:10)
  at tryCatcher (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\node_modules\bluebird\js\main\util.js:26:23)
  at ret (<anonymous>:14:23)
  at [object Object].TelegramBot._request (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\src\telegram.js:101:10)
  at [object Object].TelegramBot.sendPhoto (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\src\telegram.js:265:15)
  at Object.callback (C:\Users\Christophe\workspace\thousandbot\app.coffee:83:9)
  at C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\src\telegram.js:87:15
  at Array.forEach (native)
  at [object Object].TelegramBot._processUpdate (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\src\telegram.js:82:32)
  at C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\src\telegramPolling.js:39:12
  at Array.forEach (native)
  at C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\src\telegramPolling.js:33:13
  at tryCatcher (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\node_modules\bluebird\js\main\util.js:26:23)
  at Promise._settlePromiseFromHandler (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\node_modules\bluebird\js\main\promise.js:507:31)
  at Promise._settlePromiseAt (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\node_modules\bluebird\js\main\promise.js:581:18)
  at Promise._settlePromises (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\node_modules\bluebird\js\main\promise.js:697:14)
  at Async._drainQueue (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\node_modules\bluebird\js\main\async.js:123:16)
  at Async._drainQueues (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\node_modules\bluebird\js\main\async.js:133:10)
  at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\Christophe\workspace\thousandbot\node_modules\node-telegram-bot-api\node_modules\bluebird\js\main\async.js:15:14)
  at processImmediate [as _immediateCallback] (timers.js:367:17)

Additional remarks:

  • The bot is correctly running and set up
  • The file xkcd.png is in the same directory as my script. It is a valid image with correct access rights
  • I have tried to replace "xkcd.png" with
    • "./xkcd.png"
    • fs.createReadStream("xkcd.png")
    • __dirname + "/xkcd.png"
    • __dirname + "\\xkcd.png" (I am on windows)
    • __dirname.replace(/\//g, '/') + "/xkcd.png"

But any of these forms gives me the exact same error.

  • msg.chat.id is a valid telegram chat id

Any help appreciated!

Thanks

Node-red

Hi. Has anyone tested the use of the module within node-red?
I declared globally the module within the settings.js of node-red, and I put the following sample code in a function node:

var TelegramBot = context.global.telegram;
var token = 'my-bot-token';
var bot = new TelegramBot(token, {polling: true});
bot.on('message', function (msg) {
var chatId = msg.chat.id;
var testMsg = "test message";
bot.sendMessage(chatId, testMsg, {caption: "I'm a bot!"});
});

But the debugger gives me the following error:

Unhandled rejection Error: 409 {"ok":false,"error_code":409,"description":"Error: Conflict: terminated by other long poll or webhook"}
at /usr/local/lib/node_modules/node-red/node_modules/node-telegram-bot-api/src/telegram.js:131:15
at tryCatcher (/usr/local/lib/node_modules/node-red/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/util.js:24:31)
at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/node-red/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:489:31)
at Promise._settlePromiseAt (/usr/local/lib/node_modules/node-red/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:565:18)
at Promise._settlePromises (/usr/local/lib/node_modules/node-red/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:681:14)
at Async._drainQueue (/usr/local/lib/node_modules/node-red/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:123:16)
at Async._drainQueues (/usr/local/lib/node_modules/node-red/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:133:10)
at Async.drainQueues (/usr/local/lib/node_modules/node-red/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:15:14)
at process._tickCallback (node.js:442:13)

Thanks!

Setting initial polling offset

Would it be possible to set the initial poling offset at startup?
I would really like to be able to store the last processed message id in a database and ensure that I don't miss any messages that come in during down time.

If you want, I could probably figure it out and submit a pull request, if I can find the time.

manage commands

hi,
what is the best way to manage list of commands and replies?
now I'm filling the app with a lot of 'if'...
if command = 'xxx' {}
if command = 'xxx' {}
if command = 'xxx' {}

is there a better way, so I can manage easily the app?
thanks

Use 0ms as polling interval value

Hi!

I would like to perform long polling like this:

var bot = new TelegramBot(token, { polling: { timeout: 2000, interval: 0 } });

The problem is that 0 is replaced with default 2000ms inside the module. I can use interval: 1. It solves the issue but doesn't feel right. Is there any other way to perform long polling?

nothing append when using answerInlineQuery to send photo.

Here is my code, very basic:

bot.on('inline_query', function(query) {
  picturesToSend = [];
  // open the folder and get the number of pictures in
  var files = fs.readdirSync('./img/');
  var numberOfPics = files.length;

  // get 3 random pictures from my folder
  for (var i = 0; i < 3; i++) {
    // get a random picture name in my folder
    pictureName = files[Math.floor(Math.random() * numberOfPics)];
    // open this picture and add it to and array
    picturesToSend.push(fs.readFileSync('./img/' + pictureName));
  }
  // send the array containing 3 pictures
  bot.answerInlineQuery(query.id, picturesToSend);
});

When using answerInlineQuery nothing append and I got no error.
Of course I have activate /setinlineBot with botfather

Error sendPhoto

How to send images without the extension?

Code:
bot.sendPhoto(uid, request('http://jq.forexpf.ru/html/htmlquotes/qimg?s=SP500&h=364&w=728&z=3&gr=2&tt=0&pt=0'))

Error:

Unhandled rejection Error: 400 {"ok":false,"error_code":400,"description":"[Error]: Photo has unsupported extension. Use one of .jpg, .jpeg, .gif, .png, .tif or .bmp"}

I changed file telegram.js and photo sends succesfully

image

sendMessage with reply_markup

Having some issues with using sendMessage with reply_markup. Were you able to get this to work?

2015-07-07-165136_517x363_scrot

This is what I send if I inspect using request.bin. Maybe it needs to be a POST instead? I tried that but couldn't get it to work either.

Support for self-signed certificates in the setWebhook

On August 29, 2015 Telegram Bot API added support for self-signed certificates: upload your certificate using the certificate parameter in the setWebhook method.

My sugestion for implementation:

/**
 * Specify an url to receive incoming updates via an outgoing webHook.
 * @param {String} url URL where Telegram will make HTTP Post. Leave empty to
 * delete webHook.
 * @see https://core.telegram.org/bots/api#setwebhook
 */
TelegramBot.prototype.setWebHook = function (url) {
  var path = 'setWebHook';
  var qs = {url: url};

  if (this._WebHook)
    if (this._WebHook._webServer.cert)
      qs.formData = {
        certificate: this._WebHook._webServer.cert
      }

  return this._request(path, {qs: qs})
    .then(function (resp) {
      if (!resp) {
        throw new Error(resp);
      }
      return resp;
    });
};

duble bot message

self.api = new TelegramApi(Config.get("telegram:token"), {polling: true});
self.api.onText(//newmanager (.) (.)/, self.managerMessage.bind(self));

When user send message method managerMessage run twice. Help, please

Examples for api

Hi. Its cool library, but can u add some examples for sending messages and for to other api ?

Not receiving multiple messages in group chat

Hi,

I'm having an issue where a Bot inside a group chat (with privacy mode off) will trigger the event (such as bot.onText) only the first time but not on subsequent messages.

How to reproduce:

  1. Create / load a bot which has privacy mode turned off and invite it into a group chat (Use something similar to the example code and long-polling).
  2. Trigger the onText event by sending a message to the group-chat room manually.
  3. Wait about a minute then try to trigger the bot event again (doesn't have to be the same text). This time the bot's event will fail to fire.
  4. Trigger the event by sending a message to the bot directly (This time it will work).
  5. Do step 4 again, there is no problem.

Is anyone else able to reproduce this?

Files

Hello
Why bot can't handle many files that are sent from users? it shows message on startup but will not work anymore and messages will not received by my bot. Actually it stuck in endless loop.

Example issue

bot.onText(//echo (.+)/, function (msg, match) {
});

Maybe you mean next:

bot.onText(/echo (.+)/, function (msg, match) {
});

?

Deploy Heroku

Hi,

How can I deploy my local project to heroku?

I'm trying with Procfile: "worker: node index.js" and after 60 seconds console shows:

Process exited with status 137
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

Error: error:0906D06C:PEM routines:PEM_read_bio:no start line

Hello.

I have created crt and key files by using openssl as suggested here https://github.com/yagop/node-telegram-bot-api#webhooks

Then I wrote this code https://github.com/yagop/node-telegram-bot-api/blob/master/examples/httpsWebHook.js

And when I try to start it throws me this error:

 _tls_common.js:65
       c.context.setCert(options.cert);
                      ^

 Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
    at Error (native)
    at Object.createSecureContext (_tls_common.js:65:17)
    at Server (_tls_wrap.js:754:25)
    at new Server (https.js:24:14)
    at Object.exports.createServer (https.js:44:10)
    at new TelegramBotWebHook (d:\Phantasy  star\Mobi\Daniars_Project\Node\bot\node_modules\node-telegram-bot-api\src\telegramWebHook.js:23:29)
    at new TelegramBot (d:\Phantasy star\Mobi\Daniars_Project\Node\bot\node_modules\node-telegram-bot-api\src\telegram.js:54:21)
    at Object.<anonymous> (d:\Phantasy star\Mobi\Daniars_Project\Node\bot\main.js:19:11)
    at Module._compile (module.js:397:26)
    at Object.Module._extensions..js (module.js:404:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:429:10)
    at startup (node.js:139:18)
    at node.js:999:3

I have changed encoding of these files to UTF-8 and this does not work

Performance improvement

I'm not pretty sure about this. But when I enable keep-alive via forever option of request module, its response speed was much better.

This is simple console.time benchmarks:

// with keep-alive
t: 503.079ms 
t: 496.879ms 
t: 496.488ms 
t: 494.888ms 
t: 496.991ms 
t: 495.026ms 
t: 496.277ms 
t: 498.538ms 
t: 511.290ms 

// without keep-alive
t: 1116.574ms
t: 1013.224ms
t: 1123.053ms
t: 1045.034ms
t: 1047.880ms
t: 1087.082ms
t: 1058.906ms
t: 1080.411ms
t: 1056.534ms

Cause since this module used request, monkey patch used (ES6):

import {Request} from 'request';

const initBase = Request.prototype.init;

Request.prototype.init = function(options = {}) {
  options.forever = true;
  return Reflect.apply(initBase, this, [options]);
};

How about it?

Sending Gif example

Currently to send an animated gif you must use the method "sendDocument", but in the example you use "sendPhoto" so it's a little confused...

Anyway, I think the method "sendPhoto" would support sending animated gif, don't you?

Pd: thank you for this wonderful api!!

Unhandled rejection Error: 414 Request-URI Too Large

Hello.

I think when the message sent using sendMessage is too long it triggers the following error:

<html>
<head><title>414 Request-URI Too Large</title></head>
<body bgcolor="white">
<center><h1>414 Request-URI Too Large</h1></center>
<hr><center>nginx/1.6.2</center>
</body>
</html>

    at /home/services/node/telegram/node_modules/node-telegram-bot-api/src/telegram.js:85:15
    at tryCatcher (/home/services/node/telegram/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/util.js:26:23)
    at Promise._settlePromiseFromHandler (/home/services/node/telegram/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:503:31)
    at Promise._settlePromiseAt (/home/services/node/telegram/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:577:18)
    at Promise._settlePromises (/home/services/node/telegram/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/promise.js:693:14)
    at Async._drainQueue (/home/services/node/telegram/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:123:16)
    at Async._drainQueues (/home/services/node/telegram/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:133:10)
    at Async.drainQueues (/home/services/node/telegram/node_modules/node-telegram-bot-api/node_modules/bluebird/js/main/async.js:15:14)
    at process._tickCallback (node.js:419:13)

The bot stops working after that.

Is there any way to fix this issue (and/or report it directly to Telegram team to enable bots to send longer messages)?

Thanks in advance.

force reply

I'm tryng to use force_reply without success..
any suggestion?

if (messaggio == '/love') {
    var opts = {
        ReplyKeyboardHide: {},
        reply_to_message_id: msg.message_id,

        reply_markup: JSON.stringify({
            "keyboard": [["Ti amo alla follia"], ["Mi spiace ma non fai per me"]], 
            "one_time_keyboard": true,
            "force_reply": true
        })

    };

bot.sendMessage(chatId, 'Mi ami?', opts);
}

Possible memory leak?

Hi!
I'm running two bots on the smallest droplet on DigitalOcean (512MB), and I'm hitting 100% memory usage almost constantly. I noticed that even just running the following code causes the node process to start consuming more and more memory:

var TelegramBot = require('node-telegram-bot-api');
var nconf = require('nconf');
nconf.argv().env().file({ file: 'config.json' });
var token = nconf.get('bot_token');
var bot = new TelegramBot(token, {polling: true});

After initializing bot in the fifth line - the process's memory usage starts to grow and never stops.

I'm not sure how to debug it further. Any ideas?

I tried limiting node with --max_old_space_size but it doesn't seem to work (same behavior). Both bots are just rarely used, and anyhow it seems like the leak starts before my own code is even reached.

reply_to_message property absent in group chats

When replying to a message, the message object should look something like this:

{ message_id: 35,
  from: 
   { id: 37254959,
     first_name: 'Tom',
     last_name: 'Hansen',
     username: 'tomhansen' },
  chat: 
   { id: 37254959,
     first_name: 'Tom',
     last_name: 'Hansen',
     username: 'tomhansen',
     type: 'private' },
  date: 1453832286,
  reply_to_message: 
   { message_id: 17,
     from: 
      { id: 37254959,
        first_name: 'Hans',
        last_name: 'Tomsen',
        username: 'hanstomsen' },
     chat: 
      { id: 37254959,
        first_name: 'Tom',
        last_name: 'Hansen',
        username: 'tomhansen',
        type: 'private' },
     date: 1453829963,
     text: 'Hello.' },
  text: '/cmd1' }

The object above contains the reply_to_message property, because the message replies to another message. This works as expected when in a private chat, but not when in a group chat.

In a group chat the reply_to_message property is absent, even though the message replies to another message:

{ message_id: 35,
  from: 
   { id: 37254959,
     first_name: 'Tom',
     last_name: 'Hansen',
     username: 'tomhansen' },
  chat: { id: -25291336, title: 'Group title', type: 'group' }
  date: 1453832286,
  text: '/cmd1' }

Is there a reason for this?

listen on answer from reply_markup

hi,

Just starting to discover Telegram bot programming.
Thank you for this package it works great!

I am having issues with a bot to follow a conversation and gather the answers from users.

The conversation should be:
Bot: You are defining yourself as:
+shows a keyboard with options: Male, Female, Other+
User clicks on one of the button.
Bot receives the answer and continue to next question

To listen to user's answer I wanted use bot.on('message') but how I could make a difference between answers from question #1 and the ones from #2 ?
What would you recommend for this type of conversation?

Thanks

sendPhoto returns 400

I'm having trouble sending any type of media (photos in my case).

I'm passing a request Object (that has a readable Stream interface) to sendPhoto

client.sendPhoto(config.group_chat_id, request(someUrl));

yet telegram returns

[Error: 400 {"ok":false,"error_code":400,"description":"Error: Bad Request: there is no photo in request"}]

I noticed the same thing happens when running the examples in the repository. Has there been an API change, am I doing something wrong or is this a bug?

Promise on downloadFile

i don't understand, i try download file, but Promise dont contain filePath varible.
I use

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

    var path = bot.downloadFile(msg.photo[msg.photo.length-1].file_id, "./public/img").filePath;
    console.log(path);
});

but, i got

{ _bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: undefined }

where i lose?

Support Custom Keyboards

I'd love to see Custom Keyboard support. Perhaps you already support it, but I don't see it documented.

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.