Repository: yagop/node-telegram-bot-api
Branch: master
Commit: 24fb242bcfe4
Files: 43
Total size: 512.2 KB
Directory structure:
gitextract_kd505wwd/
├── .babelrc
├── .editorconfig
├── .eslintignore
├── .eslintrc
├── .github/
│ ├── ISSUE_TEMPLATE.md
│ └── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .npmignore
├── .travis.yml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── doc/
│ ├── api.hbs
│ ├── api.md
│ ├── experimental.md
│ ├── help.md
│ ├── tutorials.md
│ └── usage.md
├── examples/
│ ├── game/
│ │ ├── game.html
│ │ └── game.js
│ ├── polling.js
│ ├── ssl/
│ │ ├── crt.pem
│ │ └── key.pem
│ └── webhook/
│ ├── express.js
│ ├── heroku.js
│ ├── https.js
│ ├── now.js
│ └── openshift2.js
├── index.js
├── package.json
├── src/
│ ├── errors.js
│ ├── telegram.js
│ ├── telegramPolling.js
│ ├── telegramWebHook.js
│ └── utils.js
└── test/
├── README.md
├── data/
│ └── voice.ogg
├── mocha.opts
├── telegram.js
├── test.format-send-data.js
└── utils.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc
================================================
{
"plugins": [
"transform-strict-mode",
"transform-object-rest-spread",
"transform-class-properties"
],
"presets": [
"babel-preset-es2015"
]
}
================================================
FILE: .editorconfig
================================================
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
================================================
FILE: .eslintignore
================================================
bin
*.md
================================================
FILE: .eslintrc
================================================
{
"extends": "airbnb/base",
"parser": "babel-eslint",
"rules": {
"new-cap": 0,
"prefer-arrow-callback": 0,
"no-param-reassign": [2,{"props":false}],
"max-len": [2, 200],
"arrow-body-style": 0,
"comma-dangle": 0,
"indent": ["error", 2]
},
"plugins": [
"mocha"
],
"env": {
"mocha": true
}
}
================================================
FILE: .github/ISSUE_TEMPLATE.md
================================================
> 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
### Actual Behavior
### Steps to reproduce the Behavior
> Feature Request
I have:
* searched for such a feature request (https://github.com/yagop/node-telegram-bot-api/labels/enhancement) and found none
### Introduction
### Example
> Question
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
- [ ] All tests pass
- [ ] I have run `npm run doc`
### Description
### References
================================================
FILE: .gitignore
================================================
node_modules
coverage/
npm-debug.log
.package.json
package-lock.json
output.md
output/
lib/
lib-doc/
.DS_Store
================================================
FILE: .npmignore
================================================
# lcov
coverage/
*.log
.package.json
# artifacts & source
README.hbs
output.md
output/
test/
examples/
lib-doc/
# dotfiles
.travis.yml
.eslintrc
.eslintignore
.editorconfig
.babelrc
.gitignore
.git
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- "12"
- "10"
- "8"
- "6"
#
# create required bash scripts to run builds on pull requests in the future
#
#script:
# - 'if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then bash ./travis/run_on_pull_requests; fi'
# - 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then bash ./travis/run_on_non_pull_requests; fi'
after_success:
- bash <(curl -s https://codecov.io/bash)
cache:
directories:
- node_modules
================================================
FILE: CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased][Unreleased]
## [0.68.0][0.68.0] - 2026-03-15
Added:
1. Support Telegram Bot API v9.3 (by @danielperez9430)
* `#getUserGifts`
* `#getChatGifts`
* `#sendMessageDraft` (by @xjx0106)
* `#repostStory`
2. Fixed method:
* `unpinAllGeneralForumTopicMessages`
* `replaceStickerInSet`
3. Support Telegram Bot API v9.5 (by @danielperez9430)
* `setChatMemberTag`
4. Support Telegram Bot API v9.6 (by @danielperez9430)
* setMyProfilePhoto
* removeMyProfilePhoto
5. Added missing methods (by @danielperez9430)
* getUserProfileAudios
* approveSuggestedPost
* declineSuggestedPost
6. Added more test
## [0.67.0][0.67.0] - 2025-12-13
Added:
1. Support Telegram Bot API v7.4 (by @danielperez9430)
* `#refundStarPayment`
6. Support Telegram Bot API 7.6 (@danielperez9430)
* `#sendPaidMedia`
1. Support Telegram Bot API v7.9 (by @danielperez9430)
1. Support Telegram Bot API v7.10 (by @danielperez9430)
* Update: `purchased_paid_media`
1. Support Telegram Bot API v8.0 and v8.1
* `#savePreparedInlineMessage` (@IsmailBinMujeeb)
* `#setUserEmojiStatus` (@danielperez9430)
* `#editUserStarSubscription` (@danielperez9430)
* `#getAvailableGifts` (@danielperez9430)
* `#sendGift` (@danielperez9430)
1. Support Telegram Bot API v8.2, v8.3 (@danielperez9430)
* `#verifyUser`
* `#verifyChat`
* `#removeUserVerification`
* `#removeChatVerification`
1. Support Telegram Bot API v8.3 (by @danielperez9430)
1. Support Telegram Bot API v9.0 (by @danielperez9430)
* `#readBusinessMessage`
* `#deleteBusinessMessages`
* `#setBusinessAccountName`
* `#setBusinessAccountUsername`
* `#setBusinessAccountBio`
* `#setBusinessAccountProfilePhoto`
* `#removeBusinessAccountProfilePhoto`
* `#setBusinessAccountGiftSettings`
* `#getBusinessAccountStarBalance`
* `#transferBusinessAccountStars`
* `#getBusinessAccountGifts`
* `#convertGiftToStars`
* `#upgradeGift`
* `#transferGift`
* `#postStory`
* `#editStory`
* `#deleteStory`
* `#giftPremiumSubscription`
1. Support Telegram Bot API v9.1 (by @danielperez9430)
* `#sendChecklist`
* `#editMessageChecklist`
* `#getMyStarBalance`
Fixed:
1. Reference causing error in `FatalError` (by @ivanjh)
1. Stringify `scope` field in `#deleteMyCommands` (by @XC-Zhang)
1. Stringify `allowed_updates` field in `#getUpdates` (by @alfanzain)
1. Stringify `message_ids` in `#forwardMessages` (by @qiaoshouzi)
1. Rename parameter `thumb` to `thumbnail` (by @0x114514BB)
1. Remove travis badge (by @melroy89)
1. Improve documentation on events (by @programminghoch10)
1. Fix Telegram invite group link (by @melroy89)
## [0.66.0][0.66.0] - 2024-05-03
1. Support Telegram Bot API 7.2 & 7.3 (@danielperez9430)
* getBusinessConnection
* replaceStickerInSet
2. Support for updates: (@danielperez9430)
* business_connection
* business_message
* edited_business_message
* deleted_business_messages
3. Minor fixes: (@danielperez9430)
* getUserChatBoosts
## [0.65.1][0.65.1] - 2024-03-09
1. Support for updates (@danielperez9430)
* message_reaction
* message_reaction_count
* chat_boost
* removed_chat_boost
## [0.65.0][0.65.0] - 2024-02-20
1. Support Telegram Bot API v7.1
* deleteMessages (@Sp3ricka)
* copyMessages (@xjx0106 & @Sp3ricka)
* setMessageReaction (@Sp3ricka)
* forwardMessages (@danielperez9430)
* getUserChatBoosts (@danielperez9430)
2. Minor changes: (@danielperez9430)
* Refactor methods order
* Fix copyMessages & setMessageReaction methods
* Added missing tests
* Fix tests for methods copyMessages & getMyDefaulAdministratorRights
## [0.64.0][0.64.0] - 2023-10-25
1. Replace `request` with a maintained version (@danielperez9430)
* Change `request` to `@cypress/request`
* Change `request-promise` to `@cypress/request-promise`
## [0.63.0][0.63.0] - 2023-08-23
1. Support Telegram Bot API v6.8 (@danielperez9430)
* unpinAllGeneralForumTopicMessages
## [0.62.0][0.62.0] - 2023-03-19
1. Support Telegram Bot API v6.6 & v6.7 (@danielperez9430)
* setMyDescription
* getMyDescription
* setMyShortDescription
* getMyShortDescription
* setCustomEmojiStickerSetThumbnail
* setStickerSetTitle
* deleteStickerSet
* setStickerEmojiList
* setStickerKeywords
* setStickerMaskPosition
## [0.61.0][0.61.0] - 2022-12-30
1. Support Telegram Bot API v6.4 (@danielperez9430)
* editGeneralForumTopic
* closeGeneralForumTopic
* reopenGeneralForumTopic
* hideGeneralForumTopic
* unhideGeneralForumTopic
2. Minor changes: (@danielperez9430)
* The parameters `name` and `icon_custom_emoji_id` of the method `editForumTopic` are now optional.
* Fix add thumb in sendAudio, sendVideo and sendVideoNote
* Fix getMyCommands and setMyCommands
* Suggested tip amounts stringify in sendInvoice
## [0.60.0][0.60.0] - 2022-10-06
1. Support Telegram Bot API v6.3 (@danielperez9430)
* createForumTopic
* closeForumTopic
* reopenForumTopic
* deleteForumTopic
* unpinAllForumTopicMessages
* getForumTopicIconStickers
2. Fix test getMyDefaultAdministratorRights (@danielperez9430)
3. Fix parse entities - (@toniop99)
## [0.59.0][0.59.0] - 2022-08-15
1. Support Telegram Bot API v6.2 (@danielperez9430)
* getCustomEmojiStickers
2. Support test enviroment (@tinsaeDev & @kamikazechaser)
3. Remove dependencies: (@danielperez9430)
* Remove *bluebird* => Use NodeJS Native Promises
* Remove *depd* => Use node native deprecate util for warnings
* Remove contributor dev dependency and add list of contributors in the readme
4. Remove legacy methods: (@danielperez9430)
* getChatMembersCount
* kickChatMember
5. Docs: (@danielperez9430)
* Update the docs of the methods
* Order methods follow the Telegram bot API docs in src/telegram.js
* Update README
6. Fix: (@danielperez9430)
* addStickerToSet() -> Allow to send tgs_sticker + webm_sticker
* Remove mandatory param “start_parameter” from sendInvoice, because in the docs is a optional param
* getStickerSet test fix deprecated response value "contains_masks" change to "sticker_type"
* Fix some other tests
7. New Test: (@danielperez9430)
* deleteStickerFromSet
* setStickerPositionInSet
* getCustomEmojiStickers
## [0.58.0][0.58.0] - 2022-06-22
1. Support Bot API v6.1: (@danielperez9430)
* Add method *createInvoiceLink()*
2. Support for setStickerSetThumb (@elihaidv)
3. Add new test (@danielperez9430)
* createInvoiceLink
4. Test fixes (@danielperez9430)
* sendVideoNote
* createNewStickerSet
* setStickerSetThumb
* getChatMenuButton
* setWebHook
5. Bug fixes (@danielperez9430)
* answerWebAppQuery
* Support for send thumb in sendAudio
## [0.57.0][0.57.0] - 2022-04-23
Added:
1. Support Bot API v6: (@danielperez9430)
* Add method *setChatMenuButton()*
* Add method *getChatMenuButton()*
* Add method *setMyDefaultAdministratorRights()*
* Add method *getMyDefaultAdministratorRights()*
* Add method *answerWebAppQuery()*
* Renamed the fields voice_chat_scheduled, voice_chat_started, voice_chat_ended, and voice_chat_participants_invited to video_chat_scheduled, video_chat_started, video_chat_ended, and video_chat_participants_invited
Tests:
* answerWebAppQuery
* setChatMenuButton
* getChatMenuButton
* setMyDefaultAdministratorRights
* getMyDefaultAdministratorRights
## [0.56.0][0.56.0] - 2021-12-07
Added:
1. Support Bot API v5.5: (@danielperez9430)
* Add method *banChatSenderChat()*
* Add method *unbanChatSenderChat()*
Fixes:
* Tests for support with new invite link format
## [0.55.0][0.55.0] - 2021-11-06
Added:
1. Support Bot API v5.4: (@danielperez9430)
* Add method *approveChatJoinRequest()*
* Add method *declineChatJoinRequest()*
* Add support for new updates:
* *chat_join_request*
Fixes:
* Method *editMessageMedia*: Now you can send a local file (`"attach://" + filePatch`)
## [0.54.0][0.54.0] - 2021-06-29
Added:
1. Support Bot API v5.3: (@danielperez9430)
* Add method *deleteMyCommands()*
* Add method *banChatMember()*
* Add method *getChatMemberCount()*
New Test:
* deleteMyCommands
* banChatMember
* getChatMemberCount
Deprecated:
* Method *kickChatMember()*
* Method *getChatMembersCount()*
## [0.53.0][0.53.0] - 2021-04-26
Added:
1. Support Bot API v5.2:(@danielperez9430)
* Add support for new messageTypes:
* *voice_chat_scheduled*
## [0.52.0][0.52.0] - 2021-03-20
Added:
1. Support Bot API v5.1: (by @danielperez9430)
* Add method *createChatInviteLink()*
* Add method *editChatInviteLink()*
* Add method *revokeChatInviteLink()*
* Add support for new messageTypes:
* *voice_chat_started*
* *voice_chat_ended*
* *voice_chat_participants_invited*
* *message_auto_delete_timer_changed*
* *chat_invite_link*
* *chat_member_updated*
* Add support for new updates:
* *my_chat_member*
* *chat_member*
New Test: (by @danielperez9430)
* createChatInviteLink
* editChatInviteLink
* revokeChatInviteLink
## [0.51.0][0.51.0] - 2020-11-04
Added:
1. Support Bot API v5.0: (by @danielperez9430)
* Add method *copyMessage()*
* Add method *unpinAllChatMessages()*
* Add method *close()*
* Add method *logOut()*
Changed: (by @danielperez9430)
* Remove trailing-spaces
* Fix Bugs in Test
New Test: (by @danielperez9430)
* copyMessage
* unpinAllChatMessages
## [0.50.0][0.50.0] - 2020-05-2020
Added:
1. Support Bot API v4.8: (by @danielperez9430)
* Add methods: *sendDice()*
2. Support Bot API v4.7: (by @danielperez9430)
* Add methods: *getMyCommands()*,*setMyCommands()*
3. Support Bot API v4.5: (by @danielperez9430)
* Add methods: *setChatAdministratorCustomTitle()*
4. Support Bot API v4.4: (by @danielperez9430)
* Add methods: *setChatPermissions()*
5. Support for poll_answer (by @JieJiSS)
6. Add request options in file stream (by @zhangpanyi )
Changed: (by @danielperez9430)
* New message type: *dice*
* Fix Bugs in tests
* Fix regex compare (by @ledamint)
* Fix listening for error events when downloading files (by @Kraigo)
New Test: (by @danielperez9430)
* sendDice
* getMyCommands
* setMyCommands
* setChatAdministratorCustomTitle
* setChatPermissions
## [0.40.0][0.40.0] - 2019-05-04
Added:
1. Support Bot API v4.2: (by @kamikazechaser)
* Add methods: *TelegramBot#sendPoll()*, *TelegramBot#stopPoll()*
* Support events: *poll*
2. 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()*
2. Support Bot API v3.4: (by @kamikazechaser)
* Add methods *TelegramBot#editMessageLiveLocation*, *TelegramBot#stopMessageLiveLocation* (#439)
* Add methods *TelegramBot#setChatStickerSet*, *TelegramBot#deleteChatStickerSet* (#440)
3. Add methods:
* *TelegramBot#getFileStream* (#442) (by @GochoMugo, requested-by @Xaqron)
4. Add options to *TelegramBot#stopPolling()* (by @GochoMugo)
5. Add `metadata` argument in `message` event (and friends e.g. `text`, `audio`, etc.) (#409) (by @jlsjonas, @GochoMugo)
6. Add forward-compatibility i.e. support future additional Telegram options (by @GochoMugo)
7. Add support for Node.js v9 (by @GochoMugo)
8. Document *TelegramBot.errors*, *TelegramBot.messageTypes* (by @GochoMugo)
Changed:
1. Update *TelegramBot#answerCallbackQuery()* signature (by @GochoMugo)
2. Improve default error logging of `polling_error` and `webhook_error` (#377)
3. 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)
2. 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)
2. 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)
2. (#332) Support Bot API v3.0 (by @kamikazechaser, @GochoMugo)
3. Add *TelegramBot#removeTextListener()* (by @GochoMugo)
4. (#342) Add game example (by @MCSH)
5. (#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)
2. (#363) Fix download file path on windows (by @kucherenkovova)
3. (#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)
2. (#298) Fix running on Node v5 (by @jehy)
3. (#307) Fix badge links in README (by @JaakkoLipsanen)
4. Fix defaulting value of `options.polling.params.timeout` (by @GochoMugo)
5. 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)
2. Add methods:
* (#74) *TelegramBot#removeReplyListener()* (by @githugger)
3. (#283) Add proper error handling (by @GochoMugo)
4. (#272) Add health-check endpoint (by @mironov)
* `options.webHook.healthEndpoint`
5. (#152) Add test for TelegramBot#sendDocument() using 'fileOpts'
param (by @evolun)
6. Document `options.webHook.host` (by @GochoMugo)
7. (#264) Add Bot API version to README (by @kamikazechaser)
8. 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`
2. Add methods:
* *TelegramBot#stopPolling()*
* *TelegramBot#isPolling()*
* *TelegramBot#openWebHook()*
* *TelegramBot#closeWebHook()*
* *TelegramBot#hasOpenWebHook()*
* *TelegramBot#deleteWebHook()*
* *TelegramBot#getWebHookInfo()*
Changed:
1. Use POST requests by default
2. Ensure all relevant methods return Promises
3. Document auto-deletion of webhook during polling
4. Deprecate support for Node.js v0.12
5. Fix consistency of methods signatures
6. Rename *TelegramBot#initPolling()* to *TelegramBot#startPolling()*
* Deprecate *TelegramBot#initPolling()*
Fixed:
1. Handle error during formatting `formData`
2. 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)
2. Add *TelegramBot* constructor option:
* `options.request`: proxy extra request options (by @tarmolov)
* `options.onlyFirstMatch` (by @GingerPlusPlus)
3. Add methods:
* *TelegramBot#sendVenue()* (by Tketa)
* *TelegramBot#sendContact()* (by @GochoMugo)
* *TelegramBot#getGameHighScores()* (by @jishnu7)
Fixed:
1. Fix request performance issue (by @preco21)
2. 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
[0.63.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.63.0
[0.64.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.64.0
[0.65.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.65.0
[0.65.1]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.65.1
[0.66.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.66.0
[0.67.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.67.0
[0.68.0]:https://github.com/yagop/node-telegram-bot-api/releases/tag/v0.68.0
[Unreleased]:https://github.com/yagop/node-telegram-bot-api/compare/v0.68.0...master
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# 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/
================================================
FILE: CONTRIBUTING.md
================================================
# 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
================================================
FILE: LICENSE.md
================================================
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.
================================================
FILE: README.md
================================================
Node.js Telegram Bot API
Node.js module to interact with the official [Telegram Bot API](https://core.telegram.org/bots/api).
[](https://core.telegram.org/bots/api)
[](https://www.npmjs.org/package/node-telegram-bot-api)
[](https://codecov.io/gh/yagop/node-telegram-bot-api)
[](https://telegram.me/node_telegram_bot_api)
[](https://t.me/+_IC8j_b1wSFlZTVk)
[](https://telegram.me/Yago_Perez)
## 📦 Install
```sh
npm i node-telegram-bot-api
```
> ✍️ **Note:** If you use Typescript you can install this package that contains type definitions for this library
>```sh
>npm install --save-dev @types/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](../master/doc/api.md) / [development][api-dev] / [experimental][api-experimental])
* [Contributing to the Project][contributing]
* [Experimental Features][experimental]
_**Note**: Development is done against the **development** branch.
Code for the latest release resides on the **master** branch.
Experimental features reside on the **experimental** branch._
## 💭 Community
We thank all the developers in the Open-Source community who continuously
take their time and effort in advancing this project.
See our [list of contributors][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 keyboards structures creation through a more easy-to-see way (supports Inline Keyboards, Reply Keyboard, Remove Keyboard and Force Reply)
* [beetube-bot](https://github.com/kodjunkie/beetube-bot): A telegram bot for music, videos, movies, EDM tracks, torrent downloads, files and more.
* [telegram-inline-calendar](https://github.com/VDS13/telegram-inline-calendar): Date and time picker and inline calendar for Node.js telegram bots.
* [telegram-captcha](https://github.com/VDS13/telegram-captcha): Telegram bot to protect Telegram groups from automatic bots.
## 👥 Contributors
================================================
FILE: examples/game/game.js
================================================
/**
* This example demonstrates using HTML5 games with Telegram.
*/
/* eslint-disable no-console */
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const gameName = process.env.TELEGRAM_GAMENAME || 'YOUR_TELEGRAM_GAMENAME';
// Specify '0' to use ngrok i.e. localhost tunneling
let url = process.env.URL || 'https://';
const port = process.env.PORT || 8080;
const TelegramBot = require('../..');
const express = require('express');
const path = require('path');
const bot = new TelegramBot(TOKEN, { polling: true });
const app = express();
// Basic configurations
app.set('view engine', 'ejs');
// Tunnel to localhost.
// This is just for demo purposes.
// In your application, you will be using a static URL, probably that
// you paid for. :)
if (url === '0') {
const ngrok = require('ngrok');
ngrok.connect(port, function onConnect(error, u) {
if (error) throw error;
url = u;
console.log(`Game tunneled at ${url}`);
});
}
// Matches /start
bot.onText(/\/start/, function onPhotoText(msg) {
bot.sendGame(msg.chat.id, gameName);
});
// Handle callback queries
bot.on('callback_query', function onCallbackQuery(callbackQuery) {
bot.answerCallbackQuery(callbackQuery.id, { url });
});
// Render the HTML game
app.get('/', function requestListener(req, res) {
res.sendFile(path.join(__dirname, 'game.html'));
});
// Bind server to port
app.listen(port, function listen() {
console.log(`Server is listening at http://localhost:${port}`);
});
================================================
FILE: examples/polling.js
================================================
/**
* This example demonstrates using polling.
* It also demonstrates how you would process and send messages.
*/
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const TelegramBot = require('..');
const request = require('@cypress/request');
const options = {
polling: true
};
const bot = new TelegramBot(TOKEN, options);
// Matches /photo
bot.onText(/\/photo/, function onPhotoText(msg) {
// From file path
const photo = `${__dirname}/../test/data/photo.gif`;
bot.sendPhoto(msg.chat.id, photo, {
caption: "I'm a bot!"
});
});
// Matches /audio
bot.onText(/\/audio/, function onAudioText(msg) {
// From HTTP request
const url = 'https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg';
const audio = request(url);
bot.sendAudio(msg.chat.id, audio);
});
// Matches /love
bot.onText(/\/love/, function onLoveText(msg) {
const opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [
['Yes, you are the bot of my life ❤'],
['No, sorry there is another one...']
]
})
};
bot.sendMessage(msg.chat.id, 'Do you love me?', opts);
});
// Matches /echo [whatever]
bot.onText(/\/echo (.+)/, function onEchoText(msg, match) {
const resp = match[1];
bot.sendMessage(msg.chat.id, resp);
});
// Matches /editable
bot.onText(/\/editable/, function onEditableText(msg) {
const opts = {
reply_markup: {
inline_keyboard: [
[
{
text: 'Edit Text',
// we shall check for this value when we listen
// for "callback_query"
callback_data: 'edit'
}
]
]
}
};
bot.sendMessage(msg.from.id, 'Original Text', opts);
});
// Handle callback queries
bot.on('callback_query', function onCallbackQuery(callbackQuery) {
const action = callbackQuery.data;
const msg = callbackQuery.message;
const opts = {
chat_id: msg.chat.id,
message_id: msg.message_id,
};
let text;
if (action === 'edit') {
text = 'Edited Text';
}
bot.editMessageText(text, opts);
});
================================================
FILE: examples/ssl/crt.pem
================================================
-----BEGIN CERTIFICATE-----
MIIDmTCCAoGgAwIBAgIJAPz/mOxHHCRKMA0GCSqGSIb3DQEBCwUAMGMxCzAJBgNV
BAYTAlVTMQ0wCwYDVQQIDARVdGFoMQ4wDAYDVQQHDAVQcm92bzEjMCEGA1UECgwa
QUNNRSBTaWduaW5nIEF1dGhvcml0eSBJbmMxEDAOBgNVBAMMB3lhZ28ubWUwHhcN
MTUwNjI4MTk0MjAxWhcNMTgwNzA2MTk0MjAxWjBjMQswCQYDVQQGEwJVUzENMAsG
A1UECAwEVXRhaDEOMAwGA1UEBwwFUHJvdm8xIzAhBgNVBAoMGkFDTUUgU2lnbmlu
ZyBBdXRob3JpdHkgSW5jMRAwDgYDVQQDDAd5YWdvLm1lMIIBIjANBgkqhkiG9w0B
AQEFAAOCAQ8AMIIBCgKCAQEAw9YiYXN1s5KcoZy7UZyiXULpTrYPhlPhzlyJJdwg
e61C/swbqtnh/+fPZp8g8a15ond9ShUvWLcxeoDBzxn0hJIEe+DlNNHUAdWoTWUx
OP4hHDA6wCFepHWBlw10AoKAjoQA+nCX6NrdiFTpbodkEK0H4uOSCt37H616kdKU
wRgXlca2Kw88UQ0qhKteb5hYD5tm4aCv6eRCqwYdYKUG+D1uJuJ+YZmaaIXp/5QZ
q3a6mFsKLtUC33bhZZPr1qjh3zwF2JTZX1WFAxUHNxY5NVchUYDHjw0djXvw85il
iwWKFjFXfvk8WTfW3Ge3754BhYSt92Qj6BROD2AODhI8jwIDAQABo1AwTjAdBgNV
HQ4EFgQUpgp5hovXcW+eIb3xRkF1KSJb/rwwHwYDVR0jBBgwFoAUpgp5hovXcW+e
Ib3xRkF1KSJb/rwwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAjnKW
+3lHe92Ut9XJdqGJsuRV5OUh8suOicz+AXtqUdoG9xbkv5N6Ynt+r06NjnYgTIzk
i+9fXBZLrXH8qNT2PTzErs0LMXPWxWbiZwY9mI2z/xW/K6CFjb1h33hk+ypwTr1J
Q1Eqy77FXKfQ2Y8kNLARSkvUEMm7UnVbUqRbA8AlWk9HZmoPHYfKPRGRVeIugH76
b6Gm3ztmIgTZQ88+DxfedIjPib3LPsHIXrA2Qd8yrIaYDiE2HMMJ5q3SYdRY4yYB
2a3P7jCPZfKVKpRE0J0yeNH+wQL0bzCMbl2wBUhivXD+sM00Xe3a22eAYbNgLdEg
4Hvd/YIKm9yOjRolmw==
-----END CERTIFICATE-----
================================================
FILE: examples/ssl/key.pem
================================================
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAw9YiYXN1s5KcoZy7UZyiXULpTrYPhlPhzlyJJdwge61C/swb
qtnh/+fPZp8g8a15ond9ShUvWLcxeoDBzxn0hJIEe+DlNNHUAdWoTWUxOP4hHDA6
wCFepHWBlw10AoKAjoQA+nCX6NrdiFTpbodkEK0H4uOSCt37H616kdKUwRgXlca2
Kw88UQ0qhKteb5hYD5tm4aCv6eRCqwYdYKUG+D1uJuJ+YZmaaIXp/5QZq3a6mFsK
LtUC33bhZZPr1qjh3zwF2JTZX1WFAxUHNxY5NVchUYDHjw0djXvw85iliwWKFjFX
fvk8WTfW3Ge3754BhYSt92Qj6BROD2AODhI8jwIDAQABAoIBAQCga6gMNh2DtSTT
imUzrGCgjvA5RxAelFYTyl+agOCnDz4jJKXBZewoygZuZQoCj31lJgafCg2X2bER
Tan1caiIdGhx5b88bmoB+rh8ddlFe3857RQjUPKLO6qlRyLx719J3z5B6Lu3xpnU
VOJHZWcF9gfQx2RZvI862svd6idqqFfKRVr7jxur1VuTQpk6g0xi6GnFk9s6sPw9
ChT6ykxzx+fQmYzeEW6SbWilOnm9BGuAEI2G7/mDQ6NFGFvFdPivI908vHPGbhFz
Ifdwt5F9NwQrSzYaDnYzCWrEmqSz9uRmX5DD9FwFokjN2d6o3V0/+1BrWLKDBDj+
jYcOV5IBAoGBAOFLTbfRLPP0z4vgTX8FeaZXreJQPblHmJQNwvJEYiiug4aDXCLv
uBEVR+H1Y/Pm1U4s5LNESg2pOC0IZOElvAck+SY/K1KZFI9EzBLa0aybFOuLaHY1
Z9cZfc1Cg3Vmpqnkyqahi+Tt1U/nayL3DFNcIwI30DweS+KLUmjIxxMBAoGBAN6H
ByD0+d3pfqkusTI3GT1NfWMBwS+usCayLP1gMpA+0tT+/lnYLLbmINaD6hoztWWD
OUZ7PM3HkOXKly2bfKxlT8Bi3b0QpNyd54ybj4/60JLRAO5OU773an8MMsov+q1V
xWYGVMnNihXFFVGaIK8dG/2mYomHjbzx3az/EZ+PAoGAJs3pnPeSXpKUDOudbXtr
8JK5iHl5qCgEx7t3EHNm1Mr6LHkDraDMe2TG9MxnYuMnakehPJ9OgfvbiSYg+gad
1D0yDLxkod1sBSE8ZSL7aldrywY//9xC/nGNkYUbT2VW33xgy0KX7d5pF1IsyeDz
ZohAH2mtnC07tNF6aEHsyAECgYAJ3EHcm/5WbvpF1OPVLcvYg46CzJka28rCbDLC
J3kWGzKMbaAnqwSQNjJOTxoYfyISlXX8QYm4NJefFxML2k/z86lNBRR+RDaJ8BVK
jboWzy5e0xQPezkKxTva1VeKzgV1mM9ebflj18++lzUSoJnCKLAM1UqYfYEyViVU
fRjy0QKBgQCopUy7KDdKngBrSQwI9lMi1/bZJTXw1WktLZRma3uIw8uBKB2Fyf4/
7xFo49Ha7l1W38PfkqOS+539V8cJSyyJKq+PgBQ8fuLCplCDeZCieSiYm+FkpIr0
4V+hEMIkVuUBDwCbyMM5mUH+sBVtmzNYDRgYa5QN4FIBk8VcBgsIhw==
-----END RSA PRIVATE KEY-----
================================================
FILE: examples/webhook/express.js
================================================
/**
* This example demonstrates setting up a webook, and receiving
* updates in your express app
*/
/* eslint-disable no-console */
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const url = 'https://';
const port = process.env.PORT;
const TelegramBot = require('../..');
const express = require('express');
// No need to pass any parameters as we will handle the updates with Express
const bot = new TelegramBot(TOKEN);
// This informs the Telegram servers of the new webhook.
bot.setWebHook(`${url}/bot${TOKEN}`);
const app = express();
// parse the updates to JSON
app.use(express.json());
// We are receiving updates at the route below!
app.post(`/bot${TOKEN}`, (req, res) => {
bot.processUpdate(req.body);
res.sendStatus(200);
});
// Start Express Server
app.listen(port, () => {
console.log(`Express server is listening on ${port}`);
});
// Just to ping!
bot.on('message', msg => {
bot.sendMessage(msg.chat.id, 'I am alive!');
});
================================================
FILE: examples/webhook/heroku.js
================================================
/**
* This example demonstrates setting up webhook
* on the Heroku platform.
*/
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const TelegramBot = require('../..');
const options = {
webHook: {
// Port to which you should bind is assigned to $PORT variable
// See: https://devcenter.heroku.com/articles/dynos#local-environment-variables
port: process.env.PORT
// you do NOT need to set up certificates since Heroku provides
// the SSL certs already (https://.herokuapp.com)
// Also no need to pass IP because on Heroku you need to bind to 0.0.0.0
}
};
// Heroku routes from port :443 to $PORT
// Add URL of your app to env variable or enable Dyno Metadata
// to get this automatically
// See: https://devcenter.heroku.com/articles/dyno-metadata
const url = process.env.APP_URL || 'https://.herokuapp.com:443';
const bot = new TelegramBot(TOKEN, options);
// This informs the Telegram servers of the new webhook.
// Note: we do not need to pass in the cert, as it already provided
bot.setWebHook(`${url}/bot${TOKEN}`);
// Just to ping!
bot.on('message', function onMessage(msg) {
bot.sendMessage(msg.chat.id, 'I am alive on Heroku!');
});
================================================
FILE: examples/webhook/https.js
================================================
/**
* This example demonstrates setting up a webook, using a
* self-signed certificate.
*/
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const TelegramBot = require('../..');
const options = {
webHook: {
port: 443,
key: `${__dirname}/../ssl/key.pem`, // Path to file with PEM private key
cert: `${__dirname}/../ssl/crt.pem` // Path to file with PEM certificate
}
};
// This URL must route to the port set above (i.e. 443)
const url = 'https://';
const bot = new TelegramBot(TOKEN, options);
// This informs the Telegram servers of the new webhook.
bot.setWebHook(`${url}/bot${TOKEN}`, {
certificate: options.webHook.cert,
});
// Just to ping!
bot.on('message', function onMessage(msg) {
bot.sendMessage(msg.chat.id, 'I am alive!');
});
================================================
FILE: examples/webhook/now.js
================================================
/**
* This example demonstrates setting up webhook on Zeit Now platform.
* Attention: You have to use webhook with Zeit Now only, polling doesn't
* work.
*/
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const TelegramBot = require('../..');
const options = {
webHook: {
// Just use 443 directly
port: 443
}
};
// You can use 'now alias ' to assign fixed
// domain.
// See: https://zeit.co/blog/now-alias
// Or just use NOW_URL to get deployment url from env.
const url = 'YOUR_DOMAIN_ALIAS' || process.env.NOW_URL;
const bot = new TelegramBot(TOKEN, options);
// This informs the Telegram servers of the new webhook.
// Note: we do not need to pass in the cert, as it already provided
bot.setWebHook(`${url}/bot${TOKEN}`);
// Just to ping!
bot.on('message', function onMessage(msg) {
bot.sendMessage(msg.chat.id, 'I am alive on Zeit Now!');
});
================================================
FILE: examples/webhook/openshift2.js
================================================
/**
* This example demonstrates setting up webhook
* on the OpenShift platform.
*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* NOTE:
*
* Openshift 2 has been shut down.
*
* This example is kept here for historical/educational purposes.
* No changes are expected to be made to the source code below.
*
* See https://github.com/yagop/node-telegram-bot-api/issues/426 for
* more information.
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const TelegramBot = require('../..');
// See https://developers.openshift.com/en/node-js-environment-variables.html
const options = {
webHook: {
port: process.env.OPENSHIFT_NODEJS_PORT,
host: process.env.OPENSHIFT_NODEJS_IP,
// you do NOT need to set up certificates since OpenShift provides
// the SSL certs already (https://.rhcloud.com)
},
};
// OpenShift routes from port :443 to OPENSHIFT_NODEJS_PORT
const domain = process.env.OPENSHIFT_APP_DNS;
const url = `${domain}:443`;
const bot = new TelegramBot(TOKEN, options);
// This informs the Telegram servers of the new webhook.
// Note: we do not need to pass in the cert, as it already provided
bot.setWebHook(`${url}/bot${TOKEN}`);
// Just to ping!
bot.on('message', function onMessage(msg) {
bot.sendMessage(msg.chat.id, 'I am alive on OpenShift!');
});
================================================
FILE: index.js
================================================
/**
* 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('./src/utils').deprecate;
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');
}
================================================
FILE: package.json
================================================
{
"name": "node-telegram-bot-api",
"version": "0.68.0",
"description": "Telegram Bot API",
"main": "./index.js",
"directories": {
"example": "examples",
"test": "test"
},
"keywords": [
"telegram",
"telegram bot",
"telegram bot api",
"bot"
],
"scripts": {
"gen-doc": "echo 'WARNING: `npm run gen-doc` is deprecated. Use `npm run doc` instead.' && npm run doc",
"doc": "jsdoc2md --files src/telegram.js --template doc/api.hbs > doc/api.md",
"build": "babel -d ./lib src",
"prepublishOnly": "npm run build && npm run gen-doc",
"eslint": "eslint ./src ./test ./examples",
"mocha": "mocha",
"pretest": "npm run build",
"test": "npm run eslint && istanbul cover ./node_modules/mocha/bin/_mocha"
},
"author": "Yago Pérez ",
"license": "MIT",
"engines": {
"node": ">=0.12"
},
"dependencies": {
"@cypress/request": "^3.0.8",
"@cypress/request-promise": "^5.0.0",
"array.prototype.findindex": "^2.0.2",
"bl": "^1.2.3",
"debug": "^3.2.7",
"eventemitter3": "^3.0.0",
"file-type": "^3.9.0",
"mime": "^1.6.0",
"pump": "^2.0.0"
},
"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",
"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": "^9.1.3",
"mocha": "^3.5.3",
"mocha-lcov-reporter": "^1.3.0",
"node-static": "^0.7.10"
},
"repository": {
"type": "git",
"url": "https://github.com/yagop/node-telegram-bot-api.git"
},
"bugs": {
"url": "https://github.com/yagop/node-telegram-bot-api/issues"
},
"homepage": "https://github.com/yagop/node-telegram-bot-api"
}
================================================
FILE: src/errors.js
================================================
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;
this.cause = error;
}
}
};
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;
}
};
================================================
FILE: src/telegram.js
================================================
// 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('@cypress/request-promise');
const streamedRequest = require('@cypress/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('./utils').deprecate;
const _messageTypes = [
'text',
'animation',
'audio',
'channel_chat_created',
'contact',
'delete_chat_photo',
'dice',
'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',
'video_chat_started',
'video_chat_ended',
'video_chat_participants_invited',
'video_chat_scheduled',
'message_auto_delete_timer_changed',
'chat_invite_link',
'chat_member_updated',
'web_app_data',
'message_reaction'
];
const _deprecatedMessageTypes = [
'new_chat_participant', 'left_chat_participant'
];
/**
* 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;
}
/**
* 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 {Boolean} [options.testEnvironment=false] Set true to work with test enviroment.
* When working with the test environment, you may use HTTP links without TLS to test your Web App.
* @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 {Array|String} [options.polling.params.allowed_updates] A JSON-serialized list of the update types you want your bot to receive.
* For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types.
* @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}${this.options.testEnvironment ? '/test' : ''}/${_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);
}
}
/**
* Fix 'entities' or 'caption_entities' or 'explanation_entities' parameter by making it JSON-serialized, as
* required by the Telegram Bot API
* @param {Object} obj Object;
* @private
* @see https://core.telegram.org/bots/api#sendmessage
* @see https://core.telegram.org/bots/api#copymessage
* @see https://core.telegram.org/bots/api#sendpoll
*/
_fixEntitiesField(obj) {
const entities = obj.entities;
const captionEntities = obj.caption_entities;
const explanationEntities = obj.explanation_entities;
if (entities && typeof entities !== 'string') {
obj.entities = stringify(entities);
}
if (captionEntities && typeof captionEntities !== 'string') {
obj.caption_entities = stringify(captionEntities);
}
if (explanationEntities && typeof explanationEntities !== 'string') {
obj.explanation_entities = stringify(explanationEntities);
}
}
_fixAddFileThumbnail(options, opts) {
if (options.thumb) {
deprecate('The "thumb" parameter was renamed to "thumbnail" in Telegram Bot API v6.6. Please use the renamed parameter instead.');
options.thumbnail = options.thumb;
}
if (options.thumbnail) {
if (opts.formData === null) {
opts.formData = {};
}
const attachName = 'photo';
const [formData] = this._formatSendData(attachName, options.thumbnail.replace('attach://', ''));
if (formData) {
opts.formData[attachName] = formData[attachName];
opts.qs.thumbnail = `attach://${attachName}`;
}
}
}
_fixMessageIds(obj) {
const messageIds = obj.message_ids;
if (messageIds && typeof messageIds !== 'string') {
obj.message_ids = stringify(messageIds);
}
}
/**
* Fix 'reply_parameters' 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
*/
_fixReplyParameters(obj) {
if (obj.hasOwnProperty('reply_parameters') && typeof obj.reply_parameters !== 'string') {
obj.reply_parameters = stringify(obj.reply_parameters);
}
}
/**
* 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);
this._fixEntitiesField(options.form);
this._fixReplyParameters(options.form);
this._fixMessageIds(options.form);
}
if (options.qs) {
this._fixReplyMarkup(options.qs);
this._fixReplyParameters(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];
}
/**
* Format multiple files to be uploaded; handles file paths, streams, and buffers
* @param {String} type
* @param {Array} files Array of file data objects
* @param {Object} fileOptions File options
* @param {String} [fileOptions.filename] File name
* @param {String} [fileOptions.contentType] Content type (i.e. MIME)
* @return {Object} formatted
* @return {Object} formatted.formData Form data object with all files
* @return {Array} formatted.fileIds Array of fileIds for non-file data
* @throws Error if Buffer file type is not supported.
* @see https://npmjs.com/package/file-type
* @private
*/
_formatSendMultipleData(type, files, fileOptions = {}) {
const formData = {};
const fileIds = {};
files.forEach((file, index) => {
let filedata = file.media || file.data || file[type];
let filename = file.filename || fileOptions.filename;
let contentType = file.contentType || fileOptions.contentType;
if (filedata instanceof stream.Stream) {
if (!filename && filedata.path) {
const url = URL.parse(path.basename(filedata.path.toString()), true);
if (url.pathname) {
filename = qs.unescape(url.pathname);
}
}
} else if (Buffer.isBuffer(filedata)) {
filename = `filename_${index}`;
if (!contentType) {
const filetype = fileType(filedata);
if (filetype) {
contentType = filetype.mime;
const ext = filetype.ext;
if (ext) {
filename = `${filename}.${ext}`;
}
} else {
throw new errors.FatalError('Unsupported Buffer file-type');
}
}
} else if (fs.existsSync(filedata)) {
filedata = fs.createReadStream(filedata);
if (!filename) {
filename = path.basename(filedata.path);
}
} else {
fileIds[index] = filedata;
return;
}
filename = filename || `filename_${index}`;
contentType = contentType || 'application/octet-stream';
formData[`${type}_${index}`] = {
value: filedata,
options: {
filename,
contentType,
},
};
});
return { formData, fileIds };
}
/**
* 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);
}
/**
* 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 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(Object.assign({ uri: fileURI }, this.options.request)), 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, 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);
});
});
fileStream.on('error', (err) => {
reject(err);
});
return promise;
}
/**
* Register a RegExp to test against an incomming text message.
* @param {RegExp} regexpRexecuted 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 String(textListener.regexp) === String(regexp);
});
if (index === -1) {
return null;
}
return this._textRegexpCallbacks.splice(index, 1)[0];
}
/**
* Remove all listeners registered with `onText()`.
*/
clearTextListeners() {
this._textRegexpCallbacks = [];
}
/**
* 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];
}
/**
* Removes all replies that have been prev. registered for a message response.
*
* @return {Array} deletedListeners An array of removed listeners.
*/
clearReplyListeners() {
this._replyListeners = [];
}
/**
* 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;
}
/**
* 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 businessConnection = update.business_connection;
const businessMessage = update.business_message;
const editedBusinessMessage = update.edited_business_message;
const deletedBusinessMessage = update.deleted_business_messages;
const messageReaction = update.message_reaction;
const messageReactionCount = update.message_reaction_count;
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 purchasedPaidMedia = update.purchased_paid_media;
const poll = update.poll;
const pollAnswer = update.poll_answer;
const myChatMember = update.my_chat_member;
const chatMember = update.chat_member;
const chatJoinRequest = update.chat_join_request;
const chatBoost = update.chat_boost;
const removedChatBoost = update.removed_chat_boost;
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);
if (!(reg.regexp instanceof RegExp)) {
reg.regexp = new RegExp(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 (businessConnection) {
debug('Process Update business_connection %j', businessConnection);
this.emit('business_connection', businessConnection);
} else if (businessMessage) {
debug('Process Update business_message %j', businessMessage);
this.emit('business_message', businessMessage);
} else if (editedBusinessMessage) {
debug('Process Update edited_business_message %j', editedBusinessMessage);
this.emit('edited_business_message', editedBusinessMessage);
} else if (deletedBusinessMessage) {
debug('Process Update deleted_business_messages %j', deletedBusinessMessage);
this.emit('deleted_business_messages', deletedBusinessMessage);
} else if (messageReaction) {
debug('Process Update message_reaction %j', messageReaction);
this.emit('message_reaction', messageReaction);
} else if (messageReactionCount) {
debug('Process Update message_reaction_count %j', messageReactionCount);
this.emit('message_reaction_count', messageReactionCount);
} 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 (purchasedPaidMedia) {
debug('Process Update purchased_paid_media %j', purchasedPaidMedia);
this.emit('purchased_paid_media', purchasedPaidMedia);
} else if (poll) {
debug('Process Update poll %j', poll);
this.emit('poll', poll);
} else if (pollAnswer) {
debug('Process Update poll_answer %j', pollAnswer);
this.emit('poll_answer', pollAnswer);
} else if (chatMember) {
debug('Process Update chat_member %j', chatMember);
this.emit('chat_member', chatMember);
} else if (myChatMember) {
debug('Process Update my_chat_member %j', myChatMember);
this.emit('my_chat_member', myChatMember);
} else if (chatJoinRequest) {
debug('Process Update my_chat_member %j', chatJoinRequest);
this.emit('chat_join_request', chatJoinRequest);
} else if (chatBoost) {
debug('Process Update chat_boost %j', chatBoost);
this.emit('chat_boost', chatBoost);
} else if (removedChatBoost) {
debug('Process Update removed_chat_boost %j', removedChatBoost);
this.emit('removed_chat_boost', removedChatBoost);
}
}
/** Start Telegram Bot API methods */
/**
* 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 */
}
// If allowed_updates is present and is an array, stringify it.
// If it's already a string (e.g., user did JSON.stringify), leave as is.
if (form.allowed_updates) {
form.allowed_updates = stringify(form.allowed_updates);
}
return this._request('getUpdates', { 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 {String} [options.secret_token] Optional secret token to be sent in a header `X-Telegram-Bot-Api-Secret-Token` in every webhook request.
* @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 });
}
/**
* A simple method for testing your bot's authentication token. Requires no parameters.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} basic information about the bot in form of a [User](https://core.telegram.org/bots/api#user) object.
* @see https://core.telegram.org/bots/api#getme
*/
getMe(form = {}) {
return this._request('getMe', { form });
}
/**
* This method log out your bot from the cloud Bot API server before launching the bot locally.
* You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates.
* After a successful call, you will not be able to log in again using the same token for 10 minutes.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#logout
*/
logOut(form = {}) {
return this._request('logOut', { form });
}
/**
* This method close the bot instance before moving it from one local server to another.
* This method will return error 429 in the first 10 minutes after the bot is launched.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#close
*/
close(form = {}) {
return this._request('close', { form });
}
/**
* Send text message.
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} text Text of the message to be sent
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @see https://core.telegram.org/bots/api#sendmessage
*/
sendMessage(chatId, text, form = {}) {
form.chat_id = chatId;
form.text = text;
return this._request('sendMessage', { form });
}
/**
* Forward messages of any kind.
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* or username of the target channel (in the format `@channelusername`)
* @param {Number|String} fromChatId Unique identifier for the chat where the
* original message was sent (or channel username in the format `@channelusername`)
* @param {Number|String} messageId Unique message identifier in the chat specified in fromChatId
* @param {Object} [options] Additional Telegram query options
* @return {Promise}
* @see https://core.telegram.org/bots/api#forwardmessage
*/
forwardMessage(chatId, fromChatId, messageId, form = {}) {
form.chat_id = chatId;
form.from_chat_id = fromChatId;
form.message_id = messageId;
return this._request('forwardMessage', { form });
}
/**
* Use this method to forward multiple messages of any kind.
* If some of the specified messages can't be found or forwarded, they are skipped.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* or username of the target channel (in the format `@channelusername`)
* @param {Number|String} fromChatId Unique identifier for the chat where the
* original message was sent (or channel username in the format `@channelusername`)
* @param {Array} messageIds Identifiers of 1-100 messages in the chat from_chat_id to forward.
* The identifiers must be specified in a strictly increasing order.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} An array of MessageId of the sent messages on success
* @see https://core.telegram.org/bots/api#forwardmessages
*/
forwardMessages(chatId, fromChatId, messageIds, form = {}) {
form.chat_id = chatId;
form.from_chat_id = fromChatId;
form.message_ids = messageIds;
return this._request('forwardMessages', { form });
}
/**
* Copy messages of any kind. **Service messages and invoice messages can't be copied.**
* The method is analogous to the method forwardMessages, but the copied message doesn't
* have a link to the original message.
* Returns the MessageId of the sent message on success.
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @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} The [MessageId](https://core.telegram.org/bots/api#messageid) of the sent message on success
* @see https://core.telegram.org/bots/api#copymessage
*/
copyMessage(chatId, fromChatId, messageId, form = {}) {
form.chat_id = chatId;
form.from_chat_id = fromChatId;
form.message_id = messageId;
return this._request('copyMessage', { form });
}
/**
* Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped.
* Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied.
* Returns the MessageId of the sent message on success.
* @param {Number|String} chatId Unique identifier for the target chat
* @param {Number|String} fromChatId Unique identifier for the chat where the
* original message was sent
* @param {Array} messageIds Identifiers of 1-100 messages in the chat from_chat_id to copy.
* The identifiers must be specified in a strictly increasing order.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} An array of MessageId of the sent messages
* @see https://core.telegram.org/bots/api#copymessages
*/
copyMessages(chatId, fromChatId, messageIds, form = {}) {
form.chat_id = chatId;
form.from_chat_id = fromChatId;
form.message_ids = stringify(messageIds);
return this._request('copyMessages', { form });
}
/**
* Send photo
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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
*
* **Your audio must be in the .MP3 or .M4A format.**
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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];
this._fixAddFileThumbnail(options, opts);
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendAudio', opts);
}
/**
* Send Document
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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];
this._fixAddFileThumbnail(options, opts);
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendDocument', 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 target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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];
this._fixAddFileThumbnail(options, opts);
} 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 target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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.animation = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendAnimation', opts);
}
/**
* Send voice
*
* **Your audio must be in an .OGG file encoded with OPUS**, or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document)
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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);
}
/**
* Use this method to send video messages
* Telegram clients support **rounded square MPEG4 videos** of up to 1 minute long.
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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];
this._fixAddFileThumbnail(options, opts);
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendVideoNote', opts);
}
/**
* Use this method to send paid media.
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} starCount The number of Telegram Stars that must be paid to buy access to the media; 1-10000
* @param {Array} media Array of [InputPaidMedia](https://core.telegram.org/bots/api#inputpaidmedia). The media property can bea String, Stream or Buffer.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @see https://core.telegram.org/bots/api#sendpaidmedia
*/
sendPaidMedia(chatId, starCount, media, options = {}) {
const opts = {
qs: options
};
opts.qs.chat_id = chatId;
opts.qs.star_count = starCount;
try {
const inputPaidMedia = [];
opts.formData = {};
const { formData, fileIds } = this._formatSendMultipleData('media', media);
opts.formData = formData;
inputPaidMedia.push(...media.map((item, index) => {
if (fileIds[index]) {
item.media = fileIds[index];
} else {
item.media = `attach://media_${index}`;
}
return item;
}));
opts.qs.media = stringify(inputPaidMedia);
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendPaidMedia', opts);
}
/**
* Use this method to send a group of photos or videos as an album.
*
* **Documents and audio files can be only grouped in an album with messages of the same type**
*
* 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 2–10 items
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, an array of the sent [Messages](https://core.telegram.org/bots/api#message)
* is returned.
* @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 = stringify(inputMedia);
return this._request('sendMediaGroup', opts);
}
/**
* Send location.
* Use this method to send point on the map.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Float} latitude Latitude of location
* @param {Float} longitude Longitude of location
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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).
*
* A location **can be edited until its live_period expires or editing is explicitly disabled by a call to [stopMessageLiveLocation](https://core.telegram.org/bots/api#stopmessagelivelocation)**
*
* 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} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned.
* @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} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned.
* @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 target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned.
* @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 target chat or username of the target channel (in the format `@channelusername`)
* @param {String} phoneNumber Contact's phone number
* @param {String} firstName Contact's first name
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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, 1-300 characters
* @param {Array} pollOptions Poll options, between 2-10 options (only 1-100 characters each)
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @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 });
}
/**
* Send sendChecklist.
* Use this method to send a checklist on behalf of a connected business account.
*
* @param {Number|String} businessConnectionId Unique identifier for the business connection
* @param {Number|String} chatId Unique identifier for the group/channel
* @param {Object} checklist A JSON-serialized object for the checklist to send
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @see https://core.telegram.org/bots/api#sendchecklist
*/
sendChecklist(businessConnectionId, chatId, checklist, form = {}) {
form.business_connection_id = businessConnectionId;
form.chat_id = chatId;
form.checklist = stringify(checklist);
return this._request('sendChecklist', { form });
}
/**
* Send Dice
* Use this method to send an animated emoji that will display a random value.
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
* @see https://core.telegram.org/bots/api#senddice
*/
sendDice(chatId, options = {}) {
const opts = {
qs: options,
};
opts.qs.chat_id = chatId;
try {
const sendData = this._formatSendData('dice');
opts.formData = sendData[0];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('sendDice', opts);
}
/**
* Send Message Draft
* Use this method to stream a partial message to a user while the message is being generated; supported only for bots with forum topic mode enabled. Returns True on success.
* @param {Number|String} chatId Unique identifier for the target private chat
* @param {Number} draftId Unique identifier of the message draft; must be non-zero. Changes of drafts with the same identifier are animated
* @param {String} text Text of the message to be sent, 1-4096 characters after entities parsing
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, return true
* @see https://core.telegram.org/bots/api#sendmessagedraft
*/
sendMessageDraft(chatId, draftId, text, form = {}) {
form.chat_id = chatId;
form.draft_id = draftId;
form.text = text;
return this._request('sendMessageDraft', { form });
}
/**
* Send chat action.
*
* Use this method when you need to tell the user that something is happening on the bot's side.
* **The status is set for 5 seconds or less** (when a message arrives from your bot, Telegram clients clear its typing status).
*
* Action `typing` for [text messages](https://core.telegram.org/bots/api#sendmessage),
* `upload_photo` for [photos](https://core.telegram.org/bots/api#sendphoto), `record_video` or `upload_video` for [videos](https://core.telegram.org/bots/api#sendvideo),
* `record_voice` or `upload_voice` for [voice notes](https://core.telegram.org/bots/api#sendvoice), `upload_document` for [general files](https://core.telegram.org/bots/api#senddocument),
* `choose_sticker` for [stickers](https://core.telegram.org/bots/api#sendsticker), `find_location` for [location data](https://core.telegram.org/bots/api#sendlocation),
* `record_video_note` or `upload_video_note` for [video notes](https://core.telegram.org/bots/api#sendvideonote).
*
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} action Type of action to broadcast.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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 change the chosen reactions on a message.
* - Service messages can't be reacted to.
* - Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel.
* - In albums, bots must react to the first message.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param {Number} messageId Unique identifier of the target message
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setmessagereaction
*/
setMessageReaction(chatId, messageId, form = {}) {
form.chat_id = chatId;
form.message_id = messageId;
if (form.reaction) {
form.reaction = stringify(form.reaction);
}
return this._request('setMessageReaction', { 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.
*
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object
* @see https://core.telegram.org/bots/api#getuserprofilephotos
*/
getUserProfilePhotos(userId, form = {}) {
form.user_id = userId;
return this._request('getUserProfilePhotos', { form });
}
/**
* Use this method to get a list of profile audios for a user.
* Returns a [UserProfileAudios](https://core.telegram.org/bots/api#userprofileaudios) object.
*
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} Returns a [UserProfileAudios](https://core.telegram.org/bots/api#userprofileaudios) object
* @see https://core.telegram.org/bots/api#getuserprofileaudios
*/
getUserProfileAudios(userId, form = {}) {
form.user_id = userId;
return this._request('getUserProfileAudios', { form });
}
/**
* Changes the emoji status for a given user that previously allowed the bot to manage their emoji status
* via the Mini App method [requestEmojiStatusAccess](https://core.telegram.org/bots/webapps#initializing-mini-apps).
*
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setuseremojistatus
*/
setUserEmojiStatus(userId, form = {}) {
form.user_id = userId;
return this._request('setUserEmojiStatus', { 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} On success, a [File](https://core.telegram.org/bots/api#file) object is returned
* @see https://core.telegram.org/bots/api#getfile
*/
getFile(fileId, form = {}) {
form.file_id = fileId;
return this._request('getFile', { form });
}
/**
* Use this method to ban a user in a group, a supergroup or a channel.
* In the case of supergroups and channels, the user will not be able to
* return to the chat on their own using invite links, etc., unless unbanned first..
*
* The **bot must be an administrator in the group, supergroup or a channel** for this to work.
*
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success.
* @see https://core.telegram.org/bots/api#banchatmember
*/
banChatMember(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('banChatMember', { 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 supergroup or channel for this to work.
*
* **By default**, this method guarantees that after the call the user is not a member of the chat, but will be able to join it.
* So **if the user is a member of the chat they will also be removed from the chat**. If you don't want this, use the parameter *only_if_banned*
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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 channel (in the format `@channelusername`)
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} userId
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success.
* @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 set a custom title for an administrator in a supergroup promoted by the bot.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} userId Unique identifier of the target user
* @param {String} customTitle New custom title for the administrator; 0-16 characters, emoji are not allowed
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setchatadministratorcustomtitle
*/
setChatAdministratorCustomTitle(chatId, userId, customTitle, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
form.custom_title = customTitle;
return this._request('setChatAdministratorCustomTitle', { form });
}
/**
* Use this method to set a tag for a regular member in a group or a supergroup.
*
* The bot must be an administrator in the chat for this to work and must have the can_manage_tags administrator right.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setchatmembertag
*/
setChatMemberTag(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('setChatMemberTag', { form });
}
/**
* Use this method to ban a channel chat in a supergroup or a channel.
*
* Until the chat is [unbanned](https://core.telegram.org/bots/api#unbanchatsenderchat), the owner of the banned chat won't be able to send messages on behalf of any of their channels.
* The bot **must be an administrator in the supergroup or channel** for this to work and must have the appropriate administrator rights
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} senderChatId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success.
* @see https://core.telegram.org/bots/api#banchatsenderchat
*/
banChatSenderChat(chatId, senderChatId, form = {}) {
form.chat_id = chatId;
form.sender_chat_id = senderChatId;
return this._request('banChatSenderChat', { form });
}
/**
* Use this method to unban a previously banned channel chat in a supergroup or channel.
*
* The bot **must be an administrator** for this to work and must have the appropriate administrator rights.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} senderChatId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#unbanchatsenderchat
*/
unbanChatSenderChat(chatId, senderChatId, form = {}) {
form.chat_id = chatId;
form.sender_chat_id = senderChatId;
return this._request('unbanChatSenderChat', { form });
}
/**
* Use this method to set default chat permissions for all members.
*
* The bot **must be an administrator in the group or a supergroup** for this to
* work and **must have the `can_restrict_members` admin rights.**
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Array} chatPermissions New default chat permissions
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setchatpermissions
*/
setChatPermissions(chatId, chatPermissions, form = {}) {
form.chat_id = chatId;
form.permissions = stringify(chatPermissions);
return this._request('setChatPermissions', { form });
}
/**
* Use this method to generate a new primary invite link for a chat. **Any previously generated primary link is revoked**.
*
* The bot **must be an administrator in the chat** for this to work and must have the appropriate administrator rights.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Object} [options] Additional Telegram query options
* @return {Promise} Exported invite link as String on success.
* @see https://core.telegram.org/bots/api#exportchatinvitelink
*/
exportChatInviteLink(chatId, form = {}) {
form.chat_id = chatId;
return this._request('exportChatInviteLink', { form });
}
/**
* Use this method to create an additional invite link for a chat.
*
* The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
*
* The link generated with this method can be revoked using the method [revokeChatInviteLink](https://core.telegram.org/bots/api#revokechatinvitelink)
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Object} [options] Additional Telegram query options
* @return {Object} The new invite link as [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object
* @see https://core.telegram.org/bots/api#createchatinvitelink
*/
createChatInviteLink(chatId, form = {}) {
form.chat_id = chatId;
return this._request('createChatInviteLink', { form });
}
/**
* Use this method to edit a non-primary invite link created by the bot.
*
* The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} inviteLink Text with the invite link to edit
* @param {Object} [options] Additional Telegram query options
* @return {Promise} The edited invite link as a [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object
* @see https://core.telegram.org/bots/api#editchatinvitelink
*/
editChatInviteLink(chatId, inviteLink, form = {}) {
form.chat_id = chatId;
form.invite_link = inviteLink;
return this._request('editChatInviteLink', { form });
}
/**
* Use this method to create a subscription invite link for a channel chat.
*
* The bot must have the can_invite_users administrator rights
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} subscriptionPeriod The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days)
* @param {Number} subscriptionPrice The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat (1-2500)
* @param {Object} [options] Additional Telegram query options
* @return {Promise} The new invite link as a [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object
* @see https://core.telegram.org/bots/api#createchatsubscriptioninvitelink
*/
createChatSubscriptionInviteLink(chatId, subscriptionPeriod, subscriptionPrice, form = {}) {
form.chat_id = chatId;
form.subscription_period = subscriptionPeriod;
form.subscription_price = subscriptionPrice;
return this._request('createChatSubscriptionInviteLink', { form });
}
/**
* Use this method to edit a subscription invite link created by the bot.
*
* The bot must have the can_invite_users administrator rights
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} inviteLink The invite link to edit
* @param {Object} [options] Additional Telegram query options
* @return {Promise} The new invite link as a [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object
* @see https://core.telegram.org/bots/api#editchatsubscriptioninvitelink
*/
editChatSubscriptionInviteLink(chatId, inviteLink, form = {}) {
form.chat_id = chatId;
form.invite_link = inviteLink;
return this._request('editChatSubscriptionInviteLink', { form });
}
/**
* Use this method to revoke an invite link created by the bot.
* Note: If the primary link is revoked, a new link is automatically generated
*
* The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} inviteLink The invite link to revoke
* @param {Object} [options] Additional Telegram query options
* @return {Promise} The revoked invite link as [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object
* @see https://core.telegram.org/bots/api#revokechatinvitelink
*/
revokeChatInviteLink(chatId, inviteLink, form = {}) {
form.chat_id = chatId;
form.invite_link = inviteLink;
return this._request('revokeChatInviteLink', { form });
}
/**
* Use this method to approve a chat join request.
*
* The bot **must be an administrator in the chat** for this to work and **must have the `can_invite_users` administrator right.**
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#approvechatjoinrequest
*/
approveChatJoinRequest(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('approveChatJoinRequest', { form });
}
/**
* Use this method to decline a chat join request.
*
* The bot **must be an administrator in the chat** for this to work and **must have the `can_invite_users` administrator right**.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#declinechatjoinrequest
*/
declineChatJoinRequest(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('declineChatJoinRequest', { 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.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @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} True on success
* @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.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} title New chat title, 1-255 characters
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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 group, 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.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} description New chat title, 0-255 characters
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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.
*
* If the chat is not a private chat, the **bot must be an administrator in the chat** for this to work and must have the `can_pin_messages` administrator
* right in a supergroup or `can_edit_messages` administrator right in a channel.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} messageId Identifier of a message to pin
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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 remove a message from the list of pinned messages in a chat
*
* If the chat is not a private chat, the **bot must be an administrator in the chat** for this to work and must have the `can_pin_messages` administrator
* right in a supergroup or `can_edit_messages` administrator right in a channel.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#unpinchatmessage
*/
unpinChatMessage(chatId, form = {}) {
form.chat_id = chatId;
return this._request('unpinChatMessage', { form });
}
/**
* Use this method to clear the list of pinned messages in a chat.
*
* If the chat is not a private chat, the **bot must be an administrator in the chat** for this to work and must have the `can_pin_messages` administrator
* right in a supergroup or `can_edit_messages` administrator right in a channel.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#unpinallchatmessages
*/
unpinAllChatMessages(chatId, form = {}) {
form.chat_id = chatId;
return this._request('unpinAllChatMessages', { form });
}
/**
* Use this method for your bot to leave a group, supergroup or channel
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#leavechat
*/
leaveChat(chatId, form = {}) {
form.chat_id = chatId;
return this._request('leaveChat', { form });
}
/**
* 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 channel (in the format `@channelusername`) or channel
* @param {Object} [options] Additional Telegram query options
* @return {Promise} [ChatFullInfo](https://core.telegram.org/bots/api#chatfullinfo) object on success
* @see https://core.telegram.org/bots/api#getchat
*/
getChat(chatId, form = {}) {
form.chat_id = chatId;
return this._request('getChat', { form });
}
/**
* Use this method to get a list of administrators 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} On success, returns an Array of [ChatMember](https://core.telegram.org/bots/api#chatmember) objects that contains information about all chat administrators except other bots.
* If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned
* @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} Int on success
* @see https://core.telegram.org/bots/api#getchatmembercount
*/
getChatMemberCount(chatId, form = {}) {
form.chat_id = chatId;
return this._request('getChatMemberCount', { 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} [ChatMember](https://core.telegram.org/bots/api#chatmember) object on success
* @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 });
}
/**
* Use this method to set a new group sticker set for a supergroup.
*
* The bot **must be an administrator in the chat** for this to work and must have the appropriate administrator rights.
*
* **Note:** Use the field `can_set_sticker_set` optionally returned in [getChat](https://core.telegram.org/bots/api#getchat) requests to check if the bot can use this method.
*
* @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} True on success
* @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.
*
* Use the field `can_set_sticker_set` optionally returned in [getChat](https://core.telegram.org/bots/api#getchat) requests to check if the bot can use this method.
*
* @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} True on success
* @see https://core.telegram.org/bots/api#deletechatstickerset
*/
deleteChatStickerSet(chatId, form = {}) {
form.chat_id = chatId;
return this._request('deleteChatStickerSet', { form });
}
/**
* Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user.
*
* @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} Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects
* @see https://core.telegram.org/bots/api#getforumtopiciconstickers
*/
getForumTopicIconStickers(chatId, form = {}) {
form.chat_id = chatId;
return this._request('getForumTopicIconStickers', { form });
}
/**
* Use this method to create a topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
*
* Returns information about the created topic as a [ForumTopic](https://core.telegram.org/bots/api#forumtopic) object.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {String} name Topic name, 1-128 characters
* @param {Object} [options] Additional Telegram query options
* @see https://core.telegram.org/bots/api#createforumtopic
*/
createForumTopic(chatId, name, form = {}) {
form.chat_id = chatId;
form.name = name;
return this._request('createForumTopic', { form });
}
/**
* Use this method to edit name and icon of a topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights, unless it is the creator of the topic.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#editforumtopic
*/
editForumTopic(chatId, messageThreadId, form = {}) {
form.chat_id = chatId;
form.message_thread_id = messageThreadId;
return this._request('editForumTopic', { form });
}
/**
* Use this method to close an open topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#closeforumtopic
*/
closeForumTopic(chatId, messageThreadId, form = {}) {
form.chat_id = chatId;
form.message_thread_id = messageThreadId;
return this._request('closeForumTopic', { form });
}
/**
* Use this method to reopen a closed topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#reopenforumtopic
*/
reopenForumTopic(chatId, messageThreadId, form = {}) {
form.chat_id = chatId;
form.message_thread_id = messageThreadId;
return this._request('reopenForumTopic', { form });
}
/**
* Use this method to delete a forum topic along with all its messages in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#deleteforumtopic
*/
deleteForumTopic(chatId, messageThreadId, form = {}) {
form.chat_id = chatId;
form.message_thread_id = messageThreadId;
return this._request('deleteForumTopic', { form });
}
/**
* Use this method to clear the list of pinned messages in a forum topic.
* The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#unpinallforumtopicmessages
*/
unpinAllForumTopicMessages(chatId, messageThreadId, form = {}) {
form.chat_id = chatId;
form.message_thread_id = messageThreadId;
return this._request('unpinAllForumTopicMessages', { form });
}
/**
* Use this method to edit the name of the 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
* The topic will be automatically unhidden if it was hidden.
*
* @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
* @param {String} name New topic name, 1-128 characters
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#editgeneralforumtopic
*/
editGeneralForumTopic(chatId, name, form = {}) {
form.chat_id = chatId;
form.name = name;
return this._request('editGeneralForumTopic', { form });
}
/**
* Use this method to close an open 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
* The topic will be automatically unhidden if it was hidden.
*
* @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} True on success
* @see https://core.telegram.org/bots/api#closegeneralforumtopic
*/
closeGeneralForumTopic(chatId, form = {}) {
form.chat_id = chatId;
return this._request('closeGeneralForumTopic', { form });
}
/**
* Use this method to reopen a closed 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
* The topic will be automatically unhidden if it was hidden.
*
* @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} True on success
* @see https://core.telegram.org/bots/api#reopengeneralforumtopic
*/
reopenGeneralForumTopic(chatId, form = {}) {
form.chat_id = chatId;
return this._request('reopenGeneralForumTopic', { form });
}
/**
* Use this method to hide the 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
* The topic will be automatically closed if it was open.
*
* @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} True on success
* @see https://core.telegram.org/bots/api#hidegeneralforumtopic
*/
hideGeneralForumTopic(chatId, form = {}) {
form.chat_id = chatId;
return this._request('hideGeneralForumTopic', { form });
}
/**
* Use this method to unhide the 'General' topic in a forum supergroup chat.
* The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights
*
* @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} True on success
* @see https://core.telegram.org/bots/api#unhidegeneralforumtopic
*/
unhideGeneralForumTopic(chatId, form = {}) {
form.chat_id = chatId;
return this._request('unhideGeneralForumTopic', { form });
}
/**
* Use this method to clear the list of pinned messages in a General forum topic.
* The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the 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} True on success
* @see https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages
*/
unpinAllGeneralForumTopicMessages(chatId, form = {}) {
form.chat_id = chatId;
return this._request('unpinAllGeneralForumTopicMessages', { form });
}
/**
* Use this method to send answers to callback queries sent from
* [inline keyboards](https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating).
*
* The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
*
* 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} True on success
* @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 stores a message that can be sent by a user of a Mini App.
*
* @param {Number} userId Unique identifier of the target user
* @param {InlineQueryResult} result object that represents one result of an inline query
* @param {Object} [options] Optional form data to include in the request
* @return {Promise} On success, returns a [PreparedInlineMessage](https://core.telegram.org/bots/api#preparedinlinemessage) object.
* @see https://core.telegram.org/bots/api#savepreparedinlinemessage
*/
savePreparedInlineMessage(userId, result, form = {}) {
form.user_id = userId;
form.result = stringify(result);
return this._request('savePreparedInlineMessage', { form });
}
/**
* Use this method to get the list of boosts added to a chat by a use.
* Requires administrator rights in the chat
*
* @param {Number|String} chatId Unique identifier for the group/channel
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns a [UserChatBoosts](https://core.telegram.org/bots/api#userchatboosts) object
* @see https://core.telegram.org/bots/api#getuserchatboosts
*/
getUserChatBoosts(chatId, userId, form = {}) {
form.chat_id = chatId;
form.user_id = userId;
return this._request('getUserChatBoosts', { form });
}
/**
* Use this method to get information about the connection of the bot with a business account
*
* @param {Number|String} businessConnectionId Unique identifier for the group/channel
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns [BusinessConnection](https://core.telegram.org/bots/api#businessconnection) object
* @see https://core.telegram.org/bots/api#getbusinessconnection
*/
getBusinessConnection(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('getBusinessConnection', { form });
}
/**
* Use this method to change the list of the bot's commands.
*
* See https://core.telegram.org/bots#commands for more details about bot commands
*
* @param {Array} commands List of bot commands to be set as the list of the [bot's commands](https://core.telegram.org/bots/api#botcommand). At most 100 commands can be specified.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setmycommands
*/
setMyCommands(commands, form = {}) {
form.commands = stringify(commands);
if (form.scope) {
form.scope = stringify(form.scope);
}
return this._request('setMyCommands', { form });
}
/**
* Use this method to delete the list of the bot's commands for the given scope and user language.
*
* After deletion, [higher level commands](https://core.telegram.org/bots/api#determining-list-of-commands) will be shown to affected users.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#deletemycommands
*/
deleteMyCommands(form = {}) {
if (form.scope) {
form.scope = stringify(form.scope);
}
return this._request('deleteMyCommands', { form });
}
/**
* Use this method to get the current list of the bot's commands for the given scope and user language.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} Array of [BotCommand](https://core.telegram.org/bots/api#botcommand) on success. If commands aren't set, an empty list is returned.
* @see https://core.telegram.org/bots/api#getmycommands
*/
getMyCommands(form = {}) {
if (form.scope) {
form.scope = stringify(form.scope);
}
return this._request('getMyCommands', { form });
}
/**
* Use this method to change the bot's name.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setmyname
*/
setMyName(form = {}) {
return this._request('setMyName', { form });
}
/**
* Use this method to get the current bot name for the given user language.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} [BotName](https://core.telegram.org/bots/api#botname) on success
* @see https://core.telegram.org/bots/api#getmyname
*/
getMyName(form = {}) {
return this._request('getMyName', { form });
}
/**
* Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
*
* Returns True on success.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setmydescription
*/
setMyDescription(form = {}) {
return this._request('setMyDescription', { form });
}
/**
* Use this method to get the current bot description for the given user language.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} Returns [BotDescription](https://core.telegram.org/bots/api#botdescription) on success.
* @see https://core.telegram.org/bots/api#getmydescription
*/
getMyDescription(form = {}) {
return this._request('getMyDescription', { form });
}
/**
* Use this method to change the bot's short description, which is shown on the bot's profile page
* and is sent together with the link when users share the bot.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} Returns True on success.
* @see https://core.telegram.org/bots/api#setmyshortdescription
*/
setMyShortDescription(form = {}) {
return this._request('setMyShortDescription', { form });
}
/**
* Use this method to get the current bot short description for the given user language.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} Returns [BotShortDescription](https://core.telegram.org/bots/api#botshortdescription) on success.
* @see https://core.telegram.org/bots/api#getmyshortdescription
*/
getMyShortDescription(form = {}) {
return this._request('getMyShortDescription', { form });
}
/**
* Changes the profile photo of the bot.
*
* @param {String|stream.Stream|Buffer} photo New profile photo.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setmyprofilephoto
*/
setMyProfilePhoto(photo, options = {}) {
const opts = {
qs: options,
};
try {
const sendData = this._formatSendData('photo', photo);
opts.formData = sendData[0];
opts.qs.photo = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('setMyProfilePhoto', opts);
}
/**
* Removes the profile photo of the bot.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#removemyprofilephoto
*/
removeMyProfilePhoto(form = {}) {
return this._request('removeMyProfilePhoto', { form });
}
/**
* Use this method to change the bot's menu button in a private chat, or the default menu button.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setchatmenubutton
*/
setChatMenuButton(form = {}) {
return this._request('setChatMenuButton', { form });
}
/**
* Use this method to get the current value of the bot's menu button in a private chat, or the default menu button.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} [MenuButton](https://core.telegram.org/bots/api#menubutton) on success
* @see https://core.telegram.org/bots/api#getchatmenubutton
*/
getChatMenuButton(form = {}) {
return this._request('getChatMenuButton', { form });
}
/**
* Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels.
*
* These rights will be suggested to users, but they are are free to modify the list before adding the bot.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#getchatmenubutton
*/
setMyDefaultAdministratorRights(form = {}) {
return this._request('setMyDefaultAdministratorRights', { form });
}
/**
* Use this method to get the current default administrator rights of the bot.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} [ChatAdministratorRights](https://core.telegram.org/bots/api#chatadministratorrights) on success
* @see https://core.telegram.org/bots/api#getmydefaultadministratorrights
*/
getMyDefaultAdministratorRights(form = {}) {
return this._request('getMyDefaultAdministratorRights', { form });
}
/**
* Use this method to edit text or [game](https://core.telegram.org/bots/api#games) 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 {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} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
* @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).
*
* Note: 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} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
* @see https://core.telegram.org/bots/api#editmessagecaption
*/
editMessageCaption(caption, form = {}) {
form.caption = caption;
return this._request('editMessageCaption', { form });
}
/**
* Use this method to edit animation, 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.
*
* Note: 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} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
* @see https://core.telegram.org/bots/api#editmessagemedia
*/
editMessageMedia(media, form = {}) {
const regexAttach = /attach:\/\/.+/;
if (typeof media.media === 'string' && regexAttach.test(media.media)) {
const opts = {
qs: form,
};
opts.formData = {};
const payload = Object.assign({}, media);
delete payload.media;
try {
const attachName = String(0);
const [formData] = this._formatSendData(
attachName,
media.media.replace('attach://', ''),
media.fileOptions
);
if (formData) {
opts.formData[attachName] = formData[attachName];
payload.media = `attach://${attachName}`;
} else {
throw new errors.FatalError(`Failed to process the replacement action for your ${media.type}`);
}
} catch (ex) {
return Promise.reject(ex);
}
opts.qs.media = stringify(payload);
return this._request('editMessageMedia', opts);
}
form.media = stringify(media);
return this._request('editMessageMedia', { form });
}
/**
* Use this method to edit a checklist on behalf of a business connection.
* @param {Number|String} businessConnectionId Unique identifier for the target business connection
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {Number} messageId Unique identifier for the target message
* @param {Object} checklist A JSON-serialized object for the new checklist
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned.
* @see https://core.telegram.org/bots/api#editmessagechecklist
*/
editMessageChecklist(businessConnectionId, chatId, messageId, checklist, form = {}) {
form.business_connection_id = businessConnectionId;
form.chat_id = chatId;
form.message_id = messageId;
form.checklist = stringify(checklist);
return this._request('editMessageChecklist', { form });
}
/**
* Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
*
* Note: 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} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
* @see https://core.telegram.org/bots/api#editmessagetext
*/
editMessageReplyMarkup(replyMarkup, form = {}) {
form.reply_markup = replyMarkup;
return this._request('editMessageReplyMarkup', { form });
}
/**
* Use this method to stop a poll which was sent by the bot.
*
* @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} On success, the stopped [Poll](https://core.telegram.org/bots/api#poll) is returned
* @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 });
}
/**
* Use this method to approve a suggested post in a direct messages chat.
*
* The bot must have the 'can_post_messages' administrator right in the corresponding channel chat.
*
* @param {Number|String} chatId Unique identifier for the group/channel
* @param {Number} messageId Identifier of the original message with the suggested post
* @param {Object} [options] Additional Telegram query options
* @return {Promise} on success, returns True
* @see https://core.telegram.org/bots/api#approvesuggestedpost
*/
approveSuggestedPost(chatId, messageId, form = {}) {
form.chat_id = chatId;
form.message_id = messageId;
return this._request('approveSuggestedPost', { form });
}
/**
* Use this method to decline a suggested post in a direct messages chat.
*
* The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat.
*
* @param {Number|String} chatId Unique identifier for the group/channel
* @param {Number} messageId Identifier of the original message with the suggested post
* @param {Object} [options] Additional Telegram query options
* @return {Promise} on success, returns True
* @see https://core.telegram.org/bots/api#declinesuggestedpost
*/
declineSuggestedPost(chatId, messageId, form = {}) {
form.chat_id = chatId;
form.message_id = messageId;
return this._request('declineSuggestedPost', { form });
}
/**
* Use this method to send static .WEBP, [animated](https://telegram.org/blog/animated-stickers) .TGS,
* or [video](https://telegram.org/blog/video-stickers-better-reactions) .WEBM stickers.
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @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} On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned
* @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 get a sticker set.
*
* @param {String} name Name of the sticker set
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, a [StickerSet](https://core.telegram.org/bots/api#stickerset) object is returned
* @see https://core.telegram.org/bots/api#getstickerset
*/
getStickerSet(name, form = {}) {
form.name = name;
return this._request('getStickerSet', { form });
}
/**
* Use this method to get information about custom emoji stickers by their identifiers.
*
* @param {Array} custom_emoji_ids List of custom emoji identifiers. At most 200 custom emoji identifiers can be specified.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects.
* @see https://core.telegram.org/bots/api#getcustomemojistickers
*/
getCustomEmojiStickers(customEmojiIds, form = {}) {
form.custom_emoji_ids = stringify(customEmojiIds);
return this._request('getCustomEmojiStickers', { form });
}
/**
* Use this method to upload a file with a sticker for later use in *createNewStickerSet* and *addStickerToSet* methods (can be used multiple
* times).
*
* @param {Number} userId User identifier of sticker file owner
* @param {String|stream.Stream|Buffer} sticker A file path or a Stream with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. Can also be a `file_id` previously uploaded.
* @param {String} stickerFormat Allow values: `static`, `animated` or `video`
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise} On success, a [File](https://core.telegram.org/bots/api#file) object is returned
* @see https://core.telegram.org/bots/api#uploadstickerfile
*/
uploadStickerFile(userId, sticker, stickerFormat = 'static', options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
opts.qs.sticker_format = stickerFormat;
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('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.
*
* You must use exactly one of the fields *png_sticker*, *tgs_sticker*, or *webm_sticker*
*
* @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"*). Can contain only english letters, digits and underscores.
* Must begin with a letter, can't contain consecutive underscores and must end in `"_by_"`. `` is case insensitive. 1-64 characters.
* @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} True on success
* @see https://core.telegram.org/bots/api#createnewstickerset
*/
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.
*
* You must use exactly one of the fields *png_sticker*, *tgs_sticker*, or *webm_sticker*
*
* Animated stickers can be added to animated sticker sets and only to them
*
* Note:
* - Emoji sticker sets can have up to 200 sticker
* - Static or Animated sticker sets can have up to 120 stickers
*
* @param {Number} userId User identifier of sticker set owner
* @param {String} name Sticker set name
* @param {String|stream.Stream|Buffer} sticker 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, [TGS animation](https://core.telegram.org/stickers#animated-sticker-requirements)
* with the sticker or [WEBM video](https://core.telegram.org/stickers#video-sticker-requirements) with the sticker.
* @param {String} emojis One or more emoji corresponding to the sticker
* @param {String} stickerType Allow values: `png_sticker`, `tgs_sticker`, or `webm_sticker`.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#addstickertoset
*/
addStickerToSet(userId, name, sticker, emojis, stickerType = 'png_sticker', 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);
if (typeof stickerType !== 'string' || ['png_sticker', 'tgs_sticker', 'webm_sticker'].indexOf(stickerType) === -1) {
return Promise.reject(new Error('stickerType must be a string and the allow types is: png_sticker, tgs_sticker, webm_sticker'));
}
try {
const sendData = this._formatSendData(stickerType, sticker, fileOptions);
opts.formData = sendData[0];
opts.qs[stickerType] = 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.
*
* @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} True on success
* @see https://core.telegram.org/bots/api#setstickerpositioninset
*/
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.
*
* @param {String} sticker File identifier of the sticker
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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 replace an existing sticker in a sticker set with a new one
*
* @param {Number} userId User identifier of the sticker set owner
* @param {String} name Sticker set name
* @param {String} sticker File identifier of the sticker
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#replacestickerinset
* @todo Add tests for this method!
*/
replaceStickerInSet(userId, name, oldSticker, form = {}) {
form.user_id = userId;
form.name = name;
form.old_sticker = oldSticker;
return this._request('replaceStickerInSet', { form });
}
/**
* Use this method to change the list of emoji assigned to a regular or custom emoji sticker.
*
* The sticker must belong to a sticker set created by the bot.
*
* @param {String} sticker File identifier of the sticker
* @param { Array } emojiList A JSON-serialized list of 1-20 emoji associated with the sticker
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setstickeremojilist
*/
setStickerEmojiList(sticker, emojiList, form = {}) {
form.sticker = sticker;
form.emoji_list = stringify(emojiList);
return this._request('setStickerEmojiList', { form });
}
/**
* Use this method to change the list of emoji assigned to a `regular` or `custom emoji` sticker.
*
* The sticker must belong to a sticker set created by the bot.
*
* @param {String} sticker File identifier of the sticker
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setstickerkeywords
*/
setStickerKeywords(sticker, form = {}) {
form.sticker = sticker;
if (form.keywords) {
form.keywords = stringify(form.keywords);
}
return this._request('setStickerKeywords', { form });
}
/**
* Use this method to change the [mask position](https://core.telegram.org/bots/api#maskposition) of a mask sticker.
*
* The sticker must belong to a sticker set created by the bot.
*
* @param {String} sticker File identifier of the sticker
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setstickermaskposition
*/
setStickerMaskPosition(sticker, form = {}) {
form.sticker = sticker;
if (form.mask_position) {
form.mask_position = stringify(form.mask_position);
}
return this._request('setStickerMaskPosition', { form });
}
/**
* Use this method to set the title of a created sticker set.
*
* The sticker must belong to a sticker set created by the bot.
*
* @param {String} name Sticker set name
* @param {String} title Sticker set title, 1-64 characters
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setstickersettitle
*/
setStickerSetTitle(name, title, form = {}) {
form.name = name;
form.title = title;
return this._request('setStickerSetTitle', { form });
}
/**
* Use this method to add a thumb to a set created by the bot.
*
* Animated thumbnails can be set for animated sticker sets only. Video thumbnails can be set only for video sticker sets only
*
* @param {Number} userId User identifier of sticker set owner
* @param {String} name Sticker set name
* @param {String|stream.Stream|Buffer} thumbnail A .WEBP or .PNG image with the thumbnail,
* must be up to 128 kilobytes in size and have width and height exactly 100px,
* a TGS animation with the thumbnail up to 32 kilobytes in size or a WEBM video with the thumbnail up to 32 kilobytes in size.
*
* Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram
* to get a file from the Internet, or upload a new one. Animated sticker set thumbnails can't be uploaded via HTTP URL.
* @param {Object} [options] Additional Telegram query options
* @param {Object} [fileOptions] Optional file related meta-data
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setstickersetthumbnail
*/
setStickerSetThumbnail(userId, name, thumbnail, options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
opts.qs.name = name;
opts.qs.mask_position = stringify(options.mask_position);
try {
const sendData = this._formatSendData('thumbnail', thumbnail, fileOptions);
opts.formData = sendData[0];
opts.qs.thumbnail = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('setStickerSetThumbnail', opts);
}
/**
* Use this method to set the thumbnail of a custom emoji sticker set.
*
* The sticker must belong to a sticker set created by the bot.
*
* @param {String} name Sticker set name
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail
*/
setCustomEmojiStickerSetThumbnail(name, form = {}) {
form.name = name;
return this._request('setCustomEmojiStickerSetThumbnail', { form });
}
/**
* Use this method to delete a sticker set that was created by the bot.
*
* The sticker must belong to a sticker set created by the bot.
*
* @param {String} name Sticker set name
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#deletestickerset
*/
deleteStickerSet(name, form = {}) {
form.name = name;
return this._request('deleteStickerSet', { form });
}
/**
* Send answers to an inline query.
*
* Note: No more than 50 results per query are allowed.
*
* @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} On success, True is returned
* @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 });
}
/**
* Use this method to set the result of an interaction with a [Web App](https://core.telegram.org/bots/webapps)
* and send a corresponding message on behalf of the user to the chat from which the query originated.
*
* @param {String} webAppQueryId Unique identifier for the query to be answered
* @param {InlineQueryResult} result object that represents one result of an inline query
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, a [SentWebAppMessage](https://core.telegram.org/bots/api#sentwebappmessage) object is returned
* @see https://core.telegram.org/bots/api#answerwebappquery
*/
answerWebAppQuery(webAppQueryId, result, form = {}) {
form.web_app_query_id = webAppQueryId;
form.result = stringify(result);
return this._request('answerWebAppQuery', { form });
}
/**
* Use this method to send an invoice.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} title Product name, 1-32 characters
* @param {String} description Product description, 1-255 characters
* @param {String} payload Bot defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
* @param {String} providerToken Payments provider token, obtained via `@BotFather`
* @param {String} currency Three-letter ISO 4217 currency code
* @param {Array} prices Breakdown of prices
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned
* @see https://core.telegram.org/bots/api#sendinvoice
*/
sendInvoice(chatId, title, description, payload, providerToken, currency, prices, form = {}) {
form.chat_id = chatId;
form.title = title;
form.description = description;
form.payload = payload;
form.provider_token = providerToken;
form.currency = currency;
form.prices = stringify(prices);
form.provider_data = stringify(form.provider_data);
if (form.suggested_tip_amounts) {
form.suggested_tip_amounts = stringify(form.suggested_tip_amounts);
}
return this._request('sendInvoice', { form });
}
/**
* Use this method to create a link for an invoice.
*
* @param {String} title Product name, 1-32 characters
* @param {String} description Product description, 1-255 characters
* @param {String} payload Bot defined invoice payload
* @param {String} providerToken Payment provider token
* @param {String} currency Three-letter ISO 4217 currency code
* @param {Array} prices Breakdown of prices
* @param {Object} [options] Additional Telegram query options
* @returns {Promise} The created invoice link as String on success.
* @see https://core.telegram.org/bots/api#createinvoicelink
*/
createInvoiceLink(title, description, payload, providerToken, currency, prices, form = {}) {
form.title = title;
form.description = description;
form.payload = payload;
form.provider_token = providerToken;
form.currency = currency;
form.prices = stringify(prices);
return this._request('createInvoiceLink', { form });
}
/**
* Use this method to reply to shipping queries.
*
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified,
* the Bot API will send an [Update](https://core.telegram.org/bots/api#update) with a shipping_query field to the bot
*
* @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} On success, True is returned
* @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 });
}
/**
* Use this method to respond to such pre-checkout queries
*
* Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of
* an [Update](https://core.telegram.org/bots/api#update) with the field *pre_checkout_query*.
*
* **Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
*
* @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} On success, True is returned
* @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 the current Telegram Stars balance of the bot.
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns a [StarAmount](https://core.telegram.org/bots/api#staramount) object
* @see https://core.telegram.org/bots/api#getmystarbalance
*/
getMyStarBalance(form = {}) {
return this._request('getMyStarBalance', { form });
}
/**
* Use this method for get the bot's Telegram Star transactions in chronological order
*
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns a [StarTransactions](https://core.telegram.org/bots/api#startransactions) object
* @see https://core.telegram.org/bots/api#getstartransactions
*/
getStarTransactions(form = {}) {
return this._request('getStarTransactions', { form });
}
/**
* Use this method for refund a successful payment in [Telegram Stars](https://t.me/BotNews/90)
*
* @param {Number} userId Unique identifier of the user whose payment will be refunded
* @param {String} telegramPaymentChargeId Telegram payment identifier
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, True is returned
* @see https://core.telegram.org/bots/api#refundstarpayment
*/
refundStarPayment(userId, telegramPaymentChargeId, form = {}) {
form.user_id = userId;
form.telegram_payment_charge_id = telegramPaymentChargeId;
return this._request('refundStarPayment', { form });
}
/**
* Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars.
*
* @param {Number} userId Unique identifier of the user whose subscription will be canceled or re-enabled
* @param {String} telegramPaymentChargeId Telegram payment identifier for the subscription
* @param {Boolean} isCanceled True, if the subscription should be canceled, False, if it should be re-enabled
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, True is returned
* @see https://core.telegram.org/bots/api#cancelrenewsubscription
*/
editUserStarSubscription(userId, telegramPaymentChargeId, isCanceled, form = {}) {
form.user_id = userId;
form.telegram_payment_charge_id = telegramPaymentChargeId;
form.is_canceled = isCanceled;
return this._request('editUserStarSubscription', { form });
}
/**
* Use this method to send a game.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param {String} gameShortName name of the game to be sent. Set up your games via `@BotFather`.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned
* @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 message.
*
* @param {Number} userId Unique identifier of the target user
* @param {Number} score New score value, must be non-negative
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, if the message is not an inline message, the [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
* @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 tables.
*
* Will return the score of the specified user and several of their neighbors in a game.
*
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns an Array of [GameHighScore](https://core.telegram.org/bots/api#gamehighscore) objects
* @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, including service messages, with the following limitations:
* - A message can only be deleted if it was sent less than 48 hours ago.
* - A dice message can only be deleted if it was sent more than 24 hours ago.
* - Bots can delete outgoing messages in groups and supergroups.
* - Bots can delete incoming messages in groups, supergroups and channels.
* - Bots granted `can_post_messages` permissions can delete outgoing messages in channels.
* - If the bot is an administrator of a group, it can delete any message there.
* - If the bot has `can_delete_messages` permission in a supergroup, it can delete any message there.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param {Number} messageId Unique identifier of the target message
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @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 });
}
/**
* Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param {Array} messageIds Identifiers of 1-100 messages to delete. See deleteMessage for limitations on which messages can be deleted
* @param {Object} [options] Additional Telegram query options
* @return {Promise} True on success
* @see https://core.telegram.org/bots/api#deletemessages
*/
deleteMessages(chatId, messageIds, form = {}) {
form.chat_id = chatId;
form.message_ids = stringify(messageIds);
return this._request('deleteMessages', { form });
}
/**
* Use this method to returns the list of gifts that can be sent by the bot to users and channel chats.
*
* @param {Object} [options] Additional Telegram query options.
* @return {Promise} On success, returns a [Gifts](https://core.telegram.org/bots/api#gifts) objects.
* @see https://core.telegram.org/bots/api#getavailablegifts
*/
getAvailableGifts(form = {}) {
return this._request('getAvailableGifts', { form });
}
/**
* Use this method to sends a gift to the given user or channel chat.
*
* @param {String} giftId Unique identifier of the gift
* @param {Object} [options] Additional Telegram query options.
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#getavailablegifts
*/
sendGift(giftId, form = {}) {
form.gift_id = giftId;
return this._request('sendGift', { form });
}
/**
* Use this method to sends a gift to the given user or channel chat.
*
* @param {Number} userId Unique identifier of the target user who will receive a Telegram Premium subscription.
* @param {Number} monthCount Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12.
* @param {String} starCount Number of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months.
* @param {Object} [options] Additional Telegram query options.
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#getavailablegifts
*/
giftPremiumSubscription(userId, monthCount, starCount, form = {}) {
form.user_id = userId;
form.month_count = monthCount;
form.star_count = starCount;
return this._request('giftPremiumSubscription', { form });
}
/**
* This method verifies a user [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot.
*
* @param {Number} userId Unique identifier of the target user.
* @param {Object} [options] Additional Telegram query options.
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#verifyuser
*/
verifyUser(userId, form = {}) {
form.user_id = userId;
return this._request('verifyUser', { form });
}
/**
* This method verifies a chat [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot.
*
* @param {Number} chatId Unique identifier of the target chat.
* @return {Promise} On success, returns true.
* @param {Object} [options] Additional Telegram query options.
* @see https://core.telegram.org/bots/api#verifychat
*/
verifyChat(chatId, form = {}) {
form.chat_id = chatId;
return this._request('verifyChat', { form });
}
/**
* This method removes verification from a user who is currently verified [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot.
*
* @param {Number} userId Unique identifier of the target user
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#removeuserverification
*/
removeUserVerification(userId, form = {}) {
form.user_id = userId;
return this._request('removeUserVerification', { form });
}
/**
* This method removes verification from a chat who is currently verified [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot.
*
* @param {Number} chatId Unique identifier of the target chat.
* @param {Object} [options] Additional Telegram query options.
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#removechatverification
*/
removeChatVerification(chatId, form = {}) {
form.chat_id = chatId;
return this._request('removeChatVerification', { form });
}
/**
* This method marks incoming message as read on behalf of a business account.
*
* Requires the **can_read_messages** business bot right
*
* @param {String} businessConnectionId Unique identifier of the business connection on behalf of which to read the message.
* @param {Number} chatId Unique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours.
* @param {Number} messageId Unique identifier of the message to mark as read.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#readbusinessmessage
*/
readBusinessMessage(businessConnectionId, chatId, messageId, form = {}) {
form.business_connection_id = businessConnectionId;
form.chat_id = chatId;
form.message_id = messageId;
return this._request('readBusinessMessage', { form });
}
/**
* This method delete messages on behalf of a business account.
*
* Requires the **can_delete_outgoing_messages** business bot right to delete messages sent by the bot itself, or the **can_delete_all_messages business** bot right to delete any message.
*
* @param {String} businessConnectionId Unique identifier of the business connection on behalf of which to delete the message.
* @param {Number[]} messageIds List of 1-100 identifiers of messages to delete. All messages **must be from the same chat**.
* @param {Object} [options] Additional Telegram query options.
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#deletebusinessmessages
*/
deleteBusinessMessages(businessConnectionId, messageIds, form = {}) {
form.business_connection_id = businessConnectionId;
form.message_ids = stringify(messageIds);
return this._request('deleteBusinessMessages', { form });
}
/**
* This method changes the first and last name of a managed business account.
*
* Requires the **can_change_name** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {String} firstName The new value of the first name for the business account; 1-64 characters.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#setbusinessaccountname
*/
setBusinessAccountName(businessConnectionId, firstName, form = {}) {
form.business_connection_id = businessConnectionId;
form.first_name = firstName;
return this._request('setBusinessAccountName', { form });
}
/**
* This method changes the username of a managed business account.
*
* Requires the **can_change_username** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#setbusinessaccountusername
*/
setBusinessAccountUsername(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('setBusinessAccountUsername', { form });
}
/**
* This method changes the bio of a managed business account.
*
* Requires the **can_change_bio** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#setbusinessaccountbio
*/
setBusinessAccountBio(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('setBusinessAccountBio', { form });
}
/**
* This method changes the profile photo of a managed business account.
*
* Requires the **can_edit_profile_photo** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {String|stream.Stream|Buffer} photo New profile photo.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#setbusinessaccountprofilephoto
*/
setBusinessAccountProfilePhoto(businessConnectionId, photo, options = {}) {
const opts = {
qs: options,
};
opts.qs.business_connection_id = businessConnectionId;
try {
const sendData = this._formatSendData('photo', photo);
opts.formData = sendData[0];
opts.qs.photo = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('setBusinessAccountProfilePhoto', opts);
}
/**
* This method removes the current profile photo of a managed business account.
*
* Requires the **can_edit_profile_photo** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#removebusinessaccountprofilephoto
*/
removeBusinessAccountProfilePhoto(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('removeBusinessAccountProfilePhoto', { form });
}
/**
* This method changes the privacy settings pertaining to incoming gifts in a managed business account.
*
* Requires the **can_change_gift_settings** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Boolean} showGiftButton Pass True, if a button for sending a gift to the user or by the business account must always be shown in the input field.
* @param {Object} acceptedGiftTypes Types of gifts accepted by the business account.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns true.
* @see https://core.telegram.org/bots/api#setbusinessaccountgiftsettings
*/
setBusinessAccountGiftSettings(businessConnectionId, showGiftButton, acceptedGiftTypes, form = {}) {
form.business_connection_id = businessConnectionId;
form.show_gift_button = showGiftButton;
form.accepted_gift_types = acceptedGiftTypes;
return this._request('setBusinessAccountGiftSettings', { form });
}
/**
* This method returns the amount of Telegram Stars owned by a managed business account.
*
* Requires the **can_view_gifts_and_stars** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns [StarAmount](https://core.telegram.org/bots/api#staramount).
* @see https://core.telegram.org/bots/api#getbusinessaccountstarbalance
*/
getBusinessAccountStarBalance(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('getBusinessAccountStarBalance', { form });
}
/**
* This method transfers Telegram Stars from the business account balance to the bot's balance.
*
* Requires the **can_transfer_stars** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Number} starCount Number of Telegram Stars to transfer; 1-10000.
* @param {Object} [options] Additional Telegram query options.
* @return {Promise} On success, returns True.
* @see https://core.telegram.org/bots/api#transferbusinessaccountstars
*/
transferBusinessAccountStars(businessConnectionId, startCount, form = {}) {
form.business_connection_id = businessConnectionId;
form.star_count = startCount;
return this._request('transferBusinessAccountStars', { form });
}
/**
* This method returns the gifts received and owned by a managed business account.
*
* Requires the **can_view_gifts_and_stars** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns [OwnedGifts](https://core.telegram.org/bots/api#ownedgifts).
* @see https://core.telegram.org/bots/api#getbusinessaccountgifts
*/
getBusinessAccountGifts(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('getBusinessAccountGifts', { form });
}
/**
* Use this method to get gifts owned by a regular user.
*
* @param {Number} userId Unique identifier of the target user.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns an [OwnedGifts](https://core.telegram.org/bots/api#ownedgifts) object.
* @see https://core.telegram.org/bots/api#getusergifts
*/
getUserGifts(userId, form = {}) {
form.user_id = userId;
return this._request('getUserGifts', { form });
}
/**
* Use this method to get gifts received by a channel chat or a business account managed by the bot.
*
* Requires the **can_view_gifts_and_stars** administrator right if the chat is a channel.
*
* @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`).
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns an [OwnedGifts](https://core.telegram.org/bots/api#ownedgifts) object.
* @see https://core.telegram.org/bots/api#getchatgifts
*/
getChatGifts(chatId, form = {}) {
form.chat_id = chatId;
return this._request('getChatGifts', { form });
}
/**
* This method converts a given regular gift to Telegram Stars.
*
* Requires the **can_convert_gifts_to_stars** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {String} ownedGiftId Unique identifier of the regular gift that should be converted to Telegram Stars.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns True.
* @see https://core.telegram.org/bots/api#convertgifttostars
*/
convertGiftToStars(businessConnectionId, ownedGiftId, form = {}) {
form.business_connection_id = businessConnectionId;
form.owned_gift_id = ownedGiftId;
return this._request('convertGiftToStars', { form });
}
/**
* This method upgrades a given regular gift to a unique gift.
*
* Requires the **can_transfer_and_upgrade_gifts** business bot right.
* Additionally requires the **can_transfer_stars** business bot right **if the upgrade is paid**.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {String} ownedGiftId Unique identifier of the regular gift that should be upgraded to a unique one.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns True.
* @see https://core.telegram.org/bots/api#upgradegift
*/
upgradeGift(businessConnectionId, ownedGiftId, form = {}) {
form.business_connection_id = businessConnectionId;
form.owned_gift_id = ownedGiftId;
return this._request('upgradeGift', { form });
}
/**
* This method transfers an owned unique gift to another user.
*
* Requires the **can_transfer_and_upgrade_gifts** business bot right.
* Additionally requires the **can_transfer_stars** business bot right **if the transfer is paid**.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {String} ownedGiftId Unique identifier of the regular gift that should be transferred.
* @param {Number} newOwnerChatId Unique identifier of the chat which will own the gift. The chat **must be active in the last 24 hours**.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns True.
* @see https://core.telegram.org/bots/api#transfergift
*/
transferGift(businessConnectionId, ownedGiftId, newOwnerChatId, form = {}) {
form.business_connection_id = businessConnectionId;
form.owned_gift_id = ownedGiftId;
form.new_owner_chat_id = newOwnerChatId;
return this._request('transferGift', { form });
}
/**
* This method posts a story on behalf of a managed business account.
*
* Requires the **can_manage_stories** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Array} content [InputStoryContent](https://core.telegram.org/bots/api#inputpaidmedia). The photo/video property can be String, Stream or Buffer.
* @param {Number} activePeriod Unique identifier of the chat which will own the gift. The chat **must be active in the last 24 hours**.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns [Story](https://core.telegram.org/bots/api#story).
* @see https://core.telegram.org/bots/api#poststory
*/
postStory(businessConnectionId, content, activePeriod, options = {}) {
const opts = {
qs: options,
};
opts.qs.business_connection_id = businessConnectionId;
opts.qs.active_period = activePeriod;
try {
const inputHistoryContent = content;
opts.formData = {};
if (!content.type) {
return Promise.reject(new Error('content.type is required'));
}
const { formData, fileIds } = this._formatSendMultipleData(content.type, [content]);
opts.formData = formData;
if (fileIds[0]) {
inputHistoryContent[content.type] = fileIds[0];
} else {
inputHistoryContent[content.type] = `attach://${content.type}_0`;
}
opts.qs.content = stringify(inputHistoryContent);
} catch (ex) {
return Promise.reject(ex);
}
return this._request('postStory', opts);
}
/**
* This method reposts a story on behalf of a managed business account.
*
* Requires the **can_manage_stories** business bot right for both the source and destination accounts.
* The story must have been originally posted or reposted by the bot itself.
*
* @param {String} businessConnectionId Unique identifier of the business connection of the account that will repost the story.
* @param {Number} fromChatId Unique identifier of the chat that originally posted the story.
* @param {Number} fromStoryId Unique identifier of the story to repost.
* @param {Number} activePeriod The period after which the story is moved to archive, in seconds; must be one of 21600, 43200, 86400, or 172800.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns a [Story](https://core.telegram.org/bots/api#story) object.
* @see https://core.telegram.org/bots/api#repoststory
*/
repostStory(businessConnectionId, fromChatId, fromStoryId, activePeriod, form = {}) {
form.business_connection_id = businessConnectionId;
form.from_chat_id = fromChatId;
form.from_story_id = fromStoryId;
form.active_period = activePeriod;
return this._request('repostStory', { form });
}
/**
* This method edits a story previously posted by the bot on behalf of a managed business account.
*
* Requires the **can_manage_stories** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Number} storyId Unique identifier of the story to edit.
* @param {Array} content [InputStoryContent](https://core.telegram.org/bots/api#inputpaidmedia). The photo/video property can be String, Stream or Buffer.
* @param {Object} [options] Additional Telegram query options
* @return {Promise} On success, returns [Story](https://core.telegram.org/bots/api#story).
* @see https://core.telegram.org/bots/api#editstory
*/
editStory(businessConnectionId, storyId, content, options = {}) {
const opts = {
qs: options,
};
opts.qs.business_connection_id = businessConnectionId;
opts.qs.story_id = storyId;
try {
const inputHistoryContent = content;
opts.formData = {};
if (!content.type) {
return Promise.reject(new Error('content.type is required'));
}
const { formData, fileIds } = this._formatSendMultipleData(content.type, [content]);
opts.formData = formData;
if (fileIds[0]) {
inputHistoryContent[content.type] = fileIds[0];
} else {
inputHistoryContent[content.type] = `attach://${content.type}_0`;
}
opts.qs.content = stringify(inputHistoryContent);
} catch (ex) {
return Promise.reject(ex);
}
return this._request('editStory', opts);
}
/**
* This method deletes a story previously posted by the bot on behalf of a managed business account.
*
* Requires the **can_manage_stories** business bot right.
*
* @param {String} businessConnectionId Unique identifier of the business connection.
* @param {Number} storyId Unique identifier of the story to delete.
* @param {Object} [options] Additional Telegram query options.
* @return {Promise} On success, returns True.
* @see https://core.telegram.org/bots/api#deletestory
*/
deleteStory(businessConnectionId, storyId, form = {}) {
form.business_connection_id = businessConnectionId;
form.story_id = storyId;
return this._request('deleteStory', { form });
}
}
module.exports = TelegramBot;
================================================
FILE: src/telegramPolling.js
================================================
const errors = require('./errors');
const debug = require('debug')('node-telegram-bot-api');
const deprecate = require('./utils').deprecate;
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(`${new Date().toISOString()} 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';
const ts = new Date().toISOString();
console.error(`${ts} error: Internal handling of The Offset Infinite Loop failed`);
console.error(`${ts} error: Due to error '${requestErr}'`);
console.error(`${ts} error: You may receive already-processed updates on app restart`);
console.error(`${ts} 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;
================================================
FILE: src/telegramWebHook.js
================================================
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');
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, reject) => {
this._webServer.listen(this.options.port, this.options.host, () => {
debug('WebHook listening on port %s', this.options.port);
this._open = true;
return resolve();
});
this._webServer.once('error', (err) => {
reject(err);
});
});
}
/**
* 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(`${new Date().toISOString()} 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;
================================================
FILE: src/utils.js
================================================
const util = require('util');
// Native deprecation warning
exports.deprecate = (msg) => util.deprecate(() => { }, msg, 'node-telegram-bot-api')();
================================================
FILE: test/README.md
================================================
Running the tests:
```bash
# Token to be used
export TEST_TELEGRAM_TOKEN=
# User Id which you want to send the messages.
export TEST_USER_ID=
# Group Id which to use in some of the tests, e.g. for TelegramBot#getChat()
export TEST_GROUP_ID=
# Game short name to use in some tests, e.g. TelegramBot#sendGame()
# Defaults to "medusalab_test".
export TEST_GAME_SHORT_NAME=
# Sticker set name to use in some tests, e.g. TelegramBot#getStickerSet()
# Defaults to "pusheen".
export TEST_STICKER_SET_NAME=
# Payment provider token to be used
export TEST_PROVIDER_TOKEN=
# Run ALL tests
npm run test
# Run individual tests
npm run eslint # static-analysis
npm run mocha # mocha tests
```
Note: The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
================================================
FILE: test/mocha.opts
================================================
--reporter spec
--require babel-register
--timeout 30000
================================================
FILE: test/telegram.js
================================================
const TelegramBot = require('..');
const request = require('@cypress/request-promise');
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const stream = require('stream');
const is = require('is');
const utils = require('./utils');
const isCI = require('is-ci');
const concat = require('concat-stream');
// Allows self-signed certificates to be used in our tests
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const TOKEN = process.env.TEST_TELEGRAM_TOKEN;
if (!TOKEN) {
throw new Error('Bot token not provided');
}
const PROVIDER_TOKEN = process.env.TEST_PROVIDER_TOKEN;
if (!PROVIDER_TOKEN && !isCI) { // If is not running in Travis / Appveyor
throw new Error('Provider token not supplied');
}
// Telegram service if not User Id
const USERID = process.env.TEST_USER_ID || 777000;
const GROUPID = process.env.TEST_GROUP_ID || -1001075450562;
const GAME_SHORT_NAME = process.env.TEST_GAME_SHORT_NAME || 'medusalab_test';
const STICKER_SET_NAME = process.env.TEST_STICKER_SET_NAME || 'pusheen';
const CURRENT_TIMESTAMP = Date.now();
const timeout = 60 * 1000;
let portindex = 8091;
const staticPort = portindex++;
const pollingPort = portindex++;
const webHookPort = portindex++;
const pollingPort2 = portindex++;
const webHookPort2 = portindex++;
const badTgServerPort = portindex++;
const staticUrl = `http://127.0.0.1:${staticPort}`;
const key = `${__dirname}/../examples/ssl/key.pem`;
const cert = `${__dirname}/../examples/ssl/crt.pem`;
const ip = '216.58.210.174'; // Google IP ¯\_(ツ)_/¯
const lat = 47.5351072;
const long = -52.7508537;
const FILE_PATH = `${__dirname}/data/photo.png`;
let FILE_ID;
let GAME_CHAT_ID;
let GAME_MSG_ID;
let BOT_USERNAME;
let CHAT_INFO;
let STICKER_FILE_ID_FROM_SET;
let STICKERS_FROM_BOT_SET;
before(function beforeAll() {
utils.startStaticServer(staticPort);
return utils.startMockServer(pollingPort)
.then(() => {
return utils.startMockServer(pollingPort2);
}).then(() => {
return utils.startMockServer(badTgServerPort, { bad: true });
});
});
describe('module.exports', function moduleExportsSuite() {
const nodeVersion = parseInt(process.versions.node.split('.')[0], 10);
it('is loaded from src/ on Node.js v6+ and above', function test() {
if (nodeVersion <= 5) this.skip(); // skip on Node.js v5 and below
assert.strictEqual(TelegramBot, require('../src/telegram'));
});
it('is loaded from lib/ on Node.js v5 and below', function test() {
if (nodeVersion > 5) this.skip(); // skip on newer versions
assert.strictEqual(TelegramBot, require('../lib/telegram'));
});
});
describe('TelegramBot', function telegramSuite() {
let bot;
let testbot;
let botPolling;
let botWebHook;
before(function beforeAll() {
this.timeout(timeout);
bot = new TelegramBot(TOKEN);
testbot = new TelegramBot(TOKEN, {
baseApiUrl: `http://127.0.0.1:${pollingPort}`,
polling: {
autoStart: false,
},
webHook: {
autoOpen: false,
port: webHookPort,
},
});
botPolling = new TelegramBot(TOKEN, {
baseApiUrl: `http://127.0.0.1:${pollingPort2}`,
polling: true,
});
botWebHook = new TelegramBot(TOKEN, {
webHook: {
port: webHookPort2,
},
});
utils.handleRatelimit(bot, 'sendPhoto', this);
utils.handleRatelimit(bot, 'sendMessage', this);
utils.handleRatelimit(bot, 'sendGame', this);
utils.handleRatelimit(bot, 'getMe', this);
utils.handleRatelimit(bot, 'getChat', this);
return bot.sendPhoto(USERID, FILE_PATH).then(resp => {
FILE_ID = resp.photo[0].file_id;
return bot.sendMessage(USERID, 'chat');
}).then(resp => {
GAME_CHAT_ID = resp.chat.id;
return bot.sendGame(USERID, GAME_SHORT_NAME);
}).then(resp => {
GAME_MSG_ID = resp.message_id;
}).then(() => {
return bot.getMe().then(resp => {
BOT_USERNAME = resp.username;
});
}).then(() =>
bot.getChat(GROUPID).then(resp => {
CHAT_INFO = resp;
}));
});
it('automatically starts polling', function test() {
assert.strictEqual(botPolling.isPolling(), true);
return utils.isPollingMockServer(pollingPort2);
});
it('automatically opens webhook', function test() {
assert.strictEqual(botWebHook.hasOpenWebHook(), true);
return utils.hasOpenWebHook(webHookPort2);
});
it('does not automatically poll if "autoStart" is false', function test() {
assert.strictEqual(testbot.isPolling(), false);
return utils.isPollingMockServer(pollingPort, true);
});
it('does not automatically open webhook if "autoOpen" is false', function test() {
assert.strictEqual(testbot.hasOpenWebHook(), false);
return utils.hasOpenWebHook(webHookPort, true);
});
it('correctly deletes the webhook if polling', function test() {
const myBot = new TelegramBot(TOKEN, {
polling: { autoStart: false, params: { timeout: 0 } },
});
utils.handleRatelimit(myBot, 'setWebHook', this);
myBot.on('polling_error', (error) => {
assert.ifError(error);
});
return myBot.setWebHook(ip, {}).then(() => {
return myBot.startPolling();
}).then(() => {
return myBot.stopPolling();
});
});
describe('Events', function eventsSuite() {
it('(polling) emits "message" on receiving message', function test(done) {
botPolling.once('message', () => {
return done();
});
});
it('(polling) emits "polling_error" if error occurs during polling', function test(done) {
const myBot = new TelegramBot(12345, { polling: true });
myBot.once('polling_error', (error) => {
assert.ok(error);
assert.strictEqual(error.code, 'ETELEGRAM');
return myBot.stopPolling().then(() => { done(); }).catch(done);
});
});
it('(webhook) emits "message" on receiving message', function test(done) {
botWebHook.once('message', () => {
return done();
});
utils.sendWebHookMessage(webHookPort2, TOKEN);
});
it('(webhook) emits "webhook_error" if could not parse webhook request body', function test(done) {
botWebHook.once('webhook_error', (error) => {
assert.ok(error);
assert.strictEqual(error.code, 'EPARSE');
return done();
});
utils.sendWebHookMessage(webHookPort2, TOKEN, { update: 'unparseable!', json: false });
});
});
describe('WebHook', function webHookSuite() {
it('returns 200 OK for health endpoint', function test(done) {
utils.sendWebHookRequest(webHookPort2, '/healthz').then(resp => {
assert.strictEqual(resp, 'OK');
return done();
});
});
it('returns 401 error if token is wrong', function test(done) {
utils.sendWebHookMessage(webHookPort2, 'wrong-token').catch(resp => {
assert.strictEqual(resp.statusCode, 401);
return done();
});
});
it('only accepts POST method', function test() {
const methods = ['GET', 'PUT', 'DELETE', 'OPTIONS'];
return Promise.all(methods, (method) => {
return utils.sendWebHookMessage(webHookPort2, TOKEN, {
method,
}).then(() => {
throw new Error(`expected error with webhook ${method} request`);
}).catch(resp => {
if (!resp.statusCode) throw resp;
if (resp.statusCode !== 418) throw new Error(`unexpected error: ${resp.body}`);
});
}); // Promise.each
});
});
describe('WebHook HTTPS', function webHookHTTPSSuite() {
const port = portindex++;
let httpsbot;
afterEach(function afterEach() {
return httpsbot.closeWebHook();
});
it('is enabled, through options.key and options.cert', function test() {
httpsbot = new TelegramBot(TOKEN, { webHook: { port, key, cert } });
return utils.sendWebHookMessage(port, TOKEN, { https: true });
});
it('is enabled, through options.pfx');
it('is enabled, through options.https', function test() {
httpsbot = new TelegramBot(TOKEN, {
webHook: {
port,
https: {
key: fs.readFileSync(key),
cert: fs.readFileSync(cert),
},
},
});
return utils.sendWebHookMessage(port, TOKEN, { https: true });
});
});
describe('errors', function errorsSuite() {
const botParse = new TelegramBot('useless-token', {
baseApiUrl: `http://localhost:${badTgServerPort}`,
});
it('FatalError is thrown if token is missing', function test() {
const myBot = new TelegramBot(null);
return myBot.sendMessage(USERID, 'text').catch(error => {
// FIX: assert.ok(error instanceof TelegramBot.errors.FatalError);
assert.strictEqual(error.code, 'EFATAL');
assert.ok(error.message.indexOf('not provided') > -1);
});
});
it('FatalError is thrown if file-type of Buffer could not be determined', function test() {
let buffer;
try {
buffer = Buffer.from('12345');
} catch (ex) {
buffer = new Buffer('12345');
}
return bot.sendPhoto(USERID, buffer).catch(error => {
// FIX: assert.ok(error instanceof TelegramBot.errors.FatalError);
assert.strictEqual(error.code, 'EFATAL');
assert.ok(error.message.indexOf('Unsupported') > -1);
});
});
it('FatalError is thrown on network error', function test() {
const myBot = new TelegramBot('useless-token', {
baseApiUrl: 'http://localhost:23', // are we sure this port is not bound to?
});
return myBot.getMe().catch(error => {
// FIX: assert.ok(error instanceof TelegramBot.errors.FatalError);
assert.strictEqual(error.code, 'EFATAL');
});
});
it('ParseError is thrown if response body could not be parsed', function test() {
botParse.sendMessage(USERID, 'text').catch(error => {
// FIX: assert.ok(error instanceof TelegramBot.errors.ParseError);
assert.strictEqual(error.code, 'EPARSE');
assert.ok(typeof error.response === 'object');
assert.ok(typeof error.response.body === 'string');
});
});
it('TelegramError is thrown if error is from Telegram', function test() {
return bot.sendMessage('404', 'text').catch(error => {
// FIX: assert.ok(error instanceof TelegramBot.errors.TelegramError);
assert.strictEqual(error.code, 'ETELEGRAM');
assert.ok(typeof error.response === 'object');
assert.ok(typeof error.response.body === 'object');
});
});
});
describe('#startPolling', function initPollingSuite() {
it('initiates polling', function test() {
return testbot.startPolling().then(() => {
return utils.isPollingMockServer(pollingPort);
});
});
it('returns error if using webhook', function test() {
return botWebHook.startPolling().catch((err) => {
// TODO: check for error in a better way
// FIX: assert.ok(err instanceof TelegramBot.errors.FatalError);
assert.strictEqual(err.code, 'EFATAL');
assert.ok(err.message.indexOf('mutually exclusive') !== -1);
});
});
});
describe('#isPolling', function isPollingSuite() {
it('returns true if bot is polling', function test() {
assert.strictEqual(testbot.isPolling(), true);
return utils.isPollingMockServer(pollingPort);
});
it('returns false if bot is not polling', function test() {
return testbot.stopPolling().then(() => {
assert.strictEqual(testbot.isPolling(), false);
utils.clearPollingCheck(pollingPort);
return utils.isPollingMockServer(pollingPort, true);
});
});
after(function after() {
return testbot.initPolling();
});
});
describe('#stopPolling', function stopPollingSuite() {
it('stops polling by bot', function test() {
return testbot.stopPolling().then(() => {
utils.clearPollingCheck(pollingPort);
return utils.isPollingMockServer(pollingPort, true);
});
});
});
describe('#openWebHook', function openWebHookSuite() {
it('opens webhook', function test() {
return testbot.openWebHook().then(() => {
return utils.hasOpenWebHook(webHookPort);
});
});
it('returns error if using polling', function test() {
return botPolling.openWebHook().catch((err) => {
// TODO: check for error in a better way
// FIX: assert.ok(err instanceof TelegramBot.errors.FatalError);
assert.strictEqual(err.code, 'EFATAL');
assert.ok(err.message.indexOf('mutually exclusive') !== -1);
});
});
});
describe('#hasOpenWebHook', function hasOpenWebHookSuite() {
it('returns true if webhook is opened', function test() {
assert.strictEqual(testbot.hasOpenWebHook(), true);
return utils.hasOpenWebHook(webHookPort);
});
it('returns false if webhook is closed', function test() {
testbot.closeWebHook().then(() => {
assert.strictEqual(testbot.hasOpenWebHook(), false);
return utils.hasOpenWebHook(webHookPort, true);
});
});
after(function after() {
return testbot.openWebHook();
});
});
describe('#closeWebHook', function closeWebHookSuite() {
it('closes webhook', function test() {
testbot.closeWebHook().then(() => {
return utils.hasOpenWebHook(webHookPort, true);
});
});
});
describe('#setWebHook', function setWebHookSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setWebHook', this);
});
it('should set a webHook', function test() {
return bot
.setWebHook(ip, {})
.then(resp => {
assert.strictEqual(resp, true);
});
});
it('should set a webHook with certificate', function test() {
return bot
.setWebHook(ip, { certificate: cert })
.then(resp => {
assert.strictEqual(resp, true);
});
});
it('(v0.25.0 and lower) should set a webHook with certificate', function test() {
return bot
.setWebHook(ip, cert)
.then(resp => {
assert.strictEqual(resp, true);
});
});
it('should delete the webHook', function test() {
return bot
.setWebHook('', {})
.then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#getWebHookInfo', function getWebHookInfoSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getWebHookInfo', this);
});
it('should return WebhookInfo', function test() {
return bot.getWebHookInfo().then(resp => {
assert.ok(is.object(resp));
assert.ok(is.boolean(resp.has_custom_certificate));
assert.ok(is.number(resp.pending_update_count));
});
});
});
describe('#deleteWebHook', function deleteWebHookSuite() {
before(function before() {
utils.handleRatelimit(bot, 'deleteWebHook', this);
});
it('should delete webhook', function test() {
return bot.deleteWebHook().then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#getUpdates', function getUpdatesSuite() {
const opts = {
timeout: 0,
limit: 10,
};
before(function before() {
utils.handleRatelimit(bot, 'setWebHook', this);
utils.handleRatelimit(bot, 'getUpdates', this);
return bot.deleteWebHook();
});
it('should return an Array', function test() {
return bot.getUpdates(opts).then(resp => {
assert.strictEqual(Array.isArray(resp), true);
});
});
it('(v0.25.0 and lower) should return an Array', function test() {
return bot.getUpdates(opts.timeout, opts.limit).then(resp => {
assert.strictEqual(Array.isArray(resp), true);
});
});
});
describe('#getMe', function getMeSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getMe', this);
});
it('should return an User object', function test() {
return bot.getMe().then(resp => {
assert.ok(is.object(resp));
assert.ok(is.number(resp.id));
assert.ok(is.string(resp.first_name));
});
});
});
describe('#getFileLink', function getFileLinkSuite() {
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'getFileLink', this);
});
it('should get a file link', function test() {
return bot.getFileLink(FILE_ID)
.then(fileURI => {
assert.ok(is.string(fileURI));
assert.ok(utils.isTelegramFileURI(fileURI));
});
});
});
describe('#getFileStream', function getFileStreamSuite() {
this.timeout(timeout);
before(function before() {
// utils.handleRatelimit(bot, 'getFileStream', this);
});
it('should get a file stream', function test(done) {
const fileStream = bot.getFileStream(FILE_ID);
assert.ok(fileStream instanceof stream.Readable);
assert.strictEqual(fileStream.path, FILE_ID);
fileStream.on('info', (info) => {
assert.ok(info);
assert.ok(utils.isTelegramFileURI(info.uri), `${info.uri} is not a file URI`);
fileStream.pipe(concat(function readFile(buffer) {
buffer.equals(fs.readFileSync(FILE_PATH)); // sync :(
return done();
}));
});
});
});
describe('#downloadFile', function downloadFileSuite() {
const downloadPath = os.tmpdir();
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'downloadFile', this);
});
it('should download a file', function test() {
return bot.downloadFile(FILE_ID, downloadPath)
.then(filePath => {
assert.ok(is.string(filePath));
assert.strictEqual(path.dirname(filePath), downloadPath);
assert.ok(fs.existsSync(filePath));
fs.unlinkSync(filePath); // Delete file after test
});
});
});
describe('#onText', function onTextSuite() {
it('should call `onText` callback on match', function test(done) {
const regexp = /\/onText (.+)/;
botWebHook.onText(regexp, (msg, match) => {
assert.strictEqual(match[1], 'ECHO ALOHA');
assert.ok(botWebHook.removeTextListener(regexp));
return done();
});
utils.sendWebHookMessage(webHookPort2, TOKEN, {
message: { text: '/onText ECHO ALOHA' },
});
});
it('should reset the global regex state with each message', function test(done) {
const regexp = /\/onText (.+)/g;
botWebHook.onText(regexp, () => {
assert.strictEqual(regexp.lastIndex, 0);
assert.ok(botWebHook.removeTextListener(regexp));
return done();
});
utils.sendWebHookMessage(webHookPort2, TOKEN, {
message: { text: '/onText ECHO ALOHA' },
});
});
});
describe('#removeTextListener', function removeTextListenerSuite() {
const regexp = /\/onText/;
const regexp2 = /\/onText/;
const callback = function noop() { };
after(function after() {
bot.removeTextListener(regexp);
bot.removeTextListener(regexp2);
});
it('removes the right text-listener', function test() {
bot.onText(regexp, callback);
bot.onText(regexp2, callback);
const textListener = bot.removeTextListener(regexp);
assert.strictEqual(regexp, textListener.regexp);
});
it('returns `null` if missing', function test() {
assert.strictEqual(null, bot.removeTextListener(/404/));
});
});
describe.skip('#onReplyToMessage', function onReplyToMessageSuite() { });
describe('#removeReplyListener', function removeReplyListenerSuite() {
const chatId = -1234;
const messageId = 1;
const callback = function noop() { };
it('returns the right reply-listener', function test() {
const id = bot.onReplyToMessage(chatId, messageId, callback);
const replyListener = bot.removeReplyListener(id);
assert.strictEqual(id, replyListener.id);
assert.strictEqual(chatId, replyListener.chatId);
assert.strictEqual(messageId, replyListener.messageId);
assert.strictEqual(callback, replyListener.callback);
});
it('returns `null` if missing', function test() {
// NOTE: '0' is never a valid reply listener ID :)
assert.strictEqual(null, bot.removeReplyListener(0));
});
});
/** Telegram Bot API Methods */
describe.skip('#logOut', function logOutSuite() { });
describe.skip('#close', function closeSuite() { });
describe('#sendMessage', function sendMessageSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendMessage', this);
});
it('should send a message', function test() {
return bot.sendMessage(USERID, 'test').then(resp => {
assert.ok(is.object(resp));
assert.ok(is.number(resp.message_id));
});
});
});
describe('#forwardMessage', function forwardMessageSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendMessage', this);
utils.handleRatelimit(bot, 'forwardMessage', this);
});
it('should forward a message', function test() {
return bot.sendMessage(USERID, 'test').then(resp => {
const messageId = resp.message_id;
return bot.forwardMessage(USERID, USERID, messageId)
.then(forwarded => {
assert.ok(is.object(forwarded));
assert.ok(is.number(forwarded.message_id));
});
});
});
});
describe('#forwardMessages', function forwardMessagesSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendMessage', this);
utils.handleRatelimit(bot, 'forwardMessages', this);
});
it('should forward multiple messages', function test() {
return Promise.all([
bot.sendMessage(USERID, 'test 1'),
bot.sendMessage(USERID, 'test 2'),
]).then(responses => {
const messageIds = [
responses[0].message_id,
responses[1].message_id,
].sort();
return bot.forwardMessages(GROUPID, USERID, messageIds).then(forwarded => {
assert.ok(is.array(forwarded));
assert.ok(forwarded.length === 2);
});
});
});
});
describe('#copyMessage', function copyMessageSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendMessage', this);
utils.handleRatelimit(bot, 'copyMessage', this);
});
it('should send copy of a message', function test() {
return bot.sendMessage(USERID, 'test').then(resp => {
const messageId = resp.message_id;
return bot.copyMessage(USERID, USERID, messageId)
.then(copy => {
assert.ok(is.object(copy));
assert.ok(is.number(copy.message_id));
});
});
});
});
describe('#sendPhoto', function sendPhotoSuite() {
let photoId;
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'sendPhoto', this);
});
it('should send a photo from file', function test() {
const photo = `${__dirname}/data/photo.png`;
return bot.sendPhoto(USERID, photo).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.photo));
photoId = resp.photo[0].file_id;
});
});
it('should send a photo from id', function test() {
// Send the same photo as before
const photo = photoId;
return bot.sendPhoto(USERID, photo).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.photo));
});
});
it('should send a photo from fs.readStream', function test() {
const photo = fs.createReadStream(`${__dirname}/data/photo.png`);
return bot.sendPhoto(USERID, photo).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.photo));
});
});
it('should send a photo from request Stream', function test() {
const photo = request(`${staticUrl}/photo.png`);
return bot.sendPhoto(USERID, photo).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.photo));
});
});
it('should send a photo from a Buffer', function test() {
const photo = fs.readFileSync(`${__dirname}/data/photo.png`);
return bot.sendPhoto(USERID, photo).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.photo));
});
});
});
describe('#sendAudio', function sendAudioSuite() {
let audioId;
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'sendAudio', this);
});
it('should send an MP3 audio', function test() {
const audio = `${__dirname}/data/audio.mp3`;
return bot.sendAudio(USERID, audio).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.audio));
audioId = resp.audio.file_id;
});
});
it('should send an audio from id', function test() {
// Send the same audio as before
const audio = audioId;
return bot.sendAudio(USERID, audio).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.audio));
});
});
it('should send an audio from fs.readStream', function test() {
const audio = fs.createReadStream(`${__dirname}/data/audio.mp3`);
return bot.sendAudio(USERID, audio).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.audio));
});
});
it('should send an audio from request Stream', function test() {
const audio = request(`${staticUrl}/audio.mp3`);
return bot.sendAudio(USERID, audio).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.audio));
});
});
it('should send an audio from a Buffer', function test() {
const audio = fs.readFileSync(`${__dirname}/data/audio.mp3`);
return bot.sendAudio(USERID, audio).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.audio));
});
});
it('should send an audio file with thumbnail', function test() {
const audio = `${__dirname}/data/audio.mp3`;
const thumbImg = `attach://${__dirname}/data/sticker_thumb.png`;
return bot.sendAudio(USERID, audio, { thumbnail: thumbImg }).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.audio));
assert.ok(is.object(resp.audio.thumbnail));
});
});
});
describe('#sendDocument', function sendDocumentSuite() {
let documentId;
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'sendDocument', this);
});
it('should send a document from file', function test() {
const document = `${__dirname}/data/photo.gif`;
return bot.sendDocument(USERID, document).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.document));
documentId = resp.document.file_id;
});
});
it('should send a document from id', function test() {
// Send the same document as before
const document = documentId;
return bot.sendDocument(USERID, document).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.document));
});
});
it('should send a document from fs.readStream', function test() {
const document = fs.createReadStream(`${__dirname}/data/photo.gif`);
return bot.sendDocument(USERID, document).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.document));
});
});
it('should send a document from request Stream', function test() {
const document = request(`${staticUrl}/photo.gif`);
return bot.sendDocument(USERID, document).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.document));
});
});
it('should send a document from a Buffer', function test() {
const document = fs.readFileSync(`${__dirname}/data/photo.gif`);
return bot.sendDocument(USERID, document).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.document));
});
});
});
describe('#sendVideo', function sendVideoSuite() {
let videoId;
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'sendVideo', this);
});
it('should send a video from file', function test() {
const video = `${__dirname}/data/video.mp4`;
return bot.sendVideo(USERID, video).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
videoId = resp.video.file_id;
});
});
it('should send a video from id', function test() {
// Send the same video as before
return bot.sendVideo(USERID, videoId).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
});
});
it('should send a video from fs.readStream', function test() {
const video = fs.createReadStream(`${__dirname}/data/video.mp4`);
return bot.sendVideo(USERID, video).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
});
});
it('should send a video from request Stream', function test() {
const video = request(`${staticUrl}/video.mp4`);
return bot.sendVideo(USERID, video).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
});
});
it('should send a video from a Buffer', function test() {
const video = fs.readFileSync(`${__dirname}/data/video.mp4`);
return bot.sendVideo(USERID, video).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
});
});
});
describe('#sendAnimation', function sendAnimationSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendAnimation', this);
});
it('should send a gif as an animation', function test() {
return bot.sendAnimation(USERID, `${__dirname}/data/photo.gif`).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.document));
});
});
});
describe('#sendVoice', function sendVoiceSuite() {
let voiceId;
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'sendVoice', this);
});
it('should send a voice from file', function test() {
const voice = `${__dirname}/data/voice.ogg`;
return bot.sendVoice(USERID, voice).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.voice));
voiceId = resp.voice.file_id;
});
});
it('should send a voice from id', function test() {
// Send the same voice as before
return bot.sendVoice(USERID, voiceId).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.voice));
});
});
it('should send a voice from fs.readStream', function test() {
const voice = fs.createReadStream(`${__dirname}/data/voice.ogg`);
return bot.sendVoice(USERID, voice).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.voice));
});
});
it('should send a voice from request Stream', function test() {
const voice = request(`${staticUrl}/voice.ogg`);
return bot.sendVoice(USERID, voice).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.voice));
});
});
it('should send a voice from a Buffer', function test() {
const voice = fs.readFileSync(`${__dirname}/data/voice.ogg`);
return bot.sendVoice(USERID, voice).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.voice));
});
});
});
describe('#sendVideoNote', function sendVideoNoteSuite() {
let videoNoteId;
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'sendVideoNote', this);
});
it('should send a video from file', function test() {
const video = `${__dirname}/data/video.mp4`;
return bot.sendVideoNote(USERID, video, { length: 5 }).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
videoNoteId = resp.video.file_id;
});
});
it('should send a video from id', function test() {
// Send the same videonote as before
assert.ok(videoNoteId);
return bot.sendVideoNote(USERID, videoNoteId, { length: 5 }).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
});
});
it('should send a video from fs.readStream', function test() {
const video = fs.createReadStream(`${__dirname}/data/video.mp4`);
return bot.sendVideoNote(USERID, video, { length: 5 }).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
});
});
it('should send a video from a Buffer', function test() {
const video = fs.readFileSync(`${__dirname}/data/video.mp4`);
return bot.sendVideoNote(USERID, video, { length: 5 }).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.video));
});
});
});
describe('#sendMediaGroup', function sendMediaGroupSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendMediaGroup', this);
});
it('should send group of photos/videos as album', function test() {
return bot.sendMediaGroup(USERID, [
{
type: 'photo',
media: `${__dirname}/data/photo.png`,
},
{
type: 'video',
media: `${__dirname}/data/video.mp4`,
},
{
type: 'photo',
media: FILE_ID,
},
], {
disable_notification: true,
}).then(resp => {
assert.ok(is.array(resp));
assert.strictEqual(resp.length, 3);
});
});
});
describe('#sendLocation', function sendLocationSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendLocation', this);
});
it('should send a location', function test() {
return bot.sendLocation(USERID, lat, long).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.location));
assert.ok(is.number(resp.location.latitude));
assert.ok(is.number(resp.location.longitude));
});
});
});
describe('#editMessageLiveLocation', function editMessageLiveLocationSuite() {
let message;
before(function before() {
utils.handleRatelimit(bot, 'editMessageLiveLocation', this);
const opts = { live_period: 86400 };
return bot.sendLocation(USERID, lat, long, opts).then(resp => { message = resp; });
});
it('edits live location', function test() {
const opts = { chat_id: USERID, message_id: message.message_id };
return bot.editMessageLiveLocation(lat + 1, long + 1, opts).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.location));
assert.ok(is.number(resp.location.latitude));
assert.ok(is.number(resp.location.longitude));
});
});
});
describe.skip('#stopMessageLiveLocation', function editMessageLiveLocationSuite() {
let message;
before(function before() {
utils.handleRatelimit(bot, 'stopMessageLiveLocation', this);
return bot.sendLocation(USERID, lat, long, { live_period: 86400 })
.then((resp) => {
message = resp;
});
});
it('stops location updates', function test() {
const opts = { chat_id: USERID, message_id: message.message_id };
return bot.stopMessageLiveLocation(opts).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.location));
assert.ok(is.number(resp.location.latitude));
assert.ok(is.number(resp.location.longitude));
});
});
});
describe('#sendVenue', function sendVenueSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendVenue', this);
});
it('should send a venue', function test() {
const title = 'The Village Shopping Centre';
const address = '430 Topsail Rd,St. John\'s, NL A1E 4N1, Canada';
return bot.sendVenue(USERID, lat, long, title, address).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.venue));
assert.ok(is.object(resp.venue.location));
assert.ok(is.number(resp.venue.location.latitude));
assert.ok(is.number(resp.venue.location.longitude));
assert.ok(is.string(resp.venue.title));
assert.ok(is.string(resp.venue.address));
});
});
});
// NOTE: We are skipping TelegramBot#sendContact() as the
// corresponding rate-limits enforced by the Telegram servers
// are too strict! During our initial tests, we were required
// to retry after ~72000 secs (1200 mins / 20 hrs).
// We surely can NOT wait for that much time during testing
// (or in most practical cases for that matter!)
describe.skip('#sendContact', function sendContactSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendContact', this);
});
it('should send a contact', function test() {
const phoneNumber = '+1(000)000-000';
const firstName = 'John Doe';
return bot.sendContact(USERID, phoneNumber, firstName).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.contact));
assert.ok(is.string(resp.contact.phone_number));
assert.ok(is.string(resp.contact.first_name));
});
});
});
describe('#sendPoll', function sendPollSuite() {
it('should send a Poll', function test() {
const question = '¿Are you okey?';
const answers = ['Yes', 'No'];
const opts = { is_anonymous: true };
return bot.sendPoll(GROUPID, question, answers, opts).then(resp => {
assert.ok(is.object(resp));
});
});
it('should send a Quiz', function test() {
const question = '¿Are you okey?';
const answers = ['Yes', 'No'];
const opts = {
is_anonymous: true,
type: 'quiz',
correct_option_id: 0
};
return bot.sendPoll(GROUPID, question, answers, opts).then(resp => {
assert.ok(is.object(resp));
});
});
});
describe('#sendDice', function sendDiceSuite() {
it('should send a Dice', function test() {
return bot.sendDice(GROUPID).then(resp => {
assert.ok(is.object(resp));
});
});
it('should send a Dart', function test() {
const opts = { emoji: '🎯' };
return bot.sendDice(GROUPID, opts).then(resp => {
assert.ok(is.object(resp));
});
});
});
describe('#sendMessageDraft', function sendMessageDraftSuite() {
it('should send a Draft', function test() {
const draftId = Date.now();
const text = 'test content';
return bot.sendMessageDraft(GROUPID, draftId, text).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#sendChatAction', function sendChatActionSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendChatAction', this);
});
it('should send a chat action', function test() {
const action = 'typing';
return bot.sendChatAction(USERID, action).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#getUserProfilePhotos', function getUserProfilePhotosSuite() {
const opts = {
offset: 0,
limit: 1,
};
before(function before() {
utils.handleRatelimit(bot, 'getUserProfilePhotos', this);
});
it('should get user profile photos', function test() {
return bot.getUserProfilePhotos(USERID, opts).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.number(resp.total_count));
assert.ok(is.array(resp.photos));
});
});
});
describe.skip('#getUserProfileAudios', function getUserProfileAudiosSuite() { });
describe('#getFile', function getFileSuite() {
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'getFile', this);
});
it('should get a file', function test() {
return bot.getFile(FILE_ID)
.then(resp => {
assert.ok(is.object(resp));
assert.ok(is.string(resp.file_path));
});
});
});
describe.skip('#banChatMember', function banChatMemberSuite() { });
describe.skip('#unbanChatMember', function unbanChatMemberSuite() { });
describe.skip('#restrictChatMember', function restrictChatMemberSuite() { });
describe.skip('#promoteChatMember', function promoteChatMemberSuite() { });
describe.skip('#setChatAdministratorCustomTitle', function setChatAdministratorCustomTitleSuite() {
it('should set chat permissions', function test() {
return bot.setChatAdministratorCustomTitle(GROUPID, USERID, 'Custom Name').then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#setChatMemberTag', function setChatMemberTagSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setChatMemberTag', this);
});
it('should set tag for a chat member', function test() {
return bot.setChatMemberTag(GROUPID, USERID, { tag: 'nodebot' }).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe.skip('#unpinAllGeneralForumTopicMessages', function unpinAllGeneralForumTopicMessagesSuite() {
before(function before() {
utils.handleRatelimit(bot, 'unpinAllGeneralForumTopicMessages', this);
});
it('should unpin all general forum topic messages', function test() {
return bot.unpinAllGeneralForumTopicMessages(GROUPID).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe.skip('#banChatSenderChat', function banChatSenderChatSuite() { });
describe.skip('#unbanChatSenderChat', function banChatSenderChatSuite() { });
describe('#setChatPermissions ', function setChatPermissionsSuite() {
it('should set chat permissions', function test() {
const ChatPermissions = {
can_send_messages: true,
can_send_media_messages: true,
can_send_polls: false,
can_send_other_messages: false,
can_add_web_page_previews: true,
can_change_info: false,
can_invite_users: false,
can_pin_messages: true
};
return bot.setChatPermissions(GROUPID, ChatPermissions).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#exportChatInviteLink', function exportChatInviteLinkSuite() {
before(function before() {
utils.handleRatelimit(bot, 'exportChatInviteLink', this);
});
it('should export the group invite link', function test() {
return bot.exportChatInviteLink(GROUPID).then(resp => {
assert(resp.match(/^https:\/\/t\.me\/.+$/i), 'is a telegram invite link');
});
});
});
describe('#createChatInviteLink', function createChatInviteLinkSuite() {
let inviteLink;
before(function before() {
utils.handleRatelimit(bot, 'createChatInviteLink', this);
utils.handleRatelimit(bot, 'editChatInviteLink', this);
utils.handleRatelimit(bot, 'revokeChatInviteLink', this);
});
it('should create a chat invite link', function test() {
return bot.createChatInviteLink(GROUPID).then(resp => {
assert(resp.invite_link.match(/^https:\/\/t\.me\/.+$/i), 'is a telegram invite link');
inviteLink = resp.invite_link;
});
});
it('should edit chat invite link', function test() {
return bot.editChatInviteLink(GROUPID, inviteLink, { member_limit: 3 }).then(resp => {
assert.strictEqual(resp.member_limit, 3);
});
});
it('should revoke chat invite link', function test() {
return bot.revokeChatInviteLink(GROUPID, inviteLink).then(resp => {
assert.strictEqual(resp.is_revoked, true);
});
});
});
describe.skip('#approveChatJoinRequest', function approveChatJoinRequestSuite() { });
describe.skip('#declineChatJoinRequest', function declineChatJoinRequestSuite() { });
describe('#setChatPhoto', function setChatPhotoSuite() {
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'setChatPhoto', this);
});
it('should set a chat photo from file', function test() {
const photo = `${__dirname}/data/chat_photo.png`;
return bot.setChatPhoto(GROUPID, photo).then(resp => {
assert.strictEqual(resp, true);
});
});
it('should set a chat photo from fs.readStream', function test() {
const photo = fs.createReadStream(`${__dirname}/data/chat_photo.png`);
return bot.setChatPhoto(GROUPID, photo).then(resp => {
assert.strictEqual(resp, true);
});
});
it('should set a chat photo from request Stream', function test() {
const photo = request(`${staticUrl}/chat_photo.png`);
return bot.setChatPhoto(GROUPID, photo).then(resp => {
assert.strictEqual(resp, true);
});
});
it('should set a chat photo from a Buffer', function test() {
const photo = fs.readFileSync(`${__dirname}/data/chat_photo.png`);
return bot.setChatPhoto(GROUPID, photo).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#deleteChatPhoto', function deleteChatPhotoSuite() {
before(function before() {
utils.handleRatelimit(bot, 'deleteChatPhoto', this);
});
it('should delete the chat photo', function test() {
return bot.deleteChatPhoto(GROUPID).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#setChatTitle', function setChatTitleSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setChatTitle', this);
});
it('should set the chat title', function test() {
const random = Math.floor(Math.random() * 1000);
return bot.setChatTitle(GROUPID, `ntba test group (random: ${random})`).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#setChatDescription', function setChatDescriptionSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setChatDescription', this);
});
it('should set the chat description', function test() {
const random = Math.floor(Math.random() * 1000);
const description = `node-telegram-bot-api test group (random: ${random})`;
return bot.setChatDescription(GROUPID, description).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#pinChatMessage', function pinChatMessageSuite() {
let messageId;
before(function before() {
utils.handleRatelimit(bot, 'pinChatMessage', this);
return bot.sendMessage(GROUPID, 'To be pinned').then(resp => {
messageId = resp.message_id;
});
});
it('should pin chat message', function test() {
return bot.pinChatMessage(GROUPID, messageId).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#unpinChatMessage', function unpinChatMessageSuite() {
before(function before() {
utils.handleRatelimit(bot, 'unpinChatMessage', this);
});
it('should unpin chat message', function test() {
return bot.unpinChatMessage(GROUPID).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#unpinAllChatMessages', function unpinAllChatMessagesSuite() {
before(function before() {
utils.handleRatelimit(bot, 'unpinAllChatMessages', this);
});
it('should unpin all chats messages', function test() {
return bot.unpinAllChatMessages(GROUPID).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe.skip('#leaveChat', function leaveChatSuite() { });
describe('#getChat', function getChatSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getChat', this);
});
it('should return a Chat object', function test() {
return bot.getChat(USERID).then(resp => {
assert.ok(is.object(resp));
});
});
});
describe('#getChatAdministrators', function getChatAdministratorsSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getChatAdministrators', this);
});
it('should return an Array', function test() {
return bot.getChatAdministrators(GROUPID).then(resp => {
assert.ok(Array.isArray(resp));
});
});
});
describe('#getChatMemberCount', function getChatMemberCountSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getChatMemberCount', this);
});
it('should return an Integer', function test() {
return bot.getChatMemberCount(GROUPID).then(resp => {
assert.ok(Number.isInteger(resp));
});
});
});
describe('#getChatMember', function getChatMemberSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getChatMember', this);
});
it('should return a ChatMember', function test() {
return bot.getChatMember(GROUPID, USERID).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.user));
assert.ok(is.string(resp.status));
});
});
});
describe('#setChatStickerSet', function setChatStickerSetSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setChatStickerSet', this);
// Check if the chat can set sticker sets
if (!CHAT_INFO.can_set_sticker_set) {
this.skip();
}
});
it('should return a Boolean', function test() {
return bot.setChatStickerSet(GROUPID, STICKER_SET_NAME).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#deleteChatStickerSet', function deleteChatStickerSetSuite() {
before(function before() {
utils.handleRatelimit(bot, 'deleteChatStickerSet', this);
// Check if the chat can delete sticker sets
if (!CHAT_INFO.can_set_sticker_set) {
this.skip();
}
});
it('should return a Boolean', function test() {
return bot.deleteChatStickerSet(GROUPID).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe.skip('#answerCallbackQuery', function answerCallbackQuerySuite() { });
describe('#setMyCommands', function setMyCommandsSuite() {
it('should set bot commands', function test() {
const opts = [
{ command: 'eat', description: 'Command for eat' },
{ command: 'run', description: 'Command for run' }
];
return bot.setMyCommands(opts).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#deleteMyCommands', function deleteMyCommandsSuite() {
it('should delete bot commands', function test() {
return bot.deleteMyCommands().then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#setMyDescription', function getMyCommandsSuite() {
it('should set bot description for users with a specific lang code', function test() {
return bot.setMyDescription({ description: 'Bot description' }).then(resp => {
assert.ok(is.boolean(resp));
});
});
it('should set bot description for Spanish users', function test() {
return bot.setMyDescription({ description: 'Spanish bot description', language_code: 'es' }).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#setMyName', function setMyNameSuite() {
it('should set bot name for Spanish users', function test() {
return bot.setMyName({ name: 'Spanish Bot', language_code: 'es' }).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#getMyName', function setMyNameSuite() {
it('should get bot name for Spanish users', function test() {
return bot.getMyName({ language_code: 'es' }).then(resp => {
assert.ok(is.equal(resp.name, 'Spanish Bot'));
});
});
});
describe('#getMyDescription', function getMyDescriptionSuite() {
it('should get bot description for a user without lang code', function test() {
return bot.getMyDescription().then(resp => {
assert.ok(is.equal(resp.description, 'Bot description'));
});
});
it('should get bot description for Spanish users', function test() {
return bot.getMyDescription({ language_code: 'es' }).then(resp => {
assert.ok(is.equal(resp.description, 'Spanish bot description'));
});
});
});
describe('#setMyShortDescription', function setMyShortDescriptionSuite() {
it('should set sort bot description for a user without lang code', function test() {
return bot.setMyShortDescription({ short_description: 'Bot sort description' }).then(resp => {
assert.ok(is.boolean(resp));
});
});
it('should set sort description for Spanish users', function test() {
return bot.setMyShortDescription({ short_description: 'Spanish bot sort description', language_code: 'es' }).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#getMyShortDescription', function getMyShortDescriptionSuite() {
it('should get bot sort description for a user without lang code', function test() {
return bot.getMyShortDescription().then(resp => {
assert.ok(is.equal(resp.short_description, 'Bot sort description'));
});
});
it('should get bot sort description for Spanish users', function test() {
return bot.getMyShortDescription({ language_code: 'es' }).then(resp => {
assert.ok(is.equal(resp.short_description, 'Spanish bot sort description'));
});
});
});
describe('#setMyProfilePhoto', function setMyProfilePhotoSuite() {
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'setMyProfilePhoto', this);
});
it('should set bot profile photo from file', function test() {
const photo = `${__dirname}/data/chat_photo.png`;
return bot.setMyProfilePhoto(photo).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#removeMyProfilePhoto', function removeMyProfilePhotoSuite() {
before(function before() {
utils.handleRatelimit(bot, 'removeMyProfilePhoto', this);
});
it('should remove bot profile photo', function test() {
return bot.removeMyProfilePhoto().then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#getMyCommands', function getMyCommandsSuite() {
it('should get bot commands', function test() {
return bot.getMyCommands().then(resp => {
assert.ok(is.array(resp));
});
});
});
describe('#setChatMenuButton', function setChatMenuButtonSuite() {
it('should set chat menu button', function test() {
return bot.setChatMenuButton({
chat_id: USERID,
menu_button: JSON.stringify({ type: 'web_app', text: 'Hello', web_app: { url: 'https://webappcontent.telegram.org/cafe' } }),
})
.then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#getChatMenuButton', function getChatMenuButtonSuite() {
it('should get chat menu button', function test() {
return bot.getChatMenuButton({ chat_id: USERID }).then(resp => {
assert.ok(is.equal(resp, {
type: 'web_app',
text: 'Hello',
web_app: { url: 'https://webappcontent.telegram.org/cafe' }
}));
});
});
});
describe('#setMyDefaultAdministratorRights', function setMyDefaultAdministratorRightsSuite() {
it('should set default administrator rights', function test() {
return bot.setMyDefaultAdministratorRights({
rights: JSON.stringify({
can_manage_chat: true,
can_change_info: true,
can_delete_messages: false,
can_invite_users: true,
can_restrict_members: false,
can_pin_messages: true,
can_promote_members: false,
can_manage_video_chats: false,
is_anonymous: false
}),
for_channels: false
}).then(resp => {
assert.ok(is.boolean(resp));
});
});
});
describe('#getMyDefaultAdministratorRights', function getMyDefaultAdministratorRightsSuite() {
it('should get my default administrator rights', function test() {
return bot.getMyDefaultAdministratorRights({
for_channels: false
}).then(resp => {
assert.ok(is.equal(resp, {
can_manage_chat: true,
can_change_info: true,
can_delete_messages: false,
can_invite_users: true,
can_restrict_members: false,
can_pin_messages: true,
can_manage_topics: false,
can_promote_members: false,
can_manage_video_chats: false,
can_post_stories: false,
can_edit_stories: false,
can_delete_stories: false,
is_anonymous: false
}));
});
});
});
describe('#editMessageText', function editMessageTextSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendMessage', this);
utils.handleRatelimit(bot, 'editMessageText', this);
});
it('should edit a message sent by the bot', function test() {
return bot.sendMessage(USERID, 'test').then(resp => {
assert.strictEqual(resp.text, 'test');
const opts = {
chat_id: USERID,
message_id: resp.message_id
};
return bot.editMessageText('edit test', opts).then(msg => {
assert.strictEqual(msg.text, 'edit test');
});
});
});
});
describe('#editMessageCaption', function editMessageCaptionSuite() {
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'sendPhoto', this);
utils.handleRatelimit(bot, 'editMessageCaption', this);
});
it('should edit a caption sent by the bot', function test() {
const photo = `${__dirname}/data/photo.png`;
const options = { caption: 'test caption' };
return bot.sendPhoto(USERID, photo, options).then(resp => {
assert.strictEqual(resp.caption, 'test caption');
const opts = {
chat_id: USERID,
message_id: resp.message_id
};
return bot.editMessageCaption('new test caption', opts).then(msg => {
assert.strictEqual(msg.caption, 'new test caption');
});
});
});
});
describe('#editMessageMedia', function editMessageMediaSuite() {
let photoId;
let messageID;
before(function before() {
utils.handleRatelimit(bot, 'editMessageMedia', this);
const photo = `${__dirname}/data/photo.png`;
return bot.sendPhoto(USERID, photo).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.photo));
photoId = resp.photo[0].file_id;
messageID = resp.message_id;
});
});
it('should edit a media message', function nextTest() {
return bot.editMessageMedia({ type: 'photo', media: photoId, caption: 'edited' }, { chat_id: USERID, message_id: messageID }).then(editedResp => {
assert.ok(is.object(editedResp));
assert.ok(is.string(editedResp.caption));
});
});
});
describe('#editMessageReplyMarkup', function editMessageReplyMarkupSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendMessage', this);
utils.handleRatelimit(bot, 'editMessageReplyMarkup', this);
});
it('should edit previously-set reply markup', function test() {
return bot.sendMessage(USERID, 'test').then(resp => {
const replyMarkup = JSON.stringify({
inline_keyboard: [[{
text: 'Test button',
callback_data: 'test'
}]]
});
const opts = {
chat_id: USERID,
message_id: resp.message_id
};
return bot.editMessageReplyMarkup(replyMarkup, opts).then(msg => {
// Keyboard markup is not returned, do a simple object check
assert.ok(is.object(msg));
});
});
});
});
describe('#stopPoll', function stopPollSuite() {
let msg;
before(function before() {
utils.handleRatelimit(bot, 'stopPoll', this);
return bot.sendPoll(GROUPID, '¿Poll for stop before?', ['Yes', 'No']).then(resp => {
msg = resp;
});
});
it('should stop a Poll', function test() {
return bot.stopPoll(GROUPID, msg.message_id).then(resp => {
assert.ok(is.boolean(resp.is_closed) && resp.is_closed === true);
});
}
);
});
describe.skip('#approveSuggestedPost', function approveSuggestedPostSuite() { });
describe.skip('#declineSuggestedPost', function declineSuggestedPostSuite() { });
describe('#deleteMessage', function deleteMessageSuite() {
let messageId;
before(function before() {
utils.handleRatelimit(bot, 'deleteMessage', this);
return bot.sendMessage(USERID, 'To be deleted').then(resp => {
messageId = resp.message_id;
});
});
it('should delete message', function test() {
return bot.deleteMessage(USERID, messageId).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#sendSticker', function sendStickerSuite() {
let stickerId;
this.timeout(timeout);
before(function before() {
utils.handleRatelimit(bot, 'sendSticker', this);
});
it('should send a sticker from file', function test() {
const sticker = `${__dirname}/data/sticker.webp`;
return bot.sendSticker(USERID, sticker).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.sticker));
stickerId = resp.sticker.file_id;
});
});
it('should send a sticker from id', function test() {
// Send the same photo as before
return bot.sendSticker(USERID, stickerId).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.sticker));
});
});
it('should send a sticker from fs.readStream', function test() {
const sticker = fs.createReadStream(`${__dirname}/data/sticker.webp`);
return bot.sendSticker(USERID, sticker).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.sticker));
});
});
it('should send a sticker from request Stream', function test() {
const sticker = request(`${staticUrl}/sticker.webp`);
return bot.sendSticker(USERID, sticker).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.sticker));
});
});
it('should send a sticker from a Buffer', function test() {
const sticker = fs.readFileSync(`${__dirname}/data/sticker.webp`);
return bot.sendSticker(USERID, sticker).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.sticker));
});
});
});
describe('#uploadStickerFile', function sendPhotoSuite() {
before(function before() {
utils.handleRatelimit(bot, 'uploadStickerFile', this);
});
it('should upload a sticker from file', function test() {
const sticker = `${__dirname}/data/sticker.png`;
bot.uploadStickerFile(USERID, sticker).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.string(resp.file_id));
});
});
// Other tests (eg. Buffer, URL) are skipped, because they rely on the same features as sendPhoto.
});
describe('#createNewStickerSet', function createNewStickerSetSuite() {
before(function before() {
utils.handleRatelimit(bot, 'createNewStickerSet', this);
});
it('should create a new sticker set', function test(done) {
const sticker = `${__dirname}/data/sticker.png`;
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
bot.createNewStickerSet(USERID, stickerPackName, 'Sticker Pack Title', sticker, '😍').then((resp) => {
assert.ok(is.boolean(resp));
});
setTimeout(() => done(), 2000);
});
});
describe('#getStickerSet', function getStickerSetSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getStickerSet', this);
});
it('should get the sticker set given the name of the set', function test() {
return bot.getStickerSet(STICKER_SET_NAME).then(resp => {
assert.ok(is.object(resp));
assert.strictEqual(resp.name.toLowerCase(), STICKER_SET_NAME);
assert.ok(is.string(resp.title));
assert.ok(is.string(resp.sticker_type));
assert.ok(is.array(resp.stickers));
});
});
// This test depends on the previous test createNewStickerSet
it('should get the recent sticker set created given the name of the set', function test() {
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
return bot.getStickerSet(stickerPackName).then(resp => {
STICKER_FILE_ID_FROM_SET = resp.stickers[0].file_id;
assert.ok(is.object(resp));
assert.strictEqual(resp.name.toLowerCase(), stickerPackName.toLowerCase());
assert.ok(is.string(resp.title));
assert.ok(is.string(resp.sticker_type));
assert.ok(is.array(resp.stickers));
});
});
});
describe('#getCustomEmojiStickers', function getCustomEmojiStickersSuite() {
const CHERRY_EMOJI_STICKERS_ID = ['5380109565226391871', '5431711346724968789'];
const STICKER_EMOJI_SET_NAME = 'CherryEmoji';
it('should get the custom emoji stickers', function test() {
return bot.getCustomEmojiStickers([CHERRY_EMOJI_STICKERS_ID[0]]).then(resp => {
assert.ok(is.array(resp));
assert.ok(is.object(resp[0]));
assert.ok(is.string(resp[0].set_name) && resp[0].set_name === STICKER_EMOJI_SET_NAME);
assert.ok(resp[0].custom_emoji_id === CHERRY_EMOJI_STICKERS_ID[0]);
});
});
it('should get 2 custom emoji stickers', function test() {
return bot.getCustomEmojiStickers(CHERRY_EMOJI_STICKERS_ID).then(resp => {
assert.ok(is.array(resp) && resp.length === 2);
assert.ok(is.object(resp[1]));
assert.ok(is.string(resp[1].set_name) && resp[1].set_name === STICKER_EMOJI_SET_NAME);
assert.ok(resp[1].custom_emoji_id === CHERRY_EMOJI_STICKERS_ID[1]);
});
});
});
describe('#addStickerToSet', function addStickerToSetSuite() {
before(function before() {
utils.handleRatelimit(bot, 'addStickerToSet', this);
});
it('should add a sticker to a set', function test() {
const sticker = `${__dirname}/data/sticker.png`;
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
bot.addStickerToSet(USERID, stickerPackName, sticker, '😊😍🤔', 'png_sticker').then((resp) => {
assert.ok(is.boolean(resp));
});
});
it('should add a sticker to a set using the file Id', function test(done) {
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
bot.addStickerToSet(USERID, stickerPackName, STICKER_FILE_ID_FROM_SET, '😊🤔', 'png_sticker').then((resp) => {
assert.ok(is.boolean(resp));
});
setTimeout(() => done(), 2000);
});
});
describe('#setStickerPositionInSet', function setStickerPositionInSet() {
before(function before() {
utils.handleRatelimit(bot, 'setStickerPositionInSet', this);
});
it('should set the position of a sticker in a set', function test() {
bot.setStickerPositionInSet(STICKER_FILE_ID_FROM_SET, 0).then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe('#deleteStickerFromSet', function deleteStickerFromSetSuite() {
before(function before() {
utils.handleRatelimit(bot, 'deleteStickerFromSet', this);
});
it('should delete a sticker from a set', function test() {
bot.deleteStickerFromSet(STICKER_FILE_ID_FROM_SET).then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe('#setStickerEmojiList', function setStickerEmojiListSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setStickerEmojiList', this);
});
it('should get the list for the given sticker of the bot sticker pack', function test(done) {
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
bot.getStickerSet(stickerPackName).then(resp => {
STICKERS_FROM_BOT_SET = resp.stickers;
assert.ok(is.array(STICKERS_FROM_BOT_SET));
});
setTimeout(() => done(), 2000);
});
it('should set a emoji list for the given sticker', function test() {
assert.ok(is.equal(STICKERS_FROM_BOT_SET[0].type, 'regular'));
bot.setStickerEmojiList(STICKERS_FROM_BOT_SET[0].file_id, ['🥳', '😀', '😇']).then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe('#setStickerKeywords', function setStickerKeywordsSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setStickerKeywords', this);
});
it('should set a keywords list for the given sticker', function test() {
assert.ok(is.equal(STICKERS_FROM_BOT_SET[0].type, 'regular'));
bot.setStickerKeywords(STICKERS_FROM_BOT_SET[0].file_id, { keywords: ['house', 'cat'] }).then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe.skip('#setStickerMaskPosition', function setStickerKeywordsSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setStickerMaskPosition', this);
});
it('should delete a sticker from a set', function test() {
bot.setStickerMaskPosition(STICKER_FILE_ID_FROM_SET, { point: 'eyes', scale: 2, x_shift: 1, y_shift: 1 }).then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe('#setStickerSetTitle', function setStickerSetTitleSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setStickerSetTitle', this);
});
it('should set a new sticker set title', function test() {
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
bot.setStickerSetTitle(stickerPackName, 'New title').then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe('#setStickerSetThumbnail', function setStickerSetThumbnailSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setStickerSetThumbnail', this);
});
it('should set a sticker set thumbnail', function test() {
const stickerThumb = `${__dirname}/data/sticker_thumb.png`;
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
bot.setStickerSetThumbnail(USERID, stickerPackName, stickerThumb).then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe.skip('#setCustomEmojiStickerSetThumbnail', function setCustomEmojiStickerSetThumbnailSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setCustomEmojiStickerSetThumbnail', this);
});
it('should set a custom emoji sticjer set as thumbnail', function test() {
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
bot.setCustomEmojiStickerSetThumbnail(stickerPackName, { custom_emoji_id: null }).then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe.skip('#deleteStickerSet', function deleteStickerSetSuite() {
before(function before() {
utils.handleRatelimit(bot, 'deleteStickerSet', this);
});
it('should delete sticker set', function test() {
const stickerPackName = `s${CURRENT_TIMESTAMP}_by_${BOT_USERNAME}`;
bot.deleteStickerSet(stickerPackName).then((resp) => {
assert.ok(is.boolean(resp));
});
});
});
describe.skip('#answerInlineQuery', function answerInlineQuerySuite() { });
describe.skip('#answerWebAppQuery', function answerCallbackQuerySuite() { });
describe('#sendInvoice', function sendInvoiceSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendInvoice', this);
});
it('should send an invoice', function test() {
if (isCI) {
this.skip(); // Skip test for now
}
const title = 'Demo product';
const description = 'our test product';
const payload = 'sku-p001';
const providerToken = PROVIDER_TOKEN;
const currency = 'USD';
const prices = [{ label: 'product', amount: 11000 }, { label: 'tax', amount: 11000 }];
return bot.sendInvoice(USERID, title, description, payload, providerToken, currency, prices).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.invoice));
assert.ok(is.number(resp.invoice.total_amount));
});
});
});
describe('#createInvoiceLink', function createInvoiceLinkSuite() {
before(function before() {
utils.handleRatelimit(bot, 'createInvoiceLink', this);
});
it('should create an invoice link', function test() {
if (isCI) {
this.skip(); // Skip test for now
}
const title = 'Invoice link product';
const description = 'Our test invoice link product';
const payload = 'sku-p002';
const providerToken = PROVIDER_TOKEN;
const currency = 'EUR';
const prices = [{ label: 'NTBA API', amount: 12000 }, { label: 'tax', amount: 10000 }];
return bot.createInvoiceLink(title, description, payload, providerToken, currency, prices).then(resp => {
assert.ok(is.string(resp));
});
});
});
describe.skip('#answerShippingQuery', function answerShippingQuerySuite() { });
describe.skip('#answerPreCheckoutQuery', function answerPreCheckoutQuerySuite() { });
describe('#sendGame', function sendGameSuite() {
before(function before() {
utils.handleRatelimit(bot, 'sendGame', this);
});
it('should send a Game', function test() {
return bot.sendGame(USERID, GAME_SHORT_NAME).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.object(resp.game));
});
});
});
describe('#setGameScore', function setGameScoreSuite() {
before(function before() {
utils.handleRatelimit(bot, 'setGameScore', this);
});
it('should set GameScore', function test() {
const score = Math.floor(Math.random() * 1000);
const opts = {
chat_id: GAME_CHAT_ID,
message_id: GAME_MSG_ID,
force: true
};
return bot.setGameScore(USERID, score, opts).then(resp => {
assert.ok(is.object(resp) || is.boolean(resp));
});
});
});
describe('#getGameHighScores', function getGameHighScoresSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getGameHighScores', this);
});
it('should get GameHighScores', function test() {
const opts = {
chat_id: GAME_CHAT_ID,
message_id: GAME_MSG_ID,
};
return bot.getGameHighScores(USERID, opts).then(resp => {
assert.ok(is.array(resp));
});
});
});
describe('#setMessageReaction', function setMessageReactionSuite() {
let messageId;
const Reactions = [{ type: 'emoji', emoji: '👍' }];
before(function before() {
utils.handleRatelimit(bot, 'setMessageReaction', this);
return bot.sendMessage(USERID, 'To be reacted').then(resp => {
messageId = resp.message_id;
});
});
it('should add reactions to message', function test() {
return bot.setMessageReaction(USERID, messageId, { reaction: Reactions, is_big: true }).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#deleteMessages', function setMessageReactionSuite() {
let messageId;
before(function before() {
utils.handleRatelimit(bot, 'deleteMessages', this);
return bot.sendMessage(USERID, 'To be deleted').then(resp => {
messageId = resp.message_id;
});
});
it('should delete message from array', function test() {
return bot.deleteMessages(USERID, [messageId]).then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe('#copyMessages', function setMessageReactionSuite() {
let messageId;
before(function before() {
utils.handleRatelimit(bot, 'copyMessages', this);
return bot.sendMessage(GROUPID, 'To be copyed').then(resp => {
messageId = resp.message_id;
});
});
it('should copy messages from array', function test() {
return bot.copyMessages(USERID, GROUPID, [messageId]).then(resp => {
assert.ok(is.array(resp));
assert.ok(resp && resp.length === 1);
});
});
});
describe('#getUserGifts', function getUserGiftsSuite() {
before(function before() {
utils.handleRatelimit(bot, 'getUserGifts', this);
});
it('should return an OwnedGifts object', function test() {
return bot.getUserGifts(USERID).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.gifts));
assert.ok(is.number(resp.total_count));
});
});
it('should support pagination options', function test() {
return bot.getUserGifts(USERID, { limit: 10, offset: '' }).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.gifts));
});
});
});
describe.skip('#getChatGifts', function getChatGiftsSuite() {
// Requires can_view_gifts_and_stars administrator right for channels
it('should return an OwnedGifts object for a channel', function test() {
return bot.getChatGifts(GROUPID).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.array(resp.gifts));
assert.ok(is.number(resp.total_count));
});
});
});
describe.skip('#sendMessageDraft', function sendMessageDraftSuite() {
// Requires special bot permissions; available to all bots since Bot API 9.5
it('should send a message draft', function test() {
return bot.sendMessageDraft(USERID, 1, 'Draft text...').then(resp => {
assert.strictEqual(resp, true);
});
});
it('should update an existing draft with the same draft_id', function test() {
return bot.sendMessageDraft(USERID, 1, 'Updated draft text.').then(resp => {
assert.strictEqual(resp, true);
});
});
});
describe.skip('#repostStory', function repostStorySuite() {
// Requires two managed business accounts and a story posted by the bot
it('should repost a story to another business account', function test() {
const businessConnectionId = process.env.TEST_BUSINESS_CONNECTION_ID;
const fromChatId = process.env.TEST_STORY_CHAT_ID;
const fromStoryId = parseInt(process.env.TEST_STORY_ID, 10);
const activePeriod = 86400;
return bot.repostStory(businessConnectionId, fromChatId, fromStoryId, activePeriod).then(resp => {
assert.ok(is.object(resp));
assert.ok(is.number(resp.id));
});
});
});
}); // End Telegram
================================================
FILE: test/test.format-send-data.js
================================================
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const TelegramBot = require('..');
const paths = {
audio: path.join(__dirname, 'data/audio.mp3'),
};
describe('#_formatSendData', function sendfileSuite() {
const bot = new TelegramBot('token');
const type = 'file';
before(function beforeSuite() {
process.env.NTBA_FIX_350 = 1;
});
after(function afterSuite() {
delete process.env.NTBA_FIX_350;
});
describe('using fileOptions', function sendfileOptionsSuite() {
const stream = fs.createReadStream(paths.audio);
const nonPathStream = fs.createReadStream(paths.audio);
const buffer = fs.readFileSync(paths.audio);
const nonDetectableBuffer = fs.readFileSync(__filename);
const filepath = paths.audio;
const files = [stream, nonPathStream, buffer, nonDetectableBuffer, filepath];
delete nonPathStream.path;
describe('filename', function filenameSuite() {
it('(1) fileOptions.filename', function test() {
const filename = 'custom-filename';
files.forEach((file) => {
const [{ [type]: data }] = bot._formatSendData(type, file, { filename });
assert.equal(data.options.filename, filename);
});
});
it('(2) Stream#path', function test() {
if (!stream.path) {
this.skip('Stream#path unsupported');
return;
}
const [{ [type]: data }] = bot._formatSendData(type, stream);
assert.equal(data.options.filename, path.basename(paths.audio));
});
it('(3) filepath', function test() {
const [{ [type]: data }] = bot._formatSendData(type, filepath);
assert.equal(data.options.filename, path.basename(paths.audio));
});
it('(4) final default', function test() {
[nonPathStream, buffer, nonDetectableBuffer].forEach((file) => {
const [{ [type]: data }] = bot._formatSendData(type, file);
assert.equal(data.options.filename, 'filename');
});
});
});
describe('contentType', function contentTypeSuite() {
it('(1) fileOpts.contentType', function test() {
const contentType = 'application/custom-type';
files.forEach((file) => {
const [{ [type]: data }] = bot._formatSendData(type, file, { contentType });
assert.equal(data.options.contentType, contentType);
});
});
it('(2) Stream#path', function test() {
if (!stream.path) {
this.skip('Stream#path unsupported');
return;
}
const [{ [type]: data }] = bot._formatSendData(type, stream);
assert.equal(data.options.contentType, 'audio/mpeg');
});
it('(3) Buffer file-type', function test() {
const [{ [type]: data }] = bot._formatSendData(type, buffer);
assert.equal(data.options.contentType, 'audio/mpeg');
});
it('(4) filepath', function test() {
const [{ [type]: data }] = bot._formatSendData(type, filepath);
assert.equal(data.options.contentType, 'audio/mpeg');
});
it('(5) fileOptions.filename', function test() {
[nonPathStream, nonDetectableBuffer].forEach((file) => {
const [{ [type]: data }] = bot._formatSendData(type, file, {
filename: 'image.gif',
});
assert.equal(data.options.contentType, 'image/gif');
});
});
it('(6) Final default', function test() {
[nonPathStream, nonDetectableBuffer].forEach((file) => {
const [{ [type]: data }] = bot._formatSendData(type, file);
assert.equal(data.options.contentType, 'application/octet-stream');
});
});
});
});
it('should handle buffer path from fs.readStream', function test() {
let file;
try {
file = fs.createReadStream(Buffer.from(paths.audio));
} catch (ex) {
// Older Node.js versions do not support passing a Buffer
// representation of the path to fs.createReadStream()
if (ex instanceof TypeError) {
Promise.resolve();
return;
}
}
const [{ [type]: data }] = bot._formatSendData('file', file);
assert.equal(data.options.filename, path.basename(paths.audio));
});
it('should not accept file-paths if disallowed with constructor option', function test() {
const tgbot = new TelegramBot('token', { filepath: false });
const [formData, fileId] = tgbot._formatSendData('file', paths.audio);
assert.ok(fileId);
assert.ok(!formData);
});
it('should allow stream.path that can not be parsed', function test() {
const stream = fs.createReadStream(paths.audio);
stream.path = '/?id=123'; // for example, 'http://example.com/?id=666'
assert.doesNotThrow(function assertDoesNotThrow() {
bot._formatSendData('file', stream);
});
});
});
================================================
FILE: test/utils.js
================================================
/* eslint-disable no-use-before-define */
exports = module.exports = {
/**
* Clear polling check, so that 'isPollingMockServer()' returns false
* if the bot stopped polling the mock server.
* @param {Number} port
*/
clearPollingCheck,
/**
* Redefine a bot method to allow us to ignore 429 (rate-limit) errors
* @param {TelegramBot} bot
* @param {String} methodName
* @param {Suite} suite From mocha
* @return {TelegramBot}
*/
handleRatelimit,
/**
* Return true if a webhook has been opened at the specified port.
* Otherwise throw an error.
* @param {Number} port
* @param {Boolean} [reverse] Throw error when it should have returned true (and vice versa)
* @return {Promise}
*/
hasOpenWebHook,
/**
* Return true if the mock server is being polled by a bot.
* Otherwise throw an error.
* @param {Number} port
* @param {Boolean} [reverse] Throw error when it should have returned true (and vice versa)
* @return {Promise}
*/
isPollingMockServer,
/**
* Return true if the string is a URI to a file
* on Telegram servers.
* @param {String} uri
* @return {Boolean}
*/
isTelegramFileURI,
/**
* Send a message to the webhook at the specified port and path.
* @param {Number} port
* @param {String} path
* @param {Object} [options]
* @param {String} [options.method=POST] Method to use
* @param {Object} [options.update] Update object to send.
* @param {Object} [options.message] Message to send. Default to a generic text message
* @param {Boolean} [options.https=false] Use https
* @return {Promise}
*/
sendWebHookRequest,
/**
* Send a message to the webhook at the specified port.
* @param {Number} port
* @param {String} token
* @param {Object} [options]
* @param {String} [options.method=POST] Method to use
* @param {Object} [options.update] Update object to send.
* @param {Object} [options.message] Message to send. Default to a generic text message
* @param {Boolean} [options.https=false] Use https
* @return {Promise}
*/
sendWebHookMessage,
/**
* Start a mock server at the specified port.
* @param {Number} port
* @param {Object} [options]
* @param {Boolean} [options.bad=false] Bad Mock Server; responding with
* unparseable messages
* @return {Promise}
*/
startMockServer,
/**
* Start the static server, serving files in './data'
* @param {Number} port
*/
startStaticServer,
};
/* eslint-enable no-use-before-define */
const assert = require('assert');
const http = require('http');
const request = require('@cypress/request-promise');
const statics = require('node-static');
const servers = {};
function startMockServer(port, options = {}) {
assert.ok(port);
const server = http.Server((req, res) => {
servers[port].polling = true;
if (options.bad) {
return res.end('can not be parsed with JSON.parse()');
}
return res.end(JSON.stringify({
ok: true,
result: [{
update_id: 0,
message: { text: 'test' },
}],
}));
});
return new Promise((resolve, reject) => {
servers[port] = { server, polling: false };
server.on('error', reject).listen(port, resolve);
});
}
function startStaticServer(port) {
const fileServer = new statics.Server(`${__dirname}/data`);
http.Server((req, res) => {
req.addListener('end', () => {
fileServer.serve(req, res);
}).resume();
}).listen(port);
}
function isPollingMockServer(port, reverse) {
assert.ok(port);
return new Promise((resolve, reject) => {
// process.nextTick() does not wait until a poll request
// is complete!
setTimeout(() => {
let polling = servers[port] && servers[port].polling;
if (reverse) polling = !polling;
if (polling) return resolve(true);
return reject(new Error('polling-check failed'));
}, 1000);
});
}
function clearPollingCheck(port) {
assert.ok(port);
if (servers[port]) servers[port].polling = false;
}
function hasOpenWebHook(port, reverse) {
assert.ok(port);
const error = new Error('open-webhook-check failed');
let connected = false;
return request.get(`http://127.0.0.1:${port}`)
.then(() => {
connected = true;
}).catch(e => {
if (e.statusCode < 500) connected = true;
}).finally(() => {
if (reverse) {
if (connected) throw error;
return;
}
if (!connected) throw error;
});
}
function sendWebHookRequest(port, path, options = {}) {
assert.ok(port);
assert.ok(path);
const protocol = options.https ? 'https' : 'http';
const url = `${protocol}://127.0.0.1:${port}${path}`;
return request({
url,
method: options.method || 'POST',
body: options.update || {
update_id: 1,
message: options.message || { text: 'test' }
},
json: (typeof options.json === 'undefined') ? true : options.json,
});
}
function sendWebHookMessage(port, token, options = {}) {
assert.ok(port);
assert.ok(token);
const path = `/bot${token}`;
return sendWebHookRequest(port, path, options);
}
function handleRatelimit(bot, methodName, suite) {
const backupMethodName = `__${methodName}`;
if (!bot[backupMethodName]) bot[backupMethodName] = bot[methodName];
const maxRetries = 3;
const addSecs = 5;
const method = bot[backupMethodName];
assert.equal(typeof method, 'function');
bot[methodName] = (...args) => {
let retry = 0;
function exec() {
return method.call(bot, ...args)
.catch(error => {
if (!error.response || error.response.statusCode !== 429) {
throw error;
}
retry++;
if (retry > maxRetries) {
throw error;
}
if (typeof error.response.body === 'string') {
error.response.body = JSON.parse(error.response.body);
}
const retrySecs = error.response.body.parameters.retry_after;
const timeout = (1000 * retrySecs) + (1000 * addSecs);
console.error('tests: Handling rate-limit error. Retrying after %d secs', timeout / 1000); // eslint-disable-line no-console
suite.timeout(timeout * 2);
return new Promise(function timeoutPromise(resolve, reject) {
setTimeout(function execTimeout() {
return exec().then(resolve).catch(reject);
}, timeout);
});
});
}
return exec();
};
return bot;
}
function isTelegramFileURI(uri) {
return /https?:\/\/.*\/file\/bot.*\/.*/.test(uri);
}