diff --git a/.babelrc b/.babelrc deleted file mode 100644 index d03285da..00000000 --- a/.babelrc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "plugins": [ - "transform-strict-mode", - "transform-object-rest-spread", - "transform-class-properties" - ], - "presets": [ - "babel-preset-es2015" - ] -} diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index e717f5eb..00000000 --- a/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -# 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 diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 417342d6..00000000 --- a/.eslintignore +++ /dev/null @@ -1,2 +0,0 @@ -bin -*.md diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index 89f049b6..00000000 --- a/.eslintrc +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 - } -} \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index e447b5ee..00000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - -> 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 - - diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index adc2bcc8..00000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,23 +0,0 @@ - -- [ ] All tests pass -- [ ] I have run `npm run doc` - -### Description - - - -### References - - diff --git a/.gitignore b/.gitignore deleted file mode 100644 index bd74acab..00000000 --- a/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -node_modules -coverage/ -npm-debug.log -.package.json -package-lock.json -output.md -output/ -lib/ -lib-doc/ -.DS_Store \ No newline at end of file diff --git a/.npmignore b/.npmignore deleted file mode 100644 index 4bdcd350..00000000 --- a/.npmignore +++ /dev/null @@ -1,21 +0,0 @@ -# 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 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 097239ee..00000000 --- a/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 04ca7989..00000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,565 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -This project adheres to [Semantic Versioning](http://semver.org/). - -## [0.68.0][0.68.0] - UNRELEASE - -1. Support Telegram Bot API 9.1 (@danielperez9430) - * sendChecklist - * editMessageChecklist - * getMyStarBalance - -2. Support Telegram Bot API 9.0 (@danielperez9430) - * readBusinessMessage - * deleteBusinessMessages - * setBusinessAccountName - * setBusinessAccountUsername - * setBusinessAccountBio - * setBusinessAccountProfilePhoto - * removeBusinessAccountProfilePhoto - * setBusinessAccountGiftSettings - * getBusinessAccountStarBalance - * transferBusinessAccountStars - * getBusinessAccountGifts - * convertGiftToStars - * upgradeGift - * transferGift - * postStory - * editStory - * deleteStory - * giftPremiumSubscription - -3. Support Telegram Bot API 8.2 and 8.3 (@danielperez9430) - * verifyUser - * verifyChat - * removeUserVerification - * removeChatVerification - -4. Support Telegram Bot API 8.0 and 8.1 - * savePreparedInlineMessage (@IsmailBinMujeeb & @danielperez9430) - * setUserEmojiStatus (@danielperez9430) - * editUserStarSubscription (@danielperez9430) - * getAvailableGifts (@danielperez9430) - * sendGift (@danielperez9430) - -5. Support Telegram Bot API 7.10 (@danielperez9430) - * Update: `purchased_paid_media` - -6. Support Telegram Bot API 7.6 (@danielperez9430) - * sendPaidMedia - -## [0.67.0][0.67.0] - 2024-05-30 - -1. Support Telegram Bot API 7.4 (@danielperez9430) - * refundStarPayment - -## [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 -[Unreleased]:https://github.com/yagop/node-telegram-bot-api/compare/v0.30.0...master diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index c845c46d..00000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# 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/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index ab5b29fe..00000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,45 +0,0 @@ -# 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 diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index e952ab9c..00000000 --- a/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -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. diff --git a/README.md b/README.md deleted file mode 100644 index ee46fe2e..00000000 --- a/README.md +++ /dev/null @@ -1,129 +0,0 @@ -

Node.js Telegram Bot API

- -
- -Node.js module to interact with the official [Telegram Bot API](https://core.telegram.org/bots/api). - - -[![Bot API](https://img.shields.io/badge/Bot%20API-v.9.0-00aced.svg?style=flat-square&logo=telegram)](https://core.telegram.org/bots/api) -[![npm package](https://img.shields.io/npm/v/node-telegram-bot-api?logo=npm&style=flat-square)](https://www.npmjs.org/package/node-telegram-bot-api) -[![Coverage Status](https://img.shields.io/codecov/c/github/yagop/node-telegram-bot-api?style=flat-square&logo=codecov)](https://codecov.io/gh/yagop/node-telegram-bot-api) - -[![https://telegram.me/node_telegram_bot_api](https://img.shields.io/badge/💬%20Telegram-Channel-blue.svg?style=flat-square)](https://telegram.me/node_telegram_bot_api) -[![https://t.me/+_IC8j_b1wSFlZTVk](https://img.shields.io/badge/💬%20Telegram-Group-blue.svg?style=flat-square)](https://t.me/+_IC8j_b1wSFlZTVk) -[![https://telegram.me/Yago_Perez](https://img.shields.io/badge/💬%20Telegram-Yago_Perez-blue.svg?style=flat-square)](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 - -

- - - -

- -## License - -**The MIT License (MIT)** - -Copyright © 2019 Yago - -[usage]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/usage.md -[examples]:https://github.com/yagop/node-telegram-bot-api/tree/master/examples -[help]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/help.md -[tutorials]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/tutorials.md -[api-dev]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/api.md -[api-release]:https://github.com/yagop/node-telegram-bot-api/tree/release/doc/api.md -[api-experimental]:https://github.com/yagop/node-telegram-bot-api/tree/experimental/doc/api.md -[contributing]:https://github.com/yagop/node-telegram-bot-api/tree/master/CONTRIBUTING.md -[contributors]:https://github.com/yagop/node-telegram-bot-api/graphs/contributors -[experimental]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/experimental.md -[tg-channel]:https://telegram.me/node_telegram_bot_api -[tg-group]:https://t.me/+nc3A9Hs1S81mYzdk diff --git a/doc/api.hbs b/doc/api.hbs deleted file mode 100644 index 2793b2ef..00000000 --- a/doc/api.hbs +++ /dev/null @@ -1,19 +0,0 @@ -# API Reference - -**Note:** If you are looking for available [events](usage.md#events) or usage of api, please refer [`usage.md`](usage.md). - -{{#class name="TelegramBot"~}} -{{>header~}} -{{>body~}} -{{>member-index~}} -{{>members~}} -{{/class}} -* * * - - -[usage-sending-files-performance]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/usage.md#sending-files-performance -[setWebHook-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#telegrambotsetwebhookurl-cert -[getUpdates-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#TelegramBot+getUpdates -[getUserProfilePhotos-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#TelegramBot+getUserProfilePhotos -[answerCallbackQuery-v0.27.1]:https://github.com/yagop/node-telegram-bot-api/blob/v0.27.1/doc/api.md#TelegramBot+answerCallbackQuery -[answerCallbackQuery-v0.29.0]:https://github.com/yagop/node-telegram-bot-api/blob/v0.29.0/doc/api.md#TelegramBot+answerCallbackQuery diff --git a/doc/api.md b/doc/api.md deleted file mode 100644 index 1f530d4d..00000000 --- a/doc/api.md +++ /dev/null @@ -1,3067 +0,0 @@ -# API Reference - -**Note:** If you are looking for available [events](usage.md#events) or usage of api, please refer [`usage.md`](usage.md). - - - -## TelegramBot -TelegramBot - -**Kind**: global class -**See**: https://core.telegram.org/bots/api - -* [TelegramBot](#TelegramBot) - * [new TelegramBot(token, [options])](#new_TelegramBot_new) - * _instance_ - * [.on(event, listener)](#TelegramBot+on) - * [.startPolling([options])](#TelegramBot+startPolling) ⇒ Promise - * ~~[.initPolling([options])](#TelegramBot+initPolling) ⇒ Promise~~ - * [.stopPolling([options])](#TelegramBot+stopPolling) ⇒ Promise - * [.getFileLink(fileId, [options])](#TelegramBot+getFileLink) ⇒ Promise - * [.getFileStream(fileId, [options])](#TelegramBot+getFileStream) ⇒ stream.Readable - * [.downloadFile(fileId, downloadDir, [options])](#TelegramBot+downloadFile) ⇒ Promise - * [.onText(regexpRexecuted, callback)](#TelegramBot+onText) - * [.removeTextListener(regexp)](#TelegramBot+removeTextListener) ⇒ Object - * [.clearTextListeners()](#TelegramBot+clearTextListeners) - * [.onReplyToMessage(chatId, messageId, callback)](#TelegramBot+onReplyToMessage) ⇒ Number - * [.removeReplyListener(replyListenerId)](#TelegramBot+removeReplyListener) ⇒ Object - * [.clearReplyListeners()](#TelegramBot+clearReplyListeners) ⇒ Array - * [.isPolling()](#TelegramBot+isPolling) ⇒ Boolean - * [.openWebHook()](#TelegramBot+openWebHook) ⇒ Promise - * [.closeWebHook()](#TelegramBot+closeWebHook) ⇒ Promise - * [.hasOpenWebHook()](#TelegramBot+hasOpenWebHook) ⇒ Boolean - * [.processUpdate(update)](#TelegramBot+processUpdate) - * [.getUpdates([options])](#TelegramBot+getUpdates) ⇒ Promise - * [.setWebHook(url, [options], [fileOptions])](#TelegramBot+setWebHook) ⇒ Promise - * [.deleteWebHook([options])](#TelegramBot+deleteWebHook) ⇒ Promise - * [.getWebHookInfo([options])](#TelegramBot+getWebHookInfo) ⇒ Promise - * [.getMe([options])](#TelegramBot+getMe) ⇒ Promise - * [.logOut([options])](#TelegramBot+logOut) ⇒ Promise - * [.close([options])](#TelegramBot+close) ⇒ Promise - * [.sendMessage(chatId, text, [options])](#TelegramBot+sendMessage) ⇒ Promise - * [.forwardMessage(chatId, fromChatId, messageId, [options])](#TelegramBot+forwardMessage) ⇒ Promise - * [.forwardMessages(chatId, fromChatId, messageIds, [options])](#TelegramBot+forwardMessages) ⇒ Promise - * [.copyMessage(chatId, fromChatId, messageId, [options])](#TelegramBot+copyMessage) ⇒ Promise - * [.copyMessages(chatId, fromChatId, messageIds, [options])](#TelegramBot+copyMessages) ⇒ Promise - * [.sendPhoto(chatId, photo, [options], [fileOptions])](#TelegramBot+sendPhoto) ⇒ Promise - * [.sendAudio(chatId, audio, [options], [fileOptions])](#TelegramBot+sendAudio) ⇒ Promise - * [.sendDocument(chatId, doc, [options], [fileOptions])](#TelegramBot+sendDocument) ⇒ Promise - * [.sendVideo(chatId, video, [options], [fileOptions])](#TelegramBot+sendVideo) ⇒ Promise - * [.sendAnimation(chatId, animation, [options], [fileOptions])](#TelegramBot+sendAnimation) ⇒ Promise - * [.sendVoice(chatId, voice, [options], [fileOptions])](#TelegramBot+sendVoice) ⇒ Promise - * [.sendVideoNote(chatId, videoNote, [options], [fileOptions])](#TelegramBot+sendVideoNote) ⇒ Promise - * [.sendPaidMedia(chatId, starCount, media, [options])](#TelegramBot+sendPaidMedia) ⇒ Promise - * [.sendMediaGroup(chatId, media, [options])](#TelegramBot+sendMediaGroup) ⇒ Promise - * [.sendLocation(chatId, latitude, longitude, [options])](#TelegramBot+sendLocation) ⇒ Promise - * [.editMessageLiveLocation(latitude, longitude, [options])](#TelegramBot+editMessageLiveLocation) ⇒ Promise - * [.stopMessageLiveLocation([options])](#TelegramBot+stopMessageLiveLocation) ⇒ Promise - * [.sendVenue(chatId, latitude, longitude, title, address, [options])](#TelegramBot+sendVenue) ⇒ Promise - * [.sendContact(chatId, phoneNumber, firstName, [options])](#TelegramBot+sendContact) ⇒ Promise - * [.sendPoll(chatId, question, pollOptions, [options])](#TelegramBot+sendPoll) ⇒ Promise - * [.sendChecklist(businessConnectionId, chatId, checklist, [options])](#TelegramBot+sendChecklist) ⇒ Promise - * [.sendDice(chatId, [options])](#TelegramBot+sendDice) ⇒ Promise - * [.sendChatAction(chatId, action, [options])](#TelegramBot+sendChatAction) ⇒ Promise - * [.setMessageReaction(chatId, messageId, [options])](#TelegramBot+setMessageReaction) ⇒ [ 'Promise' ].<Boolean> - * [.getUserProfilePhotos(userId, [options])](#TelegramBot+getUserProfilePhotos) ⇒ Promise - * [.setUserEmojiStatus(userId, [options])](#TelegramBot+setUserEmojiStatus) ⇒ Promise - * [.getFile(fileId, [options])](#TelegramBot+getFile) ⇒ Promise - * [.banChatMember(chatId, userId, [options])](#TelegramBot+banChatMember) ⇒ Promise - * [.unbanChatMember(chatId, userId, [options])](#TelegramBot+unbanChatMember) ⇒ Promise - * [.restrictChatMember(chatId, userId, [options])](#TelegramBot+restrictChatMember) ⇒ Promise - * [.promoteChatMember(chatId, userId, [options])](#TelegramBot+promoteChatMember) ⇒ Promise - * [.setChatAdministratorCustomTitle(chatId, userId, customTitle, [options])](#TelegramBot+setChatAdministratorCustomTitle) ⇒ Promise - * [.banChatSenderChat(chatId, senderChatId, [options])](#TelegramBot+banChatSenderChat) ⇒ Promise - * [.unbanChatSenderChat(chatId, senderChatId, [options])](#TelegramBot+unbanChatSenderChat) ⇒ Promise - * [.setChatPermissions(chatId, chatPermissions, [options])](#TelegramBot+setChatPermissions) ⇒ Promise - * [.exportChatInviteLink(chatId, [options])](#TelegramBot+exportChatInviteLink) ⇒ Promise - * [.createChatInviteLink(chatId, [options])](#TelegramBot+createChatInviteLink) ⇒ Object - * [.editChatInviteLink(chatId, inviteLink, [options])](#TelegramBot+editChatInviteLink) ⇒ Promise - * [.createChatSubscriptionInviteLink(chatId, subscriptionPeriod, subscriptionPrice, [options])](#TelegramBot+createChatSubscriptionInviteLink) ⇒ Promise - * [.editChatSubscriptionInviteLink(chatId, inviteLink, [options])](#TelegramBot+editChatSubscriptionInviteLink) ⇒ Promise - * [.revokeChatInviteLink(chatId, inviteLink, [options])](#TelegramBot+revokeChatInviteLink) ⇒ Promise - * [.approveChatJoinRequest(chatId, userId, [options])](#TelegramBot+approveChatJoinRequest) ⇒ Promise - * [.declineChatJoinRequest(chatId, userId, [options])](#TelegramBot+declineChatJoinRequest) ⇒ Promise - * [.setChatPhoto(chatId, photo, [options], [fileOptions])](#TelegramBot+setChatPhoto) ⇒ Promise - * [.deleteChatPhoto(chatId, [options])](#TelegramBot+deleteChatPhoto) ⇒ Promise - * [.setChatTitle(chatId, title, [options])](#TelegramBot+setChatTitle) ⇒ Promise - * [.setChatDescription(chatId, description, [options])](#TelegramBot+setChatDescription) ⇒ Promise - * [.pinChatMessage(chatId, messageId, [options])](#TelegramBot+pinChatMessage) ⇒ Promise - * [.unpinChatMessage(chatId, [options])](#TelegramBot+unpinChatMessage) ⇒ Promise - * [.unpinAllChatMessages(chatId, [options])](#TelegramBot+unpinAllChatMessages) ⇒ Promise - * [.leaveChat(chatId, [options])](#TelegramBot+leaveChat) ⇒ Promise - * [.getChat(chatId, [options])](#TelegramBot+getChat) ⇒ Promise - * [.getChatAdministrators(chatId, [options])](#TelegramBot+getChatAdministrators) ⇒ Promise - * [.getChatMemberCount(chatId, [options])](#TelegramBot+getChatMemberCount) ⇒ Promise - * [.getChatMember(chatId, userId, [options])](#TelegramBot+getChatMember) ⇒ Promise - * [.setChatStickerSet(chatId, stickerSetName, [options])](#TelegramBot+setChatStickerSet) ⇒ Promise - * [.deleteChatStickerSet(chatId, [options])](#TelegramBot+deleteChatStickerSet) ⇒ Promise - * [.getForumTopicIconStickers(chatId, [options])](#TelegramBot+getForumTopicIconStickers) ⇒ Promise - * [.createForumTopic(chatId, name, [options])](#TelegramBot+createForumTopic) - * [.editForumTopic(chatId, messageThreadId, [options])](#TelegramBot+editForumTopic) ⇒ Promise - * [.closeForumTopic(chatId, messageThreadId, [options])](#TelegramBot+closeForumTopic) ⇒ Promise - * [.reopenForumTopic(chatId, messageThreadId, [options])](#TelegramBot+reopenForumTopic) ⇒ Promise - * [.deleteForumTopic(chatId, messageThreadId, [options])](#TelegramBot+deleteForumTopic) ⇒ Promise - * [.unpinAllForumTopicMessages(chatId, messageThreadId, [options])](#TelegramBot+unpinAllForumTopicMessages) ⇒ Promise - * [.editGeneralForumTopic(chatId, name, [options])](#TelegramBot+editGeneralForumTopic) ⇒ Promise - * [.closeGeneralForumTopic(chatId, [options])](#TelegramBot+closeGeneralForumTopic) ⇒ Promise - * [.reopenGeneralForumTopic(chatId, [options])](#TelegramBot+reopenGeneralForumTopic) ⇒ Promise - * [.hideGeneralForumTopic(chatId, [options])](#TelegramBot+hideGeneralForumTopic) ⇒ Promise - * [.unhideGeneralForumTopic(chatId, [options])](#TelegramBot+unhideGeneralForumTopic) ⇒ Promise - * [.unpinAllGeneralForumTopicMessages(chatId, [options])](#TelegramBot+unpinAllGeneralForumTopicMessages) ⇒ Promise - * [.answerCallbackQuery(callbackQueryId, [options])](#TelegramBot+answerCallbackQuery) ⇒ Promise - * [.savePreparedInlineMessage(userId, result, [options])](#TelegramBot+savePreparedInlineMessage) ⇒ Promise - * [.getUserChatBoosts(chatId, userId, [options])](#TelegramBot+getUserChatBoosts) ⇒ Promise - * [.getBusinessConnection(businessConnectionId, [options])](#TelegramBot+getBusinessConnection) ⇒ Promise - * [.setMyCommands(commands, [options])](#TelegramBot+setMyCommands) ⇒ Promise - * [.deleteMyCommands([options])](#TelegramBot+deleteMyCommands) ⇒ Promise - * [.getMyCommands([options])](#TelegramBot+getMyCommands) ⇒ Promise - * [.setMyName([options])](#TelegramBot+setMyName) ⇒ Promise - * [.getMyName([options])](#TelegramBot+getMyName) ⇒ Promise - * [.setMyDescription([options])](#TelegramBot+setMyDescription) ⇒ Promise - * [.getMyDescription([options])](#TelegramBot+getMyDescription) ⇒ Promise - * [.setMyShortDescription([options])](#TelegramBot+setMyShortDescription) ⇒ Promise - * [.getMyShortDescription([options])](#TelegramBot+getMyShortDescription) ⇒ Promise - * [.setChatMenuButton([options])](#TelegramBot+setChatMenuButton) ⇒ Promise - * [.getChatMenuButton([options])](#TelegramBot+getChatMenuButton) ⇒ Promise - * [.setMyDefaultAdministratorRights([options])](#TelegramBot+setMyDefaultAdministratorRights) ⇒ Promise - * [.getMyDefaultAdministratorRights([options])](#TelegramBot+getMyDefaultAdministratorRights) ⇒ Promise - * [.editMessageText(text, [options])](#TelegramBot+editMessageText) ⇒ Promise - * [.editMessageCaption(caption, [options])](#TelegramBot+editMessageCaption) ⇒ Promise - * [.editMessageMedia(media, [options])](#TelegramBot+editMessageMedia) ⇒ Promise - * [.editMessageChecklist(businessConnectionId, chatId, messageId, checklist, [options])](#TelegramBot+editMessageChecklist) ⇒ Promise - * [.editMessageReplyMarkup(replyMarkup, [options])](#TelegramBot+editMessageReplyMarkup) ⇒ Promise - * [.stopPoll(chatId, pollId, [options])](#TelegramBot+stopPoll) ⇒ Promise - * [.sendSticker(chatId, sticker, [options], [fileOptions])](#TelegramBot+sendSticker) ⇒ Promise - * [.getStickerSet(name, [options])](#TelegramBot+getStickerSet) ⇒ Promise - * [.getCustomEmojiStickers(custom_emoji_ids, [options])](#TelegramBot+getCustomEmojiStickers) ⇒ Promise - * [.uploadStickerFile(userId, sticker, stickerFormat, [options], [fileOptions])](#TelegramBot+uploadStickerFile) ⇒ Promise - * [.createNewStickerSet(userId, name, title, pngSticker, emojis, [options], [fileOptions])](#TelegramBot+createNewStickerSet) ⇒ Promise - * [.addStickerToSet(userId, name, sticker, emojis, stickerType, [options], [fileOptions])](#TelegramBot+addStickerToSet) ⇒ Promise - * [.setStickerPositionInSet(sticker, position, [options])](#TelegramBot+setStickerPositionInSet) ⇒ Promise - * [.deleteStickerFromSet(sticker, [options])](#TelegramBot+deleteStickerFromSet) ⇒ Promise - * [.replaceStickerInSet(user_id, name, sticker, [options])](#TelegramBot+replaceStickerInSet) ⇒ Promise - * [.setStickerEmojiList(sticker, emojiList, [options])](#TelegramBot+setStickerEmojiList) ⇒ Promise - * [.setStickerKeywords(sticker, [options])](#TelegramBot+setStickerKeywords) ⇒ Promise - * [.setStickerMaskPosition(sticker, [options])](#TelegramBot+setStickerMaskPosition) ⇒ Promise - * [.setStickerSetTitle(name, title, [options])](#TelegramBot+setStickerSetTitle) ⇒ Promise - * [.setStickerSetThumbnail(userId, name, thumbnail, [options], [fileOptions])](#TelegramBot+setStickerSetThumbnail) ⇒ Promise - * [.setCustomEmojiStickerSetThumbnail(name, [options])](#TelegramBot+setCustomEmojiStickerSetThumbnail) ⇒ Promise - * [.deleteStickerSet(name, [options])](#TelegramBot+deleteStickerSet) ⇒ Promise - * [.answerInlineQuery(inlineQueryId, results, [options])](#TelegramBot+answerInlineQuery) ⇒ Promise - * [.answerWebAppQuery(webAppQueryId, result, [options])](#TelegramBot+answerWebAppQuery) ⇒ Promise - * [.sendInvoice(chatId, title, description, payload, providerToken, currency, prices, [options])](#TelegramBot+sendInvoice) ⇒ Promise - * [.createInvoiceLink(title, description, payload, providerToken, currency, prices, [options])](#TelegramBot+createInvoiceLink) ⇒ Promise - * [.answerShippingQuery(shippingQueryId, ok, [options])](#TelegramBot+answerShippingQuery) ⇒ Promise - * [.answerPreCheckoutQuery(preCheckoutQueryId, ok, [options])](#TelegramBot+answerPreCheckoutQuery) ⇒ Promise - * [.getMyStarBalance([options])](#TelegramBot+getMyStarBalance) ⇒ Promise - * [.getStarTransactions([options])](#TelegramBot+getStarTransactions) ⇒ Promise - * [.refundStarPayment(userId, telegramPaymentChargeId, [options])](#TelegramBot+refundStarPayment) ⇒ Promise - * [.editUserStarSubscription(userId, telegramPaymentChargeId, isCanceled, [options])](#TelegramBot+editUserStarSubscription) ⇒ Promise - * [.sendGame(chatId, gameShortName, [options])](#TelegramBot+sendGame) ⇒ Promise - * [.setGameScore(userId, score, [options])](#TelegramBot+setGameScore) ⇒ Promise - * [.getGameHighScores(userId, [options])](#TelegramBot+getGameHighScores) ⇒ Promise - * [.deleteMessage(chatId, messageId, [options])](#TelegramBot+deleteMessage) ⇒ Promise - * [.deleteMessages(chatId, messageIds, [options])](#TelegramBot+deleteMessages) ⇒ [ 'Promise' ].<Boolean> - * [.getAvailableGifts([options])](#TelegramBot+getAvailableGifts) ⇒ Promise - * [.sendGift(giftId, [options])](#TelegramBot+sendGift) ⇒ Promise - * [.giftPremiumSubscription(userId, monthCount, starCount, [options])](#TelegramBot+giftPremiumSubscription) ⇒ Promise - * [.verifyUser(userId, [options])](#TelegramBot+verifyUser) ⇒ Promise - * [.verifyChat(chatId, [options])](#TelegramBot+verifyChat) ⇒ Promise - * [.removeUserVerification(userId, [options])](#TelegramBot+removeUserVerification) ⇒ Promise - * [.removeChatVerification(chatId, [options])](#TelegramBot+removeChatVerification) ⇒ Promise - * [.readBusinessMessage(businessConnectionId, chatId, messageId, [options])](#TelegramBot+readBusinessMessage) ⇒ Promise - * [.deleteBusinessMessages(businessConnectionId, messageIds, [options])](#TelegramBot+deleteBusinessMessages) ⇒ Promise - * [.setBusinessAccountName(businessConnectionId, firstName, [options])](#TelegramBot+setBusinessAccountName) ⇒ Promise - * [.setBusinessAccountUsername(businessConnectionId, [options])](#TelegramBot+setBusinessAccountUsername) ⇒ Promise - * [.setBusinessAccountBio(businessConnectionId, [options])](#TelegramBot+setBusinessAccountBio) ⇒ Promise - * [.setBusinessAccountProfilePhoto(businessConnectionId, photo, [options])](#TelegramBot+setBusinessAccountProfilePhoto) ⇒ Promise - * [.removeBusinessAccountProfilePhoto(businessConnectionId, [options])](#TelegramBot+removeBusinessAccountProfilePhoto) ⇒ Promise - * [.setBusinessAccountGiftSettings(businessConnectionId, showGiftButton, acceptedGiftTypes, [options])](#TelegramBot+setBusinessAccountGiftSettings) ⇒ Promise - * [.getBusinessAccountStarBalance(businessConnectionId, [options])](#TelegramBot+getBusinessAccountStarBalance) ⇒ Promise - * [.transferBusinessAccountStars(businessConnectionId, starCount, [options])](#TelegramBot+transferBusinessAccountStars) ⇒ Promise - * [.getBusinessAccountGifts(businessConnectionId, [options])](#TelegramBot+getBusinessAccountGifts) ⇒ Promise - * [.convertGiftToStars(businessConnectionId, ownedGiftId, [options])](#TelegramBot+convertGiftToStars) ⇒ Promise - * [.upgradeGift(businessConnectionId, ownedGiftId, [options])](#TelegramBot+upgradeGift) ⇒ Promise - * [.transferGift(businessConnectionId, ownedGiftId, newOwnerChatId, [options])](#TelegramBot+transferGift) ⇒ Promise - * [.postStory(businessConnectionId, content, activePeriod, [options])](#TelegramBot+postStory) ⇒ Promise - * [.editStory(businessConnectionId, storyId, content, [options])](#TelegramBot+editStory) ⇒ Promise - * [.deleteStory(businessConnectionId, storyId, [options])](#TelegramBot+deleteStory) ⇒ Promise - * _static_ - * [.errors](#TelegramBot.errors) : Object - * [.messageTypes](#TelegramBot.messageTypes) : [ 'Array' ].<String> - - - -### new TelegramBot(token, [options]) -Both request method to obtain messages are implemented. To use standard polling, set `polling: true` -on `options`. Notice that [webHook](https://core.telegram.org/bots/api#setwebhook) will need a SSL certificate. -Emits `message` when a message arrives. - - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| token | String | | Bot Token | -| [options] | Object | | | -| [options.polling] | Boolean \| Object | false | Set true to enable polling or set options. If a WebHook has been set, it will be deleted automatically. | -| [options.polling.timeout] | String \| Number | 10 | *Deprecated. Use `options.polling.params` instead*. Timeout in seconds for long polling. | -| [options.testEnvironment] | Boolean | 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. | -| [options.polling.interval] | String \| Number | 300 | Interval between requests in miliseconds | -| [options.polling.autoStart] | Boolean | true | Start polling immediately | -| [options.polling.params] | Object | | Parameters to be used in polling API requests. See https://core.telegram.org/bots/api#getupdates for more information. | -| [options.polling.params.timeout] | Number | 10 | Timeout in seconds for long polling. | -| [options.webHook] | Boolean \| Object | false | Set true to enable WebHook or set options | -| [options.webHook.host] | String | "0.0.0.0" | Host to bind to | -| [options.webHook.port] | Number | 8443 | Port to bind to | -| [options.webHook.key] | String | | Path to file with PEM private key for webHook server. The file is read **synchronously**! | -| [options.webHook.cert] | String | | Path to file with PEM certificate (public) for webHook server. The file is read **synchronously**! | -| [options.webHook.pfx] | String | | Path to file with PFX private key and certificate chain for webHook server. The file is read **synchronously**! | -| [options.webHook.autoOpen] | Boolean | true | Open webHook immediately | -| [options.webHook.https] | Object | | Options to be passed to `https.createServer()`. Note that `options.webHook.key`, `options.webHook.cert` and `options.webHook.pfx`, if provided, will be used to override `key`, `cert` and `pfx` in this object, respectively. See https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener for more information. | -| [options.webHook.healthEndpoint] | String | "/healthz" | An endpoint for health checks that always responds with 200 OK | -| [options.onlyFirstMatch] | Boolean | false | Set to true to stop after first match. Otherwise, all regexps are executed | -| [options.request] | Object | | Options which will be added for all requests to telegram api. See https://github.com/request/request#requestoptions-callback for more information. | -| [options.baseApiUrl] | String | "https://api.telegram.org" | API Base URl; useful for proxying and testing | -| [options.filepath] | Boolean | 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. | -| [options.badRejection] | Boolean | 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*. | - - - -### telegramBot.on(event, listener) -Add listener for the specified [event](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events). -This is the usual `emitter.on()` method. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**See** - -- [Available events](https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#events) -- https://nodejs.org/api/events.html#events_emitter_on_eventname_listener - - -| Param | Type | -| --- | --- | -| event | String | -| listener | function | - - - -### telegramBot.startPolling([options]) ⇒ Promise -Start polling. -Rejects returned promise if a WebHook is being used by this instance. - -**Kind**: instance method of [TelegramBot](#TelegramBot) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| [options] | Object | | | -| [options.restart] | Boolean | true | Consecutive calls to this method causes polling to be restarted | - - - -### ~~telegramBot.initPolling([options]) ⇒ Promise~~ -***Deprecated*** - -Alias of `TelegramBot#startPolling()`. This is **deprecated**. - -**Kind**: instance method of [TelegramBot](#TelegramBot) - -| Param | Type | -| --- | --- | -| [options] | Object | - - - -### telegramBot.stopPolling([options]) ⇒ Promise -Stops polling after the last polling request resolves. -Multiple invocations do nothing if polling is already stopped. -Returning the promise of the last polling request is **deprecated**. - -**Kind**: instance method of [TelegramBot](#TelegramBot) - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Options | -| [options.cancel] | Boolean | Cancel current request | -| [options.reason] | String | Reason for stopping polling | - - - -### telegramBot.getFileLink(fileId, [options]) ⇒ Promise -Get link for file. -Use this method to get link for file for subsequent use. -Attention: link will be valid for 1 hour. - -This method is a sugar extension of the (getFile)[#getfilefileid] method, -which returns just path to file on remote server (you will have to manually build full uri after that). - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Promise which will have *fileURI* in resolve callback -**See**: https://core.telegram.org/bots/api#getfile - -| Param | Type | Description | -| --- | --- | --- | -| fileId | String | File identifier to get info about | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getFileStream(fileId, [options]) ⇒ stream.Readable -Return a readable stream for file. - -`fileStream.path` is the specified file ID i.e. `fileId`. -`fileStream` emits event `info` passing a single argument i.e. -`info` with the interface `{ uri }` where `uri` is the URI of the -file on Telegram servers. - -This method is a sugar extension of the [getFileLink](#TelegramBot+getFileLink) method, -which returns the full URI to the file on remote server. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: stream.Readable - fileStream - -| Param | Type | Description | -| --- | --- | --- | -| fileId | String | File identifier to get info about | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.downloadFile(fileId, downloadDir, [options]) ⇒ Promise -Downloads file in the specified folder. - -This method is a sugar extension of the [getFileStream](#TelegramBot+getFileStream) method, -which returns a readable file stream. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Promise, which will have *filePath* of downloaded file in resolve callback - -| Param | Type | Description | -| --- | --- | --- | -| fileId | String | File identifier to get info about | -| downloadDir | String | Absolute path to the folder in which file will be saved | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.onText(regexpRexecuted, callback) -Register a RegExp to test against an incomming text message. - -**Kind**: instance method of [TelegramBot](#TelegramBot) - -| Param | Type | Description | -| --- | --- | --- | -| regexpRexecuted | RegExp | with `exec`. | -| callback | function | Callback will be called with 2 parameters, the `msg` and the result of executing `regexp.exec` on message text. | - - - -### telegramBot.removeTextListener(regexp) ⇒ Object -Remove a listener registered with `onText()`. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Object - deletedListener The removed reply listener if - found. This object has `regexp` and `callback` - properties. If not found, returns `null`. - -| Param | Type | Description | -| --- | --- | --- | -| regexp | RegExp | RegExp used previously in `onText()` | - - - -### telegramBot.clearTextListeners() -Remove all listeners registered with `onText()`. - -**Kind**: instance method of [TelegramBot](#TelegramBot) - - -### telegramBot.onReplyToMessage(chatId, messageId, callback) ⇒ Number -Register a reply to wait for a message response. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Number - id The ID of the inserted reply listener. - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | The chat id where the message cames from. | -| messageId | Number \| String | The message id to be replied. | -| callback | function | Callback will be called with the reply message. | - - - -### telegramBot.removeReplyListener(replyListenerId) ⇒ Object -Removes a reply that has been prev. registered for a message response. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Object - deletedListener The removed reply listener if - found. This object has `id`, `chatId`, `messageId` and `callback` - properties. If not found, returns `null`. - -| Param | Type | Description | -| --- | --- | --- | -| replyListenerId | Number | The ID of the reply listener. | - - - -### telegramBot.clearReplyListeners() ⇒ Array -Removes all replies that have been prev. registered for a message response. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Array - deletedListeners An array of removed listeners. - - -### telegramBot.isPolling() ⇒ Boolean -Return true if polling. Otherwise, false. - -**Kind**: instance method of [TelegramBot](#TelegramBot) - - -### telegramBot.openWebHook() ⇒ Promise -Open webhook. -Multiple invocations do nothing if webhook is already open. -Rejects returned promise if Polling is being used by this instance. - -**Kind**: instance method of [TelegramBot](#TelegramBot) - - -### telegramBot.closeWebHook() ⇒ Promise -Close webhook after closing all current connections. -Multiple invocations do nothing if webhook is already closed. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Promise - - -### telegramBot.hasOpenWebHook() ⇒ Boolean -Return true if using webhook and it is open i.e. accepts connections. -Otherwise, false. - -**Kind**: instance method of [TelegramBot](#TelegramBot) - - -### telegramBot.processUpdate(update) -Process an update; emitting the proper events and executing regexp -callbacks. This method is useful should you be using a different -way to fetch updates, other than those provided by TelegramBot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**See**: https://core.telegram.org/bots/api#update - -| Param | Type | -| --- | --- | -| update | Object | - - - -### telegramBot.getUpdates([options]) ⇒ Promise -Use this method to receive incoming updates using long polling. -This method has an [older, compatible signature][getUpdates-v0.25.0] -that is being deprecated. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**See**: https://core.telegram.org/bots/api#getupdates - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setWebHook(url, [options], [fileOptions]) ⇒ Promise -Specify an url to receive incoming updates via an outgoing webHook. -This method has an [older, compatible signature][setWebHook-v0.25.0] -that is being deprecated. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**See** - -- https://core.telegram.org/bots/api#setwebhook -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| url | String | URL where Telegram will make HTTP Post. Leave empty to delete webHook. | -| [options] | Object | Additional Telegram query options | -| [options.certificate] | String \| stream.Stream | PEM certificate key (public). | -| [options.secret_token] | String | Optional secret token to be sent in a header `X-Telegram-Bot-Api-Secret-Token` in every webhook request. | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.deleteWebHook([options]) ⇒ Promise -Use this method to remove webhook integration if you decide to -switch back to getUpdates. Returns True on success. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**See**: https://core.telegram.org/bots/api#deletewebhook - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getWebHookInfo([options]) ⇒ Promise -Use this method to get current webhook status. -On success, returns a [WebhookInfo](https://core.telegram.org/bots/api#webhookinfo) object. -If the bot is using getUpdates, will return an object with the -url field empty. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**See**: https://core.telegram.org/bots/api#getwebhookinfo - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getMe([options]) ⇒ Promise -A simple method for testing your bot's authentication token. Requires no parameters. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.logOut([options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#logout - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.close([options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#close - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendMessage(chatId, text, [options]) ⇒ Promise -Send text message. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See**: https://core.telegram.org/bots/api#sendmessage - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| text | String | Text of the message to be sent | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.forwardMessage(chatId, fromChatId, messageId, [options]) ⇒ Promise -Forward messages of any kind. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**See**: https://core.telegram.org/bots/api#forwardmessage - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | 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`) | -| fromChatId | Number \| String | Unique identifier for the chat where the original message was sent (or channel username in the format `@channelusername`) | -| messageId | Number \| String | Unique message identifier in the chat specified in fromChatId | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.forwardMessages(chatId, fromChatId, messageIds, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - An array of MessageId of the sent messages on success -**See**: https://core.telegram.org/bots/api#forwardmessages - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | 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`) | -| fromChatId | Number \| String | Unique identifier for the chat where the original message was sent (or channel username in the format `@channelusername`) | -| messageIds | [ 'Array' ].<(Number\|String)> | Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.copyMessage(chatId, fromChatId, messageId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - The [MessageId](https://core.telegram.org/bots/api#messageid) of the sent message on success -**See**: https://core.telegram.org/bots/api#copymessage - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| fromChatId | Number \| String | Unique identifier for the chat where the original message was sent | -| messageId | Number \| String | Unique message identifier | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.copyMessages(chatId, fromChatId, messageIds, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - An array of MessageId of the sent messages -**See**: https://core.telegram.org/bots/api#copymessages - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat | -| fromChatId | Number \| String | Unique identifier for the chat where the original message was sent | -| messageIds | Array | Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendPhoto(chatId, photo, [options], [fileOptions]) ⇒ Promise -Send photo - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See** - -- https://core.telegram.org/bots/api#sendphoto -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| photo | String \| stream.Stream \| Buffer | A file path or a Stream. Can also be a `file_id` previously uploaded | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.sendAudio(chatId, audio, [options], [fileOptions]) ⇒ Promise -Send audio - -**Your audio must be in the .MP3 or .M4A format.** - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See** - -- https://core.telegram.org/bots/api#sendaudio -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| audio | String \| stream.Stream \| Buffer | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.sendDocument(chatId, doc, [options], [fileOptions]) ⇒ Promise -Send Document - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See** - -- https://core.telegram.org/bots/api#sendDocument -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| doc | String \| stream.Stream \| Buffer | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.sendVideo(chatId, video, [options], [fileOptions]) ⇒ Promise -Use this method to send video files, **Telegram clients support mp4 videos** (other formats may be sent as Document). - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See** - -- https://core.telegram.org/bots/api#sendvideo -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| video | String \| stream.Stream \| Buffer | A file path or Stream. Can also be a `file_id` previously uploaded. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.sendAnimation(chatId, animation, [options], [fileOptions]) ⇒ Promise -Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See** - -- https://core.telegram.org/bots/api#sendanimation -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| animation | String \| stream.Stream \| Buffer | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.sendVoice(chatId, voice, [options], [fileOptions]) ⇒ Promise -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) - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See** - -- https://core.telegram.org/bots/api#sendvoice -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| voice | String \| stream.Stream \| Buffer | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.sendVideoNote(chatId, videoNote, [options], [fileOptions]) ⇒ Promise -Use this method to send video messages -Telegram clients support **rounded square MPEG4 videos** of up to 1 minute long. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| videoNote | String \| stream.Stream \| Buffer | A file path or Stream. Can also be a `file_id` previously uploaded. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.sendPaidMedia(chatId, starCount, media, [options]) ⇒ Promise -Use this method to send paid media. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See**: https://core.telegram.org/bots/api#sendpaidmedia - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| starCount | Number | The number of Telegram Stars that must be paid to buy access to the media; 1-10000 | -| media | Array | Array of [InputPaidMedia](https://core.telegram.org/bots/api#inputpaidmedia). The media property can bea String, Stream or Buffer. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendMediaGroup(chatId, media, [options]) ⇒ Promise -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`. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 -- https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files - - -| Param | Type | Description | -| --- | --- | --- | -| chatId | String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| media | Array | A JSON-serialized array describing photos and videos to be sent, must include 2–10 items | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendLocation(chatId, latitude, longitude, [options]) ⇒ Promise -Send location. -Use this method to send point on the map. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See**: https://core.telegram.org/bots/api#sendlocation - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| latitude | Float | Latitude of location | -| longitude | Float | Longitude of location | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editMessageLiveLocation(latitude, longitude, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| latitude | Float | Latitude of location | -| longitude | Float | Longitude of location | -| [options] | Object | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) | - - - -### telegramBot.stopMessageLiveLocation([options]) ⇒ Promise -Use this method to stop updating a live location message sent by -the bot or via the bot (for inline bots) before live_period expires. - -Note that you must provide one of chat_id, message_id, or -inline_message_id in your request. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) | - - - -### telegramBot.sendVenue(chatId, latitude, longitude, title, address, [options]) ⇒ Promise -Send venue. -Use this method to send information about a venue. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned. -**See**: https://core.telegram.org/bots/api#sendvenue - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| latitude | Float | Latitude of location | -| longitude | Float | Longitude of location | -| title | String | Name of the venue | -| address | String | Address of the venue | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendContact(chatId, phoneNumber, firstName, [options]) ⇒ Promise -Send contact. -Use this method to send phone contacts. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See**: https://core.telegram.org/bots/api#sendcontact - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| phoneNumber | String | Contact's phone number | -| firstName | String | Contact's first name | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendPoll(chatId, question, pollOptions, [options]) ⇒ Promise -Send poll. -Use this method to send a native poll. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See**: https://core.telegram.org/bots/api#sendpoll - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the group/channel | -| question | String | Poll question, 1-300 characters | -| pollOptions | Array | Poll options, between 2-10 options (only 1-100 characters each) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendChecklist(businessConnectionId, chatId, checklist, [options]) ⇒ Promise -Send sendChecklist. -Use this method to send a checklist on behalf of a connected business account. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See**: https://core.telegram.org/bots/api#sendchecklist - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | Number \| String | Unique identifier for the business connection | -| chatId | Number \| String | Unique identifier for the group/channel | -| checklist | Object | A JSON-serialized object for the checklist to send | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendDice(chatId, [options]) ⇒ Promise -Send Dice -Use this method to send an animated emoji that will display a random value. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned -**See**: https://core.telegram.org/bots/api#senddice - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendChatAction(chatId, action, [options]) ⇒ Promise -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). - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#sendchataction - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| action | String | Type of action to broadcast. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setMessageReaction(chatId, messageId, [options]) ⇒ [ 'Promise' ].<Boolean> -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: [ 'Promise' ].<Boolean> - True on success -**See**: https://core.telegram.org/bots/api#setmessagereaction - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | -| messageId | Number | Unique identifier of the target message | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getUserProfilePhotos(userId, [options]) ⇒ Promise -Use this method to get a list of profile pictures for a user. -Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object. -This method has an [older, compatible signature][getUserProfilePhotos-v0.25.0] -that is being deprecated. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object -**See**: https://core.telegram.org/bots/api#getuserprofilephotos - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setUserEmojiStatus(userId, [options]) ⇒ Promise -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). - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setuseremojistatus - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getFile(fileId, [options]) ⇒ Promise -Get file. -Use this method to get basic info about a file and prepare it for downloading. - -Attention: **link will be valid for 1 hour.** - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, a [File](https://core.telegram.org/bots/api#file) object is returned -**See**: https://core.telegram.org/bots/api#getfile - -| Param | Type | Description | -| --- | --- | --- | -| fileId | String | File identifier to get info about | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.banChatMember(chatId, userId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success. -**See**: https://core.telegram.org/bots/api#banchatmember - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.unbanChatMember(chatId, userId, [options]) ⇒ Promise -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* - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#unbanchatmember - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.restrictChatMember(chatId, userId, [options]) ⇒ Promise -Use this method to restrict a user in a supergroup. -The bot **must be an administrator in the supergroup** for this to work -and must have the appropriate admin rights. Pass True for all boolean parameters -to lift restrictions from a user. Returns True on success. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#restrictchatmember - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.promoteChatMember(chatId, userId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success. -**See**: https://core.telegram.org/bots/api#promotechatmember - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| userId | Number | | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setChatAdministratorCustomTitle(chatId, userId, customTitle, [options]) ⇒ Promise -Use this method to set a custom title for an administrator in a supergroup promoted by the bot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setchatadministratorcustomtitle - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| userId | Number | Unique identifier of the target user | -| customTitle | String | New custom title for the administrator; 0-16 characters, emoji are not allowed | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.banChatSenderChat(chatId, senderChatId, [options]) ⇒ Promise -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 - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success. -**See**: https://core.telegram.org/bots/api#banchatsenderchat - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| senderChatId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.unbanChatSenderChat(chatId, senderChatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#unbanchatsenderchat - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| senderChatId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setChatPermissions(chatId, chatPermissions, [options]) ⇒ Promise -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.** - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setchatpermissions - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| chatPermissions | Array | New default chat permissions | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.exportChatInviteLink(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Exported invite link as String on success. -**See**: https://core.telegram.org/bots/api#exportchatinvitelink - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.createChatInviteLink(chatId, [options]) ⇒ Object -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) - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Object - The new invite link as [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object -**See**: https://core.telegram.org/bots/api#createchatinvitelink - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editChatInviteLink(chatId, inviteLink, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - The edited invite link as a [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object -**See**: https://core.telegram.org/bots/api#editchatinvitelink - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| inviteLink | String | Text with the invite link to edit | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.createChatSubscriptionInviteLink(chatId, subscriptionPeriod, subscriptionPrice, [options]) ⇒ Promise -Use this method to create a subscription invite link for a channel chat. - -The bot must have the can_invite_users administrator rights - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - The new invite link as a [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object -**See**: https://core.telegram.org/bots/api#createchatsubscriptioninvitelink - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| subscriptionPeriod | Number | The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days) | -| subscriptionPrice | Number | 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) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editChatSubscriptionInviteLink(chatId, inviteLink, [options]) ⇒ Promise -Use this method to edit a subscription invite link created by the bot. - -The bot must have the can_invite_users administrator rights - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - The new invite link as a [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object -**See**: https://core.telegram.org/bots/api#editchatsubscriptioninvitelink - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| inviteLink | String | The invite link to edit | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.revokeChatInviteLink(chatId, inviteLink, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - The revoked invite link as [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object -**See**: https://core.telegram.org/bots/api#revokechatinvitelink - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| inviteLink | String | The invite link to revoke | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.approveChatJoinRequest(chatId, userId, [options]) ⇒ Promise -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.** - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#approvechatjoinrequest - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.declineChatJoinRequest(chatId, userId, [options]) ⇒ Promise -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**. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#declinechatjoinrequest - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setChatPhoto(chatId, photo, [options], [fileOptions]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setchatphoto - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| photo | stream.Stream \| Buffer | A file path or a Stream. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.deleteChatPhoto(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#deletechatphoto - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setChatTitle(chatId, title, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setchattitle - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| title | String | New chat title, 1-255 characters | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setChatDescription(chatId, description, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setchatdescription - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| description | String | New chat title, 0-255 characters | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.pinChatMessage(chatId, messageId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#pinchatmessage - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| messageId | Number | Identifier of a message to pin | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.unpinChatMessage(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#unpinchatmessage - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.unpinAllChatMessages(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#unpinallchatmessages - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.leaveChat(chatId, [options]) ⇒ Promise -Use this method for your bot to leave a group, supergroup or channel - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#leavechat - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getChat(chatId, [options]) ⇒ Promise -Use this method to get up to date information about the chat -(current name of the user for one-on-one conversations, current -username of a user, group or channel, etc.). - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - [ChatFullInfo](https://core.telegram.org/bots/api#chatfullinfo) object on success -**See**: https://core.telegram.org/bots/api#getchat - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) or channel | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getChatAdministrators(chatId, [options]) ⇒ Promise -Use this method to get a list of administrators in a chat - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getChatMemberCount(chatId, [options]) ⇒ Promise -Use this method to get the number of members in a chat. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Int on success -**See**: https://core.telegram.org/bots/api#getchatmembercount - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getChatMember(chatId, userId, [options]) ⇒ Promise -Use this method to get information about a member of a chat. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - [ChatMember](https://core.telegram.org/bots/api#chatmember) object on success -**See**: https://core.telegram.org/bots/api#getchatmember - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setChatStickerSet(chatId, stickerSetName, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setchatstickerset - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| stickerSetName | String | Name of the sticker set to be set as the group sticker set | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteChatStickerSet(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#deletechatstickerset - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getForumTopicIconStickers(chatId, [options]) ⇒ Promise -Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects -**See**: https://core.telegram.org/bots/api#getforumtopiciconstickers - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.createForumTopic(chatId, name, [options]) -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**See**: https://core.telegram.org/bots/api#createforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| name | String | Topic name, 1-128 characters | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editForumTopic(chatId, messageThreadId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#editforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| messageThreadId | Number | Unique identifier for the target message thread of the forum topic | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.closeForumTopic(chatId, messageThreadId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#closeforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| messageThreadId | Number | Unique identifier for the target message thread of the forum topic | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.reopenForumTopic(chatId, messageThreadId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#reopenforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| messageThreadId | Number | Unique identifier for the target message thread of the forum topic | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteForumTopic(chatId, messageThreadId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#deleteforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| messageThreadId | Number | Unique identifier for the target message thread of the forum topic | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.unpinAllForumTopicMessages(chatId, messageThreadId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#unpinallforumtopicmessages - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| messageThreadId | Number | Unique identifier for the target message thread of the forum topic | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editGeneralForumTopic(chatId, name, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#editgeneralforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| name | String | New topic name, 1-128 characters | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.closeGeneralForumTopic(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#closegeneralforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.reopenGeneralForumTopic(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#reopengeneralforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.hideGeneralForumTopic(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#hidegeneralforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.unhideGeneralForumTopic(chatId, [options]) ⇒ Promise -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 - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#unhidegeneralforumtopic - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.unpinAllGeneralForumTopicMessages(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername) | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.answerCallbackQuery(callbackQueryId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#answercallbackquery - -| Param | Type | Description | -| --- | --- | --- | -| callbackQueryId | String | Unique identifier for the query to be answered | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.savePreparedInlineMessage(userId, result, [options]) ⇒ Promise -Use this method to stores a message that can be sent by a user of a Mini App. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns a [PreparedInlineMessage](https://core.telegram.org/bots/api#preparedinlinemessage) object. -**See**: https://core.telegram.org/bots/api#savepreparedinlinemessage - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the target user | -| result | InlineQueryResult | object that represents one result of an inline query | -| [options] | Object | Optional form data to include in the request | - - - -### telegramBot.getUserChatBoosts(chatId, userId, [options]) ⇒ Promise -Use this method to get the list of boosts added to a chat by a use. -Requires administrator rights in the chat - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns a [UserChatBoosts](https://core.telegram.org/bots/api#userchatboosts) object -**See**: https://core.telegram.org/bots/api#getuserchatboosts - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the group/channel | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getBusinessConnection(businessConnectionId, [options]) ⇒ Promise -Use this method to get information about the connection of the bot with a business account - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns [BusinessConnection](https://core.telegram.org/bots/api#businessconnection) object -**See**: https://core.telegram.org/bots/api#getbusinessconnection - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | Number \| String | Unique identifier for the group/channel | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setMyCommands(commands, [options]) ⇒ Promise -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 - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setmycommands - -| Param | Type | Description | -| --- | --- | --- | -| commands | Array | 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. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteMyCommands([options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#deletemycommands - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getMyCommands([options]) ⇒ Promise -Use this method to get the current list of the bot's commands for the given scope and user language. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setMyName([options]) ⇒ Promise -Use this method to change the bot's name. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setmyname - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getMyName([options]) ⇒ Promise -Use this method to get the current bot name for the given user language. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - [BotName](https://core.telegram.org/bots/api#botname) on success -**See**: https://core.telegram.org/bots/api#getmyname - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setMyDescription([options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setmydescription - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getMyDescription([options]) ⇒ Promise -Use this method to get the current bot description for the given user language. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Returns [BotDescription](https://core.telegram.org/bots/api#botdescription) on success. -**See**: https://core.telegram.org/bots/api#getmydescription - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setMyShortDescription([options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Returns True on success. -**See**: https://core.telegram.org/bots/api#setmyshortdescription - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getMyShortDescription([options]) ⇒ Promise -Use this method to get the current bot short description for the given user language. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Returns [BotShortDescription](https://core.telegram.org/bots/api#botshortdescription) on success. -**See**: https://core.telegram.org/bots/api#getmyshortdescription - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setChatMenuButton([options]) ⇒ Promise -Use this method to change the bot's menu button in a private chat, or the default menu button. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setchatmenubutton - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getChatMenuButton([options]) ⇒ Promise -Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - [MenuButton](https://core.telegram.org/bots/api#menubutton) on success -**See**: https://core.telegram.org/bots/api#getchatmenubutton - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setMyDefaultAdministratorRights([options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#getchatmenubutton - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getMyDefaultAdministratorRights([options]) ⇒ Promise -Use this method to get the current default administrator rights of the bot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - [ChatAdministratorRights](https://core.telegram.org/bots/api#chatadministratorrights) on success -**See**: https://core.telegram.org/bots/api#getmydefaultadministratorrights - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editMessageText(text, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| text | String | New text of the message | -| [options] | Object | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) | - - - -### telegramBot.editMessageCaption(caption, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| caption | String | New caption of the message | -| [options] | Object | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) | - - - -### telegramBot.editMessageMedia(media, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| media | Object | A JSON-serialized object for a new media content of the message | -| [options] | Object | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) | - - - -### telegramBot.editMessageChecklist(businessConnectionId, chatId, messageId, checklist, [options]) ⇒ Promise -Use this method to edit a checklist on behalf of a business connection. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned. -**See**: https://core.telegram.org/bots/api#editmessagechecklist - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | Number \| String | Unique identifier for the target business connection | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| messageId | Number | Unique identifier for the target message | -| checklist | Object | A JSON-serialized object for the new checklist | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editMessageReplyMarkup(replyMarkup, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| replyMarkup | Object | A JSON-serialized object for an inline keyboard. | -| [options] | Object | Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here) | - - - -### telegramBot.stopPoll(chatId, pollId, [options]) ⇒ Promise -Use this method to stop a poll which was sent by the bot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the stopped [Poll](https://core.telegram.org/bots/api#poll) is returned -**See**: https://core.telegram.org/bots/api#stoppoll - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the group/channel | -| pollId | Number | Identifier of the original message with the poll | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendSticker(chatId, sticker, [options], [fileOptions]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned -**See**: https://core.telegram.org/bots/api#sendsticker - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| sticker | String \| stream.Stream \| Buffer | A file path, Stream or Buffer. Can also be a `file_id` previously uploaded. Stickers are WebP format files. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.getStickerSet(name, [options]) ⇒ Promise -Use this method to get a sticker set. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, a [StickerSet](https://core.telegram.org/bots/api#stickerset) object is returned -**See**: https://core.telegram.org/bots/api#getstickerset - -| Param | Type | Description | -| --- | --- | --- | -| name | String | Name of the sticker set | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getCustomEmojiStickers(custom_emoji_ids, [options]) ⇒ Promise -Use this method to get information about custom emoji stickers by their identifiers. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects. -**See**: https://core.telegram.org/bots/api#getcustomemojistickers - -| Param | Type | Description | -| --- | --- | --- | -| custom_emoji_ids | Array | List of custom emoji identifiers. At most 200 custom emoji identifiers can be specified. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.uploadStickerFile(userId, sticker, stickerFormat, [options], [fileOptions]) ⇒ Promise -Use this method to upload a file with a sticker for later use in *createNewStickerSet* and *addStickerToSet* methods (can be used multiple -times). - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, a [File](https://core.telegram.org/bots/api#file) object is returned -**See**: https://core.telegram.org/bots/api#uploadstickerfile - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| userId | Number | | User identifier of sticker file owner | -| sticker | String \| stream.Stream \| Buffer | | A file path or a Stream with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. Can also be a `file_id` previously uploaded. | -| stickerFormat | String | static | Allow values: `static`, `animated` or `video` | -| [options] | Object | | Additional Telegram query options | -| [fileOptions] | Object | | Optional file related meta-data | - - - -### telegramBot.createNewStickerSet(userId, name, title, pngSticker, emojis, [options], [fileOptions]) ⇒ Promise -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* - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#createnewstickerset - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | User identifier of created sticker set owner | -| name | String | 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. | -| title | String | Sticker set title, 1-64 characters | -| pngSticker | String \| stream.Stream \| Buffer | Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. | -| emojis | String | One or more emoji corresponding to the sticker | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.addStickerToSet(userId, name, sticker, emojis, stickerType, [options], [fileOptions]) ⇒ Promise -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 - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#addstickertoset - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| userId | Number | | User identifier of sticker set owner | -| name | String | | Sticker set name | -| sticker | String \| stream.Stream \| Buffer | | 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. | -| emojis | String | | One or more emoji corresponding to the sticker | -| stickerType | String | png_sticker | Allow values: `png_sticker`, `tgs_sticker`, or `webm_sticker`. | -| [options] | Object | | Additional Telegram query options | -| [fileOptions] | Object | | Optional file related meta-data | - - - -### telegramBot.setStickerPositionInSet(sticker, position, [options]) ⇒ Promise -Use this method to move a sticker in a set created by the bot to a specific position. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setstickerpositioninset - -| Param | Type | Description | -| --- | --- | --- | -| sticker | String | File identifier of the sticker | -| position | Number | New sticker position in the set, zero-based | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteStickerFromSet(sticker, [options]) ⇒ Promise -Use this method to delete a sticker from a set created by the bot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#deletestickerfromset -**Todo** - -- [ ] Add tests for this method! - - -| Param | Type | Description | -| --- | --- | --- | -| sticker | String | File identifier of the sticker | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.replaceStickerInSet(user_id, name, sticker, [options]) ⇒ Promise -Use this method to replace an existing sticker in a sticker set with a new one - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#replacestickerinset -**Todo** - -- [ ] Add tests for this method! - - -| Param | Type | Description | -| --- | --- | --- | -| user_id | Number | User identifier of the sticker set owner | -| name | String | Sticker set name | -| sticker | String | File identifier of the sticker | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setStickerEmojiList(sticker, emojiList, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setstickeremojilist - -| Param | Type | Description | -| --- | --- | --- | -| sticker | String | File identifier of the sticker | -| emojiList | Array | A JSON-serialized list of 1-20 emoji associated with the sticker | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setStickerKeywords(sticker, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setstickerkeywords - -| Param | Type | Description | -| --- | --- | --- | -| sticker | String | File identifier of the sticker | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setStickerMaskPosition(sticker, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setstickermaskposition - -| Param | Type | Description | -| --- | --- | --- | -| sticker | String | File identifier of the sticker | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setStickerSetTitle(name, title, [options]) ⇒ Promise -Use this method to set the title of a created sticker set. - -The sticker must belong to a sticker set created by the bot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setstickersettitle - -| Param | Type | Description | -| --- | --- | --- | -| name | String | Sticker set name | -| title | String | Sticker set title, 1-64 characters | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setStickerSetThumbnail(userId, name, thumbnail, [options], [fileOptions]) ⇒ Promise -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 - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setstickersetthumbnail - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | User identifier of sticker set owner | -| name | String | Sticker set name | -| thumbnail | String \| stream.Stream \| Buffer | 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. | -| [options] | Object | Additional Telegram query options | -| [fileOptions] | Object | Optional file related meta-data | - - - -### telegramBot.setCustomEmojiStickerSetThumbnail(name, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail - -| Param | Type | Description | -| --- | --- | --- | -| name | String | Sticker set name | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteStickerSet(name, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#deletestickerset - -| Param | Type | Description | -| --- | --- | --- | -| name | String | Sticker set name | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.answerInlineQuery(inlineQueryId, results, [options]) ⇒ Promise -Send answers to an inline query. - -Note: No more than 50 results per query are allowed. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, True is returned -**See**: https://core.telegram.org/bots/api#answerinlinequery - -| Param | Type | Description | -| --- | --- | --- | -| inlineQueryId | String | Unique identifier of the query | -| results | [ 'Array' ].<InlineQueryResult> | An array of results for the inline query | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.answerWebAppQuery(webAppQueryId, result, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, a [SentWebAppMessage](https://core.telegram.org/bots/api#sentwebappmessage) object is returned -**See**: https://core.telegram.org/bots/api#answerwebappquery - -| Param | Type | Description | -| --- | --- | --- | -| webAppQueryId | String | Unique identifier for the query to be answered | -| result | InlineQueryResult | object that represents one result of an inline query | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendInvoice(chatId, title, description, payload, providerToken, currency, prices, [options]) ⇒ Promise -Use this method to send an invoice. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned -**See**: https://core.telegram.org/bots/api#sendinvoice - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| title | String | Product name, 1-32 characters | -| description | String | Product description, 1-255 characters | -| payload | String | Bot defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. | -| providerToken | String | Payments provider token, obtained via `@BotFather` | -| currency | String | Three-letter ISO 4217 currency code | -| prices | Array | Breakdown of prices | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.createInvoiceLink(title, description, payload, providerToken, currency, prices, [options]) ⇒ Promise -Use this method to create a link for an invoice. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - The created invoice link as String on success. -**See**: https://core.telegram.org/bots/api#createinvoicelink - -| Param | Type | Description | -| --- | --- | --- | -| title | String | Product name, 1-32 characters | -| description | String | Product description, 1-255 characters | -| payload | String | Bot defined invoice payload | -| providerToken | String | Payment provider token | -| currency | String | Three-letter ISO 4217 currency code | -| prices | Array | Breakdown of prices | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.answerShippingQuery(shippingQueryId, ok, [options]) ⇒ Promise -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 - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, True is returned -**See**: https://core.telegram.org/bots/api#answershippingquery - -| Param | Type | Description | -| --- | --- | --- | -| shippingQueryId | String | Unique identifier for the query to be answered | -| ok | Boolean | Specify if delivery of the product is possible | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.answerPreCheckoutQuery(preCheckoutQueryId, ok, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, True is returned -**See**: https://core.telegram.org/bots/api#answerprecheckoutquery - -| Param | Type | Description | -| --- | --- | --- | -| preCheckoutQueryId | String | Unique identifier for the query to be answered | -| ok | Boolean | Specify if every order details are ok | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getMyStarBalance([options]) ⇒ Promise -Use this method to get the current Telegram Stars balance of the bot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns a [StarAmount](https://core.telegram.org/bots/api#staramount) object -**See**: https://core.telegram.org/bots/api#getmystarbalance - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getStarTransactions([options]) ⇒ Promise -Use this method for get the bot's Telegram Star transactions in chronological order - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns a [StarTransactions](https://core.telegram.org/bots/api#startransactions) object -**See**: https://core.telegram.org/bots/api#getstartransactions - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.refundStarPayment(userId, telegramPaymentChargeId, [options]) ⇒ Promise -Use this method for refund a successful payment in [Telegram Stars](https://t.me/BotNews/90) - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, True is returned -**See**: https://core.telegram.org/bots/api#refundstarpayment - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the user whose payment will be refunded | -| telegramPaymentChargeId | String | Telegram payment identifier | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editUserStarSubscription(userId, telegramPaymentChargeId, isCanceled, [options]) ⇒ Promise -Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, True is returned -**See**: https://core.telegram.org/bots/api#cancelrenewsubscription - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the user whose subscription will be canceled or re-enabled | -| telegramPaymentChargeId | String | Telegram payment identifier for the subscription | -| isCanceled | Boolean | True, if the subscription should be canceled, False, if it should be re-enabled | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.sendGame(chatId, gameShortName, [options]) ⇒ Promise -Use this method to send a game. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned -**See**: https://core.telegram.org/bots/api#sendgame - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) | -| gameShortName | String | name of the game to be sent. Set up your games via `@BotFather`. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setGameScore(userId, score, [options]) ⇒ Promise -Use this method to set the score of the specified user in a game message. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: 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 - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the target user | -| score | Number | New score value, must be non-negative | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getGameHighScores(userId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns an Array of [GameHighScore](https://core.telegram.org/bots/api#gamehighscore) objects -**See**: https://core.telegram.org/bots/api#getgamehighscores - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteMessage(chatId, messageId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - True on success -**See**: https://core.telegram.org/bots/api#deletemessage - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | -| messageId | Number | Unique identifier of the target message | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteMessages(chatId, messageIds, [options]) ⇒ [ 'Promise' ].<Boolean> -Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: [ 'Promise' ].<Boolean> - True on success -**See**: https://core.telegram.org/bots/api#deletemessages - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number \| String | Unique identifier for the target chat or username of the target channel (in the format @channelusername) | -| messageIds | [ 'Array' ].<(Number\|String)> | Identifiers of 1-100 messages to delete. See deleteMessage for limitations on which messages can be deleted | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getAvailableGifts([options]) ⇒ Promise -Use this method to returns the list of gifts that can be sent by the bot to users and channel chats. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns a [Gifts](https://core.telegram.org/bots/api#gifts) objects. -**See**: https://core.telegram.org/bots/api#getavailablegifts - -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Additional Telegram query options. | - - - -### telegramBot.sendGift(giftId, [options]) ⇒ Promise -Use this method to sends a gift to the given user or channel chat. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#getavailablegifts - -| Param | Type | Description | -| --- | --- | --- | -| giftId | String | Unique identifier of the gift | -| [options] | Object | Additional Telegram query options. | - - - -### telegramBot.giftPremiumSubscription(userId, monthCount, starCount, [options]) ⇒ Promise -Use this method to sends a gift to the given user or channel chat. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#getavailablegifts - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the target user who will receive a Telegram Premium subscription. | -| monthCount | Number | Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12. | -| starCount | String | 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. | -| [options] | Object | Additional Telegram query options. | - - - -### telegramBot.verifyUser(userId, [options]) ⇒ Promise -This method verifies a user [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#verifyuser - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the target user. | -| [options] | Object | Additional Telegram query options. | - - - -### telegramBot.verifyChat(chatId, [options]) ⇒ Promise -This method verifies a chat [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#verifychat - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number | Unique identifier of the target chat. | -| [options] | Object | Additional Telegram query options. | - - - -### telegramBot.removeUserVerification(userId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#removeuserverification - -| Param | Type | Description | -| --- | --- | --- | -| userId | Number | Unique identifier of the target user | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.removeChatVerification(chatId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#removechatverification - -| Param | Type | Description | -| --- | --- | --- | -| chatId | Number | Unique identifier of the target chat. | -| [options] | Object | Additional Telegram query options. | - - - -### telegramBot.readBusinessMessage(businessConnectionId, chatId, messageId, [options]) ⇒ Promise -This method marks incoming message as read on behalf of a business account. - -Requires the **can_read_messages** business bot right - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#readbusinessmessage - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection on behalf of which to read the message. | -| chatId | Number | Unique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours. | -| messageId | Number | Unique identifier of the message to mark as read. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteBusinessMessages(businessConnectionId, messageIds, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#deletebusinessmessages - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection on behalf of which to delete the message. | -| messageIds | [ 'Array' ].<Number> | List of 1-100 identifiers of messages to delete. All messages **must be from the same chat**. | -| [options] | Object | Additional Telegram query options. | - - - -### telegramBot.setBusinessAccountName(businessConnectionId, firstName, [options]) ⇒ Promise -This method changes the first and last name of a managed business account. - -Requires the **can_change_name** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#setbusinessaccountname - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| firstName | String | The new value of the first name for the business account; 1-64 characters. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setBusinessAccountUsername(businessConnectionId, [options]) ⇒ Promise -This method changes the username of a managed business account. - -Requires the **can_change_username** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#setbusinessaccountusername - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setBusinessAccountBio(businessConnectionId, [options]) ⇒ Promise -This method changes the bio of a managed business account. - -Requires the **can_change_bio** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#setbusinessaccountbio - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setBusinessAccountProfilePhoto(businessConnectionId, photo, [options]) ⇒ Promise -This method changes the profile photo of a managed business account. - -Requires the **can_edit_profile_photo** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#setbusinessaccountprofilephoto - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| photo | String \| stream.Stream \| Buffer | New profile photo. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.removeBusinessAccountProfilePhoto(businessConnectionId, [options]) ⇒ Promise -This method removes the current profile photo of a managed business account. - -Requires the **can_edit_profile_photo** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#removebusinessaccountprofilephoto - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.setBusinessAccountGiftSettings(businessConnectionId, showGiftButton, acceptedGiftTypes, [options]) ⇒ Promise -This method changes the privacy settings pertaining to incoming gifts in a managed business account. - -Requires the **can_change_gift_settings** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns true. -**See**: https://core.telegram.org/bots/api#setbusinessaccountgiftsettings - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| showGiftButton | Boolean | 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. | -| acceptedGiftTypes | Object | Types of gifts accepted by the business account. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.getBusinessAccountStarBalance(businessConnectionId, [options]) ⇒ Promise -This method returns the amount of Telegram Stars owned by a managed business account. - -Requires the **can_view_gifts_and_stars** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns [StarAmount](https://core.telegram.org/bots/api#staramount). -**See**: https://core.telegram.org/bots/api#getbusinessaccountstarbalance - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.transferBusinessAccountStars(businessConnectionId, starCount, [options]) ⇒ Promise -This method transfers Telegram Stars from the business account balance to the bot's balance. - -Requires the **can_transfer_stars** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns True. -**See**: https://core.telegram.org/bots/api#transferbusinessaccountstars - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| starCount | Number | Number of Telegram Stars to transfer; 1-10000. | -| [options] | Object | Additional Telegram query options. | - - - -### telegramBot.getBusinessAccountGifts(businessConnectionId, [options]) ⇒ Promise -This method returns the gifts received and owned by a managed business account. - -Requires the **can_view_gifts_and_stars** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns [OwnedGifts](https://core.telegram.org/bots/api#ownedgifts). -**See**: https://core.telegram.org/bots/api#getbusinessaccountgifts - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.convertGiftToStars(businessConnectionId, ownedGiftId, [options]) ⇒ Promise -This method converts a given regular gift to Telegram Stars. - -Requires the **can_convert_gifts_to_stars** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns True. -**See**: https://core.telegram.org/bots/api#convertgifttostars - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| ownedGiftId | String | Unique identifier of the regular gift that should be converted to Telegram Stars. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.upgradeGift(businessConnectionId, ownedGiftId, [options]) ⇒ Promise -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**. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns True. -**See**: https://core.telegram.org/bots/api#upgradegift - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| ownedGiftId | String | Unique identifier of the regular gift that should be upgraded to a unique one. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.transferGift(businessConnectionId, ownedGiftId, newOwnerChatId, [options]) ⇒ Promise -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**. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns True. -**See**: https://core.telegram.org/bots/api#transfergift - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| ownedGiftId | String | Unique identifier of the regular gift that should be transferred. | -| newOwnerChatId | Number | Unique identifier of the chat which will own the gift. The chat **must be active in the last 24 hours**. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.postStory(businessConnectionId, content, activePeriod, [options]) ⇒ Promise -This method posts a story on behalf of a managed business account. - -Requires the **can_manage_stories** business bot right. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns [Story](https://core.telegram.org/bots/api#story). -**See**: https://core.telegram.org/bots/api#poststory - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| content | Array | [InputStoryContent](https://core.telegram.org/bots/api#inputpaidmedia). The photo/video property can be String, Stream or Buffer. | -| activePeriod | Number | Unique identifier of the chat which will own the gift. The chat **must be active in the last 24 hours**. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.editStory(businessConnectionId, storyId, content, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns [Story](https://core.telegram.org/bots/api#story). -**See**: https://core.telegram.org/bots/api#editstory - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| storyId | Number | Unique identifier of the story to edit. | -| content | Array | [InputStoryContent](https://core.telegram.org/bots/api#inputpaidmedia). The photo/video property can be String, Stream or Buffer. | -| [options] | Object | Additional Telegram query options | - - - -### telegramBot.deleteStory(businessConnectionId, storyId, [options]) ⇒ Promise -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. - -**Kind**: instance method of [TelegramBot](#TelegramBot) -**Returns**: Promise - On success, returns True. -**See**: https://core.telegram.org/bots/api#deletestory - -| Param | Type | Description | -| --- | --- | --- | -| businessConnectionId | String | Unique identifier of the business connection. | -| storyId | Number | Unique identifier of the story to delete. | -| [options] | Object | Additional Telegram query options. | - - - -### TelegramBot.errors : Object -The different errors the library uses. - -**Kind**: static property of [TelegramBot](#TelegramBot) - - -### TelegramBot.messageTypes : [ 'Array' ].<String> -The types of message updates the library handles. - -**Kind**: static property of [TelegramBot](#TelegramBot) -* * * - - -[usage-sending-files-performance]:https://github.com/yagop/node-telegram-bot-api/tree/master/doc/usage.md#sending-files-performance -[setWebHook-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#telegrambotsetwebhookurl-cert -[getUpdates-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#TelegramBot+getUpdates -[getUserProfilePhotos-v0.25.0]:https://github.com/yagop/node-telegram-bot-api/tree/4e5a493cadfaad5589a8d79e55d9e0d103000ce4#TelegramBot+getUserProfilePhotos -[answerCallbackQuery-v0.27.1]:https://github.com/yagop/node-telegram-bot-api/blob/v0.27.1/doc/api.md#TelegramBot+answerCallbackQuery -[answerCallbackQuery-v0.29.0]:https://github.com/yagop/node-telegram-bot-api/blob/v0.29.0/doc/api.md#TelegramBot+answerCallbackQuery diff --git a/doc/experimental.md b/doc/experimental.md deleted file mode 100644 index 0dad2d63..00000000 --- a/doc/experimental.md +++ /dev/null @@ -1,28 +0,0 @@ -# Experimental - -Experimental features are things we are trying out. We are **not** sure -if they'll become stable and move into the `master` branch. -Try them out and give feedback to support stabilizing them. - -* [Features](#features) -* [API Reference][api-experimental] -* [Installation](#installation) - - - -## features: - -* Support API method `deleteMessage` - -Open issues tagged `experimental`: [link](https://github.com/yagop/node-telegram-bot-api/issues?q=is%3Apr+is%3Aopen+label%3Aexperimental) - - - -## installation: - -```bash -$ npm install yagop/node-telegram-bot-api#experimental -``` - - -[api-experimental]:https://github.com/yagop/node-telegram-bot-api/tree/experimental/doc/api.md diff --git a/doc/help.md b/doc/help.md deleted file mode 100644 index 82172fcd..00000000 --- a/doc/help.md +++ /dev/null @@ -1,151 +0,0 @@ -# Help Information - -* [Common Pitfalls](#pitfalls) -* [FAQs](#faqs) - - -## Common Pitfalls - - -### Failing to receive reply with `ReplyToMessage` - -The user has to **manually reply** to your message, by tapping on the bot's message and select *Reply*. - -Sources: - -* Issue [#113](https://github.com/yagop/node-telegram-bot-api/issues/113) - - -## Frequently Asked Questions - -> Check out [all questions ever asked][questions] on our Github Issues. - -1. [How do I send GIFs?](#gifs) -1. [Why and When do I need a certificate when using WebHooks?](#webhook-cert) -1. [How do I know when a user leaves a chat?](#leave-chat) -1. [What does this error mean?](#error-meanings) -1. [How do I know the selected option in reply keyboard?](#reply-keyboard) -1. [How do I send multiple message in correct sequence?](#ordered-sending) -1. [How do I run my bot behind a proxy?](#proxy) -1. [Can you add feature X to the library?](#new-feature) -1. [Is this scalable?](#scalable) -1. [How do I listen for messages in a chat group?](#messages-in-chat) -1. [How do I know when a user blocks the bot?](#blocked-bot) - - -### How do I send GIFs? - -You might be trying to send your animated GIFs using *TelegramBot#sendPhoto()*. -The method mostly supports static images. As noted by the community, -it seems you need to send them as documents, using *TelegramBot#sendDocument()*. - -```js -bot.sendDocument(chatId, 'cat.gif'); -``` - -Sources: - -* Issue [#11](https://github.com/yagop/node-telegram-bot-api/issues/11) - - -### Why and When do I need a certificate when using WebHooks? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#63](https://github.com/yagop/node-telegram-bot-api/issues/63) -* Issue [#125](https://github.com/yagop/node-telegram-bot-api/issues/125) - - -### How do I know when a user leaves a chat? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#248](https://github.com/yagop/node-telegram-bot-api/issues/248) - - -### What does this error mean? - -* [502 Bad Gateway](https://github.com/yagop/node-telegram-bot-api/issues/377) - -*Not complete. PRs welcome!* - -Sources: - -* Issue [#73](https://github.com/yagop/node-telegram-bot-api/issues/73) -* Issue [#99](https://github.com/yagop/node-telegram-bot-api/issues/99) -* Issue [#101](https://github.com/yagop/node-telegram-bot-api/issues/101) -* Issue [#107](https://github.com/yagop/node-telegram-bot-api/issues/107) -* Issue [#156](https://github.com/yagop/node-telegram-bot-api/issues/156) -* Issue [#170](https://github.com/yagop/node-telegram-bot-api/issues/170) -* Issue [#244](https://github.com/yagop/node-telegram-bot-api/issues/244) - - -### How do I know the selected option in reply keyboard? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#108](https://github.com/yagop/node-telegram-bot-api/issues/108) - - -### How do I send multiple message in correct sequence? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#240](https://github.com/yagop/node-telegram-bot-api/issues/240) - - -### How do I run my bot behind a proxy? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#122](https://github.com/yagop/node-telegram-bot-api/issues/122) -* Issue [#253](https://github.com/yagop/node-telegram-bot-api/issues/253) -* Issue [#766](https://github.com/yagop/node-telegram-bot-api/issues/766) - - -### Can you add feature X to the library? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#238](https://github.com/yagop/node-telegram-bot-api/issues/238) - - -### Is this scalable? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#219](https://github.com/yagop/node-telegram-bot-api/issues/219) - - -### How do I listen for messages in a chat group? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#304](https://github.com/yagop/node-telegram-bot-api/issues/304) - - -### How do I know when a user blocks the bot? - -*Not done. PRs welcome!* - -Sources: - -* Issue [#273](https://github.com/yagop/node-telegram-bot-api/issues/273) - -[questions]:https://github.com/yagop/node-telegram-bot-api/issues?utf8=%E2%9C%93&q=is%3Aissue%20label%3Aquestion%20 diff --git a/doc/tutorials.md b/doc/tutorials.md deleted file mode 100644 index 90b48a5f..00000000 --- a/doc/tutorials.md +++ /dev/null @@ -1,12 +0,0 @@ -# Tutorials - -* [node-telegram-bot-api-tutorial by @hosein2398](https://github.com/hosein2398/node-telegram-bot-api-tutorial) -* [node-telegram-bot-api-persian-language by @saeedhei](https://github.com/saeedhei/node-telegram-bot-api-persian-language) -* [Node.JS: Делаем своего Telegram бота [RUS]](https://archakov.im/post/telegram-bot-on-nodejs) -* [YouTube: Пишем Telegram бота на NodeJS [RUS]](https://www.youtube.com/watch?v=RS1nmDMf69U&list=PL6AOr-PZtK-mM2QC1ixyfa5CtJZGK61aN) -* [Node.jsでTelegramのチャットボットを作る - Qiita](https://qiita.com/neetshin/items/0e2f6fa3ade41adb77bc) -* [Guía: Creación de bots de Telegram en Nodejs [ES]](https://tecnonucleous.com/creacion-de-bots-de-telegram-en-nodejs/) -* [node-telegram-bot-api-tutorial:a telegram bot helper to send templates by sms](https://github.com/vito2005/chatManagerTelegramBot) -* [Telegram bot using blockchain services](https://ilanolkies.com/post/Telegram-bot-using-blockchain-services) -* [How to set webhooks using express local server and NGROK](https://github.com/leobloise/node-telegram-bot-api-wb-tutorial) -> Send a PR with useful links **not** listed above diff --git a/doc/usage.md b/doc/usage.md deleted file mode 100644 index 8aa5e279..00000000 --- a/doc/usage.md +++ /dev/null @@ -1,269 +0,0 @@ -# Usage - -- [Usage](#usage) - - [Events](#events) - - [WebHooks](#webhooks) - - [Sending files](#sending-files) - - [File Options (metadata)](#file-options-metadata) - - [Performance Issue](#performance-issue) - - [Error handling](#error-handling) - - [Polling errors](#polling-errors) - - [WebHook errors](#webhook-errors) - - -## Events - -*TelegramBot* is an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) -that emits the following events: - -1. `message`: Received a new incoming [Message][message] of any kind - 1. Depending on the properties of the [Message][message], one of these - events may **ALSO** be emitted: `text`, `audio`, `document`, `photo`, - `sticker`, `video`, `voice`, `contact`, `location`, - `new_chat_members`, `left_chat_member`, `new_chat_title`, - `new_chat_photo`, `delete_chat_photo`, `group_chat_created`, - `game`, `pinned_message`, `poll`, `dice`, `migrate_from_chat_id`, `migrate_to_chat_id`, - `channel_chat_created`, `supergroup_chat_created`, - `successful_payment`, `invoice`, `video_note` - 1. **Arguments**: `message` ([Message][message]), `metadata` (`{ type?:string }`) - 1. `new_chat_participant`, `left_chat_participant` are **deprecated** -1. `callback_query`: Received a new incoming [Callback Query][callback-query] -1. `inline_query`: Received a new incoming [Inline Query][inline-query] -1. `chosen_inline_result`: Received result of an inline query i.e. [ChosenInlineResult][chosen-inline-result] -1. `channel_post`: Received a new incoming channel post of any kind -1. `edited_message`: Received a new version of a message that is known to the bot and was edited - 1. `edited_message_text` - 1. `edited_message_caption` -1. `edited_channel_post`: Received a new version of a channel post that is known to the bot and was edited - 1. `edited_channel_post_text` - 1. `edited_channel_post_caption` -1. `shipping_query`: Received a new incoming shipping query -1. `pre_checkout_query`: Received a new incoming pre-checkout query -1. `poll`: Received a new incoming poll -2. `poll_answer`: A user has changed their answer in a non-anonymous poll (Only polls sent by the bot) -3. `chat_member`: A chat member's status was updated in a chat -4. `my_chat_member`: The bot's chat member status was updated in a chat -5. `chat_join_request`: A request to join the chat has been sent (The bot must have the can_invite_users administrator right) -5. `polling_error`: Error occurred during polling. See [polling errors](#polling-errors). -6. `webhook_error`: Error occurred handling a webhook request. See [webhook errors](#webhook-errors). -7. `error`: Unexpected error occurred, usually fatal! - -**Tip:** Its much better to listen a specific event rather than on -`message` in order to stay safe from the content. - -**Tip:** Bot must be enabled on [inline mode][inline-mode] for receive some -messages. - - -## WebHooks - -Telegram only supports HTTPS connections to WebHooks. -Therefore, in order to set a WebHook, you will need a SSL certificate. -Since August 29, 2015 Telegram supports self-signed ones, thus, you can -generate them: - -```bash -# Our private cert will be key.pem, keep this file private -$ openssl genrsa -out key.pem 2048 - -# Our public certificate will be crt.pem -$ openssl req -new -sha256 -key key.pem -out crt.pem -``` - -Once they are generated, the `crt.pem` should be uploaded, when setting up -your webhook. For example, - -```js -bot.setWebHook('public-url.com', { - certificate: 'path/to/crt.pem', // Path to your crt.pem -}); -``` - -**Note:** If you encounter an error, like -`Error: error:0906D06C:PEM routines:PEM_read_bio:no start line`, -you may want to proceed to [this issue][issue-63] for more information. - - -## Sending files - -The library makes it easy to get started sending files. *By default*, you -may provide a **file-path** and the library will handle reading it for you. -For example, - -```js -bot.sendAudio(chatId, 'path/to/audio.mp3'); -``` - -You may also pass in a **Readable Stream** from which data will be piped. -For example, - -```js -const stream = fs.createReadStream('path/to/audio.mp3'); -bot.sendAudio(chatId, stream); -``` - -You may also pass in a **Buffer** containing the contents of your file. -For example, - -```js -const buffer = fs.readFileSync('path/to/audio.mp3'); // sync! that's sad! :-( Just making a point! -bot.sendAudio(chatId, buffer); -``` - -If you already have a **File ID**, you earlier retrieved from Telegram, -you may pass it in, for example: - -```js -const fileId = getFileIdSomehow(); -bot.sendAudio(chatId, fileId); -``` - -Some API methods, such as *SendPhoto*, allow passing a **HTTP URL**, that -the Telegram servers will use to download the file. For example, - -```js -const url = 'https://telegram.org/img/t_logo.png'; -bot.sendPhoto(chatId, url); -``` - -If you wish to explicitly specify the filename or -[MIME type](http://en.wikipedia.org/wiki/Internet_media_type), -you may pass an additional argument as file options, like so: - -```js -const fileOptions = { - // Explicitly specify the file name. - filename: 'customfilename', - // Explicitly specify the MIME type. - contentType: 'audio/mpeg', -}; -bot.sendAudio(chatId, data, {}, fileOptions); -``` - -**NOTE:** You **MUST** provide an empty object (`{}`) in place of -*Additional Telegram query options*, if you have **no** query options -to specify. For example, - -```js -// WRONG! -// 'fileOptions' will be taken as additional Telegram query options!!! -bot.sendAudio(chatId, data, fileOptions); - -// RIGHT! -bot.sendAudio(chatId, data, {}, fileOptions); -``` - - - -### File Options (metadata) - -When sending files, the library automatically resolves -the `filename` and `contentType` properties. -**For now, this has to be manually activated using environment -variable `NTBA_FIX_350`.** - -In order of highest-to-lowest precedence in searching for -a value, when resolving the `filename`: - -*(`fileOptions` is the Object argument passed to the method. -The "file" argument passed to the method can be a `Stream`, -`Buffer` or `filepath`.)* - -1. Is `fileOptions.filename` explictly defined? -1. Does `Stream#path` exist? -1. Is `filepath` provided? -1. Default to `"filename"` - -And the `contentType`: - -1. Is `fileOptions.contentType` explictly-defined? -1. Does `Stream#path` exist? -1. Try detecting file-type from the `Buffer` -1. Is `filepath` provided? -1. Is `fileOptions.filename` explicitly defined? -1. Default to `"application/octet-stream"` - - -### Performance Issue - -To support providing file-paths to methods that send files involves -performing a file operation, i.e. *fs.existsSync()*, that checks for -the existence of the file at the provided path. While the cost of -this operation *might* be negligible in most use cases, if you want -to squeeze the best performance out of this library, you may wish to -disable this behavior. - -This will mean that you will **NOT** be able to pass in file-paths. -You will have to use Streams or Buffers to provide the file contents. - -Disabling this behavior: - -```js -const bot = new TelegramBot(token, { - filepath: false, -}); -``` - - -## Error handling - -Every `Error` object we pass back has the properties: - -* `code` (String): - * value is `EFATAL` if error was fatal e.g. network error - * value is `EPARSE` if response body could **not** be parsed - * value is `ETELEGRAM` if error was returned from Telegram servers -* `response` ([http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)): - * available if `error.code` is **not** `EFATAL` -* `response.body` (String|Object): Error response from Telegram - * type is `String` if `error.code` is `EPARSE` - * type is `Object` if `error.code` is `ETELEGRAM` - -For example, sending message to a non-existent user: - -```js -bot.sendMessage(nonExistentUserId, 'text').catch((error) => { - console.log(error.code); // => 'ETELEGRAM' - console.log(error.response.body); // => { ok: false, error_code: 400, description: 'Bad Request: chat not found' } -}); -``` - - -## Polling errors - -An error may occur during polling. It is up to you to handle it -as you see fit. You may decide to crash your bot after a maximum number -of polling errors occurring. **It is all up to you.** - -By default, the polling error is just logged to stderr, if you do -**not** handle this event yourself. - -Listen on the `'polling_error'` event. For example, - -```js -bot.on('polling_error', (error) => { - console.log(error.code); // => 'EFATAL' -}); -``` - - -## WebHook errors - -Just like with [polling errors](#polling-errors), you decide on how to -handle it. By default, the error is logged to stderr. - -Listen on the `'webhook_error'` event. For example, - -```js -bot.on('webhook_error', (error) => { - console.log(error.code); // => 'EPARSE' -}); -``` - -[update]:https://core.telegram.org/bots/api#update -[message]:https://core.telegram.org/bots/api#message -[callback-query]:https://core.telegram.org/bots/api#callbackquery -[inline-query]:https://core.telegram.org/bots/api#inlinequery -[chosen-inline-result]:https://core.telegram.org/bots/api#choseninlineresult -[inline-mode]:https://core.telegram.org/bots/api#inline-mode -[issue-63]:https://github.com/yagop/node-telegram-bot-api/issues/63 diff --git a/examples/game/game.html b/examples/game/game.html deleted file mode 100644 index 0158133d..00000000 --- a/examples/game/game.html +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - - -

-

Use the ACCELERATE button to stay in the air

-

How long can you stay alive?

- - - diff --git a/examples/game/game.js b/examples/game/game.js deleted file mode 100644 index cd7a9d23..00000000 --- a/examples/game/game.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 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}`); -}); diff --git a/examples/polling.js b/examples/polling.js deleted file mode 100644 index 3d6aecb4..00000000 --- a/examples/polling.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * 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); -}); diff --git a/examples/ssl/crt.pem b/examples/ssl/crt.pem deleted file mode 100644 index 1a657635..00000000 --- a/examples/ssl/crt.pem +++ /dev/null @@ -1,22 +0,0 @@ ------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----- diff --git a/examples/ssl/key.pem b/examples/ssl/key.pem deleted file mode 100644 index 427ad656..00000000 --- a/examples/ssl/key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------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----- diff --git a/examples/webhook/express.js b/examples/webhook/express.js deleted file mode 100644 index 4978e3ba..00000000 --- a/examples/webhook/express.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 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!'); -}); diff --git a/examples/webhook/heroku.js b/examples/webhook/heroku.js deleted file mode 100644 index 87953ef0..00000000 --- a/examples/webhook/heroku.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 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!'); -}); diff --git a/examples/webhook/https.js b/examples/webhook/https.js deleted file mode 100644 index 418c648e..00000000 --- a/examples/webhook/https.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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!'); -}); diff --git a/examples/webhook/now.js b/examples/webhook/now.js deleted file mode 100644 index f492e664..00000000 --- a/examples/webhook/now.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 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!'); -}); diff --git a/examples/webhook/openshift2.js b/examples/webhook/openshift2.js deleted file mode 100644 index 72ffaee6..00000000 --- a/examples/webhook/openshift2.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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!'); -}); diff --git a/index.js b/index.js deleted file mode 100644 index 86e04808..00000000 --- a/index.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * 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'); -} diff --git a/package.json b/package.json deleted file mode 100644 index 550f3281..00000000 --- a/package.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "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": "^3.0.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" -} \ No newline at end of file diff --git a/src/errors.js b/src/errors.js deleted file mode 100644 index 8f1c597b..00000000 --- a/src/errors.js +++ /dev/null @@ -1,68 +0,0 @@ -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; - } -}; diff --git a/src/telegram.js b/src/telegram.js deleted file mode 100644 index f2e41efe..00000000 --- a/src/telegram.js +++ /dev/null @@ -1,3838 +0,0 @@ -// 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 {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) { - if (opts.formData === null) { - opts.formData = {}; - } - - const attachName = 'photo'; - const [formData] = this._formatSendData(attachName, options.thumb.replace('attach://', '')); - - if (formData) { - opts.formData[attachName] = formData[attachName]; - opts.qs.thumbnail = `attach://${attachName}`; - } - } - } - - /** - * 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); - } - 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 businesssMessage = 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 (businesssMessage) { - debug('Process Update business_message %j', businesssMessage); - this.emit('business_message', businesssMessage); - } 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 */ - } - - 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 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. - * This method has an [older, compatible signature][getUserProfilePhotos-v0.25.0] - * that is being deprecated. - * - * @param {Number} userId Unique identifier of the target user - * @param {Object} [options] Additional Telegram query options - * @return {Promise} Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object - * @see https://core.telegram.org/bots/api#getuserprofilephotos - */ - getUserProfilePhotos(userId, form = {}) { - /* The older method signature was getUserProfilePhotos(userId, offset, limit). - * We need to ensure backwards-compatibility while maintaining - * consistency of the method signatures throughout the library */ - if (typeof form !== 'object') { - /* eslint-disable no-param-reassign, prefer-rest-params */ - deprecate('The method signature getUserProfilePhotos(userId, offset, limit) has been deprecated since v0.25.0'); - form = { - offset: arguments[1], - limit: arguments[2], - }; - /* eslint-enable no-param-reassign, prefer-rest-params */ - } - form.user_id = userId; - return this._request('getUserProfilePhotos', { form }); - } - - /** - * 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 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('unhideGeneralForumTopic', { 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 = {}) { - 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 }); - } - - /** - * 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 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} user_id 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('deleteStickerFromSet', { 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 }); - } - - /** - * 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 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; diff --git a/src/telegramPolling.js b/src/telegramPolling.js deleted file mode 100644 index 9e6cf904..00000000 --- a/src/telegramPolling.js +++ /dev/null @@ -1,202 +0,0 @@ -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('error: [polling_error] %j', error); // eslint-disable-line no-console - } - return this.bot.emit('polling_error', error); - } - - /** - * Invokes polling (with recursion!) - * @return {Promise} promise of the current request - * @private - */ - _polling() { - this._lastRequest = this - ._getUpdates() - .then(updates => { - this._lastUpdate = Date.now(); - debug('polling data %j', updates); - updates.forEach(update => { - this.options.params.offset = update.update_id + 1; - debug('updated offset: %s', this.options.params.offset); - try { - this.bot.processUpdate(update); - } catch (err) { - err._processing = true; - throw err; - } - }); - return null; - }) - .catch(err => { - debug('polling error: %s', err.message); - if (!err._processing) { - return this._error(err); - } - delete err._processing; - /* - * An error occured while processing the items, - * i.e. in `this.bot.processUpdate()` above. - * We need to mark the already-processed items - * to avoid fetching them again once the application - * is restarted, or moves to next polling interval - * (in cases where unhandled rejections do not terminate - * the process). - * See https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067 - */ - if (!this.bot.options.badRejection) { - return this._error(err); - } - const opts = { - offset: this.options.params.offset, - limit: 1, - timeout: 0, - }; - return this.bot.getUpdates(opts).then(() => { - return this._error(err); - }).catch(requestErr => { - /* - * We have been unable to handle this error. - * We have to log this to stderr to ensure devops - * understands that they may receive already-processed items - * on app restart. - * We simply can not rescue this situation, emit "error" - * event, with the hope that the application exits. - */ - /* eslint-disable no-console */ - const bugUrl = 'https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067'; - console.error('error: Internal handling of The Offset Infinite Loop failed'); - console.error(`error: Due to error '${requestErr}'`); - console.error('error: You may receive already-processed updates on app restart'); - console.error(`error: Please see ${bugUrl} for more information`); - /* eslint-enable no-console */ - return this.bot.emit('error', new errors.FatalError(err)); - }); - }) - .finally(() => { - if (this._abort) { - debug('Polling is aborted!'); - } else { - debug('setTimeout for %s miliseconds', this.options.interval); - this._pollingTimeout = setTimeout(() => this._polling(), this.options.interval); - } - }); - return this._lastRequest; - } - - /** - * Unset current webhook. Used when we detect that a webhook has been set - * and we are trying to poll. Polling and WebHook are mutually exclusive. - * @see https://core.telegram.org/bots/api#getting-updates - * @private - */ - _unsetWebHook() { - debug('unsetting webhook'); - return this.bot._request('setWebHook'); - } - - /** - * Retrieve updates - */ - _getUpdates() { - debug('polling with options: %j', this.options.params); - return this.bot.getUpdates(this.options.params) - .catch(err => { - if (err.response && err.response.statusCode === ANOTHER_WEB_HOOK_USED) { - return this._unsetWebHook().then(() => { - return this.bot.getUpdates(this.options.params); - }); - } - throw err; - }); - } -} - -module.exports = TelegramBotPolling; diff --git a/src/telegramWebHook.js b/src/telegramWebHook.js deleted file mode 100644 index a8a8f8ba..00000000 --- a/src/telegramWebHook.js +++ /dev/null @@ -1,158 +0,0 @@ -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('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; diff --git a/src/utils.js b/src/utils.js deleted file mode 100644 index a2d36ebf..00000000 --- a/src/utils.js +++ /dev/null @@ -1,3 +0,0 @@ -const util = require('util'); -// Native deprecation warning -exports.deprecate = (msg) => util.deprecate(() => { }, msg, 'node-telegram-bot-api')(); diff --git a/test/README.md b/test/README.md deleted file mode 100644 index fa6f19f0..00000000 --- a/test/README.md +++ /dev/null @@ -1,31 +0,0 @@ -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. \ No newline at end of file diff --git a/test/data/audio.mp3 b/test/data/audio.mp3 deleted file mode 100644 index 11cd7852..00000000 Binary files a/test/data/audio.mp3 and /dev/null differ diff --git a/test/data/chat_photo.png b/test/data/chat_photo.png deleted file mode 100644 index df5c81da..00000000 Binary files a/test/data/chat_photo.png and /dev/null differ diff --git a/test/data/photo.gif b/test/data/photo.gif deleted file mode 100644 index 1dfad4e7..00000000 Binary files a/test/data/photo.gif and /dev/null differ diff --git a/test/data/photo.png b/test/data/photo.png deleted file mode 100644 index df5c81da..00000000 Binary files a/test/data/photo.png and /dev/null differ diff --git a/test/data/sticker.png b/test/data/sticker.png deleted file mode 100644 index 971ebc13..00000000 Binary files a/test/data/sticker.png and /dev/null differ diff --git a/test/data/sticker.webp b/test/data/sticker.webp deleted file mode 100644 index ba394470..00000000 Binary files a/test/data/sticker.webp and /dev/null differ diff --git a/test/data/sticker_thumb.png b/test/data/sticker_thumb.png deleted file mode 100644 index 659e561a..00000000 Binary files a/test/data/sticker_thumb.png and /dev/null differ diff --git a/test/data/video.mp4 b/test/data/video.mp4 deleted file mode 100644 index 8b2dbd80..00000000 Binary files a/test/data/video.mp4 and /dev/null differ diff --git a/test/data/voice.ogg b/test/data/voice.ogg deleted file mode 100644 index 0d7f43eb..00000000 Binary files a/test/data/voice.ogg and /dev/null differ diff --git a/test/mocha.opts b/test/mocha.opts deleted file mode 100644 index c7f44ab8..00000000 --- a/test/mocha.opts +++ /dev/null @@ -1,3 +0,0 @@ ---reporter spec ---require babel-register ---timeout 30000 diff --git a/test/telegram.js b/test/telegram.js deleted file mode 100644 index 5950efd1..00000000 --- a/test/telegram.js +++ /dev/null @@ -1,2101 +0,0 @@ -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('#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 thumb', function test() { - const audio = `${__dirname}/data/audio.mp3`; - const thumbImg = `attach://${__dirname}/data/sticker_thumb.png`; - - return bot.sendAudio(USERID, audio, { thumb: thumbImg }).then(resp => { - assert.ok(is.object(resp)); - assert.ok(is.object(resp.audio)); - assert.ok(is.object(resp.audio.thumb)); - }); - }); - }); - - 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('#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)); - }); - }); - it('(v0.25.0 and lower) should get user profile photos', function test() { - return bot.getUserProfilePhotos(USERID, opts.offset, opts.limit).then(resp => { - assert.ok(is.object(resp)); - assert.ok(is.number(resp.total_count)); - assert.ok(is.array(resp.photos)); - }); - }); - }); - - 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.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('#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('#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 thumb', 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); - }); - }); - }); -}); // End Telegram diff --git a/test/test.format-send-data.js b/test/test.format-send-data.js deleted file mode 100644 index 97828427..00000000 --- a/test/test.format-send-data.js +++ /dev/null @@ -1,139 +0,0 @@ -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); - }); - }); -}); diff --git a/test/utils.js b/test/utils.js deleted file mode 100644 index 78dec279..00000000 --- a/test/utils.js +++ /dev/null @@ -1,230 +0,0 @@ -/* 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); -}