Intial Commit

This commit is contained in:
valki
2020-10-17 18:42:50 +02:00
commit 664c6d8ca3
5892 changed files with 759183 additions and 0 deletions

View File

@@ -0,0 +1,68 @@
<!--
This template includes three sections:
1. Bug reporting
2. Feature request
3. Question
Please remove sections that do not apply to your issue
-->
<!--********************************************************************
Reporting a Bug.
*********************************************************************-->
> Bug Report
I have read:
* [Usage information](https://github.com/yagop/node-telegram-bot-api/tree/master/doc/usage.md)
* [Help information](https://github.com/yagop/node-telegram-bot-api/tree/master/doc/help.md)
I am using the latest version of the library.
### Expected Behavior
<!-- Explain what you are trying to achieve -->
### Actual Behavior
<!-- Explain what happens, contrary to what you expected -->
### Steps to reproduce the Behavior
<!-- Explain how we can reproduce the bug -->
<!--********************************************************************
Feature Request.
*********************************************************************-->
> Feature Request
I have:
* searched for such a feature request (https://github.com/yagop/node-telegram-bot-api/labels/enhancement) and found none
### Introduction
<!-- Describe what value this feature would add, and in which use case,
or scenario -->
### Example
<!-- A code snippet of how this feature would work, were it already
implemented -->
<!--********************************************************************
Question.
*********************************************************************-->
> Question
<!-- Ask your question here. Please be precise, adding as much detail
as necessary. Also, add a code snippet(s) if possible. -->

View File

@@ -0,0 +1,23 @@
<!--
Mark whichever option below applies to this PR.
For example, if your PR passes all tests, you would mark the option as so:
- [x] All tests pass
Note the 'x' in between the square brackets '[]'
-->
- [ ] All tests pass
- [ ] I have run `npm run doc`
### Description
<!-- Explain what you are trying to achieve with this PR -->
### References
<!--
Add references to other documents/pages that are relevant to this
PR, such as related issues, documentation, etc.
For example,
* Issue #1: https://github.com/yagop/node-telegram-bot-api/issues/1
* Telegram Bot API - Getting updates: https://core.telegram.org/bots/api#getting-updates
-->

View File

@@ -0,0 +1,221 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [0.40.0][0.40.0] - 2019-10-15
Added:
1. Support Bot API v4.2: (by @kamikazechaser)
* Add methods: *TelegramBot#sendPoll()*, *TelegramBot#stopPoll()*
* Support events: *poll*
1. Support Bot API v4.0: (by @kamikazechaser)
* Add methods: *TelegramBot#editMessageMedia()*, *TelegramBot#sendAnimation()*
* Support new message types: *passport_data*, *animation*
* * *
## [0.30.0][0.30.0] - 2017-12-21
Added:
1. Support Bot API v3.5: (by @GochoMugo)
* Allow `provider_data` parameter in *TelegramBot#sendInvoice*
* Add method *TelegramBot#sendMediaGroup()*
1. Support Bot API v3.4: (by @kamikazechaser)
* Add methods *TelegramBot#editMessageLiveLocation*, *TelegramBot#stopMessageLiveLocation* (#439)
* Add methods *TelegramBot#setChatStickerSet*, *TelegramBot#deleteChatStickerSet* (#440)
1. Add methods:
* *TelegramBot#getFileStream* (#442) (by @GochoMugo, requested-by @Xaqron)
1. Add options to *TelegramBot#stopPolling()* (by @GochoMugo)
1. Add `metadata` argument in `message` event (and friends e.g. `text`, `audio`, etc.) (#409) (by @jlsjonas, @GochoMugo)
1. Add forward-compatibility i.e. support future additional Telegram options (by @GochoMugo)
1. Add support for Node.js v9 (by @GochoMugo)
1. Document *TelegramBot.errors*, *TelegramBot.messageTypes* (by @GochoMugo)
Changed:
1. Update *TelegramBot#answerCallbackQuery()* signature (by @GochoMugo)
1. Improve default error logging of `polling_error` and `webhook_error` (#377)
1. Update dependencies
Deprecated:
1. Sending files: *(See [usage guide][usage-sending-files])* (by @hufan-akari, @GochoMugo)
* Error will **not** be thrown if `Buffer` is used and file-type could **not** be detected.
* Filename will **not** be set to `data.${ext}` if `Buffer` is used
* Content type will **not** default to `null` or `undefined`
Fixed:
1. Fix the offset infinite loop bug (#265, #36) (by @GochoMugo)
1. Fix game example (#449, #418) (by @MCSH)
* * *
## [0.29.0][0.29.0] - 2017-10-22
Added:
1. Add Bot API v3.2 methods:
* (#429) *TelegramBot#getStickerSet* (by @CapacitorSet, @LibertyLocked)
* (#430) *TelegramBot#uploadStickerFile* (by @CapacitorSet)
* *TelegramBot#createNewStickerSet*, *TelegramBot#addStickerToSet*, *TelegramBot#setStickerPositionInSet*, *TelegramBot#deleteStickerFromSet* (by @GochoMugo)
1. Supports API v3.3
Deprecated:
1. Auto-enabling Promise cancellation (#319) (by @GochoMugo)
* * *
## [0.28.0][0.28.0] - 2017-08-06
Added:
1. (#361) Support Bot API v3.1 (by @Lord-Protector, @kamikazechaser)
1. (#332) Support Bot API v3.0 (by @kamikazechaser, @GochoMugo)
1. Add *TelegramBot#removeTextListener()* (by @GochoMugo)
1. (#342) Add game example (by @MCSH)
1. (#315) List 'bot-brother' project in community section in README (by @saeedhei)
Changed:
1. (#367) Update *TelegramBot#answerCallbackQuery()* signature (by @mnb3000)
Fixed:
1. (#325) Fix global regexp state reset (by @Sirius-A)
1. (#363) Fix download file path on windows (by @kucherenkovova)
1. (#346) Fix anchor webhook link in docs (by @Coac)
* * *
## [0.27.1][0.27.1] - 2017-04-07
Added:
1. (#287) Add Express WebHook example (by @kamikazechaser)
Fixed:
1. (#291) Improve docs (by @preco21)
1. (#298) Fix running on Node v5 (by @jehy)
1. (#307) Fix badge links in README (by @JaakkoLipsanen)
1. Fix defaulting value of `options.polling.params.timeout` (by @GochoMugo)
1. Fix typos in Github issue template (by @GochoMugo, requested-by @GingerPlusPlus)
* * *
## [0.27.0][0.27.0] - 2017-02-10
Added:
1. Add constructor options:
* (#243) `options.polling.params` (by @GochoMugo, requested-by @sidelux)
1. Add methods:
* (#74) *TelegramBot#removeReplyListener()* (by @githugger)
1. (#283) Add proper error handling (by @GochoMugo)
1. (#272) Add health-check endpoint (by @mironov)
* `options.webHook.healthEndpoint`
1. (#152) Add test for TelegramBot#sendDocument() using 'fileOpts'
param (by @evolun)
1. Document `options.webHook.host` (by @GochoMugo)
1. (#264) Add Bot API version to README (by @kamikazechaser)
1. Add examples:
- (#271) WebHook on Heroku (by @TheBeastOfCaerbannog)
- (#274) WebHook on Zeit Now (by @Ferrari)
Changed:
1. (#147) Use *String#indexOf()*, instead of *RegExp#test()*, to
find token in webhook request (by @AVVS)
Fixed:
* Fix bug:
- (#275, #280) fix es6 syntax error on Node.js v4.x (by @crazyabdul)
- (#276) promise.warning from `request-promise` (by @GochoMugo,
reported-by @preco21)
- (#281) fix handling error during polling (by @GochoMugo,
reported-by @dimawebmaker)
- (#284) fix error during deletion of already-set webhook, during
polling (by @GochoMugo, reported-by @dcparga)
1. Fix links in documentation (by @Ni2c2k)
* * *
## [0.26.0][0.26.0] - 2017-01-20
Added:
1. Add *TelegramBot* constructor options:
* `options.https`
* `options.baseApiUrl`
* `options.filepath`
1. Add methods:
* *TelegramBot#stopPolling()*
* *TelegramBot#isPolling()*
* *TelegramBot#openWebHook()*
* *TelegramBot#closeWebHook()*
* *TelegramBot#hasOpenWebHook()*
* *TelegramBot#deleteWebHook()*
* *TelegramBot#getWebHookInfo()*
Changed:
1. Use POST requests by default
1. Ensure all relevant methods return Promises
1. Document auto-deletion of webhook during polling
1. Deprecate support for Node.js v0.12
1. Fix consistency of methods signatures
1. Rename *TelegramBot#initPolling()* to *TelegramBot#startPolling()*
* Deprecate *TelegramBot#initPolling()*
Fixed:
1. Handle error during formatting `formData`
1. Fix ES6 syntax
*Credits/Blames: Unless explicitly stated otherwise, above work was
done by @GochoMugo*
* * *
## [0.25.0][0.25.0] - 2016-12-21
Added:
1. Supports the API v2.3 updates (by @kamikazechaser)
1. Add *TelegramBot* constructor option:
* `options.request`: proxy extra request options (by @tarmolov)
* `options.onlyFirstMatch` (by @GingerPlusPlus)
1. Add methods:
* *TelegramBot#sendVenue()* (by Tketa)
* *TelegramBot#sendContact()* (by @GochoMugo)
* *TelegramBot#getGameHighScores()* (by @jishnu7)
Fixed:
1. Fix request performance issue (by @preco21)
1. Fix typos (by oflisback)
[usage-sending-files]:https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files-options
[0.25.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.25.0
[0.26.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.26.0
[0.27.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.27.0
[0.27.1]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.27.1
[0.28.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.28.0
[0.29.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.29.0
[0.30.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.30.0
[Unreleased]:https://github.com/yagop/node-telegram-bot-api/compare/v0.30.0...master

View File

@@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at mugo@forfuture.co.ke. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -0,0 +1,45 @@
# Contributing
> If you are willing to contribute, first you should know that
> I will love you and so will the Telegram Bot community.
Before proceeding any further, read the following documents:
1. [Code of Conduct][coc]
1. [License][license]
## General Information
### Creating a Github issue:
1. Ensure that your issue does **not** already exist. [Do a search](https://github.com/yagop/node-telegram-bot-api/issues).
2. Browse through [StackOverflow](https://stackoverflow.com/search?q=telegram+nodejs) and other similar platforms.
3. Should you open your issue, ensure you use the English language for
the wider target audience.
4. Be patient please.
### Updating API Reference i.e. generating `doc/api.md`
Run:
```bash
$ npm run doc
```
### Running tests
Please read `test/README.md` for more information.
### Transpiling ES2015 for older Node.js versions
We use babel to transpile the code:
```bash
$ npm run build
```
[coc]:https://github.com/yagop/node-telegram-bot-api/blob/master/CODE_OF_CONDUCT.md
[license]:https://github.com/yagop/node-telegram-bot-api/blob/master/LICENSE.md

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 Yago
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,111 @@
<h1 align="center">Node.js Telegram Bot API</h1>
<div align="center">
Node.js module to interact with the official [Telegram Bot API](https://core.telegram.org/bots/api).
[![Bot API](https://img.shields.io/badge/Bot%20API-v.4.4.0-00aced.svg?style=flat-square&logo=telegram)](https://core.telegram.org/bots/api)
[![npm package](https://img.shields.io/npm/v/node-telegram-bot-api?logo=npm&style=flat-square)](https://www.npmjs.org/package/node-telegram-bot-api)
[![Build Status](https://img.shields.io/travis/yagop/node-telegram-bot-api/master?style=flat-square&logo=travis)](https://travis-ci.org/yagop/node-telegram-bot-api)
[![Coverage Status](https://img.shields.io/codecov/c/github/yagop/node-telegram-bot-api?style=flat-square&logo=codecov)](https://codecov.io/gh/yagop/node-telegram-bot-api)
[![https://telegram.me/node_telegram_bot_api](https://img.shields.io/badge/💬%20Telegram-Channel-blue.svg?style=flat-square)](https://telegram.me/node_telegram_bot_api)
[![https://telegram.me/ntbasupport](https://img.shields.io/badge/💬%20Telegram-Group-blue.svg?style=flat-square)](https://telegram.me/ntbasupport)
[![https://telegram.me/Yago_Perez](https://img.shields.io/badge/💬%20Telegram-Yago_Perez-blue.svg?style=flat-square)](https://telegram.me/Yago_Perez)
</div>
## Install
```bash
npm install --save node-telegram-bot-api
```
## Usage
```js
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
* [Usage][usage]
* [Examples][examples]
* [Tutorials][tutorials]
* [Help Information][help]
* API Reference [api-release] / [development][api-dev] / [experimental][api-experimental])
* [Contributing to the Project][contributing]
* [Experimental Features][experimental]
_**Note**: Development is done against the **master** branch.
Code for the latest release resides on the **release** 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][contributors].
We have a [Telegram channel][tg-channel] where we post updates on
the Project. Head over and subscribe!
We also have a [Telegram group][tg-group] to discuss issues related to this library.
Some things built using this library that might interest you:
* [tgfancy](https://github.com/GochoMugo/tgfancy): A fancy, higher-level wrapper for Telegram Bot API
* [node-telegram-bot-api-middleware](https://github.com/idchlife/node-telegram-bot-api-middleware): Middleware for node-telegram-bot-api
* [teleirc](https://github.com/FruitieX/teleirc): A simple Telegram ↔ IRC gateway
* [bot-brother](https://github.com/SerjoPepper/bot-brother): Node.js library to help you easily create telegram bots
* [redbot](https://github.com/guidone/node-red-contrib-chatbot): A Node-RED plugin to create telegram bots visually
* [node-telegram-keyboard-wrapper](https://github.com/alexandercerutti/node-telegram-keyboard-wrapper): A wrapper to improve `reply_markup` structures creation in an easy way (supports Inline Keyboards, Reply Keyboard, Remove Keyboard and Force Reply)
* [node-telegram-operation-manager](https://github.com/alexandercerutti/node-telegram-operation-manager): A utility to manage replies flows and commands. Let also create custom queues for your own bot.
## License
**The MIT License (MIT)**
Copyright © 2019 Yago
[usage]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/usage.md
[examples]:https://github.com/yagop/node-telegram-bot-api/tree/master/examples
[help]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/help.md
[tutorials]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/tutorials.md
[api-dev]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/api.md
[api-release]:https://github.com/yagop/node-telegram-bot-api/tree/release/doc/api.md
[api-experimental]:https://github.com/yagop/node-telegram-bot-api/tree/experimental/doc/api.md
[contributing]:https://github.com/yagop/node-telegram-bot-api/tree/master/CONTRIBUTING.md
[contributors]:https://github.com/yagop/node-telegram-bot-api/graphs/contributors
[experimental]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/experimental.md
[tg-channel]:https://telegram.me/node_telegram_bot_api
[tg-group]:https://telegram.me/ntbasupport

View File

@@ -0,0 +1,19 @@
# API Reference
**Note:** If you are looking for available [events](usage.md#events) or usage of api, please refer [`usage.md`](usage.md).
{{#class name="TelegramBot"~}}
{{>header~}}
{{>body~}}
{{>member-index~}}
{{>members~}}
{{/class}}
* * *
[usage-sending-files-performance]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/usage.md#sending-files-performance
[setWebHook-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#telegrambotsetwebhookurl-cert
[getUpdates-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#TelegramBot+getUpdates
[getUserProfilePhotos-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#TelegramBot+getUserProfilePhotos
[answerCallbackQuery-v0.27.1]:https://github.com/yagop/node-telegram-bot-api/blob/v0.27.1/doc/api.md#TelegramBot+answerCallbackQuery
[answerCallbackQuery-v0.29.0]:https://github.com/yagop/node-telegram-bot-api/blob/v0.29.0/doc/api.md#TelegramBot+answerCallbackQuery

View File

@@ -0,0 +1,1421 @@
# API Reference
**Note:** If you are looking for available [events](usage.md#events) or usage of api, please refer [`usage.md`](usage.md).
<a name="TelegramBot"></a>
## TelegramBot
TelegramBot
**Kind**: global class
**See**: https://core.telegram.org/bots/api
* [TelegramBot](#TelegramBot)
* [new TelegramBot(token, [options])](#new_TelegramBot_new)
* _instance_
* [.on(event, listener)](#TelegramBot+on)
* [.startPolling([options])](#TelegramBot+startPolling) ⇒ <code>Promise</code>
* ~~[.initPolling([options])](#TelegramBot+initPolling) ⇒ <code>Promise</code>~~
* [.stopPolling([options])](#TelegramBot+stopPolling) ⇒ <code>Promise</code>
* [.isPolling()](#TelegramBot+isPolling) ⇒ <code>Boolean</code>
* [.openWebHook()](#TelegramBot+openWebHook) ⇒ <code>Promise</code>
* [.closeWebHook()](#TelegramBot+closeWebHook) ⇒ <code>Promise</code>
* [.hasOpenWebHook()](#TelegramBot+hasOpenWebHook) ⇒ <code>Boolean</code>
* [.getMe([options])](#TelegramBot+getMe) ⇒ <code>Promise</code>
* [.setWebHook(url, [options], [fileOptions])](#TelegramBot+setWebHook) ⇒ <code>Promise</code>
* [.deleteWebHook([options])](#TelegramBot+deleteWebHook) ⇒ <code>Promise</code>
* [.getWebHookInfo([options])](#TelegramBot+getWebHookInfo) ⇒ <code>Promise</code>
* [.getUpdates([options])](#TelegramBot+getUpdates) ⇒ <code>Promise</code>
* [.processUpdate(update)](#TelegramBot+processUpdate)
* [.sendMessage(chatId, text, [options])](#TelegramBot+sendMessage) ⇒ <code>Promise</code>
* [.answerInlineQuery(inlineQueryId, results, [options])](#TelegramBot+answerInlineQuery) ⇒ <code>Promise</code>
* [.forwardMessage(chatId, fromChatId, messageId, [options])](#TelegramBot+forwardMessage) ⇒ <code>Promise</code>
* [.sendPhoto(chatId, photo, [options], [fileOptions])](#TelegramBot+sendPhoto) ⇒ <code>Promise</code>
* [.sendAudio(chatId, audio, [options], [fileOptions])](#TelegramBot+sendAudio) ⇒ <code>Promise</code>
* [.sendDocument(chatId, doc, [options], [fileOptions])](#TelegramBot+sendDocument) ⇒ <code>Promise</code>
* [.sendSticker(chatId, sticker, [options], [fileOptions])](#TelegramBot+sendSticker) ⇒ <code>Promise</code>
* [.sendVideo(chatId, video, [options], [fileOptions])](#TelegramBot+sendVideo) ⇒ <code>Promise</code>
* [.sendAnimation(chatId, animation, [options], [fileOptions])](#TelegramBot+sendAnimation) ⇒ <code>Promise</code>
* [.sendVideoNote(chatId, videoNote, [options], [fileOptions])](#TelegramBot+sendVideoNote) ⇒ <code>Promise</code>
* [.sendVoice(chatId, voice, [options], [fileOptions])](#TelegramBot+sendVoice) ⇒ <code>Promise</code>
* [.sendChatAction(chatId, action, [options])](#TelegramBot+sendChatAction) ⇒ <code>Promise</code>
* [.kickChatMember(chatId, userId, [options])](#TelegramBot+kickChatMember) ⇒ <code>Promise</code>
* [.unbanChatMember(chatId, userId, [options])](#TelegramBot+unbanChatMember) ⇒ <code>Promise</code>
* [.restrictChatMember(chatId, userId, [options])](#TelegramBot+restrictChatMember) ⇒ <code>Promise</code>
* [.promoteChatMember(chatId, userId, [options])](#TelegramBot+promoteChatMember) ⇒ <code>Promise</code>
* [.exportChatInviteLink(chatId, [options])](#TelegramBot+exportChatInviteLink) ⇒ <code>Promise</code>
* [.setChatPhoto(chatId, photo, [options], [fileOptions])](#TelegramBot+setChatPhoto) ⇒ <code>Promise</code>
* [.deleteChatPhoto(chatId, [options])](#TelegramBot+deleteChatPhoto) ⇒ <code>Promise</code>
* [.setChatTitle(chatId, title, [options])](#TelegramBot+setChatTitle) ⇒ <code>Promise</code>
* [.setChatDescription(chatId, description, [options])](#TelegramBot+setChatDescription) ⇒ <code>Promise</code>
* [.pinChatMessage(chatId, messageId, [options])](#TelegramBot+pinChatMessage) ⇒ <code>Promise</code>
* [.unpinChatMessage(chatId, [options])](#TelegramBot+unpinChatMessage) ⇒ <code>Promise</code>
* [.answerCallbackQuery(callbackQueryId, [options])](#TelegramBot+answerCallbackQuery) ⇒ <code>Promise</code>
* [.editMessageText(text, [options])](#TelegramBot+editMessageText) ⇒ <code>Promise</code>
* [.editMessageCaption(caption, [options])](#TelegramBot+editMessageCaption) ⇒ <code>Promise</code>
* [.editMessageMedia(media, [options])](#TelegramBot+editMessageMedia) ⇒ <code>Promise</code>
* [.editMessageReplyMarkup(replyMarkup, [options])](#TelegramBot+editMessageReplyMarkup) ⇒ <code>Promise</code>
* [.getUserProfilePhotos(userId, [options])](#TelegramBot+getUserProfilePhotos) ⇒ <code>Promise</code>
* [.sendLocation(chatId, latitude, longitude, [options])](#TelegramBot+sendLocation) ⇒ <code>Promise</code>
* [.editMessageLiveLocation(latitude, longitude, [options])](#TelegramBot+editMessageLiveLocation) ⇒ <code>Promise</code>
* [.stopMessageLiveLocation([options])](#TelegramBot+stopMessageLiveLocation) ⇒ <code>Promise</code>
* [.sendVenue(chatId, latitude, longitude, title, address, [options])](#TelegramBot+sendVenue) ⇒ <code>Promise</code>
* [.sendContact(chatId, phoneNumber, firstName, [options])](#TelegramBot+sendContact) ⇒ <code>Promise</code>
* [.sendPoll(chatId, question, pollOptions, [options])](#TelegramBot+sendPoll) ⇒ <code>Promise</code>
* [.stopPoll(chatId, pollId, [options])](#TelegramBot+stopPoll) ⇒ <code>Promise</code>
* [.getFile(fileId, [options])](#TelegramBot+getFile) ⇒ <code>Promise</code>
* [.getFileLink(fileId, [options])](#TelegramBot+getFileLink) ⇒ <code>Promise</code>
* [.getFileStream(fileId, [options])](#TelegramBot+getFileStream) ⇒ <code>stream.Readable</code>
* [.downloadFile(fileId, downloadDir, [options])](#TelegramBot+downloadFile) ⇒ <code>Promise</code>
* [.onText(regexp, callback)](#TelegramBot+onText)
* [.removeTextListener(regexp)](#TelegramBot+removeTextListener) ⇒ <code>Object</code>
* [.onReplyToMessage(chatId, messageId, callback)](#TelegramBot+onReplyToMessage) ⇒ <code>Number</code>
* [.removeReplyListener(replyListenerId)](#TelegramBot+removeReplyListener) ⇒ <code>Object</code>
* [.getChat(chatId, [options])](#TelegramBot+getChat) ⇒ <code>Promise</code>
* [.getChatAdministrators(chatId, [options])](#TelegramBot+getChatAdministrators) ⇒ <code>Promise</code>
* [.getChatMembersCount(chatId, [options])](#TelegramBot+getChatMembersCount) ⇒ <code>Promise</code>
* [.getChatMember(chatId, userId, [options])](#TelegramBot+getChatMember) ⇒ <code>Promise</code>
* [.leaveChat(chatId, [options])](#TelegramBot+leaveChat) ⇒ <code>Promise</code>
* [.setChatStickerSet(chatId, stickerSetName, [options])](#TelegramBot+setChatStickerSet) ⇒ <code>Promise</code>
* [.deleteChatStickerSet(chatId, [options])](#TelegramBot+deleteChatStickerSet) ⇒ <code>Promise</code>
* [.sendGame(chatId, gameShortName, [options])](#TelegramBot+sendGame) ⇒ <code>Promise</code>
* [.setGameScore(userId, score, [options])](#TelegramBot+setGameScore) ⇒ <code>Promise</code>
* [.getGameHighScores(userId, [options])](#TelegramBot+getGameHighScores) ⇒ <code>Promise</code>
* [.deleteMessage(chatId, messageId, [options])](#TelegramBot+deleteMessage) ⇒ <code>Promise</code>
* [.sendInvoice(chatId, title, description, payload, providerToken, startParameter, currency, prices, [options])](#TelegramBot+sendInvoice) ⇒ <code>Promise</code>
* [.answerShippingQuery(shippingQueryId, ok, [options])](#TelegramBot+answerShippingQuery) ⇒ <code>Promise</code>
* [.answerPreCheckoutQuery(preCheckoutQueryId, ok, [options])](#TelegramBot+answerPreCheckoutQuery) ⇒ <code>Promise</code>
* [.getStickerSet(name, [options])](#TelegramBot+getStickerSet) ⇒ <code>Promise</code>
* [.uploadStickerFile(userId, pngSticker, [options], [fileOptions])](#TelegramBot+uploadStickerFile) ⇒ <code>Promise</code>
* [.createNewStickerSet(userId, name, title, pngSticker, emojis, [options], [fileOptions])](#TelegramBot+createNewStickerSet) ⇒ <code>Promise</code>
* [.addStickerToSet(userId, name, pngSticker, emojis, [options], [fileOptions])](#TelegramBot+addStickerToSet) ⇒ <code>Promise</code>
* [.setStickerPositionInSet(sticker, position, [options])](#TelegramBot+setStickerPositionInSet) ⇒ <code>Promise</code>
* [.deleteStickerFromSet(sticker, [options])](#TelegramBot+deleteStickerFromSet) ⇒ <code>Promise</code>
* [.sendMediaGroup(chatId, media, [options])](#TelegramBot+sendMediaGroup) ⇒ <code>Promise</code>
* _static_
* [.errors](#TelegramBot.errors) : <code>Object</code>
* [.messageTypes](#TelegramBot.messageTypes) : <code>Array.&lt;String&gt;</code>
* [.Promise](#TelegramBot.Promise)
<a name="new_TelegramBot_new"></a>
### new TelegramBot(token, [options])
Both request method to obtain messages are implemented. To use standard polling, set `polling: true`
on `options`. Notice that [webHook](https://core.telegram.org/bots/api#setwebhook) will need a SSL certificate.
Emits `message` when a message arrives.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| token | <code>String</code> | | Bot Token |
| [options] | <code>Object</code> | | |
| [options.polling] | <code>Boolean</code> \| <code>Object</code> | <code>false</code> | Set true to enable polling or set options. If a WebHook has been set, it will be deleted automatically. |
| [options.polling.timeout] | <code>String</code> \| <code>Number</code> | <code>10</code> | *Deprecated. Use `options.polling.params` instead*. Timeout in seconds for long polling. |
| [options.polling.interval] | <code>String</code> \| <code>Number</code> | <code>300</code> | Interval between requests in miliseconds |
| [options.polling.autoStart] | <code>Boolean</code> | <code>true</code> | Start polling immediately |
| [options.polling.params] | <code>Object</code> | | Parameters to be used in polling API requests. See https://core.telegram.org/bots/api#getupdates for more information. |
| [options.polling.params.timeout] | <code>Number</code> | <code>10</code> | Timeout in seconds for long polling. |
| [options.webHook] | <code>Boolean</code> \| <code>Object</code> | <code>false</code> | Set true to enable WebHook or set options |
| [options.webHook.host] | <code>String</code> | <code>&quot;0.0.0.0&quot;</code> | Host to bind to |
| [options.webHook.port] | <code>Number</code> | <code>8443</code> | Port to bind to |
| [options.webHook.key] | <code>String</code> | | Path to file with PEM private key for webHook server. The file is read **synchronously**! |
| [options.webHook.cert] | <code>String</code> | | Path to file with PEM certificate (public) for webHook server. The file is read **synchronously**! |
| [options.webHook.pfx] | <code>String</code> | | Path to file with PFX private key and certificate chain for webHook server. The file is read **synchronously**! |
| [options.webHook.autoOpen] | <code>Boolean</code> | <code>true</code> | Open webHook immediately |
| [options.webHook.https] | <code>Object</code> | | Options to be passed to `https.createServer()`. Note that `options.webHook.key`, `options.webHook.cert` and `options.webHook.pfx`, if provided, will be used to override `key`, `cert` and `pfx` in this object, respectively. See https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener for more information. |
| [options.webHook.healthEndpoint] | <code>String</code> | <code>&quot;/healthz&quot;</code> | An endpoint for health checks that always responds with 200 OK |
| [options.onlyFirstMatch] | <code>Boolean</code> | <code>false</code> | Set to true to stop after first match. Otherwise, all regexps are executed |
| [options.request] | <code>Object</code> | | Options which will be added for all requests to telegram api. See https://github.com/request/request#requestoptions-callback for more information. |
| [options.baseApiUrl] | <code>String</code> | <code>&quot;https://api.telegram.org&quot;</code> | API Base URl; useful for proxying and testing |
| [options.filepath] | <code>Boolean</code> | <code>true</code> | Allow passing file-paths as arguments when sending files, such as photos using `TelegramBot#sendPhoto()`. See [usage information][usage-sending-files-performance] for more information on this option and its consequences. |
| [options.badRejection] | <code>Boolean</code> | <code>false</code> | Set to `true` **if and only if** the Node.js version you're using terminates the process on unhandled rejections. This option is only for *forward-compatibility purposes*. |
<a name="TelegramBot+on"></a>
### telegramBot.on(event, listener)
Add listener for the specified [event](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events).
This is the usual `emitter.on()` method.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- [Available events](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events)
- https://nodejs.org/api/events.html#events_emitter_on_eventname_listener
| Param | Type |
| --- | --- |
| event | <code>String</code> |
| listener | <code>function</code> |
<a name="TelegramBot+startPolling"></a>
### telegramBot.startPolling([options]) ⇒ <code>Promise</code>
Start polling.
Rejects returned promise if a WebHook is being used by this instance.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [options] | <code>Object</code> | | |
| [options.restart] | <code>Boolean</code> | <code>true</code> | Consecutive calls to this method causes polling to be restarted |
<a name="TelegramBot+initPolling"></a>
### ~~telegramBot.initPolling([options]) ⇒ <code>Promise</code>~~
***Deprecated***
Alias of `TelegramBot#startPolling()`. This is **deprecated**.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
| Param | Type |
| --- | --- |
| [options] | <code>Object</code> |
<a name="TelegramBot+stopPolling"></a>
### telegramBot.stopPolling([options]) ⇒ <code>Promise</code>
Stops polling after the last polling request resolves.
Multiple invocations do nothing if polling is already stopped.
Returning the promise of the last polling request is **deprecated**.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | Options |
| [options.cancel] | <code>Boolean</code> | Cancel current request |
| [options.reason] | <code>String</code> | Reason for stopping polling |
<a name="TelegramBot+isPolling"></a>
### telegramBot.isPolling() ⇒ <code>Boolean</code>
Return true if polling. Otherwise, false.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
<a name="TelegramBot+openWebHook"></a>
### telegramBot.openWebHook() ⇒ <code>Promise</code>
Open webhook.
Multiple invocations do nothing if webhook is already open.
Rejects returned promise if Polling is being used by this instance.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
<a name="TelegramBot+closeWebHook"></a>
### telegramBot.closeWebHook() ⇒ <code>Promise</code>
Close webhook after closing all current connections.
Multiple invocations do nothing if webhook is already closed.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**Returns**: <code>Promise</code> - promise
<a name="TelegramBot+hasOpenWebHook"></a>
### telegramBot.hasOpenWebHook() ⇒ <code>Boolean</code>
Return true if using webhook and it is open i.e. accepts connections.
Otherwise, false.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
<a name="TelegramBot+getMe"></a>
### telegramBot.getMe([options]) ⇒ <code>Promise</code>
Returns basic information about the bot in form of a `User` object.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getme
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+setWebHook"></a>
### telegramBot.setWebHook(url, [options], [fileOptions]) ⇒ <code>Promise</code>
Specify an url to receive incoming updates via an outgoing webHook.
This method has an [older, compatible signature][setWebHook-v0.25.0]
that is being deprecated.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- https://core.telegram.org/bots/api#setwebhook
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| url | <code>String</code> | URL where Telegram will make HTTP Post. Leave empty to delete webHook. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [options.certificate] | <code>String</code> \| <code>stream.Stream</code> | PEM certificate key (public). |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+deleteWebHook"></a>
### telegramBot.deleteWebHook([options]) ⇒ <code>Promise</code>
Use this method to remove webhook integration if you decide to
switch back to getUpdates. Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#deletewebhook
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getWebHookInfo"></a>
### telegramBot.getWebHookInfo([options]) ⇒ <code>Promise</code>
Use this method to get current webhook status.
On success, returns a [WebhookInfo](https://core.telegram.org/bots/api#webhookinfo) object.
If the bot is using getUpdates, will return an object with the
url field empty.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getwebhookinfo
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getUpdates"></a>
### telegramBot.getUpdates([options]) ⇒ <code>Promise</code>
Use this method to receive incoming updates using long polling.
This method has an [older, compatible signature][getUpdates-v0.25.0]
that is being deprecated.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getupdates
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+processUpdate"></a>
### telegramBot.processUpdate(update)
Process an update; emitting the proper events and executing regexp
callbacks. This method is useful should you be using a different
way to fetch updates, other than those provided by TelegramBot.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#update
| Param | Type |
| --- | --- |
| update | <code>Object</code> |
<a name="TelegramBot+sendMessage"></a>
### telegramBot.sendMessage(chatId, text, [options]) ⇒ <code>Promise</code>
Send text message.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendmessage
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| text | <code>String</code> | Text of the message to be sent |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+answerInlineQuery"></a>
### telegramBot.answerInlineQuery(inlineQueryId, results, [options]) ⇒ <code>Promise</code>
Send answers to an inline query.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#answerinlinequery
| Param | Type | Description |
| --- | --- | --- |
| inlineQueryId | <code>String</code> | Unique identifier of the query |
| results | <code>Array.&lt;InlineQueryResult&gt;</code> | An array of results for the inline query |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+forwardMessage"></a>
### telegramBot.forwardMessage(chatId, fromChatId, messageId, [options]) ⇒ <code>Promise</code>
Forward messages of any kind.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| fromChatId | <code>Number</code> \| <code>String</code> | Unique identifier for the chat where the original message was sent |
| messageId | <code>Number</code> \| <code>String</code> | Unique message identifier |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+sendPhoto"></a>
### telegramBot.sendPhoto(chatId, photo, [options], [fileOptions]) ⇒ <code>Promise</code>
Send photo
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- https://core.telegram.org/bots/api#sendphoto
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| photo | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path or a Stream. Can also be a `file_id` previously uploaded |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+sendAudio"></a>
### telegramBot.sendAudio(chatId, audio, [options], [fileOptions]) ⇒ <code>Promise</code>
Send audio
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- https://core.telegram.org/bots/api#sendaudio
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| audio | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+sendDocument"></a>
### telegramBot.sendDocument(chatId, doc, [options], [fileOptions]) ⇒ <code>Promise</code>
Send Document
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- https://core.telegram.org/bots/api#sendDocument
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| doc | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+sendSticker"></a>
### telegramBot.sendSticker(chatId, sticker, [options], [fileOptions]) ⇒ <code>Promise</code>
Send .webp stickers.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendsticker
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| sticker | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. Stickers are WebP format files. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+sendVideo"></a>
### telegramBot.sendVideo(chatId, video, [options], [fileOptions]) ⇒ <code>Promise</code>
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- https://core.telegram.org/bots/api#sendvideo
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| video | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path or Stream. Can also be a `file_id` previously uploaded. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+sendAnimation"></a>
### telegramBot.sendAnimation(chatId, animation, [options], [fileOptions]) ⇒ <code>Promise</code>
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- https://core.telegram.org/bots/api#sendanimation
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| animation | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+sendVideoNote"></a>
### telegramBot.sendVideoNote(chatId, videoNote, [options], [fileOptions]) ⇒ <code>Promise</code>
Use this method to send rounded square videos of upto 1 minute long.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**Info**: The length parameter is actually optional. However, the API (at time of writing) requires you to always provide it until it is fixed.
**See**
- https://core.telegram.org/bots/api#sendvideonote
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| videoNote | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path or Stream. Can also be a `file_id` previously uploaded. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+sendVoice"></a>
### telegramBot.sendVoice(chatId, voice, [options], [fileOptions]) ⇒ <code>Promise</code>
Send voice
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- https://core.telegram.org/bots/api#sendvoice
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| voice | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+sendChatAction"></a>
### telegramBot.sendChatAction(chatId, action, [options]) ⇒ <code>Promise</code>
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.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendchataction
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| action | <code>String</code> | Type of action to broadcast. |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+kickChatMember"></a>
### telegramBot.kickChatMember(chatId, userId, [options]) ⇒ <code>Promise</code>
Use this method to kick a user from a group or a supergroup.
In the case of supergroups, the user will not be able to return
to the group on their own using invite links, etc., unless unbanned
first. The bot must be an administrator in the group for this to work.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#kickchatmember
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target group or username of the target supergroup |
| userId | <code>Number</code> | Unique identifier of the target user |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+unbanChatMember"></a>
### telegramBot.unbanChatMember(chatId, userId, [options]) ⇒ <code>Promise</code>
Use this method to unban a previously kicked user in a supergroup.
The user will not return to the group automatically, but will be
able to join via link, etc. The bot must be an administrator in
the group for this to work. Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#unbanchatmember
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target group or username of the target supergroup |
| userId | <code>Number</code> | Unique identifier of the target user |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+restrictChatMember"></a>
### telegramBot.restrictChatMember(chatId, userId, [options]) ⇒ <code>Promise</code>
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. Pass True for all boolean parameters
to lift restrictions from a user. Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#restrictchatmember
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target chat or username of the target supergroup |
| userId | <code>Number</code> | Unique identifier of the target user |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+promoteChatMember"></a>
### telegramBot.promoteChatMember(chatId, userId, [options]) ⇒ <code>Promise</code>
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. Pass False for all boolean parameters to demote a user.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#promotechatmember
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target chat or username of the target supergroup |
| userId | <code>Number</code> | |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+exportChatInviteLink"></a>
### telegramBot.exportChatInviteLink(chatId, [options]) ⇒ <code>Promise</code>
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.
Returns exported invite link as String on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#exportchatinvitelink
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target chat or username of the target supergroup |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+setChatPhoto"></a>
### telegramBot.setChatPhoto(chatId, photo, [options], [fileOptions]) ⇒ <code>Promise</code>
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.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#setchatphoto
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| photo | <code>stream.Stream</code> \| <code>Buffer</code> | A file path or a Stream. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+deleteChatPhoto"></a>
### telegramBot.deleteChatPhoto(chatId, [options]) ⇒ <code>Promise</code>
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.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#deletechatphoto
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+setChatTitle"></a>
### telegramBot.setChatTitle(chatId, title, [options]) ⇒ <code>Promise</code>
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.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#setchattitle
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| title | <code>String</code> | New chat title, 1-255 characters |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+setChatDescription"></a>
### telegramBot.setChatDescription(chatId, description, [options]) ⇒ <code>Promise</code>
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.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#setchatdescription
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| description | <code>String</code> | New chat title, 1-255 characters |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+pinChatMessage"></a>
### telegramBot.pinChatMessage(chatId, messageId, [options]) ⇒ <code>Promise</code>
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.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#pinchatmessage
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| messageId | <code>Number</code> | Identifier of a message to pin |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+unpinChatMessage"></a>
### telegramBot.unpinChatMessage(chatId, [options]) ⇒ <code>Promise</code>
Use this method to unpin a message in a supergroup chat.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#unpinchatmessage
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+answerCallbackQuery"></a>
### telegramBot.answerCallbackQuery(callbackQueryId, [options]) ⇒ <code>Promise</code>
Use this method to send answers to callback queries sent from
inline keyboards. The answer will be displayed to the user as
a notification at the top of the chat screen or as an alert.
On success, True is returned.
This method has **older, compatible signatures ([1][answerCallbackQuery-v0.27.1])([2][answerCallbackQuery-v0.29.0])**
that are being deprecated.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#answercallbackquery
| Param | Type | Description |
| --- | --- | --- |
| callbackQueryId | <code>String</code> | Unique identifier for the query to be answered |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+editMessageText"></a>
### telegramBot.editMessageText(text, [options]) ⇒ <code>Promise</code>
Use this method to edit text messages sent by the bot or via
the bot (for inline bots). On success, the edited Message is
returned.
Note that you must provide one of chat_id, message_id, or
inline_message_id in your request.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#editmessagetext
| Param | Type | Description |
| --- | --- | --- |
| text | <code>String</code> | New text of the message |
| [options] | <code>Object</code> | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) |
<a name="TelegramBot+editMessageCaption"></a>
### telegramBot.editMessageCaption(caption, [options]) ⇒ <code>Promise</code>
Use this method to edit captions of messages sent by the
bot or via the bot (for inline bots). On success, the
edited Message is returned.
Note that you must provide one of chat_id, message_id, or
inline_message_id in your request.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#editmessagecaption
| Param | Type | Description |
| --- | --- | --- |
| caption | <code>String</code> | New caption of the message |
| [options] | <code>Object</code> | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) |
<a name="TelegramBot+editMessageMedia"></a>
### telegramBot.editMessageMedia(media, [options]) ⇒ <code>Promise</code>
Use this method to edit audio, document, photo, or video messages.
If a message is a part of a message album, then it can be edited only to a photo or a video.
Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded.
Use previously uploaded file via its file_id or specify a URL.
On success, the edited Message is returned.
Note that you must provide one of chat_id, message_id, or
inline_message_id in your request.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#editmessagemedia
| Param | Type | Description |
| --- | --- | --- |
| media | <code>Object</code> | A JSON-serialized object for a new media content of the message |
| [options] | <code>Object</code> | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) |
<a name="TelegramBot+editMessageReplyMarkup"></a>
### telegramBot.editMessageReplyMarkup(replyMarkup, [options]) ⇒ <code>Promise</code>
Use this method to edit only the reply markup of messages
sent by the bot or via the bot (for inline bots).
On success, the edited Message is returned.
Note that you must provide one of chat_id, message_id, or
inline_message_id in your request.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#editmessagetext
| Param | Type | Description |
| --- | --- | --- |
| replyMarkup | <code>Object</code> | A JSON-serialized object for an inline keyboard. |
| [options] | <code>Object</code> | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) |
<a name="TelegramBot+getUserProfilePhotos"></a>
### telegramBot.getUserProfilePhotos(userId, [options]) ⇒ <code>Promise</code>
Use this method to get a list of profile pictures for a user.
Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object.
This method has an [older, compatible signature][getUserProfilePhotos-v0.25.0]
that is being deprecated.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getuserprofilephotos
| Param | Type | Description |
| --- | --- | --- |
| userId | <code>Number</code> | Unique identifier of the target user |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+sendLocation"></a>
### telegramBot.sendLocation(chatId, latitude, longitude, [options]) ⇒ <code>Promise</code>
Send location.
Use this method to send point on the map.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendlocation
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| latitude | <code>Float</code> | Latitude of location |
| longitude | <code>Float</code> | Longitude of location |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+editMessageLiveLocation"></a>
### telegramBot.editMessageLiveLocation(latitude, longitude, [options]) ⇒ <code>Promise</code>
Use this method to edit live location messages sent by
the bot or via the bot (for inline bots).
Note that you must provide one of chat_id, message_id, or
inline_message_id in your request.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#editmessagelivelocation
| Param | Type | Description |
| --- | --- | --- |
| latitude | <code>Float</code> | Latitude of location |
| longitude | <code>Float</code> | Longitude of location |
| [options] | <code>Object</code> | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) |
<a name="TelegramBot+stopMessageLiveLocation"></a>
### telegramBot.stopMessageLiveLocation([options]) ⇒ <code>Promise</code>
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.
Note that you must provide one of chat_id, message_id, or
inline_message_id in your request.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#stopmessagelivelocation
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) |
<a name="TelegramBot+sendVenue"></a>
### telegramBot.sendVenue(chatId, latitude, longitude, title, address, [options]) ⇒ <code>Promise</code>
Send venue.
Use this method to send information about a venue.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendvenue
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| latitude | <code>Float</code> | Latitude of location |
| longitude | <code>Float</code> | Longitude of location |
| title | <code>String</code> | Name of the venue |
| address | <code>String</code> | Address of the venue |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+sendContact"></a>
### telegramBot.sendContact(chatId, phoneNumber, firstName, [options]) ⇒ <code>Promise</code>
Send contact.
Use this method to send phone contacts.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendcontact
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| phoneNumber | <code>String</code> | Contact's phone number |
| firstName | <code>String</code> | Contact's first name |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+sendPoll"></a>
### telegramBot.sendPoll(chatId, question, pollOptions, [options]) ⇒ <code>Promise</code>
Send poll.
Use this method to send a native poll.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendpoll
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the group/channel |
| question | <code>String</code> | Poll question, 255 char limit |
| pollOptions | <code>Array</code> | Poll options, between 2-10 options |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+stopPoll"></a>
### telegramBot.stopPoll(chatId, pollId, [options]) ⇒ <code>Promise</code>
Stop poll.
Use this method to stop a native poll.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#stoppoll
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the group/channel |
| pollId | <code>Number</code> | Identifier of the original message with the poll |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getFile"></a>
### telegramBot.getFile(fileId, [options]) ⇒ <code>Promise</code>
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 [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getfile
| Param | Type | Description |
| --- | --- | --- |
| fileId | <code>String</code> | File identifier to get info about |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getFileLink"></a>
### telegramBot.getFileLink(fileId, [options]) ⇒ <code>Promise</code>
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 [<code>TelegramBot</code>](#TelegramBot)
**Returns**: <code>Promise</code> - promise Promise which will have *fileURI* in resolve callback
**See**: https://core.telegram.org/bots/api#getfile
| Param | Type | Description |
| --- | --- | --- |
| fileId | <code>String</code> | File identifier to get info about |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getFileStream"></a>
### telegramBot.getFileStream(fileId, [options]) ⇒ <code>stream.Readable</code>
Return a readable stream for file.
`fileStream.path` is the specified file ID i.e. `fileId`.
`fileStream` emits event `info` passing a single argument i.e.
`info` with the interface `{ uri }` where `uri` is the URI of the
file on Telegram servers.
This method is a sugar extension of the [getFileLink](#TelegramBot+getFileLink) method,
which returns the full URI to the file on remote server.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**Returns**: <code>stream.Readable</code> - fileStream
| Param | Type | Description |
| --- | --- | --- |
| fileId | <code>String</code> | File identifier to get info about |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+downloadFile"></a>
### telegramBot.downloadFile(fileId, downloadDir, [options]) ⇒ <code>Promise</code>
Downloads file in the specified folder.
This method is a sugar extension of the [getFileStream](#TelegramBot+getFileStream) method,
which returns a readable file stream.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**Returns**: <code>Promise</code> - promise Promise, which will have *filePath* of downloaded file in resolve callback
| Param | Type | Description |
| --- | --- | --- |
| fileId | <code>String</code> | File identifier to get info about |
| downloadDir | <code>String</code> | Absolute path to the folder in which file will be saved |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+onText"></a>
### telegramBot.onText(regexp, callback)
Register a RegExp to test against an incomming text message.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
| Param | Type | Description |
| --- | --- | --- |
| regexp | <code>RegExp</code> | RegExp to be executed with `exec`. |
| callback | <code>function</code> | Callback will be called with 2 parameters, the `msg` and the result of executing `regexp.exec` on message text. |
<a name="TelegramBot+removeTextListener"></a>
### telegramBot.removeTextListener(regexp) ⇒ <code>Object</code>
Remove a listener registered with `onText()`.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**Returns**: <code>Object</code> - deletedListener The removed reply listener if
found. This object has `regexp` and `callback`
properties. If not found, returns `null`.
| Param | Type | Description |
| --- | --- | --- |
| regexp | <code>RegExp</code> | RegExp used previously in `onText()` |
<a name="TelegramBot+onReplyToMessage"></a>
### telegramBot.onReplyToMessage(chatId, messageId, callback) ⇒ <code>Number</code>
Register a reply to wait for a message response.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**Returns**: <code>Number</code> - id The ID of the inserted reply listener.
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | The chat id where the message cames from. |
| messageId | <code>Number</code> \| <code>String</code> | The message id to be replied. |
| callback | <code>function</code> | Callback will be called with the reply message. |
<a name="TelegramBot+removeReplyListener"></a>
### telegramBot.removeReplyListener(replyListenerId) ⇒ <code>Object</code>
Removes a reply that has been prev. registered for a message response.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**Returns**: <code>Object</code> - deletedListener The removed reply listener if
found. This object has `id`, `chatId`, `messageId` and `callback`
properties. If not found, returns `null`.
| Param | Type | Description |
| --- | --- | --- |
| replyListenerId | <code>Number</code> | The ID of the reply listener. |
<a name="TelegramBot+getChat"></a>
### telegramBot.getChat(chatId, [options]) ⇒ <code>Promise</code>
Use this method to get up to date information about the chat
(current name of the user for one-on-one conversations, current
username of a user, group or channel, etc.).
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getchat
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target chat or username of the target supergroup or channel |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getChatAdministrators"></a>
### telegramBot.getChatAdministrators(chatId, [options]) ⇒ <code>Promise</code>
Returns the administrators in a chat in form of an Array of `ChatMember` objects.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getchatadministrators
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target group or username of the target supergroup |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getChatMembersCount"></a>
### telegramBot.getChatMembersCount(chatId, [options]) ⇒ <code>Promise</code>
Use this method to get the number of members in a chat.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getchatmemberscount
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target group or username of the target supergroup |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getChatMember"></a>
### telegramBot.getChatMember(chatId, userId, [options]) ⇒ <code>Promise</code>
Use this method to get information about a member of a chat.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getchatmember
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target group or username of the target supergroup |
| userId | <code>Number</code> | Unique identifier of the target user |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+leaveChat"></a>
### telegramBot.leaveChat(chatId, [options]) ⇒ <code>Promise</code>
Leave a group, supergroup or channel.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#leavechat
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+setChatStickerSet"></a>
### telegramBot.setChatStickerSet(chatId, stickerSetName, [options]) ⇒ <code>Promise</code>
Use this method to set a new group sticker set for a supergroup.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#setchatstickerset
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) |
| stickerSetName | <code>String</code> | Name of the sticker set to be set as the group sticker set |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+deleteChatStickerSet"></a>
### telegramBot.deleteChatStickerSet(chatId, [options]) ⇒ <code>Promise</code>
Use this method to delete a group sticker set from a supergroup.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#deletechatstickerset
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+sendGame"></a>
### telegramBot.sendGame(chatId, gameShortName, [options]) ⇒ <code>Promise</code>
Use this method to send a game.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendgame
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| gameShortName | <code>String</code> | name of the game to be sent. |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+setGameScore"></a>
### telegramBot.setGameScore(userId, score, [options]) ⇒ <code>Promise</code>
Use this method to set the score of the specified user in a game.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#setgamescore
| Param | Type | Description |
| --- | --- | --- |
| userId | <code>Number</code> | Unique identifier of the target user |
| score | <code>Number</code> | New score value. |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getGameHighScores"></a>
### telegramBot.getGameHighScores(userId, [options]) ⇒ <code>Promise</code>
Use this method to get data for high score table.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getgamehighscores
| Param | Type | Description |
| --- | --- | --- |
| userId | <code>Number</code> | Unique identifier of the target user |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+deleteMessage"></a>
### telegramBot.deleteMessage(chatId, messageId, [options]) ⇒ <code>Promise</code>
Use this method to delete a message.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#deletemessage
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier of the target chat |
| messageId | <code>Number</code> | Unique identifier of the target message |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+sendInvoice"></a>
### telegramBot.sendInvoice(chatId, title, description, payload, providerToken, startParameter, currency, prices, [options]) ⇒ <code>Promise</code>
Send invoice.
Use this method to send an invoice.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#sendinvoice
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>Number</code> \| <code>String</code> | Unique identifier for the message recipient |
| title | <code>String</code> | Product name |
| description | <code>String</code> | product description |
| payload | <code>String</code> | Bot defined invoice payload |
| providerToken | <code>String</code> | Payments provider token |
| startParameter | <code>String</code> | Deep-linking parameter |
| currency | <code>String</code> | Three-letter ISO 4217 currency code |
| prices | <code>Array</code> | Breakdown of prices |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+answerShippingQuery"></a>
### telegramBot.answerShippingQuery(shippingQueryId, ok, [options]) ⇒ <code>Promise</code>
Answer shipping query..
Use this method to reply to shipping queries.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#answershippingquery
| Param | Type | Description |
| --- | --- | --- |
| shippingQueryId | <code>String</code> | Unique identifier for the query to be answered |
| ok | <code>Boolean</code> | Specify if delivery of the product is possible |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+answerPreCheckoutQuery"></a>
### telegramBot.answerPreCheckoutQuery(preCheckoutQueryId, ok, [options]) ⇒ <code>Promise</code>
Answer pre-checkout query.
Use this method to confirm shipping of a product.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#answerprecheckoutquery
| Param | Type | Description |
| --- | --- | --- |
| preCheckoutQueryId | <code>String</code> | Unique identifier for the query to be answered |
| ok | <code>Boolean</code> | Specify if every order details are ok |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+getStickerSet"></a>
### telegramBot.getStickerSet(name, [options]) ⇒ <code>Promise</code>
Use this method to get a sticker set. On success, a [StickerSet](https://core.telegram.org/bots/api#stickerset) object is returned.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#getstickerset
| Param | Type | Description |
| --- | --- | --- |
| name | <code>String</code> | Name of the sticker set |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+uploadStickerFile"></a>
### telegramBot.uploadStickerFile(userId, pngSticker, [options], [fileOptions]) ⇒ <code>Promise</code>
Use this method to upload a .png file with a sticker for later use in *createNewStickerSet* and *addStickerToSet* methods (can be used multiple
times). Returns the uploaded [File](https://core.telegram.org/bots/api#file) on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#uploadstickerfile
| Param | Type | Description |
| --- | --- | --- |
| userId | <code>Number</code> | User identifier of sticker file owner |
| pngSticker | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | A file path or a Stream. Can also be a `file_id` previously uploaded. **Png** image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+createNewStickerSet"></a>
### telegramBot.createNewStickerSet(userId, name, title, pngSticker, emojis, [options], [fileOptions]) ⇒ <code>Promise</code>
Use this method to create new sticker set owned by a user.
The bot will be able to edit the created sticker set.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#createnewstickerset
**Todo**
- [ ] Add tests for this method!
| Param | Type | Description |
| --- | --- | --- |
| userId | <code>Number</code> | User identifier of created sticker set owner |
| name | <code>String</code> | Short name of sticker set, to be used in `t.me/addstickers/` URLs (e.g., *animals*) |
| title | <code>String</code> | Sticker set title, 1-64 characters |
| pngSticker | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. |
| emojis | <code>String</code> | One or more emoji corresponding to the sticker |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+addStickerToSet"></a>
### telegramBot.addStickerToSet(userId, name, pngSticker, emojis, [options], [fileOptions]) ⇒ <code>Promise</code>
Use this method to add a new sticker to a set created by the bot.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#addstickertoset
**Todo**
- [ ] Add tests for this method!
| Param | Type | Description |
| --- | --- | --- |
| userId | <code>Number</code> | User identifier of sticker set owner |
| name | <code>String</code> | Sticker set name |
| pngSticker | <code>String</code> \| <code>stream.Stream</code> \| <code>Buffer</code> | Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px |
| emojis | <code>String</code> | One or more emoji corresponding to the sticker |
| [options] | <code>Object</code> | Additional Telegram query options |
| [fileOptions] | <code>Object</code> | Optional file related meta-data |
<a name="TelegramBot+setStickerPositionInSet"></a>
### telegramBot.setStickerPositionInSet(sticker, position, [options]) ⇒ <code>Promise</code>
Use this method to move a sticker in a set created by the bot to a specific position.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#setstickerpositioninset
**Todo**
- [ ] Add tests for this method!
| Param | Type | Description |
| --- | --- | --- |
| sticker | <code>String</code> | File identifier of the sticker |
| position | <code>Number</code> | New sticker position in the set, zero-based |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+deleteStickerFromSet"></a>
### telegramBot.deleteStickerFromSet(sticker, [options]) ⇒ <code>Promise</code>
Use this method to delete a sticker from a set created by the bot.
Returns True on success.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**: https://core.telegram.org/bots/api#deletestickerfromset
**Todo**
- [ ] Add tests for this method!
| Param | Type | Description |
| --- | --- | --- |
| sticker | <code>String</code> | File identifier of the sticker |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot+sendMediaGroup"></a>
### telegramBot.sendMediaGroup(chatId, media, [options]) ⇒ <code>Promise</code>
Use this method to send a group of photos or videos as an album.
On success, an array of the sent [Messages](https://core.telegram.org/bots/api#message)
is returned.
If you wish to [specify file options](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files),
add a `fileOptions` property to the target input in `media`.
**Kind**: instance method of [<code>TelegramBot</code>](#TelegramBot)
**See**
- https://core.telegram.org/bots/api#sendmediagroup
- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
| Param | Type | Description |
| --- | --- | --- |
| chatId | <code>String</code> | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) |
| media | <code>Array</code> | A JSON-serialized array describing photos and videos to be sent, must include 210 items |
| [options] | <code>Object</code> | Additional Telegram query options |
<a name="TelegramBot.errors"></a>
### TelegramBot.errors : <code>Object</code>
The different errors the library uses.
**Kind**: static property of [<code>TelegramBot</code>](#TelegramBot)
<a name="TelegramBot.messageTypes"></a>
### TelegramBot.messageTypes : <code>Array.&lt;String&gt;</code>
The types of message updates the library handles.
**Kind**: static property of [<code>TelegramBot</code>](#TelegramBot)
<a name="TelegramBot.Promise"></a>
### TelegramBot.Promise
Change Promise library used internally, for all existing and new
instances.
**Kind**: static property of [<code>TelegramBot</code>](#TelegramBot)
| Param | Type |
| --- | --- |
| customPromise | <code>function</code> |
**Example**
```js
const TelegramBot = require('node-telegram-bot-api');
TelegramBot.Promise = myPromise;
```
* * *
[usage-sending-files-performance]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/usage.md#sending-files-performance
[setWebHook-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#telegrambotsetwebhookurl-cert
[getUpdates-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#TelegramBot+getUpdates
[getUserProfilePhotos-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#TelegramBot+getUserProfilePhotos
[answerCallbackQuery-v0.27.1]:https://github.com/yagop/node-telegram-bot-api/blob/v0.27.1/doc/api.md#TelegramBot+answerCallbackQuery
[answerCallbackQuery-v0.29.0]:https://github.com/yagop/node-telegram-bot-api/blob/v0.29.0/doc/api.md#TelegramBot+answerCallbackQuery

View File

@@ -0,0 +1,28 @@
# Experimental
Experimental features are things we are trying out. We are **not** sure
if they'll become stable and move into the `master` branch.
Try them out and give feedback to support stabilizing them.
* [Features](#features)
* [API Reference][api-experimental]
* [Installation](#installation)
<a name="features"></a>
## features:
* Support API method `deleteMessage`
Open issues tagged `experimental`: [link](https://github.com/yagop/node-telegram-bot-api/issues?q=is%3Apr+is%3Aopen+label%3Aexperimental)
<a name="installation"></a>
## installation:
```bash
$ npm install yagop/node-telegram-bot-api#experimental
```
[api-experimental]:https://github.com/yagop/node-telegram-bot-api/tree/experimental/doc/api.md

View File

@@ -0,0 +1,150 @@
# Help Information
* [Common Pitfalls](#pitfalls)
* [FAQs](#faqs)
<a name="pitfalls"></a>
## Common Pitfalls
<a name="reply-to-message"></a>
### Failing to receive reply with `ReplyToMessage`
The user has to **manually reply** to your message, by tapping on the bot's message and select *Reply*.
Sources:
* Issue [#113](https://github.com/yagop/node-telegram-bot-api/issues/113)
<a name="faqs"></a>
## Frequently Asked Questions
> Check out [all questions ever asked][questions] on our Github Issues.
1. [How do I send GIFs?](#gifs)
1. [Why and When do I need a certificate when using WebHooks?](#webhook-cert)
1. [How do I know when a user leaves a chat?](#leave-chat)
1. [What does this error mean?](#error-meanings)
1. [How do I know the selected option in reply keyboard?](#reply-keyboard)
1. [How do I send multiple message in correct sequence?](#ordered-sending)
1. [How do I run my bot behind a proxy?](#proxy)
1. [Can you add feature X to the library?](#new-feature)
1. [Is this scalable?](#scalable)
1. [How do I listen for messages in a chat group?](#messages-in-chat)
1. [How do I know when a user blocks the bot?](#blocked-bot)
<a name="gifs"></a>
### How do I send GIFs?
You might be trying to send your animated GIFs using *TelegramBot#sendPhoto()*.
The method mostly supports static images. As noted by the community,
it seems you need to send them as documents, using *TelegramBot#sendDocument()*.
```js
bot.sendDocument(chatId, 'cat.gif');
```
Sources:
* Issue [#11](https://github.com/yagop/node-telegram-bot-api/issues/11)
<a name="webhook-cert"></a>
### Why and When do I need a certificate when using WebHooks?
*Not done. PRs welcome!*
Sources:
* Issue [#63](https://github.com/yagop/node-telegram-bot-api/issues/63)
* Issue [#125](https://github.com/yagop/node-telegram-bot-api/issues/125)
<a name="leave-chat"></a>
### How do I know when a user leaves a chat?
*Not done. PRs welcome!*
Sources:
* Issue [#248](https://github.com/yagop/node-telegram-bot-api/issues/248)
<a name="error-meanings"></a>
### What does this error mean?
* [502 Bad Gateway](https://github.com/yagop/node-telegram-bot-api/issues/377)
*Not complete. PRs welcome!*
Sources:
* Issue [#73](https://github.com/yagop/node-telegram-bot-api/issues/73)
* Issue [#99](https://github.com/yagop/node-telegram-bot-api/issues/99)
* Issue [#101](https://github.com/yagop/node-telegram-bot-api/issues/101)
* Issue [#107](https://github.com/yagop/node-telegram-bot-api/issues/107)
* Issue [#156](https://github.com/yagop/node-telegram-bot-api/issues/156)
* Issue [#170](https://github.com/yagop/node-telegram-bot-api/issues/170)
* Issue [#244](https://github.com/yagop/node-telegram-bot-api/issues/244)
<a name="reply-keyboard"></a>
### How do I know the selected option in reply keyboard?
*Not done. PRs welcome!*
Sources:
* Issue [#108](https://github.com/yagop/node-telegram-bot-api/issues/108)
<a name="ordered-sending"></a>
### How do I send multiple message in correct sequence?
*Not done. PRs welcome!*
Sources:
* Issue [#240](https://github.com/yagop/node-telegram-bot-api/issues/240)
<a name="proxy"></a>
### How do I run my bot behind a proxy?
*Not done. PRs welcome!*
Sources:
* Issue [#122](https://github.com/yagop/node-telegram-bot-api/issues/122)
* Issue [#253](https://github.com/yagop/node-telegram-bot-api/issues/253)
<a name="new-feature"></a>
### Can you add feature X to the library?
*Not done. PRs welcome!*
Sources:
* Issue [#238](https://github.com/yagop/node-telegram-bot-api/issues/238)
<a name="scalable"></a>
### Is this scalable?
*Not done. PRs welcome!*
Sources:
* Issue [#219](https://github.com/yagop/node-telegram-bot-api/issues/219)
<a name="messages-in-chat"></a>
### How do I listen for messages in a chat group?
*Not done. PRs welcome!*
Sources:
* Issue [#304](https://github.com/yagop/node-telegram-bot-api/issues/304)
<a name="blocked-bot"></a>
### How do I know when a user blocks the bot?
*Not done. PRs welcome!*
Sources:
* Issue [#273](https://github.com/yagop/node-telegram-bot-api/issues/273)
[questions]:https://github.com/yagop/node-telegram-bot-api/issues?utf8=%E2%9C%93&q=is%3Aissue%20label%3Aquestion%20

View File

@@ -0,0 +1,11 @@
# Tutorials
* [node-telegram-bot-api-tutorial by @hosein2398](https://github.com/hosein2398/node-telegram-bot-api-tutorial)
* [node-telegram-bot-api-persian-language by @saeedhei](https://github.com/saeedhei/node-telegram-bot-api-persian-language)
* [Node.JS: Делаем своего Telegram бота [RUS]](https://archakov.im/post/telegram-bot-on-nodejs.html)
* [YouTube: Пишем Telegram бота на NodeJS [RUS]](https://www.youtube.com/watch?v=RS1nmDMf69U&list=PL6AOr-PZtK-mM2QC1ixyfa5CtJZGK61aN)
* [Node.jsでTelegramのチャットボットを作る - Qiita](https://qiita.com/neetshin/items/0e2f6fa3ade41adb77bc)
* [Guía: Creación de bots de Telegram en Nodejs [ES]](https://tecnonucleous.com/creacion-de-bots-de-telegram-en-nodejs/)
* [node-telegram-bot-api-tutorial:a telegram bot helper to send templates by sms](https://github.com/vito2005/chatManagerTelegramBot)
> Send a PR with useful links **not** listed above

View File

@@ -0,0 +1,260 @@
# Usage
* [Events](#events)
* [WebHooks](#webhooks)
* [Sending files](#sending-files)
* [Error handling](#error-handling)
<a name="events"></a>
## Events
*TelegramBot* is an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
that emits the following events:
1. `message`: Received a new incoming [Message][message] of any kind
1. Depending on the properties of the [Message][message], one of these
events may **ALSO** be emitted: `text`, `audio`, `document`, `photo`,
`sticker`, `video`, `voice`, `contact`, `location`,
`new_chat_members`, `left_chat_member`, `new_chat_title`,
`new_chat_photo`, `delete_chat_photo`, `group_chat_created`,
`game`, `pinned_message`, `poll`, `migrate_from_chat_id`, `migrate_to_chat_id`,
`channel_chat_created`, `supergroup_chat_created`,
`successful_payment`, `invoice`, `video_note`
1. **Arguments**: `message` ([Message][message]), `metadata` (`{ type?:string }`)
1. `new_chat_participant`, `left_chat_participant` are **deprecated**
1. `callback_query`: Received a new incoming [Callback Query][callback-query]
1. `inline_query`: Received a new incoming [Inline Query][inline-query]
1. `chosen_inline_result`: Received result of an inline query i.e. [ChosenInlineResult][chosen-inline-result]
1. `channel_post`: Received a new incoming channel post of any kind
1. `edited_message`: Received a new version of a message that is known to the bot and was edited
1. `edited_message_text`
1. `edited_message_caption`
1. `edited_channel_post`: Received a new version of a channel post that is known to the bot and was edited
1. `edited_channel_post_text`
1. `edited_channel_post_caption`
1. `shipping_query`: Received a new incoming shipping query
1. `pre_checkout_query`: Received a new incoming pre-checkout query
1. `poll`: Received a new incoming poll
1. `polling_error`: Error occurred during polling. See [polling errors](#polling-errors).
1. `webhook_error`: Error occurred handling a webhook request. See [webhook errors](#webhook-errors).
1. `error`: Unexpected error occurred, usually fatal!
**Tip:** Its much better to listen a specific event rather than on
`message` in order to stay safe from the content.
**Tip:** Bot must be enabled on [inline mode][inline-mode] for receive some
messages.
<a name="webhooks"></a>
## WebHooks
Telegram only supports HTTPS connections to WebHooks.
Therefore, in order to set a WebHook, you will need a SSL certificate.
Since August 29, 2015 Telegram supports self-signed ones, thus, you can
generate them:
```bash
# Our private cert will be key.pem, keep this file private
$ 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` should be uploaded, when setting up
your webhook. For example,
```js
bot.setWebHook('public-url.com', {
certificate: 'path/to/crt.pem', // Path to your crt.pem
});
```
**Note:** If you encounter an error, like
`Error: error:0906D06C:PEM routines:PEM_read_bio:no start line`,
you may want to proceed to [this issue][issue-63] for more information.
<a name="sending-files"></a>
## Sending files
The library makes it easy to get started sending files. *By default*, you
may provide a **file-path** and the library will handle reading it for you.
For example,
```js
bot.sendAudio(chatId, 'path/to/audio.mp3');
```
You may also pass in a **Readable Stream** from which data will be piped.
For example,
```js
const stream = fs.createReadStream('path/to/audio.mp3');
bot.sendAudio(chatId, stream);
```
You may also pass in a **Buffer** containing the contents of your file.
For example,
```js
const buffer = fs.readFileSync('path/to/audio.mp3'); // sync! that's sad! :-( Just making a point!
bot.sendAudio(chatId, buffer);
```
If you already have a **File ID**, you earlier retrieved from Telegram,
you may pass it in, for example:
```js
const fileId = getFileIdSomehow();
bot.sendAudio(chatId, fileId);
```
Some API methods, such as *SendPhoto*, allow passing a **HTTP URL**, that
the Telegram servers will use to download the file. For example,
```js
const url = 'https://telegram.org/img/t_logo.png';
bot.sendPhoto(chatId, url);
```
If you wish to explicitly specify the filename or
[MIME type](http://en.wikipedia.org/wiki/Internet_media_type),
you may pass an additional argument as file options, like so:
```js
const fileOptions = {
// Explicitly specify the file name.
filename: 'customfilename',
// Explicitly specify the MIME type.
contentType: 'audio/mpeg',
};
bot.sendAudio(chatId, data, {}, fileOptions);
```
**NOTE:** You **MUST** provide an empty object (`{}`) in place of
*Additional Telegram query options*, if you have **no** query options
to specify. For example,
```js
// WRONG!
// 'fileOptions' will be taken as additional Telegram query options!!!
bot.sendAudio(chatId, data, fileOptions);
// RIGHT!
bot.sendAudio(chatId, data, {}, fileOptions);
```
<a name="sending-files-options"></a>
### File Options (metadata)
When sending files, the library automatically resolves
the `filename` and `contentType` properties.
**For now, this has to be manually activated using environment
variable `NTBA_FIX_350`.**
In order of highest-to-lowest precedence in searching for
a value, when resolving the `filename`:
*(`fileOptions` is the Object argument passed to the method.
The "file" argument passed to the method can be a `Stream`,
`Buffer` or `filepath`.)*
1. Is `fileOptions.filename` explictly defined?
1. Does `Stream#path` exist?
1. Is `filepath` provided?
1. Default to `"filename"`
And the `contentType`:
1. Is `fileOptions.contentType` explictly-defined?
1. Does `Stream#path` exist?
1. Try detecting file-type from the `Buffer`
1. Is `filepath` provided?
1. Is `fileOptions.filename` explicitly defined?
1. Default to `"application/octet-stream"`
<a name="sending-files-performance"></a>
### Performance Issue
To support providing file-paths to methods that send files involves
performing a file operation, i.e. *fs.existsSync()*, that checks for
the existence of the file at the provided path. While the cost of
this operation *might* be negligible in most use cases, if you want
to squeeze the best performance out of this library, you may wish to
disable this behavior.
This will mean that you will **NOT** be able to pass in file-paths.
You will have to use Streams or Buffers to provide the file contents.
Disabling this behavior:
```js
const bot = new TelegramBot(token, {
filepath: false,
});
```
<a name="error-handling"></a>
## Error handling
Every `Error` object we pass back has the properties:
* `code` (String):
* value is `EFATAL` if error was fatal e.g. network error
* value is `EPARSE` if response body could **not** be parsed
* value is `ETELEGRAM` if error was returned from Telegram servers
* `response` ([http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)):
* available if `error.code` is **not** `EFATAL`
* `response.body` (String|Object): Error response from Telegram
* type is `String` if `error.code` is `EPARSE`
* type is `Object` if `error.code` is `ETELEGRAM`
For example, sending message to a non-existent user:
```js
bot.sendMessage(nonExistentUserId, 'text').catch((error) => {
console.log(error.code); // => 'ETELEGRAM'
console.log(error.response.body); // => { ok: false, error_code: 400, description: 'Bad Request: chat not found' }
});
```
<a name="polling-errors"></a>
## Polling errors
An error may occur during polling. It is up to you to handle it
as you see fit. You may decide to crash your bot after a maximum number
of polling errors occurring. **It is all up to you.**
By default, the polling error is just logged to stderr, if you do
**not** handle this event yourself.
Listen on the `'polling_error'` event. For example,
```js
bot.on('polling_error', (error) => {
console.log(error.code); // => 'EFATAL'
});
```
<a name="webhook-errors"></a>
## WebHook errors
Just like with [polling errors](#polling-errors), you decide on how to
handle it. By default, the error is logged to stderr.
Listen on the `'webhook_error'` event. For example,
```js
bot.on('webhook_error', (error) => {
console.log(error.code); // => 'EPARSE'
});
```
[update]:https://core.telegram.org/bots/api#update
[message]:https://core.telegram.org/bots/api#message
[callback-query]:https://core.telegram.org/bots/api#callbackquery
[inline-query]:https://core.telegram.org/bots/api#inlinequery
[chosen-inline-result]:https://core.telegram.org/bots/api#choseninlineresult
[inline-mode]:https://core.telegram.org/bots/api#inline-mode
[issue-63]:https://github.com/yagop/node-telegram-bot-api/issues/63

View File

@@ -0,0 +1,13 @@
/**
* If running on Nodejs 5.x and below, we load the transpiled code.
* Otherwise, we use the ES6 code.
* We are deprecating support for Node.js v5.x and below.
*/
const majorVersion = parseInt(process.versions.node.split('.')[0], 10);
if (majorVersion <= 5) {
const deprecate = require('depd')('node-telegram-bot-api');
deprecate('Node.js v5.x and below will no longer be supported in the future');
module.exports = require('./lib/telegram');
} else {
module.exports = require('./src/telegram');
}

View File

@@ -0,0 +1,109 @@
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
exports.BaseError = function (_Error) {
_inherits(BaseError, _Error);
/**
* @class BaseError
* @constructor
* @private
* @param {String} code Error code
* @param {String} message Error message
*/
function BaseError(code, message) {
_classCallCheck(this, BaseError);
var _this = _possibleConstructorReturn(this, (BaseError.__proto__ || Object.getPrototypeOf(BaseError)).call(this, code + ': ' + message));
_this.code = code;
return _this;
}
_createClass(BaseError, [{
key: 'toJSON',
value: function toJSON() {
return {
code: this.code,
message: this.message
};
}
}]);
return BaseError;
}(Error);
exports.FatalError = function (_exports$BaseError) {
_inherits(FatalError, _exports$BaseError);
/**
* Fatal Error. Error code is `"EFATAL"`.
* @class FatalError
* @constructor
* @param {String|Error} data Error object or message
*/
function FatalError(data) {
_classCallCheck(this, FatalError);
var error = typeof data === 'string' ? null : data;
var message = error ? error.message : data;
var _this2 = _possibleConstructorReturn(this, (FatalError.__proto__ || Object.getPrototypeOf(FatalError)).call(this, 'EFATAL', message));
if (error) _this2.stack = error.stack;
return _this2;
}
return FatalError;
}(exports.BaseError);
exports.ParseError = function (_exports$BaseError2) {
_inherits(ParseError, _exports$BaseError2);
/**
* Error during parsing. Error code is `"EPARSE"`.
* @class ParseError
* @constructor
* @param {String} message Error message
* @param {http.IncomingMessage} response Server response
*/
function ParseError(message, response) {
_classCallCheck(this, ParseError);
var _this3 = _possibleConstructorReturn(this, (ParseError.__proto__ || Object.getPrototypeOf(ParseError)).call(this, 'EPARSE', message));
_this3.response = response;
return _this3;
}
return ParseError;
}(exports.BaseError);
exports.TelegramError = function (_exports$BaseError3) {
_inherits(TelegramError, _exports$BaseError3);
/**
* Error returned from Telegram. Error code is `"ETELEGRAM"`.
* @class TelegramError
* @constructor
* @param {String} message Error message
* @param {http.IncomingMessage} response Server response
*/
function TelegramError(message, response) {
_classCallCheck(this, TelegramError);
var _this4 = _possibleConstructorReturn(this, (TelegramError.__proto__ || Object.getPrototypeOf(TelegramError)).call(this, 'ETELEGRAM', message));
_this4.response = response;
return _this4;
}
return TelegramError;
}(exports.BaseError);

View File

@@ -0,0 +1,2395 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
// shims
require('array.prototype.findindex').shim(); // for Node.js v0.x
var errors = require('./errors');
var TelegramBotWebHook = require('./telegramWebHook');
var TelegramBotPolling = require('./telegramPolling');
var debug = require('debug')('node-telegram-bot-api');
var EventEmitter = require('eventemitter3');
var fileType = require('file-type');
var request = require('request-promise');
var streamedRequest = require('request');
var qs = require('querystring');
var stream = require('stream');
var mime = require('mime');
var path = require('path');
var URL = require('url');
var fs = require('fs');
var pump = require('pump');
var deprecate = require('depd')('node-telegram-bot-api');
var Promise = require('bluebird');
var _messageTypes = ['text', 'animation', 'audio', 'channel_chat_created', 'contact', 'delete_chat_photo', 'document', 'game', 'group_chat_created', 'invoice', 'left_chat_member', 'location', 'migrate_from_chat_id', 'migrate_to_chat_id', 'new_chat_members', 'new_chat_photo', 'new_chat_title', 'passport_data', 'photo', 'pinned_message', 'poll', 'sticker', 'successful_payment', 'supergroup_chat_created', 'video', 'video_note', 'voice'];
var _deprecatedMessageTypes = ['new_chat_participant', 'left_chat_participant'];
if (!process.env.NTBA_FIX_319) {
// Enable Promise cancellation.
try {
var msg = 'Automatic enabling of cancellation of promises is deprecated.\n' + 'In the future, you will have to enable it yourself.\n' + 'See https://github.com/yagop/node-telegram-bot-api/issues/319.';
deprecate(msg);
Promise.config({
cancellation: true
});
} catch (ex) {
/* eslint-disable no-console */
var _msg = 'error: Enabling Promise cancellation failed.\n' + ' Temporary fix is to load/require this library as early as possible before using any Promises.';
console.error(_msg);
throw ex;
/* eslint-enable no-console */
}
}
/**
* JSON-serialize data. If the provided data is already a String,
* return it as is.
* @private
* @param {*} data
* @return {String}
*/
function stringify(data) {
if (typeof data === 'string') {
return data;
}
return JSON.stringify(data);
}
var TelegramBot = function (_EventEmitter) {
_inherits(TelegramBot, _EventEmitter);
_createClass(TelegramBot, [{
key: 'on',
/**
* Add listener for the specified [event](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events).
* This is the usual `emitter.on()` method.
* @param {String} event
* @param {Function} listener
* @see {@link https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events|Available events}
* @see https://nodejs.org/api/events.html#events_emitter_on_eventname_listener
*/
value: function on(event, listener) {
if (_deprecatedMessageTypes.indexOf(event) !== -1) {
var url = 'https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events';
deprecate('Events ' + _deprecatedMessageTypes.join(',') + ' are deprecated. See the updated list of events: ' + url);
}
_get(TelegramBot.prototype.__proto__ || Object.getPrototypeOf(TelegramBot.prototype), 'on', this).call(this, event, listener);
}
/**
* Both request method to obtain messages are implemented. To use standard polling, set `polling: true`
* on `options`. Notice that [webHook](https://core.telegram.org/bots/api#setwebhook) will need a SSL certificate.
* Emits `message` when a message arrives.
*
* @class TelegramBot
* @constructor
* @param {String} token Bot Token
* @param {Object} [options]
* @param {Boolean|Object} [options.polling=false] Set true to enable polling or set options.
* If a WebHook has been set, it will be deleted automatically.
* @param {String|Number} [options.polling.timeout=10] *Deprecated. Use `options.polling.params` instead*.
* Timeout in seconds for long polling.
* @param {String|Number} [options.polling.interval=300] Interval between requests in miliseconds
* @param {Boolean} [options.polling.autoStart=true] Start polling immediately
* @param {Object} [options.polling.params] Parameters to be used in polling API requests.
* See https://core.telegram.org/bots/api#getupdates for more information.
* @param {Number} [options.polling.params.timeout=10] Timeout in seconds for long polling.
* @param {Boolean|Object} [options.webHook=false] Set true to enable WebHook or set options
* @param {String} [options.webHook.host="0.0.0.0"] Host to bind to
* @param {Number} [options.webHook.port=8443] Port to bind to
* @param {String} [options.webHook.key] Path to file with PEM private key for webHook server.
* The file is read **synchronously**!
* @param {String} [options.webHook.cert] Path to file with PEM certificate (public) for webHook server.
* The file is read **synchronously**!
* @param {String} [options.webHook.pfx] Path to file with PFX private key and certificate chain for webHook server.
* The file is read **synchronously**!
* @param {Boolean} [options.webHook.autoOpen=true] Open webHook immediately
* @param {Object} [options.webHook.https] Options to be passed to `https.createServer()`.
* Note that `options.webHook.key`, `options.webHook.cert` and `options.webHook.pfx`, if provided, will be
* used to override `key`, `cert` and `pfx` in this object, respectively.
* See https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener for more information.
* @param {String} [options.webHook.healthEndpoint="/healthz"] An endpoint for health checks that always responds with 200 OK
* @param {Boolean} [options.onlyFirstMatch=false] Set to true to stop after first match. Otherwise, all regexps are executed
* @param {Object} [options.request] Options which will be added for all requests to telegram api.
* See https://github.com/request/request#requestoptions-callback for more information.
* @param {String} [options.baseApiUrl="https://api.telegram.org"] API Base URl; useful for proxying and testing
* @param {Boolean} [options.filepath=true] Allow passing file-paths as arguments when sending files,
* such as photos using `TelegramBot#sendPhoto()`. See [usage information][usage-sending-files-performance]
* for more information on this option and its consequences.
* @param {Boolean} [options.badRejection=false] Set to `true`
* **if and only if** the Node.js version you're using terminates the
* process on unhandled rejections. This option is only for
* *forward-compatibility purposes*.
* @see https://core.telegram.org/bots/api
*/
}], [{
key: 'errors',
/**
* The different errors the library uses.
* @type {Object}
*/
get: function get() {
return errors;
}
/**
* The types of message updates the library handles.
* @type {String[]}
*/
}, {
key: 'messageTypes',
get: function get() {
return _messageTypes;
}
/**
* Change Promise library used internally, for all existing and new
* instances.
* @param {Function} customPromise
*
* @example
* const TelegramBot = require('node-telegram-bot-api');
* TelegramBot.Promise = myPromise;
*/
}, {
key: 'Promise',
set: function set(customPromise) {
Promise = customPromise;
}
}]);
function TelegramBot(token) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, TelegramBot);
var _this = _possibleConstructorReturn(this, (TelegramBot.__proto__ || Object.getPrototypeOf(TelegramBot)).call(this));
_this.token = token;
_this.options = options;
_this.options.polling = typeof options.polling === 'undefined' ? false : options.polling;
_this.options.webHook = typeof options.webHook === 'undefined' ? false : options.webHook;
_this.options.baseApiUrl = options.baseApiUrl || 'https://api.telegram.org';
_this.options.filepath = typeof options.filepath === 'undefined' ? true : options.filepath;
_this.options.badRejection = typeof options.badRejection === 'undefined' ? false : options.badRejection;
_this._textRegexpCallbacks = [];
_this._replyListenerId = 0;
_this._replyListeners = [];
_this._polling = null;
_this._webHook = null;
if (options.polling) {
var autoStart = options.polling.autoStart;
if (typeof autoStart === 'undefined' || autoStart === true) {
_this.startPolling();
}
}
if (options.webHook) {
var autoOpen = options.webHook.autoOpen;
if (typeof autoOpen === 'undefined' || autoOpen === true) {
_this.openWebHook();
}
}
return _this;
}
/**
* Generates url with bot token and provided path/method you want to be got/executed by bot
* @param {String} path
* @return {String} url
* @private
* @see https://core.telegram.org/bots/api#making-requests
*/
_createClass(TelegramBot, [{
key: '_buildURL',
value: function _buildURL(_path) {
return this.options.baseApiUrl + '/bot' + this.token + '/' + _path;
}
/**
* Fix 'reply_markup' parameter by making it JSON-serialized, as
* required by the Telegram Bot API
* @param {Object} obj Object; either 'form' or 'qs'
* @private
* @see https://core.telegram.org/bots/api#sendmessage
*/
}, {
key: '_fixReplyMarkup',
value: function _fixReplyMarkup(obj) {
var replyMarkup = obj.reply_markup;
if (replyMarkup && typeof replyMarkup !== 'string') {
obj.reply_markup = stringify(replyMarkup);
}
}
/**
* Make request against the API
* @param {String} _path API endpoint
* @param {Object} [options]
* @private
* @return {Promise}
*/
}, {
key: '_request',
value: function _request(_path) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!this.token) {
return Promise.reject(new errors.FatalError('Telegram Bot Token not provided!'));
}
if (this.options.request) {
Object.assign(options, this.options.request);
}
if (options.form) {
this._fixReplyMarkup(options.form);
}
if (options.qs) {
this._fixReplyMarkup(options.qs);
}
options.method = 'POST';
options.url = this._buildURL(_path);
options.simple = false;
options.resolveWithFullResponse = true;
options.forever = true;
debug('HTTP request: %j', options);
return request(options).then(function (resp) {
var data = void 0;
try {
data = resp.body = JSON.parse(resp.body);
} catch (err) {
throw new errors.ParseError('Error parsing response: ' + resp.body, resp);
}
if (data.ok) {
return data.result;
}
throw new errors.TelegramError(data.error_code + ' ' + data.description, resp);
}).catch(function (error) {
// TODO: why can't we do `error instanceof errors.BaseError`?
if (error.response) throw error;
throw new errors.FatalError(error);
});
}
/**
* Format data to be uploaded; handles file paths, streams and buffers
* @param {String} type
* @param {String|stream.Stream|Buffer} data
* @param {Object} fileOptions File options
* @param {String} [fileOptions.filename] File name
* @param {String} [fileOptions.contentType] Content type (i.e. MIME)
* @return {Array} formatted
* @return {Object} formatted[0] formData
* @return {String} formatted[1] fileId
* @throws Error if Buffer file type is not supported.
* @see https://npmjs.com/package/file-type
* @private
*/
}, {
key: '_formatSendData',
value: function _formatSendData(type, data) {
var fileOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var deprecationMessage = 'See https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files' + ' for more information on how sending files has been improved and' + ' on how to disable this deprecation message altogether.';
var filedata = data;
var filename = fileOptions.filename;
var contentType = fileOptions.contentType;
if (data instanceof stream.Stream) {
if (!filename && data.path) {
// Will be 'null' if could not be parsed.
// For example, 'data.path' === '/?id=123' from 'request("https://example.com/?id=123")'
var url = URL.parse(path.basename(data.path.toString()));
if (url.pathname) {
filename = qs.unescape(url.pathname);
}
}
} else if (Buffer.isBuffer(data)) {
if (!filename && !process.env.NTBA_FIX_350) {
deprecate('Buffers will have their filenames default to "filename" instead of "data". ' + deprecationMessage);
filename = 'data';
}
if (!contentType) {
var filetype = fileType(data);
if (filetype) {
contentType = filetype.mime;
var ext = filetype.ext;
if (ext && !process.env.NTBA_FIX_350) {
filename = filename + '.' + ext;
}
} else if (!process.env.NTBA_FIX_350) {
deprecate('An error will no longer be thrown if file-type of buffer could not be detected. ' + deprecationMessage);
throw new errors.FatalError('Unsupported Buffer file-type');
}
}
} else if (data) {
if (this.options.filepath && fs.existsSync(data)) {
filedata = fs.createReadStream(data);
if (!filename) {
filename = path.basename(data);
}
} else {
return [null, data];
}
} else {
return [null, data];
}
filename = filename || 'filename';
contentType = contentType || mime.lookup(filename);
if (process.env.NTBA_FIX_350) {
contentType = contentType || 'application/octet-stream';
} else {
deprecate('In the future, content-type of files you send will default to "application/octet-stream". ' + deprecationMessage);
}
// TODO: Add missing file extension.
return [_defineProperty({}, type, {
value: filedata,
options: {
filename: filename,
contentType: contentType
}
}), null];
}
/**
* Start polling.
* Rejects returned promise if a WebHook is being used by this instance.
* @param {Object} [options]
* @param {Boolean} [options.restart=true] Consecutive calls to this method causes polling to be restarted
* @return {Promise}
*/
}, {
key: 'startPolling',
value: function startPolling() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (this.hasOpenWebHook()) {
return Promise.reject(new errors.FatalError('Polling and WebHook are mutually exclusive'));
}
options.restart = typeof options.restart === 'undefined' ? true : options.restart;
if (!this._polling) {
this._polling = new TelegramBotPolling(this);
}
return this._polling.start(options);
}
/**
* Alias of `TelegramBot#startPolling()`. This is **deprecated**.
* @param {Object} [options]
* @return {Promise}
* @deprecated
*/
}, {
key: 'initPolling',
value: function initPolling() {
deprecate('TelegramBot#initPolling() is deprecated. Use TelegramBot#startPolling() instead.');
return this.startPolling();
}
/**
* Stops polling after the last polling request resolves.
* Multiple invocations do nothing if polling is already stopped.
* Returning the promise of the last polling request is **deprecated**.
* @param {Object} [options] Options
* @param {Boolean} [options.cancel] Cancel current request
* @param {String} [options.reason] Reason for stopping polling
* @return {Promise}
*/
}, {
key: 'stopPolling',
value: function stopPolling(options) {
if (!this._polling) {
return Promise.resolve();
}
return this._polling.stop(options);
}
/**
* Return true if polling. Otherwise, false.
* @return {Boolean}
*/
}, {
key: 'isPolling',
value: function isPolling() {
return this._polling ? this._polling.isPolling() : false;
}
/**
* Open webhook.
* Multiple invocations do nothing if webhook is already open.
* Rejects returned promise if Polling is being used by this instance.
* @return {Promise}
*/
}, {
key: 'openWebHook',
value: function openWebHook() {
if (this.isPolling()) {
return Promise.reject(new errors.FatalError('WebHook and Polling are mutually exclusive'));
}
if (!this._webHook) {
this._webHook = new TelegramBotWebHook(this);
}
return this._webHook.open();
}
/**
* Close webhook after closing all current connections.
* Multiple invocations do nothing if webhook is already closed.
* @return {Promise} promise
*/
}, {
key: 'closeWebHook',
value: function closeWebHook() {
if (!this._webHook) {
return Promise.resolve();
}
return this._webHook.close();
}
/**
* Return true if using webhook and it is open i.e. accepts connections.
* Otherwise, false.
* @return {Boolean}
*/
}, {
key: 'hasOpenWebHook',
value: function hasOpenWebHook() {
return this._webHook ? this._webHook.isOpen() : false;
}
/**
* Returns basic information about the bot in form of a `User` object.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getme
*/
}, {
key: 'getMe',
value: function getMe() {
var form = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return this._request('getMe', { form: form });
}
/**
* Specify an url to receive incoming updates via an outgoing webHook.
* This method has an [older, compatible signature][setWebHook-v0.25.0]
* that is being deprecated.
*
* @param {String} url URL where Telegram will make HTTP Post. Leave empty to
* delete webHook.
* @param {Object} [options] Additional Telegram query options
* @param {String|stream.Stream} [options.certificate] PEM certificate key (public).
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#setwebhook
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'setWebHook',
value: function setWebHook(url) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var fileOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
/* The older method signature was setWebHook(url, cert).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
var cert = void 0;
// Note: 'options' could be an object, if a stream was provided (in place of 'cert')
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object' || options instanceof stream.Stream) {
deprecate('The method signature setWebHook(url, cert) has been deprecated since v0.25.0');
cert = options;
options = {}; // eslint-disable-line no-param-reassign
} else {
cert = options.certificate;
}
var opts = {
qs: options
};
opts.qs.url = url;
if (cert) {
try {
var sendData = this._formatSendData('certificate', cert, fileOptions);
opts.formData = sendData[0];
opts.qs.certificate = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
}
return this._request('setWebHook', opts);
}
/**
* Use this method to remove webhook integration if you decide to
* switch back to getUpdates. Returns True on success.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletewebhook
*/
}, {
key: 'deleteWebHook',
value: function deleteWebHook() {
var form = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return this._request('deleteWebhook', { form: form });
}
/**
* Use this method to get current webhook status.
* On success, returns a [WebhookInfo](https://core.telegram.org/bots/api#webhookinfo) object.
* If the bot is using getUpdates, will return an object with the
* url field empty.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getwebhookinfo
*/
}, {
key: 'getWebHookInfo',
value: function getWebHookInfo() {
var form = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return this._request('getWebhookInfo', { form: form });
}
/**
* Use this method to receive incoming updates using long polling.
* This method has an [older, compatible signature][getUpdates-v0.25.0]
* that is being deprecated.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getupdates
*/
}, {
key: 'getUpdates',
value: function getUpdates() {
var form = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
/* The older method signature was getUpdates(timeout, limit, offset).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
if ((typeof form === 'undefined' ? 'undefined' : _typeof(form)) !== 'object') {
/* eslint-disable no-param-reassign, prefer-rest-params */
deprecate('The method signature getUpdates(timeout, limit, offset) has been deprecated since v0.25.0');
form = {
timeout: arguments[0],
limit: arguments[1],
offset: arguments[2]
};
/* eslint-enable no-param-reassign, prefer-rest-params */
}
return this._request('getUpdates', { form: form });
}
/**
* Process an update; emitting the proper events and executing regexp
* callbacks. This method is useful should you be using a different
* way to fetch updates, other than those provided by TelegramBot.
* @param {Object} update
* @see https://core.telegram.org/bots/api#update
*/
}, {
key: 'processUpdate',
value: function processUpdate(update) {
var _this2 = this;
debug('Process Update %j', update);
var message = update.message;
var editedMessage = update.edited_message;
var channelPost = update.channel_post;
var editedChannelPost = update.edited_channel_post;
var inlineQuery = update.inline_query;
var chosenInlineResult = update.chosen_inline_result;
var callbackQuery = update.callback_query;
var shippingQuery = update.shipping_query;
var preCheckoutQuery = update.pre_checkout_query;
var poll = update.poll;
if (message) {
debug('Process Update message %j', message);
var metadata = {};
metadata.type = TelegramBot.messageTypes.find(function (messageType) {
return message[messageType];
});
this.emit('message', message, metadata);
if (metadata.type) {
debug('Emitting %s: %j', metadata.type, message);
this.emit(metadata.type, message, metadata);
}
if (message.text) {
debug('Text message');
this._textRegexpCallbacks.some(function (reg) {
debug('Matching %s with %s', message.text, reg.regexp);
var result = reg.regexp.exec(message.text);
if (!result) {
return false;
}
// reset index so we start at the beginning of the regex each time
reg.regexp.lastIndex = 0;
debug('Matches %s', reg.regexp);
reg.callback(message, result);
// returning truthy value exits .some
return _this2.options.onlyFirstMatch;
});
}
if (message.reply_to_message) {
// Only callbacks waiting for this message
this._replyListeners.forEach(function (reply) {
// Message from the same chat
if (reply.chatId === message.chat.id) {
// Responding to that message
if (reply.messageId === message.reply_to_message.message_id) {
// Resolve the promise
reply.callback(message);
}
}
});
}
} else if (editedMessage) {
debug('Process Update edited_message %j', editedMessage);
this.emit('edited_message', editedMessage);
if (editedMessage.text) {
this.emit('edited_message_text', editedMessage);
}
if (editedMessage.caption) {
this.emit('edited_message_caption', editedMessage);
}
} else if (channelPost) {
debug('Process Update channel_post %j', channelPost);
this.emit('channel_post', channelPost);
} else if (editedChannelPost) {
debug('Process Update edited_channel_post %j', editedChannelPost);
this.emit('edited_channel_post', editedChannelPost);
if (editedChannelPost.text) {
this.emit('edited_channel_post_text', editedChannelPost);
}
if (editedChannelPost.caption) {
this.emit('edited_channel_post_caption', editedChannelPost);
}
} else if (inlineQuery) {
debug('Process Update inline_query %j', inlineQuery);
this.emit('inline_query', inlineQuery);
} else if (chosenInlineResult) {
debug('Process Update chosen_inline_result %j', chosenInlineResult);
this.emit('chosen_inline_result', chosenInlineResult);
} else if (callbackQuery) {
debug('Process Update callback_query %j', callbackQuery);
this.emit('callback_query', callbackQuery);
} else if (shippingQuery) {
debug('Process Update shipping_query %j', shippingQuery);
this.emit('shipping_query', shippingQuery);
} else if (preCheckoutQuery) {
debug('Process Update pre_checkout_query %j', preCheckoutQuery);
this.emit('pre_checkout_query', preCheckoutQuery);
} else if (poll) {
debug('Process Update poll %j', poll);
this.emit('poll', poll);
}
}
/**
* Send text message.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} text Text of the message to be sent
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendmessage
*/
}, {
key: 'sendMessage',
value: function sendMessage(chatId, text) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.text = text;
return this._request('sendMessage', { form: form });
}
/**
* Send answers to an inline query.
* @param {String} inlineQueryId Unique identifier of the query
* @param {InlineQueryResult[]} results An array of results for the inline query
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#answerinlinequery
*/
}, {
key: 'answerInlineQuery',
value: function answerInlineQuery(inlineQueryId, results) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.inline_query_id = inlineQueryId;
form.results = stringify(results);
return this._request('answerInlineQuery', { form: form });
}
/**
* Forward messages of any kind.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Number|String} fromChatId Unique identifier for the chat where the
* original message was sent
* @param {Number|String} messageId Unique message identifier
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
*/
}, {
key: 'forwardMessage',
value: function forwardMessage(chatId, fromChatId, messageId) {
var form = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
form.chat_id = chatId;
form.from_chat_id = fromChatId;
form.message_id = messageId;
return this._request('forwardMessage', { form: form });
}
/**
* Send photo
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} photo A file path or a Stream. Can
* also be a `file_id` previously uploaded
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendphoto
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'sendPhoto',
value: function sendPhoto(chatId, photo) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('photo', photo, fileOptions);
opts.formData = sendData[0];
opts.qs.photo = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendPhoto', opts);
}
/**
* Send audio
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} audio A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendaudio
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'sendAudio',
value: function sendAudio(chatId, audio) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('audio', audio, fileOptions);
opts.formData = sendData[0];
opts.qs.audio = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendAudio', opts);
}
/**
* Send Document
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} doc A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendDocument
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'sendDocument',
value: function sendDocument(chatId, doc) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('document', doc, fileOptions);
opts.formData = sendData[0];
opts.qs.document = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendDocument', opts);
}
/**
* Send .webp stickers.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} sticker A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded. Stickers are WebP format files.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendsticker
*/
}, {
key: 'sendSticker',
value: function sendSticker(chatId, sticker) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('sticker', sticker, fileOptions);
opts.formData = sendData[0];
opts.qs.sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendSticker', opts);
}
/**
* Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} video A file path or Stream.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendvideo
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'sendVideo',
value: function sendVideo(chatId, video) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('video', video, fileOptions);
opts.formData = sendData[0];
opts.qs.video = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendVideo', opts);
}
/**
* Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} animation A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendanimation
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'sendAnimation',
value: function sendAnimation(chatId, animation) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('animation', animation, fileOptions);
opts.formData = sendData[0];
opts.qs.document = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendAnimation', opts);
}
/**
* Use this method to send rounded square videos of upto 1 minute long.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} videoNote A file path or Stream.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @info The length parameter is actually optional. However, the API (at time of writing) requires you to always provide it until it is fixed.
* @see https://core.telegram.org/bots/api#sendvideonote
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'sendVideoNote',
value: function sendVideoNote(chatId, videoNote) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('video_note', videoNote, fileOptions);
opts.formData = sendData[0];
opts.qs.video_note = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendVideoNote', opts);
}
/**
* Send voice
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} voice A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendvoice
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'sendVoice',
value: function sendVoice(chatId, voice) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('voice', voice, fileOptions);
opts.formData = sendData[0];
opts.qs.voice = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendVoice', opts);
}
/**
* 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.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} action Type of action to broadcast.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendchataction
*/
}, {
key: 'sendChatAction',
value: function sendChatAction(chatId, action) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.action = action;
return this._request('sendChatAction', { form: form });
}
/**
* Use this method to kick a user from a group or a supergroup.
* In the case of supergroups, the user will not be able to return
* to the group on their own using invite links, etc., unless unbanned
* first. The bot must be an administrator in the group for this to work.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#kickchatmember
*/
}, {
key: 'kickChatMember',
value: function kickChatMember(chatId, userId) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.user_id = userId;
return this._request('kickChatMember', { form: form });
}
/**
* Use this method to unban a previously kicked user in a supergroup.
* The user will not return to the group automatically, but will be
* able to join via link, etc. The bot must be an administrator in
* the group for this to work. Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#unbanchatmember
*/
}, {
key: 'unbanChatMember',
value: function unbanChatMember(chatId, userId) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.user_id = userId;
return this._request('unbanChatMember', { form: form });
}
/**
* 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. Pass True for all boolean parameters
* to lift restrictions from a user. Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target supergroup
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#restrictchatmember
*/
}, {
key: 'restrictChatMember',
value: function restrictChatMember(chatId, userId) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.user_id = userId;
return this._request('restrictChatMember', { form: form });
}
/**
* 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. Pass False for all boolean parameters to demote a user.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target supergroup
* @param {Number} userId
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#promotechatmember
*/
}, {
key: 'promoteChatMember',
value: function promoteChatMember(chatId, userId) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.user_id = userId;
return this._request('promoteChatMember', { form: form });
}
/**
* 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.
* Returns exported invite link as String on success.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target supergroup
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#exportchatinvitelink
*/
}, {
key: 'exportChatInviteLink',
value: function exportChatInviteLink(chatId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.chat_id = chatId;
return this._request('exportChatInviteLink', { form: form });
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {stream.Stream|Buffer} photo A file path or a Stream.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#setchatphoto
*/
}, {
key: 'setChatPhoto',
value: function setChatPhoto(chatId, photo) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
var sendData = this._formatSendData('photo', photo, fileOptions);
opts.formData = sendData[0];
opts.qs.photo = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('setChatPhoto', opts);
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletechatphoto
*/
}, {
key: 'deleteChatPhoto',
value: function deleteChatPhoto(chatId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.chat_id = chatId;
return this._request('deleteChatPhoto', { form: form });
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} title New chat title, 1-255 characters
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setchattitle
*/
}, {
key: 'setChatTitle',
value: function setChatTitle(chatId, title) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.title = title;
return this._request('setChatTitle', { form: form });
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} description New chat title, 1-255 characters
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setchatdescription
*/
}, {
key: 'setChatDescription',
value: function setChatDescription(chatId, description) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.description = description;
return this._request('setChatDescription', { form: form });
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Number} messageId Identifier of a message to pin
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#pinchatmessage
*/
}, {
key: 'pinChatMessage',
value: function pinChatMessage(chatId, messageId) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.message_id = messageId;
return this._request('pinChatMessage', { form: form });
}
/**
* Use this method to unpin a message in a supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#unpinchatmessage
*/
}, {
key: 'unpinChatMessage',
value: function unpinChatMessage(chatId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.chat_id = chatId;
return this._request('unpinChatMessage', { form: form });
}
/**
* Use this method to send answers to callback queries sent from
* inline keyboards. The answer will be displayed to the user as
* a notification at the top of the chat screen or as an alert.
* On success, True is returned.
*
* This method has **older, compatible signatures ([1][answerCallbackQuery-v0.27.1])([2][answerCallbackQuery-v0.29.0])**
* that are being deprecated.
*
* @param {String} callbackQueryId Unique identifier for the query to be answered
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#answercallbackquery
*/
}, {
key: 'answerCallbackQuery',
value: function answerCallbackQuery(callbackQueryId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
/* The older method signature (in/before v0.27.1) was answerCallbackQuery(callbackQueryId, text, showAlert).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
if ((typeof form === 'undefined' ? 'undefined' : _typeof(form)) !== 'object') {
/* eslint-disable no-param-reassign, prefer-rest-params */
deprecate('The method signature answerCallbackQuery(callbackQueryId, text, showAlert) has been deprecated since v0.27.1');
form = {
callback_query_id: arguments[0],
text: arguments[1],
show_alert: arguments[2]
};
/* eslint-enable no-param-reassign, prefer-rest-params */
}
/* The older method signature (in/before v0.29.0) was answerCallbackQuery([options]).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library. */
if ((typeof callbackQueryId === 'undefined' ? 'undefined' : _typeof(callbackQueryId)) === 'object') {
/* eslint-disable no-param-reassign, prefer-rest-params */
deprecate('The method signature answerCallbackQuery([options]) has been deprecated since v0.29.0');
form = callbackQueryId;
/* eslint-enable no-param-reassign, prefer-rest-params */
} else {
form.callback_query_id = callbackQueryId;
}
return this._request('answerCallbackQuery', { form: form });
}
/**
* Use this method to edit text messages sent by the bot or via
* the bot (for inline bots). On success, the edited Message is
* returned.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {String} text New text of the message
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagetext
*/
}, {
key: 'editMessageText',
value: function editMessageText(text) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.text = text;
return this._request('editMessageText', { form: form });
}
/**
* Use this method to edit captions of messages sent by the
* bot or via the bot (for inline bots). On success, the
* edited Message is returned.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {String} caption New caption of the message
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagecaption
*/
}, {
key: 'editMessageCaption',
value: function editMessageCaption(caption) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.caption = caption;
return this._request('editMessageCaption', { form: form });
}
/**
* Use this method to edit audio, document, photo, or video messages.
* If a message is a part of a message album, then it can be edited only to a photo or a video.
* Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded.
* Use previously uploaded file via its file_id or specify a URL.
* On success, the edited Message is returned.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {Object} media A JSON-serialized object for a new media content of the message
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagemedia
*/
}, {
key: 'editMessageMedia',
value: function editMessageMedia(media) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.media = stringify(media);
return this._request('editMessageMedia', { form: form });
}
/**
* Use this method to edit only the reply markup of messages
* sent by the bot or via the bot (for inline bots).
* On success, the edited Message is returned.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {Object} replyMarkup A JSON-serialized object for an inline keyboard.
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagetext
*/
}, {
key: 'editMessageReplyMarkup',
value: function editMessageReplyMarkup(replyMarkup) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.reply_markup = replyMarkup;
return this._request('editMessageReplyMarkup', { form: form });
}
/**
* Use this method to get a list of profile pictures for a user.
* Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object.
* This method has an [older, compatible signature][getUserProfilePhotos-v0.25.0]
* that is being deprecated.
*
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getuserprofilephotos
*/
}, {
key: 'getUserProfilePhotos',
value: function getUserProfilePhotos(userId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
/* The older method signature was getUserProfilePhotos(userId, offset, limit).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
if ((typeof form === 'undefined' ? 'undefined' : _typeof(form)) !== 'object') {
/* eslint-disable no-param-reassign, prefer-rest-params */
deprecate('The method signature getUserProfilePhotos(userId, offset, limit) has been deprecated since v0.25.0');
form = {
offset: arguments[1],
limit: arguments[2]
};
/* eslint-enable no-param-reassign, prefer-rest-params */
}
form.user_id = userId;
return this._request('getUserProfilePhotos', { form: form });
}
/**
* Send location.
* Use this method to send point on the map.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Float} latitude Latitude of location
* @param {Float} longitude Longitude of location
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendlocation
*/
}, {
key: 'sendLocation',
value: function sendLocation(chatId, latitude, longitude) {
var form = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
form.chat_id = chatId;
form.latitude = latitude;
form.longitude = longitude;
return this._request('sendLocation', { form: form });
}
/**
* Use this method to edit live location messages sent by
* the bot or via the bot (for inline bots).
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {Float} latitude Latitude of location
* @param {Float} longitude Longitude of location
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagelivelocation
*/
}, {
key: 'editMessageLiveLocation',
value: function editMessageLiveLocation(latitude, longitude) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.latitude = latitude;
form.longitude = longitude;
return this._request('editMessageLiveLocation', { form: form });
}
/**
* 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.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#stopmessagelivelocation
*/
}, {
key: 'stopMessageLiveLocation',
value: function stopMessageLiveLocation() {
var form = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return this._request('stopMessageLiveLocation', { form: form });
}
/**
* Send venue.
* Use this method to send information about a venue.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Float} latitude Latitude of location
* @param {Float} longitude Longitude of location
* @param {String} title Name of the venue
* @param {String} address Address of the venue
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendvenue
*/
}, {
key: 'sendVenue',
value: function sendVenue(chatId, latitude, longitude, title, address) {
var form = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
form.chat_id = chatId;
form.latitude = latitude;
form.longitude = longitude;
form.title = title;
form.address = address;
return this._request('sendVenue', { form: form });
}
/**
* Send contact.
* Use this method to send phone contacts.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} phoneNumber Contact's phone number
* @param {String} firstName Contact's first name
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendcontact
*/
}, {
key: 'sendContact',
value: function sendContact(chatId, phoneNumber, firstName) {
var form = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
form.chat_id = chatId;
form.phone_number = phoneNumber;
form.first_name = firstName;
return this._request('sendContact', { form: form });
}
/**
* Send poll.
* Use this method to send a native poll.
*
* @param {Number|String} chatId Unique identifier for the group/channel
* @param {String} question Poll question, 255 char limit
* @param {Array} pollOptions Poll options, between 2-10 options
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendpoll
*/
}, {
key: 'sendPoll',
value: function sendPoll(chatId, question, pollOptions) {
var form = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
form.chat_id = chatId;
form.question = question;
form.options = stringify(pollOptions);
return this._request('sendPoll', { form: form });
}
/**
* Stop poll.
* Use this method to stop a native poll.
*
* @param {Number|String} chatId Unique identifier for the group/channel
* @param {Number} pollId Identifier of the original message with the poll
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#stoppoll
*/
}, {
key: 'stopPoll',
value: function stopPoll(chatId, pollId) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.message_id = pollId;
return this._request('stopPoll', { form: form });
}
/**
* 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.
*
* @param {String} fileId File identifier to get info about
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getfile
*/
}, {
key: 'getFile',
value: function getFile(fileId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.file_id = fileId;
return this._request('getFile', { form: form });
}
/**
* 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).
*
* @param {String} fileId File identifier to get info about
* @param {Object} [options] Additional Telegram query options
* @return {Promise} promise Promise which will have *fileURI* in resolve callback
* @see https://core.telegram.org/bots/api#getfile
*/
}, {
key: 'getFileLink',
value: function getFileLink(fileId) {
var _this3 = this;
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.getFile(fileId, form).then(function (resp) {
return _this3.options.baseApiUrl + '/file/bot' + _this3.token + '/' + resp.file_path;
});
}
/**
* Return a readable stream for file.
*
* `fileStream.path` is the specified file ID i.e. `fileId`.
* `fileStream` emits event `info` passing a single argument i.e.
* `info` with the interface `{ uri }` where `uri` is the URI of the
* file on Telegram servers.
*
* This method is a sugar extension of the [getFileLink](#TelegramBot+getFileLink) method,
* which returns the full URI to the file on remote server.
*
* @param {String} fileId File identifier to get info about
* @param {Object} [options] Additional Telegram query options
* @return {stream.Readable} fileStream
*/
}, {
key: 'getFileStream',
value: function getFileStream(fileId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var fileStream = new stream.PassThrough();
fileStream.path = fileId;
this.getFileLink(fileId, form).then(function (fileURI) {
fileStream.emit('info', {
uri: fileURI
});
pump(streamedRequest({ uri: fileURI }), fileStream);
}).catch(function (error) {
fileStream.emit('error', error);
});
return fileStream;
}
/**
* Downloads file in the specified folder.
*
* This method is a sugar extension of the [getFileStream](#TelegramBot+getFileStream) method,
* which returns a readable file stream.
*
* @param {String} fileId File identifier to get info about
* @param {String} downloadDir Absolute path to the folder in which file will be saved
* @param {Object} [options] Additional Telegram query options
* @return {Promise} promise Promise, which will have *filePath* of downloaded file in resolve callback
*/
}, {
key: 'downloadFile',
value: function downloadFile(fileId, downloadDir) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var resolve = void 0;
var reject = void 0;
var promise = new Promise(function (a, b) {
resolve = a;
reject = b;
});
var fileStream = this.getFileStream(fileId, form);
fileStream.on('info', function (info) {
var fileName = info.uri.slice(info.uri.lastIndexOf('/') + 1);
// TODO: Ensure fileName doesn't contains slashes
var filePath = path.join(downloadDir, fileName);
pump(fileStream, fs.createWriteStream(filePath), function (error) {
if (error) {
return reject(error);
}
return resolve(filePath);
});
});
return promise;
}
/**
* Register a RegExp to test against an incomming text message.
* @param {RegExp} regexp RegExp to be executed with `exec`.
* @param {Function} callback Callback will be called with 2 parameters,
* the `msg` and the result of executing `regexp.exec` on message text.
*/
}, {
key: 'onText',
value: function onText(regexp, callback) {
this._textRegexpCallbacks.push({ regexp: regexp, callback: callback });
}
/**
* Remove a listener registered with `onText()`.
* @param {RegExp} regexp RegExp used previously in `onText()`
* @return {Object} deletedListener The removed reply listener if
* found. This object has `regexp` and `callback`
* properties. If not found, returns `null`.
*/
}, {
key: 'removeTextListener',
value: function removeTextListener(regexp) {
var index = this._textRegexpCallbacks.findIndex(function (textListener) {
return textListener.regexp === regexp;
});
if (index === -1) {
return null;
}
return this._textRegexpCallbacks.splice(index, 1)[0];
}
/**
* Register a reply to wait for a message response.
* @param {Number|String} chatId The chat id where the message cames from.
* @param {Number|String} messageId The message id to be replied.
* @param {Function} callback Callback will be called with the reply
* message.
* @return {Number} id The ID of the inserted reply listener.
*/
}, {
key: 'onReplyToMessage',
value: function onReplyToMessage(chatId, messageId, callback) {
var id = ++this._replyListenerId;
this._replyListeners.push({
id: id,
chatId: chatId,
messageId: messageId,
callback: callback
});
return id;
}
/**
* Removes a reply that has been prev. registered for a message response.
* @param {Number} replyListenerId The ID of the reply listener.
* @return {Object} deletedListener The removed reply listener if
* found. This object has `id`, `chatId`, `messageId` and `callback`
* properties. If not found, returns `null`.
*/
}, {
key: 'removeReplyListener',
value: function removeReplyListener(replyListenerId) {
var index = this._replyListeners.findIndex(function (replyListener) {
return replyListener.id === replyListenerId;
});
if (index === -1) {
return null;
}
return this._replyListeners.splice(index, 1)[0];
}
/**
* Use this method to get up to date information about the chat
* (current name of the user for one-on-one conversations, current
* username of a user, group or channel, etc.).
* @param {Number|String} chatId Unique identifier for the target chat or username of the target supergroup or channel
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getchat
*/
}, {
key: 'getChat',
value: function getChat(chatId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.chat_id = chatId;
return this._request('getChat', { form: form });
}
/**
* Returns the administrators in a chat in form of an Array of `ChatMember` objects.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getchatadministrators
*/
}, {
key: 'getChatAdministrators',
value: function getChatAdministrators(chatId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.chat_id = chatId;
return this._request('getChatAdministrators', { form: form });
}
/**
* Use this method to get the number of members in a chat.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getchatmemberscount
*/
}, {
key: 'getChatMembersCount',
value: function getChatMembersCount(chatId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.chat_id = chatId;
return this._request('getChatMembersCount', { form: form });
}
/**
* Use this method to get information about a member of a chat.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getchatmember
*/
}, {
key: 'getChatMember',
value: function getChatMember(chatId, userId) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.user_id = userId;
return this._request('getChatMember', { form: form });
}
/**
* Leave a group, supergroup or channel.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#leavechat
*/
}, {
key: 'leaveChat',
value: function leaveChat(chatId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.chat_id = chatId;
return this._request('leaveChat', { form: form });
}
/**
* Use this method to set a new group sticker set for a supergroup.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {String} stickerSetName Name of the sticker set to be set as the group sticker set
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setchatstickerset
*/
}, {
key: 'setChatStickerSet',
value: function setChatStickerSet(chatId, stickerSetName) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.sticker_set_name = stickerSetName;
return this._request('setChatStickerSet', { form: form });
}
/**
* Use this method to delete a group sticker set from a supergroup.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletechatstickerset
*/
}, {
key: 'deleteChatStickerSet',
value: function deleteChatStickerSet(chatId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.chat_id = chatId;
return this._request('deleteChatStickerSet', { form: form });
}
/**
* Use this method to send a game.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} gameShortName name of the game to be sent.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendgame
*/
}, {
key: 'sendGame',
value: function sendGame(chatId, gameShortName) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.game_short_name = gameShortName;
return this._request('sendGame', { form: form });
}
/**
* Use this method to set the score of the specified user in a game.
* @param {Number} userId Unique identifier of the target user
* @param {Number} score New score value.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setgamescore
*/
}, {
key: 'setGameScore',
value: function setGameScore(userId, score) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.user_id = userId;
form.score = score;
return this._request('setGameScore', { form: form });
}
/**
* Use this method to get data for high score table.
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getgamehighscores
*/
}, {
key: 'getGameHighScores',
value: function getGameHighScores(userId) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.user_id = userId;
return this._request('getGameHighScores', { form: form });
}
/**
* Use this method to delete a message.
* @param {Number|String} chatId Unique identifier of the target chat
* @param {Number} messageId Unique identifier of the target message
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletemessage
*/
}, {
key: 'deleteMessage',
value: function deleteMessage(chatId, messageId) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.chat_id = chatId;
form.message_id = messageId;
return this._request('deleteMessage', { form: form });
}
/**
* Send invoice.
* Use this method to send an invoice.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} title Product name
* @param {String} description product description
* @param {String} payload Bot defined invoice payload
* @param {String} providerToken Payments provider token
* @param {String} startParameter Deep-linking parameter
* @param {String} currency Three-letter ISO 4217 currency code
* @param {Array} prices Breakdown of prices
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendinvoice
*/
}, {
key: 'sendInvoice',
value: function sendInvoice(chatId, title, description, payload, providerToken, startParameter, currency, prices) {
var form = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : {};
form.chat_id = chatId;
form.title = title;
form.description = description;
form.payload = payload;
form.provider_token = providerToken;
form.start_parameter = startParameter;
form.currency = currency;
form.prices = stringify(prices);
form.provider_data = stringify(form.provider_data);
return this._request('sendInvoice', { form: form });
}
/**
* Answer shipping query..
* Use this method to reply to shipping queries.
*
* @param {String} shippingQueryId Unique identifier for the query to be answered
* @param {Boolean} ok Specify if delivery of the product is possible
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#answershippingquery
*/
}, {
key: 'answerShippingQuery',
value: function answerShippingQuery(shippingQueryId, ok) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.shipping_query_id = shippingQueryId;
form.ok = ok;
form.shipping_options = stringify(form.shipping_options);
return this._request('answerShippingQuery', { form: form });
}
/**
* Answer pre-checkout query.
* Use this method to confirm shipping of a product.
*
* @param {String} preCheckoutQueryId Unique identifier for the query to be answered
* @param {Boolean} ok Specify if every order details are ok
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#answerprecheckoutquery
*/
}, {
key: 'answerPreCheckoutQuery',
value: function answerPreCheckoutQuery(preCheckoutQueryId, ok) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.pre_checkout_query_id = preCheckoutQueryId;
form.ok = ok;
return this._request('answerPreCheckoutQuery', { form: form });
}
/**
* Use this method to get a sticker set. On success, a [StickerSet](https://core.telegram.org/bots/api#stickerset) object is returned.
*
* @param {String} name Name of the sticker set
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getstickerset
*/
}, {
key: 'getStickerSet',
value: function getStickerSet(name) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.name = name;
return this._request('getStickerSet', { form: form });
}
/**
* Use this method to upload a .png file with a sticker for later use in *createNewStickerSet* and *addStickerToSet* methods (can be used multiple
* times). Returns the uploaded [File](https://core.telegram.org/bots/api#file) on success.
*
* @param {Number} userId User identifier of sticker file owner
* @param {String|stream.Stream|Buffer} pngSticker A file path or a Stream. Can also be a `file_id` previously uploaded. **Png** image with the
* sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#uploadstickerfile
*/
}, {
key: 'uploadStickerFile',
value: function uploadStickerFile(userId, pngSticker) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fileOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = {
qs: options
};
opts.qs.user_id = userId;
try {
var sendData = this._formatSendData('png_sticker', pngSticker, fileOptions);
opts.formData = sendData[0];
opts.qs.png_sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('uploadStickerFile', opts);
}
/**
* Use this method to create new sticker set owned by a user.
* The bot will be able to edit the created sticker set.
* Returns True on success.
*
* @param {Number} userId User identifier of created sticker set owner
* @param {String} name Short name of sticker set, to be used in `t.me/addstickers/` URLs (e.g., *animals*)
* @param {String} title Sticker set title, 1-64 characters
* @param {String|stream.Stream|Buffer} pngSticker Png image with the sticker, must be up to 512 kilobytes in size,
* dimensions must not exceed 512px, and either width or height must be exactly 512px.
* @param {String} emojis One or more emoji corresponding to the sticker
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#createnewstickerset
* @todo Add tests for this method!
*/
}, {
key: 'createNewStickerSet',
value: function createNewStickerSet(userId, name, title, pngSticker, emojis) {
var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
var fileOptions = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {};
var opts = {
qs: options
};
opts.qs.user_id = userId;
opts.qs.name = name;
opts.qs.title = title;
opts.qs.emojis = emojis;
opts.qs.mask_position = stringify(options.mask_position);
try {
var sendData = this._formatSendData('png_sticker', pngSticker, fileOptions);
opts.formData = sendData[0];
opts.qs.png_sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('createNewStickerSet', opts);
}
/**
* Use this method to add a new sticker to a set created by the bot.
* Returns True on success.
*
* @param {Number} userId User identifier of sticker set owner
* @param {String} name Sticker set name
* @param {String|stream.Stream|Buffer} pngSticker Png image with the sticker, must be up to 512 kilobytes in size,
* dimensions must not exceed 512px, and either width or height must be exactly 512px
* @param {String} emojis One or more emoji corresponding to the sticker
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#addstickertoset
* @todo Add tests for this method!
*/
}, {
key: 'addStickerToSet',
value: function addStickerToSet(userId, name, pngSticker, emojis) {
var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
var fileOptions = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
var opts = {
qs: options
};
opts.qs.user_id = userId;
opts.qs.name = name;
opts.qs.emojis = emojis;
opts.qs.mask_position = stringify(options.mask_position);
try {
var sendData = this._formatSendData('png_sticker', pngSticker, fileOptions);
opts.formData = sendData[0];
opts.qs.png_sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('addStickerToSet', opts);
}
/**
* Use this method to move a sticker in a set created by the bot to a specific position.
* Returns True on success.
*
* @param {String} sticker File identifier of the sticker
* @param {Number} position New sticker position in the set, zero-based
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setstickerpositioninset
* @todo Add tests for this method!
*/
}, {
key: 'setStickerPositionInSet',
value: function setStickerPositionInSet(sticker, position) {
var form = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
form.sticker = sticker;
form.position = position;
return this._request('setStickerPositionInSet', { form: form });
}
/**
* Use this method to delete a sticker from a set created by the bot.
* Returns True on success.
*
* @param {String} sticker File identifier of the sticker
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletestickerfromset
* @todo Add tests for this method!
*/
}, {
key: 'deleteStickerFromSet',
value: function deleteStickerFromSet(sticker) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
form.sticker = sticker;
return this._request('deleteStickerFromSet', { form: form });
}
/**
* Use this method to send a group of photos or videos as an album.
* On success, an array of the sent [Messages](https://core.telegram.org/bots/api#message)
* is returned.
*
* If you wish to [specify file options](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files),
* add a `fileOptions` property to the target input in `media`.
*
* @param {String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Array} media A JSON-serialized array describing photos and videos to be sent, must include 210 items
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendmediagroup
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
}, {
key: 'sendMediaGroup',
value: function sendMediaGroup(chatId, media) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var opts = {
qs: options
};
opts.qs.chat_id = chatId;
opts.formData = {};
var inputMedia = [];
var index = 0;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = media[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var input = _step.value;
var payload = Object.assign({}, input);
delete payload.media;
delete payload.fileOptions;
try {
var attachName = String(index);
var _formatSendData2 = this._formatSendData(attachName, input.media, input.fileOptions),
_formatSendData3 = _slicedToArray(_formatSendData2, 2),
formData = _formatSendData3[0],
fileId = _formatSendData3[1];
if (formData) {
opts.formData[attachName] = formData[attachName];
payload.media = 'attach://' + attachName;
} else {
payload.media = fileId;
}
} catch (ex) {
return Promise.reject(ex);
}
inputMedia.push(payload);
index++;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
opts.qs.media = JSON.stringify(inputMedia);
return this._request('sendMediaGroup', opts);
}
}]);
return TelegramBot;
}(EventEmitter);
module.exports = TelegramBot;

View File

@@ -0,0 +1,245 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var errors = require('./errors');
var debug = require('debug')('node-telegram-bot-api');
var deprecate = require('depd')('node-telegram-bot-api');
var ANOTHER_WEB_HOOK_USED = 409;
var TelegramBotPolling = function () {
/**
* Handles polling against the Telegram servers.
* @param {TelegramBot} bot
* @see https://core.telegram.org/bots/api#getting-updates
*/
function TelegramBotPolling(bot) {
_classCallCheck(this, TelegramBotPolling);
this.bot = bot;
this.options = typeof bot.options.polling === 'boolean' ? {} : bot.options.polling;
this.options.interval = typeof this.options.interval === 'number' ? this.options.interval : 300;
this.options.params = _typeof(this.options.params) === 'object' ? this.options.params : {};
this.options.params.offset = typeof this.options.params.offset === 'number' ? this.options.params.offset : 0;
this.options.params.timeout = typeof this.options.params.timeout === 'number' ? this.options.params.timeout : 10;
if (typeof this.options.timeout === 'number') {
deprecate('`options.polling.timeout` is deprecated. Use `options.polling.params` instead.');
this.options.params.timeout = this.options.timeout;
}
this._lastUpdate = 0;
this._lastRequest = null;
this._abort = false;
this._pollingTimeout = null;
}
/**
* Start polling
* @param {Object} [options]
* @param {Object} [options.restart]
* @return {Promise}
*/
_createClass(TelegramBotPolling, [{
key: 'start',
value: function start() {
var _this = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (this._lastRequest) {
if (!options.restart) {
return Promise.resolve();
}
return this.stop({
cancel: true,
reason: 'Polling restart'
}).then(function () {
return _this._polling();
});
}
return this._polling();
}
/**
* Stop polling
* @param {Object} [options] Options
* @param {Boolean} [options.cancel] Cancel current request
* @param {String} [options.reason] Reason for stopping polling
* @return {Promise}
*/
}, {
key: 'stop',
value: function stop() {
var _this2 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!this._lastRequest) {
return Promise.resolve();
}
var lastRequest = this._lastRequest;
this._lastRequest = null;
clearTimeout(this._pollingTimeout);
if (options.cancel) {
var reason = options.reason || 'Polling stop';
lastRequest.cancel(reason);
return Promise.resolve();
}
this._abort = true;
return lastRequest.finally(function () {
_this2._abort = false;
});
}
/**
* Return `true` if is polling. Otherwise, `false`.
*/
}, {
key: 'isPolling',
value: function isPolling() {
return !!this._lastRequest;
}
/**
* Handle error thrown during polling.
* @private
* @param {Error} error
*/
}, {
key: '_error',
value: function _error(error) {
if (!this.bot.listeners('polling_error').length) {
return console.error('error: [polling_error] %j', error); // eslint-disable-line no-console
}
return this.bot.emit('polling_error', error);
}
/**
* Invokes polling (with recursion!)
* @return {Promise} promise of the current request
* @private
*/
}, {
key: '_polling',
value: function _polling() {
var _this3 = this;
this._lastRequest = this._getUpdates().then(function (updates) {
_this3._lastUpdate = Date.now();
debug('polling data %j', updates);
updates.forEach(function (update) {
_this3.options.params.offset = update.update_id + 1;
debug('updated offset: %s', _this3.options.params.offset);
try {
_this3.bot.processUpdate(update);
} catch (err) {
err._processing = true;
throw err;
}
});
return null;
}).catch(function (err) {
debug('polling error: %s', err.message);
if (!err._processing) {
return _this3._error(err);
}
delete err._processing;
/*
* An error occured while processing the items,
* i.e. in `this.bot.processUpdate()` above.
* We need to mark the already-processed items
* to avoid fetching them again once the application
* is restarted, or moves to next polling interval
* (in cases where unhandled rejections do not terminate
* the process).
* See https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067
*/
if (!_this3.bot.options.badRejection) {
return _this3._error(err);
}
var opts = {
offset: _this3.options.params.offset,
limit: 1,
timeout: 0
};
return _this3.bot.getUpdates(opts).then(function () {
return _this3._error(err);
}).catch(function (requestErr) {
/*
* We have been unable to handle this error.
* We have to log this to stderr to ensure devops
* understands that they may receive already-processed items
* on app restart.
* We simply can not rescue this situation, emit "error"
* event, with the hope that the application exits.
*/
/* eslint-disable no-console */
var bugUrl = 'https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067';
console.error('error: Internal handling of The Offset Infinite Loop failed');
console.error('error: Due to error \'' + requestErr + '\'');
console.error('error: You may receive already-processed updates on app restart');
console.error('error: Please see ' + bugUrl + ' for more information');
/* eslint-enable no-console */
return _this3.bot.emit('error', new errors.FatalError(err));
});
}).finally(function () {
if (_this3._abort) {
debug('Polling is aborted!');
} else {
debug('setTimeout for %s miliseconds', _this3.options.interval);
_this3._pollingTimeout = setTimeout(function () {
return _this3._polling();
}, _this3.options.interval);
}
});
return this._lastRequest;
}
/**
* Unset current webhook. Used when we detect that a webhook has been set
* and we are trying to poll. Polling and WebHook are mutually exclusive.
* @see https://core.telegram.org/bots/api#getting-updates
* @private
*/
}, {
key: '_unsetWebHook',
value: function _unsetWebHook() {
debug('unsetting webhook');
return this.bot._request('setWebHook');
}
/**
* Retrieve updates
*/
}, {
key: '_getUpdates',
value: function _getUpdates() {
var _this4 = this;
debug('polling with options: %j', this.options.params);
return this.bot.getUpdates(this.options.params).catch(function (err) {
if (err.response && err.response.statusCode === ANOTHER_WEB_HOOK_USED) {
return _this4._unsetWebHook().then(function () {
return _this4.bot.getUpdates(_this4.options.params);
});
}
throw err;
});
}
}]);
return TelegramBotPolling;
}();
module.exports = TelegramBotPolling;

View File

@@ -0,0 +1,189 @@
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var errors = require('./errors');
var debug = require('debug')('node-telegram-bot-api');
var https = require('https');
var http = require('http');
var fs = require('fs');
var bl = require('bl');
var Promise = require('bluebird');
var TelegramBotWebHook = function () {
/**
* Sets up a webhook to receive updates
* @param {TelegramBot} bot
* @see https://core.telegram.org/bots/api#getting-updates
*/
function TelegramBotWebHook(bot) {
_classCallCheck(this, TelegramBotWebHook);
this.bot = bot;
this.options = typeof bot.options.webHook === 'boolean' ? {} : bot.options.webHook;
this.options.host = this.options.host || '0.0.0.0';
this.options.port = this.options.port || 8443;
this.options.https = this.options.https || {};
this.options.healthEndpoint = this.options.healthEndpoint || '/healthz';
this._healthRegex = new RegExp(this.options.healthEndpoint);
this._webServer = null;
this._open = false;
this._requestListener = this._requestListener.bind(this);
this._parseBody = this._parseBody.bind(this);
if (this.options.key && this.options.cert) {
debug('HTTPS WebHook enabled (by key/cert)');
this.options.https.key = fs.readFileSync(this.options.key);
this.options.https.cert = fs.readFileSync(this.options.cert);
this._webServer = https.createServer(this.options.https, this._requestListener);
} else if (this.options.pfx) {
debug('HTTPS WebHook enabled (by pfx)');
this.options.https.pfx = fs.readFileSync(this.options.pfx);
this._webServer = https.createServer(this.options.https, this._requestListener);
} else if (Object.keys(this.options.https).length) {
debug('HTTPS WebHook enabled by (https)');
this._webServer = https.createServer(this.options.https, this._requestListener);
} else {
debug('HTTP WebHook enabled');
this._webServer = http.createServer(this._requestListener);
}
}
/**
* Open WebHook by listening on the port
* @return {Promise}
*/
_createClass(TelegramBotWebHook, [{
key: 'open',
value: function open() {
var _this = this;
if (this.isOpen()) {
return Promise.resolve();
}
return new Promise(function (resolve) {
_this._webServer.listen(_this.options.port, _this.options.host, function () {
debug('WebHook listening on port %s', _this.options.port);
_this._open = true;
return resolve();
});
});
}
/**
* Close the webHook
* @return {Promise}
*/
}, {
key: 'close',
value: function close() {
var _this2 = this;
if (!this.isOpen()) {
return Promise.resolve();
}
return new Promise(function (resolve, reject) {
_this2._webServer.close(function (error) {
if (error) return reject(error);
_this2._open = false;
return resolve();
});
});
}
/**
* Return `true` if server is listening. Otherwise, `false`.
*/
}, {
key: 'isOpen',
value: function isOpen() {
// NOTE: Since `http.Server.listening` was added in v5.7.0
// and we still need to support Node v4,
// we are going to fallback to 'this._open'.
// The following LOC would suffice for newer versions of Node.js
// return this._webServer.listening;
return this._open;
}
/**
* Handle error thrown during processing of webhook request.
* @private
* @param {Error} error
*/
}, {
key: '_error',
value: function _error(error) {
if (!this.bot.listeners('webhook_error').length) {
return console.error('error: [webhook_error] %j', error); // eslint-disable-line no-console
}
return this.bot.emit('webhook_error', error);
}
/**
* Handle request body by passing it to 'callback'
* @private
*/
}, {
key: '_parseBody',
value: function _parseBody(error, body) {
if (error) {
return this._error(new errors.FatalError(error));
}
var data = void 0;
try {
data = JSON.parse(body.toString());
} catch (parseError) {
return this._error(new errors.ParseError(parseError.message));
}
return this.bot.processUpdate(data);
}
/**
* Listener for 'request' event on server
* @private
* @see https://nodejs.org/docs/latest/api/http.html#http_http_createserver_requestlistener
* @see https://nodejs.org/docs/latest/api/https.html#https_https_createserver_options_requestlistener
*/
}, {
key: '_requestListener',
value: function _requestListener(req, res) {
debug('WebHook request URL: %s', req.url);
debug('WebHook request headers: %j', req.headers);
if (req.url.indexOf(this.bot.token) !== -1) {
if (req.method !== 'POST') {
debug('WebHook request isn\'t a POST');
res.statusCode = 418; // I'm a teabot!
res.end();
} else {
req.pipe(bl(this._parseBody)).on('finish', function () {
return res.end('OK');
});
}
} else if (this._healthRegex.test(req.url)) {
debug('WebHook health check passed');
res.statusCode = 200;
res.end('OK');
} else {
debug('WebHook request unauthorized');
res.statusCode = 401;
res.end();
}
}
}]);
return TelegramBotWebHook;
}();
module.exports = TelegramBotWebHook;

View File

@@ -0,0 +1,395 @@
3.1.0 / 2017-09-26
==================
* Add `DEBUG_HIDE_DATE` env var (#486)
* Remove ReDoS regexp in %o formatter (#504)
* Remove "component" from package.json
* Remove `component.json`
* Ignore package-lock.json
* Examples: fix colors printout
* Fix: browser detection
* Fix: spelling mistake (#496, @EdwardBetts)
3.0.1 / 2017-08-24
==================
* Fix: Disable colors in Edge and Internet Explorer (#489)
3.0.0 / 2017-08-08
==================
* Breaking: Remove DEBUG_FD (#406)
* Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418)
* Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408)
* Addition: document `enabled` flag (#465)
* Addition: add 256 colors mode (#481)
* Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440)
* Update: component: update "ms" to v2.0.0
* Update: separate the Node and Browser tests in Travis-CI
* Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots
* Update: separate Node.js and web browser examples for organization
* Update: update "browserify" to v14.4.0
* Fix: fix Readme typo (#473)
2.6.9 / 2017-09-22
==================
* remove ReDoS regexp in %o formatter (#504)
2.6.8 / 2017-05-18
==================
* Fix: Check for undefined on browser globals (#462, @marbemac)
2.6.7 / 2017-05-16
==================
* Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom)
* Fix: Inline extend function in node implementation (#452, @dougwilson)
* Docs: Fix typo (#455, @msasad)
2.6.5 / 2017-04-27
==================
* Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek)
* Misc: clean up browser reference checks (#447, @thebigredgeek)
* Misc: add npm-debug.log to .gitignore (@thebigredgeek)
2.6.4 / 2017-04-20
==================
* Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo)
* Chore: ignore bower.json in npm installations. (#437, @joaovieira)
* Misc: update "ms" to v0.7.3 (@tootallnate)
2.6.3 / 2017-03-13
==================
* Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts)
* Docs: Changelog fix (@thebigredgeek)
2.6.2 / 2017-03-10
==================
* Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin)
* Docs: Add backers and sponsors from Open Collective (#422, @piamancini)
* Docs: Add Slackin invite badge (@tootallnate)
2.6.1 / 2017-02-10
==================
* Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error
* Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0)
* Fix: IE8 "Expected identifier" error (#414, @vgoma)
* Fix: Namespaces would not disable once enabled (#409, @musikov)
2.6.0 / 2016-12-28
==================
* Fix: added better null pointer checks for browser useColors (@thebigredgeek)
* Improvement: removed explicit `window.debug` export (#404, @tootallnate)
* Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate)
2.5.2 / 2016-12-25
==================
* Fix: reference error on window within webworkers (#393, @KlausTrainer)
* Docs: fixed README typo (#391, @lurch)
* Docs: added notice about v3 api discussion (@thebigredgeek)
2.5.1 / 2016-12-20
==================
* Fix: babel-core compatibility
2.5.0 / 2016-12-20
==================
* Fix: wrong reference in bower file (@thebigredgeek)
* Fix: webworker compatibility (@thebigredgeek)
* Fix: output formatting issue (#388, @kribblo)
* Fix: babel-loader compatibility (#383, @escwald)
* Misc: removed built asset from repo and publications (@thebigredgeek)
* Misc: moved source files to /src (#378, @yamikuronue)
* Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
* Test: coveralls integration (#378, @yamikuronue)
* Docs: simplified language in the opening paragraph (#373, @yamikuronue)
2.4.5 / 2016-12-17
==================
* Fix: `navigator` undefined in Rhino (#376, @jochenberger)
* Fix: custom log function (#379, @hsiliev)
* Improvement: bit of cleanup + linting fixes (@thebigredgeek)
* Improvement: rm non-maintainted `dist/` dir (#375, @freewil)
* Docs: simplified language in the opening paragraph. (#373, @yamikuronue)
2.4.4 / 2016-12-14
==================
* Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)
2.4.3 / 2016-12-14
==================
* Fix: navigation.userAgent error for react native (#364, @escwald)
2.4.2 / 2016-12-14
==================
* Fix: browser colors (#367, @tootallnate)
* Misc: travis ci integration (@thebigredgeek)
* Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)
2.4.1 / 2016-12-13
==================
* Fix: typo that broke the package (#356)
2.4.0 / 2016-12-13
==================
* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
* Fix: revert "handle regex special characters" (@tootallnate)
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
* Improvement: allow colors in workers (#335, @botverse)
* Improvement: use same color for same namespace. (#338, @lchenay)
2.3.3 / 2016-11-09
==================
* Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne)
* Fix: Returning `localStorage` saved values (#331, Levi Thomason)
* Improvement: Don't create an empty object when no `process` (Nathan Rajlich)
2.3.2 / 2016-11-09
==================
* Fix: be super-safe in index.js as well (@TooTallNate)
* Fix: should check whether process exists (Tom Newby)
2.3.1 / 2016-11-09
==================
* Fix: Added electron compatibility (#324, @paulcbetts)
* Improvement: Added performance optimizations (@tootallnate)
* Readme: Corrected PowerShell environment variable example (#252, @gimre)
* Misc: Removed yarn lock file from source control (#321, @fengmk2)
2.3.0 / 2016-11-07
==================
* Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
* Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
* Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
* Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
* Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
* Package: Update "ms" to 0.7.2 (#315, @DevSide)
* Package: removed superfluous version property from bower.json (#207 @kkirsche)
* Readme: fix USE_COLORS to DEBUG_COLORS
* Readme: Doc fixes for format string sugar (#269, @mlucool)
* Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
* Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
* Readme: better docs for browser support (#224, @matthewmueller)
* Tooling: Added yarn integration for development (#317, @thebigredgeek)
* Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
* Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
* Misc: Updated contributors (@thebigredgeek)
2.2.0 / 2015-05-09
==================
* package: update "ms" to v0.7.1 (#202, @dougwilson)
* README: add logging to file example (#193, @DanielOchoa)
* README: fixed a typo (#191, @amir-s)
* browser: expose `storage` (#190, @stephenmathieson)
* Makefile: add a `distclean` target (#189, @stephenmathieson)
2.1.3 / 2015-03-13
==================
* Updated stdout/stderr example (#186)
* Updated example/stdout.js to match debug current behaviour
* Renamed example/stderr.js to stdout.js
* Update Readme.md (#184)
* replace high intensity foreground color for bold (#182, #183)
2.1.2 / 2015-03-01
==================
* dist: recompile
* update "ms" to v0.7.0
* package: update "browserify" to v9.0.3
* component: fix "ms.js" repo location
* changed bower package name
* updated documentation about using debug in a browser
* fix: security error on safari (#167, #168, @yields)
2.1.1 / 2014-12-29
==================
* browser: use `typeof` to check for `console` existence
* browser: check for `console.log` truthiness (fix IE 8/9)
* browser: add support for Chrome apps
* Readme: added Windows usage remarks
* Add `bower.json` to properly support bower install
2.1.0 / 2014-10-15
==================
* node: implement `DEBUG_FD` env variable support
* package: update "browserify" to v6.1.0
* package: add "license" field to package.json (#135, @panuhorsmalahti)
2.0.0 / 2014-09-01
==================
* package: update "browserify" to v5.11.0
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
1.0.4 / 2014-07-15
==================
* dist: recompile
* example: remove `console.info()` log usage
* example: add "Content-Type" UTF-8 header to browser example
* browser: place %c marker after the space character
* browser: reset the "content" color via `color: inherit`
* browser: add colors support for Firefox >= v31
* debug: prefer an instance `log()` function over the global one (#119)
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
1.0.3 / 2014-07-09
==================
* Add support for multiple wildcards in namespaces (#122, @seegno)
* browser: fix lint
1.0.2 / 2014-06-10
==================
* browser: update color palette (#113, @gscottolson)
* common: make console logging function configurable (#108, @timoxley)
* node: fix %o colors on old node <= 0.8.x
* Makefile: find node path using shell/which (#109, @timoxley)
1.0.1 / 2014-06-06
==================
* browser: use `removeItem()` to clear localStorage
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
* package: add "contributors" section
* node: fix comment typo
* README: list authors
1.0.0 / 2014-06-04
==================
* make ms diff be global, not be scope
* debug: ignore empty strings in enable()
* node: make DEBUG_COLORS able to disable coloring
* *: export the `colors` array
* npmignore: don't publish the `dist` dir
* Makefile: refactor to use browserify
* package: add "browserify" as a dev dependency
* Readme: add Web Inspector Colors section
* node: reset terminal color for the debug content
* node: map "%o" to `util.inspect()`
* browser: map "%j" to `JSON.stringify()`
* debug: add custom "formatters"
* debug: use "ms" module for humanizing the diff
* Readme: add "bash" syntax highlighting
* browser: add Firebug color support
* browser: add colors for WebKit browsers
* node: apply log to `console`
* rewrite: abstract common logic for Node & browsers
* add .jshintrc file
0.8.1 / 2014-04-14
==================
* package: re-add the "component" section
0.8.0 / 2014-03-30
==================
* add `enable()` method for nodejs. Closes #27
* change from stderr to stdout
* remove unnecessary index.js file
0.7.4 / 2013-11-13
==================
* remove "browserify" key from package.json (fixes something in browserify)
0.7.3 / 2013-10-30
==================
* fix: catch localStorage security error when cookies are blocked (Chrome)
* add debug(err) support. Closes #46
* add .browser prop to package.json. Closes #42
0.7.2 / 2013-02-06
==================
* fix package.json
* fix: Mobile Safari (private mode) is broken with debug
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
0.7.1 / 2013-02-05
==================
* add repository URL to package.json
* add DEBUG_COLORED to force colored output
* add browserify support
* fix component. Closes #24
0.7.0 / 2012-05-04
==================
* Added .component to package.json
* Added debug.component.js build
0.6.0 / 2012-03-16
==================
* Added support for "-" prefix in DEBUG [Vinay Pulim]
* Added `.enabled` flag to the node version [TooTallNate]
0.5.0 / 2012-02-02
==================
* Added: humanize diffs. Closes #8
* Added `debug.disable()` to the CS variant
* Removed padding. Closes #10
* Fixed: persist client-side variant again. Closes #9
0.4.0 / 2012-02-01
==================
* Added browser variant support for older browsers [TooTallNate]
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
* Added padding to diff (moved it to the right)
0.3.0 / 2012-01-26
==================
* Added millisecond diff when isatty, otherwise UTC string
0.2.0 / 2012-01-22
==================
* Added wildcard support
0.1.0 / 2011-12-02
==================
* Added: remove colors unless stderr isatty [TooTallNate]
0.0.1 / 2010-01-03
==================
* Initial release

View File

@@ -0,0 +1,19 @@
(The MIT License)
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,437 @@
# debug
[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,886 @@
"use strict";
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
(function (f) {
if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === "object" && typeof module !== "undefined") {
module.exports = f();
} else if (typeof define === "function" && define.amd) {
define([], f);
} else {
var g;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
} else {
g = this;
}
g.debug = f();
}
})(function () {
var define, module, exports;
return function () {
function r(e, n, t) {
function o(i, f) {
if (!n[i]) {
if (!e[i]) {
var c = "function" == typeof require && require;
if (!f && c) return c(i, !0);
if (u) return u(i, !0);
var a = new Error("Cannot find module '" + i + "'");
throw a.code = "MODULE_NOT_FOUND", a;
}
var p = n[i] = {
exports: {}
};
e[i][0].call(p.exports, function (r) {
var n = e[i][1][r];
return o(n || r);
}, p, p.exports, r, e, n, t);
}
return n[i].exports;
}
for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) {
o(t[i]);
}
return o;
}
return r;
}()({
1: [function (require, module, exports) {
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = _typeof(val);
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
}, {}],
2: [function (require, module, exports) {
// shim for using process in browser
var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
} // if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
} // if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
}; // v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) {
return [];
};
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () {
return '/';
};
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function () {
return 0;
};
}, {}],
3: [function (require, module, exports) {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
Object.keys(env).forEach(function (key) {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
var hash = 0;
for (var i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime;
function debug() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Disabled?
if (!debug.enabled) {
return;
}
var self = debug; // Set `diff` timestamp
var curr = Number(new Date());
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
} // Apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
}
index++;
var formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
var val = args[index];
match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
}); // Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend; // Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
// env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
var index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.names = [];
createDebug.skips = [];
var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
var instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
createDebug.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i;
var len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
}, {
"ms": 1
}],
4: [function (require, module, exports) {
(function (process) {
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
/**
* Colors.
*/
exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
} // Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
} // Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function (match) {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
var _console;
// This hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.getItem('debug');
} catch (error) {} // Swallow
// XXX (@Qix-) should we be logging these?
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
var formatters = module.exports.formatters;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
}).call(this, require('_process'));
}, {
"./common": 3,
"_process": 2
}]
}, {}, [4])(4);
});

View File

@@ -0,0 +1 @@
module.exports = require('./src/node');

View File

@@ -0,0 +1,90 @@
{
"_from": "debug@^3.1.0",
"_id": "debug@3.2.6",
"_inBundle": false,
"_integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
"_location": "/node-telegram-bot-api/debug",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "debug@^3.1.0",
"name": "debug",
"escapedName": "debug",
"rawSpec": "^3.1.0",
"saveSpec": null,
"fetchSpec": "^3.1.0"
},
"_requiredBy": [
"/node-telegram-bot-api"
],
"_resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz",
"_shasum": "e83d17de16d8a7efb7717edbe5fb10135eee629b",
"_spec": "debug@^3.1.0",
"_where": "/data/node_modules/node-telegram-bot-api",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"browser": "./src/browser.js",
"bugs": {
"url": "https://github.com/visionmedia/debug/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://n8.io"
},
{
"name": "Andrew Rhyne",
"email": "rhyneandrew@gmail.com"
}
],
"dependencies": {
"ms": "^2.1.1"
},
"deprecated": false,
"description": "small debugging utility",
"devDependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"browserify": "14.4.0",
"chai": "^3.5.0",
"concurrently": "^3.1.0",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.0.0",
"karma-chai": "^0.1.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"rimraf": "^2.5.4",
"xo": "^0.23.0"
},
"files": [
"src",
"node.js",
"dist/debug.js",
"LICENSE",
"README.md"
],
"homepage": "https://github.com/visionmedia/debug#readme",
"keywords": [
"debug",
"log",
"debugger"
],
"license": "MIT",
"main": "./src/index.js",
"name": "debug",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"unpkg": "./dist/debug.js",
"version": "3.2.6"
}

View File

@@ -0,0 +1,180 @@
"use strict";
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
/**
* Colors.
*/
exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
} // Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
} // Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function (match) {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
var _console;
// This hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.getItem('debug');
} catch (error) {} // Swallow
// XXX (@Qix-) should we be logging these?
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
var formatters = module.exports.formatters;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};

View File

@@ -0,0 +1,249 @@
"use strict";
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
Object.keys(env).forEach(function (key) {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
var hash = 0;
for (var i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime;
function debug() {
// Disabled?
if (!debug.enabled) {
return;
}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var self = debug; // Set `diff` timestamp
var curr = Number(new Date());
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
} // Apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
}
index++;
var formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
var val = args[index];
match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
}); // Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend; // Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
// env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
var index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.names = [];
createDebug.skips = [];
var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
var instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
createDebug.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i;
var len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;

View File

@@ -0,0 +1,12 @@
"use strict";
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}

View File

@@ -0,0 +1,174 @@
"use strict";
/**
* Module dependencies.
*/
var tty = require('tty');
var util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
var supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221];
}
} catch (error) {} // Swallow - we only care if `supports-color` is available; it doesn't have to be.
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(function (key) {
return /^debug_/i.test(key);
}).reduce(function (obj, key) {
// Camel-case
var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function (_, k) {
return k.toUpperCase();
}); // Coerce string value into JS value
var val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
var name = this.namespace,
useColors = this.useColors;
if (useColors) {
var c = this.color;
var colorCode = "\x1B[3" + (c < 8 ? c : '8;5;' + c);
var prefix = " ".concat(colorCode, ";1m").concat(name, " \x1B[0m");
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + "\x1B[0m");
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.format()` with the specified arguments and writes to stderr.
*/
function log() {
return process.stderr.write(util.format.apply(util, arguments) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
var keys = Object.keys(exports.inspectOpts);
for (var i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
var formatters = module.exports.formatters;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts).replace(/\s*\n\s*/g, ' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};

View File

@@ -0,0 +1,162 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Zeit, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,69 @@
{
"_from": "ms@^2.1.1",
"_id": "ms@2.1.2",
"_inBundle": false,
"_integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
"_location": "/node-telegram-bot-api/ms",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ms@^2.1.1",
"name": "ms",
"escapedName": "ms",
"rawSpec": "^2.1.1",
"saveSpec": null,
"fetchSpec": "^2.1.1"
},
"_requiredBy": [
"/node-telegram-bot-api/debug"
],
"_resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"_shasum": "d09d1f357b443f493382a8eb3ccd183872ae6009",
"_spec": "ms@^2.1.1",
"_where": "/data/node_modules/node-telegram-bot-api/node_modules/debug",
"bugs": {
"url": "https://github.com/zeit/ms/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Tiny millisecond conversion utility",
"devDependencies": {
"eslint": "4.12.1",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"files": [
"index.js"
],
"homepage": "https://github.com/zeit/ms#readme",
"license": "MIT",
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"main": "./index",
"name": "ms",
"repository": {
"type": "git",
"url": "git+https://github.com/zeit/ms.git"
},
"scripts": {
"lint": "eslint lib/* bin/*",
"precommit": "lint-staged",
"test": "mocha tests.js"
},
"version": "2.1.2"
}

View File

@@ -0,0 +1,60 @@
# ms
[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms)
[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`

View File

@@ -0,0 +1,5 @@
language: node_js
node_js:
- "0.10"
script: "npm test"

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Mathias Buus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,56 @@
# pump
pump is a small node module that pipes streams together and destroys all of them if one of them closes.
```
npm install pump
```
[![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump)
## What problem does it solve?
When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error.
You are also not able to provide a callback to tell when then pipe has finished.
pump does these two things for you
## Usage
Simply pass the streams you want to pipe together to pump and add an optional callback
``` js
var pump = require('pump')
var fs = require('fs')
var source = fs.createReadStream('/dev/random')
var dest = fs.createWriteStream('/dev/null')
pump(source, dest, function(err) {
console.log('pipe finished', err)
})
setTimeout(function() {
dest.destroy() // when dest is closed pump will destroy source
}, 1000)
```
You can use pump to pipe more than two streams together as well
``` js
var transform = someTransformStream()
pump(source, transform, anotherTransform, dest, function(err) {
console.log('pipe finished', err)
})
```
If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed.
## License
MIT
## Related
`pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one.

View File

@@ -0,0 +1,82 @@
var once = require('once')
var eos = require('end-of-stream')
var fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes
var noop = function () {}
var ancient = /^v?\.0/.test(process.version)
var isFn = function (fn) {
return typeof fn === 'function'
}
var isFS = function (stream) {
if (!ancient) return false // newer node version do not need to care about fs is a special way
if (!fs) return false // browser
return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)
}
var isRequest = function (stream) {
return stream.setHeader && isFn(stream.abort)
}
var destroyer = function (stream, reading, writing, callback) {
callback = once(callback)
var closed = false
stream.on('close', function () {
closed = true
})
eos(stream, {readable: reading, writable: writing}, function (err) {
if (err) return callback(err)
closed = true
callback()
})
var destroyed = false
return function (err) {
if (closed) return
if (destroyed) return
destroyed = true
if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks
if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
if (isFn(stream.destroy)) return stream.destroy()
callback(err || new Error('stream was destroyed'))
}
}
var call = function (fn) {
fn()
}
var pipe = function (from, to) {
return from.pipe(to)
}
var pump = function () {
var streams = Array.prototype.slice.call(arguments)
var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop
if (Array.isArray(streams[0])) streams = streams[0]
if (streams.length < 2) throw new Error('pump requires two streams per minimum')
var error
var destroys = streams.map(function (stream, i) {
var reading = i < streams.length - 1
var writing = i > 0
return destroyer(stream, reading, writing, function (err) {
if (!error) error = err
if (err) destroys.forEach(call)
if (reading) return
destroys.forEach(call)
callback(error)
})
})
streams.reduce(pipe)
}
module.exports = pump

View File

@@ -0,0 +1,59 @@
{
"_from": "pump@^2.0.0",
"_id": "pump@2.0.1",
"_inBundle": false,
"_integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==",
"_location": "/node-telegram-bot-api/pump",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "pump@^2.0.0",
"name": "pump",
"escapedName": "pump",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/node-telegram-bot-api"
],
"_resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz",
"_shasum": "12399add6e4cf7526d973cbc8b5ce2e2908b3909",
"_spec": "pump@^2.0.0",
"_where": "/data/node_modules/node-telegram-bot-api",
"author": {
"name": "Mathias Buus Madsen",
"email": "mathiasbuus@gmail.com"
},
"browser": {
"fs": false
},
"bugs": {
"url": "https://github.com/mafintosh/pump/issues"
},
"bundleDependencies": false,
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
},
"deprecated": false,
"description": "pipe streams together and close all of them if one of them closes",
"homepage": "https://github.com/mafintosh/pump#readme",
"keywords": [
"streams",
"pipe",
"destroy",
"callback"
],
"license": "MIT",
"name": "pump",
"repository": {
"type": "git",
"url": "git://github.com/mafintosh/pump.git"
},
"scripts": {
"test": "node test-browser.js && node test-node.js"
},
"version": "2.0.1"
}

View File

@@ -0,0 +1,62 @@
var stream = require('stream')
var pump = require('./index')
var rs = new stream.Readable()
var ws = new stream.Writable()
rs._read = function (size) {
this.push(Buffer(size).fill('abc'))
}
ws._write = function (chunk, encoding, cb) {
setTimeout(function () {
cb()
}, 100)
}
var toHex = function () {
var reverse = new (require('stream').Transform)()
reverse._transform = function (chunk, enc, callback) {
reverse.push(chunk.toString('hex'))
callback()
}
return reverse
}
var wsClosed = false
var rsClosed = false
var callbackCalled = false
var check = function () {
if (wsClosed && rsClosed && callbackCalled) {
console.log('test-browser.js passes')
clearTimeout(timeout)
}
}
ws.on('finish', function () {
wsClosed = true
check()
})
rs.on('end', function () {
rsClosed = true
check()
})
pump(rs, toHex(), toHex(), toHex(), ws, function () {
callbackCalled = true
check()
})
setTimeout(function () {
rs.push(null)
rs.emit('close')
}, 1000)
var timeout = setTimeout(function () {
check()
throw new Error('timeout')
}, 5000)

View File

@@ -0,0 +1,53 @@
var pump = require('./index')
var rs = require('fs').createReadStream('/dev/random')
var ws = require('fs').createWriteStream('/dev/null')
var toHex = function () {
var reverse = new (require('stream').Transform)()
reverse._transform = function (chunk, enc, callback) {
reverse.push(chunk.toString('hex'))
callback()
}
return reverse
}
var wsClosed = false
var rsClosed = false
var callbackCalled = false
var check = function () {
if (wsClosed && rsClosed && callbackCalled) {
console.log('test-node.js passes')
clearTimeout(timeout)
}
}
ws.on('close', function () {
wsClosed = true
check()
})
rs.on('close', function () {
rsClosed = true
check()
})
var res = pump(rs, toHex(), toHex(), toHex(), ws, function () {
callbackCalled = true
check()
})
if (res) {
process.exit(1)
}
setTimeout(function () {
rs.destroy()
}, 1000)
var timeout = setTimeout(function () {
throw new Error('timeout')
}, 5000)

View File

@@ -0,0 +1,318 @@
{
"_from": "node-telegram-bot-api@^0.40.0",
"_id": "node-telegram-bot-api@0.40.0",
"_inBundle": false,
"_integrity": "sha512-kDVCU1Y0L7hDnkm8oosO7cKIRyftPOvIGMvDbj7CU/FDIqqkC13VytRieHb/pFgTfFmiCpBTzAeK66YLHIfchQ==",
"_location": "/node-telegram-bot-api",
"_phantomChildren": {
"end-of-stream": "1.4.4",
"once": "1.4.0"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "node-telegram-bot-api@^0.40.0",
"name": "node-telegram-bot-api",
"escapedName": "node-telegram-bot-api",
"rawSpec": "^0.40.0",
"saveSpec": null,
"fetchSpec": "^0.40.0"
},
"_requiredBy": [
"/node-red-contrib-telegrambot"
],
"_resolved": "https://registry.npmjs.org/node-telegram-bot-api/-/node-telegram-bot-api-0.40.0.tgz",
"_shasum": "7e6acf631e868b8000025808daf566181c7673d5",
"_spec": "node-telegram-bot-api@^0.40.0",
"_where": "/data/node_modules/node-red-contrib-telegrambot",
"author": {
"name": "Yago Pérez",
"email": "yagoperezs@gmail.com"
},
"bugs": {
"url": "https://github.com/yagop/node-telegram-bot-api/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Oleg",
"url": "https://github.com/olegmdev"
},
{
"name": "Archakov Dennis",
"url": "https://github.com/Archakov06"
},
{
"name": "drGOD",
"url": "https://github.com/drGOD"
},
{
"name": "MCSH",
"url": "https://github.com/MCSH"
},
{
"name": "Aaron Meese",
"url": "https://github.com/ajmeese7"
},
{
"name": "Misha",
"url": "https://github.com/mnb3000"
},
{
"name": "Savely Krasovsky",
"url": "https://github.com/L11R"
},
{
"name": "Victor Le",
"url": "https://github.com/Coac"
},
{
"url": "https://github.com/kucherenkovova"
},
{
"name": "Guidone",
"url": "https://github.com/guidone"
},
{
"name": "Jaakko Lipsanen",
"url": "https://github.com/JaakkoLipsanen"
},
{
"name": "Fabio Zuber",
"url": "https://github.com/Sirius-A"
},
{
"name": "Evgeny Bondarenko",
"url": "https://github.com/jehy"
},
{
"name": "Anton Mironov",
"url": "https://github.com/mironov"
},
{
"name": "Daniil Yastremskiy",
"url": "https://github.com/TheBeastOfCaerbannog"
},
{
"name": "Nikolay Ershov",
"url": "https://github.com/Ni2c2k"
},
{
"name": "Alexander Tarmolov",
"url": "https://github.com/tarmolov"
},
{
"url": "https://github.com/GingerPlusPlus"
},
{
"name": "Mikhail Burshteyn",
"url": "https://github.com/m-burst"
},
{
"name": "Sergey Bogdanov",
"url": "https://github.com/desunit"
},
{
"name": "Ola Flisbäck",
"url": "https://github.com/oflisback"
},
{
"name": "Horus Lugo",
"url": "https://github.com/HorusGoul"
},
{
"name": "Conor Fennell",
"url": "https://github.com/conorfennell"
},
{
"name": "Serhii Dmytruk",
"url": "https://github.com/imserhii"
},
{
"name": "Aleksandr L.",
"url": "https://github.com/w-site"
},
{
"name": "Matthew Brandly",
"url": "https://github.com/brandly"
},
{
"name": "Patricio López Juri",
"url": "https://github.com/mrpatiwi"
},
{
"name": "Anton",
"url": "https://github.com/Feverqwe"
},
{
"name": "Guido García",
"url": "https://github.com/palmerabollo"
},
{
"name": "Sebastian Troć",
"url": "https://github.com/SebastianTroc"
},
{
"name": "CapacitorSet",
"url": "https://github.com/CapacitorSet"
},
{
"name": "Plusb Preco",
"url": "https://github.com/preco21"
},
{
"name": "Jishnu Mohan",
"url": "https://github.com/jishnu7"
},
{
"name": "TJ Horner",
"url": "https://github.com/tjhorner"
},
{
"name": "Alex Godko",
"url": "https://github.com/koloboid"
},
{
"name": "Dardan Neziri",
"url": "https://github.com/knock-in"
},
{
"name": "Jérémy Gotteland",
"url": "https://github.com/Tketa"
},
{
"name": "Iiro Jäppinen",
"url": "https://github.com/iiroj"
},
{
"url": "https://github.com/evolun"
},
{
"name": "Vitaly Aminev",
"url": "https://github.com/AVVS"
},
{
"name": "Cristian Baldi",
"url": "https://github.com/crisbal"
},
{
"name": "Vítor Augusto da Silva Vasconcellos",
"url": "https://github.com/HeavenVolkoff"
},
{
"name": "Rey",
"url": "https://github.com/reyy"
},
{
"name": "Ivan Skorokhodov",
"url": "https://github.com/universome"
},
{
"name": "Rafael Kr",
"url": "https://github.com/RafaelKr"
},
{
"url": "https://github.com/EXL"
},
{
"name": "Riddler",
"url": "https://github.com/Waterloo"
},
{
"name": "Chris54721",
"url": "https://github.com/chris54721"
},
{
"name": "Ilias Ismanalijev",
"url": "https://github.com/Illyism"
},
{
"name": "Gocho Mugo",
"url": "https://github.com/GochoMugo"
},
{
"name": "Mohammed Sohail",
"url": "https://github.com/kamikazechaser"
},
{
"name": "Yago",
"url": "https://github.com/yagop"
},
{
"name": "Sedric Heidarizarei",
"url": "https://github.com/saeedhei"
}
],
"dependencies": {
"array.prototype.findindex": "^2.0.2",
"bl": "^1.2.1",
"bluebird": "^3.5.1",
"debug": "^3.1.0",
"depd": "^1.1.1",
"eventemitter3": "^3.0.0",
"file-type": "^3.9.0",
"mime": "^1.6.0",
"pump": "^2.0.0",
"request": "^2.83.0",
"request-promise": "^4.2.2"
},
"deprecated": false,
"description": "Telegram Bot API",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-eslint": "^8.0.3",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-es2015-destructuring": "^6.23.0",
"babel-plugin-transform-es2015-parameters": "^6.24.1",
"babel-plugin-transform-es2015-shorthand-properties": "^6.24.1",
"babel-plugin-transform-es2015-spread": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-strict-mode": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-register": "^6.26.0",
"concat-stream": "^1.6.0",
"contributor": "^0.1.25",
"eslint": "^2.13.1",
"eslint-config-airbnb": "^6.2.0",
"eslint-plugin-mocha": "^4.11.0",
"is": "^3.2.1",
"is-ci": "^1.0.10",
"istanbul": "^1.1.0-alpha.1",
"jsdoc-to-markdown": "^3.0.3",
"mocha": "^3.5.3",
"mocha-lcov-reporter": "^1.3.0",
"node-static": "^0.7.10"
},
"directories": {
"example": "examples",
"test": "test"
},
"engines": {
"node": ">=0.12"
},
"homepage": "https://github.com/yagop/node-telegram-bot-api",
"keywords": [
"telegram",
"telegram bot",
"telegram bot api",
"bot"
],
"license": "MIT",
"main": "./index.js",
"name": "node-telegram-bot-api",
"repository": {
"type": "git",
"url": "git+https://github.com/yagop/node-telegram-bot-api.git"
},
"scripts": {
"build": "babel -d ./lib src",
"doc": "jsdoc2md --files src/telegram.js --template doc/api.hbs > doc/api.md",
"eslint": "eslint ./src ./test ./examples",
"gen-doc": "echo 'WARNING: `npm run gen-doc` is deprecated. Use `npm run doc` instead.' && npm run doc",
"mocha": "mocha",
"prepublishOnly": "npm run build && npm run gen-doc",
"pretest": "npm run build",
"test": "npm run eslint && istanbul cover ./node_modules/mocha/bin/_mocha"
},
"version": "0.40.0"
}

View File

@@ -0,0 +1,65 @@
exports.BaseError = class BaseError extends Error {
/**
* @class BaseError
* @constructor
* @private
* @param {String} code Error code
* @param {String} message Error message
*/
constructor(code, message) {
super(`${code}: ${message}`);
this.code = code;
}
toJSON() {
return {
code: this.code,
message: this.message,
};
}
};
exports.FatalError = class FatalError extends exports.BaseError {
/**
* Fatal Error. Error code is `"EFATAL"`.
* @class FatalError
* @constructor
* @param {String|Error} data Error object or message
*/
constructor(data) {
const error = (typeof data === 'string') ? null : data;
const message = error ? error.message : data;
super('EFATAL', message);
if (error) this.stack = error.stack;
}
};
exports.ParseError = class ParseError extends exports.BaseError {
/**
* Error during parsing. Error code is `"EPARSE"`.
* @class ParseError
* @constructor
* @param {String} message Error message
* @param {http.IncomingMessage} response Server response
*/
constructor(message, response) {
super('EPARSE', message);
this.response = response;
}
};
exports.TelegramError = class TelegramError extends exports.BaseError {
/**
* Error returned from Telegram. Error code is `"ETELEGRAM"`.
* @class TelegramError
* @constructor
* @param {String} message Error message
* @param {http.IncomingMessage} response Server response
*/
constructor(message, response) {
super('ETELEGRAM', message);
this.response = response;
}
};

View File

@@ -0,0 +1,1966 @@
// shims
require('array.prototype.findindex').shim(); // for Node.js v0.x
const errors = require('./errors');
const TelegramBotWebHook = require('./telegramWebHook');
const TelegramBotPolling = require('./telegramPolling');
const debug = require('debug')('node-telegram-bot-api');
const EventEmitter = require('eventemitter3');
const fileType = require('file-type');
const request = require('request-promise');
const streamedRequest = require('request');
const qs = require('querystring');
const stream = require('stream');
const mime = require('mime');
const path = require('path');
const URL = require('url');
const fs = require('fs');
const pump = require('pump');
const deprecate = require('depd')('node-telegram-bot-api');
let Promise = require('bluebird');
const _messageTypes = [
'text',
'animation',
'audio',
'channel_chat_created',
'contact',
'delete_chat_photo',
'document',
'game',
'group_chat_created',
'invoice',
'left_chat_member',
'location',
'migrate_from_chat_id',
'migrate_to_chat_id',
'new_chat_members',
'new_chat_photo',
'new_chat_title',
'passport_data',
'photo',
'pinned_message',
'poll',
'sticker',
'successful_payment',
'supergroup_chat_created',
'video',
'video_note',
'voice',
];
const _deprecatedMessageTypes = [
'new_chat_participant', 'left_chat_participant'
];
if (!process.env.NTBA_FIX_319) {
// Enable Promise cancellation.
try {
const msg =
'Automatic enabling of cancellation of promises is deprecated.\n' +
'In the future, you will have to enable it yourself.\n' +
'See https://github.com/yagop/node-telegram-bot-api/issues/319.';
deprecate(msg);
Promise.config({
cancellation: true,
});
} catch (ex) {
/* eslint-disable no-console */
const msg =
'error: Enabling Promise cancellation failed.\n' +
' Temporary fix is to load/require this library as early as possible before using any Promises.';
console.error(msg);
throw ex;
/* eslint-enable no-console */
}
}
/**
* JSON-serialize data. If the provided data is already a String,
* return it as is.
* @private
* @param {*} data
* @return {String}
*/
function stringify(data) {
if (typeof data === 'string') {
return data;
}
return JSON.stringify(data);
}
class TelegramBot extends EventEmitter {
/**
* The different errors the library uses.
* @type {Object}
*/
static get errors() {
return errors;
}
/**
* The types of message updates the library handles.
* @type {String[]}
*/
static get messageTypes() {
return _messageTypes;
}
/**
* Change Promise library used internally, for all existing and new
* instances.
* @param {Function} customPromise
*
* @example
* const TelegramBot = require('node-telegram-bot-api');
* TelegramBot.Promise = myPromise;
*/
static set Promise(customPromise) {
Promise = customPromise;
}
/**
* Add listener for the specified [event](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events).
* This is the usual `emitter.on()` method.
* @param {String} event
* @param {Function} listener
* @see {@link https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events|Available events}
* @see https://nodejs.org/api/events.html#events_emitter_on_eventname_listener
*/
on(event, listener) {
if (_deprecatedMessageTypes.indexOf(event) !== -1) {
const url = 'https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events';
deprecate(`Events ${_deprecatedMessageTypes.join(',')} are deprecated. See the updated list of events: ${url}`);
}
super.on(event, listener);
}
/**
* Both request method to obtain messages are implemented. To use standard polling, set `polling: true`
* on `options`. Notice that [webHook](https://core.telegram.org/bots/api#setwebhook) will need a SSL certificate.
* Emits `message` when a message arrives.
*
* @class TelegramBot
* @constructor
* @param {String} token Bot Token
* @param {Object} [options]
* @param {Boolean|Object} [options.polling=false] Set true to enable polling or set options.
* If a WebHook has been set, it will be deleted automatically.
* @param {String|Number} [options.polling.timeout=10] *Deprecated. Use `options.polling.params` instead*.
* Timeout in seconds for long polling.
* @param {String|Number} [options.polling.interval=300] Interval between requests in miliseconds
* @param {Boolean} [options.polling.autoStart=true] Start polling immediately
* @param {Object} [options.polling.params] Parameters to be used in polling API requests.
* See https://core.telegram.org/bots/api#getupdates for more information.
* @param {Number} [options.polling.params.timeout=10] Timeout in seconds for long polling.
* @param {Boolean|Object} [options.webHook=false] Set true to enable WebHook or set options
* @param {String} [options.webHook.host="0.0.0.0"] Host to bind to
* @param {Number} [options.webHook.port=8443] Port to bind to
* @param {String} [options.webHook.key] Path to file with PEM private key for webHook server.
* The file is read **synchronously**!
* @param {String} [options.webHook.cert] Path to file with PEM certificate (public) for webHook server.
* The file is read **synchronously**!
* @param {String} [options.webHook.pfx] Path to file with PFX private key and certificate chain for webHook server.
* The file is read **synchronously**!
* @param {Boolean} [options.webHook.autoOpen=true] Open webHook immediately
* @param {Object} [options.webHook.https] Options to be passed to `https.createServer()`.
* Note that `options.webHook.key`, `options.webHook.cert` and `options.webHook.pfx`, if provided, will be
* used to override `key`, `cert` and `pfx` in this object, respectively.
* See https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener for more information.
* @param {String} [options.webHook.healthEndpoint="/healthz"] An endpoint for health checks that always responds with 200 OK
* @param {Boolean} [options.onlyFirstMatch=false] Set to true to stop after first match. Otherwise, all regexps are executed
* @param {Object} [options.request] Options which will be added for all requests to telegram api.
* See https://github.com/request/request#requestoptions-callback for more information.
* @param {String} [options.baseApiUrl="https://api.telegram.org"] API Base URl; useful for proxying and testing
* @param {Boolean} [options.filepath=true] Allow passing file-paths as arguments when sending files,
* such as photos using `TelegramBot#sendPhoto()`. See [usage information][usage-sending-files-performance]
* for more information on this option and its consequences.
* @param {Boolean} [options.badRejection=false] Set to `true`
* **if and only if** the Node.js version you're using terminates the
* process on unhandled rejections. This option is only for
* *forward-compatibility purposes*.
* @see https://core.telegram.org/bots/api
*/
constructor(token, options = {}) {
super();
this.token = token;
this.options = options;
this.options.polling = (typeof options.polling === 'undefined') ? false : options.polling;
this.options.webHook = (typeof options.webHook === 'undefined') ? false : options.webHook;
this.options.baseApiUrl = options.baseApiUrl || 'https://api.telegram.org';
this.options.filepath = (typeof options.filepath === 'undefined') ? true : options.filepath;
this.options.badRejection = (typeof options.badRejection === 'undefined') ? false : options.badRejection;
this._textRegexpCallbacks = [];
this._replyListenerId = 0;
this._replyListeners = [];
this._polling = null;
this._webHook = null;
if (options.polling) {
const autoStart = options.polling.autoStart;
if (typeof autoStart === 'undefined' || autoStart === true) {
this.startPolling();
}
}
if (options.webHook) {
const autoOpen = options.webHook.autoOpen;
if (typeof autoOpen === 'undefined' || autoOpen === true) {
this.openWebHook();
}
}
}
/**
* Generates url with bot token and provided path/method you want to be got/executed by bot
* @param {String} path
* @return {String} url
* @private
* @see https://core.telegram.org/bots/api#making-requests
*/
_buildURL(_path) {
return `${this.options.baseApiUrl}/bot${this.token}/${_path}`;
}
/**
* Fix 'reply_markup' parameter by making it JSON-serialized, as
* required by the Telegram Bot API
* @param {Object} obj Object; either 'form' or 'qs'
* @private
* @see https://core.telegram.org/bots/api#sendmessage
*/
_fixReplyMarkup(obj) {
const replyMarkup = obj.reply_markup;
if (replyMarkup && typeof replyMarkup !== 'string') {
obj.reply_markup = stringify(replyMarkup);
}
}
/**
* Make request against the API
* @param {String} _path API endpoint
* @param {Object} [options]
* @private
* @return {Promise}
*/
_request(_path, options = {}) {
if (!this.token) {
return Promise.reject(new errors.FatalError('Telegram Bot Token not provided!'));
}
if (this.options.request) {
Object.assign(options, this.options.request);
}
if (options.form) {
this._fixReplyMarkup(options.form);
}
if (options.qs) {
this._fixReplyMarkup(options.qs);
}
options.method = 'POST';
options.url = this._buildURL(_path);
options.simple = false;
options.resolveWithFullResponse = true;
options.forever = true;
debug('HTTP request: %j', options);
return request(options)
.then(resp => {
let data;
try {
data = resp.body = JSON.parse(resp.body);
} catch (err) {
throw new errors.ParseError(`Error parsing response: ${resp.body}`, resp);
}
if (data.ok) {
return data.result;
}
throw new errors.TelegramError(`${data.error_code} ${data.description}`, resp);
}).catch(error => {
// TODO: why can't we do `error instanceof errors.BaseError`?
if (error.response) throw error;
throw new errors.FatalError(error);
});
}
/**
* Format data to be uploaded; handles file paths, streams and buffers
* @param {String} type
* @param {String|stream.Stream|Buffer} data
* @param {Object} fileOptions File options
* @param {String} [fileOptions.filename] File name
* @param {String} [fileOptions.contentType] Content type (i.e. MIME)
* @return {Array} formatted
* @return {Object} formatted[0] formData
* @return {String} formatted[1] fileId
* @throws Error if Buffer file type is not supported.
* @see https://npmjs.com/package/file-type
* @private
*/
_formatSendData(type, data, fileOptions = {}) {
const deprecationMessage =
'See https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files' +
' for more information on how sending files has been improved and' +
' on how to disable this deprecation message altogether.';
let filedata = data;
let filename = fileOptions.filename;
let contentType = fileOptions.contentType;
if (data instanceof stream.Stream) {
if (!filename && data.path) {
// Will be 'null' if could not be parsed.
// For example, 'data.path' === '/?id=123' from 'request("https://example.com/?id=123")'
const url = URL.parse(path.basename(data.path.toString()));
if (url.pathname) {
filename = qs.unescape(url.pathname);
}
}
} else if (Buffer.isBuffer(data)) {
if (!filename && !process.env.NTBA_FIX_350) {
deprecate(`Buffers will have their filenames default to "filename" instead of "data". ${deprecationMessage}`);
filename = 'data';
}
if (!contentType) {
const filetype = fileType(data);
if (filetype) {
contentType = filetype.mime;
const ext = filetype.ext;
if (ext && !process.env.NTBA_FIX_350) {
filename = `${filename}.${ext}`;
}
} else if (!process.env.NTBA_FIX_350) {
deprecate(`An error will no longer be thrown if file-type of buffer could not be detected. ${deprecationMessage}`);
throw new errors.FatalError('Unsupported Buffer file-type');
}
}
} else if (data) {
if (this.options.filepath && fs.existsSync(data)) {
filedata = fs.createReadStream(data);
if (!filename) {
filename = path.basename(data);
}
} else {
return [null, data];
}
} else {
return [null, data];
}
filename = filename || 'filename';
contentType = contentType || mime.lookup(filename);
if (process.env.NTBA_FIX_350) {
contentType = contentType || 'application/octet-stream';
} else {
deprecate(`In the future, content-type of files you send will default to "application/octet-stream". ${deprecationMessage}`);
}
// TODO: Add missing file extension.
return [{
[type]: {
value: filedata,
options: {
filename,
contentType,
},
},
}, null];
}
/**
* Start polling.
* Rejects returned promise if a WebHook is being used by this instance.
* @param {Object} [options]
* @param {Boolean} [options.restart=true] Consecutive calls to this method causes polling to be restarted
* @return {Promise}
*/
startPolling(options = {}) {
if (this.hasOpenWebHook()) {
return Promise.reject(new errors.FatalError('Polling and WebHook are mutually exclusive'));
}
options.restart = typeof options.restart === 'undefined' ? true : options.restart;
if (!this._polling) {
this._polling = new TelegramBotPolling(this);
}
return this._polling.start(options);
}
/**
* Alias of `TelegramBot#startPolling()`. This is **deprecated**.
* @param {Object} [options]
* @return {Promise}
* @deprecated
*/
initPolling() {
deprecate('TelegramBot#initPolling() is deprecated. Use TelegramBot#startPolling() instead.');
return this.startPolling();
}
/**
* Stops polling after the last polling request resolves.
* Multiple invocations do nothing if polling is already stopped.
* Returning the promise of the last polling request is **deprecated**.
* @param {Object} [options] Options
* @param {Boolean} [options.cancel] Cancel current request
* @param {String} [options.reason] Reason for stopping polling
* @return {Promise}
*/
stopPolling(options) {
if (!this._polling) {
return Promise.resolve();
}
return this._polling.stop(options);
}
/**
* Return true if polling. Otherwise, false.
* @return {Boolean}
*/
isPolling() {
return this._polling ? this._polling.isPolling() : false;
}
/**
* Open webhook.
* Multiple invocations do nothing if webhook is already open.
* Rejects returned promise if Polling is being used by this instance.
* @return {Promise}
*/
openWebHook() {
if (this.isPolling()) {
return Promise.reject(new errors.FatalError('WebHook and Polling are mutually exclusive'));
}
if (!this._webHook) {
this._webHook = new TelegramBotWebHook(this);
}
return this._webHook.open();
}
/**
* Close webhook after closing all current connections.
* Multiple invocations do nothing if webhook is already closed.
* @return {Promise} promise
*/
closeWebHook() {
if (!this._webHook) {
return Promise.resolve();
}
return this._webHook.close();
}
/**
* Return true if using webhook and it is open i.e. accepts connections.
* Otherwise, false.
* @return {Boolean}
*/
hasOpenWebHook() {
return this._webHook ? this._webHook.isOpen() : false;
}
/**
* Returns basic information about the bot in form of a `User` object.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getme
*/
getMe(form = {}) {
return this._request('getMe', { form });
}
/**
* Specify an url to receive incoming updates via an outgoing webHook.
* This method has an [older, compatible signature][setWebHook-v0.25.0]
* that is being deprecated.
*
* @param {String} url URL where Telegram will make HTTP Post. Leave empty to
* delete webHook.
* @param {Object} [options] Additional Telegram query options
* @param {String|stream.Stream} [options.certificate] PEM certificate key (public).
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#setwebhook
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
setWebHook(url, options = {}, fileOptions = {}) {
/* The older method signature was setWebHook(url, cert).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
let cert;
// Note: 'options' could be an object, if a stream was provided (in place of 'cert')
if (typeof options !== 'object' || options instanceof stream.Stream) {
deprecate('The method signature setWebHook(url, cert) has been deprecated since v0.25.0');
cert = options;
options = {}; // eslint-disable-line no-param-reassign
} else {
cert = options.certificate;
}
const opts = {
qs: options,
};
opts.qs.url = url;
if (cert) {
try {
const sendData = this._formatSendData('certificate', cert, fileOptions);
opts.formData = sendData[0];
opts.qs.certificate = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
}
return this._request('setWebHook', opts);
}
/**
* Use this method to remove webhook integration if you decide to
* switch back to getUpdates. Returns True on success.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletewebhook
*/
deleteWebHook(form = {}) {
return this._request('deleteWebhook', { form });
}
/**
* Use this method to get current webhook status.
* On success, returns a [WebhookInfo](https://core.telegram.org/bots/api#webhookinfo) object.
* If the bot is using getUpdates, will return an object with the
* url field empty.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getwebhookinfo
*/
getWebHookInfo(form = {}) {
return this._request('getWebhookInfo', { form });
}
/**
* Use this method to receive incoming updates using long polling.
* This method has an [older, compatible signature][getUpdates-v0.25.0]
* that is being deprecated.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getupdates
*/
getUpdates(form = {}) {
/* The older method signature was getUpdates(timeout, limit, offset).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
if (typeof form !== 'object') {
/* eslint-disable no-param-reassign, prefer-rest-params */
deprecate('The method signature getUpdates(timeout, limit, offset) has been deprecated since v0.25.0');
form = {
timeout: arguments[0],
limit: arguments[1],
offset: arguments[2],
};
/* eslint-enable no-param-reassign, prefer-rest-params */
}
return this._request('getUpdates', { form });
}
/**
* Process an update; emitting the proper events and executing regexp
* callbacks. This method is useful should you be using a different
* way to fetch updates, other than those provided by TelegramBot.
* @param {Object} update
* @see https://core.telegram.org/bots/api#update
*/
processUpdate(update) {
debug('Process Update %j', update);
const message = update.message;
const editedMessage = update.edited_message;
const channelPost = update.channel_post;
const editedChannelPost = update.edited_channel_post;
const inlineQuery = update.inline_query;
const chosenInlineResult = update.chosen_inline_result;
const callbackQuery = update.callback_query;
const shippingQuery = update.shipping_query;
const preCheckoutQuery = update.pre_checkout_query;
const poll = update.poll;
if (message) {
debug('Process Update message %j', message);
const metadata = {};
metadata.type = TelegramBot.messageTypes.find((messageType) => {
return message[messageType];
});
this.emit('message', message, metadata);
if (metadata.type) {
debug('Emitting %s: %j', metadata.type, message);
this.emit(metadata.type, message, metadata);
}
if (message.text) {
debug('Text message');
this._textRegexpCallbacks.some(reg => {
debug('Matching %s with %s', message.text, reg.regexp);
const result = reg.regexp.exec(message.text);
if (!result) {
return false;
}
// reset index so we start at the beginning of the regex each time
reg.regexp.lastIndex = 0;
debug('Matches %s', reg.regexp);
reg.callback(message, result);
// returning truthy value exits .some
return this.options.onlyFirstMatch;
});
}
if (message.reply_to_message) {
// Only callbacks waiting for this message
this._replyListeners.forEach(reply => {
// Message from the same chat
if (reply.chatId === message.chat.id) {
// Responding to that message
if (reply.messageId === message.reply_to_message.message_id) {
// Resolve the promise
reply.callback(message);
}
}
});
}
} else if (editedMessage) {
debug('Process Update edited_message %j', editedMessage);
this.emit('edited_message', editedMessage);
if (editedMessage.text) {
this.emit('edited_message_text', editedMessage);
}
if (editedMessage.caption) {
this.emit('edited_message_caption', editedMessage);
}
} else if (channelPost) {
debug('Process Update channel_post %j', channelPost);
this.emit('channel_post', channelPost);
} else if (editedChannelPost) {
debug('Process Update edited_channel_post %j', editedChannelPost);
this.emit('edited_channel_post', editedChannelPost);
if (editedChannelPost.text) {
this.emit('edited_channel_post_text', editedChannelPost);
}
if (editedChannelPost.caption) {
this.emit('edited_channel_post_caption', editedChannelPost);
}
} else if (inlineQuery) {
debug('Process Update inline_query %j', inlineQuery);
this.emit('inline_query', inlineQuery);
} else if (chosenInlineResult) {
debug('Process Update chosen_inline_result %j', chosenInlineResult);
this.emit('chosen_inline_result', chosenInlineResult);
} else if (callbackQuery) {
debug('Process Update callback_query %j', callbackQuery);
this.emit('callback_query', callbackQuery);
} else if (shippingQuery) {
debug('Process Update shipping_query %j', shippingQuery);
this.emit('shipping_query', shippingQuery);
} else if (preCheckoutQuery) {
debug('Process Update pre_checkout_query %j', preCheckoutQuery);
this.emit('pre_checkout_query', preCheckoutQuery);
} else if (poll) {
debug('Process Update poll %j', poll);
this.emit('poll', poll);
}
}
/**
* Send text message.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} text Text of the message to be sent
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendmessage
*/
sendMessage(chatId, text, form = {}) {
form.chat_id = chatId;
form.text = text;
return this._request('sendMessage', { form });
}
/**
* Send answers to an inline query.
* @param {String} inlineQueryId Unique identifier of the query
* @param {InlineQueryResult[]} results An array of results for the inline query
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#answerinlinequery
*/
answerInlineQuery(inlineQueryId, results, form = {}) {
form.inline_query_id = inlineQueryId;
form.results = stringify(results);
return this._request('answerInlineQuery', { form });
}
/**
* Forward messages of any kind.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Number|String} fromChatId Unique identifier for the chat where the
* original message was sent
* @param {Number|String} messageId Unique message identifier
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
*/
forwardMessage(chatId, fromChatId, messageId, form = {}) {
form.chat_id = chatId;
form.from_chat_id = fromChatId;
form.message_id = messageId;
return this._request('forwardMessage', { form });
}
/**
* Send photo
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} photo A file path or a Stream. Can
* also be a `file_id` previously uploaded
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendphoto
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
sendPhoto(chatId, photo, options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('photo', photo, fileOptions);
opts.formData = sendData[0];
opts.qs.photo = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendPhoto', opts);
}
/**
* Send audio
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} audio A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendaudio
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
sendAudio(chatId, audio, options = {}, fileOptions = {}) {
const opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('audio', audio, fileOptions);
opts.formData = sendData[0];
opts.qs.audio = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendAudio', opts);
}
/**
* Send Document
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} doc A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendDocument
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
sendDocument(chatId, doc, options = {}, fileOptions = {}) {
const opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('document', doc, fileOptions);
opts.formData = sendData[0];
opts.qs.document = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendDocument', opts);
}
/**
* Send .webp stickers.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} sticker A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded. Stickers are WebP format files.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendsticker
*/
sendSticker(chatId, sticker, options = {}, fileOptions = {}) {
const opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('sticker', sticker, fileOptions);
opts.formData = sendData[0];
opts.qs.sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendSticker', opts);
}
/**
* Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} video A file path or Stream.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendvideo
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
sendVideo(chatId, video, options = {}, fileOptions = {}) {
const opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('video', video, fileOptions);
opts.formData = sendData[0];
opts.qs.video = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendVideo', opts);
}
/**
* Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} animation A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendanimation
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
sendAnimation(chatId, animation, options = {}, fileOptions = {}) {
const opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('animation', animation, fileOptions);
opts.formData = sendData[0];
opts.qs.document = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendAnimation', opts);
}
/**
* Use this method to send rounded square videos of upto 1 minute long.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} videoNote A file path or Stream.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @info The length parameter is actually optional. However, the API (at time of writing) requires you to always provide it until it is fixed.
* @see https://core.telegram.org/bots/api#sendvideonote
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
sendVideoNote(chatId, videoNote, options = {}, fileOptions = {}) {
const opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('video_note', videoNote, fileOptions);
opts.formData = sendData[0];
opts.qs.video_note = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendVideoNote', opts);
}
/**
* Send voice
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String|stream.Stream|Buffer} voice A file path, Stream or Buffer.
* Can also be a `file_id` previously uploaded.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendvoice
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
sendVoice(chatId, voice, options = {}, fileOptions = {}) {
const opts = {
qs: options
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('voice', voice, fileOptions);
opts.formData = sendData[0];
opts.qs.voice = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendVoice', opts);
}
/**
* 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.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} action Type of action to broadcast.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendchataction
*/
sendChatAction(chatId, action, form = {}) {
form.chat_id = chatId;
form.action = action;
return this._request('sendChatAction', { form });
}
/**
* Use this method to kick a user from a group or a supergroup.
* In the case of supergroups, the user will not be able to return
* to the group on their own using invite links, etc., unless unbanned
* first. The bot must be an administrator in the group for this to work.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#kickchatmember
*/
kickChatMember(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('kickChatMember', { form });
}
/**
* Use this method to unban a previously kicked user in a supergroup.
* The user will not return to the group automatically, but will be
* able to join via link, etc. The bot must be an administrator in
* the group for this to work. Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#unbanchatmember
*/
unbanChatMember(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('unbanChatMember', { form });
}
/**
* 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. Pass True for all boolean parameters
* to lift restrictions from a user. Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target supergroup
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#restrictchatmember
*/
restrictChatMember(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('restrictChatMember', { form });
}
/**
* 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. Pass False for all boolean parameters to demote a user.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target supergroup
* @param {Number} userId
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#promotechatmember
*/
promoteChatMember(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('promoteChatMember', { form });
}
/**
* 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.
* Returns exported invite link as String on success.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target supergroup
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#exportchatinvitelink
*/
exportChatInviteLink(chatId, form = {}) {
form.chat_id = chatId;
return this._request('exportChatInviteLink', { form });
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {stream.Stream|Buffer} photo A file path or a Stream.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#setchatphoto
*/
setChatPhoto(chatId, photo, options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('photo', photo, fileOptions);
opts.formData = sendData[0];
opts.qs.photo = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('setChatPhoto', opts);
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletechatphoto
*/
deleteChatPhoto(chatId, form = {}) {
form.chat_id = chatId;
return this._request('deleteChatPhoto', { form });
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} title New chat title, 1-255 characters
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setchattitle
*/
setChatTitle(chatId, title, form = {}) {
form.chat_id = chatId;
form.title = title;
return this._request('setChatTitle', { form });
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} description New chat title, 1-255 characters
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setchatdescription
*/
setChatDescription(chatId, description, form = {}) {
form.chat_id = chatId;
form.description = description;
return this._request('setChatDescription', { form });
}
/**
* 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.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Number} messageId Identifier of a message to pin
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#pinchatmessage
*/
pinChatMessage(chatId, messageId, form = {}) {
form.chat_id = chatId;
form.message_id = messageId;
return this._request('pinChatMessage', { form });
}
/**
* Use this method to unpin a message in a supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Returns True on success.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#unpinchatmessage
*/
unpinChatMessage(chatId, form = {}) {
form.chat_id = chatId;
return this._request('unpinChatMessage', { form });
}
/**
* Use this method to send answers to callback queries sent from
* inline keyboards. The answer will be displayed to the user as
* a notification at the top of the chat screen or as an alert.
* On success, True is returned.
*
* This method has **older, compatible signatures ([1][answerCallbackQuery-v0.27.1])([2][answerCallbackQuery-v0.29.0])**
* that are being deprecated.
*
* @param {String} callbackQueryId Unique identifier for the query to be answered
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#answercallbackquery
*/
answerCallbackQuery(callbackQueryId, form = {}) {
/* The older method signature (in/before v0.27.1) was answerCallbackQuery(callbackQueryId, text, showAlert).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
if (typeof form !== 'object') {
/* eslint-disable no-param-reassign, prefer-rest-params */
deprecate('The method signature answerCallbackQuery(callbackQueryId, text, showAlert) has been deprecated since v0.27.1');
form = {
callback_query_id: arguments[0],
text: arguments[1],
show_alert: arguments[2],
};
/* eslint-enable no-param-reassign, prefer-rest-params */
}
/* The older method signature (in/before v0.29.0) was answerCallbackQuery([options]).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library. */
if (typeof callbackQueryId === 'object') {
/* eslint-disable no-param-reassign, prefer-rest-params */
deprecate('The method signature answerCallbackQuery([options]) has been deprecated since v0.29.0');
form = callbackQueryId;
/* eslint-enable no-param-reassign, prefer-rest-params */
} else {
form.callback_query_id = callbackQueryId;
}
return this._request('answerCallbackQuery', { form });
}
/**
* Use this method to edit text messages sent by the bot or via
* the bot (for inline bots). On success, the edited Message is
* returned.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {String} text New text of the message
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagetext
*/
editMessageText(text, form = {}) {
form.text = text;
return this._request('editMessageText', { form });
}
/**
* Use this method to edit captions of messages sent by the
* bot or via the bot (for inline bots). On success, the
* edited Message is returned.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {String} caption New caption of the message
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagecaption
*/
editMessageCaption(caption, form = {}) {
form.caption = caption;
return this._request('editMessageCaption', { form });
}
/**
* Use this method to edit audio, document, photo, or video messages.
* If a message is a part of a message album, then it can be edited only to a photo or a video.
* Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded.
* Use previously uploaded file via its file_id or specify a URL.
* On success, the edited Message is returned.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {Object} media A JSON-serialized object for a new media content of the message
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagemedia
*/
editMessageMedia(media, form = {}) {
form.media = stringify(media);
return this._request('editMessageMedia', { form });
}
/**
* Use this method to edit only the reply markup of messages
* sent by the bot or via the bot (for inline bots).
* On success, the edited Message is returned.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {Object} replyMarkup A JSON-serialized object for an inline keyboard.
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagetext
*/
editMessageReplyMarkup(replyMarkup, form = {}) {
form.reply_markup = replyMarkup;
return this._request('editMessageReplyMarkup', { form });
}
/**
* Use this method to get a list of profile pictures for a user.
* Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object.
* This method has an [older, compatible signature][getUserProfilePhotos-v0.25.0]
* that is being deprecated.
*
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getuserprofilephotos
*/
getUserProfilePhotos(userId, form = {}) {
/* The older method signature was getUserProfilePhotos(userId, offset, limit).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
if (typeof form !== 'object') {
/* eslint-disable no-param-reassign, prefer-rest-params */
deprecate('The method signature getUserProfilePhotos(userId, offset, limit) has been deprecated since v0.25.0');
form = {
offset: arguments[1],
limit: arguments[2],
};
/* eslint-enable no-param-reassign, prefer-rest-params */
}
form.user_id = userId;
return this._request('getUserProfilePhotos', { form });
}
/**
* Send location.
* Use this method to send point on the map.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Float} latitude Latitude of location
* @param {Float} longitude Longitude of location
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendlocation
*/
sendLocation(chatId, latitude, longitude, form = {}) {
form.chat_id = chatId;
form.latitude = latitude;
form.longitude = longitude;
return this._request('sendLocation', { form });
}
/**
* Use this method to edit live location messages sent by
* the bot or via the bot (for inline bots).
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {Float} latitude Latitude of location
* @param {Float} longitude Longitude of location
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#editmessagelivelocation
*/
editMessageLiveLocation(latitude, longitude, form = {}) {
form.latitude = latitude;
form.longitude = longitude;
return this._request('editMessageLiveLocation', { form });
}
/**
* 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.
*
* Note that you must provide one of chat_id, message_id, or
* inline_message_id in your request.
*
* @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
* @return {Promise}
* @see https://core.telegram.org/bots/api#stopmessagelivelocation
*/
stopMessageLiveLocation(form = {}) {
return this._request('stopMessageLiveLocation', { form });
}
/**
* Send venue.
* Use this method to send information about a venue.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {Float} latitude Latitude of location
* @param {Float} longitude Longitude of location
* @param {String} title Name of the venue
* @param {String} address Address of the venue
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendvenue
*/
sendVenue(chatId, latitude, longitude, title, address, form = {}) {
form.chat_id = chatId;
form.latitude = latitude;
form.longitude = longitude;
form.title = title;
form.address = address;
return this._request('sendVenue', { form });
}
/**
* Send contact.
* Use this method to send phone contacts.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} phoneNumber Contact's phone number
* @param {String} firstName Contact's first name
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendcontact
*/
sendContact(chatId, phoneNumber, firstName, form = {}) {
form.chat_id = chatId;
form.phone_number = phoneNumber;
form.first_name = firstName;
return this._request('sendContact', { form });
}
/**
* Send poll.
* Use this method to send a native poll.
*
* @param {Number|String} chatId Unique identifier for the group/channel
* @param {String} question Poll question, 255 char limit
* @param {Array} pollOptions Poll options, between 2-10 options
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendpoll
*/
sendPoll(chatId, question, pollOptions, form = {}) {
form.chat_id = chatId;
form.question = question;
form.options = stringify(pollOptions);
return this._request('sendPoll', { form });
}
/**
* Stop poll.
* Use this method to stop a native poll.
*
* @param {Number|String} chatId Unique identifier for the group/channel
* @param {Number} pollId Identifier of the original message with the poll
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#stoppoll
*/
stopPoll(chatId, pollId, form = {}) {
form.chat_id = chatId;
form.message_id = pollId;
return this._request('stopPoll', { form });
}
/**
* 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.
*
* @param {String} fileId File identifier to get info about
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getfile
*/
getFile(fileId, form = {}) {
form.file_id = fileId;
return this._request('getFile', { form });
}
/**
* 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).
*
* @param {String} fileId File identifier to get info about
* @param {Object} [options] Additional Telegram query options
* @return {Promise} promise Promise which will have *fileURI* in resolve callback
* @see https://core.telegram.org/bots/api#getfile
*/
getFileLink(fileId, form = {}) {
return this.getFile(fileId, form)
.then(resp => `${this.options.baseApiUrl}/file/bot${this.token}/${resp.file_path}`);
}
/**
* Return a readable stream for file.
*
* `fileStream.path` is the specified file ID i.e. `fileId`.
* `fileStream` emits event `info` passing a single argument i.e.
* `info` with the interface `{ uri }` where `uri` is the URI of the
* file on Telegram servers.
*
* This method is a sugar extension of the [getFileLink](#TelegramBot+getFileLink) method,
* which returns the full URI to the file on remote server.
*
* @param {String} fileId File identifier to get info about
* @param {Object} [options] Additional Telegram query options
* @return {stream.Readable} fileStream
*/
getFileStream(fileId, form = {}) {
const fileStream = new stream.PassThrough();
fileStream.path = fileId;
this.getFileLink(fileId, form)
.then((fileURI) => {
fileStream.emit('info', {
uri: fileURI,
});
pump(streamedRequest({ uri: fileURI }), fileStream);
})
.catch((error) => {
fileStream.emit('error', error);
});
return fileStream;
}
/**
* Downloads file in the specified folder.
*
* This method is a sugar extension of the [getFileStream](#TelegramBot+getFileStream) method,
* which returns a readable file stream.
*
* @param {String} fileId File identifier to get info about
* @param {String} downloadDir Absolute path to the folder in which file will be saved
* @param {Object} [options] Additional Telegram query options
* @return {Promise} promise Promise, which will have *filePath* of downloaded file in resolve callback
*/
downloadFile(fileId, downloadDir, form = {}) {
let resolve;
let reject;
const promise = new Promise((a, b) => {
resolve = a;
reject = b;
});
const fileStream = this.getFileStream(fileId, form);
fileStream.on('info', (info) => {
const fileName = info.uri.slice(info.uri.lastIndexOf('/') + 1);
// TODO: Ensure fileName doesn't contains slashes
const filePath = path.join(downloadDir, fileName);
pump(fileStream, fs.createWriteStream(filePath), (error) => {
if (error) { return reject(error); }
return resolve(filePath);
});
});
return promise;
}
/**
* Register a RegExp to test against an incomming text message.
* @param {RegExp} regexp RegExp to be executed with `exec`.
* @param {Function} callback Callback will be called with 2 parameters,
* the `msg` and the result of executing `regexp.exec` on message text.
*/
onText(regexp, callback) {
this._textRegexpCallbacks.push({ regexp, callback });
}
/**
* Remove a listener registered with `onText()`.
* @param {RegExp} regexp RegExp used previously in `onText()`
* @return {Object} deletedListener The removed reply listener if
* found. This object has `regexp` and `callback`
* properties. If not found, returns `null`.
*/
removeTextListener(regexp) {
const index = this._textRegexpCallbacks.findIndex((textListener) => {
return textListener.regexp === regexp;
});
if (index === -1) {
return null;
}
return this._textRegexpCallbacks.splice(index, 1)[0];
}
/**
* Register a reply to wait for a message response.
* @param {Number|String} chatId The chat id where the message cames from.
* @param {Number|String} messageId The message id to be replied.
* @param {Function} callback Callback will be called with the reply
* message.
* @return {Number} id The ID of the inserted reply listener.
*/
onReplyToMessage(chatId, messageId, callback) {
const id = ++this._replyListenerId;
this._replyListeners.push({
id,
chatId,
messageId,
callback
});
return id;
}
/**
* Removes a reply that has been prev. registered for a message response.
* @param {Number} replyListenerId The ID of the reply listener.
* @return {Object} deletedListener The removed reply listener if
* found. This object has `id`, `chatId`, `messageId` and `callback`
* properties. If not found, returns `null`.
*/
removeReplyListener(replyListenerId) {
const index = this._replyListeners.findIndex((replyListener) => {
return replyListener.id === replyListenerId;
});
if (index === -1) {
return null;
}
return this._replyListeners.splice(index, 1)[0];
}
/**
* Use this method to get up to date information about the chat
* (current name of the user for one-on-one conversations, current
* username of a user, group or channel, etc.).
* @param {Number|String} chatId Unique identifier for the target chat or username of the target supergroup or channel
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getchat
*/
getChat(chatId, form = {}) {
form.chat_id = chatId;
return this._request('getChat', { form });
}
/**
* Returns the administrators in a chat in form of an Array of `ChatMember` objects.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getchatadministrators
*/
getChatAdministrators(chatId, form = {}) {
form.chat_id = chatId;
return this._request('getChatAdministrators', { form });
}
/**
* Use this method to get the number of members in a chat.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getchatmemberscount
*/
getChatMembersCount(chatId, form = {}) {
form.chat_id = chatId;
return this._request('getChatMembersCount', { form });
}
/**
* Use this method to get information about a member of a chat.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getchatmember
*/
getChatMember(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('getChatMember', { form });
}
/**
* Leave a group, supergroup or channel.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#leavechat
*/
leaveChat(chatId, form = {}) {
form.chat_id = chatId;
return this._request('leaveChat', { form });
}
/**
* Use this method to set a new group sticker set for a supergroup.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {String} stickerSetName Name of the sticker set to be set as the group sticker set
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setchatstickerset
*/
setChatStickerSet(chatId, stickerSetName, form = {}) {
form.chat_id = chatId;
form.sticker_set_name = stickerSetName;
return this._request('setChatStickerSet', { form });
}
/**
* Use this method to delete a group sticker set from a supergroup.
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletechatstickerset
*/
deleteChatStickerSet(chatId, form = {}) {
form.chat_id = chatId;
return this._request('deleteChatStickerSet', { form });
}
/**
* Use this method to send a game.
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} gameShortName name of the game to be sent.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendgame
*/
sendGame(chatId, gameShortName, form = {}) {
form.chat_id = chatId;
form.game_short_name = gameShortName;
return this._request('sendGame', { form });
}
/**
* Use this method to set the score of the specified user in a game.
* @param {Number} userId Unique identifier of the target user
* @param {Number} score New score value.
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setgamescore
*/
setGameScore(userId, score, form = {}) {
form.user_id = userId;
form.score = score;
return this._request('setGameScore', { form });
}
/**
* Use this method to get data for high score table.
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getgamehighscores
*/
getGameHighScores(userId, form = {}) {
form.user_id = userId;
return this._request('getGameHighScores', { form });
}
/**
* Use this method to delete a message.
* @param {Number|String} chatId Unique identifier of the target chat
* @param {Number} messageId Unique identifier of the target message
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletemessage
*/
deleteMessage(chatId, messageId, form = {}) {
form.chat_id = chatId;
form.message_id = messageId;
return this._request('deleteMessage', { form });
}
/**
* Send invoice.
* Use this method to send an invoice.
*
* @param {Number|String} chatId Unique identifier for the message recipient
* @param {String} title Product name
* @param {String} description product description
* @param {String} payload Bot defined invoice payload
* @param {String} providerToken Payments provider token
* @param {String} startParameter Deep-linking parameter
* @param {String} currency Three-letter ISO 4217 currency code
* @param {Array} prices Breakdown of prices
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendinvoice
*/
sendInvoice(chatId, title, description, payload, providerToken, startParameter, currency, prices, form = {}) {
form.chat_id = chatId;
form.title = title;
form.description = description;
form.payload = payload;
form.provider_token = providerToken;
form.start_parameter = startParameter;
form.currency = currency;
form.prices = stringify(prices);
form.provider_data = stringify(form.provider_data);
return this._request('sendInvoice', { form });
}
/**
* Answer shipping query..
* Use this method to reply to shipping queries.
*
* @param {String} shippingQueryId Unique identifier for the query to be answered
* @param {Boolean} ok Specify if delivery of the product is possible
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#answershippingquery
*/
answerShippingQuery(shippingQueryId, ok, form = {}) {
form.shipping_query_id = shippingQueryId;
form.ok = ok;
form.shipping_options = stringify(form.shipping_options);
return this._request('answerShippingQuery', { form });
}
/**
* Answer pre-checkout query.
* Use this method to confirm shipping of a product.
*
* @param {String} preCheckoutQueryId Unique identifier for the query to be answered
* @param {Boolean} ok Specify if every order details are ok
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#answerprecheckoutquery
*/
answerPreCheckoutQuery(preCheckoutQueryId, ok, form = {}) {
form.pre_checkout_query_id = preCheckoutQueryId;
form.ok = ok;
return this._request('answerPreCheckoutQuery', { form });
}
/**
* Use this method to get a sticker set. On success, a [StickerSet](https://core.telegram.org/bots/api#stickerset) object is returned.
*
* @param {String} name Name of the sticker set
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#getstickerset
*/
getStickerSet(name, form = {}) {
form.name = name;
return this._request('getStickerSet', { form });
}
/**
* Use this method to upload a .png file with a sticker for later use in *createNewStickerSet* and *addStickerToSet* methods (can be used multiple
* times). Returns the uploaded [File](https://core.telegram.org/bots/api#file) on success.
*
* @param {Number} userId User identifier of sticker file owner
* @param {String|stream.Stream|Buffer} pngSticker A file path or a Stream. Can also be a `file_id` previously uploaded. **Png** image with the
* sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#uploadstickerfile
*/
uploadStickerFile(userId, pngSticker, options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
try {
const sendData = this._formatSendData('png_sticker', pngSticker, fileOptions);
opts.formData = sendData[0];
opts.qs.png_sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('uploadStickerFile', opts);
}
/**
* Use this method to create new sticker set owned by a user.
* The bot will be able to edit the created sticker set.
* Returns True on success.
*
* @param {Number} userId User identifier of created sticker set owner
* @param {String} name Short name of sticker set, to be used in `t.me/addstickers/` URLs (e.g., *animals*)
* @param {String} title Sticker set title, 1-64 characters
* @param {String|stream.Stream|Buffer} pngSticker Png image with the sticker, must be up to 512 kilobytes in size,
* dimensions must not exceed 512px, and either width or height must be exactly 512px.
* @param {String} emojis One or more emoji corresponding to the sticker
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#createnewstickerset
* @todo Add tests for this method!
*/
createNewStickerSet(userId, name, title, pngSticker, emojis, options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
opts.qs.name = name;
opts.qs.title = title;
opts.qs.emojis = emojis;
opts.qs.mask_position = stringify(options.mask_position);
try {
const sendData = this._formatSendData('png_sticker', pngSticker, fileOptions);
opts.formData = sendData[0];
opts.qs.png_sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('createNewStickerSet', opts);
}
/**
* Use this method to add a new sticker to a set created by the bot.
* Returns True on success.
*
* @param {Number} userId User identifier of sticker set owner
* @param {String} name Sticker set name
* @param {String|stream.Stream|Buffer} pngSticker Png image with the sticker, must be up to 512 kilobytes in size,
* dimensions must not exceed 512px, and either width or height must be exactly 512px
* @param {String} emojis One or more emoji corresponding to the sticker
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise}
* @see https://core.telegram.org/bots/api#addstickertoset
* @todo Add tests for this method!
*/
addStickerToSet(userId, name, pngSticker, emojis, options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
opts.qs.name = name;
opts.qs.emojis = emojis;
opts.qs.mask_position = stringify(options.mask_position);
try {
const sendData = this._formatSendData('png_sticker', pngSticker, fileOptions);
opts.formData = sendData[0];
opts.qs.png_sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('addStickerToSet', opts);
}
/**
* Use this method to move a sticker in a set created by the bot to a specific position.
* Returns True on success.
*
* @param {String} sticker File identifier of the sticker
* @param {Number} position New sticker position in the set, zero-based
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#setstickerpositioninset
* @todo Add tests for this method!
*/
setStickerPositionInSet(sticker, position, form = {}) {
form.sticker = sticker;
form.position = position;
return this._request('setStickerPositionInSet', { form });
}
/**
* Use this method to delete a sticker from a set created by the bot.
* Returns True on success.
*
* @param {String} sticker File identifier of the sticker
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#deletestickerfromset
* @todo Add tests for this method!
*/
deleteStickerFromSet(sticker, form = {}) {
form.sticker = sticker;
return this._request('deleteStickerFromSet', { form });
}
/**
* Use this method to send a group of photos or videos as an album.
* On success, an array of the sent [Messages](https://core.telegram.org/bots/api#message)
* is returned.
*
* If you wish to [specify file options](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files),
* add a `fileOptions` property to the target input in `media`.
*
* @param {String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Array} media A JSON-serialized array describing photos and videos to be sent, must include 210 items
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#sendmediagroup
* @see https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files
*/
sendMediaGroup(chatId, media, options = {}) {
const opts = {
qs: options,
};
opts.qs.chat_id = chatId;
opts.formData = {};
const inputMedia = [];
let index = 0;
for (const input of media) {
const payload = Object.assign({}, input);
delete payload.media;
delete payload.fileOptions;
try {
const attachName = String(index);
const [formData, fileId] = this._formatSendData(attachName, input.media, input.fileOptions);
if (formData) {
opts.formData[attachName] = formData[attachName];
payload.media = `attach://${attachName}`;
} else {
payload.media = fileId;
}
} catch (ex) {
return Promise.reject(ex);
}
inputMedia.push(payload);
index++;
}
opts.qs.media = JSON.stringify(inputMedia);
return this._request('sendMediaGroup', opts);
}
}
module.exports = TelegramBot;

View File

@@ -0,0 +1,202 @@
const errors = require('./errors');
const debug = require('debug')('node-telegram-bot-api');
const deprecate = require('depd')('node-telegram-bot-api');
const ANOTHER_WEB_HOOK_USED = 409;
class TelegramBotPolling {
/**
* Handles polling against the Telegram servers.
* @param {TelegramBot} bot
* @see https://core.telegram.org/bots/api#getting-updates
*/
constructor(bot) {
this.bot = bot;
this.options = (typeof bot.options.polling === 'boolean') ? {} : bot.options.polling;
this.options.interval = (typeof this.options.interval === 'number') ? this.options.interval : 300;
this.options.params = (typeof this.options.params === 'object') ? this.options.params : {};
this.options.params.offset = (typeof this.options.params.offset === 'number') ? this.options.params.offset : 0;
this.options.params.timeout = (typeof this.options.params.timeout === 'number') ? this.options.params.timeout : 10;
if (typeof this.options.timeout === 'number') {
deprecate('`options.polling.timeout` is deprecated. Use `options.polling.params` instead.');
this.options.params.timeout = this.options.timeout;
}
this._lastUpdate = 0;
this._lastRequest = null;
this._abort = false;
this._pollingTimeout = null;
}
/**
* Start polling
* @param {Object} [options]
* @param {Object} [options.restart]
* @return {Promise}
*/
start(options = {}) {
if (this._lastRequest) {
if (!options.restart) {
return Promise.resolve();
}
return this.stop({
cancel: true,
reason: 'Polling restart',
}).then(() => {
return this._polling();
});
}
return this._polling();
}
/**
* Stop polling
* @param {Object} [options] Options
* @param {Boolean} [options.cancel] Cancel current request
* @param {String} [options.reason] Reason for stopping polling
* @return {Promise}
*/
stop(options = {}) {
if (!this._lastRequest) {
return Promise.resolve();
}
const lastRequest = this._lastRequest;
this._lastRequest = null;
clearTimeout(this._pollingTimeout);
if (options.cancel) {
const reason = options.reason || 'Polling stop';
lastRequest.cancel(reason);
return Promise.resolve();
}
this._abort = true;
return lastRequest.finally(() => {
this._abort = false;
});
}
/**
* Return `true` if is polling. Otherwise, `false`.
*/
isPolling() {
return !!this._lastRequest;
}
/**
* Handle error thrown during polling.
* @private
* @param {Error} error
*/
_error(error) {
if (!this.bot.listeners('polling_error').length) {
return console.error('error: [polling_error] %j', error); // eslint-disable-line no-console
}
return this.bot.emit('polling_error', error);
}
/**
* Invokes polling (with recursion!)
* @return {Promise} promise of the current request
* @private
*/
_polling() {
this._lastRequest = this
._getUpdates()
.then(updates => {
this._lastUpdate = Date.now();
debug('polling data %j', updates);
updates.forEach(update => {
this.options.params.offset = update.update_id + 1;
debug('updated offset: %s', this.options.params.offset);
try {
this.bot.processUpdate(update);
} catch (err) {
err._processing = true;
throw err;
}
});
return null;
})
.catch(err => {
debug('polling error: %s', err.message);
if (!err._processing) {
return this._error(err);
}
delete err._processing;
/*
* An error occured while processing the items,
* i.e. in `this.bot.processUpdate()` above.
* We need to mark the already-processed items
* to avoid fetching them again once the application
* is restarted, or moves to next polling interval
* (in cases where unhandled rejections do not terminate
* the process).
* See https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067
*/
if (!this.bot.options.badRejection) {
return this._error(err);
}
const opts = {
offset: this.options.params.offset,
limit: 1,
timeout: 0,
};
return this.bot.getUpdates(opts).then(() => {
return this._error(err);
}).catch(requestErr => {
/*
* We have been unable to handle this error.
* We have to log this to stderr to ensure devops
* understands that they may receive already-processed items
* on app restart.
* We simply can not rescue this situation, emit "error"
* event, with the hope that the application exits.
*/
/* eslint-disable no-console */
const bugUrl = 'https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067';
console.error('error: Internal handling of The Offset Infinite Loop failed');
console.error(`error: Due to error '${requestErr}'`);
console.error('error: You may receive already-processed updates on app restart');
console.error(`error: Please see ${bugUrl} for more information`);
/* eslint-enable no-console */
return this.bot.emit('error', new errors.FatalError(err));
});
})
.finally(() => {
if (this._abort) {
debug('Polling is aborted!');
} else {
debug('setTimeout for %s miliseconds', this.options.interval);
this._pollingTimeout = setTimeout(() => this._polling(), this.options.interval);
}
});
return this._lastRequest;
}
/**
* Unset current webhook. Used when we detect that a webhook has been set
* and we are trying to poll. Polling and WebHook are mutually exclusive.
* @see https://core.telegram.org/bots/api#getting-updates
* @private
*/
_unsetWebHook() {
debug('unsetting webhook');
return this.bot._request('setWebHook');
}
/**
* Retrieve updates
*/
_getUpdates() {
debug('polling with options: %j', this.options.params);
return this.bot.getUpdates(this.options.params)
.catch(err => {
if (err.response && err.response.statusCode === ANOTHER_WEB_HOOK_USED) {
return this._unsetWebHook().then(() => {
return this.bot.getUpdates(this.options.params);
});
}
throw err;
});
}
}
module.exports = TelegramBotPolling;

View File

@@ -0,0 +1,156 @@
const errors = require('./errors');
const debug = require('debug')('node-telegram-bot-api');
const https = require('https');
const http = require('http');
const fs = require('fs');
const bl = require('bl');
const Promise = require('bluebird');
class TelegramBotWebHook {
/**
* Sets up a webhook to receive updates
* @param {TelegramBot} bot
* @see https://core.telegram.org/bots/api#getting-updates
*/
constructor(bot) {
this.bot = bot;
this.options = (typeof bot.options.webHook === 'boolean') ? {} : bot.options.webHook;
this.options.host = this.options.host || '0.0.0.0';
this.options.port = this.options.port || 8443;
this.options.https = this.options.https || {};
this.options.healthEndpoint = this.options.healthEndpoint || '/healthz';
this._healthRegex = new RegExp(this.options.healthEndpoint);
this._webServer = null;
this._open = false;
this._requestListener = this._requestListener.bind(this);
this._parseBody = this._parseBody.bind(this);
if (this.options.key && this.options.cert) {
debug('HTTPS WebHook enabled (by key/cert)');
this.options.https.key = fs.readFileSync(this.options.key);
this.options.https.cert = fs.readFileSync(this.options.cert);
this._webServer = https.createServer(this.options.https, this._requestListener);
} else if (this.options.pfx) {
debug('HTTPS WebHook enabled (by pfx)');
this.options.https.pfx = fs.readFileSync(this.options.pfx);
this._webServer = https.createServer(this.options.https, this._requestListener);
} else if (Object.keys(this.options.https).length) {
debug('HTTPS WebHook enabled by (https)');
this._webServer = https.createServer(this.options.https, this._requestListener);
} else {
debug('HTTP WebHook enabled');
this._webServer = http.createServer(this._requestListener);
}
}
/**
* Open WebHook by listening on the port
* @return {Promise}
*/
open() {
if (this.isOpen()) {
return Promise.resolve();
}
return new Promise(resolve => {
this._webServer.listen(this.options.port, this.options.host, () => {
debug('WebHook listening on port %s', this.options.port);
this._open = true;
return resolve();
});
});
}
/**
* Close the webHook
* @return {Promise}
*/
close() {
if (!this.isOpen()) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
this._webServer.close(error => {
if (error) return reject(error);
this._open = false;
return resolve();
});
});
}
/**
* Return `true` if server is listening. Otherwise, `false`.
*/
isOpen() {
// NOTE: Since `http.Server.listening` was added in v5.7.0
// and we still need to support Node v4,
// we are going to fallback to 'this._open'.
// The following LOC would suffice for newer versions of Node.js
// return this._webServer.listening;
return this._open;
}
/**
* Handle error thrown during processing of webhook request.
* @private
* @param {Error} error
*/
_error(error) {
if (!this.bot.listeners('webhook_error').length) {
return console.error('error: [webhook_error] %j', error); // eslint-disable-line no-console
}
return this.bot.emit('webhook_error', error);
}
/**
* Handle request body by passing it to 'callback'
* @private
*/
_parseBody(error, body) {
if (error) {
return this._error(new errors.FatalError(error));
}
let data;
try {
data = JSON.parse(body.toString());
} catch (parseError) {
return this._error(new errors.ParseError(parseError.message));
}
return this.bot.processUpdate(data);
}
/**
* Listener for 'request' event on server
* @private
* @see https://nodejs.org/docs/latest/api/http.html#http_http_createserver_requestlistener
* @see https://nodejs.org/docs/latest/api/https.html#https_https_createserver_options_requestlistener
*/
_requestListener(req, res) {
debug('WebHook request URL: %s', req.url);
debug('WebHook request headers: %j', req.headers);
if (req.url.indexOf(this.bot.token) !== -1) {
if (req.method !== 'POST') {
debug('WebHook request isn\'t a POST');
res.statusCode = 418; // I'm a teabot!
res.end();
} else {
req
.pipe(bl(this._parseBody))
.on('finish', () => res.end('OK'));
}
} else if (this._healthRegex.test(req.url)) {
debug('WebHook health check passed');
res.statusCode = 200;
res.end('OK');
} else {
debug('WebHook request unauthorized');
res.statusCode = 401;
res.end();
}
}
}
module.exports = TelegramBotWebHook;