From 9f29616ce9282b6c7f74a07fcc085be7bdd33845 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Fri, 8 Jan 2021 06:57:53 +0300 Subject: [PATCH 01/79] add copyMessage method --- context.js | 11 +++++++++++ telegram.js | 9 +++++++++ test/telegraf.js | 2 ++ typings/telegram.d.ts | 15 +++++++++++++++ 4 files changed, 37 insertions(+) diff --git a/context.js b/context.js index 02f421079..1f2698d9b 100644 --- a/context.js +++ b/context.js @@ -590,6 +590,17 @@ class TelegrafContext { this.assert(message, 'forwardMessage') return this.telegram.forwardMessage(chatId, this.chat.id, message.message_id, extra) } + + copyMessage (chatId, extra) { + this.assert(this.message, 'copyMessage') + const message = this.message || + this.editedMessage || + this.channelPost || + this.editedChannelPost || + (this.callbackQuery && this.callbackQuery.message) + this.assert(message, 'copyMessage') + return this.telegram.copyMessage(chatId, message.chat.id, message.message_id, extra) + } } module.exports = TelegrafContext diff --git a/telegram.js b/telegram.js index 1224b766e..26a8a03fa 100644 --- a/telegram.js +++ b/telegram.js @@ -428,6 +428,15 @@ class Telegram extends ApiClient { } return this.callApi(replicators.copyMethods[type], opts) } + + copyMessage (chatId, fromChatId, messageId, extra) { + return this.callApi('copyMessage', { + chat_id: chatId, + from_chat_id: fromChatId, + message_id: messageId, + ...extra + }) + } } module.exports = Telegram diff --git a/test/telegraf.js b/test/telegraf.js index 92d894009..d7a533875 100644 --- a/test/telegraf.js +++ b/test/telegraf.js @@ -102,6 +102,7 @@ test.cb('should provide shortcuts for `message` update', (t) => { t.true('editMessageLiveLocation' in ctx) t.true('stopMessageLiveLocation' in ctx) t.true('forwardMessage' in ctx) + t.true('copyMessage' in ctx) t.end() }) bot.handleUpdate({ message: BaseTextMessage }) @@ -156,6 +157,7 @@ test.cb('should provide shortcuts for `callback_query` update', (t) => { t.true('editMessageLiveLocation' in ctx) t.true('stopMessageLiveLocation' in ctx) t.true('forwardMessage' in ctx) + t.true('copyMessage' in ctx) t.end() }) bot.handleUpdate({ callback_query: BaseTextMessage }) diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 4d7a20699..5bd164c71 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -246,6 +246,21 @@ export declare class Telegram extends ApiClient { extra?: object ): Promise + /** + * Use this method to send copy of exists message. + * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) + * @param fromChatId Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) + * @param messageId Message identifier in the chat specified in from_chat_id + * @param extra Additional params to send modified copy of message + * @returns the MessageId of the sent message on success + */ + copyMessage( + chatId: number | string, + fromChatId: number | string, + messageId: number, + extra?: object + ): 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. * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) From 52d31f82267f9a7c0438d9de4c9901cc6a5a43d2 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Fri, 8 Jan 2021 07:18:05 +0300 Subject: [PATCH 02/79] duplicate assignment --- context.js | 1 - 1 file changed, 1 deletion(-) diff --git a/context.js b/context.js index 1f2698d9b..761ec7bd7 100644 --- a/context.js +++ b/context.js @@ -592,7 +592,6 @@ class TelegrafContext { } copyMessage (chatId, extra) { - this.assert(this.message, 'copyMessage') const message = this.message || this.editedMessage || this.channelPost || From 8146103e47ada59d5fb36bc60c6dfba7589f6404 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Fri, 8 Jan 2021 07:38:36 +0300 Subject: [PATCH 03/79] add context copyMessage typings --- typings/context.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/typings/context.d.ts b/typings/context.d.ts index 7021badde..173453ed2 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -348,6 +348,17 @@ export declare class TelegrafContext { */ replyWithDice(extra?: tt.ExtraDice): Promise + /** + * Use this method to send copy of exists message. + * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) + * @param extra Additional params to send modified copy of message + * @returns the MessageId of the sent message on success + */ + copyMessage( + chatId: number | string, + extra?: object + ): Promise + // ------------------------------------------------------------------------------------------ // // ------------------------------------------------------------------------------------------ // // ------------------------------------------------------------------------------------------ // From 1efd56666f7eeb1f3c1d844005205daa5b60ec8c Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 04:26:45 +0300 Subject: [PATCH 04/79] Bot API 5.0 - Webhooks --- docs/README.md | 10 ++++++---- telegram.js | 13 ++++--------- typings/telegram-types.d.ts | 22 ++++++++++++++++++++++ typings/telegram.d.ts | 13 ++++++------- 4 files changed, 38 insertions(+), 20 deletions(-) diff --git a/docs/README.md b/docs/README.md index 6d0af7c7a..a75e7e8b1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1808,6 +1808,10 @@ Removes webhook integration. `telegram.deleteWebhook() => Promise` [Official documentation](https://core.telegram.org/bots/api#deletewebhook) +| Param | Type | Description | +| --- | --- | --- | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#deletewebhook) | + ##### sendAudio Sends audio. @@ -2106,15 +2110,13 @@ Use this method to upload a .png file with a sticker for later use in createNewS Specifies an url to receive incoming updates via an outgoing webhook. -`telegram.setWebhook(url, [cert], [maxConnections], [allowedUpdates]) => Promise` +`telegram.setWebhook(url, [extra]) => Promise` [Official documentation](https://core.telegram.org/bots/api#setwebhook) | Param | Type | Description | | --- | --- | --- | | url | `string` | Public url for webhook | -| [cert] | `File` | SSL public certificate | -| [maxConnections] | `number` | Maximum allowed number of simultaneous HTTPS connections to the webhook | -| [allowedUpdates] | `string[]` | List the types of updates you want your bot to receive | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#setwebhook) | ##### unbanChatMember diff --git a/telegram.js b/telegram.js index 26a8a03fa..7d723df8e 100644 --- a/telegram.js +++ b/telegram.js @@ -54,17 +54,12 @@ class Telegram extends ApiClient { }) } - setWebhook (url, certificate, maxConnections, allowedUpdates) { - return this.callApi('setWebhook', { - url, - certificate, - max_connections: maxConnections, - allowed_updates: allowedUpdates - }) + setWebhook (url, extra) { + return this.callApi('setWebhook', { url, ...extra }) } - deleteWebhook () { - return this.callApi('deleteWebhook') + deleteWebhook (extra) { + return this.callApi('deleteWebhook', extra) } sendMessage (chatId, text, extra) { diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index decfa226b..74ccc5d6b 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -207,6 +207,28 @@ export interface ChatPermissions { can_pin_messages?: boolean } +export interface ExtraSetWebhook { + /** SSL public certificate */ + certificate?: InputFile + + /** The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS */ + ip_address?: string + + /** Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. */ + max_connections?: number + + /** List the types of updates you want your bot to receive */ + allowed_updates?: UpdateType[] + + /** Pass True to drop all pending updates */ + drop_pending_updates?: boolean +} + +export interface ExtraDeleteWebhook { + /** Pass True to drop all pending updates */ + drop_pending_updates?: boolean +} + export interface ExtraRestrictChatMember { /** New user permissions */ permissions: ChatPermissions diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 5bd164c71..8545b2904 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -601,23 +601,22 @@ export declare class Telegram extends ApiClient { /** * Use this method to specify a url and receive incoming updates via an outgoing webhook * @param url HTTPS url to send updates to. Use an empty string to remove webhook integration - * @param cert Upload your public key certificate so that the root certificate in use can be checked - * @param maxConnections Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100 - * @param allowedUpdates List the types of updates you want your bot to receive + * @param extra Additional params to set webhook * @returns True on success */ setWebhook( url: string, - cert?: tt.InputFile, - maxConnections?: number, - allowedUpdates?: string[] + extra?: tt.ExtraSetWebhook ): Promise /** * Use this method to delete webhook + * @param extra Additional params to delete webhook * @returns True on success */ - deleteWebhook(): Promise + deleteWebhook( + extra?: tt.ExtraDeleteWebhook + ): Promise /** * Use this method to get information about set webhook From 909f33772d1d6771cdc4d8f806ba8f0f714ba2b1 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 05:27:50 +0300 Subject: [PATCH 05/79] Bot API 5.0 - unbanChatMember --- docs/README.md | 2 +- telegram.js | 4 ++-- typings/context.d.ts | 3 ++- typings/telegram-types.d.ts | 5 +++++ typings/telegram.d.ts | 3 ++- 5 files changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/README.md b/docs/README.md index a75e7e8b1..455f2adde 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2129,7 +2129,7 @@ Use this method to unban a previously kicked user in a supergroup. | --- | --- | --- | | chatId | `number/string` | Chat id | | userId | `number` | User id | - +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unbanchatmember) | ##### setPassportDataErrors diff --git a/telegram.js b/telegram.js index 7d723df8e..aff289459 100644 --- a/telegram.js +++ b/telegram.js @@ -234,8 +234,8 @@ class Telegram extends ApiClient { return this.callApi('leaveChat', { chat_id: chatId }) } - unbanChatMember (chatId, userId) { - return this.callApi('unbanChatMember', { chat_id: chatId, user_id: userId }) + unbanChatMember (chatId, userId, extra) { + return this.callApi('unbanChatMember', { chat_id: chatId, user_id: userId, ...extra }) } answerCbQuery (callbackQueryId, text, showAlert, extra) { diff --git a/typings/context.d.ts b/typings/context.d.ts index 173453ed2..926c6ff8d 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -471,9 +471,10 @@ export declare class TelegrafContext { /** * Use this method to unban a user from 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 userId Unique identifier of the target user + * @param extra Extra params * @returns True on success */ - unbanChatMember(userId: number): Promise + unbanChatMember(userId: number, extra?: tt.ExtraUnban): 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. diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 74ccc5d6b..823f882e4 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -570,6 +570,11 @@ export interface ExtraStopPoll { reply_markup?: TT.InlineKeyboardMarkup } +export interface ExtraUnban { + /** Do nothing if the user is not banned */ + only_if_banned?: Boolean +} + export interface IncomingMessage extends TT.Message { audio?: TT.Audio entities?: TT.MessageEntity[] diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 8545b2904..895bf8c11 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -655,9 +655,10 @@ export declare class Telegram extends ApiClient { * Use this method to unban a user from 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 chatId Unique identifier for the target group or username of the target supergroup or channel (in the format @username) * @param userId Unique identifier of the target user + * @param extra Extra params * @returns True on success */ - unbanChatMember(chatId: number | string, userId: number): Promise + unbanChatMember(chatId: number | string, userId: number, extra?: tt.ExtraUnban): 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. From 5dd9bda5f81c0cd5bb2e3d52a03a5e08ce1b49cf Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 05:47:32 +0300 Subject: [PATCH 06/79] add sendDocument params --- typings/telegram-types.d.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 823f882e4..8a9c39713 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -343,6 +343,21 @@ export interface ExtraDocument extends ExtraReplyMessage { * Document caption (may also be used when resending documents by file_id), 0-1024 characters */ caption?: string + + /** + * List of special entities that appear in the caption, which can be specified instead of parse_mode + */ + caption_entities?: TT.MessageEntity + + /** + * Disables automatic server-side content type detection for files uploaded using multipart/form-data + */ + disable_content_type_detection?: Boolean + + /** + * Pass True, if the message should be sent even if the specified replied-to message is not found + */ + allow_sending_without_reply?: Boolean /** * Does not exist, see https://core.telegram.org/bots/api#senddocument From e81dadbb4c55ff8483a2f0c4316101ee99701a08 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 06:09:57 +0300 Subject: [PATCH 07/79] add param to unpinChatMessage --- docs/README.md | 1 + telegram.js | 4 ++-- typings/context.d.ts | 3 ++- typings/telegram-types.d.ts | 7 +++++++ typings/telegram.d.ts | 3 ++- 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/README.md b/docs/README.md index 455f2adde..c55c52826 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1789,6 +1789,7 @@ Use this method to unpin a message in a supergroup chat. | Param | Type | Description | | --- | --- | --- | | chatId | `number/string` | Chat id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unpinchatmessage)| ##### leaveChat diff --git a/telegram.js b/telegram.js index aff289459..5575f4ec8 100644 --- a/telegram.js +++ b/telegram.js @@ -226,8 +226,8 @@ class Telegram extends ApiClient { return this.callApi('pinChatMessage', { chat_id: chatId, message_id: messageId, ...extra }) } - unpinChatMessage (chatId) { - return this.callApi('unpinChatMessage', { chat_id: chatId }) + unpinChatMessage (chatId, extra) { + return this.callApi('unpinChatMessage', { chat_id: chatId, ...extra }) } leaveChat (chatId) { diff --git a/typings/context.d.ts b/typings/context.d.ts index 926c6ff8d..bebf4e2c2 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -145,8 +145,9 @@ export declare class TelegrafContext { /** * Use this method to unpin a message in a group, a supergroup, or a channel. * @returns True on success + * @param extra Extra params */ - unpinChatMessage(): Promise + unpinChatMessage(extra?: tt.ExtraUnpinMessage): Promise /** * Use this method to reply on messages in the same chat. diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 8a9c39713..917d2a84f 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -295,6 +295,13 @@ export interface ExtraEditMessage extends ExtraReplyMessage { // no specified properties } +export interface ExtraUnpinMessage { + /** + * Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned. + */ + message_id?: number +} + export interface ExtraAudio extends ExtraReplyMessage { /** * Audio caption, 0-1024 characters diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 895bf8c11..3a3a2d346 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -346,9 +346,10 @@ export declare class Telegram extends ApiClient { /** * Use this method to unpin a message in a group, a supergroup, or a channel. * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) + * @param extra Extra params * @returns True on success */ - unpinChatMessage(chatId: number | string): Promise + unpinChatMessage(chatId: number | string, extra?: tt.ExtraUnpinMessage): Promise /** * Use this method to send text messages From 281bd15154253569c27fb9470872c9b481a0f147 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 06:29:19 +0300 Subject: [PATCH 08/79] Bot API 5.0 - unpinAllChatMessages --- context.js | 5 +++++ docs/README.md | 13 +++++++++++++ telegram.js | 4 ++++ test/telegraf.js | 2 ++ typings/context.d.ts | 6 ++++++ typings/telegram.d.ts | 7 +++++++ 6 files changed, 37 insertions(+) diff --git a/context.js b/context.js index 761ec7bd7..6e4b151d9 100644 --- a/context.js +++ b/context.js @@ -380,6 +380,11 @@ class TelegrafContext { return this.telegram.unpinChatMessage(this.chat.id, ...args) } + unpinAllChatMessages () { + this.assert(this.chat, 'unpinAllChatMessages') + return this.telegram.unpinAllChatMessages(this.chat.id) + } + leaveChat (...args) { this.assert(this.chat, 'leaveChat') return this.telegram.leaveChat(this.chat.id, ...args) diff --git a/docs/README.md b/docs/README.md index c55c52826..18d817b95 100644 --- a/docs/README.md +++ b/docs/README.md @@ -280,6 +280,7 @@ Context shortcuts for **message** update: | `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | | `stopPoll` | [`telegram.stopPoll`](#stoppoll) | | `unpinChatMessage` | [`telegram.unpinChatMessage`](#unpinchatmessage) | +| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](#unpinallchatmessages) | | `uploadStickerFile` | [`telegram.uploadStickerFile`](#uploadstickerfile) | | `unbanChatMember` | [`telegram.unbanChatMember`](#unbanchatmember) | @@ -332,6 +333,7 @@ Context shortcuts for **callback_query** update: | `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | | `stopPoll` | [`telegram.stopPoll`](#stoppoll) | | `unpinChatMessage` | [`telegram.unpinChatMessage`](#unpinchatmessage) | +| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](#unpinallchatmessages) | | `uploadStickerFile` | [`telegram.uploadStickerFile`](#uploadstickerfile) | | `unbanChatMember` | [`telegram.unbanChatMember`](#unbanchatmember) | @@ -1791,6 +1793,17 @@ Use this method to unpin a message in a supergroup chat. | chatId | `number/string` | Chat id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unpinchatmessage)| +##### unpinAllChatMessages + +Use this method to clear the list of pinned messages in a chat + +`telegram.unpinAllChatMessages(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#unpinallchatmessages) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + ##### leaveChat Use this method for your bot to leave a group, supergroup or channel. diff --git a/telegram.js b/telegram.js index 5575f4ec8..3d282ba13 100644 --- a/telegram.js +++ b/telegram.js @@ -230,6 +230,10 @@ class Telegram extends ApiClient { return this.callApi('unpinChatMessage', { chat_id: chatId, ...extra }) } + unpinAllChatMessages (chatId) { + return this.callApi('unpinAllChatMessages', { chat_id: chatId }) + } + leaveChat (chatId) { return this.callApi('leaveChat', { chat_id: chatId }) } diff --git a/test/telegraf.js b/test/telegraf.js index d7a533875..f48e7e944 100644 --- a/test/telegraf.js +++ b/test/telegraf.js @@ -86,6 +86,7 @@ test.cb('should provide shortcuts for `message` update', (t) => { t.true('setChatDescription' in ctx) t.true('pinChatMessage' in ctx) t.true('unpinChatMessage' in ctx) + t.true('unpinAllChatMessages' in ctx) t.true('leaveChat' in ctx) t.true('getChatAdministrators' in ctx) t.true('getChatMember' in ctx) @@ -142,6 +143,7 @@ test.cb('should provide shortcuts for `callback_query` update', (t) => { t.true('setChatDescription' in ctx) t.true('pinChatMessage' in ctx) t.true('unpinChatMessage' in ctx) + t.true('unpinAllChatMessages' in ctx) t.true('leaveChat' in ctx) t.true('getChatAdministrators' in ctx) t.true('getChatMember' in ctx) diff --git a/typings/context.d.ts b/typings/context.d.ts index bebf4e2c2..d53bf6d30 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -149,6 +149,12 @@ export declare class TelegrafContext { */ unpinChatMessage(extra?: tt.ExtraUnpinMessage): Promise + /** + * Use this method to clear the list of pinned messages in a chat + * @returns True on success + */ + unpinAllChatMessages(): Promise + /** * Use this method to reply on messages in the same chat. * @param text Text of the message to be sent diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 3a3a2d346..d613cf7b0 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -351,6 +351,13 @@ export declare class Telegram extends ApiClient { */ unpinChatMessage(chatId: number | string, extra?: tt.ExtraUnpinMessage): Promise + /** + * Use this method to clear the list of pinned messages in a chat + * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) + * @returns True on success + */ + unpinAllChatMessages(chatId: number | string): Promise + /** * Use this method to send text messages * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) From b6cacbb7477aab7a3c7f90e88e6f3d4d65b42c7f Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 12:07:37 +0300 Subject: [PATCH 09/79] correct params in sendMediaGroup --- typings/telegram-types.d.ts | 5 +++++ typings/telegram.d.ts | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 917d2a84f..d8bbc4a49 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -450,6 +450,11 @@ export interface ExtraMediaGroup extends ExtraReplyMessage { * Does not exist, see https://core.telegram.org/bots/api#sendmediagroup */ reply_markup?: never + + /** + * Pass True, if the message should be sent even if the specified replied-to message is not found + */ + allow_sending_without_reply?: Boolean } export interface ExtraAnimation extends ExtraReplyMessage { diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index d613cf7b0..ec8ff3b8b 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -482,7 +482,7 @@ export declare class Telegram extends ApiClient { */ sendMediaGroup( chatId: number | string, - media: tt.MessageMedia[], + media: (tt.InputMediaAudio | tt.InputMediaDocument | tt.InputMediaPhoto | tt.InputMediaVideo)[], extra?: tt.ExtraMediaGroup ): Promise> From 1389203aad195ea2d4ab2133a5e81e8117d4b774 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 15:18:30 +0300 Subject: [PATCH 10/79] correct params in sendLocation --- typings/telegram-types.d.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index d8bbc4a49..a8dbfa997 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -407,11 +407,31 @@ export interface ExtraInvoice extends ExtraReplyMessage { } export interface ExtraLocation extends ExtraReplyMessage { + /** + * The radius of uncertainty for the location, measured in meters; 0-1500 + */ + horizontal_accuracy?: number + /** * Period in seconds for which the location will be updated (should be between 60 and 86400) */ live_period?: number + /** + * For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + */ + heading?: number + + /** + * For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + */ + proximity_alert_radius?: number + + /** + * Pass True, if the message should be sent even if the specified replied-to message is not found + */ + allow_sending_without_reply?: boolean + /** * Does not exist, see https://core.telegram.org/bots/api#sendlocation */ From beab76e64c105fa4169db3b050de98560451d344 Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 15:37:53 +0300 Subject: [PATCH 11/79] Use typegram instead of telegram-typings --- package.json | 2 +- typings/telegram-types.d.ts | 91 +++++++------------------------------ 2 files changed, 18 insertions(+), 75 deletions(-) diff --git a/package.json b/package.json index bee6b14da..5bd7f1271 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,7 @@ "module-alias": "^2.2.2", "node-fetch": "^2.2.0", "sandwich-stream": "^2.0.1", - "telegram-typings": "^3.6.0" + "typegram": "^3.1.5" }, "devDependencies": { "@types/node": "^13.1.0", diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index d8bbc4a49..b13ddae13 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -1,5 +1,4 @@ -import * as TT from "telegram-typings"; -export * from "telegram-typings"; +import * as TT from 'typegram' export type ParseMode = 'Markdown' | 'MarkdownV2' | 'HTML' @@ -350,7 +349,7 @@ export interface ExtraDocument extends ExtraReplyMessage { * Document caption (may also be used when resending documents by file_id), 0-1024 characters */ caption?: string - + /** * List of special entities that appear in the caption, which can be specified instead of parse_mode */ @@ -602,77 +601,21 @@ export interface ExtraUnban { only_if_banned?: Boolean } -export interface IncomingMessage extends TT.Message { - audio?: TT.Audio - entities?: TT.MessageEntity[] - caption?: string - document?: TT.Document - game?: TT.Game - photo?: TT.PhotoSize[] - animation?: TT.Animation - sticker?: TT.Sticker - video?: TT.Video - video_note?: TT.VideoNote - contact?: TT.Contact - location?: TT.Location - venue?: TT.Venue - pinned_message?: TT.Message - invoice?: TT.Invoice - successful_payment?: TT.SuccessfulPayment - dice?: Dice -} - -export interface MessageAudio extends TT.Message { - audio: TT.Audio -} - -export interface MessageDocument extends TT.Message { - document: TT.Document -} - -export interface MessageGame extends TT.Message { - game: TT.Game -} - -export interface MessageInvoice extends TT.Message { - invoice: TT.Invoice -} - -export interface MessageLocation extends TT.Message { - location: TT.Location -} - -export interface MessagePhoto extends TT.Message { - photo: TT.PhotoSize[] -} - -export interface MessageAnimation extends TT.Message { - animation: TT.Animation -} - -export interface MessageSticker extends TT.Message { - sticker: TT.Sticker -} - -export interface MessageVideo extends TT.Message { - video: TT.Video -} - -export interface MessageVideoNote extends TT.Message { - video_note: TT.VideoNote -} - -export interface MessageVoice extends TT.Message { - voice: TT.Voice -} - -export interface MessageDice extends TT.Message { - dice: Dice -} - -export interface MessagePoll extends TT.Message { - poll: Poll -} +export type IncomingMessage = TT.Message + +export type MessageAudio = TT.Message.AudioMessage +export type MessageDocument = TT.Message.DocumentMessage +export type MessageGame = TT.Message.GameMessage +export type MessageInvoice = TT.Message.InvoiceMessage +export type MessageLocation = TT.Message.LocationMessage +export type MessagePhoto = TT.Message.PhotoMessage +export type MessageAnimation = TT.Message.AnimationMessage +export type MessageSticker = TT.Message.StickerMessage +export type MessageVideo = TT.Message.VideoMessage +export type MessageVideoNote = TT.Message.VideoNoteMessage +export type MessageVoice = TT.Message.VoiceMessage +export type MessageDice = TT.Message.DiceMessage +export type MessagePoll = TT.Message.PollMessage export interface NewInvoiceParameters { /** From f46b2d90af7cae2e985370b7a9b653fba7ceca41 Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 15:43:22 +0300 Subject: [PATCH 12/79] Fix: add reexport --- typings/telegram-types.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index b13ddae13..bfd172d0f 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -1,4 +1,5 @@ import * as TT from 'typegram' +export * from 'typegram' export type ParseMode = 'Markdown' | 'MarkdownV2' | 'HTML' From 611b91da2b74b446cb7afe85131411791ca8f28a Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 15:46:13 +0300 Subject: [PATCH 13/79] Fix JSDoc for promoteChatMember --- typings/telegram.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index ec8ff3b8b..4e457642d 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -672,6 +672,7 @@ export declare class Telegram extends ApiClient { * 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 chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) * @param userId Unique identifier of the target user + * @param extra Extra parameters for promoteChatMember * @returns True on success */ promoteChatMember( From 0810733a070778cd66b690142b0cd4cc22ab46cb Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 16:05:53 +0300 Subject: [PATCH 14/79] missing space --- typings/test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings/test.ts b/typings/test.ts index 6eb0d387c..47917b5e6 100644 --- a/typings/test.ts +++ b/typings/test.ts @@ -108,7 +108,7 @@ bot.hears('something', async (ctx) => { reply_markup: Markup.inlineKeyboard([]) }) - ctx.editMessageLiveLocation(90,90, { + ctx.editMessageLiveLocation(90, 90, { reply_markup: Markup.inlineKeyboard([]) }) From 498308e177b8543745504d8216721ab7629f7e41 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 16:52:31 +0300 Subject: [PATCH 15/79] correct params in editMessageLiveLocation --- context.js | 8 +++++--- docs/README.md | 1 + telegram.js | 5 +++-- typings/context.d.ts | 15 +++++++++------ typings/telegram-types.d.ts | 7 +++++++ typings/telegram.d.ts | 21 +++++++++++++++++++++ 6 files changed, 46 insertions(+), 11 deletions(-) diff --git a/context.js b/context.js index 6e4b151d9..f374ab9b1 100644 --- a/context.js +++ b/context.js @@ -272,7 +272,7 @@ class TelegrafContext { ) } - editMessageLiveLocation (latitude, longitude, markup) { + editMessageLiveLocation (latitude, longitude, markup, extra) { this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageLiveLocation') return this.inlineMessageId ? this.telegram.editMessageLiveLocation( @@ -281,7 +281,8 @@ class TelegrafContext { undefined, undefined, this.inlineMessageId, - markup + markup, + extra ) : this.telegram.editMessageLiveLocation( latitude, @@ -289,7 +290,8 @@ class TelegrafContext { this.chat.id, this.callbackQuery.message.message_id, undefined, - markup + markup, + extra ) } diff --git a/docs/README.md b/docs/README.md index 18d817b95..ef2e0c539 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1442,6 +1442,7 @@ Use this method to edit live location messages sent by the bot or via the bot. | messageId | `string` | Message id | | inlineMessageId | `string` | Inline message id | | [markup] | `object` | Keyboard markup | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagelivelocation)| ##### editMessageReplyMarkup diff --git a/telegram.js b/telegram.js index 3d282ba13..dbf3cea37 100644 --- a/telegram.js +++ b/telegram.js @@ -315,14 +315,15 @@ class Telegram extends ApiClient { }) } - editMessageLiveLocation (latitude, longitude, chatId, messageId, inlineMessageId, markup) { + editMessageLiveLocation (latitude, longitude, chatId, messageId, inlineMessageId, markup, extra = {}) { return this.callApi('editMessageLiveLocation', { latitude, longitude, chat_id: chatId, message_id: messageId, inline_message_id: inlineMessageId, - reply_markup: markup + reply_markup: markup, + ...extra }) } diff --git a/typings/context.d.ts b/typings/context.d.ts index d53bf6d30..b9897946f 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -456,15 +456,18 @@ export declare class TelegrafContext { ): Promise /** - * Use this method to edit live location messages. + * Use this method to edit live location messages * @returns On success, if the edited message was sent by the bot, the edited message is returned, otherwise True is returned. - * @param lat New latitude - * @param lon New longitude + * @param latitude New latitude + * @param longitude New longitude + * @param markup Markup of inline keyboard + * @param extra Extra params */ editMessageLiveLocation( - lat: number, - lon: number, - extra?: tt.ExtraLocation + latitude: number, + longitude: number, + markup: tt.InlineKeyboardMarkup, + extra?: tt.ExtraEditLocation ): Promise /** diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index a8dbfa997..45761bd42 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -443,6 +443,13 @@ export interface ExtraLocation extends ExtraReplyMessage { parse_mode?: never } +export interface ExtraEditLocation extends ExtraLocation { + /** + * Does not exist, see https://core.telegram.org/bots/api#sendlocation + */ + live_period?: never +} + export interface ExtraPhoto extends ExtraReplyMessage { /** * Photo caption (may also be used when resending photos by file_id), 0-1024 characters diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index ec8ff3b8b..3ee7bf674 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -156,6 +156,27 @@ export declare class Telegram extends ApiClient { markup?: string ): Promise + /** + * Use this method to edit live location messages + * @param latitude Latitude of location + * @param longitude Longitude of location + * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) + * @param messageId Required if inlineMessageId is not specified. Identifier of the sent message + * @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message + * @param markup Markup of inline keyboard + * @param extra Extra params + * @returns On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + */ + editMessageLiveLocation( + latitude: number, + longitude: number, + chatId: number | string | void, + messageId: number, + inlineMessageId: string | void, + markup: tt.InlineKeyboardMarkup, + extra?: tt.ExtraLocation + ): 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. From c88c326833a7814f8b3acbbc1da50197e1e1a989 Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 17:08:17 +0300 Subject: [PATCH 16/79] Remove IncomingMessage --- typings/context.d.ts | 2 +- typings/telegram-types.d.ts | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/typings/context.d.ts b/typings/context.d.ts index d53bf6d30..9a4ce9464 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -21,7 +21,7 @@ export declare class TelegrafContext { inlineQuery?: tt.InlineQuery match?: RegExpExecArray | null me?: string - message?: tt.IncomingMessage + message?: tt.Message poll?: tt.Poll pollAnswer?: tt.PollAnswer preCheckoutQuery?: tt.PreCheckoutQuery diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index bfd172d0f..691cb9ab9 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -602,8 +602,6 @@ export interface ExtraUnban { only_if_banned?: Boolean } -export type IncomingMessage = TT.Message - export type MessageAudio = TT.Message.AudioMessage export type MessageDocument = TT.Message.DocumentMessage export type MessageGame = TT.Message.GameMessage From 3b320a95af843f53204112bcc983b2293b3a2e59 Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 17:14:51 +0300 Subject: [PATCH 17/79] Add emoji param to ExtraDice --- typings/telegram-types.d.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index e1449738c..af914ec8f 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -421,12 +421,12 @@ export interface ExtraLocation extends ExtraReplyMessage { * For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. */ heading?: number - + /** * For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */ proximity_alert_radius?: number - + /** * Pass True, if the message should be sent even if the specified replied-to message is not found */ @@ -581,6 +581,14 @@ export interface ExtraVoice extends ExtraReplyMessage { } export interface ExtraDice extends ExtraReplyMessage { + /** + * Emoji on which the dice throw animation is based. + * Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, or “🎰”. + * Dice can have values 1-6 for “🎲” and “🎯”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. + * Defaults to “🎲” + * */ + emoji?: string + /** * Does not exist, see https://core.telegram.org/bots/api#senddice */ From b32ea344e44adbd9e7de4c506bb689fd4b42d024 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 17:51:00 +0300 Subject: [PATCH 18/79] its ok ...undefined --- telegram.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telegram.js b/telegram.js index dbf3cea37..8b817e7c4 100644 --- a/telegram.js +++ b/telegram.js @@ -315,7 +315,7 @@ class Telegram extends ApiClient { }) } - editMessageLiveLocation (latitude, longitude, chatId, messageId, inlineMessageId, markup, extra = {}) { + editMessageLiveLocation (latitude, longitude, chatId, messageId, inlineMessageId, markup, extra) { return this.callApi('editMessageLiveLocation', { latitude, longitude, From b7f2852aa4f440fe999862b41f582136ad189ed7 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 18:02:16 +0300 Subject: [PATCH 19/79] correct params in promoteChatMember --- typings/context.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings/context.d.ts b/typings/context.d.ts index 1986b33e2..2c254f525 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -488,8 +488,8 @@ export declare class TelegrafContext { /** * 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 chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) * @param userId Unique identifier of the target user + * @param extra Extra parameters for promoteChatMember * @returns True on success */ promoteChatMember( From 6fd65b7161a8790dd40ef61046aaed94d384d1cb Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 17:16:41 +0300 Subject: [PATCH 20/79] Change max poll question length to 300 --- typings/telegram.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index beae98499..62b796578 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -510,7 +510,7 @@ export declare class Telegram extends ApiClient { /** * Use this method to send a native poll. * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) - * @param question Poll question, 1-255 characters + * @param question Poll question, 1-300 characters * @param options A JSON-serialized list of answer options, 2-10 strings 1-100 characters each * @param extra Additional params to send poll * @returns On success, the sent Message is returned. From fc86259cd139eeb386df2a91c75e03f2ee758a82 Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 18:44:05 +0300 Subject: [PATCH 21/79] Fix test for sendVideoNote --- typings/test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/typings/test.ts b/typings/test.ts index 47917b5e6..66bd503af 100644 --- a/typings/test.ts +++ b/typings/test.ts @@ -166,9 +166,7 @@ bot.hears('something', async (ctx) => { duration: 0, length: 0, thumb: '', - parse_mode: "HTML", disable_notification: false, - disable_web_page_preview: false, reply_markup: Markup.inlineKeyboard([]), reply_to_message_id: 0, }) From 22d4e5d496502b64310374ef2211dfe3c23ec16c Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 18:44:23 +0300 Subject: [PATCH 22/79] Fix test for editMessageLiveLocation --- typings/test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/typings/test.ts b/typings/test.ts index 66bd503af..51e296344 100644 --- a/typings/test.ts +++ b/typings/test.ts @@ -108,8 +108,8 @@ bot.hears('something', async (ctx) => { reply_markup: Markup.inlineKeyboard([]) }) - ctx.editMessageLiveLocation(90, 90, { - reply_markup: Markup.inlineKeyboard([]) + ctx.editMessageLiveLocation(90, 90, Markup.inlineKeyboard([]), { + heading: 1 }) ctx.stopMessageLiveLocation({ From b1286d9f134820da431d26e7bfe524424e6f53ea Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 18:18:08 +0300 Subject: [PATCH 23/79] add copyMessage method --- docs/README.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index ef2e0c539..f76c9ae5f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1485,7 +1485,6 @@ Forwards message. | messageId | `number` | Message id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#forwardmessage)| - ##### sendCopy Sends message copy. @@ -1498,6 +1497,19 @@ Sends message copy. | message | `object` | Message | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| +##### copyMessage + +Use this method to copy messages of any kind. + +`telegram.copyMessage(chatId, message, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Target Chat id | +| fromChatId | `number/string` | Source Chat id | +| messageId | `number` | Message id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#copymessage)| + ##### getWebhookInfo Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. From ef7b1efba61dbdfbe3f3dcddf82d4fd5bf1a8574 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 18:46:08 +0300 Subject: [PATCH 24/79] =?UTF-8?q?convert=20sendCopy=20to=20proxy=20method?= =?UTF-8?q?=20=F0=9F=98=A5=20bb=20replicators?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/replicators.js | 140 -------------------------------------------- telegram.js | 14 +---- 2 files changed, 2 insertions(+), 152 deletions(-) delete mode 100644 core/replicators.js diff --git a/core/replicators.js b/core/replicators.js deleted file mode 100644 index 1d93758e2..000000000 --- a/core/replicators.js +++ /dev/null @@ -1,140 +0,0 @@ -const { formatHTML } = require('../markup') - -module.exports = { - copyMethods: { - audio: 'sendAudio', - contact: 'sendContact', - document: 'sendDocument', - location: 'sendLocation', - photo: 'sendPhoto', - sticker: 'sendSticker', - text: 'sendMessage', - venue: 'sendVenue', - video: 'sendVideo', - video_note: 'sendVideoNote', - animation: 'sendAnimation', - voice: 'sendVoice', - poll: 'sendPoll' - }, - text: (message) => { - const entities = message.entities || [] - return { - reply_markup: message.reply_markup, - parse_mode: entities.length > 0 ? 'HTML' : '', - text: formatHTML(message.text, entities) - } - }, - contact: (message) => { - return { - reply_markup: message.reply_markup, - phone_number: message.contact.phone_number, - first_name: message.contact.first_name, - last_name: message.contact.last_name - } - }, - location: (message) => { - return { - reply_markup: message.reply_markup, - latitude: message.location.latitude, - longitude: message.location.longitude - } - }, - venue: (message) => { - return { - reply_markup: message.reply_markup, - latitude: message.venue.location.latitude, - longitude: message.venue.location.longitude, - title: message.venue.title, - address: message.venue.address, - foursquare_id: message.venue.foursquare_id - } - }, - voice: (message) => { - const entities = message.caption_entities || [] - return { - reply_markup: message.reply_markup, - voice: message.voice.file_id, - duration: message.voice.duration, - caption: formatHTML(message.caption, entities), - parse_mode: entities.length > 0 ? 'HTML' : '' - } - }, - audio: (message) => { - const entities = message.caption_entities || [] - return { - reply_markup: message.reply_markup, - audio: message.audio.file_id, - thumb: message.audio.thumb, - duration: message.audio.duration, - performer: message.audio.performer, - title: message.audio.title, - caption: formatHTML(message.caption, entities), - parse_mode: entities.length > 0 ? 'HTML' : '' - } - }, - video: (message) => { - const entities = message.caption_entities || [] - return { - reply_markup: message.reply_markup, - video: message.video.file_id, - thumb: message.video.thumb, - caption: formatHTML(message.caption, entities), - parse_mode: entities.length > 0 ? 'HTML' : '', - duration: message.video.duration, - width: message.video.width, - height: message.video.height, - supports_streaming: !!message.video.supports_streaming - } - }, - document: (message) => { - const entities = message.caption_entities || [] - return { - reply_markup: message.reply_markup, - document: message.document.file_id, - caption: formatHTML(message.caption, entities), - parse_mode: entities.length > 0 ? 'HTML' : '' - } - }, - sticker: (message) => { - return { - reply_markup: message.reply_markup, - sticker: message.sticker.file_id - } - }, - photo: (message) => { - const entities = message.caption_entities || [] - return { - reply_markup: message.reply_markup, - photo: message.photo[message.photo.length - 1].file_id, - parse_mode: entities.length > 0 ? 'HTML' : '', - caption: formatHTML(message.caption, entities) - } - }, - video_note: (message) => { - return { - reply_markup: message.reply_markup, - video_note: message.video_note.file_id, - thumb: message.video_note.thumb, - length: message.video_note.length, - duration: message.video_note.duration - } - }, - animation: (message) => { - return { - reply_markup: message.reply_markup, - animation: message.animation.file_id, - thumb: message.animation.thumb, - duration: message.animation.duration - } - }, - poll: (message) => { - return { - question: message.poll.question, - type: message.poll.type, - is_anonymous: message.poll.is_anonymous, - allows_multiple_answers: message.poll.allows_multiple_answers, - correct_option_id: message.poll.correct_option_id, - options: message.poll.options.map(({ text }) => text) - } - } -} diff --git a/telegram.js b/telegram.js index 8b817e7c4..a3e7cbda3 100644 --- a/telegram.js +++ b/telegram.js @@ -1,4 +1,3 @@ -const replicators = require('./core/replicators') const ApiClient = require('./core/network/client') class Telegram extends ApiClient { @@ -414,19 +413,10 @@ class Telegram extends ApiClient { } sendCopy (chatId, message, extra) { - if (!message) { + if (!message || !message.chat || !message.chat.id || message.message_id) { throw new Error('Message is required') } - const type = Object.keys(replicators.copyMethods).find((type) => message[type]) - if (!type) { - throw new Error('Unsupported message type') - } - const opts = { - chat_id: chatId, - ...replicators[type](message), - ...extra - } - return this.callApi(replicators.copyMethods[type], opts) + return this.copyMessage(chatId, message.chat.id, message.message_id, extra) } copyMessage (chatId, fromChatId, messageId, extra) { From d9e189ea55b500f5be1b2c4a59a24581b473e869 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 19:02:21 +0300 Subject: [PATCH 25/79] =?UTF-8?q?Revert=20"convert=20sendCopy=20to=20proxy?= =?UTF-8?q?=20method=20=F0=9F=98=A5=20bb=20replicators"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit ef7b1efba61dbdfbe3f3dcddf82d4fd5bf1a8574. --- core/replicators.js | 140 ++++++++++++++++++++++++++++++++++++++++++++ telegram.js | 14 ++++- 2 files changed, 152 insertions(+), 2 deletions(-) create mode 100644 core/replicators.js diff --git a/core/replicators.js b/core/replicators.js new file mode 100644 index 000000000..1d93758e2 --- /dev/null +++ b/core/replicators.js @@ -0,0 +1,140 @@ +const { formatHTML } = require('../markup') + +module.exports = { + copyMethods: { + audio: 'sendAudio', + contact: 'sendContact', + document: 'sendDocument', + location: 'sendLocation', + photo: 'sendPhoto', + sticker: 'sendSticker', + text: 'sendMessage', + venue: 'sendVenue', + video: 'sendVideo', + video_note: 'sendVideoNote', + animation: 'sendAnimation', + voice: 'sendVoice', + poll: 'sendPoll' + }, + text: (message) => { + const entities = message.entities || [] + return { + reply_markup: message.reply_markup, + parse_mode: entities.length > 0 ? 'HTML' : '', + text: formatHTML(message.text, entities) + } + }, + contact: (message) => { + return { + reply_markup: message.reply_markup, + phone_number: message.contact.phone_number, + first_name: message.contact.first_name, + last_name: message.contact.last_name + } + }, + location: (message) => { + return { + reply_markup: message.reply_markup, + latitude: message.location.latitude, + longitude: message.location.longitude + } + }, + venue: (message) => { + return { + reply_markup: message.reply_markup, + latitude: message.venue.location.latitude, + longitude: message.venue.location.longitude, + title: message.venue.title, + address: message.venue.address, + foursquare_id: message.venue.foursquare_id + } + }, + voice: (message) => { + const entities = message.caption_entities || [] + return { + reply_markup: message.reply_markup, + voice: message.voice.file_id, + duration: message.voice.duration, + caption: formatHTML(message.caption, entities), + parse_mode: entities.length > 0 ? 'HTML' : '' + } + }, + audio: (message) => { + const entities = message.caption_entities || [] + return { + reply_markup: message.reply_markup, + audio: message.audio.file_id, + thumb: message.audio.thumb, + duration: message.audio.duration, + performer: message.audio.performer, + title: message.audio.title, + caption: formatHTML(message.caption, entities), + parse_mode: entities.length > 0 ? 'HTML' : '' + } + }, + video: (message) => { + const entities = message.caption_entities || [] + return { + reply_markup: message.reply_markup, + video: message.video.file_id, + thumb: message.video.thumb, + caption: formatHTML(message.caption, entities), + parse_mode: entities.length > 0 ? 'HTML' : '', + duration: message.video.duration, + width: message.video.width, + height: message.video.height, + supports_streaming: !!message.video.supports_streaming + } + }, + document: (message) => { + const entities = message.caption_entities || [] + return { + reply_markup: message.reply_markup, + document: message.document.file_id, + caption: formatHTML(message.caption, entities), + parse_mode: entities.length > 0 ? 'HTML' : '' + } + }, + sticker: (message) => { + return { + reply_markup: message.reply_markup, + sticker: message.sticker.file_id + } + }, + photo: (message) => { + const entities = message.caption_entities || [] + return { + reply_markup: message.reply_markup, + photo: message.photo[message.photo.length - 1].file_id, + parse_mode: entities.length > 0 ? 'HTML' : '', + caption: formatHTML(message.caption, entities) + } + }, + video_note: (message) => { + return { + reply_markup: message.reply_markup, + video_note: message.video_note.file_id, + thumb: message.video_note.thumb, + length: message.video_note.length, + duration: message.video_note.duration + } + }, + animation: (message) => { + return { + reply_markup: message.reply_markup, + animation: message.animation.file_id, + thumb: message.animation.thumb, + duration: message.animation.duration + } + }, + poll: (message) => { + return { + question: message.poll.question, + type: message.poll.type, + is_anonymous: message.poll.is_anonymous, + allows_multiple_answers: message.poll.allows_multiple_answers, + correct_option_id: message.poll.correct_option_id, + options: message.poll.options.map(({ text }) => text) + } + } +} diff --git a/telegram.js b/telegram.js index a3e7cbda3..8b817e7c4 100644 --- a/telegram.js +++ b/telegram.js @@ -1,3 +1,4 @@ +const replicators = require('./core/replicators') const ApiClient = require('./core/network/client') class Telegram extends ApiClient { @@ -413,10 +414,19 @@ class Telegram extends ApiClient { } sendCopy (chatId, message, extra) { - if (!message || !message.chat || !message.chat.id || message.message_id) { + if (!message) { throw new Error('Message is required') } - return this.copyMessage(chatId, message.chat.id, message.message_id, extra) + const type = Object.keys(replicators.copyMethods).find((type) => message[type]) + if (!type) { + throw new Error('Unsupported message type') + } + const opts = { + chat_id: chatId, + ...replicators[type](message), + ...extra + } + return this.callApi(replicators.copyMethods[type], opts) } copyMessage (chatId, fromChatId, messageId, extra) { From 86196a18f477c67c6f0286eb264ebd9b2262ba2b Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 19:12:55 +0300 Subject: [PATCH 26/79] sendCopy via proxy method --- telegram.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/telegram.js b/telegram.js index 8b817e7c4..13a6749f9 100644 --- a/telegram.js +++ b/telegram.js @@ -417,6 +417,9 @@ class Telegram extends ApiClient { if (!message) { throw new Error('Message is required') } + if (message.chat && message.chat.id && message.message_id) { + return this.copyMessage(chatId, message.chat.id, message.message_id, extra) + } const type = Object.keys(replicators.copyMethods).find((type) => message[type]) if (!type) { throw new Error('Unsupported message type') From c2c3174a2919c3c514891f59e77adccb37eb20b1 Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 18:48:13 +0300 Subject: [PATCH 27/79] Update typings for Extra --- typings/composer.d.ts | 2 +- typings/context.d.ts | 6 +- typings/extra.d.ts | 4 +- typings/markup.d.ts | 2 +- typings/telegram-types.d.ts | 313 +++++++++--------------------------- 5 files changed, 81 insertions(+), 246 deletions(-) diff --git a/typings/composer.d.ts b/typings/composer.d.ts index 9212add6e..a0438b15a 100644 --- a/typings/composer.d.ts +++ b/typings/composer.d.ts @@ -169,7 +169,7 @@ export declare class Composer static reply( text: string, - extra?: tt.ExtraReplyMessage + extra?: tt.ExtraSendMessage ): MiddlewareFn /** diff --git a/typings/context.d.ts b/typings/context.d.ts index 2c254f525..e2ec6470d 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -161,7 +161,7 @@ export declare class TelegrafContext { * @param extra SendMessage additional params * @returns sent Message if Success */ - reply(text: string, extra?: tt.ExtraReplyMessage): Promise + reply(text: string, extra?: tt.ExtraSendMessage): Promise /** * Use this method to send audio files to the same chat, if you want Telegram clients to display them in the music player. @@ -220,7 +220,7 @@ export declare class TelegrafContext { * @param extra Additional params to send message * @returns a Message on success */ - replyWithHTML(html: string, extra?: tt.ExtraReplyMessage): Promise + replyWithHTML(html: string, extra?: tt.ExtraSendMessage): Promise /** * Use this method to send invoices @@ -254,7 +254,7 @@ export declare class TelegrafContext { */ replyWithMarkdown( markdown: string, - extra?: tt.ExtraReplyMessage + extra?: tt.ExtraSendMessage ): Promise /** diff --git a/typings/extra.d.ts b/typings/extra.d.ts index f05a0161b..d6d627014 100644 --- a/typings/extra.d.ts +++ b/typings/extra.d.ts @@ -13,7 +13,7 @@ export declare class Extra { webPreview(value?: boolean): this - markup(markup: any): tt.ExtraEditMessage & this + markup(markup: any): tt.ExtraReplyMarkup & this HTML(value?: boolean): this @@ -29,7 +29,7 @@ export declare class Extra { static webPreview(value?: boolean): Extra - static markup(markup: any): tt.ExtraEditMessage + static markup(markup: any): tt.ExtraReplyMarkup static HTML(value?: boolean): Extra diff --git a/typings/markup.d.ts b/typings/markup.d.ts index b38508a4c..778f3cb5a 100644 --- a/typings/markup.d.ts +++ b/typings/markup.d.ts @@ -103,7 +103,7 @@ export declare class Markup { selective(value?: boolean): this - extra(options?: tt.ExtraReplyMessage): tt.ExtraReplyMessage + extra(options?: tt.Extra): tt.Extra keyboard( buttons: KeyboardButton[] | KeyboardButton[][], diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index af914ec8f..885f1fd88 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -263,37 +263,76 @@ export interface ExtraPromoteChatMember { can_promote_members?: boolean } -export interface ExtraReplyMessage { +export interface ExtraReplyMarkup { + /** + * Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + */ + reply_markup?: TT.InlineKeyboardMarkup | TT.ReplyKeyboardMarkup | TT.ReplyKeyboardRemove | TT.ForceReply +} + +interface ExtraReplyMarkupInlineKeyboard { + /** A JSON-serialized object for a new message inline keyboard. */ + reply_markup?: TT.InlineKeyboardMarkup +} + +interface ExtraFormatting { + /** + * Mode for parsing entities in the message text. See formatting options for more details. + */ + parse_mode?: ParseMode + + /** + * List of special entities that appear in message text, which can be specified instead of parse_mode + */ + entities?: TT.MessageEntity[] +} + +interface ExtraCaption { + /** + * Audio caption, 0-1024 characters + */ + caption?: string /** - * Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * Mode for parsing entities in the photo caption. See formatting options for more details. */ parse_mode?: ParseMode + /** + * List of special entities that appear in message text, which can be specified instead of parse_mode + */ + caption_entities?: TT.MessageEntity[] +} + +interface ExtraDisableWebPagePreview { /** * Disables link previews for links in this message */ disable_web_page_preview?: boolean +} +interface ExtraDisableNotifications { /** * Sends the message silently. Users will receive a notification with no sound. */ disable_notification?: boolean +} +interface ExtraReplyMessage { /** * If the message is a reply, ID of the original message */ reply_to_message_id?: number /** - * Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + * Pass True, if the message should be sent even if the specified replied-to message is not found */ - reply_markup?: TT.InlineKeyboardMarkup | TT.ReplyKeyboardMarkup | TT.ReplyKeyboardRemove | TT.ForceReply + allow_sending_without_reply?: boolean } -export interface ExtraEditMessage extends ExtraReplyMessage { - // no specified properties -} +export interface ExtraSendMessage extends ExtraFormatting, ExtraDisableWebPagePreview, ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup {} + +export interface ExtraEditMessage extends ExtraFormatting, ExtraDisableWebPagePreview, ExtraReplyMarkupInlineKeyboard {} export interface ExtraUnpinMessage { /** @@ -302,11 +341,7 @@ export interface ExtraUnpinMessage { message_id?: number } -export interface ExtraAudio extends ExtraReplyMessage { - /** - * Audio caption, 0-1024 characters - */ - caption?: string +export interface ExtraAudio extends ExtraCaption, ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup { /** * Duration of the audio in seconds @@ -330,14 +365,9 @@ export interface ExtraAudio extends ExtraReplyMessage { * so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . */ thumb?: InputFile - - /** - * Does not exist, see https://core.telegram.org/bots/api#sendaudio - */ - disable_web_page_preview?: never } -export interface ExtraDocument extends ExtraReplyMessage { +export interface ExtraDocument extends ExtraCaption, ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup { /** * Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. * The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 320. @@ -346,67 +376,39 @@ export interface ExtraDocument extends ExtraReplyMessage { */ thumb?: InputFile - /** - * Document caption (may also be used when resending documents by file_id), 0-1024 characters - */ - caption?: string - - /** - * List of special entities that appear in the caption, which can be specified instead of parse_mode - */ - caption_entities?: TT.MessageEntity - /** * Disables automatic server-side content type detection for files uploaded using multipart/form-data */ disable_content_type_detection?: Boolean - - /** - * Pass True, if the message should be sent even if the specified replied-to message is not found - */ - allow_sending_without_reply?: Boolean - - /** - * Does not exist, see https://core.telegram.org/bots/api#senddocument - */ - disable_web_page_preview?: never } -export interface ExtraGame extends ExtraReplyMessage { - /** - * Inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game. - */ - reply_markup?: TT.InlineKeyboardMarkup +export interface ExtraGame extends ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkupInlineKeyboard {} - /** - * Does not exist, see https://core.telegram.org/bots/api#sendgame - */ - disable_web_page_preview?: never +export interface ExtraInvoice extends ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkupInlineKeyboard {} +export interface ExtraLocation extends ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup { /** - * Does not exist, see https://core.telegram.org/bots/api#sendgame + * The radius of uncertainty for the location, measured in meters; 0-1500 */ - parse_mode?: never -} + horizontal_accuracy?: number -export interface ExtraInvoice extends ExtraReplyMessage { /** - * Inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. + * Period in seconds for which the location will be updated (should be between 60 and 86400) */ - reply_markup?: TT.InlineKeyboardMarkup + live_period?: number /** - * Does not exist, see https://core.telegram.org/bots/api#sendinvoice + * For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. */ - disable_web_page_preview?: never + heading?: number /** - * Does not exist, see https://core.telegram.org/bots/api#sendinvoice + * For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */ - parse_mode?: never + proximity_alert_radius?: number } -export interface ExtraLocation extends ExtraReplyMessage { +export interface ExtraEditLocation { /** * The radius of uncertainty for the location, measured in meters; 0-1500 */ @@ -426,84 +428,17 @@ export interface ExtraLocation extends ExtraReplyMessage { * For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */ proximity_alert_radius?: number - - /** - * Pass True, if the message should be sent even if the specified replied-to message is not found - */ - allow_sending_without_reply?: boolean - - /** - * Does not exist, see https://core.telegram.org/bots/api#sendlocation - */ - disable_web_page_preview?: never - - /** - * Does not exist, see https://core.telegram.org/bots/api#sendlocation - */ - parse_mode?: never -} - -export interface ExtraEditLocation extends ExtraLocation { - /** - * Does not exist, see https://core.telegram.org/bots/api#sendlocation - */ - live_period?: never } -export interface ExtraPhoto extends ExtraReplyMessage { - /** - * Photo caption (may also be used when resending photos by file_id), 0-1024 characters - */ - caption?: string - - /** - * Does not exist, see https://core.telegram.org/bots/api#sendphoto - */ - disable_web_page_preview?: never -} - -export interface ExtraMediaGroup extends ExtraReplyMessage { - /** - * Does not exist, see https://core.telegram.org/bots/api#sendmediagroup - */ - disable_web_page_preview?: never - - /** - * Does not exist, see https://core.telegram.org/bots/api#sendmediagroup - */ - parse_mode?: never - - /** - * Does not exist, see https://core.telegram.org/bots/api#sendmediagroup - */ - reply_markup?: never - - /** - * Pass True, if the message should be sent even if the specified replied-to message is not found - */ - allow_sending_without_reply?: Boolean -} +export interface ExtraPhoto extends ExtraCaption, ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup {} -export interface ExtraAnimation extends ExtraReplyMessage { - /** - * Animation caption (may also be used when resending animation by file_id), 0-200 characters - */ - caption?: string -} +export interface ExtraMediaGroup extends ExtraDisableNotifications, ExtraReplyMessage {} -export interface ExtraSticker extends ExtraReplyMessage { - /** - * Does not exist, see https://core.telegram.org/bots/api#sendsticker - */ - disable_web_page_preview?: never +export interface ExtraAnimation extends ExtraCaption, ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup {} - /** - * Does not exist, see https://core.telegram.org/bots/api#sendsticker - */ - parse_mode?: never -} +export interface ExtraSticker extends ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup {} -export interface ExtraVideo extends ExtraReplyMessage { +export interface ExtraVideo extends ExtraCaption, ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup { /** * Duration of sent video in seconds */ @@ -527,23 +462,13 @@ export interface ExtraVideo extends ExtraReplyMessage { */ thumb?: InputFile - /** - * Video caption (may also be used when resending videos by file_id), 0-1024 characters - */ - caption?: string - /** * Pass True, if the uploaded video is suitable for streaming */ supports_streaming?: boolean - - /** - * Does not exist, see https://core.telegram.org/bots/api#sendvideo - */ - disable_web_page_preview?: never } -export interface ExtraVideoNote extends ExtraReplyMessage { +export interface ExtraVideoNote extends ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup { /** * Duration of sent video in seconds */ @@ -563,24 +488,14 @@ export interface ExtraVideoNote extends ExtraReplyMessage { thumb?: InputFile } -export interface ExtraVoice extends ExtraReplyMessage { - /** - * Voice message caption, 0-1024 characters - */ - caption?: string - +export interface ExtraVoice extends ExtraCaption, ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup { /** * Duration of the voice message in seconds */ duration?: number - - /** - * Does not exist, see https://core.telegram.org/bots/api#sendvoice - */ - disable_web_page_preview?: never } -export interface ExtraDice extends ExtraReplyMessage { +export interface ExtraDice extends ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup { /** * Emoji on which the dice throw animation is based. * Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, or “🎰”. @@ -588,19 +503,9 @@ export interface ExtraDice extends ExtraReplyMessage { * Defaults to “🎲” * */ emoji?: string - - /** - * Does not exist, see https://core.telegram.org/bots/api#senddice - */ - parse_mode?: never - - /** - * Does not exist, see https://core.telegram.org/bots/api#senddice - */ - disable_web_page_preview?: never } -export interface ExtraPoll { +export interface ExtraPoll extends ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup { /** True, if the poll needs to be anonymous, defaults to True */ is_anonymous?: boolean @@ -612,25 +517,13 @@ export interface ExtraPoll { /** Pass True, if the poll needs to be immediately closed. This can be useful for poll preview. */ is_closed?: boolean - - /** Sends the message silently. Users will receive a notification with no sound. */ - disable_notification?: boolean - - /** If the message is a reply, ID of the original message */ - reply_to_message_id?: number - - /** Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. */ - reply_markup?: - | TT.InlineKeyboardMarkup - | TT.ReplyKeyboardMarkup - | TT.ReplyKeyboardRemove - | TT.ForceReply } -export interface ExtraStopPoll { - /** A JSON-serialized object for a new message inline keyboard. */ - reply_markup?: TT.InlineKeyboardMarkup -} +export interface ExtraStopPoll extends ExtraReplyMarkupInlineKeyboard {} + +export type Extra = ExtraSendMessage + | ExtraEditMessage + | ExtraUnpinMessage export interface ExtraUnban { /** Do nothing if the user is not banned */ @@ -774,61 +667,3 @@ export interface BotCommand { */ description: string } - -/** - * This object represents a dice with random value from 1 to 6. (Yes, we're aware of the “proper” singular of die. But it's awkward, and we decided to help it change. One dice at a time!) - */ -export interface Dice { - /** - * Value of the dice, 1-6 - */ - value: number -} - -export interface PollOption { - /** Option text, 1-100 characters */ - text: string - - /** Number of users that voted for this option */ - voter_count: number -} - -export interface PollAnswer { - /** Unique poll identifier */ - poll_id: string - - /** The user, who changed the answer to the poll */ - user: TT.User - - /** 0-based identifiers of answer options, chosen by the user. May be empty if the user retracted their vote. */ - option_ids: number[] -} - -export interface Poll { - /** Unique poll identifier */ - id: string - - /** Poll question, 1-255 characters */ - question: string - - /** List of poll options */ - options: PollOption[] - - /** Total number of users that voted in the poll */ - total_voter_count: number - - /** True, if the poll is closed */ - is_closed: boolean - - /** True, if the poll is anonymous */ - is_anonymous: boolean - - /** Poll type, currently can be “regular” or “quiz” */ - type: 'regular' | 'quiz' - - /** True, if the poll allows multiple answers */ - allows_multiple_answers: boolean - - /** 0-based identifier of the correct answer option. Available only for polls in the quiz mode, which are closed, or was sent (not forwarded) by the bot or to the private chat with the bot. */ - correct_option_id?: number -} From 318d88f6302612a9f23fa920a92d067f57dcb41d Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 19:16:43 +0300 Subject: [PATCH 28/79] Update typings for quiz --- typings/context.d.ts | 2 +- typings/telegram-types.d.ts | 23 ++++++++++++++++++++--- typings/telegram.d.ts | 2 +- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/typings/context.d.ts b/typings/context.d.ts index e2ec6470d..3608504f9 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -302,7 +302,7 @@ export declare class TelegrafContext { replyWithQuiz( question: string, options: string[], - extra: tt.ExtraPoll + extra: tt.ExtraQuiz ): Promise /** diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 885f1fd88..56a052b35 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -512,13 +512,30 @@ export interface ExtraPoll extends ExtraDisableNotifications, ExtraReplyMessage, /** True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False */ allows_multiple_answers?: boolean - /** 0-based identifier of the correct answer option, required for polls in quiz mode */ - correct_option_id?: number - /** Pass True, if the poll needs to be immediately closed. This can be useful for poll preview. */ is_closed?: boolean } +export interface ExtraQuiz extends ExtraPoll { + /** 0-based identifier of the correct answer option, required for polls in quiz mode */ + correct_option_id: number + + /** Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing */ + explanation?: string + + /** List of special entities that appear in the poll explanation, which can be specified instead of parse_mode */ + explanation_entities?: TT.MessageEntity[] + + /** Mode for parsing entities in the explanation. See formatting options for more details. */ + explanation_parse_mode?: ParseMode + + /** Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with close_date. */ + open_period?: number + + /** Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with open_period. */ + close_date?: number +} + export interface ExtraStopPoll extends ExtraReplyMarkupInlineKeyboard {} export type Extra = ExtraSendMessage diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 62b796578..a214eccbc 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -534,7 +534,7 @@ export declare class Telegram extends ApiClient { chatId: number | string, question: string, options: string[], - extra: tt.ExtraPoll + extra: tt.ExtraQuiz ): Promise /** From 4136de46501d5ab1a10cfa5229a141433bcc974f Mon Sep 17 00:00:00 2001 From: Loskir Date: Thu, 14 Jan 2021 19:40:57 +0300 Subject: [PATCH 29/79] Fix typings for poll --- typings/telegram-types.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 56a052b35..b05c00d64 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -514,6 +514,12 @@ export interface ExtraPoll extends ExtraDisableNotifications, ExtraReplyMessage, /** Pass True, if the poll needs to be immediately closed. This can be useful for poll preview. */ is_closed?: boolean + + /** Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with close_date. */ + open_period?: number + + /** Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with open_period. */ + close_date?: number } export interface ExtraQuiz extends ExtraPoll { @@ -528,12 +534,6 @@ export interface ExtraQuiz extends ExtraPoll { /** Mode for parsing entities in the explanation. See formatting options for more details. */ explanation_parse_mode?: ParseMode - - /** Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with close_date. */ - open_period?: number - - /** Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with open_period. */ - close_date?: number } export interface ExtraStopPoll extends ExtraReplyMarkupInlineKeyboard {} From 35e37d236c138feee163f20845d6f285126cd995 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Thu, 14 Jan 2021 20:44:53 +0300 Subject: [PATCH 30/79] native copy message & online require --- docs/examples/echo-bot-module.js | 6 ++---- docs/examples/echo-bot.js | 6 ++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/docs/examples/echo-bot-module.js b/docs/examples/echo-bot-module.js index 56c5971c3..65b395070 100644 --- a/docs/examples/echo-bot-module.js +++ b/docs/examples/echo-bot-module.js @@ -1,8 +1,6 @@ // Modules documentation: https://telegraf.js.org/#/?id=telegraf-modules // $> telegraf -t `BOT TOKEN` echo-bot-module.js -const Composer = require('telegraf/composer') -const Extra = require('telegraf/extra') -const Markup = require('telegraf/markup') +const { Composer, Extra, Markup } = require('telegraf') const keyboard = Markup.inlineKeyboard([ Markup.urlButton('❤️', 'http://telegraf.js.org'), @@ -35,6 +33,6 @@ bot.help(async (ctx) => { }) bot.action('delete', ({ deleteMessage }) => deleteMessage()) bot.on('dice', (ctx) => ctx.reply(`Value: ${ctx.message.dice.value}`)) -bot.on('message', (ctx) => ctx.telegram.sendCopy(ctx.chat.id, ctx.message, Extra.markup(keyboard))) +bot.on('message', (ctx) => ctx.copyMessage(ctx.chat.id, Extra.markup(keyboard))) module.exports = bot diff --git a/docs/examples/echo-bot.js b/docs/examples/echo-bot.js index e2475a652..3660ee3e1 100644 --- a/docs/examples/echo-bot.js +++ b/docs/examples/echo-bot.js @@ -1,6 +1,4 @@ -const Telegraf = require('telegraf') -const Extra = require('telegraf/extra') -const Markup = require('telegraf/markup') +const { Telegraf, Extra, Markup } = require('../../telegraf') const keyboard = Markup.inlineKeyboard([ Markup.urlButton('❤️', 'http://telegraf.js.org'), @@ -10,6 +8,6 @@ const keyboard = Markup.inlineKeyboard([ const bot = new Telegraf(process.env.BOT_TOKEN) bot.start((ctx) => ctx.reply('Hello')) bot.help((ctx) => ctx.reply('Help message')) -bot.on('message', (ctx) => ctx.telegram.sendCopy(ctx.chat.id, ctx.message, Extra.markup(keyboard))) +bot.on('message', (ctx) => ctx.copyMessage(ctx.chat.id, Extra.markup(keyboard))) bot.action('delete', ({ deleteMessage }) => deleteMessage()) bot.launch() From 9415f8dedb58578565a512994148dedbd07eb90b Mon Sep 17 00:00:00 2001 From: del333ted <56775051+del333ted@users.noreply.github.com> Date: Fri, 15 Jan 2021 02:26:38 +0300 Subject: [PATCH 31/79] bump license date --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 43cf7f141..d4ada101a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016-2019 Vitaly Domnikov +Copyright (c) 2016-2021 Vitaly Domnikov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 8b64b6aa75b87fd1b9249cbedf949ff132da98fc Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 11:00:32 +0300 Subject: [PATCH 32/79] Fix typings for editMessageCaption --- typings/telegram-types.d.ts | 16 ++++++++++------ typings/telegram.d.ts | 4 ++-- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index b05c00d64..28c092f62 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -287,12 +287,7 @@ interface ExtraFormatting { entities?: TT.MessageEntity[] } -interface ExtraCaption { - /** - * Audio caption, 0-1024 characters - */ - caption?: string - +interface ExtraCaptionFormatting { /** * Mode for parsing entities in the photo caption. See formatting options for more details. */ @@ -304,6 +299,13 @@ interface ExtraCaption { caption_entities?: TT.MessageEntity[] } +interface ExtraCaption extends ExtraCaptionFormatting{ + /** + * Audio caption, 0-1024 characters + */ + caption?: string +} + interface ExtraDisableWebPagePreview { /** * Disables link previews for links in this message @@ -538,6 +540,8 @@ export interface ExtraQuiz extends ExtraPoll { export interface ExtraStopPoll extends ExtraReplyMarkupInlineKeyboard {} +export interface ExtraEditCaption extends ExtraCaptionFormatting, ExtraReplyMarkupInlineKeyboard {} + export type Extra = ExtraSendMessage | ExtraEditMessage | ExtraUnpinMessage diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index a214eccbc..288d04ee0 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -131,14 +131,14 @@ export declare class Telegram extends ApiClient { * @param messageId Required if inlineMessageId is not specified. Identifier of the sent message * @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message * @param caption New caption of the message - * @param markup A JSON-serialized object for an inline keyboard. + * @param extra Extra params */ editMessageCaption( chatId?: number | string, messageId?: number, inlineMessageId?: string, caption?: string, - markup?: string + extra?: tt.ExtraEditCaption ): Promise /** From d00ee1e9666e19c4476b30242756dc0b2615818b Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 11:52:21 +0300 Subject: [PATCH 33/79] Update editMessageLiveLocation --- context.js | 12 +++++------- telegram.js | 7 +++---- typings/context.d.ts | 2 -- typings/telegram-types.d.ts | 2 +- typings/telegram.d.ts | 10 ++++------ 5 files changed, 13 insertions(+), 20 deletions(-) diff --git a/context.js b/context.js index f374ab9b1..154deed72 100644 --- a/context.js +++ b/context.js @@ -272,25 +272,23 @@ class TelegrafContext { ) } - editMessageLiveLocation (latitude, longitude, markup, extra) { + editMessageLiveLocation (latitude, longitude, extra) { this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageLiveLocation') return this.inlineMessageId ? this.telegram.editMessageLiveLocation( - latitude, - longitude, undefined, undefined, this.inlineMessageId, - markup, + latitude, + longitude, extra ) : this.telegram.editMessageLiveLocation( - latitude, - longitude, this.chat.id, this.callbackQuery.message.message_id, undefined, - markup, + latitude, + longitude, extra ) } diff --git a/telegram.js b/telegram.js index 13a6749f9..e2bba074d 100644 --- a/telegram.js +++ b/telegram.js @@ -315,14 +315,13 @@ class Telegram extends ApiClient { }) } - editMessageLiveLocation (latitude, longitude, chatId, messageId, inlineMessageId, markup, extra) { + editMessageLiveLocation (chatId, messageId, inlineMessageId, latitude, longitude, extra) { return this.callApi('editMessageLiveLocation', { - latitude, - longitude, chat_id: chatId, message_id: messageId, inline_message_id: inlineMessageId, - reply_markup: markup, + latitude, + longitude, ...extra }) } diff --git a/typings/context.d.ts b/typings/context.d.ts index 3608504f9..54c408e9e 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -460,13 +460,11 @@ export declare class TelegrafContext { * @returns On success, if the edited message was sent by the bot, the edited message is returned, otherwise True is returned. * @param latitude New latitude * @param longitude New longitude - * @param markup Markup of inline keyboard * @param extra Extra params */ editMessageLiveLocation( latitude: number, longitude: number, - markup: tt.InlineKeyboardMarkup, extra?: tt.ExtraEditLocation ): Promise diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 28c092f62..954e42ce8 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -410,7 +410,7 @@ export interface ExtraLocation extends ExtraDisableNotifications, ExtraReplyMess proximity_alert_radius?: number } -export interface ExtraEditLocation { +export interface ExtraEditLocation extends ExtraReplyMarkupInlineKeyboard { /** * The radius of uncertainty for the location, measured in meters; 0-1500 */ diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 288d04ee0..df67b11fa 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -163,18 +163,16 @@ export declare class Telegram extends ApiClient { * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) * @param messageId Required if inlineMessageId is not specified. Identifier of the sent message * @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message - * @param markup Markup of inline keyboard * @param extra Extra params * @returns On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. */ editMessageLiveLocation( - latitude: number, - longitude: number, chatId: number | string | void, - messageId: number, + messageId: number | void, inlineMessageId: string | void, - markup: tt.InlineKeyboardMarkup, - extra?: tt.ExtraLocation + latitude: number, + longitude: number, + extra?: tt.ExtraEditLocation ): Promise /** From ce10b73260d844d5dabb785e780a6374a38781c4 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:00:18 +0300 Subject: [PATCH 34/79] Fix typings for editMessageCaption --- typings/context.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/typings/context.d.ts b/typings/context.d.ts index 54c408e9e..c22bd7d76 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -428,11 +428,11 @@ export declare class TelegrafContext { * Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. * @param caption New caption of the message - * @param markup Markup of inline keyboard + * @param extra Extra params */ editMessageCaption( caption?: string, - markup?: tt.InlineKeyboardMarkup + extra?: tt.ExtraEditCaption ): Promise /** From 213d04a4f901043ac73d9c63d1e419efed9ac4ec Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:00:39 +0300 Subject: [PATCH 35/79] Fix JSDoc for editMessageMedia --- typings/context.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings/context.d.ts b/typings/context.d.ts index c22bd7d76..220f6395e 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -448,7 +448,7 @@ export declare class TelegrafContext { * Use this method to edit animation, audio, document, photo, or video messages. * @returns On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. * @param media New media of message - * @param markup Markup of inline keyboard + * @param extra Extra params */ editMessageMedia( media: tt.MessageMedia, From 16233292456c4aad74b2b212850937f2c902edfb Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:01:16 +0300 Subject: [PATCH 36/79] Fix typings for editMessageReplyMarkup --- typings/telegram.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index df67b11fa..ac9734cfe 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -147,13 +147,13 @@ export declare class Telegram extends ApiClient { * @param chatId Required if inlineMessageId is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) * @param messageId Required if inlineMessageId is not specified. Identifier of the sent message * @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message - * @param markup A JSON-serialized object for an inline keyboard. + * @param markup Markup of inline keyboard */ editMessageReplyMarkup( chatId?: number | string, messageId?: number, inlineMessageId?: string, - markup?: string + markup?: tt.InlineKeyboardMarkup ): Promise /** From 9b9c888d54c73204f0a30aad70220d72efa8e7d1 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:03:15 +0300 Subject: [PATCH 37/79] Fix JSDoc for editMessageLiveLocation --- typings/telegram.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index ac9734cfe..caaa498a4 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -158,11 +158,11 @@ export declare class Telegram extends ApiClient { /** * Use this method to edit live location messages - * @param latitude Latitude of location - * @param longitude Longitude of location * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) * @param messageId Required if inlineMessageId is not specified. Identifier of the sent message * @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message + * @param latitude Latitude of location + * @param longitude Longitude of location * @param extra Extra params * @returns On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. */ From 94087f293d18a244925f153544f322e0ba73e3bb Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:21:03 +0300 Subject: [PATCH 38/79] Add fallback support for caption and caption_entities passed as extra to editMessageMedia --- telegram.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/telegram.js b/telegram.js index e2bba074d..cf50ef90e 100644 --- a/telegram.js +++ b/telegram.js @@ -301,7 +301,12 @@ class Telegram extends ApiClient { chat_id: chatId, message_id: messageId, inline_message_id: inlineMessageId, - media: { ...media, parse_mode: extra.parse_mode }, + media: { + ...media, + parse_mode: extra.parse_mode, + caption: extra.caption, + caption_entities: extra.caption_entities + }, reply_markup: extra.reply_markup ? extra.reply_markup : extra }) } From 2adadc51075fd6f0b0dcbc5049dd1c45506e2a87 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:21:23 +0300 Subject: [PATCH 39/79] Add support for caption and caption_entities to editMessageCaption --- telegram.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/telegram.js b/telegram.js index cf50ef90e..41cf5f3cd 100644 --- a/telegram.js +++ b/telegram.js @@ -291,7 +291,8 @@ class Telegram extends ApiClient { chat_id: chatId, message_id: messageId, inline_message_id: inlineMessageId, - parse_mode: extra.parse_mode, + ...extra.parse_mode && { parse_mode: extra.parse_mode }, + ...extra.caption_entities && { caption_entities: extra.caption_entities }, reply_markup: extra.parse_mode || extra.reply_markup ? extra.reply_markup : extra }) } From e53cbe464a4505d5c86147cf6eb73ed4f498d139 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:22:27 +0300 Subject: [PATCH 40/79] Add caption_entities to InputMedia typings --- typings/telegram-types.d.ts | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 954e42ce8..f7f20f36e 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -93,55 +93,45 @@ export type MessageMedia = InputMediaAudio | InputMediaDocument -export interface InputMediaPhoto { +export interface InputMediaPhoto extends ExtraCaption { type: string media: InputFile - caption?: string - parse_mode?: string } -export interface InputMediaVideo { +export interface InputMediaVideo extends ExtraCaption { type: string media: InputFile thumb?: string | InputFile - caption?: string - parse_mode?: string width?: number height?: number duration?: number supports_streaming?: boolean } -export interface InputMediaAnimation { +export interface InputMediaAnimation extends ExtraCaption { type: string media: InputFile thumb?: string | InputFile - caption?: string - parse_mode?: string width?: number height?: number duration?: number supports_streaming?: boolean } -export interface InputMediaAudio { +export interface InputMediaAudio extends ExtraCaption { type: string media: InputFile thumb?: string | InputFile - caption?: string - parse_mode?: string performer?: string title?: string duration?: number supports_streaming?: boolean } -export interface InputMediaDocument { +export interface InputMediaDocument extends ExtraCaption { type: string media: InputFile thumb?: string | InputFile - caption?: string - parse_mode?: string } export interface StickerData { From 9726f1fde533ffd30d48b85e8dce7f2292f6fb44 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:25:16 +0300 Subject: [PATCH 41/79] Add InputMediaTypes description --- typings/telegram-types.d.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index f7f20f36e..5d5ae84e0 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -64,6 +64,12 @@ export type MessageSubTypes = 'connected_website' | 'animation' +export type InputMediaTypes = 'photo' + | 'video' + | 'animation' + | 'audio' + | 'document' + export type InlineQueryResult = TT.InlineQueryResultCachedAudio | TT.InlineQueryResultCachedDocument | @@ -94,12 +100,12 @@ export type MessageMedia = InputMediaDocument export interface InputMediaPhoto extends ExtraCaption { - type: string + type: InputMediaTypes media: InputFile } export interface InputMediaVideo extends ExtraCaption { - type: string + type: InputMediaTypes media: InputFile thumb?: string | InputFile width?: number @@ -109,7 +115,7 @@ export interface InputMediaVideo extends ExtraCaption { } export interface InputMediaAnimation extends ExtraCaption { - type: string + type: InputMediaTypes media: InputFile thumb?: string | InputFile width?: number @@ -119,7 +125,7 @@ export interface InputMediaAnimation extends ExtraCaption { } export interface InputMediaAudio extends ExtraCaption { - type: string + type: InputMediaTypes media: InputFile thumb?: string | InputFile performer?: string @@ -129,7 +135,7 @@ export interface InputMediaAudio extends ExtraCaption { } export interface InputMediaDocument extends ExtraCaption { - type: string + type: InputMediaTypes media: InputFile thumb?: string | InputFile } From 4807d00669939da1cecca6dcd0bf461f97355ac7 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:33:46 +0300 Subject: [PATCH 42/79] Fix test for editMessageLiveLocation --- typings/test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/typings/test.ts b/typings/test.ts index 51e296344..50919296b 100644 --- a/typings/test.ts +++ b/typings/test.ts @@ -108,8 +108,9 @@ bot.hears('something', async (ctx) => { reply_markup: Markup.inlineKeyboard([]) }) - ctx.editMessageLiveLocation(90, 90, Markup.inlineKeyboard([]), { - heading: 1 + ctx.editMessageLiveLocation(90, 90, { + heading: 1, + reply_markup: Markup.inlineKeyboard([]) }) ctx.stopMessageLiveLocation({ From 3bca8426f400ba225da6457d2ba505d74ebb018a Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:34:40 +0300 Subject: [PATCH 43/79] Fix typings for editMessageMedia --- typings/context.d.ts | 2 +- typings/telegram-types.d.ts | 4 +++- typings/telegram.d.ts | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/typings/context.d.ts b/typings/context.d.ts index 220f6395e..557f31d52 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -452,7 +452,7 @@ export declare class TelegrafContext { */ editMessageMedia( media: tt.MessageMedia, - extra?: tt.ExtraEditMessage + extra?: tt.ExtraEditMessageMedia ): Promise /** diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 5d5ae84e0..029434d54 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -295,7 +295,7 @@ interface ExtraCaptionFormatting { caption_entities?: TT.MessageEntity[] } -interface ExtraCaption extends ExtraCaptionFormatting{ +interface ExtraCaption extends ExtraCaptionFormatting { /** * Audio caption, 0-1024 characters */ @@ -332,6 +332,8 @@ export interface ExtraSendMessage extends ExtraFormatting, ExtraDisableWebPagePr export interface ExtraEditMessage extends ExtraFormatting, ExtraDisableWebPagePreview, ExtraReplyMarkupInlineKeyboard {} +export interface ExtraEditMessageMedia extends ExtraReplyMarkupInlineKeyboard {} + export interface ExtraUnpinMessage { /** * Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned. diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index caaa498a4..7ba7d5ff5 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -156,6 +156,23 @@ export declare class Telegram extends ApiClient { markup?: tt.InlineKeyboardMarkup ): Promise + /** + * Use this method to edit animation, audio, document, photo, or video messages. + * @returns On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. + * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) + * @param messageId Required if inlineMessageId is not specified. Identifier of the sent message + * @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message + * @param media New media of message + * @param extra Extra params + */ + editMessageMedia( + chatId: number | string | void, + messageId: number | void, + inlineMessageId: string | void, + media: tt.MessageMedia, + extra?: tt.ExtraEditMessageMedia + ): Promise + /** * Use this method to edit live location messages * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) From 796447da700440ee9669f2faaadc63f081afb9eb Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:36:33 +0300 Subject: [PATCH 44/79] Update Extra type --- typings/telegram-types.d.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 029434d54..d639bad02 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -542,7 +542,26 @@ export interface ExtraEditCaption extends ExtraCaptionFormatting, ExtraReplyMark export type Extra = ExtraSendMessage | ExtraEditMessage + | ExtraEditMessageMedia | ExtraUnpinMessage + | ExtraAudio + | ExtraDocument + | ExtraGame + | ExtraInvoice + | ExtraLocation + | ExtraEditLocation + | ExtraPhoto + | ExtraMediaGroup + | ExtraAnimation + | ExtraSticker + | ExtraVideo + | ExtraVideoNote + | ExtraVoice + | ExtraDice + | ExtraPoll + | ExtraQuiz + | ExtraStopPoll + | ExtraEditCaption export interface ExtraUnban { /** Do nothing if the user is not banned */ From 0957a0b49698bbc44db309cf4f1622ab7f54e997 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 12:36:53 +0300 Subject: [PATCH 45/79] Add deprecation warning TODOs --- telegram.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/telegram.js b/telegram.js index 41cf5f3cd..ce2758672 100644 --- a/telegram.js +++ b/telegram.js @@ -286,6 +286,7 @@ class Telegram extends ApiClient { } editMessageCaption (chatId, messageId, inlineMessageId, caption, extra = {}) { + // todo: deprecation warning about Markup being passed instead of extra return this.callApi('editMessageCaption', { caption, chat_id: chatId, @@ -298,6 +299,7 @@ class Telegram extends ApiClient { } editMessageMedia (chatId, messageId, inlineMessageId, media, extra = {}) { + // todo: deprecation warning about Markup being passed instead of extra return this.callApi('editMessageMedia', { chat_id: chatId, message_id: messageId, From eff3ebc78e74fa84b2b0c0ccc9ef41a1ae35dc45 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 13:15:40 +0300 Subject: [PATCH 46/79] Update typings for stopMessageLiveLocation --- typings/context.d.ts | 18 +++++++++--------- typings/telegram-types.d.ts | 2 ++ typings/telegram.d.ts | 15 +++++++++++++++ 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/typings/context.d.ts b/typings/context.d.ts index 557f31d52..35b316670 100644 --- a/typings/context.d.ts +++ b/typings/context.d.ts @@ -468,6 +468,15 @@ export declare class TelegrafContext { extra?: tt.ExtraEditLocation ): Promise + /** + * Use this method to stop updating a live location message before live_period expires. + * @param extra Extra params + * @returns On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. + */ + stopMessageLiveLocation( + extra?: tt.ExtraStopLiveLocation + ): Promise + /** * Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights * @param userId Unique identifier of the target user @@ -495,15 +504,6 @@ export declare class TelegrafContext { extra: tt.ExtraPromoteChatMember ): Promise - /** - * Use this method to stop updating a live location message before live_period expires. - * @returns On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. - * @param extra Extra params - */ - stopMessageLiveLocation( - extra?: tt.ExtraLocation - ): 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. diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index d639bad02..5ab0653af 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -430,6 +430,8 @@ export interface ExtraEditLocation extends ExtraReplyMarkupInlineKeyboard { proximity_alert_radius?: number } +export interface ExtraStopLiveLocation extends ExtraReplyMarkupInlineKeyboard {} + export interface ExtraPhoto extends ExtraCaption, ExtraDisableNotifications, ExtraReplyMessage, ExtraReplyMarkup {} export interface ExtraMediaGroup extends ExtraDisableNotifications, ExtraReplyMessage {} diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 7ba7d5ff5..4c5b45678 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -192,6 +192,21 @@ export declare class Telegram extends ApiClient { extra?: tt.ExtraEditLocation ): Promise + /** + * Use this method to stop updating a live location message before live_period expires. + * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) + * @param messageId Required if inlineMessageId is not specified. Identifier of the sent message + * @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message + * @param extra Extra params + * @returns On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. + */ + stopMessageLiveLocation( + chatId: number | string | void, + messageId: number | void, + inlineMessageId: string | void, + extra?: tt.ExtraStopLiveLocation + ): 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. From f96d2c8b331f943d68469e5c5c02e44c5ca3796d Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 13:15:56 +0300 Subject: [PATCH 47/79] Fix JSDoc --- typings/telegram.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings/telegram.d.ts b/typings/telegram.d.ts index 4c5b45678..12066c703 100644 --- a/typings/telegram.d.ts +++ b/typings/telegram.d.ts @@ -364,7 +364,7 @@ export declare class Telegram extends ApiClient { /** * 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 chatId Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) - * @param user_id Unique identifier of the target user + * @param userId Unique identifier of the target user * @param extra Additional params for restrict chat member * @returns True on success */ From ea0799c9a78ba08e3e929aeb1790a3728dde4335 Mon Sep 17 00:00:00 2001 From: Loskir Date: Fri, 15 Jan 2021 13:41:51 +0300 Subject: [PATCH 48/79] Fix typos --- docs/README.md | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/README.md b/docs/README.md index f76c9ae5f..724d00d06 100644 --- a/docs/README.md +++ b/docs/README.md @@ -129,7 +129,7 @@ that you may have encountered such as Koa, Ruby's Rack, Connect. Middleware is an essential part of any modern framework. It allows you to modify requests and responses as they pass between the Telegram and your bot. -You can imagine middleware as a chain of logic connection your bot to the Telegram request. +You can imagine a middleware as a chain of logic connection your bot to the Telegram request. Middleware normally takes two parameters (ctx, next), `ctx` is the context for one Telegram update, `next` is a function that is invoked to execute the downstream middleware. @@ -159,13 +159,13 @@ bot.launch() - [Natural language processing via wit.ai](https://github.com/telegraf/telegraf-wit) - [Natural language processing via recast.ai](https://github.com/telegraf/telegraf-recast) - [Multivariate and A/B testing](https://github.com/telegraf/telegraf-experiments) -- [Powerfull bot stats via Mixpanel](https://github.com/telegraf/telegraf-mixpanel) +- [Powerful bot stats via Mixpanel](https://github.com/telegraf/telegraf-mixpanel) - [statsd integration](https://github.com/telegraf/telegraf-statsd) - [and more...](https://www.npmjs.com/search?q=telegraf-) #### Error handling -By default Telegraf will print all errors to `stderr` and rethrow error. +By default, Telegraf will print all errors to `stderr` and rethrow error. To perform custom error-handling logic use following snippet: @@ -196,7 +196,7 @@ Context is created per request and contains following props: | `[ctx.chosenInlineResult]` | Received inline query result | | `[ctx.callbackQuery]` | Received callback query | | `[ctx.shippingQuery]` | Shipping query | -| `[ctx.preCheckoutQuery]` | Precheckout query | +| `[ctx.preCheckoutQuery]` | Pre-checkout query | | `[ctx.channelPost]` | New incoming channel post of any kind — text, photo, sticker, etc. | | `[ctx.editedChannelPost]` | New version of a channel post that is known to the bot and was edited | | `[ctx.poll]` | New version of a anonymous poll that is known to the bot and was changed | @@ -434,7 +434,7 @@ bot.launch() **Note: For persistent sessions you can use any of [`telegraf-session-*`](https://www.npmjs.com/search?q=telegraf-session) middleware.** -**Tip: To use same session in private chat with bot and in inline mode, use following session key resolver:** +**Tip: To use same session in private chat with the bot and in inline mode, use following session key resolver:** ```js { @@ -628,7 +628,7 @@ Supported file sources: - `Buffer` - `ReadStream` -Also you can provide optional name of file as `filename`. +Also, you can provide an optional name of file as `filename`. ```js bot.on('message', (ctx) => { @@ -719,7 +719,7 @@ telegraf [opts] ##### Telegraf Module example -Create module with name `bot.js` and following content: +Create a module with name `bot.js` and following content: ```js const Composer = require('telegraf/composer') @@ -1042,7 +1042,7 @@ Compose `middlewares` returning a fully valid middleware comprised of all those ##### Telegraf.mount -Generates middleware for handling provided update types. +Generates a middleware for handling provided update types. `Telegraf.mount(updateTypes, ...middleware) => function` @@ -1053,7 +1053,7 @@ Generates middleware for handling provided update types. ##### Telegraf.hears -Generates middleware for handling `text` messages with regular expressions. +Generates a middleware for handling `text` messages with regular expressions. `Telegraf.hears(triggers, ...middleware) => function` @@ -1064,7 +1064,7 @@ Generates middleware for handling `text` messages with regular expressions. ##### Telegraf.action -Generates middleware for handling `callbackQuery` data with regular expressions. +Generates a middleware for handling `callbackQuery` data with regular expressions. `Telegraf.action(triggers, ...middleware) => function` @@ -1075,7 +1075,7 @@ Generates middleware for handling `callbackQuery` data with regular expressions. ##### Telegraf.inlineQuery -Generates middleware for handling `inlineQuery` data with regular expressions. +Generates a middleware for handling `inlineQuery` data with regular expressions. `Telegraf.inlineQuery(triggers, ...middleware) => function` @@ -1092,13 +1092,13 @@ Generates pass thru middleware. ##### Telegraf.safePassThru -Generates safe version of pass thru middleware. +Generates a safe version of pass thru middleware. `Telegraf.safePassThru() => function` ##### Telegraf.optional -Generates optional middleware. +Generates an optional middleware. `Telegraf.optional(test, ...middleware) => function` @@ -1109,7 +1109,7 @@ Generates optional middleware. ##### Telegraf.acl -Generates middleware for provided users only. +Generates a middleware for provided users only. `Telegraf.acl(userId, ...middleware) => function` @@ -1153,7 +1153,7 @@ Generates branch middleware. ##### Telegraf.email -Generates middleware for handling messages with `email` entity. +Generates a middleware for handling messages with `email` entity. `Telegraf.email(triggers, ...middleware) => function` @@ -1164,7 +1164,7 @@ Generates middleware for handling messages with `email` entity. ##### Telegraf.hashtag -Generates middleware for handling messages with `hashtag` entity. +Generates a middleware for handling messages with `hashtag` entity. `Telegraf.hashtag(triggers, ...middleware) => function` @@ -1175,7 +1175,7 @@ Generates middleware for handling messages with `hashtag` entity. ##### Telegraf.cashtag -Generates middleware for handling messages with `cashtag` entity. +Generates a middleware for handling messages with `cashtag` entity. `Telegraf.cashtag(triggers, ...middleware) => function` @@ -1186,7 +1186,7 @@ Generates middleware for handling messages with `cashtag` entity. ##### Telegraf.url -Generates middleware for handling messages with `url` entity. +Generates a middleware for handling messages with `url` entity. `Telegraf.url(triggers, ...middleware) => function` @@ -1197,7 +1197,7 @@ Generates middleware for handling messages with `url` entity. ##### Telegraf.phone -Generates middleware for handling messages with `phone` entity. +Generates a middleware for handling messages with `phone` entity. `Telegraf.phone(triggers, ...middleware) => function` @@ -1208,7 +1208,7 @@ Generates middleware for handling messages with `phone` entity. ##### Telegraf.textLink -Generates middleware for handling messages with `text_link` entity. +Generates a middleware for handling messages with `text_link` entity. `Telegraf.textLink(triggers, ...middleware) => function` @@ -1219,7 +1219,7 @@ Generates middleware for handling messages with `text_link` entity. ##### Telegraf.textMention -Generates middleware for handling messages with `text_mention` entity. +Generates a middleware for handling messages with `text_mention` entity. `Telegraf.textMention(triggers, ...middleware) => function` @@ -1938,7 +1938,7 @@ Sends text message. ##### sendPhoto -Sends photo. +Sends a photo. `telegram.sendPhoto(chatId, photo, [extra]) => Promise` @@ -2059,7 +2059,7 @@ Sends voice. ##### sendPoll -Sends anonymous poll. +Sends a poll. `telegram.sendPoll(chatId, question, options, [extra]) => Promise` @@ -2160,7 +2160,7 @@ Use this method to unban a previously kicked user in a supergroup. ##### setPassportDataErrors -Informs a user that some of the Telegram Passport elements they provided contains errors. +Informs a user that some Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). From d3b770cb01389f5aade2cc2bb1cf805ee3e66c8e Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sat, 16 Jan 2021 01:56:23 +0300 Subject: [PATCH 49/79] typo caption type --- typings/telegram-types.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings/telegram-types.d.ts b/typings/telegram-types.d.ts index 5ab0653af..22ccb8833 100644 --- a/typings/telegram-types.d.ts +++ b/typings/telegram-types.d.ts @@ -297,7 +297,7 @@ interface ExtraCaptionFormatting { interface ExtraCaption extends ExtraCaptionFormatting { /** - * Audio caption, 0-1024 characters + * Media caption, 0-1024 characters */ caption?: string } From 3bd2fb780fe374d96b923d50de466e19a43139c9 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sat, 16 Jan 2021 23:39:11 +0300 Subject: [PATCH 50/79] correct TelegrafOptions --- typings/telegraf.d.ts | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/typings/telegraf.d.ts b/typings/telegraf.d.ts index 09e4921da..d62873081 100644 --- a/typings/telegraf.d.ts +++ b/typings/telegraf.d.ts @@ -13,16 +13,18 @@ import { TelegrafContext } from './context' import { Composer } from './composer' import { Telegram, TelegramOptions } from './telegram' -export interface TelegrafOptions { +export interface TelegrafOptions extends TOptions { /** * Telegram options */ telegram?: TelegramOptions + context?: TelegrafContext + /** - * Bot username + * Autoset after launch by botInfo method */ - username?: string + username?: never } export interface LaunchPollingOptions { @@ -189,17 +191,7 @@ export interface TOptions { /** * Telegram options */ - telegram?: { - /** - * https.Agent or http.Agent instance, allows custom proxy, certificate, keep alive, etc. - */ - agent: https.Agent | http.Agent - - /** - * Reply via webhook - */ - webhookReply: boolean - } + telegram?: TelegramOptions /** * Bot username @@ -211,7 +203,13 @@ export interface TOptions { */ channelMode?: boolean + /** + * Delay (in seconds) before making a follow-up request to get updates + */ retryAfter?: number + /** + * Maximum amount of time (in microseconds) for which middlewares execution can pause updates fetching + */ handlerTimeout?: number } From 15d2020a5ef2ce0919599d98d6a070e4896f2871 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sun, 17 Jan 2021 00:28:20 +0300 Subject: [PATCH 51/79] typo contextType param --- typings/telegraf.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings/telegraf.d.ts b/typings/telegraf.d.ts index d62873081..5361d3353 100644 --- a/typings/telegraf.d.ts +++ b/typings/telegraf.d.ts @@ -19,7 +19,7 @@ export interface TelegrafOptions extends TOptions { */ telegram?: TelegramOptions - context?: TelegrafContext + contextType?: TelegrafContext /** * Autoset after launch by botInfo method From 0d68238b4013f72ac5570aae1943959d45267349 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sun, 17 Jan 2021 21:21:00 +0300 Subject: [PATCH 52/79] add MarkdownV2 thx @mmm-ui --- extra.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/extra.js b/extra.js index 61fea593f..de2c132b7 100644 --- a/extra.js +++ b/extra.js @@ -42,6 +42,11 @@ class Extra { return this } + markdownV2 (value = true) { + this.parse_mode = value ? 'MarkdownV2' : undefined + return this + } + caption (caption = '') { this.caption = caption return this @@ -75,6 +80,10 @@ class Extra { return new Extra().markdown(value) } + static markdownV2 (value) { + return new Extra().markdownV2(value) + } + static caption (caption) { return new Extra().caption(caption) } From c81f8f323778b6e6fcbc6984e762ef0f75262f79 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sun, 17 Jan 2021 21:23:47 +0300 Subject: [PATCH 53/79] add Custom context desc --- typings/telegraf.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/typings/telegraf.d.ts b/typings/telegraf.d.ts index 5361d3353..8b3914fec 100644 --- a/typings/telegraf.d.ts +++ b/typings/telegraf.d.ts @@ -19,6 +19,9 @@ export interface TelegrafOptions extends TOptions { */ telegram?: TelegramOptions + /** + * Custom context + */ contextType?: TelegrafContext /** From 7f49b292fb40501dda8e78a6d4c4f26f93b04458 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sun, 17 Jan 2021 21:44:23 +0300 Subject: [PATCH 54/79] remove warnings & repair level headings --- docs/README.md | 345 +++++++++++++++++++++++-------------------------- 1 file changed, 164 insertions(+), 181 deletions(-) diff --git a/docs/README.md b/docs/README.md index 724d00d06..224e4ca2d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,13 +2,11 @@ ## Introduction -Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically. -Users can interact with bots by sending them command messages in private or group chats. -These accounts serve as an interface for code running somewhere on your server. +Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server. -#### Features +### Features -- Full [Telegram Bot API 4.8](https://core.telegram.org/bots/api) support +- Full [Telegram Bot API 5.0](https://core.telegram.org/bots/api) support - [Telegram Payment Platform](https://telegram.org/blog/payments) - [HTML5 Games](https://core.telegram.org/bots/api#games) - [Inline mode](https://core.telegram.org/bots/api#inline-mode) @@ -18,19 +16,19 @@ These accounts serve as an interface for code running somewhere on your server. - Easy to extend - `TypeScript` typings -#### Installation +### Installation ```bash -$ npm install telegraf --save +npm install telegraf --save ``` or using yarn ```bash -$ yarn add telegraf +yarn add telegraf ``` -#### Example +### Example ```js const { Telegraf } = require('telegraf') @@ -110,30 +108,24 @@ For additional bot examples see [`examples`](https://github.com/telegraf/telegra ## Getting started -#### Telegram token +### Telegram token -To use the [Telegram Bot API](https://core.telegram.org/bots/api), -you first have to [get a bot account](https://core.telegram.org/bots) -by [chatting with BotFather](https://core.telegram.org/bots#6-botfather). +To use the [Telegram Bot API](https://core.telegram.org/bots/api), you first have to [get a bot account](https://core.telegram.org/bots) by [chatting with BotFather](https://core.telegram.org/bots#6-botfather). BotFather will give you a *token*, something like `123456789:AbCdfGhIJKlmNoQQRsTUVwxyZ`. -#### Bot +### Bot -A Telegraf bot is an object containing an array of middlewares which are composed -and executed in a stack-like manner upon request. Is similar to many other middleware systems -that you may have encountered such as Koa, Ruby's Rack, Connect. +A Telegraf bot is an object containing an array of middlewares which are composed and executed in a stack-like manner upon request. Is similar to many other middleware systems that you may have encountered such as Koa, Ruby's Rack, Connect. -#### Middleware +### Middleware Middleware is an essential part of any modern framework. It allows you to modify requests and responses as they pass between the Telegram and your bot. You can imagine a middleware as a chain of logic connection your bot to the Telegram request. -Middleware normally takes two parameters (ctx, next), `ctx` is the context for one Telegram update, -`next` is a function that is invoked to execute the downstream middleware. -It returns a Promise with a then function for running code after completion. +Middleware normally takes two parameters (ctx, next), `ctx` is the context for one Telegram update, `next` is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion. ```js const bot = new Telegraf(process.env.BOT_TOKEN) @@ -149,7 +141,7 @@ bot.on('text', (ctx) => ctx.reply('Hello World')) bot.launch() ``` -##### Known middleware +#### Known middleware - [Internationalization](https://github.com/telegraf/telegraf-i18n) - [Redis powered session](https://github.com/telegraf/telegraf-session-redis) @@ -163,7 +155,7 @@ bot.launch() - [statsd integration](https://github.com/telegraf/telegraf-statsd) - [and more...](https://www.npmjs.com/search?q=telegraf-) -#### Error handling +### Error handling By default, Telegraf will print all errors to `stderr` and rethrow error. @@ -178,9 +170,9 @@ bot.start((ctx) => { throw new Error('Example error') }) bot.launch() -``` +``` -#### Context +### Context A Telegraf Context encapsulates telegram update. Context is created per request and contains following props: @@ -212,7 +204,7 @@ bot.use((ctx) => { }) ``` -##### Extending context +#### Extending context The recommended way to extend bot context: @@ -231,7 +223,7 @@ bot.on('text', (ctx) => { bot.launch() ``` -##### Shortcuts +#### Shortcuts Context shortcuts for **message** update: @@ -396,7 +388,7 @@ bot.on('inline_query', (ctx) => { bot.launch() ``` -#### State +### State The recommended namespace to share information between middlewares. @@ -416,7 +408,7 @@ bot.on('text', (ctx) => { bot.launch() ``` -#### Session +### Session ```js const session = require('telegraf/session') @@ -449,7 +441,7 @@ bot.launch() } ``` -#### Update types +### Update types Supported update types: @@ -508,9 +500,10 @@ bot.on(['sticker', 'photo'], (ctx) => { return ctx.reply('Cool!') }) ``` + [Official Docs](https://core.telegram.org/bots/api#message) -#### Webhooks +### Webhooks ```js require('dotenv') @@ -618,7 +611,7 @@ app.use(async (ctx) => { app.listen(3000) ``` -#### Working with files +### Working with files Supported file sources: @@ -659,7 +652,7 @@ bot.on('message', (ctx) => { }) ``` -#### Telegram Passport +### Telegram Passport To enable Telegram Passport support you can use [`telegram-passport`](https://www.npmjs.com/package/telegram-passport) package: @@ -679,7 +672,7 @@ bot.on('passport_data', (ctx) => { }) ``` -#### Telegraf Modules +### Telegraf Modules Telegraf Modules is higher level abstraction for writing modular Telegram bots. @@ -701,12 +694,12 @@ module.exports = Composer.mount( To run modules you can use `telegraf` module runner, it allows you to start Telegraf module easily from the command line. ```bash -$ npm install telegraf -g +npm install telegraf -g ``` -#### Telegraf CLI usage +### Telegraf CLI usage -``` +```bash telegraf [opts] -t Bot token [$BOT_TOKEN] -d Webhook domain @@ -717,7 +710,7 @@ telegraf [opts] -h Show this help message ``` -##### Telegraf Module example +#### Telegraf Module example Create a module with name `bot.js` and following content: @@ -736,12 +729,12 @@ module.exports = bot then run it: ```bash -$ telegraf -t "bot token" bot.js +telegraf -t "bot token" bot.js ``` ## API reference -#### Telegraf +### Telegraf Telegraf API reference @@ -749,7 +742,7 @@ Telegraf API reference const { Telegraf } = require('telegraf') ``` -##### Constructor +#### Constructor Initialize new Telegraf bot. @@ -773,19 +766,19 @@ Telegraf options: } ``` -##### token +#### token Use this property to get/set bot token. `telegraf.token = [string]` -##### webhookReply +#### webhookReply Use this property to control `reply via webhook` feature. `telegraf.webhookReply = [bool]` -##### use +#### use Registers a middleware. @@ -795,7 +788,7 @@ Registers a middleware. | --- | --- | --- | | middleware | `function` | Middleware function | -##### on +#### on Registers middleware for provided update type. @@ -806,7 +799,7 @@ Registers middleware for provided update type. | updateTypes | `string/string[]` | Update type | | middleware | `function` | Middleware | -##### hears +#### hears Registers middleware for handling `text` messages. @@ -817,7 +810,7 @@ Registers middleware for handling `text` messages. | triggers | `string/string[]/RegEx/RegEx[]/Function` | Triggers | | middleware | `function` | Middleware | -##### command +#### command Command handling. @@ -828,7 +821,7 @@ Command handling. | commands | `string/string[]` | Commands | | middleware | `function` | Middleware | -##### start +#### start Handler for /start command. @@ -838,7 +831,7 @@ Handler for /start command. | --- | --- | --- | | middleware | `function` | Middleware | -##### help +#### help Handler for /help command. @@ -848,7 +841,7 @@ Handler for /help command. | --- | --- | --- | | middleware | `function` | Middleware | -##### settings +#### settings Handler for /settings command. @@ -858,7 +851,7 @@ Handler for /settings command. | --- | --- | --- | | middleware | `function` | Middleware | -##### entity +#### entity Entity handling. @@ -869,7 +862,7 @@ Entity handling. | entity | `string/string[]/RegEx/RegEx[]/Function` | Entity name | | middleware | `function` | Middleware | -##### mention +#### mention Mention handling. @@ -880,7 +873,7 @@ Mention handling. | username | `string/string[]` | Username | | middleware | `function` | Middleware | -##### phone +#### phone Phone number handling. @@ -891,7 +884,7 @@ Phone number handling. | number | `string/string[]` | Phone number | | middleware | `function` | Middleware | -##### hashtag +#### hashtag Hashtag handling. @@ -902,7 +895,7 @@ Hashtag handling. | hashtag | `string/string[]` | Hashtag | | middleware | `function` | Middleware | -##### cashtag +#### cashtag Cashtag handling. @@ -913,7 +906,7 @@ Cashtag handling. | cashtag | `string/string[]` | Cashtag | | middleware | `function` | Middleware | -##### action +#### action Registers middleware for handling `callback_data` actions with regular expressions. @@ -924,8 +917,7 @@ Registers middleware for handling `callback_data` actions with regular expressio | triggers | `string/string[]/RegEx/RegEx[]` | Triggers | | middleware | `function` | Middleware | - -##### inlineQuery +#### inlineQuery Registers middleware for handling `inline_query` actions with regular expressions. @@ -936,8 +928,7 @@ Registers middleware for handling `inline_query` actions with regular expression | triggers | `string/string[]/RegEx/RegEx[]` | Triggers | | middleware | `function` | Middleware | - -##### gameQuery +#### gameQuery Registers middleware for handling `callback_data` actions with game query. @@ -947,9 +938,9 @@ Registers middleware for handling `callback_data` actions with game query. | --- | --- | --- | | middleware | `function` | Middleware | -##### launch +#### launch -Launch bot in long-polling or webhook mode. +Launch bot in long-polling or webhook mode. `telegraf.launch(options) => Promise` @@ -971,7 +962,7 @@ Launch options: } ``` -##### startPolling +#### startPolling Start poll updates. @@ -984,7 +975,7 @@ Start poll updates. | [allowedUpdates] | `string[]/string/null` | null | List the types of updates you want your bot to receive | | [stopCallback] | `function` | null | Polling stop callback | -##### startWebhook +#### startWebhook Start listening @ `https://host:port/webhookPath` for Telegram calls. @@ -997,7 +988,7 @@ Start listening @ `https://host:port/webhookPath` for Telegram calls. | port | `number` | Port number | | [host] | `string` | Hostname | -##### stop +#### stop Stop Webhook and polling @@ -1007,10 +998,9 @@ Stop Webhook and polling | --- | --- | | [callback] | function | -##### webhookCallback +#### webhookCallback -Return a callback function suitable for the http[s].createServer() method to handle a request. -You may also use this callback function to mount your telegraf app in a Connect/Express app. +Return a callback function suitable for the http[s].createServer() method to handle a request. You may also use this callback function to mount your telegraf app in a Connect/Express app. `telegraf.webhookCallback(webhookPath) => Function` @@ -1018,10 +1008,9 @@ You may also use this callback function to mount your telegraf app in a Connect/ | --- | --- | --- | | webhookPath | `string` | Webhook url path (see Telegraf.setWebhook) | -##### handleUpdate +#### handleUpdate -Handle raw Telegram update. -In case you use centralized webhook server, queue, etc. +Handle raw Telegram update. In case you use centralized webhook server, queue, etc. `telegraf.handleUpdate(rawUpdate, [webhookResponse])` @@ -1030,7 +1019,7 @@ In case you use centralized webhook server, queue, etc. | rawUpdate | `object` | Telegram update payload | | [webhookResponse] | `object` | [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) | -##### Telegraf.compose +#### Telegraf.compose Compose `middlewares` returning a fully valid middleware comprised of all those which are passed. @@ -1040,7 +1029,7 @@ Compose `middlewares` returning a fully valid middleware comprised of all those | --- | --- | --- | | middlewares | `function[]` | Array of middlewares | -##### Telegraf.mount +#### Telegraf.mount Generates a middleware for handling provided update types. @@ -1051,7 +1040,7 @@ Generates a middleware for handling provided update types. | updateTypes | `string/string[]` | Update type | | middleware | `function` | middleware | -##### Telegraf.hears +#### Telegraf.hears Generates a middleware for handling `text` messages with regular expressions. @@ -1062,7 +1051,7 @@ Generates a middleware for handling `text` messages with regular expressions. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.action +#### Telegraf.action Generates a middleware for handling `callbackQuery` data with regular expressions. @@ -1073,7 +1062,7 @@ Generates a middleware for handling `callbackQuery` data with regular expression | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.inlineQuery +#### Telegraf.inlineQuery Generates a middleware for handling `inlineQuery` data with regular expressions. @@ -1084,19 +1073,19 @@ Generates a middleware for handling `inlineQuery` data with regular expressions. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.passThru +#### Telegraf.passThru Generates pass thru middleware. `Telegraf.passThru() => function` -##### Telegraf.safePassThru +#### Telegraf.safePassThru Generates a safe version of pass thru middleware. `Telegraf.safePassThru() => function` -##### Telegraf.optional +#### Telegraf.optional Generates an optional middleware. @@ -1107,7 +1096,7 @@ Generates an optional middleware. | test | `truthy/function` | Value or predicate `(ctx) => bool` | | middleware | `function` | middleware | -##### Telegraf.acl +#### Telegraf.acl Generates a middleware for provided users only. @@ -1118,7 +1107,7 @@ Generates a middleware for provided users only. | userId | `string/string[]` | User id | | middleware | `function` | middleware | -##### Telegraf.drop +#### Telegraf.drop Generates drop middleware. @@ -1128,7 +1117,7 @@ Generates drop middleware. | --- | --- | --- | | test | `truthy/function` | Value or predicate `(ctx) => bool` | -##### Telegraf.filter +#### Telegraf.filter Generates filter middleware. @@ -1138,7 +1127,7 @@ Generates filter middleware. | --- | --- | --- | | test | `truthy/function` | Value or predicate `(ctx) => bool` | -##### Telegraf.branch +#### Telegraf.branch Generates branch middleware. @@ -1150,8 +1139,7 @@ Generates branch middleware. | trueMiddleware | `function` | true action middleware | | falseMiddleware | `function` | false action middleware | - -##### Telegraf.email +#### Telegraf.email Generates a middleware for handling messages with `email` entity. @@ -1162,7 +1150,7 @@ Generates a middleware for handling messages with `email` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.hashtag +#### Telegraf.hashtag Generates a middleware for handling messages with `hashtag` entity. @@ -1173,7 +1161,7 @@ Generates a middleware for handling messages with `hashtag` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.cashtag +#### Telegraf.cashtag Generates a middleware for handling messages with `cashtag` entity. @@ -1184,7 +1172,7 @@ Generates a middleware for handling messages with `cashtag` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.url +#### Telegraf.url Generates a middleware for handling messages with `url` entity. @@ -1195,7 +1183,7 @@ Generates a middleware for handling messages with `url` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.phone +#### Telegraf.phone Generates a middleware for handling messages with `phone` entity. @@ -1206,7 +1194,7 @@ Generates a middleware for handling messages with `phone` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.textLink +#### Telegraf.textLink Generates a middleware for handling messages with `text_link` entity. @@ -1217,7 +1205,7 @@ Generates a middleware for handling messages with `text_link` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -##### Telegraf.textMention +#### Telegraf.textMention Generates a middleware for handling messages with `text_mention` entity. @@ -1228,7 +1216,7 @@ Generates a middleware for handling messages with `text_mention` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegram +### Telegram Telegram client API reference. @@ -1236,7 +1224,7 @@ Telegram client API reference. const Telegram = require('telegraf/telegram') ``` -##### Constructor +#### Constructor Initialize new Telegram client. @@ -1256,13 +1244,13 @@ Telegram options: } ``` -##### webhookReply +#### webhookReply Use this property to control `reply via webhook` feature. `telegram.webhookReply = [bool]` -##### addStickerToSet +#### addStickerToSet Use this method to add a new sticker to a set created by the bot. @@ -1275,7 +1263,7 @@ Use this method to add a new sticker to a set created by the bot. | name | `string` | Sticker set name | | stickerData | `Object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | -##### answerCbQuery +#### answerCbQuery Use this method to send answers to callback queries. @@ -1289,7 +1277,7 @@ Use this method to send answers to callback queries. | [showAlert] | `bool` | Show alert instead of notification | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answercallbackquery) | -##### answerGameQuery +#### answerGameQuery Use this method to send answers to game query. @@ -1300,7 +1288,7 @@ Use this method to send answers to game query. | callbackQueryId | `string` | Query id | | url | `string` | Notification text | -##### answerShippingQuery +#### answerShippingQuery Use this method to send answers to shipping query. @@ -1313,7 +1301,7 @@ Use this method to send answers to shipping query. | shippingOptions | `object` | [Shipping Options](https://core.telegram.org/bots/api#answershippingquery) | | [errorMessage] | `string` | Error message in human readable form | -##### answerPreCheckoutQuery +#### answerPreCheckoutQuery Use this method to send answers to shipping query. @@ -1325,7 +1313,7 @@ Use this method to send answers to shipping query. | ok | `bool` | Specify True if everything is alright (goods are available, etc.) | | [errorMessage] | `string` | Error message in human readable form | -##### answerInlineQuery +#### answerInlineQuery Use this method to send answers to an inline query. @@ -1337,7 +1325,7 @@ Use this method to send answers to an inline query. | results | `object[]` | Results | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answerinlinequery)| -##### createNewStickerSet +#### createNewStickerSet Use this method to create new sticker set owned by a user. @@ -1352,7 +1340,7 @@ Use this method to create new sticker set owned by a user. | stickerData | `object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | | [isMasks] | `bool` | Pass True, if a set of mask stickers should be created | -##### deleteChatStickerSet +#### deleteChatStickerSet Use this method to delete a group sticker set from a supergroup. @@ -1363,7 +1351,7 @@ Use this method to delete a group sticker set from a supergroup. | --- | --- | --- | | chatId | `number/string` | Chat id | -##### deleteMessage +#### deleteMessage Use this method to delete bot messages. @@ -1375,7 +1363,7 @@ Use this method to delete bot messages. | chatId | `number/string` | Chat id | | messageId | `string` | Message id | -##### setStickerSetThumb +#### setStickerSetThumb Use this method to set the thumbnail of a sticker set. @@ -1388,7 +1376,7 @@ Use this method to set the thumbnail of a sticker set. | userId | `string` | User identifier of the sticker set owner | | thumb | `File` | A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size | -##### deleteStickerFromSet +#### deleteStickerFromSet Use this method to delete a sticker from a set created by the bot. @@ -1399,7 +1387,7 @@ Use this method to delete a sticker from a set created by the bot. | --- | --- | --- | | stickerId | `string` | File identifier of the sticker | -##### editMessageCaption +#### editMessageCaption Use this method to edit captions of messages sent by the bot or via the bot. @@ -1413,7 +1401,7 @@ Use this method to edit captions of messages sent by the bot or via the bot. | caption | `string` | Caption | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagecaption)| -##### editMessageMedia +#### editMessageMedia Use this method to edit media of messages sent by the bot or via the bot. @@ -1427,7 +1415,7 @@ Use this method to edit media of messages sent by the bot or via the bot. | media | `InputMedia` | [InputMedia](https://core.telegram.org/bots/api#inputmedia) | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagemedia)| -##### editMessageLiveLocation +#### editMessageLiveLocation Use this method to edit live location messages sent by the bot or via the bot. @@ -1444,7 +1432,7 @@ Use this method to edit live location messages sent by the bot or via the bot. | [markup] | `object` | Keyboard markup | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagelivelocation)| -##### editMessageReplyMarkup +#### editMessageReplyMarkup Use this method to edit only the reply markup of messages sent by the bot or via the bot. @@ -1458,7 +1446,7 @@ Use this method to edit only the reply markup of messages sent by the bot or via | markup | `object` | Keyboard markup | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagereplymarkup)| -##### editMessageText +#### editMessageText Use this method to edit text messages sent by the bot or via the bot. @@ -1472,7 +1460,7 @@ Use this method to edit text messages sent by the bot or via the bot. | text | `string` | Message | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagetext)| -##### forwardMessage +#### forwardMessage Forwards message. @@ -1485,7 +1473,7 @@ Forwards message. | messageId | `number` | Message id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#forwardmessage)| -##### sendCopy +#### sendCopy Sends message copy. @@ -1497,7 +1485,7 @@ Sends message copy. | message | `object` | Message | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| -##### copyMessage +#### copyMessage Use this method to copy messages of any kind. @@ -1510,13 +1498,13 @@ Use this method to copy messages of any kind. | messageId | `number` | Message id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#copymessage)| -##### getWebhookInfo +#### getWebhookInfo Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. `telegram.getWebhookInfo() => Promise` -##### getChat +#### getChat Use this method to get up to date information about the chat (current name of the user for one-on-one conversatio ns, current username of a user, group or channel, etc.). @@ -1528,7 +1516,7 @@ ns, current username of a user, group or channel, etc.). | --- | --- | --- | | chatId | `number/string` | Chat id | -##### getChatAdministrators +#### getChatAdministrators Use this method to get a list of administrators in a chat. On success, returns an Array of 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. @@ -1539,7 +1527,7 @@ Use this method to get a list of administrators in a chat. On success, returns a | --- | --- | --- | | chatId | `number/string` | Chat id | -##### setGameScore +#### setGameScore Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat. @@ -1556,7 +1544,7 @@ Use this method to set the score of the specified user in a game. On success, if | [editMessage] | `boolean` | edit target message, default value is True | | [force] | `boolean` | Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters | -##### getGameHighScores +#### getGameHighScores Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. @@ -1570,7 +1558,7 @@ Use this method to get data for high score tables. Will return the score of the | chatId | `number/string` | Target Chat id | | messageId | `number/string` | Message id | -##### getChatMember +#### getChatMember Use this method to get information about a member of a chat. @@ -1582,7 +1570,7 @@ Use this method to get information about a member of a chat. | chatId | `number/string` | Chat id | | userId | `number` | User identifier | -##### getChatMembersCount +#### getChatMembersCount Use this method to get the number of members in a chat. @@ -1593,7 +1581,7 @@ Use this method to get the number of members in a chat. | --- | --- | --- | | chatId | `number/string` | Chat id | -##### getFile +#### getFile Returns basic info about a file and prepare it for downloading. @@ -1604,7 +1592,7 @@ Returns basic info about a file and prepare it for downloading. | --- | --- | --- | | fileId | `string` | File id | -##### getFileLink +#### getFileLink Returns link to file. @@ -1614,22 +1602,21 @@ Returns link to file. | --- | --- | --- | | fileId | `string/object` | File id or file object | -##### getMe +#### getMe Returns basic information about the bot. `telegram.getMe() => Promise` [Official documentation](https://core.telegram.org/bots/api#getme) -##### getMyCommands +#### getMyCommands -Use this method to get the current list of the bot's commands. -Requires no parameters. Returns Array of BotCommand on success. +Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success. `telegram.getMyCommands() => Promise` [Official documentation](https://core.telegram.org/bots/api#getmycommands) -##### getStickerSet +#### getStickerSet Use this method to get a sticker set. @@ -1640,7 +1627,7 @@ Use this method to get a sticker set. | name | `string` | Short name of the sticker set | [Official documentation](https://core.telegram.org/bots/api#getstickerset) -##### getUserProfilePhotos +#### getUserProfilePhotos Returns profiles photos for provided user. @@ -1653,7 +1640,7 @@ Returns profiles photos for provided user. | [offset] | `number` | Offset | | [limit] | `number` | Limit | -##### setChatPermissions +#### setChatPermissions Use this method to set default chat permissions for all members. @@ -1664,7 +1651,7 @@ Use this method to set default chat permissions for all members. | chatId | `number/string` | Chat id | | permissions | `object` | [New default chat permissions](https://core.telegram.org/bots/api#chatpermissions)| -##### kickChatMember +#### kickChatMember Use this method to kick a user from a group or a supergroup. @@ -1676,9 +1663,9 @@ Use this method to kick a user from a group or a supergroup. | userId | `number` | User id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#kickchatmember)| -##### restrictChatMember +#### restrictChatMember -Use this method to restrict a user in a supergroup. +Use this method to restrict a user in a supergroup. `telegram.restrictChatMember(chatId, userId, [extra]) => Promise` @@ -1688,7 +1675,7 @@ Use this method to restrict a user in a supergroup. | userId | `number` | User id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#restrictchatmember)| -##### promoteChatMember +#### promoteChatMember Use this method to promote or demote a user in a supergroup or a channel. @@ -1700,7 +1687,7 @@ Use this method to promote or demote a user in a supergroup or a channel. | userId | `number` | User id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#promotechatmember)| -##### setChatAdministratorCustomTitle +#### setChatAdministratorCustomTitle New custom title for the administrator; 0-16 characters, emoji are not allowed @@ -1712,7 +1699,7 @@ New custom title for the administrator; 0-16 characters, emoji are not allowed | userId | `number` | User id | | title | `string` | Custom title | -##### exportChatInviteLink +#### exportChatInviteLink Use this method to export an invite link to a supergroup or a channel. @@ -1723,7 +1710,7 @@ Use this method to export an invite link to a supergroup or a channel. | --- | --- | --- | | chatId | `number/string` | Chat id | -##### setChatPhoto +#### setChatPhoto Use this method to set a new profile photo for the chat. @@ -1735,7 +1722,7 @@ Use this method to set a new profile photo for the chat. | chatId | `number/string` | Chat id | | photo | `File` | New chat photo | -##### deleteChatPhoto +#### deleteChatPhoto Use this method to delete a chat photo. @@ -1746,7 +1733,7 @@ Use this method to delete a chat photo. | --- | --- | --- | | chatId | `number/string` | Chat id | -##### setChatTitle +#### setChatTitle Use this method to change the title of a chat. @@ -1758,7 +1745,7 @@ Use this method to change the title of a chat. | chatId | `number/string` | Chat id | | title | `string` | New chat title, 1-255 characters | -##### setChatDescription +#### setChatDescription Use this method to change the description of a supergroup or a channel. @@ -1770,9 +1757,9 @@ Use this method to change the description of a supergroup or a channel. | chatId | `number/string` | Chat id | | description | `string` | New chat description, 0-255 characters | -##### setChatStickerSet +#### setChatStickerSet -Use this method to set a new group sticker set for a supergroup. +Use this method to set a new group sticker set for a supergroup. `telegram.setChatStickerSet(chatId, stickerSetName) => Promise` [Official documentation](https://core.telegram.org/bots/api#setchatstickerset) @@ -1782,7 +1769,7 @@ Use this method to set a new group sticker set for a supergroup. | chatId | `number/string` | Chat id | | stickerSetName | `string` | Name of the sticker set | -##### pinChatMessage +#### pinChatMessage Use this method to pin a message in a supergroup. @@ -1794,7 +1781,7 @@ Use this method to pin a message in a supergroup. | messageId | `number` | Message id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#pinchatmessage)| -##### unpinChatMessage +#### unpinChatMessage Use this method to unpin a message in a supergroup chat. @@ -1806,7 +1793,7 @@ Use this method to unpin a message in a supergroup chat. | chatId | `number/string` | Chat id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unpinchatmessage)| -##### unpinAllChatMessages +#### unpinAllChatMessages Use this method to clear the list of pinned messages in a chat @@ -1817,7 +1804,7 @@ Use this method to clear the list of pinned messages in a chat | --- | --- | --- | | chatId | `number/string` | Chat id | -##### leaveChat +#### leaveChat Use this method for your bot to leave a group, supergroup or channel. @@ -1828,7 +1815,7 @@ Use this method for your bot to leave a group, supergroup or channel. | --- | --- | --- | | chatId | `number/string` | Chat id | -##### deleteWebhook +#### deleteWebhook Removes webhook integration. @@ -1839,7 +1826,7 @@ Removes webhook integration. | --- | --- | --- | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#deletewebhook) | -##### sendAudio +#### sendAudio Sends audio. @@ -1851,8 +1838,7 @@ Sends audio. | audio | `File` | Document | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendaudio)| - -##### sendGame +#### sendGame Sends game. @@ -1864,7 +1850,7 @@ Sends game. | gameName | `String` | Game short name | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendgame)| -##### sendChatAction +#### sendChatAction Sends chat action. @@ -1875,7 +1861,7 @@ Sends chat action. | chatId | `number/string` | Chat id | | action | `string` | [Chat action](https://core.telegram.org/bots/api#sendchataction) | -##### sendContact +#### sendContact Sends document. @@ -1888,7 +1874,7 @@ Sends document. | firstName | `string` | Contact first name | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendcontact)| -##### sendDice +#### sendDice Sends dice. @@ -1899,7 +1885,7 @@ Sends dice. | chatId | `number/string` | Chat id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddice)| -##### sendDocument +#### sendDocument Sends document. @@ -1911,7 +1897,7 @@ Sends document. | doc | `File` | Document | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddocument)| -##### sendLocation +#### sendLocation Sends location. @@ -1924,7 +1910,7 @@ Sends location. | longitude | `number` | Longitude | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendlocation)| -##### sendMessage +#### sendMessage Sends text message. @@ -1936,7 +1922,7 @@ Sends text message. | text | `string` | Message | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| -##### sendPhoto +#### sendPhoto Sends a photo. @@ -1948,7 +1934,7 @@ Sends a photo. | photo | `File` | Photo | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendphoto)| -##### sendMediaGroup +#### sendMediaGroup Sends media album. @@ -1960,7 +1946,7 @@ Sends media album. | media | `InputMedia[]` | Media array | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmediagroup)| -##### sendSticker +#### sendSticker Sends sticker. @@ -1972,7 +1958,7 @@ Sends sticker. | sticker | `File` | Document | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendsticker)| -##### setStickerPositionInSet +#### setStickerPositionInSet Use this method to move a sticker in a set created by the bot to a specific position. @@ -1983,7 +1969,7 @@ Use this method to move a sticker in a set created by the bot to a specific posi | sticker | `string` | File identifier of the sticker | | position | `number` | New sticker position in the set, zero-based | -##### sendVenue +#### sendVenue Sends venue information. @@ -1998,7 +1984,7 @@ Sends venue information. | address | `string` | Venue address | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvenue)| -##### sendInvoice +#### sendInvoice Sends invoice. @@ -2009,7 +1995,7 @@ Sends invoice. | chatId | `number/string` | Chat id | | invoice | `object` | [Invoice object](https://core.telegram.org/bots/api#sendinvoice) | -##### sendVideo +#### sendVideo Sends video. @@ -2021,7 +2007,7 @@ Sends video. | video | `File` | Document | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideo)| -##### sendAnimation +#### sendAnimation Sends video. @@ -2033,7 +2019,7 @@ Sends video. | animation | `File` | Document | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendanimation)| -##### sendVideoNote +#### sendVideoNote Sends round video. @@ -2045,7 +2031,7 @@ Sends round video. | video | `File` | Video note file | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideonote)| -##### sendVoice +#### sendVoice Sends voice. @@ -2057,7 +2043,7 @@ Sends voice. | voice | `File/string` | File, file id or HTTP URL | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvoice)| -##### sendPoll +#### sendPoll Sends a poll. @@ -2070,7 +2056,7 @@ Sends a poll. | options | `string[]` | Answer options | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| -##### setMyCommands +#### setMyCommands Use this method to change the list of the bot's commands @@ -2080,7 +2066,7 @@ Use this method to change the list of the bot's commands | --- | --- | --- | | commands | `object[]` | [List of bot commands](https://core.telegram.org/bots/api#setmycommands) | -##### sendQuiz +#### sendQuiz Sends quiz. @@ -2093,8 +2079,7 @@ Sends quiz. | options | `string[]` | Answer options | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| - -##### stopPoll +#### stopPoll Stops anonymous poll. @@ -2107,7 +2092,7 @@ Stops anonymous poll. | options| `string[]` | Answer options | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#stoppoll)| -##### stopMessageLiveLocation +#### stopMessageLiveLocation 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. @@ -2121,7 +2106,7 @@ Use this method to stop updating a live location message sent by the bot or via | inlineMessageId | `string` | Inline message id | | [markup] | `object` | Keyboard markup | -##### uploadStickerFile +#### uploadStickerFile Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods. @@ -2133,7 +2118,7 @@ Use this method to upload a .png file with a sticker for later use in createNewS | ownerId | `string` | User identifier of sticker file owner | | stickerFile | `File` | Png image with the sticker | -##### setWebhook +#### setWebhook Specifies an url to receive incoming updates via an outgoing webhook. @@ -2145,7 +2130,7 @@ Specifies an url to receive incoming updates via an outgoing webhook. | url | `string` | Public url for webhook | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#setwebhook) | -##### unbanChatMember +#### unbanChatMember Use this method to unban a previously kicked user in a supergroup. @@ -2158,11 +2143,9 @@ Use this method to unban a previously kicked user in a supergroup. | userId | `number` | User id | | [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unbanchatmember) | -##### setPassportDataErrors +#### setPassportDataErrors -Informs a user that some Telegram Passport elements they provided contains errors. -The user will not be able to re-submit their Passport to you -until the errors are fixed (the contents of the field for which you returned the error must change). +Informs a user that some Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). `telegram.setPassportDataErrors(errors) => Promise` [Official documentation](https://core.telegram.org/bots/api#setpassportdataerrors) @@ -2171,15 +2154,15 @@ until the errors are fixed (the contents of the field for which you returned the | --- | --- | --- | | [errors] | `PassportElementError[]` | An array describing the errors | -#### Extra +### Extra Telegram message options helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). -#### Markup +### Markup Telegram markup helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). -#### Stage +### Stage Simple scene-based control flow middleware. From 735319f33bd870aacb39eccc2d710e7e9e9f2d21 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sun, 17 Jan 2021 22:22:51 +0300 Subject: [PATCH 55/79] add MarkdownV2 --- typings/extra.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/typings/extra.d.ts b/typings/extra.d.ts index d6d627014..d1186f88d 100644 --- a/typings/extra.d.ts +++ b/typings/extra.d.ts @@ -19,6 +19,8 @@ export declare class Extra { markdown(value?: boolean): this + markdownV2(value?: boolean): this + caption(caption: string): this static load(opts: object): Extra From 44d38d128fe94ed82cc6ed27cee80a8ad970b8eb Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sun, 17 Jan 2021 23:10:47 +0300 Subject: [PATCH 56/79] missing pollRequestButton method --- markup.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/markup.js b/markup.js index ca0683c0c..df50ec1ed 100644 --- a/markup.js +++ b/markup.js @@ -59,6 +59,10 @@ class Markup { return Markup.locationRequestButton(text, hide) } + pollRequestButton (text, type, hide) { + return Markup.pollRequestButton(text, type, hide) + } + urlButton (text, url, hide) { return Markup.urlButton(text, url, hide) } From 67286fe7881510913bb27a1643f9543cc6bdb39d Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sun, 17 Jan 2021 23:53:02 +0300 Subject: [PATCH 57/79] improve button extends --- typings/markup.d.ts | 45 +++++++++++++++------------------------------ 1 file changed, 15 insertions(+), 30 deletions(-) diff --git a/typings/markup.d.ts b/typings/markup.d.ts index 778f3cb5a..f616c0642 100644 --- a/typings/markup.d.ts +++ b/typings/markup.d.ts @@ -4,25 +4,24 @@ import * as tt from './telegram-types.d' export interface Button { text: string - hide: boolean + + /** + * Keyboard builder sugar + */ + hide?: boolean } -export interface ContactRequestButton { - text: string - hide: boolean +export interface ContactRequestButton extends Button { request_contact: boolean } -export interface LocationRequestButton { - text: string - hide: boolean +export interface LocationRequestButton extends Button { request_location: boolean } type PollType = 'poll' | 'quiz' -export interface PollRequestButton { - text: string +export interface PollRequestButton extends Button { request_poll: { type?: PollType } } @@ -33,40 +32,28 @@ export type KeyboardButton = | PollRequestButton | string -export interface UrlButton { +export interface UrlButton extends Button { url: string - text: string - hide?: boolean } -export interface CallbackButton { - text: string - hide: boolean +export interface CallbackButton extends Button { callback_data: string } -export interface SwitchToChatButton { - text: string - hide: boolean +export interface SwitchToChatButton extends Button { switch_inline_query: string } -export interface SwitchToCurrentChatButton { - text: string - hide: boolean +export interface SwitchToCurrentChatButton extends Button { switch_inline_query_current_chat: string } -export interface GameButton { - text: string - hide: boolean +export interface GameButton extends Button { callback_game: tt.CallbackGame } -export interface PayButton { +export interface PayButton extends Button { pay: boolean - text: string - hide: boolean } export interface LoginUrl { @@ -76,10 +63,8 @@ export interface LoginUrl { request_write_access?: boolean } -export interface LoginButton { - text: string +export interface LoginButton extends Button { login_url: LoginUrl - hide: boolean } export type InlineKeyboardButton = From 2b5daea725249d55762dd6f92375f6210adf3590 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Mon, 18 Jan 2021 01:40:20 +0300 Subject: [PATCH 58/79] pretty TOC navigation --- docs/index.html | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/index.html b/docs/index.html index da6abfb71..05d204ad0 100644 --- a/docs/index.html +++ b/docs/index.html @@ -46,7 +46,10 @@
From 435ef654fff977a1652a8fb935affefa65a172d2 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Mon, 18 Jan 2021 01:55:30 +0300 Subject: [PATCH 59/79] correct Telegraf sublevels --- docs/README.md | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/docs/README.md b/docs/README.md index 224e4ca2d..13847f63b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1019,7 +1019,7 @@ Handle raw Telegram update. In case you use centralized webhook server, queue, e | rawUpdate | `object` | Telegram update payload | | [webhookResponse] | `object` | [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) | -#### Telegraf.compose +#### compose Compose `middlewares` returning a fully valid middleware comprised of all those which are passed. @@ -1029,7 +1029,7 @@ Compose `middlewares` returning a fully valid middleware comprised of all those | --- | --- | --- | | middlewares | `function[]` | Array of middlewares | -#### Telegraf.mount +#### mount Generates a middleware for handling provided update types. @@ -1040,7 +1040,7 @@ Generates a middleware for handling provided update types. | updateTypes | `string/string[]` | Update type | | middleware | `function` | middleware | -#### Telegraf.hears +#### hears Generates a middleware for handling `text` messages with regular expressions. @@ -1051,7 +1051,7 @@ Generates a middleware for handling `text` messages with regular expressions. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.action +#### action Generates a middleware for handling `callbackQuery` data with regular expressions. @@ -1062,7 +1062,7 @@ Generates a middleware for handling `callbackQuery` data with regular expression | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.inlineQuery +#### inlineQuery Generates a middleware for handling `inlineQuery` data with regular expressions. @@ -1073,19 +1073,19 @@ Generates a middleware for handling `inlineQuery` data with regular expressions. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.passThru +#### passThru Generates pass thru middleware. `Telegraf.passThru() => function` -#### Telegraf.safePassThru +#### safePassThru Generates a safe version of pass thru middleware. `Telegraf.safePassThru() => function` -#### Telegraf.optional +#### optional Generates an optional middleware. @@ -1096,7 +1096,7 @@ Generates an optional middleware. | test | `truthy/function` | Value or predicate `(ctx) => bool` | | middleware | `function` | middleware | -#### Telegraf.acl +#### acl Generates a middleware for provided users only. @@ -1107,7 +1107,7 @@ Generates a middleware for provided users only. | userId | `string/string[]` | User id | | middleware | `function` | middleware | -#### Telegraf.drop +#### drop Generates drop middleware. @@ -1117,7 +1117,7 @@ Generates drop middleware. | --- | --- | --- | | test | `truthy/function` | Value or predicate `(ctx) => bool` | -#### Telegraf.filter +#### filter Generates filter middleware. @@ -1127,7 +1127,7 @@ Generates filter middleware. | --- | --- | --- | | test | `truthy/function` | Value or predicate `(ctx) => bool` | -#### Telegraf.branch +#### branch Generates branch middleware. @@ -1139,7 +1139,7 @@ Generates branch middleware. | trueMiddleware | `function` | true action middleware | | falseMiddleware | `function` | false action middleware | -#### Telegraf.email +#### email Generates a middleware for handling messages with `email` entity. @@ -1150,7 +1150,7 @@ Generates a middleware for handling messages with `email` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.hashtag +#### hashtag Generates a middleware for handling messages with `hashtag` entity. @@ -1161,7 +1161,7 @@ Generates a middleware for handling messages with `hashtag` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.cashtag +#### cashtag Generates a middleware for handling messages with `cashtag` entity. @@ -1172,7 +1172,7 @@ Generates a middleware for handling messages with `cashtag` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.url +#### url Generates a middleware for handling messages with `url` entity. @@ -1183,7 +1183,7 @@ Generates a middleware for handling messages with `url` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.phone +#### phone Generates a middleware for handling messages with `phone` entity. @@ -1194,7 +1194,7 @@ Generates a middleware for handling messages with `phone` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.textLink +#### textLink Generates a middleware for handling messages with `text_link` entity. @@ -1205,7 +1205,7 @@ Generates a middleware for handling messages with `text_link` entity. | triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | | handler | `function` | Handler | -#### Telegraf.textMention +#### textMention Generates a middleware for handling messages with `text_mention` entity. From 80fcc21028c46afb3a07055c3cd4fdeb1999788b Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Mon, 18 Jan 2021 07:33:56 +0300 Subject: [PATCH 60/79] init --- docs/README.md | 2109 +-------------------------------- docs/_sidebar.md | 8 + docs/api-reference.md | 1472 +++++++++++++++++++++++ docs/extra.md | 3 + docs/getting-started.md | 625 ++++++++++ docs/index.html | 27 +- docs/markup.md | 3 + docs/{ => media}/header.png | Bin docs/{ => media}/telegraf.png | Bin docs/stage.md | 42 + docs/telegraf.md | 481 ++++++++ docs/telegram.md | 937 +++++++++++++++ 12 files changed, 3592 insertions(+), 2115 deletions(-) create mode 100644 docs/_sidebar.md create mode 100644 docs/api-reference.md create mode 100644 docs/extra.md create mode 100644 docs/getting-started.md create mode 100644 docs/markup.md rename docs/{ => media}/header.png (100%) rename docs/{ => media}/telegraf.png (100%) create mode 100644 docs/stage.md create mode 100644 docs/telegraf.md create mode 100644 docs/telegram.md diff --git a/docs/README.md b/docs/README.md index 13847f63b..b5b71982e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,10 +1,10 @@ -![Telegraf](header.png) +![Telegraf](media/header.png) -## Introduction +# Introduction Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server. -### Features +## Features - Full [Telegram Bot API 5.0](https://core.telegram.org/bots/api) support - [Telegram Payment Platform](https://telegram.org/blog/payments) @@ -16,7 +16,7 @@ Bots are special [Telegram](https://telegram.org) accounts designed to handle me - Easy to extend - `TypeScript` typings -### Installation +## Installation ```bash npm install telegraf --save @@ -28,7 +28,7 @@ or using yarn yarn add telegraf ``` -### Example +## Example ```js const { Telegraf } = require('telegraf') @@ -105,2102 +105,3 @@ For additional bot examples see [`examples`](https://github.com/telegraf/telegra | [BibleBot](https://github.com/Kriv-Art/BibleBot) | Bot to get bible verses | | [BitcoinDogBot](https://github.com/jibital/bitcoin-dog-bot) | Bitcoin prices, Technical analysis and Alerts! | | Send PR to add link to your bot | | - -## Getting started - -### Telegram token - -To use the [Telegram Bot API](https://core.telegram.org/bots/api), you first have to [get a bot account](https://core.telegram.org/bots) by [chatting with BotFather](https://core.telegram.org/bots#6-botfather). - -BotFather will give you a *token*, something like `123456789:AbCdfGhIJKlmNoQQRsTUVwxyZ`. - -### Bot - -A Telegraf bot is an object containing an array of middlewares which are composed and executed in a stack-like manner upon request. Is similar to many other middleware systems that you may have encountered such as Koa, Ruby's Rack, Connect. - -### Middleware - -Middleware is an essential part of any modern framework. -It allows you to modify requests and responses as they pass between the Telegram and your bot. - -You can imagine a middleware as a chain of logic connection your bot to the Telegram request. - -Middleware normally takes two parameters (ctx, next), `ctx` is the context for one Telegram update, `next` is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion. - -```js -const bot = new Telegraf(process.env.BOT_TOKEN) - -bot.use(async (ctx, next) => { - const start = new Date() - await next() - const ms = new Date() - start - console.log('Response time: %sms', ms) -}) - -bot.on('text', (ctx) => ctx.reply('Hello World')) -bot.launch() -``` - -#### Known middleware - -- [Internationalization](https://github.com/telegraf/telegraf-i18n) -- [Redis powered session](https://github.com/telegraf/telegraf-session-redis) -- [Local powered session (via lowdb)](https://github.com/RealSpeaker/telegraf-session-local) -- [Rate-limiting](https://github.com/telegraf/telegraf-ratelimit) -- [Menus via inline keyboards](https://github.com/EdJoPaTo/telegraf-inline-menu) -- [Natural language processing via wit.ai](https://github.com/telegraf/telegraf-wit) -- [Natural language processing via recast.ai](https://github.com/telegraf/telegraf-recast) -- [Multivariate and A/B testing](https://github.com/telegraf/telegraf-experiments) -- [Powerful bot stats via Mixpanel](https://github.com/telegraf/telegraf-mixpanel) -- [statsd integration](https://github.com/telegraf/telegraf-statsd) -- [and more...](https://www.npmjs.com/search?q=telegraf-) - -### Error handling - -By default, Telegraf will print all errors to `stderr` and rethrow error. - -To perform custom error-handling logic use following snippet: - -```js -const bot = new Telegraf(process.env.BOT_TOKEN) -bot.catch((err, ctx) => { - console.log(`Ooops, encountered an error for ${ctx.updateType}`, err) -}) -bot.start((ctx) => { - throw new Error('Example error') -}) -bot.launch() -``` - -### Context - -A Telegraf Context encapsulates telegram update. -Context is created per request and contains following props: - -| Property | Description | -| --- | --- | -| ` ctx.telegram ` | Telegram client instance | -| ` ctx.updateType ` | Update type (message, inline_query, etc.) | -| `[ctx.updateSubTypes]` | Update subtypes (text, sticker, audio, etc.) | -| `[ctx.message]` | Received message | -| `[ctx.editedMessage]` | Edited message | -| `[ctx.inlineQuery]` | Received inline query | -| `[ctx.chosenInlineResult]` | Received inline query result | -| `[ctx.callbackQuery]` | Received callback query | -| `[ctx.shippingQuery]` | Shipping query | -| `[ctx.preCheckoutQuery]` | Pre-checkout query | -| `[ctx.channelPost]` | New incoming channel post of any kind — text, photo, sticker, etc. | -| `[ctx.editedChannelPost]` | New version of a channel post that is known to the bot and was edited | -| `[ctx.poll]` | New version of a anonymous poll that is known to the bot and was changed | -| `[ctx.pollAnswer]` | This object represents an answer of a user in a non-anonymous poll. | -| `[ctx.chat]` | Current chat info | -| `[ctx.from]` | Sender info | -| `[ctx.match]` | Regex match (available only for `hears`, `command`, `action`, `inlineQuery` handlers) | -| ` ctx.webhookReply ` | Shortcut to `ctx.telegram.webhookReply` | - -```js -bot.use((ctx) => { - console.log(ctx.message) -}) -``` - -#### Extending context - -The recommended way to extend bot context: - -```js -const bot = new Telegraf(process.env.BOT_TOKEN) - -bot.context.db = { - getScores: () => { return 42 } -} - -bot.on('text', (ctx) => { - const scores = ctx.db.getScores(ctx.message.from.username) - return ctx.reply(`${ctx.message.from.username}: ${scores}`) -}) - -bot.launch() -``` - -#### Shortcuts - -Context shortcuts for **message** update: - -| Shortcut | Bound to | -| --- | --- | -| `addStickerToSet` | [`telegram.addStickerToSet`](#addstickertoset) | -| `createNewStickerSet` | [`telegram.createNewStickerSet`](#createnewstickerset) | -| `deleteChatPhoto` | [`telegram.deleteChatPhoto`](#deletechatphoto) | -| `deleteMessage` | [`telegram.deleteMessage`](#deletemessage) | -| `deleteStickerFromSet` | [`telegram.deleteStickerFromSet`](#deletestickerfromset) | -| `exportChatInviteLink` | [`telegram.exportChatInviteLink`](#exportchatinvitelink) | -| `forwardMessage` | [`telegram.forwardMessage`](#forwardmessage) | -| `getChat` | [`telegram.getChat`](#getchat) | -| `getChatAdministrators` | [`telegram.getChatAdministrators`](#getchatadministrators) | -| `getChatMember` | [`telegram.getChatMember`](#getchatmember) | -| `getChatMembersCount` | [`telegram.getChatMembersCount`](#getchatmemberscount) | -| `getMyCommands` | [`telegram.getMyCommands`](#getmycommands) | -| `getStickerSet` | [`telegram.getStickerSet`](#getstickerset) | -| `leaveChat` | [`telegram.leaveChat`](#leavechat) | -| `pinChatMessage` | [`telegram.pinChatMessage`](#pinchatmessage) | -| `reply` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithAudio` | [`telegram.sendAudio`](#sendaudio) | -| `replyWithChatAction` | [`telegram.sendChatAction`](#sendchataction) | -| `replyWithDice` | [`telegram.sendDice`](#senddice) | -| `replyWithDocument` | [`telegram.sendDocument`](#senddocument) | -| `replyWithGame` | [`telegram.sendGame`](#sendgame) | -| `replyWithHTML` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithInvoice` | [`telegram.sendInvoice`](#sendinvoice) | -| `replyWithLocation` | [`telegram.sendLocation`](#sendlocation) | -| `replyWithMarkdown` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithMediaGroup` | [`telegram.sendMediaGroup`](#sendmediagroup) | -| `replyWithPhoto` | [`telegram.sendPhoto`](#sendphoto) | -| `replyWithPoll` | [`telegram.sendPoll`](#sendpoll) | -| `replyWithQuiz` | [`telegram.sendQuiz`](#sendquiz) | -| `replyWithSticker` | [`telegram.sendSticker`](#sendsticker) | -| `replyWithVideo` | [`telegram.sendVideo`](#sendvideo) | -| `replyWithVideoNote` | [`telegram.sendVideoNote`](#sendvideonote) | -| `replyWithVoice` | [`telegram.sendVoice`](#sendvoice) | -| `setChatDescription` | [`telegram.setChatDescription`](#setchatdescription) | -| `setChatPhoto` | [`telegram.setChatPhoto`](#setchatphoto) | -| `setChatTitle` | [`telegram.setChatTitle`](#setchattitle) | -| `setMyCommands` | [`telegram.setMyCommands`](#setmycommands) | -| `setPassportDataErrors` | [`telegram.setPassportDataErrors`](#setpassportdataerrors) | -| `setStickerPositionInSet` | [`telegram.setStickerPositionInSet`](#setstickerpositioninset) | -| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | -| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | -| `stopPoll` | [`telegram.stopPoll`](#stoppoll) | -| `unpinChatMessage` | [`telegram.unpinChatMessage`](#unpinchatmessage) | -| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](#unpinallchatmessages) | -| `uploadStickerFile` | [`telegram.uploadStickerFile`](#uploadstickerfile) | -| `unbanChatMember` | [`telegram.unbanChatMember`](#unbanchatmember) | - -Context shortcuts for **callback_query** update: - -| Shortcut | Bound to | -| --- | --- | -| `addStickerToSet` | [`telegram.addStickerToSet`](#addstickertoset) | -| `answerCbQuery` | [`telegram.answerCbQuery`](#answercbquery) | -| `answerGameQuery` | [`telegram.answerGameQuery`](#answergamequery) | -| `createNewStickerSet` | [`telegram.createNewStickerSet`](#createnewstickerset) | -| `deleteChatPhoto` | [`telegram.deleteChatPhoto`](#deletechatphoto) | -| `deleteMessage` | [`telegram.deleteMessage`](#deletemessage) | -| `deleteStickerFromSet` | [`telegram.deleteStickerFromSet`](#deletestickerfromset) | -| `editMessageCaption` | [`telegram.editMessageCaption`](#editmessagecaption) | -| `editMessageMedia` | [`telegram.editMessageMedia`](#editmessagemedia) | -| `editMessageReplyMarkup` | [`telegram.editMessageReplyMarkup`](#editmessagereplymarkup) | -| `editMessageText` | [`telegram.editMessageText`](#editmessagetext) | -| `exportChatInviteLink` | [`telegram.exportChatInviteLink`](#exportchatinvitelink) | -| `forwardMessage` | [`telegram.forwardMessage`](#forwardmessage) | -| `getChat` | [`telegram.getChat`](#getchat) | -| `getChatAdministrators` | [`telegram.getChatAdministrators`](#getchatadministrators) | -| `getChatMember` | [`telegram.getChatMember`](#getchatmember) | -| `getChatMembersCount` | [`telegram.getChatMembersCount`](#getchatmemberscount) | -| `getStickerSet` | [`telegram.getStickerSet`](#getstickerset) | -| `leaveChat` | [`telegram.leaveChat`](#leavechat) | -| `pinChatMessage` | [`telegram.pinChatMessage`](#pinchatmessage) | -| `reply` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithAnimation` | [`telegram.sendAnimation`](#sendanimation) | -| `replyWithAudio` | [`telegram.sendAudio`](#sendaudio) | -| `replyWithChatAction` | [`telegram.sendChatAction`](#sendchataction) | -| `replyWithDice` | [`telegram.sendDice`](#senddice) | -| `replyWithDocument` | [`telegram.sendDocument`](#senddocument) | -| `replyWithGame` | [`telegram.sendGame`](#sendgame) | -| `replyWithHTML` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithInvoice` | [`telegram.sendInvoice`](#sendinvoice) | -| `replyWithLocation` | [`telegram.sendLocation`](#sendlocation) | -| `replyWithMarkdown` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithMediaGroup` | [`telegram.sendMediaGroup`](#sendmediagroup) | -| `replyWithPhoto` | [`telegram.sendPhoto`](#sendphoto) | -| `replyWithPoll` | [`telegram.sendPoll`](#sendpoll) | -| `replyWithSticker` | [`telegram.sendSticker`](#sendsticker) | -| `replyWithVideo` | [`telegram.sendVideo`](#sendvideo) | -| `replyWithVideoNote` | [`telegram.sendVideoNote`](#sendvideonote) | -| `replyWithVoice` | [`telegram.sendVoice`](#sendvoice) | -| `setChatDescription` | [`telegram.setChatDescription`](#setchatdescription) | -| `setChatPhoto` | [`telegram.setChatPhoto`](#setchatphoto) | -| `setChatTitle` | [`telegram.setChatTitle`](#setchattitle) | -| `setStickerPositionInSet` | [`telegram.setStickerPositionInSet`](#setstickerpositioninset) | -| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | -| `stopPoll` | [`telegram.stopPoll`](#stoppoll) | -| `unpinChatMessage` | [`telegram.unpinChatMessage`](#unpinchatmessage) | -| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](#unpinallchatmessages) | -| `uploadStickerFile` | [`telegram.uploadStickerFile`](#uploadstickerfile) | -| `unbanChatMember` | [`telegram.unbanChatMember`](#unbanchatmember) | - -Context shortcuts for **inline_query** update: - -| Shortcut | Bound to | -| --- | --- | -| `answerInlineQuery` | [`telegram.answerInlineQuery`](#answerinlinequery) | - -Context shortcuts for **shipping_query** update: - -| Shortcut | Bound to | -| --- | --- | -| `answerShippingQuery` | [`telegram.answerShippingQuery`](#answershippingquery) | - -Context shortcuts for **pre_checkout_query** update: - -| Shortcut | Bound to | -| --- | --- | -| `answerPreCheckoutQuery` | [`telegram.answerPreCheckoutQuery`](#answerprecheckoutquery) | - -##### Shortcuts usage example - -```js -const bot = new Telegraf(process.env.BOT_TOKEN) - -bot.command('quit', (ctx) => { - // Explicit usage - ctx.telegram.leaveChat(ctx.message.chat.id) - - // Using context shortcut - ctx.leaveChat() -}) - -bot.on('text', (ctx) => { - // Explicit usage - ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`) - - // Using context shortcut - ctx.reply(`Hello ${ctx.state.role}`) -}) - -bot.on('callback_query', (ctx) => { - // Explicit usage - ctx.telegram.answerCbQuery(ctx.callbackQuery.id) - - // Using context shortcut - ctx.answerCbQuery() -}) - -bot.on('inline_query', (ctx) => { - const result = [] - // Explicit usage - ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result) - - // Using context shortcut - ctx.answerInlineQuery(result) -}) - -bot.launch() -``` - -### State - -The recommended namespace to share information between middlewares. - -```js -const bot = new Telegraf(process.env.BOT_TOKEN) - -// Naive authorization middleware -bot.use((ctx, next) => { - ctx.state.role = getUserRole(ctx.message) - return next() -}) - -bot.on('text', (ctx) => { - return ctx.reply(`Hello ${ctx.state.role}`) -}) - -bot.launch() -``` - -### Session - -```js -const session = require('telegraf/session') - -const bot = new Telegraf(process.env.BOT_TOKEN) -bot.use(session()) -bot.on('text', (ctx) => { - ctx.session.counter = ctx.session.counter || 0 - ctx.session.counter++ - return ctx.reply(`Message counter:${ctx.session.counter}`) -}) - -bot.launch() -``` - -**Note: For persistent sessions you can use any of [`telegraf-session-*`](https://www.npmjs.com/search?q=telegraf-session) middleware.** - -**Tip: To use same session in private chat with the bot and in inline mode, use following session key resolver:** - -```js -{ - getSessionKey: (ctx) => { - if (ctx.from && ctx.chat) { - return `${ctx.from.id}:${ctx.chat.id}` - } else if (ctx.from && ctx.inlineQuery) { - return `${ctx.from.id}:${ctx.from.id}` - } - return null - } -} -``` - -### Update types - -Supported update types: - -- `message` -- `edited_message` -- `callback_query` -- `inline_query` -- `shipping_query` -- `pre_checkout_query` -- `chosen_inline_result` -- `channel_post` -- `edited_channel_post` - -Available update sub-types: - -- `text` -- `audio` -- `dice` -- `document` -- `photo` -- `sticker` -- `video` -- `voice` -- `contact` -- `location` -- `venue` -- `forward` -- `new_chat_members` -- `left_chat_member` -- `new_chat_title` -- `new_chat_photo` -- `delete_chat_photo` -- `group_chat_created` -- `migrate_to_chat_id` -- `supergroup_chat_created` -- `channel_chat_created` -- `migrate_from_chat_id` -- `pinned_message` -- `game` -- `video_note` -- `invoice` -- `successful_payment` -- `connected_website` -- `passport_data` -- `poll` - -```js -// Handle message update -bot.on('message', (ctx) => { - return ctx.reply('Hello') -}) - -// Handle sticker or photo update -bot.on(['sticker', 'photo'], (ctx) => { - console.log(ctx.message) - return ctx.reply('Cool!') -}) -``` - -[Official Docs](https://core.telegram.org/bots/api#message) - -### Webhooks - -```js -require('dotenv') - -const bot = new Telegraf(process.env.BOT_TOKEN) - -// TLS options -const tlsOptions = { - key: fs.readFileSync('server-key.pem'), - cert: fs.readFileSync('server-cert.pem'), - ca: [ - // This is necessary only if the client uses a self-signed certificate. - fs.readFileSync('client-cert.pem') - ] -} - -// Set telegram webhook -// The second argument is necessary only if the client uses a self-signed -// certificate. Including it for a verified certificate may cause things to break. -bot.telegram.setWebhook('https://server.tld:8443/secret-path', { - source: 'server-cert.pem' -}) - -// Start https webhook -bot.startWebhook('/secret-path', tlsOptions, 8443) - -// Http webhook, for nginx/heroku users. -bot.startWebhook('/secret-path', null, 5000) -``` - -Use webhookCallback() if you want to attach telegraf to existing http server - -```js -require('http') - .createServer(bot.webhookCallback('/secret-path')) - .listen(3000) - -require('https') - .createServer(tlsOptions, bot.webhookCallback('/secret-path')) - .listen(8443) -``` - -Express.js example integration - -```js -const { Telegraf } = require('telegraf') -const express = require('express') -const expressApp = express() - -const bot = new Telegraf(process.env.BOT_TOKEN) -expressApp.use(bot.webhookCallback('/secret-path')) -bot.telegram.setWebhook('https://server.tld:8443/secret-path') - -expressApp.get('/', (req, res) => { - res.send('Hello World!') -}) - -expressApp.listen(3000, () => { - console.log('Example app listening on port 3000!') -}) -``` - -Fastify example integration - -```js -const { Telegraf } = require('telegraf') -const fastifyApp = require('fastify')() - -const bot = new Telegraf(process.env.BOT_TOKEN) - -bot.on('text', ({ reply }) => reply('Hello')) -fastifyApp.use(bot.webhookCallback('/secret-path')) -// Set telegram webhook -// npm install -g localtunnel && lt --port 3000 -bot.telegram.setWebhook('https://------.localtunnel.me/secret-path') - -fastifyApp.listen(3000, () => { - console.log('Example app listening on port 3000!') -}) -``` - -Koa.js example integration - -```js -const { Telegraf } = require('telegraf') -const Koa = require('koa') -const koaBody = require('koa-body') - -const bot = new Telegraf(process.env.BOT_TOKEN) -bot.telegram.setWebhook('https://server.tld:8443/secret-path') - -const app = new Koa() -app.use(koaBody()) -app.use(async (ctx, next) => { - if (ctx.method !== 'POST' || ctx.url !== '/secret-path') { - return next() - } - await bot.handleUpdate(ctx.request.body, ctx.response) - ctx.status = 200 -}) -app.use(async (ctx) => { - ctx.body = 'Hello World' -}) - -app.listen(3000) -``` - -### Working with files - -Supported file sources: - -- `Existing file_id` -- `File path` -- `Url` -- `Buffer` -- `ReadStream` - -Also, you can provide an optional name of file as `filename`. - -```js -bot.on('message', (ctx) => { - // resend existing file by file_id - ctx.replyWithSticker('123123jkbhj6b') - - // send file - ctx.replyWithVideo({ source: '/path/to/video.mp4' }) - - // send stream - ctx.replyWithVideo({ - source: fs.createReadStream('/path/to/video.mp4') - }) - - // send buffer - ctx.replyWithVoice({ - source: Buffer.alloc() - }) - - // send url via Telegram server - ctx.replyWithPhoto('https://picsum.photos/200/300/') - - // pipe url content - ctx.replyWithPhoto({ - url: 'https://picsum.photos/200/300/?random', - filename: 'kitten.jpg' - }) -}) -``` - -### Telegram Passport - -To enable Telegram Passport support you can use [`telegram-passport`](https://www.npmjs.com/package/telegram-passport) package: - -```js -const { Telegraf } = require('telegraf') -const TelegramPassport = require('telegram-passport') - -const bot = new Telegraf(process.env.BOT_TOKEN) -const passport = new TelegramPassport("PRIVATE_KEY_IN_PEM_FORMAT") - -bot.on('passport_data', (ctx) => { - const decryptedPasswordData = passport.decrypt(ctx.passportData) - console.log(decryptedPasswordData) - return ctx.setPassportDataErrors([ - { source: 'selfie', type: 'driver_license', file_hash: 'file-hash', message: 'Selfie photo is too low quality'} - ]) -}) -``` - -### Telegraf Modules - -Telegraf Modules is higher level abstraction for writing modular Telegram bots. - -Module is simple js file with exported Telegraf middleware: - -```js -module.exports = (ctx) => ctx.reply('Hello from Telegraf Module!') -``` - -```js -const Composer = require('telegraf/composer') - -module.exports = Composer.mount( - 'sticker', - (ctx) => ctx.reply('Wow, sticker') -) -``` - -To run modules you can use `telegraf` module runner, it allows you to start Telegraf module easily from the command line. - -```bash -npm install telegraf -g -``` - -### Telegraf CLI usage - -```bash -telegraf [opts] - -t Bot token [$BOT_TOKEN] - -d Webhook domain - -H Webhook host [0.0.0.0] - -p Webhook port [$PORT or 3000] - -s Stop on error - -l Enable logs - -h Show this help message -``` - -#### Telegraf Module example - -Create a module with name `bot.js` and following content: - -```js -const Composer = require('telegraf/composer') -const PhotoURL = 'https://picsum.photos/200/300/?random' - -const bot = new Composer() -bot.start((ctx) => ctx.reply('Hello there!')) -bot.help((ctx) => ctx.reply('Help message')) -bot.command('photo', (ctx) => ctx.replyWithPhoto({ url: PhotoURL })) - -module.exports = bot -``` - -then run it: - -```bash -telegraf -t "bot token" bot.js -``` - -## API reference - -### Telegraf - -Telegraf API reference - -```js -const { Telegraf } = require('telegraf') -``` - -#### Constructor - -Initialize new Telegraf bot. - -`const telegraf = new Telegraf(token, [options])` - -| Param | Type | Description | -| --- | --- | --- | -| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) | -| [options] | `object` | Telegraf options | - -Telegraf options: - -```js -{ - telegram: { // Telegram options - agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc. - webhookReply: true // Reply via webhook - }, - username: '' // Bot username (optional) - channelMode: false // Handle `channel_post` updates as messages (optional) -} -``` - -#### token - -Use this property to get/set bot token. - -`telegraf.token = [string]` - -#### webhookReply - -Use this property to control `reply via webhook` feature. - -`telegraf.webhookReply = [bool]` - -#### use - -Registers a middleware. - -`telegraf.use(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware function | - -#### on - -Registers middleware for provided update type. - -`telegraf.on(updateTypes, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| updateTypes | `string/string[]` | Update type | -| middleware | `function` | Middleware | - -#### hears - -Registers middleware for handling `text` messages. - -`telegraf.hears(triggers, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function` | Triggers | -| middleware | `function` | Middleware | - -#### command - -Command handling. - -`telegraf.command(commands, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| commands | `string/string[]` | Commands | -| middleware | `function` | Middleware | - -#### start - -Handler for /start command. - -`telegraf.start(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware | - -#### help - -Handler for /help command. - -`telegraf.help(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware | - -#### settings - -Handler for /settings command. - -`telegraf.settings(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware | - -#### entity - -Entity handling. - -`telegraf.entity(entity, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| entity | `string/string[]/RegEx/RegEx[]/Function` | Entity name | -| middleware | `function` | Middleware | - -#### mention - -Mention handling. - -`telegraf.mention(username, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| username | `string/string[]` | Username | -| middleware | `function` | Middleware | - -#### phone - -Phone number handling. - -`telegraf.phone(number, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| number | `string/string[]` | Phone number | -| middleware | `function` | Middleware | - -#### hashtag - -Hashtag handling. - -`telegraf.hashtag(hashtag, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| hashtag | `string/string[]` | Hashtag | -| middleware | `function` | Middleware | - -#### cashtag - -Cashtag handling. - -`telegraf.cashtag(cashtag, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| cashtag | `string/string[]` | Cashtag | -| middleware | `function` | Middleware | - -#### action - -Registers middleware for handling `callback_data` actions with regular expressions. - -`telegraf.action(triggers, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]` | Triggers | -| middleware | `function` | Middleware | - -#### inlineQuery - -Registers middleware for handling `inline_query` actions with regular expressions. - -`telegraf.inlineQuery(triggers, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]` | Triggers | -| middleware | `function` | Middleware | - -#### gameQuery - -Registers middleware for handling `callback_data` actions with game query. - -`telegraf.gameQuery(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware | - -#### launch - -Launch bot in long-polling or webhook mode. - -`telegraf.launch(options) => Promise` - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| [options] | `object` | Launch options | - -Launch options: - -```js -{ - // Start bot in polling mode (Default) - // See startPolling reference - polling: { timeout, limit, allowedUpdates, stopCallback }, - - // Start bot in webhook mode - // See startWebhook reference - webhook: { domain, hookPath, port, host, tlsOptions, cb } -} -``` - -#### startPolling - -Start poll updates. - -`telegraf.startPolling([timeout], [limit], [allowedUpdates], [stopCallback])` - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| [timeout] | `number` | 30 | Poll timeout in seconds | -| [limit] | `number` | 100 | Limits the number of updates to be retrieved | -| [allowedUpdates] | `string[]/string/null` | null | List the types of updates you want your bot to receive | -| [stopCallback] | `function` | null | Polling stop callback | - -#### startWebhook - -Start listening @ `https://host:port/webhookPath` for Telegram calls. - -`telegraf.startWebhook(hookPath, [tlsOptions], port, [host])` - -| Param | Type | Description | -| --- | --- | --- | -| hookPath | `string` | Webhook url path (see Telegraf.setWebhook) | -| [tlsOptions] | `object` | [TLS server options](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener). Pass null to use http | -| port | `number` | Port number | -| [host] | `string` | Hostname | - -#### stop - -Stop Webhook and polling - -`telegraf.stop([callback]) => Promise` - -| Param | Type | -| --- | --- | -| [callback] | function | - -#### webhookCallback - -Return a callback function suitable for the http[s].createServer() method to handle a request. You may also use this callback function to mount your telegraf app in a Connect/Express app. - -`telegraf.webhookCallback(webhookPath) => Function` - -| Param | Type | Description | -| --- | --- | --- | -| webhookPath | `string` | Webhook url path (see Telegraf.setWebhook) | - -#### handleUpdate - -Handle raw Telegram update. In case you use centralized webhook server, queue, etc. - -`telegraf.handleUpdate(rawUpdate, [webhookResponse])` - -| Param | Type | Description | -| --- | --- | --- | -| rawUpdate | `object` | Telegram update payload | -| [webhookResponse] | `object` | [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) | - -#### compose - -Compose `middlewares` returning a fully valid middleware comprised of all those which are passed. - -`Telegraf.compose(middlewares) => function` - -| Param | Type | Description | -| --- | --- | --- | -| middlewares | `function[]` | Array of middlewares | - -#### mount - -Generates a middleware for handling provided update types. - -`Telegraf.mount(updateTypes, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| updateTypes | `string/string[]` | Update type | -| middleware | `function` | middleware | - -#### hears - -Generates a middleware for handling `text` messages with regular expressions. - -`Telegraf.hears(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### action - -Generates a middleware for handling `callbackQuery` data with regular expressions. - -`Telegraf.action(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### inlineQuery - -Generates a middleware for handling `inlineQuery` data with regular expressions. - -`Telegraf.inlineQuery(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### passThru - -Generates pass thru middleware. - -`Telegraf.passThru() => function` - -#### safePassThru - -Generates a safe version of pass thru middleware. - -`Telegraf.safePassThru() => function` - -#### optional - -Generates an optional middleware. - -`Telegraf.optional(test, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| test | `truthy/function` | Value or predicate `(ctx) => bool` | -| middleware | `function` | middleware | - -#### acl - -Generates a middleware for provided users only. - -`Telegraf.acl(userId, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| userId | `string/string[]` | User id | -| middleware | `function` | middleware | - -#### drop - -Generates drop middleware. - -`Telegraf.drop(test) => function` - -| Param | Type | Description | -| --- | --- | --- | -| test | `truthy/function` | Value or predicate `(ctx) => bool` | - -#### filter - -Generates filter middleware. - -`Telegraf.filter(test) => function` - -| Param | Type | Description | -| --- | --- | --- | -| test | `truthy/function` | Value or predicate `(ctx) => bool` | - -#### branch - -Generates branch middleware. - -`Telegraf.branch(test, trueMiddleware, falseMiddleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| test | `truthy/function` | Value or predicate `(ctx) => bool` | -| trueMiddleware | `function` | true action middleware | -| falseMiddleware | `function` | false action middleware | - -#### email - -Generates a middleware for handling messages with `email` entity. - -`Telegraf.email(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### hashtag - -Generates a middleware for handling messages with `hashtag` entity. - -`Telegraf.hashtag(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### cashtag - -Generates a middleware for handling messages with `cashtag` entity. - -`Telegraf.cashtag(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### url - -Generates a middleware for handling messages with `url` entity. - -`Telegraf.url(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### phone - -Generates a middleware for handling messages with `phone` entity. - -`Telegraf.phone(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### textLink - -Generates a middleware for handling messages with `text_link` entity. - -`Telegraf.textLink(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -#### textMention - -Generates a middleware for handling messages with `text_mention` entity. - -`Telegraf.textMention(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### Telegram - -Telegram client API reference. - -```js -const Telegram = require('telegraf/telegram') -``` - -#### Constructor - -Initialize new Telegram client. - -`const telegram = new Telegram(token, [options])` - -| Param | Type | Description | -| --- | --- | --- | -| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) | -| [options] | `object` | Telegram options | - -Telegram options: - -```js -{ - agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc. - webhookReply: true // Reply via webhook -} -``` - -#### webhookReply - -Use this property to control `reply via webhook` feature. - -`telegram.webhookReply = [bool]` - -#### addStickerToSet - -Use this method to add a new sticker to a set created by the bot. - -`telegram.addStickerToSet(ownerId, name, stickerData) => Promise` -[Official documentation](https://core.telegram.org/bots/api#addstickertoset) - -| Param | Type | Description | -| --- | --- | --- | -| ownerId | `string` | User identifier of sticker set owner | -| name | `string` | Sticker set name | -| stickerData | `Object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | - -#### answerCbQuery - -Use this method to send answers to callback queries. - -`telegram.answerCbQuery(callbackQueryId, text, [showAlert], [extra]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#answercallbackquery) - -| Param | Type | Description | -| --- | --- | --- | -| callbackQueryId | `string` | Query id | -| [text] | `string` | Notification text | -| [showAlert] | `bool` | Show alert instead of notification | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answercallbackquery) | - -#### answerGameQuery - -Use this method to send answers to game query. - -`telegram.answerGameQuery(callbackQueryId, url) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| callbackQueryId | `string` | Query id | -| url | `string` | Notification text | - -#### answerShippingQuery - -Use this method to send answers to shipping query. - -`telegram.answerShippingQuery(shippingQueryId, ok, shippingOptions, [errorMessage]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| shippingQueryId | `string` | Shipping Query id | -| ok | `bool` | Specify True if delivery to the specified address is possible | -| shippingOptions | `object` | [Shipping Options](https://core.telegram.org/bots/api#answershippingquery) | -| [errorMessage] | `string` | Error message in human readable form | - -#### answerPreCheckoutQuery - -Use this method to send answers to shipping query. - -`telegram.answerPreCheckoutQuery(preCheckoutQueryId, ok, [errorMessage]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| preCheckoutQueryId | `string` | Shipping Query id | -| ok | `bool` | Specify True if everything is alright (goods are available, etc.) | -| [errorMessage] | `string` | Error message in human readable form | - -#### answerInlineQuery - -Use this method to send answers to an inline query. - -`telegram.answerInlineQuery(inlineQueryId, results, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| inlineQueryId | `string` | Query id | -| results | `object[]` | Results | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answerinlinequery)| - -#### createNewStickerSet - -Use this method to create new sticker set owned by a user. - -`telegram.createNewStickerSet(ownerId, name, title, stickerData, [isMasks]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#createnewstickerset) - -| Param | Type | Description | -| --- | --- | --- | -| ownerId | `string` | User identifier of sticker set owner | -| name | `string` | Sticker set name | -| title | `string` | Sticker set title | -| stickerData | `object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | -| [isMasks] | `bool` | Pass True, if a set of mask stickers should be created | - -#### deleteChatStickerSet - -Use this method to delete a group sticker set from a supergroup. - -`telegram.deleteChatStickerSet(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletechatstickerset) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -#### deleteMessage - -Use this method to delete bot messages. - -`telegram.deleteMessage(chatId, messageId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletemessage) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | - -#### setStickerSetThumb - -Use this method to set the thumbnail of a sticker set. - -`telegram.setStickerSetThumb(name, userId, [thumb]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setstickersetthumb) - -| Param | Type | Description | -| --- | --- | --- | -| name | `string` | Sticker set name | -| userId | `string` | User identifier of the sticker set owner | -| thumb | `File` | A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size | - -#### deleteStickerFromSet - -Use this method to delete a sticker from a set created by the bot. - -`telegram.deleteStickerFromSet(stickerId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletestickerfromset) - -| Param | Type | Description | -| --- | --- | --- | -| stickerId | `string` | File identifier of the sticker | - -#### editMessageCaption - -Use this method to edit captions of messages sent by the bot or via the bot. - -`telegram.editMessageCaption(chatId, messageId, inlineMessageId, caption, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| caption | `string` | Caption | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagecaption)| - -#### editMessageMedia - -Use this method to edit media of messages sent by the bot or via the bot. - -`telegram.editMessageMedia(chatId, messageId, inlineMessageId, media, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| media | `InputMedia` | [InputMedia](https://core.telegram.org/bots/api#inputmedia) | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagemedia)| - -#### editMessageLiveLocation - -Use this method to edit live location messages sent by the bot or via the bot. - -`telegram.editMessageLiveLocation(latitude, longitude, chatId, messageId, inlineMessageId, [markup]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#editmessagelivelocation) - -| Param | Type | Description | -| --- | --- | --- | -| latitude | `string` | Latitude of new location | -| longitude | `string` | Longitude of new location | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| [markup] | `object` | Keyboard markup | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagelivelocation)| - -#### editMessageReplyMarkup - -Use this method to edit only the reply markup of messages sent by the bot or via the bot. - -`telegram.editMessageReplyMarkup(chatId, messageId, inlineMessageId, markup, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| markup | `object` | Keyboard markup | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagereplymarkup)| - -#### editMessageText - -Use this method to edit text messages sent by the bot or via the bot. - -`telegram.editMessageText(chatId, messageId, inlineMessageId, text, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| text | `string` | Message | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagetext)| - -#### forwardMessage - -Forwards message. - -`telegram.forwardMessage(chatId, fromChatId, messageId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Target Chat id | -| fromChatId | `number/string` | Source Chat id | -| messageId | `number` | Message id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#forwardmessage)| - -#### sendCopy - -Sends message copy. - -`telegram.sendCopy(chatId, message, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Target Chat id | -| message | `object` | Message | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| - -#### copyMessage - -Use this method to copy messages of any kind. - -`telegram.copyMessage(chatId, message, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Target Chat id | -| fromChatId | `number/string` | Source Chat id | -| messageId | `number` | Message id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#copymessage)| - -#### getWebhookInfo - -Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. - -`telegram.getWebhookInfo() => Promise` - -#### getChat - -Use this method to get up to date information about the chat (current name of the user for one-on-one conversatio -ns, current username of a user, group or channel, etc.). - -`telegram.getChat(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getchat) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -#### getChatAdministrators - -Use this method to get a list of administrators in a chat. On success, returns an Array of 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. - -`telegram.getChatAdministrators(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getchatadministrators) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -#### setGameScore - -Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat. - -`telegram.setGameScore(userId, score, inlineMessageId, chatId, messageId, [editMessage], [force]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setgamescore) - -| Param | Type | Description | -| --- | --- | --- | -| userId | `number` | Target User id | -| score | `number` | Target User id | -| inlineMessageId | `string` | Inline message id | -| chatId | `number/string` | Target Chat id | -| messageId | `number/string` | Message id | -| [editMessage] | `boolean` | edit target message, default value is True | -| [force] | `boolean` | Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters | - -#### getGameHighScores - -Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. - -`telegram.getGameHighScores(userId, inlineMessageId, chatId, messageId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getgamehighscores) - -| Param | Type | Description | -| --- | --- | --- | -| userId | `number`\ | Target User id | -| inlineMessageId | `string` | Inline message id | -| chatId | `number/string` | Target Chat id | -| messageId | `number/string` | Message id | - -#### getChatMember - -Use this method to get information about a member of a chat. - -`telegram.getChatMember(chatId, userId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getchatmember) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User identifier | - -#### getChatMembersCount - -Use this method to get the number of members in a chat. - -`telegram.getChatMembersCount(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getchatmemberscount) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -#### getFile - -Returns basic info about a file and prepare it for downloading. - -`telegram.getFile(fileId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getfile) - -| Param | Type | Description | -| --- | --- | --- | -| fileId | `string` | File id | - -#### getFileLink - -Returns link to file. - -`telegram.getFileLink(fileId) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| fileId | `string/object` | File id or file object | - -#### getMe - -Returns basic information about the bot. - -`telegram.getMe() => Promise` -[Official documentation](https://core.telegram.org/bots/api#getme) - -#### getMyCommands - -Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success. - -`telegram.getMyCommands() => Promise` -[Official documentation](https://core.telegram.org/bots/api#getmycommands) - -#### getStickerSet - -Use this method to get a sticker set. - -`telegram.getStickerSet(name) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| name | `string` | Short name of the sticker set | -[Official documentation](https://core.telegram.org/bots/api#getstickerset) - -#### getUserProfilePhotos - -Returns profiles photos for provided user. - -`telegram.getUserProfilePhotos(userId, [offset], [limit]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getuserprofilephotos) - -| Param | Type | Description | -| --- | --- | --- | -| userId | `number` | Chat id | -| [offset] | `number` | Offset | -| [limit] | `number` | Limit | - -#### setChatPermissions - -Use this method to set default chat permissions for all members. - -`telegram.setChatPermissions(chatId, permissions) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| permissions | `object` | [New default chat permissions](https://core.telegram.org/bots/api#chatpermissions)| - -#### kickChatMember - -Use this method to kick a user from a group or a supergroup. - -`telegram.kickChatMember(chatId, userId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#kickchatmember)| - -#### restrictChatMember - -Use this method to restrict a user in a supergroup. - -`telegram.restrictChatMember(chatId, userId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#restrictchatmember)| - -#### promoteChatMember - -Use this method to promote or demote a user in a supergroup or a channel. - -`telegram.promoteChatMember(chatId, userId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#promotechatmember)| - -#### setChatAdministratorCustomTitle - -New custom title for the administrator; 0-16 characters, emoji are not allowed - -`telegram.setChatAdministratorCustomTitle(chatId, userId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| title | `string` | Custom title | - -#### exportChatInviteLink - -Use this method to export an invite link to a supergroup or a channel. - -`telegram.exportChatInviteLink(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#exportchatinvitelink) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -#### setChatPhoto - -Use this method to set a new profile photo for the chat. - -`telegram.setChatPhoto(chatId, photo) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setchatphoto) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| photo | `File` | New chat photo | - -#### deleteChatPhoto - -Use this method to delete a chat photo. - -`telegram.deleteChatPhoto(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletechatphoto) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -#### setChatTitle - -Use this method to change the title of a chat. - -`telegram.setChatTitle(chatId, title) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setchattitle) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| title | `string` | New chat title, 1-255 characters | - -#### setChatDescription - -Use this method to change the description of a supergroup or a channel. - -`telegram.setChatDescription(chatId, description) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setchattitle) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| description | `string` | New chat description, 0-255 characters | - -#### setChatStickerSet - -Use this method to set a new group sticker set for a supergroup. - -`telegram.setChatStickerSet(chatId, stickerSetName) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setchatstickerset) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| stickerSetName | `string` | Name of the sticker set | - -#### pinChatMessage - -Use this method to pin a message in a supergroup. - -`telegram.pinChatMessage(chatId, messageId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `number` | Message id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#pinchatmessage)| - -#### unpinChatMessage - -Use this method to unpin a message in a supergroup chat. - -`telegram.unpinChatMessage(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#unpinchatmessage) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unpinchatmessage)| - -#### unpinAllChatMessages - -Use this method to clear the list of pinned messages in a chat - -`telegram.unpinAllChatMessages(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#unpinallchatmessages) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -#### leaveChat - -Use this method for your bot to leave a group, supergroup or channel. - -`telegram.leaveChat(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#leavechat) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -#### deleteWebhook - -Removes webhook integration. - -`telegram.deleteWebhook() => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletewebhook) - -| Param | Type | Description | -| --- | --- | --- | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#deletewebhook) | - -#### sendAudio - -Sends audio. - -`telegram.sendAudio(chatId, audio, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| audio | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendaudio)| - -#### sendGame - -Sends game. - -`telegram.sendGame(chatId, gameName, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| gameName | `String` | Game short name | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendgame)| - -#### sendChatAction - -Sends chat action. - -`telegram.sendChatAction(chatId, action) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| action | `string` | [Chat action](https://core.telegram.org/bots/api#sendchataction) | - -#### sendContact - -Sends document. - -`telegram.sendContact(chatId, phoneNumber, firstName, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| phoneNumber | `string` | Contact phone number | -| firstName | `string` | Contact first name | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendcontact)| - -#### sendDice - -Sends dice. - -`telegram.sendDice(chatId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddice)| - -#### sendDocument - -Sends document. - -`telegram.sendDocument(chatId, doc, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| doc | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddocument)| - -#### sendLocation - -Sends location. - -`telegram.sendLocation(chatId, latitude, longitude, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| latitude | `number` | Latitude | -| longitude | `number` | Longitude | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendlocation)| - -#### sendMessage - -Sends text message. - -`telegram.sendMessage(chatId, text, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| text | `string` | Message | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| - -#### sendPhoto - -Sends a photo. - -`telegram.sendPhoto(chatId, photo, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| photo | `File` | Photo | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendphoto)| - -#### sendMediaGroup - -Sends media album. - -`telegram.sendMediaGroup(chatId, media, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| media | `InputMedia[]` | Media array | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmediagroup)| - -#### sendSticker - -Sends sticker. - -`telegram.sendSticker(chatId, sticker, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| sticker | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendsticker)| - -#### setStickerPositionInSet - -Use this method to move a sticker in a set created by the bot to a specific position. - -`telegram.setStickerPositionInSet(sticker, position) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| sticker | `string` | File identifier of the sticker | -| position | `number` | New sticker position in the set, zero-based | - -#### sendVenue - -Sends venue information. - -`telegram.sendVenue(chatId, latitude, longitude, title, address, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| latitude | `number` | Latitude | -| longitude | `number` | Longitude | -| title | `string` | Venue title | -| address | `string` | Venue address | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvenue)| - -#### sendInvoice - -Sends invoice. - -`telegram.sendInvoice(chatId, invoice) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| invoice | `object` | [Invoice object](https://core.telegram.org/bots/api#sendinvoice) | - -#### sendVideo - -Sends video. - -`telegram.sendVideo(chatId, video, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| video | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideo)| - -#### sendAnimation - -Sends video. - -`telegram.sendAnimation(chatId, animation, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| animation | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendanimation)| - -#### sendVideoNote - -Sends round video. - -`telegram.sendVideoNote(chatId, video, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| video | `File` | Video note file | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideonote)| - -#### sendVoice - -Sends voice. - -`telegram.sendVoice(chatId, voice, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| voice | `File/string` | File, file id or HTTP URL | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvoice)| - -#### sendPoll - -Sends a poll. - -`telegram.sendPoll(chatId, question, options, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| question | `string` | Poll question | -| options | `string[]` | Answer options | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| - -#### setMyCommands - -Use this method to change the list of the bot's commands - -`telegram.setMyCommands(commands) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| commands | `object[]` | [List of bot commands](https://core.telegram.org/bots/api#setmycommands) | - -#### sendQuiz - -Sends quiz. - -`telegram.sendQuiz(chatId, question, options, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| question | `string` | Poll question | -| options | `string[]` | Answer options | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| - -#### stopPoll - -Stops anonymous poll. - -`telegram.stopPoll(chatId, messageId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Poll message id | -| options| `string[]` | Answer options | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#stoppoll)| - -#### stopMessageLiveLocation - -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. - -`telegram.stopMessageLiveLocation(chatId, messageId, inlineMessageId, [markup]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#stopmessagelivelocation) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| [markup] | `object` | Keyboard markup | - -#### uploadStickerFile - -Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods. - -`telegram.uploadStickerFile(ownerId, stickerFile) => Promise` -[Official documentation](https://core.telegram.org/bots/api#uploadstickerfile) - -| Param | Type | Description | -| --- | --- | --- | -| ownerId | `string` | User identifier of sticker file owner | -| stickerFile | `File` | Png image with the sticker | - -#### setWebhook - -Specifies an url to receive incoming updates via an outgoing webhook. - -`telegram.setWebhook(url, [extra]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setwebhook) - -| Param | Type | Description | -| --- | --- | --- | -| url | `string` | Public url for webhook | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#setwebhook) | - -#### unbanChatMember - -Use this method to unban a previously kicked user in a supergroup. - -`telegram.unbanChatMember(chatId, userId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#unbanchatmember) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unbanchatmember) | - -#### setPassportDataErrors - -Informs a user that some Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). - -`telegram.setPassportDataErrors(errors) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setpassportdataerrors) - -| Param | Type | Description | -| --- | --- | --- | -| [errors] | `PassportElementError[]` | An array describing the errors | - -### Extra - -Telegram message options helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). - -### Markup - -Telegram markup helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). - -### Stage - -Simple scene-based control flow middleware. - -```js -const { Telegraf } = require('telegraf') -const session = require('telegraf/session') -const Stage = require('telegraf/stage') -const Scene = require('telegraf/scenes/base') -const { leave } = Stage - -// Greeter scene -const greeter = new Scene('greeter') -greeter.enter((ctx) => ctx.reply('Hi')) -greeter.leave((ctx) => ctx.reply('Bye')) -greeter.hears(/hi/gi, leave()) -greeter.on('message', (ctx) => ctx.reply('Send `hi`')) - -// Create scene manager -const stage = new Stage() -stage.command('cancel', leave()) - -// Scene registration -stage.register(greeter) - -const bot = new Telegraf(process.env.BOT_TOKEN) -bot.use(session()) -bot.use(stage.middleware()) -bot.command('greeter', (ctx) => ctx.scene.enter('greeter')) -bot.startPolling() -``` - -Scenes related context props and functions: - -```js -bot.on('message', (ctx) => { - ctx.scene.state // Current scene state (persistent) - ctx.scene.enter(sceneId, [defaultState, silent]) // Enter scene - ctx.scene.reenter() // Reenter current scene - ctx.scene.leave() // Leave scene -}) -``` diff --git a/docs/_sidebar.md b/docs/_sidebar.md new file mode 100644 index 000000000..bcbcc3a0b --- /dev/null +++ b/docs/_sidebar.md @@ -0,0 +1,8 @@ +- [Introduction](/) +- [Getting started](getting-started.md) +- API reference + - [Telegraf](telegraf.md) + - [Telegram](telegram.md) + - [Extra](extra.md) + - [Markup](markup.md) + - [Stage](stage.md) diff --git a/docs/api-reference.md b/docs/api-reference.md new file mode 100644 index 000000000..f44ca8887 --- /dev/null +++ b/docs/api-reference.md @@ -0,0 +1,1472 @@ +# API reference + +## Telegraf + +Telegraf API reference + +```js +const { Telegraf } = require('telegraf') +``` + +### Constructor + +Initialize new Telegraf bot. + +`const telegraf = new Telegraf(token, [options])` + +| Param | Type | Description | +| --- | --- | --- | +| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) | +| [options] | `object` | Telegraf options | + +Telegraf options: + +```js +{ + telegram: { // Telegram options + agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc. + webhookReply: true // Reply via webhook + }, + username: '' // Bot username (optional) + channelMode: false // Handle `channel_post` updates as messages (optional) +} +``` + +### token + +Use this property to get/set bot token. + +`telegraf.token = [string]` + +### webhookReply + +Use this property to control `reply via webhook` feature. + +`telegraf.webhookReply = [bool]` + +### use + +Registers a middleware. + +`telegraf.use(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware function | + +### on + +Registers middleware for provided update type. + +`telegraf.on(updateTypes, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| updateTypes | `string/string[]` | Update type | +| middleware | `function` | Middleware | + +### hears + +Registers middleware for handling `text` messages. + +`telegraf.hears(triggers, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function` | Triggers | +| middleware | `function` | Middleware | + +### command + +Command handling. + +`telegraf.command(commands, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| commands | `string/string[]` | Commands | +| middleware | `function` | Middleware | + +### start + +Handler for /start command. + +`telegraf.start(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware | + +### help + +Handler for /help command. + +`telegraf.help(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware | + +### settings + +Handler for /settings command. + +`telegraf.settings(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware | + +### entity + +Entity handling. + +`telegraf.entity(entity, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| entity | `string/string[]/RegEx/RegEx[]/Function` | Entity name | +| middleware | `function` | Middleware | + +### mention + +Mention handling. + +`telegraf.mention(username, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| username | `string/string[]` | Username | +| middleware | `function` | Middleware | + +### phone + +Phone number handling. + +`telegraf.phone(number, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| number | `string/string[]` | Phone number | +| middleware | `function` | Middleware | + +### hashtag + +Hashtag handling. + +`telegraf.hashtag(hashtag, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| hashtag | `string/string[]` | Hashtag | +| middleware | `function` | Middleware | + +### cashtag + +Cashtag handling. + +`telegraf.cashtag(cashtag, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| cashtag | `string/string[]` | Cashtag | +| middleware | `function` | Middleware | + +### action + +Registers middleware for handling `callback_data` actions with regular expressions. + +`telegraf.action(triggers, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]` | Triggers | +| middleware | `function` | Middleware | + +### inlineQuery + +Registers middleware for handling `inline_query` actions with regular expressions. + +`telegraf.inlineQuery(triggers, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]` | Triggers | +| middleware | `function` | Middleware | + +### gameQuery + +Registers middleware for handling `callback_data` actions with game query. + +`telegraf.gameQuery(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware | + +### launch + +Launch bot in long-polling or webhook mode. + +`telegraf.launch(options) => Promise` + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [options] | `object` | Launch options | + +Launch options: + +```js +{ + // Start bot in polling mode (Default) + // See startPolling reference + polling: { timeout, limit, allowedUpdates, stopCallback }, + + // Start bot in webhook mode + // See startWebhook reference + webhook: { domain, hookPath, port, host, tlsOptions, cb } +} +``` + +### startPolling + +Start poll updates. + +`telegraf.startPolling([timeout], [limit], [allowedUpdates], [stopCallback])` + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [timeout] | `number` | 30 | Poll timeout in seconds | +| [limit] | `number` | 100 | Limits the number of updates to be retrieved | +| [allowedUpdates] | `string[]/string/null` | null | List the types of updates you want your bot to receive | +| [stopCallback] | `function` | null | Polling stop callback | + +### startWebhook + +Start listening @ `https://host:port/webhookPath` for Telegram calls. + +`telegraf.startWebhook(hookPath, [tlsOptions], port, [host])` + +| Param | Type | Description | +| --- | --- | --- | +| hookPath | `string` | Webhook url path (see Telegraf.setWebhook) | +| [tlsOptions] | `object` | [TLS server options](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener). Pass null to use http | +| port | `number` | Port number | +| [host] | `string` | Hostname | + +### stop + +Stop Webhook and polling + +`telegraf.stop([callback]) => Promise` + +| Param | Type | +| --- | --- | +| [callback] | function | + +### webhookCallback + +Return a callback function suitable for the http[s].createServer() method to handle a request. You may also use this callback function to mount your telegraf app in a Connect/Express app. + +`telegraf.webhookCallback(webhookPath) => Function` + +| Param | Type | Description | +| --- | --- | --- | +| webhookPath | `string` | Webhook url path (see Telegraf.setWebhook) | + +### handleUpdate + +Handle raw Telegram update. In case you use centralized webhook server, queue, etc. + +`telegraf.handleUpdate(rawUpdate, [webhookResponse])` + +| Param | Type | Description | +| --- | --- | --- | +| rawUpdate | `object` | Telegram update payload | +| [webhookResponse] | `object` | [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) | + +### compose + +Compose `middlewares` returning a fully valid middleware comprised of all those which are passed. + +`Telegraf.compose(middlewares) => function` + +| Param | Type | Description | +| --- | --- | --- | +| middlewares | `function[]` | Array of middlewares | + +### mount + +Generates a middleware for handling provided update types. + +`Telegraf.mount(updateTypes, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| updateTypes | `string/string[]` | Update type | +| middleware | `function` | middleware | + +### hears + +Generates a middleware for handling `text` messages with regular expressions. + +`Telegraf.hears(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### action + +Generates a middleware for handling `callbackQuery` data with regular expressions. + +`Telegraf.action(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### inlineQuery + +Generates a middleware for handling `inlineQuery` data with regular expressions. + +`Telegraf.inlineQuery(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### passThru + +Generates pass thru middleware. + +`Telegraf.passThru() => function` + +### safePassThru + +Generates a safe version of pass thru middleware. + +`Telegraf.safePassThru() => function` + +### optional + +Generates an optional middleware. + +`Telegraf.optional(test, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| test | `truthy/function` | Value or predicate `(ctx) => bool` | +| middleware | `function` | middleware | + +### acl + +Generates a middleware for provided users only. + +`Telegraf.acl(userId, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| userId | `string/string[]` | User id | +| middleware | `function` | middleware | + +### drop + +Generates drop middleware. + +`Telegraf.drop(test) => function` + +| Param | Type | Description | +| --- | --- | --- | +| test | `truthy/function` | Value or predicate `(ctx) => bool` | + +### filter + +Generates filter middleware. + +`Telegraf.filter(test) => function` + +| Param | Type | Description | +| --- | --- | --- | +| test | `truthy/function` | Value or predicate `(ctx) => bool` | + +### branch + +Generates branch middleware. + +`Telegraf.branch(test, trueMiddleware, falseMiddleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| test | `truthy/function` | Value or predicate `(ctx) => bool` | +| trueMiddleware | `function` | true action middleware | +| falseMiddleware | `function` | false action middleware | + +### email + +Generates a middleware for handling messages with `email` entity. + +`Telegraf.email(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### hashtag + +Generates a middleware for handling messages with `hashtag` entity. + +`Telegraf.hashtag(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### cashtag + +Generates a middleware for handling messages with `cashtag` entity. + +`Telegraf.cashtag(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### url + +Generates a middleware for handling messages with `url` entity. + +`Telegraf.url(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### phone + +Generates a middleware for handling messages with `phone` entity. + +`Telegraf.phone(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### textLink + +Generates a middleware for handling messages with `text_link` entity. + +`Telegraf.textLink(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +### textMention + +Generates a middleware for handling messages with `text_mention` entity. + +`Telegraf.textMention(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## Telegram + +Telegram client API reference. + +```js +const Telegram = require('telegraf/telegram') +``` + +### Constructor + +Initialize new Telegram client. + +`const telegram = new Telegram(token, [options])` + +| Param | Type | Description | +| --- | --- | --- | +| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) | +| [options] | `object` | Telegram options | + +Telegram options: + +```js +{ + agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc. + webhookReply: true // Reply via webhook +} +``` + +### webhookReply + +Use this property to control `reply via webhook` feature. + +`telegram.webhookReply = [bool]` + +### addStickerToSet + +Use this method to add a new sticker to a set created by the bot. + +`telegram.addStickerToSet(ownerId, name, stickerData) => Promise` +[Official documentation](https://core.telegram.org/bots/api#addstickertoset) + +| Param | Type | Description | +| --- | --- | --- | +| ownerId | `string` | User identifier of sticker set owner | +| name | `string` | Sticker set name | +| stickerData | `Object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | + +### answerCbQuery + +Use this method to send answers to callback queries. + +`telegram.answerCbQuery(callbackQueryId, text, [showAlert], [extra]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#answercallbackquery) + +| Param | Type | Description | +| --- | --- | --- | +| callbackQueryId | `string` | Query id | +| [text] | `string` | Notification text | +| [showAlert] | `bool` | Show alert instead of notification | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answercallbackquery) | + +### answerGameQuery + +Use this method to send answers to game query. + +`telegram.answerGameQuery(callbackQueryId, url) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| callbackQueryId | `string` | Query id | +| url | `string` | Notification text | + +### answerShippingQuery + +Use this method to send answers to shipping query. + +`telegram.answerShippingQuery(shippingQueryId, ok, shippingOptions, [errorMessage]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| shippingQueryId | `string` | Shipping Query id | +| ok | `bool` | Specify True if delivery to the specified address is possible | +| shippingOptions | `object` | [Shipping Options](https://core.telegram.org/bots/api#answershippingquery) | +| [errorMessage] | `string` | Error message in human readable form | + +### answerPreCheckoutQuery + +Use this method to send answers to shipping query. + +`telegram.answerPreCheckoutQuery(preCheckoutQueryId, ok, [errorMessage]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| preCheckoutQueryId | `string` | Shipping Query id | +| ok | `bool` | Specify True if everything is alright (goods are available, etc.) | +| [errorMessage] | `string` | Error message in human readable form | + +### answerInlineQuery + +Use this method to send answers to an inline query. + +`telegram.answerInlineQuery(inlineQueryId, results, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| inlineQueryId | `string` | Query id | +| results | `object[]` | Results | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answerinlinequery)| + +### createNewStickerSet + +Use this method to create new sticker set owned by a user. + +`telegram.createNewStickerSet(ownerId, name, title, stickerData, [isMasks]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#createnewstickerset) + +| Param | Type | Description | +| --- | --- | --- | +| ownerId | `string` | User identifier of sticker set owner | +| name | `string` | Sticker set name | +| title | `string` | Sticker set title | +| stickerData | `object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | +| [isMasks] | `bool` | Pass True, if a set of mask stickers should be created | + +### deleteChatStickerSet + +Use this method to delete a group sticker set from a supergroup. + +`telegram.deleteChatStickerSet(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletechatstickerset) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +### deleteMessage + +Use this method to delete bot messages. + +`telegram.deleteMessage(chatId, messageId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletemessage) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | + +### setStickerSetThumb + +Use this method to set the thumbnail of a sticker set. + +`telegram.setStickerSetThumb(name, userId, [thumb]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setstickersetthumb) + +| Param | Type | Description | +| --- | --- | --- | +| name | `string` | Sticker set name | +| userId | `string` | User identifier of the sticker set owner | +| thumb | `File` | A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size | + +### deleteStickerFromSet + +Use this method to delete a sticker from a set created by the bot. + +`telegram.deleteStickerFromSet(stickerId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletestickerfromset) + +| Param | Type | Description | +| --- | --- | --- | +| stickerId | `string` | File identifier of the sticker | + +### editMessageCaption + +Use this method to edit captions of messages sent by the bot or via the bot. + +`telegram.editMessageCaption(chatId, messageId, inlineMessageId, caption, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| caption | `string` | Caption | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagecaption)| + +### editMessageMedia + +Use this method to edit media of messages sent by the bot or via the bot. + +`telegram.editMessageMedia(chatId, messageId, inlineMessageId, media, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| media | `InputMedia` | [InputMedia](https://core.telegram.org/bots/api#inputmedia) | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagemedia)| + +### editMessageLiveLocation + +Use this method to edit live location messages sent by the bot or via the bot. + +`telegram.editMessageLiveLocation(latitude, longitude, chatId, messageId, inlineMessageId, [markup]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#editmessagelivelocation) + +| Param | Type | Description | +| --- | --- | --- | +| latitude | `string` | Latitude of new location | +| longitude | `string` | Longitude of new location | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| [markup] | `object` | Keyboard markup | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagelivelocation)| + +### editMessageReplyMarkup + +Use this method to edit only the reply markup of messages sent by the bot or via the bot. + +`telegram.editMessageReplyMarkup(chatId, messageId, inlineMessageId, markup, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| markup | `object` | Keyboard markup | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagereplymarkup)| + +### editMessageText + +Use this method to edit text messages sent by the bot or via the bot. + +`telegram.editMessageText(chatId, messageId, inlineMessageId, text, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| text | `string` | Message | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagetext)| + +### forwardMessage + +Forwards message. + +`telegram.forwardMessage(chatId, fromChatId, messageId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Target Chat id | +| fromChatId | `number/string` | Source Chat id | +| messageId | `number` | Message id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#forwardmessage)| + +### sendCopy + +Sends message copy. + +`telegram.sendCopy(chatId, message, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Target Chat id | +| message | `object` | Message | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| + +### copyMessage + +Use this method to copy messages of any kind. + +`telegram.copyMessage(chatId, message, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Target Chat id | +| fromChatId | `number/string` | Source Chat id | +| messageId | `number` | Message id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#copymessage)| + +### getWebhookInfo + +Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. + +`telegram.getWebhookInfo() => Promise` + +### getChat + +Use this method to get up to date information about the chat (current name of the user for one-on-one conversatio +ns, current username of a user, group or channel, etc.). + +`telegram.getChat(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getchat) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +### getChatAdministrators + +Use this method to get a list of administrators in a chat. On success, returns an Array of 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. + +`telegram.getChatAdministrators(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getchatadministrators) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +### setGameScore + +Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat. + +`telegram.setGameScore(userId, score, inlineMessageId, chatId, messageId, [editMessage], [force]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setgamescore) + +| Param | Type | Description | +| --- | --- | --- | +| userId | `number` | Target User id | +| score | `number` | Target User id | +| inlineMessageId | `string` | Inline message id | +| chatId | `number/string` | Target Chat id | +| messageId | `number/string` | Message id | +| [editMessage] | `boolean` | edit target message, default value is True | +| [force] | `boolean` | Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters | + +### getGameHighScores + +Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. + +`telegram.getGameHighScores(userId, inlineMessageId, chatId, messageId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getgamehighscores) + +| Param | Type | Description | +| --- | --- | --- | +| userId | `number`\ | Target User id | +| inlineMessageId | `string` | Inline message id | +| chatId | `number/string` | Target Chat id | +| messageId | `number/string` | Message id | + +### getChatMember + +Use this method to get information about a member of a chat. + +`telegram.getChatMember(chatId, userId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getchatmember) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User identifier | + +### getChatMembersCount + +Use this method to get the number of members in a chat. + +`telegram.getChatMembersCount(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getchatmemberscount) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +### getFile + +Returns basic info about a file and prepare it for downloading. + +`telegram.getFile(fileId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getfile) + +| Param | Type | Description | +| --- | --- | --- | +| fileId | `string` | File id | + +### getFileLink + +Returns link to file. + +`telegram.getFileLink(fileId) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| fileId | `string/object` | File id or file object | + +### getMe + +Returns basic information about the bot. + +`telegram.getMe() => Promise` +[Official documentation](https://core.telegram.org/bots/api#getme) + +### getMyCommands + +Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success. + +`telegram.getMyCommands() => Promise` +[Official documentation](https://core.telegram.org/bots/api#getmycommands) + +### getStickerSet + +Use this method to get a sticker set. + +`telegram.getStickerSet(name) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| name | `string` | Short name of the sticker set | +[Official documentation](https://core.telegram.org/bots/api#getstickerset) + +### getUserProfilePhotos + +Returns profiles photos for provided user. + +`telegram.getUserProfilePhotos(userId, [offset], [limit]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getuserprofilephotos) + +| Param | Type | Description | +| --- | --- | --- | +| userId | `number` | Chat id | +| [offset] | `number` | Offset | +| [limit] | `number` | Limit | + +### setChatPermissions + +Use this method to set default chat permissions for all members. + +`telegram.setChatPermissions(chatId, permissions) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| permissions | `object` | [New default chat permissions](https://core.telegram.org/bots/api#chatpermissions)| + +### kickChatMember + +Use this method to kick a user from a group or a supergroup. + +`telegram.kickChatMember(chatId, userId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#kickchatmember)| + +### restrictChatMember + +Use this method to restrict a user in a supergroup. + +`telegram.restrictChatMember(chatId, userId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#restrictchatmember)| + +### promoteChatMember + +Use this method to promote or demote a user in a supergroup or a channel. + +`telegram.promoteChatMember(chatId, userId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#promotechatmember)| + +### setChatAdministratorCustomTitle + +New custom title for the administrator; 0-16 characters, emoji are not allowed + +`telegram.setChatAdministratorCustomTitle(chatId, userId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| title | `string` | Custom title | + +### exportChatInviteLink + +Use this method to export an invite link to a supergroup or a channel. + +`telegram.exportChatInviteLink(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#exportchatinvitelink) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +### setChatPhoto + +Use this method to set a new profile photo for the chat. + +`telegram.setChatPhoto(chatId, photo) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setchatphoto) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| photo | `File` | New chat photo | + +### deleteChatPhoto + +Use this method to delete a chat photo. + +`telegram.deleteChatPhoto(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletechatphoto) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +### setChatTitle + +Use this method to change the title of a chat. + +`telegram.setChatTitle(chatId, title) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setchattitle) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| title | `string` | New chat title, 1-255 characters | + +### setChatDescription + +Use this method to change the description of a supergroup or a channel. + +`telegram.setChatDescription(chatId, description) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setchattitle) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| description | `string` | New chat description, 0-255 characters | + +### setChatStickerSet + +Use this method to set a new group sticker set for a supergroup. + +`telegram.setChatStickerSet(chatId, stickerSetName) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setchatstickerset) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| stickerSetName | `string` | Name of the sticker set | + +### pinChatMessage + +Use this method to pin a message in a supergroup. + +`telegram.pinChatMessage(chatId, messageId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `number` | Message id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#pinchatmessage)| + +### unpinChatMessage + +Use this method to unpin a message in a supergroup chat. + +`telegram.unpinChatMessage(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#unpinchatmessage) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unpinchatmessage)| + +### unpinAllChatMessages + +Use this method to clear the list of pinned messages in a chat + +`telegram.unpinAllChatMessages(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#unpinallchatmessages) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +### leaveChat + +Use this method for your bot to leave a group, supergroup or channel. + +`telegram.leaveChat(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#leavechat) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +### deleteWebhook + +Removes webhook integration. + +`telegram.deleteWebhook() => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletewebhook) + +| Param | Type | Description | +| --- | --- | --- | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#deletewebhook) | + +### sendAudio + +Sends audio. + +`telegram.sendAudio(chatId, audio, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| audio | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendaudio)| + +### sendGame + +Sends game. + +`telegram.sendGame(chatId, gameName, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| gameName | `String` | Game short name | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendgame)| + +### sendChatAction + +Sends chat action. + +`telegram.sendChatAction(chatId, action) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| action | `string` | [Chat action](https://core.telegram.org/bots/api#sendchataction) | + +### sendContact + +Sends document. + +`telegram.sendContact(chatId, phoneNumber, firstName, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| phoneNumber | `string` | Contact phone number | +| firstName | `string` | Contact first name | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendcontact)| + +### sendDice + +Sends dice. + +`telegram.sendDice(chatId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddice)| + +### sendDocument + +Sends document. + +`telegram.sendDocument(chatId, doc, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| doc | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddocument)| + +### sendLocation + +Sends location. + +`telegram.sendLocation(chatId, latitude, longitude, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| latitude | `number` | Latitude | +| longitude | `number` | Longitude | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendlocation)| + +### sendMessage + +Sends text message. + +`telegram.sendMessage(chatId, text, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| text | `string` | Message | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| + +### sendPhoto + +Sends a photo. + +`telegram.sendPhoto(chatId, photo, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| photo | `File` | Photo | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendphoto)| + +### sendMediaGroup + +Sends media album. + +`telegram.sendMediaGroup(chatId, media, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| media | `InputMedia[]` | Media array | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmediagroup)| + +### sendSticker + +Sends sticker. + +`telegram.sendSticker(chatId, sticker, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| sticker | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendsticker)| + +### setStickerPositionInSet + +Use this method to move a sticker in a set created by the bot to a specific position. + +`telegram.setStickerPositionInSet(sticker, position) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| sticker | `string` | File identifier of the sticker | +| position | `number` | New sticker position in the set, zero-based | + +### sendVenue + +Sends venue information. + +`telegram.sendVenue(chatId, latitude, longitude, title, address, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| latitude | `number` | Latitude | +| longitude | `number` | Longitude | +| title | `string` | Venue title | +| address | `string` | Venue address | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvenue)| + +### sendInvoice + +Sends invoice. + +`telegram.sendInvoice(chatId, invoice) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| invoice | `object` | [Invoice object](https://core.telegram.org/bots/api#sendinvoice) | + +### sendVideo + +Sends video. + +`telegram.sendVideo(chatId, video, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| video | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideo)| + +### sendAnimation + +Sends video. + +`telegram.sendAnimation(chatId, animation, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| animation | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendanimation)| + +### sendVideoNote + +Sends round video. + +`telegram.sendVideoNote(chatId, video, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| video | `File` | Video note file | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideonote)| + +### sendVoice + +Sends voice. + +`telegram.sendVoice(chatId, voice, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| voice | `File/string` | File, file id or HTTP URL | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvoice)| + +### sendPoll + +Sends a poll. + +`telegram.sendPoll(chatId, question, options, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| question | `string` | Poll question | +| options | `string[]` | Answer options | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| + +### setMyCommands + +Use this method to change the list of the bot's commands + +`telegram.setMyCommands(commands) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| commands | `object[]` | [List of bot commands](https://core.telegram.org/bots/api#setmycommands) | + +### sendQuiz + +Sends quiz. + +`telegram.sendQuiz(chatId, question, options, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| question | `string` | Poll question | +| options | `string[]` | Answer options | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| + +### stopPoll + +Stops anonymous poll. + +`telegram.stopPoll(chatId, messageId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Poll message id | +| options| `string[]` | Answer options | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#stoppoll)| + +### stopMessageLiveLocation + +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. + +`telegram.stopMessageLiveLocation(chatId, messageId, inlineMessageId, [markup]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#stopmessagelivelocation) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| [markup] | `object` | Keyboard markup | + +### uploadStickerFile + +Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods. + +`telegram.uploadStickerFile(ownerId, stickerFile) => Promise` +[Official documentation](https://core.telegram.org/bots/api#uploadstickerfile) + +| Param | Type | Description | +| --- | --- | --- | +| ownerId | `string` | User identifier of sticker file owner | +| stickerFile | `File` | Png image with the sticker | + +### setWebhook + +Specifies an url to receive incoming updates via an outgoing webhook. + +`telegram.setWebhook(url, [extra]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setwebhook) + +| Param | Type | Description | +| --- | --- | --- | +| url | `string` | Public url for webhook | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#setwebhook) | + +### unbanChatMember + +Use this method to unban a previously kicked user in a supergroup. + +`telegram.unbanChatMember(chatId, userId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#unbanchatmember) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unbanchatmember) | + +### setPassportDataErrors + +Informs a user that some Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). + +`telegram.setPassportDataErrors(errors) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setpassportdataerrors) + +| Param | Type | Description | +| --- | --- | --- | +| [errors] | `PassportElementError[]` | An array describing the errors | + +## Extra + +Telegram message options helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). + +## Markup + +Telegram markup helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). + +## Stage + +Simple scene-based control flow middleware. + +```js +const { Telegraf } = require('telegraf') +const session = require('telegraf/session') +const Stage = require('telegraf/stage') +const Scene = require('telegraf/scenes/base') +const { leave } = Stage + +// Greeter scene +const greeter = new Scene('greeter') +greeter.enter((ctx) => ctx.reply('Hi')) +greeter.leave((ctx) => ctx.reply('Bye')) +greeter.hears(/hi/gi, leave()) +greeter.on('message', (ctx) => ctx.reply('Send `hi`')) + +// Create scene manager +const stage = new Stage() +stage.command('cancel', leave()) + +// Scene registration +stage.register(greeter) + +const bot = new Telegraf(process.env.BOT_TOKEN) +bot.use(session()) +bot.use(stage.middleware()) +bot.command('greeter', (ctx) => ctx.scene.enter('greeter')) +bot.startPolling() +``` + +Scenes related context props and functions: + +```js +bot.on('message', (ctx) => { + ctx.scene.state // Current scene state (persistent) + ctx.scene.enter(sceneId, [defaultState, silent]) // Enter scene + ctx.scene.reenter() // Reenter current scene + ctx.scene.leave() // Leave scene +}) +``` diff --git a/docs/extra.md b/docs/extra.md new file mode 100644 index 000000000..3b9da27be --- /dev/null +++ b/docs/extra.md @@ -0,0 +1,3 @@ +# Extra + +Telegram message options helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 000000000..6de2d45e0 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,625 @@ +# Getting started + +## Telegram token + +To use the [Telegram Bot API](https://core.telegram.org/bots/api), you first have to [get a bot account](https://core.telegram.org/bots) by [chatting with BotFather](https://core.telegram.org/bots#6-botfather). + +BotFather will give you a *token*, something like `123456789:AbCdfGhIJKlmNoQQRsTUVwxyZ`. + +## Bot + +A Telegraf bot is an object containing an array of middlewares which are composed and executed in a stack-like manner upon request. Is similar to many other middleware systems that you may have encountered such as Koa, Ruby's Rack, Connect. + +## Middleware + +Middleware is an essential part of any modern framework. +It allows you to modify requests and responses as they pass between the Telegram and your bot. + +You can imagine a middleware as a chain of logic connection your bot to the Telegram request. + +Middleware normally takes two parameters (ctx, next), `ctx` is the context for one Telegram update, `next` is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion. + +```js +const bot = new Telegraf(process.env.BOT_TOKEN) + +bot.use(async (ctx, next) => { + const start = new Date() + await next() + const ms = new Date() - start + console.log('Response time: %sms', ms) +}) + +bot.on('text', (ctx) => ctx.reply('Hello World')) +bot.launch() +``` + +### Known middleware + +- [Internationalization](https://github.com/telegraf/telegraf-i18n) +- [Redis powered session](https://github.com/telegraf/telegraf-session-redis) +- [Local powered session (via lowdb)](https://github.com/RealSpeaker/telegraf-session-local) +- [Rate-limiting](https://github.com/telegraf/telegraf-ratelimit) +- [Menus via inline keyboards](https://github.com/EdJoPaTo/telegraf-inline-menu) +- [Natural language processing via wit.ai](https://github.com/telegraf/telegraf-wit) +- [Natural language processing via recast.ai](https://github.com/telegraf/telegraf-recast) +- [Multivariate and A/B testing](https://github.com/telegraf/telegraf-experiments) +- [Powerful bot stats via Mixpanel](https://github.com/telegraf/telegraf-mixpanel) +- [statsd integration](https://github.com/telegraf/telegraf-statsd) +- [and more...](https://www.npmjs.com/search?q=telegraf-) + +## Error handling + +By default, Telegraf will print all errors to `stderr` and rethrow error. + +To perform custom error-handling logic use following snippet: + +```js +const bot = new Telegraf(process.env.BOT_TOKEN) +bot.catch((err, ctx) => { + console.log(`Ooops, encountered an error for ${ctx.updateType}`, err) +}) +bot.start((ctx) => { + throw new Error('Example error') +}) +bot.launch() +``` + +## Context + +A Telegraf Context encapsulates telegram update. +Context is created per request and contains following props: + +| Property | Description | +| --- | --- | +| ` ctx.telegram ` | Telegram client instance | +| ` ctx.updateType ` | Update type (message, inline_query, etc.) | +| `[ctx.updateSubTypes]` | Update subtypes (text, sticker, audio, etc.) | +| `[ctx.message]` | Received message | +| `[ctx.editedMessage]` | Edited message | +| `[ctx.inlineQuery]` | Received inline query | +| `[ctx.chosenInlineResult]` | Received inline query result | +| `[ctx.callbackQuery]` | Received callback query | +| `[ctx.shippingQuery]` | Shipping query | +| `[ctx.preCheckoutQuery]` | Pre-checkout query | +| `[ctx.channelPost]` | New incoming channel post of any kind — text, photo, sticker, etc. | +| `[ctx.editedChannelPost]` | New version of a channel post that is known to the bot and was edited | +| `[ctx.poll]` | New version of a anonymous poll that is known to the bot and was changed | +| `[ctx.pollAnswer]` | This object represents an answer of a user in a non-anonymous poll. | +| `[ctx.chat]` | Current chat info | +| `[ctx.from]` | Sender info | +| `[ctx.match]` | Regex match (available only for `hears`, `command`, `action`, `inlineQuery` handlers) | +| ` ctx.webhookReply ` | Shortcut to `ctx.telegram.webhookReply` | + +```js +bot.use((ctx) => { + console.log(ctx.message) +}) +``` + +### Extending context + +The recommended way to extend bot context: + +```js +const bot = new Telegraf(process.env.BOT_TOKEN) + +bot.context.db = { + getScores: () => { return 42 } +} + +bot.on('text', (ctx) => { + const scores = ctx.db.getScores(ctx.message.from.username) + return ctx.reply(`${ctx.message.from.username}: ${scores}`) +}) + +bot.launch() +``` + +### Shortcuts + +Context shortcuts for **message** update: + +| Shortcut | Bound to | +| --- | --- | +| `addStickerToSet` | [`telegram.addStickerToSet`](#addstickertoset) | +| `createNewStickerSet` | [`telegram.createNewStickerSet`](#createnewstickerset) | +| `deleteChatPhoto` | [`telegram.deleteChatPhoto`](#deletechatphoto) | +| `deleteMessage` | [`telegram.deleteMessage`](#deletemessage) | +| `deleteStickerFromSet` | [`telegram.deleteStickerFromSet`](#deletestickerfromset) | +| `exportChatInviteLink` | [`telegram.exportChatInviteLink`](#exportchatinvitelink) | +| `forwardMessage` | [`telegram.forwardMessage`](#forwardmessage) | +| `getChat` | [`telegram.getChat`](#getchat) | +| `getChatAdministrators` | [`telegram.getChatAdministrators`](#getchatadministrators) | +| `getChatMember` | [`telegram.getChatMember`](#getchatmember) | +| `getChatMembersCount` | [`telegram.getChatMembersCount`](#getchatmemberscount) | +| `getMyCommands` | [`telegram.getMyCommands`](#getmycommands) | +| `getStickerSet` | [`telegram.getStickerSet`](#getstickerset) | +| `leaveChat` | [`telegram.leaveChat`](#leavechat) | +| `pinChatMessage` | [`telegram.pinChatMessage`](#pinchatmessage) | +| `reply` | [`telegram.sendMessage`](#sendmessage) | +| `replyWithAudio` | [`telegram.sendAudio`](#sendaudio) | +| `replyWithChatAction` | [`telegram.sendChatAction`](#sendchataction) | +| `replyWithDice` | [`telegram.sendDice`](#senddice) | +| `replyWithDocument` | [`telegram.sendDocument`](#senddocument) | +| `replyWithGame` | [`telegram.sendGame`](#sendgame) | +| `replyWithHTML` | [`telegram.sendMessage`](#sendmessage) | +| `replyWithInvoice` | [`telegram.sendInvoice`](#sendinvoice) | +| `replyWithLocation` | [`telegram.sendLocation`](#sendlocation) | +| `replyWithMarkdown` | [`telegram.sendMessage`](#sendmessage) | +| `replyWithMediaGroup` | [`telegram.sendMediaGroup`](#sendmediagroup) | +| `replyWithPhoto` | [`telegram.sendPhoto`](#sendphoto) | +| `replyWithPoll` | [`telegram.sendPoll`](#sendpoll) | +| `replyWithQuiz` | [`telegram.sendQuiz`](#sendquiz) | +| `replyWithSticker` | [`telegram.sendSticker`](#sendsticker) | +| `replyWithVideo` | [`telegram.sendVideo`](#sendvideo) | +| `replyWithVideoNote` | [`telegram.sendVideoNote`](#sendvideonote) | +| `replyWithVoice` | [`telegram.sendVoice`](#sendvoice) | +| `setChatDescription` | [`telegram.setChatDescription`](#setchatdescription) | +| `setChatPhoto` | [`telegram.setChatPhoto`](#setchatphoto) | +| `setChatTitle` | [`telegram.setChatTitle`](#setchattitle) | +| `setMyCommands` | [`telegram.setMyCommands`](#setmycommands) | +| `setPassportDataErrors` | [`telegram.setPassportDataErrors`](#setpassportdataerrors) | +| `setStickerPositionInSet` | [`telegram.setStickerPositionInSet`](#setstickerpositioninset) | +| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | +| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | +| `stopPoll` | [`telegram.stopPoll`](#stoppoll) | +| `unpinChatMessage` | [`telegram.unpinChatMessage`](#unpinchatmessage) | +| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](#unpinallchatmessages) | +| `uploadStickerFile` | [`telegram.uploadStickerFile`](#uploadstickerfile) | +| `unbanChatMember` | [`telegram.unbanChatMember`](#unbanchatmember) | + +Context shortcuts for **callback_query** update: + +| Shortcut | Bound to | +| --- | --- | +| `addStickerToSet` | [`telegram.addStickerToSet`](#addstickertoset) | +| `answerCbQuery` | [`telegram.answerCbQuery`](#answercbquery) | +| `answerGameQuery` | [`telegram.answerGameQuery`](#answergamequery) | +| `createNewStickerSet` | [`telegram.createNewStickerSet`](#createnewstickerset) | +| `deleteChatPhoto` | [`telegram.deleteChatPhoto`](#deletechatphoto) | +| `deleteMessage` | [`telegram.deleteMessage`](#deletemessage) | +| `deleteStickerFromSet` | [`telegram.deleteStickerFromSet`](#deletestickerfromset) | +| `editMessageCaption` | [`telegram.editMessageCaption`](#editmessagecaption) | +| `editMessageMedia` | [`telegram.editMessageMedia`](#editmessagemedia) | +| `editMessageReplyMarkup` | [`telegram.editMessageReplyMarkup`](#editmessagereplymarkup) | +| `editMessageText` | [`telegram.editMessageText`](#editmessagetext) | +| `exportChatInviteLink` | [`telegram.exportChatInviteLink`](#exportchatinvitelink) | +| `forwardMessage` | [`telegram.forwardMessage`](#forwardmessage) | +| `getChat` | [`telegram.getChat`](#getchat) | +| `getChatAdministrators` | [`telegram.getChatAdministrators`](#getchatadministrators) | +| `getChatMember` | [`telegram.getChatMember`](#getchatmember) | +| `getChatMembersCount` | [`telegram.getChatMembersCount`](#getchatmemberscount) | +| `getStickerSet` | [`telegram.getStickerSet`](#getstickerset) | +| `leaveChat` | [`telegram.leaveChat`](#leavechat) | +| `pinChatMessage` | [`telegram.pinChatMessage`](#pinchatmessage) | +| `reply` | [`telegram.sendMessage`](#sendmessage) | +| `replyWithAnimation` | [`telegram.sendAnimation`](#sendanimation) | +| `replyWithAudio` | [`telegram.sendAudio`](#sendaudio) | +| `replyWithChatAction` | [`telegram.sendChatAction`](#sendchataction) | +| `replyWithDice` | [`telegram.sendDice`](#senddice) | +| `replyWithDocument` | [`telegram.sendDocument`](#senddocument) | +| `replyWithGame` | [`telegram.sendGame`](#sendgame) | +| `replyWithHTML` | [`telegram.sendMessage`](#sendmessage) | +| `replyWithInvoice` | [`telegram.sendInvoice`](#sendinvoice) | +| `replyWithLocation` | [`telegram.sendLocation`](#sendlocation) | +| `replyWithMarkdown` | [`telegram.sendMessage`](#sendmessage) | +| `replyWithMediaGroup` | [`telegram.sendMediaGroup`](#sendmediagroup) | +| `replyWithPhoto` | [`telegram.sendPhoto`](#sendphoto) | +| `replyWithPoll` | [`telegram.sendPoll`](#sendpoll) | +| `replyWithSticker` | [`telegram.sendSticker`](#sendsticker) | +| `replyWithVideo` | [`telegram.sendVideo`](#sendvideo) | +| `replyWithVideoNote` | [`telegram.sendVideoNote`](#sendvideonote) | +| `replyWithVoice` | [`telegram.sendVoice`](#sendvoice) | +| `setChatDescription` | [`telegram.setChatDescription`](#setchatdescription) | +| `setChatPhoto` | [`telegram.setChatPhoto`](#setchatphoto) | +| `setChatTitle` | [`telegram.setChatTitle`](#setchattitle) | +| `setStickerPositionInSet` | [`telegram.setStickerPositionInSet`](#setstickerpositioninset) | +| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | +| `stopPoll` | [`telegram.stopPoll`](#stoppoll) | +| `unpinChatMessage` | [`telegram.unpinChatMessage`](#unpinchatmessage) | +| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](#unpinallchatmessages) | +| `uploadStickerFile` | [`telegram.uploadStickerFile`](#uploadstickerfile) | +| `unbanChatMember` | [`telegram.unbanChatMember`](#unbanchatmember) | + +Context shortcuts for **inline_query** update: + +| Shortcut | Bound to | +| --- | --- | +| `answerInlineQuery` | [`telegram.answerInlineQuery`](#answerinlinequery) | + +Context shortcuts for **shipping_query** update: + +| Shortcut | Bound to | +| --- | --- | +| `answerShippingQuery` | [`telegram.answerShippingQuery`](#answershippingquery) | + +Context shortcuts for **pre_checkout_query** update: + +| Shortcut | Bound to | +| --- | --- | +| `answerPreCheckoutQuery` | [`telegram.answerPreCheckoutQuery`](#answerprecheckoutquery) | + +#### Shortcuts usage example + +```js +const bot = new Telegraf(process.env.BOT_TOKEN) + +bot.command('quit', (ctx) => { + // Explicit usage + ctx.telegram.leaveChat(ctx.message.chat.id) + + // Using context shortcut + ctx.leaveChat() +}) + +bot.on('text', (ctx) => { + // Explicit usage + ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`) + + // Using context shortcut + ctx.reply(`Hello ${ctx.state.role}`) +}) + +bot.on('callback_query', (ctx) => { + // Explicit usage + ctx.telegram.answerCbQuery(ctx.callbackQuery.id) + + // Using context shortcut + ctx.answerCbQuery() +}) + +bot.on('inline_query', (ctx) => { + const result = [] + // Explicit usage + ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result) + + // Using context shortcut + ctx.answerInlineQuery(result) +}) + +bot.launch() +``` + +## State + +The recommended namespace to share information between middlewares. + +```js +const bot = new Telegraf(process.env.BOT_TOKEN) + +// Naive authorization middleware +bot.use((ctx, next) => { + ctx.state.role = getUserRole(ctx.message) + return next() +}) + +bot.on('text', (ctx) => { + return ctx.reply(`Hello ${ctx.state.role}`) +}) + +bot.launch() +``` + +## Session + +```js +const session = require('telegraf/session') + +const bot = new Telegraf(process.env.BOT_TOKEN) +bot.use(session()) +bot.on('text', (ctx) => { + ctx.session.counter = ctx.session.counter || 0 + ctx.session.counter++ + return ctx.reply(`Message counter:${ctx.session.counter}`) +}) + +bot.launch() +``` + +**Note: For persistent sessions you can use any of [`telegraf-session-*`](https://www.npmjs.com/search?q=telegraf-session) middleware.** + +**Tip: To use same session in private chat with the bot and in inline mode, use following session key resolver:** + +```js +{ + getSessionKey: (ctx) => { + if (ctx.from && ctx.chat) { + return `${ctx.from.id}:${ctx.chat.id}` + } else if (ctx.from && ctx.inlineQuery) { + return `${ctx.from.id}:${ctx.from.id}` + } + return null + } +} +``` + +## Update types + +Supported update types: + +- `message` +- `edited_message` +- `callback_query` +- `inline_query` +- `shipping_query` +- `pre_checkout_query` +- `chosen_inline_result` +- `channel_post` +- `edited_channel_post` + +Available update sub-types: + +- `text` +- `audio` +- `dice` +- `document` +- `photo` +- `sticker` +- `video` +- `voice` +- `contact` +- `location` +- `venue` +- `forward` +- `new_chat_members` +- `left_chat_member` +- `new_chat_title` +- `new_chat_photo` +- `delete_chat_photo` +- `group_chat_created` +- `migrate_to_chat_id` +- `supergroup_chat_created` +- `channel_chat_created` +- `migrate_from_chat_id` +- `pinned_message` +- `game` +- `video_note` +- `invoice` +- `successful_payment` +- `connected_website` +- `passport_data` +- `poll` + +```js +// Handle message update +bot.on('message', (ctx) => { + return ctx.reply('Hello') +}) + +// Handle sticker or photo update +bot.on(['sticker', 'photo'], (ctx) => { + console.log(ctx.message) + return ctx.reply('Cool!') +}) +``` + +[Official Docs](https://core.telegram.org/bots/api#message) + +## Webhooks + +```js +require('dotenv') + +const bot = new Telegraf(process.env.BOT_TOKEN) + +// TLS options +const tlsOptions = { + key: fs.readFileSync('server-key.pem'), + cert: fs.readFileSync('server-cert.pem'), + ca: [ + // This is necessary only if the client uses a self-signed certificate. + fs.readFileSync('client-cert.pem') + ] +} + +// Set telegram webhook +// The second argument is necessary only if the client uses a self-signed +// certificate. Including it for a verified certificate may cause things to break. +bot.telegram.setWebhook('https://server.tld:8443/secret-path', { + source: 'server-cert.pem' +}) + +// Start https webhook +bot.startWebhook('/secret-path', tlsOptions, 8443) + +// Http webhook, for nginx/heroku users. +bot.startWebhook('/secret-path', null, 5000) +``` + +Use webhookCallback() if you want to attach telegraf to existing http server + +```js +require('http') + .createServer(bot.webhookCallback('/secret-path')) + .listen(3000) + +require('https') + .createServer(tlsOptions, bot.webhookCallback('/secret-path')) + .listen(8443) +``` + +Express.js example integration + +```js +const { Telegraf } = require('telegraf') +const express = require('express') +const expressApp = express() + +const bot = new Telegraf(process.env.BOT_TOKEN) +expressApp.use(bot.webhookCallback('/secret-path')) +bot.telegram.setWebhook('https://server.tld:8443/secret-path') + +expressApp.get('/', (req, res) => { + res.send('Hello World!') +}) + +expressApp.listen(3000, () => { + console.log('Example app listening on port 3000!') +}) +``` + +Fastify example integration + +```js +const { Telegraf } = require('telegraf') +const fastifyApp = require('fastify')() + +const bot = new Telegraf(process.env.BOT_TOKEN) + +bot.on('text', ({ reply }) => reply('Hello')) +fastifyApp.use(bot.webhookCallback('/secret-path')) +// Set telegram webhook +// npm install -g localtunnel && lt --port 3000 +bot.telegram.setWebhook('https://------.localtunnel.me/secret-path') + +fastifyApp.listen(3000, () => { + console.log('Example app listening on port 3000!') +}) +``` + +Koa.js example integration + +```js +const { Telegraf } = require('telegraf') +const Koa = require('koa') +const koaBody = require('koa-body') + +const bot = new Telegraf(process.env.BOT_TOKEN) +bot.telegram.setWebhook('https://server.tld:8443/secret-path') + +const app = new Koa() +app.use(koaBody()) +app.use(async (ctx, next) => { + if (ctx.method !== 'POST' || ctx.url !== '/secret-path') { + return next() + } + await bot.handleUpdate(ctx.request.body, ctx.response) + ctx.status = 200 +}) +app.use(async (ctx) => { + ctx.body = 'Hello World' +}) + +app.listen(3000) +``` + +## Working with files + +Supported file sources: + +- `Existing file_id` +- `File path` +- `Url` +- `Buffer` +- `ReadStream` + +Also, you can provide an optional name of file as `filename`. + +```js +bot.on('message', (ctx) => { + // resend existing file by file_id + ctx.replyWithSticker('123123jkbhj6b') + + // send file + ctx.replyWithVideo({ source: '/path/to/video.mp4' }) + + // send stream + ctx.replyWithVideo({ + source: fs.createReadStream('/path/to/video.mp4') + }) + + // send buffer + ctx.replyWithVoice({ + source: Buffer.alloc() + }) + + // send url via Telegram server + ctx.replyWithPhoto('https://picsum.photos/200/300/') + + // pipe url content + ctx.replyWithPhoto({ + url: 'https://picsum.photos/200/300/?random', + filename: 'kitten.jpg' + }) +}) +``` + +## Telegram Passport + +To enable Telegram Passport support you can use [`telegram-passport`](https://www.npmjs.com/package/telegram-passport) package: + +```js +const { Telegraf } = require('telegraf') +const TelegramPassport = require('telegram-passport') + +const bot = new Telegraf(process.env.BOT_TOKEN) +const passport = new TelegramPassport("PRIVATE_KEY_IN_PEM_FORMAT") + +bot.on('passport_data', (ctx) => { + const decryptedPasswordData = passport.decrypt(ctx.passportData) + console.log(decryptedPasswordData) + return ctx.setPassportDataErrors([ + { source: 'selfie', type: 'driver_license', file_hash: 'file-hash', message: 'Selfie photo is too low quality'} + ]) +}) +``` + +## Telegraf Modules + +Telegraf Modules is higher level abstraction for writing modular Telegram bots. + +Module is simple js file with exported Telegraf middleware: + +```js +module.exports = (ctx) => ctx.reply('Hello from Telegraf Module!') +``` + +```js +const Composer = require('telegraf/composer') + +module.exports = Composer.mount( + 'sticker', + (ctx) => ctx.reply('Wow, sticker') +) +``` + +To run modules you can use `telegraf` module runner, it allows you to start Telegraf module easily from the command line. + +```bash +npm install telegraf -g +``` + +## Telegraf CLI usage + +```bash +telegraf [opts] + -t Bot token [$BOT_TOKEN] + -d Webhook domain + -H Webhook host [0.0.0.0] + -p Webhook port [$PORT or 3000] + -s Stop on error + -l Enable logs + -h Show this help message +``` + +### Telegraf Module example + +Create a module with name `bot.js` and following content: + +```js +const Composer = require('telegraf/composer') +const PhotoURL = 'https://picsum.photos/200/300/?random' + +const bot = new Composer() +bot.start((ctx) => ctx.reply('Hello there!')) +bot.help((ctx) => ctx.reply('Help message')) +bot.command('photo', (ctx) => ctx.replyWithPhoto({ url: PhotoURL })) + +module.exports = bot +``` + +then run it: + +```bash +telegraf -t "bot token" bot.js +``` diff --git a/docs/index.html b/docs/index.html index 05d204ad0..4eba23786 100644 --- a/docs/index.html +++ b/docs/index.html @@ -6,10 +6,11 @@ - - + + +
- + diff --git a/docs/markup.md b/docs/markup.md new file mode 100644 index 000000000..5d03a4fc3 --- /dev/null +++ b/docs/markup.md @@ -0,0 +1,3 @@ +# Markup + +Telegram markup helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). diff --git a/docs/header.png b/docs/media/header.png similarity index 100% rename from docs/header.png rename to docs/media/header.png diff --git a/docs/telegraf.png b/docs/media/telegraf.png similarity index 100% rename from docs/telegraf.png rename to docs/media/telegraf.png diff --git a/docs/stage.md b/docs/stage.md new file mode 100644 index 000000000..c3bdc8ad8 --- /dev/null +++ b/docs/stage.md @@ -0,0 +1,42 @@ +# Stage + +Simple scene-based control flow middleware. + +```js +const { Telegraf } = require('telegraf') +const session = require('telegraf/session') +const Stage = require('telegraf/stage') +const Scene = require('telegraf/scenes/base') +const { leave } = Stage + +// Greeter scene +const greeter = new Scene('greeter') +greeter.enter((ctx) => ctx.reply('Hi')) +greeter.leave((ctx) => ctx.reply('Bye')) +greeter.hears(/hi/gi, leave()) +greeter.on('message', (ctx) => ctx.reply('Send `hi`')) + +// Create scene manager +const stage = new Stage() +stage.command('cancel', leave()) + +// Scene registration +stage.register(greeter) + +const bot = new Telegraf(process.env.BOT_TOKEN) +bot.use(session()) +bot.use(stage.middleware()) +bot.command('greeter', (ctx) => ctx.scene.enter('greeter')) +bot.startPolling() +``` + +Scenes related context props and functions: + +```js +bot.on('message', (ctx) => { + ctx.scene.state // Current scene state (persistent) + ctx.scene.enter(sceneId, [defaultState, silent]) // Enter scene + ctx.scene.reenter() // Reenter current scene + ctx.scene.leave() // Leave scene +}) +``` diff --git a/docs/telegraf.md b/docs/telegraf.md new file mode 100644 index 000000000..9e1f75d24 --- /dev/null +++ b/docs/telegraf.md @@ -0,0 +1,481 @@ +# Telegraf + +Telegraf API reference + +```js +const { Telegraf } = require('telegraf') +``` + +## Constructor + +Initialize new Telegraf bot. + +`const telegraf = new Telegraf(token, [options])` + +| Param | Type | Description | +| --- | --- | --- | +| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) | +| [options] | `object` | Telegraf options | + +Telegraf options: + +```js +{ + telegram: { // Telegram options + agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc. + webhookReply: true // Reply via webhook + }, + username: '' // Bot username (optional) + channelMode: false // Handle `channel_post` updates as messages (optional) +} +``` + +## token + +Use this property to get/set bot token. + +`telegraf.token = [string]` + +## webhookReply + +Use this property to control `reply via webhook` feature. + +`telegraf.webhookReply = [bool]` + +## use + +Registers a middleware. + +`telegraf.use(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware function | + +## on + +Registers middleware for provided update type. + +`telegraf.on(updateTypes, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| updateTypes | `string/string[]` | Update type | +| middleware | `function` | Middleware | + +## hears + +Registers middleware for handling `text` messages. + +`telegraf.hears(triggers, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function` | Triggers | +| middleware | `function` | Middleware | + +## command + +Command handling. + +`telegraf.command(commands, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| commands | `string/string[]` | Commands | +| middleware | `function` | Middleware | + +## start + +Handler for /start command. + +`telegraf.start(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware | + +## help + +Handler for /help command. + +`telegraf.help(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware | + +## settings + +Handler for /settings command. + +`telegraf.settings(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware | + +## entity + +Entity handling. + +`telegraf.entity(entity, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| entity | `string/string[]/RegEx/RegEx[]/Function` | Entity name | +| middleware | `function` | Middleware | + +## mention + +Mention handling. + +`telegraf.mention(username, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| username | `string/string[]` | Username | +| middleware | `function` | Middleware | + +## phone + +Phone number handling. + +`telegraf.phone(number, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| number | `string/string[]` | Phone number | +| middleware | `function` | Middleware | + +## hashtag + +Hashtag handling. + +`telegraf.hashtag(hashtag, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| hashtag | `string/string[]` | Hashtag | +| middleware | `function` | Middleware | + +## cashtag + +Cashtag handling. + +`telegraf.cashtag(cashtag, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| cashtag | `string/string[]` | Cashtag | +| middleware | `function` | Middleware | + +## action + +Registers middleware for handling `callback_data` actions with regular expressions. + +`telegraf.action(triggers, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]` | Triggers | +| middleware | `function` | Middleware | + +## inlineQuery + +Registers middleware for handling `inline_query` actions with regular expressions. + +`telegraf.inlineQuery(triggers, ...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]` | Triggers | +| middleware | `function` | Middleware | + +## gameQuery + +Registers middleware for handling `callback_data` actions with game query. + +`telegraf.gameQuery(...middleware)` + +| Param | Type | Description | +| --- | --- | --- | +| middleware | `function` | Middleware | + +## launch + +Launch bot in long-polling or webhook mode. + +`telegraf.launch(options) => Promise` + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [options] | `object` | Launch options | + +Launch options: + +```js +{ + // Start bot in polling mode (Default) + // See startPolling reference + polling: { timeout, limit, allowedUpdates, stopCallback }, + + // Start bot in webhook mode + // See startWebhook reference + webhook: { domain, hookPath, port, host, tlsOptions, cb } +} +``` + +## startPolling + +Start poll updates. + +`telegraf.startPolling([timeout], [limit], [allowedUpdates], [stopCallback])` + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [timeout] | `number` | 30 | Poll timeout in seconds | +| [limit] | `number` | 100 | Limits the number of updates to be retrieved | +| [allowedUpdates] | `string[]/string/null` | null | List the types of updates you want your bot to receive | +| [stopCallback] | `function` | null | Polling stop callback | + +## startWebhook + +Start listening @ `https://host:port/webhookPath` for Telegram calls. + +`telegraf.startWebhook(hookPath, [tlsOptions], port, [host])` + +| Param | Type | Description | +| --- | --- | --- | +| hookPath | `string` | Webhook url path (see Telegraf.setWebhook) | +| [tlsOptions] | `object` | [TLS server options](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener). Pass null to use http | +| port | `number` | Port number | +| [host] | `string` | Hostname | + +## stop + +Stop Webhook and polling + +`telegraf.stop([callback]) => Promise` + +| Param | Type | +| --- | --- | +| [callback] | function | + +## webhookCallback + +Return a callback function suitable for the http[s].createServer() method to handle a request. You may also use this callback function to mount your telegraf app in a Connect/Express app. + +`telegraf.webhookCallback(webhookPath) => Function` + +| Param | Type | Description | +| --- | --- | --- | +| webhookPath | `string` | Webhook url path (see Telegraf.setWebhook) | + +## handleUpdate + +Handle raw Telegram update. In case you use centralized webhook server, queue, etc. + +`telegraf.handleUpdate(rawUpdate, [webhookResponse])` + +| Param | Type | Description | +| --- | --- | --- | +| rawUpdate | `object` | Telegram update payload | +| [webhookResponse] | `object` | [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) | + +## compose + +Compose `middlewares` returning a fully valid middleware comprised of all those which are passed. + +`Telegraf.compose(middlewares) => function` + +| Param | Type | Description | +| --- | --- | --- | +| middlewares | `function[]` | Array of middlewares | + +## mount + +Generates a middleware for handling provided update types. + +`Telegraf.mount(updateTypes, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| updateTypes | `string/string[]` | Update type | +| middleware | `function` | middleware | + +## hears + +Generates a middleware for handling `text` messages with regular expressions. + +`Telegraf.hears(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## action + +Generates a middleware for handling `callbackQuery` data with regular expressions. + +`Telegraf.action(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## inlineQuery + +Generates a middleware for handling `inlineQuery` data with regular expressions. + +`Telegraf.inlineQuery(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## passThru + +Generates pass thru middleware. + +`Telegraf.passThru() => function` + +## safePassThru + +Generates a safe version of pass thru middleware. + +`Telegraf.safePassThru() => function` + +## optional + +Generates an optional middleware. + +`Telegraf.optional(test, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| test | `truthy/function` | Value or predicate `(ctx) => bool` | +| middleware | `function` | middleware | + +## acl + +Generates a middleware for provided users only. + +`Telegraf.acl(userId, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| userId | `string/string[]` | User id | +| middleware | `function` | middleware | + +## drop + +Generates drop middleware. + +`Telegraf.drop(test) => function` + +| Param | Type | Description | +| --- | --- | --- | +| test | `truthy/function` | Value or predicate `(ctx) => bool` | + +## filter + +Generates filter middleware. + +`Telegraf.filter(test) => function` + +| Param | Type | Description | +| --- | --- | --- | +| test | `truthy/function` | Value or predicate `(ctx) => bool` | + +## branch + +Generates branch middleware. + +`Telegraf.branch(test, trueMiddleware, falseMiddleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| test | `truthy/function` | Value or predicate `(ctx) => bool` | +| trueMiddleware | `function` | true action middleware | +| falseMiddleware | `function` | false action middleware | + +## email + +Generates a middleware for handling messages with `email` entity. + +`Telegraf.email(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## hashtag + +Generates a middleware for handling messages with `hashtag` entity. + +`Telegraf.hashtag(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## cashtag + +Generates a middleware for handling messages with `cashtag` entity. + +`Telegraf.cashtag(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## url + +Generates a middleware for handling messages with `url` entity. + +`Telegraf.url(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## phone + +Generates a middleware for handling messages with `phone` entity. + +`Telegraf.phone(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## textLink + +Generates a middleware for handling messages with `text_link` entity. + +`Telegraf.textLink(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | + +## textMention + +Generates a middleware for handling messages with `text_mention` entity. + +`Telegraf.textMention(triggers, ...middleware) => function` + +| Param | Type | Description | +| --- | --- | --- | +| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | +| handler | `function` | Handler | diff --git a/docs/telegram.md b/docs/telegram.md new file mode 100644 index 000000000..83ccb4b86 --- /dev/null +++ b/docs/telegram.md @@ -0,0 +1,937 @@ +# Telegram + +Telegram client API reference. + +```js +const Telegram = require('telegraf/telegram') +``` + +## Constructor + +Initialize new Telegram client. + +`const telegram = new Telegram(token, [options])` + +| Param | Type | Description | +| --- | --- | --- | +| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) | +| [options] | `object` | Telegram options | + +Telegram options: + +```js +{ + agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc. + webhookReply: true // Reply via webhook +} +``` + +## webhookReply + +Use this property to control `reply via webhook` feature. + +`telegram.webhookReply = [bool]` + +## addStickerToSet + +Use this method to add a new sticker to a set created by the bot. + +`telegram.addStickerToSet(ownerId, name, stickerData) => Promise` +[Official documentation](https://core.telegram.org/bots/api#addstickertoset) + +| Param | Type | Description | +| --- | --- | --- | +| ownerId | `string` | User identifier of sticker set owner | +| name | `string` | Sticker set name | +| stickerData | `Object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | + +## answerCbQuery + +Use this method to send answers to callback queries. + +`telegram.answerCbQuery(callbackQueryId, text, [showAlert], [extra]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#answercallbackquery) + +| Param | Type | Description | +| --- | --- | --- | +| callbackQueryId | `string` | Query id | +| [text] | `string` | Notification text | +| [showAlert] | `bool` | Show alert instead of notification | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answercallbackquery) | + +## answerGameQuery + +Use this method to send answers to game query. + +`telegram.answerGameQuery(callbackQueryId, url) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| callbackQueryId | `string` | Query id | +| url | `string` | Notification text | + +## answerShippingQuery + +Use this method to send answers to shipping query. + +`telegram.answerShippingQuery(shippingQueryId, ok, shippingOptions, [errorMessage]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| shippingQueryId | `string` | Shipping Query id | +| ok | `bool` | Specify True if delivery to the specified address is possible | +| shippingOptions | `object` | [Shipping Options](https://core.telegram.org/bots/api#answershippingquery) | +| [errorMessage] | `string` | Error message in human readable form | + +## answerPreCheckoutQuery + +Use this method to send answers to shipping query. + +`telegram.answerPreCheckoutQuery(preCheckoutQueryId, ok, [errorMessage]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| preCheckoutQueryId | `string` | Shipping Query id | +| ok | `bool` | Specify True if everything is alright (goods are available, etc.) | +| [errorMessage] | `string` | Error message in human readable form | + +## answerInlineQuery + +Use this method to send answers to an inline query. + +`telegram.answerInlineQuery(inlineQueryId, results, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| inlineQueryId | `string` | Query id | +| results | `object[]` | Results | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answerinlinequery)| + +## createNewStickerSet + +Use this method to create new sticker set owned by a user. + +`telegram.createNewStickerSet(ownerId, name, title, stickerData, [isMasks]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#createnewstickerset) + +| Param | Type | Description | +| --- | --- | --- | +| ownerId | `string` | User identifier of sticker set owner | +| name | `string` | Sticker set name | +| title | `string` | Sticker set title | +| stickerData | `object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | +| [isMasks] | `bool` | Pass True, if a set of mask stickers should be created | + +## deleteChatStickerSet + +Use this method to delete a group sticker set from a supergroup. + +`telegram.deleteChatStickerSet(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletechatstickerset) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +## deleteMessage + +Use this method to delete bot messages. + +`telegram.deleteMessage(chatId, messageId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletemessage) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | + +## setStickerSetThumb + +Use this method to set the thumbnail of a sticker set. + +`telegram.setStickerSetThumb(name, userId, [thumb]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setstickersetthumb) + +| Param | Type | Description | +| --- | --- | --- | +| name | `string` | Sticker set name | +| userId | `string` | User identifier of the sticker set owner | +| thumb | `File` | A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size | + +## deleteStickerFromSet + +Use this method to delete a sticker from a set created by the bot. + +`telegram.deleteStickerFromSet(stickerId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletestickerfromset) + +| Param | Type | Description | +| --- | --- | --- | +| stickerId | `string` | File identifier of the sticker | + +## editMessageCaption + +Use this method to edit captions of messages sent by the bot or via the bot. + +`telegram.editMessageCaption(chatId, messageId, inlineMessageId, caption, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| caption | `string` | Caption | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagecaption)| + +## editMessageMedia + +Use this method to edit media of messages sent by the bot or via the bot. + +`telegram.editMessageMedia(chatId, messageId, inlineMessageId, media, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| media | `InputMedia` | [InputMedia](https://core.telegram.org/bots/api#inputmedia) | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagemedia)| + +## editMessageLiveLocation + +Use this method to edit live location messages sent by the bot or via the bot. + +`telegram.editMessageLiveLocation(latitude, longitude, chatId, messageId, inlineMessageId, [markup]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#editmessagelivelocation) + +| Param | Type | Description | +| --- | --- | --- | +| latitude | `string` | Latitude of new location | +| longitude | `string` | Longitude of new location | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| [markup] | `object` | Keyboard markup | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagelivelocation)| + +## editMessageReplyMarkup + +Use this method to edit only the reply markup of messages sent by the bot or via the bot. + +`telegram.editMessageReplyMarkup(chatId, messageId, inlineMessageId, markup, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| markup | `object` | Keyboard markup | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagereplymarkup)| + +## editMessageText + +Use this method to edit text messages sent by the bot or via the bot. + +`telegram.editMessageText(chatId, messageId, inlineMessageId, text, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| text | `string` | Message | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagetext)| + +## forwardMessage + +Forwards message. + +`telegram.forwardMessage(chatId, fromChatId, messageId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Target Chat id | +| fromChatId | `number/string` | Source Chat id | +| messageId | `number` | Message id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#forwardmessage)| + +## sendCopy + +Sends message copy. + +`telegram.sendCopy(chatId, message, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Target Chat id | +| message | `object` | Message | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| + +## copyMessage + +Use this method to copy messages of any kind. + +`telegram.copyMessage(chatId, message, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Target Chat id | +| fromChatId | `number/string` | Source Chat id | +| messageId | `number` | Message id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#copymessage)| + +## getWebhookInfo + +Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. + +`telegram.getWebhookInfo() => Promise` + +## getChat + +Use this method to get up to date information about the chat (current name of the user for one-on-one conversatio +ns, current username of a user, group or channel, etc.). + +`telegram.getChat(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getchat) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +## getChatAdministrators + +Use this method to get a list of administrators in a chat. On success, returns an Array of 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. + +`telegram.getChatAdministrators(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getchatadministrators) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +## setGameScore + +Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat. + +`telegram.setGameScore(userId, score, inlineMessageId, chatId, messageId, [editMessage], [force]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setgamescore) + +| Param | Type | Description | +| --- | --- | --- | +| userId | `number` | Target User id | +| score | `number` | Target User id | +| inlineMessageId | `string` | Inline message id | +| chatId | `number/string` | Target Chat id | +| messageId | `number/string` | Message id | +| [editMessage] | `boolean` | edit target message, default value is True | +| [force] | `boolean` | Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters | + +## getGameHighScores + +Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. + +`telegram.getGameHighScores(userId, inlineMessageId, chatId, messageId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getgamehighscores) + +| Param | Type | Description | +| --- | --- | --- | +| userId | `number`\ | Target User id | +| inlineMessageId | `string` | Inline message id | +| chatId | `number/string` | Target Chat id | +| messageId | `number/string` | Message id | + +## getChatMember + +Use this method to get information about a member of a chat. + +`telegram.getChatMember(chatId, userId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getchatmember) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User identifier | + +## getChatMembersCount + +Use this method to get the number of members in a chat. + +`telegram.getChatMembersCount(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getchatmemberscount) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +## getFile + +Returns basic info about a file and prepare it for downloading. + +`telegram.getFile(fileId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getfile) + +| Param | Type | Description | +| --- | --- | --- | +| fileId | `string` | File id | + +## getFileLink + +Returns link to file. + +`telegram.getFileLink(fileId) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| fileId | `string/object` | File id or file object | + +## getMe + +Returns basic information about the bot. + +`telegram.getMe() => Promise` +[Official documentation](https://core.telegram.org/bots/api#getme) + +## getMyCommands + +Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success. + +`telegram.getMyCommands() => Promise` +[Official documentation](https://core.telegram.org/bots/api#getmycommands) + +## getStickerSet + +Use this method to get a sticker set. + +`telegram.getStickerSet(name) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| name | `string` | Short name of the sticker set | +[Official documentation](https://core.telegram.org/bots/api#getstickerset) + +## getUserProfilePhotos + +Returns profiles photos for provided user. + +`telegram.getUserProfilePhotos(userId, [offset], [limit]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#getuserprofilephotos) + +| Param | Type | Description | +| --- | --- | --- | +| userId | `number` | Chat id | +| [offset] | `number` | Offset | +| [limit] | `number` | Limit | + +## setChatPermissions + +Use this method to set default chat permissions for all members. + +`telegram.setChatPermissions(chatId, permissions) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| permissions | `object` | [New default chat permissions](https://core.telegram.org/bots/api#chatpermissions)| + +## kickChatMember + +Use this method to kick a user from a group or a supergroup. + +`telegram.kickChatMember(chatId, userId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#kickchatmember)| + +## restrictChatMember + +Use this method to restrict a user in a supergroup. + +`telegram.restrictChatMember(chatId, userId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#restrictchatmember)| + +## promoteChatMember + +Use this method to promote or demote a user in a supergroup or a channel. + +`telegram.promoteChatMember(chatId, userId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#promotechatmember)| + +## setChatAdministratorCustomTitle + +New custom title for the administrator; 0-16 characters, emoji are not allowed + +`telegram.setChatAdministratorCustomTitle(chatId, userId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| title | `string` | Custom title | + +## exportChatInviteLink + +Use this method to export an invite link to a supergroup or a channel. + +`telegram.exportChatInviteLink(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#exportchatinvitelink) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +## setChatPhoto + +Use this method to set a new profile photo for the chat. + +`telegram.setChatPhoto(chatId, photo) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setchatphoto) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| photo | `File` | New chat photo | + +## deleteChatPhoto + +Use this method to delete a chat photo. + +`telegram.deleteChatPhoto(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletechatphoto) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +## setChatTitle + +Use this method to change the title of a chat. + +`telegram.setChatTitle(chatId, title) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setchattitle) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| title | `string` | New chat title, 1-255 characters | + +## setChatDescription + +Use this method to change the description of a supergroup or a channel. + +`telegram.setChatDescription(chatId, description) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setchattitle) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| description | `string` | New chat description, 0-255 characters | + +## setChatStickerSet + +Use this method to set a new group sticker set for a supergroup. + +`telegram.setChatStickerSet(chatId, stickerSetName) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setchatstickerset) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| stickerSetName | `string` | Name of the sticker set | + +## pinChatMessage + +Use this method to pin a message in a supergroup. + +`telegram.pinChatMessage(chatId, messageId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `number` | Message id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#pinchatmessage)| + +## unpinChatMessage + +Use this method to unpin a message in a supergroup chat. + +`telegram.unpinChatMessage(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#unpinchatmessage) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unpinchatmessage)| + +## unpinAllChatMessages + +Use this method to clear the list of pinned messages in a chat + +`telegram.unpinAllChatMessages(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#unpinallchatmessages) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +## leaveChat + +Use this method for your bot to leave a group, supergroup or channel. + +`telegram.leaveChat(chatId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#leavechat) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | + +## deleteWebhook + +Removes webhook integration. + +`telegram.deleteWebhook() => Promise` +[Official documentation](https://core.telegram.org/bots/api#deletewebhook) + +| Param | Type | Description | +| --- | --- | --- | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#deletewebhook) | + +## sendAudio + +Sends audio. + +`telegram.sendAudio(chatId, audio, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| audio | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendaudio)| + +## sendGame + +Sends game. + +`telegram.sendGame(chatId, gameName, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| gameName | `String` | Game short name | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendgame)| + +## sendChatAction + +Sends chat action. + +`telegram.sendChatAction(chatId, action) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| action | `string` | [Chat action](https://core.telegram.org/bots/api#sendchataction) | + +## sendContact + +Sends document. + +`telegram.sendContact(chatId, phoneNumber, firstName, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| phoneNumber | `string` | Contact phone number | +| firstName | `string` | Contact first name | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendcontact)| + +## sendDice + +Sends dice. + +`telegram.sendDice(chatId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddice)| + +## sendDocument + +Sends document. + +`telegram.sendDocument(chatId, doc, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| doc | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddocument)| + +## sendLocation + +Sends location. + +`telegram.sendLocation(chatId, latitude, longitude, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| latitude | `number` | Latitude | +| longitude | `number` | Longitude | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendlocation)| + +## sendMessage + +Sends text message. + +`telegram.sendMessage(chatId, text, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| text | `string` | Message | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| + +## sendPhoto + +Sends a photo. + +`telegram.sendPhoto(chatId, photo, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| photo | `File` | Photo | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendphoto)| + +## sendMediaGroup + +Sends media album. + +`telegram.sendMediaGroup(chatId, media, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| media | `InputMedia[]` | Media array | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmediagroup)| + +## sendSticker + +Sends sticker. + +`telegram.sendSticker(chatId, sticker, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| sticker | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendsticker)| + +## setStickerPositionInSet + +Use this method to move a sticker in a set created by the bot to a specific position. + +`telegram.setStickerPositionInSet(sticker, position) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| sticker | `string` | File identifier of the sticker | +| position | `number` | New sticker position in the set, zero-based | + +## sendVenue + +Sends venue information. + +`telegram.sendVenue(chatId, latitude, longitude, title, address, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| latitude | `number` | Latitude | +| longitude | `number` | Longitude | +| title | `string` | Venue title | +| address | `string` | Venue address | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvenue)| + +## sendInvoice + +Sends invoice. + +`telegram.sendInvoice(chatId, invoice) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| invoice | `object` | [Invoice object](https://core.telegram.org/bots/api#sendinvoice) | + +## sendVideo + +Sends video. + +`telegram.sendVideo(chatId, video, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| video | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideo)| + +## sendAnimation + +Sends video. + +`telegram.sendAnimation(chatId, animation, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| animation | `File` | Document | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendanimation)| + +## sendVideoNote + +Sends round video. + +`telegram.sendVideoNote(chatId, video, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| video | `File` | Video note file | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideonote)| + +## sendVoice + +Sends voice. + +`telegram.sendVoice(chatId, voice, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| voice | `File/string` | File, file id or HTTP URL | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvoice)| + +## sendPoll + +Sends a poll. + +`telegram.sendPoll(chatId, question, options, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| question | `string` | Poll question | +| options | `string[]` | Answer options | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| + +## setMyCommands + +Use this method to change the list of the bot's commands + +`telegram.setMyCommands(commands) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| commands | `object[]` | [List of bot commands](https://core.telegram.org/bots/api#setmycommands) | + +## sendQuiz + +Sends quiz. + +`telegram.sendQuiz(chatId, question, options, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| question | `string` | Poll question | +| options | `string[]` | Answer options | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| + +## stopPoll + +Stops anonymous poll. + +`telegram.stopPoll(chatId, messageId, [extra]) => Promise` + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Poll message id | +| options| `string[]` | Answer options | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#stoppoll)| + +## stopMessageLiveLocation + +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. + +`telegram.stopMessageLiveLocation(chatId, messageId, inlineMessageId, [markup]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#stopmessagelivelocation) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| messageId | `string` | Message id | +| inlineMessageId | `string` | Inline message id | +| [markup] | `object` | Keyboard markup | + +## uploadStickerFile + +Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods. + +`telegram.uploadStickerFile(ownerId, stickerFile) => Promise` +[Official documentation](https://core.telegram.org/bots/api#uploadstickerfile) + +| Param | Type | Description | +| --- | --- | --- | +| ownerId | `string` | User identifier of sticker file owner | +| stickerFile | `File` | Png image with the sticker | + +## setWebhook + +Specifies an url to receive incoming updates via an outgoing webhook. + +`telegram.setWebhook(url, [extra]) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setwebhook) + +| Param | Type | Description | +| --- | --- | --- | +| url | `string` | Public url for webhook | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#setwebhook) | + +## unbanChatMember + +Use this method to unban a previously kicked user in a supergroup. + +`telegram.unbanChatMember(chatId, userId) => Promise` +[Official documentation](https://core.telegram.org/bots/api#unbanchatmember) + +| Param | Type | Description | +| --- | --- | --- | +| chatId | `number/string` | Chat id | +| userId | `number` | User id | +| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unbanchatmember) | + +## setPassportDataErrors + +Informs a user that some Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). + +`telegram.setPassportDataErrors(errors) => Promise` +[Official documentation](https://core.telegram.org/bots/api#setpassportdataerrors) + +| Param | Type | Description | +| --- | --- | --- | +| [errors] | `PassportElementError[]` | An array describing the errors | From 443ca1c87bf3377c10d6722871bf82cd76c45f73 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Mon, 18 Jan 2021 07:55:59 +0300 Subject: [PATCH 61/79] less padding --- docs/index.html | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/index.html b/docs/index.html index 4eba23786..ba79e45aa 100644 --- a/docs/index.html +++ b/docs/index.html @@ -10,6 +10,9 @@ From 663c23452429264534774435fa9924df182dc61c Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Mon, 18 Jan 2021 21:23:36 +0300 Subject: [PATCH 68/79] old structure --- docs/api-reference.md | 1472 ----------------------------------------- 1 file changed, 1472 deletions(-) delete mode 100644 docs/api-reference.md diff --git a/docs/api-reference.md b/docs/api-reference.md deleted file mode 100644 index f44ca8887..000000000 --- a/docs/api-reference.md +++ /dev/null @@ -1,1472 +0,0 @@ -# API reference - -## Telegraf - -Telegraf API reference - -```js -const { Telegraf } = require('telegraf') -``` - -### Constructor - -Initialize new Telegraf bot. - -`const telegraf = new Telegraf(token, [options])` - -| Param | Type | Description | -| --- | --- | --- | -| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) | -| [options] | `object` | Telegraf options | - -Telegraf options: - -```js -{ - telegram: { // Telegram options - agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc. - webhookReply: true // Reply via webhook - }, - username: '' // Bot username (optional) - channelMode: false // Handle `channel_post` updates as messages (optional) -} -``` - -### token - -Use this property to get/set bot token. - -`telegraf.token = [string]` - -### webhookReply - -Use this property to control `reply via webhook` feature. - -`telegraf.webhookReply = [bool]` - -### use - -Registers a middleware. - -`telegraf.use(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware function | - -### on - -Registers middleware for provided update type. - -`telegraf.on(updateTypes, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| updateTypes | `string/string[]` | Update type | -| middleware | `function` | Middleware | - -### hears - -Registers middleware for handling `text` messages. - -`telegraf.hears(triggers, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function` | Triggers | -| middleware | `function` | Middleware | - -### command - -Command handling. - -`telegraf.command(commands, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| commands | `string/string[]` | Commands | -| middleware | `function` | Middleware | - -### start - -Handler for /start command. - -`telegraf.start(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware | - -### help - -Handler for /help command. - -`telegraf.help(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware | - -### settings - -Handler for /settings command. - -`telegraf.settings(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware | - -### entity - -Entity handling. - -`telegraf.entity(entity, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| entity | `string/string[]/RegEx/RegEx[]/Function` | Entity name | -| middleware | `function` | Middleware | - -### mention - -Mention handling. - -`telegraf.mention(username, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| username | `string/string[]` | Username | -| middleware | `function` | Middleware | - -### phone - -Phone number handling. - -`telegraf.phone(number, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| number | `string/string[]` | Phone number | -| middleware | `function` | Middleware | - -### hashtag - -Hashtag handling. - -`telegraf.hashtag(hashtag, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| hashtag | `string/string[]` | Hashtag | -| middleware | `function` | Middleware | - -### cashtag - -Cashtag handling. - -`telegraf.cashtag(cashtag, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| cashtag | `string/string[]` | Cashtag | -| middleware | `function` | Middleware | - -### action - -Registers middleware for handling `callback_data` actions with regular expressions. - -`telegraf.action(triggers, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]` | Triggers | -| middleware | `function` | Middleware | - -### inlineQuery - -Registers middleware for handling `inline_query` actions with regular expressions. - -`telegraf.inlineQuery(triggers, ...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]` | Triggers | -| middleware | `function` | Middleware | - -### gameQuery - -Registers middleware for handling `callback_data` actions with game query. - -`telegraf.gameQuery(...middleware)` - -| Param | Type | Description | -| --- | --- | --- | -| middleware | `function` | Middleware | - -### launch - -Launch bot in long-polling or webhook mode. - -`telegraf.launch(options) => Promise` - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| [options] | `object` | Launch options | - -Launch options: - -```js -{ - // Start bot in polling mode (Default) - // See startPolling reference - polling: { timeout, limit, allowedUpdates, stopCallback }, - - // Start bot in webhook mode - // See startWebhook reference - webhook: { domain, hookPath, port, host, tlsOptions, cb } -} -``` - -### startPolling - -Start poll updates. - -`telegraf.startPolling([timeout], [limit], [allowedUpdates], [stopCallback])` - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| [timeout] | `number` | 30 | Poll timeout in seconds | -| [limit] | `number` | 100 | Limits the number of updates to be retrieved | -| [allowedUpdates] | `string[]/string/null` | null | List the types of updates you want your bot to receive | -| [stopCallback] | `function` | null | Polling stop callback | - -### startWebhook - -Start listening @ `https://host:port/webhookPath` for Telegram calls. - -`telegraf.startWebhook(hookPath, [tlsOptions], port, [host])` - -| Param | Type | Description | -| --- | --- | --- | -| hookPath | `string` | Webhook url path (see Telegraf.setWebhook) | -| [tlsOptions] | `object` | [TLS server options](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener). Pass null to use http | -| port | `number` | Port number | -| [host] | `string` | Hostname | - -### stop - -Stop Webhook and polling - -`telegraf.stop([callback]) => Promise` - -| Param | Type | -| --- | --- | -| [callback] | function | - -### webhookCallback - -Return a callback function suitable for the http[s].createServer() method to handle a request. You may also use this callback function to mount your telegraf app in a Connect/Express app. - -`telegraf.webhookCallback(webhookPath) => Function` - -| Param | Type | Description | -| --- | --- | --- | -| webhookPath | `string` | Webhook url path (see Telegraf.setWebhook) | - -### handleUpdate - -Handle raw Telegram update. In case you use centralized webhook server, queue, etc. - -`telegraf.handleUpdate(rawUpdate, [webhookResponse])` - -| Param | Type | Description | -| --- | --- | --- | -| rawUpdate | `object` | Telegram update payload | -| [webhookResponse] | `object` | [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) | - -### compose - -Compose `middlewares` returning a fully valid middleware comprised of all those which are passed. - -`Telegraf.compose(middlewares) => function` - -| Param | Type | Description | -| --- | --- | --- | -| middlewares | `function[]` | Array of middlewares | - -### mount - -Generates a middleware for handling provided update types. - -`Telegraf.mount(updateTypes, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| updateTypes | `string/string[]` | Update type | -| middleware | `function` | middleware | - -### hears - -Generates a middleware for handling `text` messages with regular expressions. - -`Telegraf.hears(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### action - -Generates a middleware for handling `callbackQuery` data with regular expressions. - -`Telegraf.action(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### inlineQuery - -Generates a middleware for handling `inlineQuery` data with regular expressions. - -`Telegraf.inlineQuery(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### passThru - -Generates pass thru middleware. - -`Telegraf.passThru() => function` - -### safePassThru - -Generates a safe version of pass thru middleware. - -`Telegraf.safePassThru() => function` - -### optional - -Generates an optional middleware. - -`Telegraf.optional(test, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| test | `truthy/function` | Value or predicate `(ctx) => bool` | -| middleware | `function` | middleware | - -### acl - -Generates a middleware for provided users only. - -`Telegraf.acl(userId, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| userId | `string/string[]` | User id | -| middleware | `function` | middleware | - -### drop - -Generates drop middleware. - -`Telegraf.drop(test) => function` - -| Param | Type | Description | -| --- | --- | --- | -| test | `truthy/function` | Value or predicate `(ctx) => bool` | - -### filter - -Generates filter middleware. - -`Telegraf.filter(test) => function` - -| Param | Type | Description | -| --- | --- | --- | -| test | `truthy/function` | Value or predicate `(ctx) => bool` | - -### branch - -Generates branch middleware. - -`Telegraf.branch(test, trueMiddleware, falseMiddleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| test | `truthy/function` | Value or predicate `(ctx) => bool` | -| trueMiddleware | `function` | true action middleware | -| falseMiddleware | `function` | false action middleware | - -### email - -Generates a middleware for handling messages with `email` entity. - -`Telegraf.email(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### hashtag - -Generates a middleware for handling messages with `hashtag` entity. - -`Telegraf.hashtag(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### cashtag - -Generates a middleware for handling messages with `cashtag` entity. - -`Telegraf.cashtag(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### url - -Generates a middleware for handling messages with `url` entity. - -`Telegraf.url(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### phone - -Generates a middleware for handling messages with `phone` entity. - -`Telegraf.phone(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### textLink - -Generates a middleware for handling messages with `text_link` entity. - -`Telegraf.textLink(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -### textMention - -Generates a middleware for handling messages with `text_mention` entity. - -`Telegraf.textMention(triggers, ...middleware) => function` - -| Param | Type | Description | -| --- | --- | --- | -| triggers | `string/string[]/RegEx/RegEx[]/Function/Function[]` | Triggers | -| handler | `function` | Handler | - -## Telegram - -Telegram client API reference. - -```js -const Telegram = require('telegraf/telegram') -``` - -### Constructor - -Initialize new Telegram client. - -`const telegram = new Telegram(token, [options])` - -| Param | Type | Description | -| --- | --- | --- | -| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) | -| [options] | `object` | Telegram options | - -Telegram options: - -```js -{ - agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc. - webhookReply: true // Reply via webhook -} -``` - -### webhookReply - -Use this property to control `reply via webhook` feature. - -`telegram.webhookReply = [bool]` - -### addStickerToSet - -Use this method to add a new sticker to a set created by the bot. - -`telegram.addStickerToSet(ownerId, name, stickerData) => Promise` -[Official documentation](https://core.telegram.org/bots/api#addstickertoset) - -| Param | Type | Description | -| --- | --- | --- | -| ownerId | `string` | User identifier of sticker set owner | -| name | `string` | Sticker set name | -| stickerData | `Object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | - -### answerCbQuery - -Use this method to send answers to callback queries. - -`telegram.answerCbQuery(callbackQueryId, text, [showAlert], [extra]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#answercallbackquery) - -| Param | Type | Description | -| --- | --- | --- | -| callbackQueryId | `string` | Query id | -| [text] | `string` | Notification text | -| [showAlert] | `bool` | Show alert instead of notification | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answercallbackquery) | - -### answerGameQuery - -Use this method to send answers to game query. - -`telegram.answerGameQuery(callbackQueryId, url) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| callbackQueryId | `string` | Query id | -| url | `string` | Notification text | - -### answerShippingQuery - -Use this method to send answers to shipping query. - -`telegram.answerShippingQuery(shippingQueryId, ok, shippingOptions, [errorMessage]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| shippingQueryId | `string` | Shipping Query id | -| ok | `bool` | Specify True if delivery to the specified address is possible | -| shippingOptions | `object` | [Shipping Options](https://core.telegram.org/bots/api#answershippingquery) | -| [errorMessage] | `string` | Error message in human readable form | - -### answerPreCheckoutQuery - -Use this method to send answers to shipping query. - -`telegram.answerPreCheckoutQuery(preCheckoutQueryId, ok, [errorMessage]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| preCheckoutQueryId | `string` | Shipping Query id | -| ok | `bool` | Specify True if everything is alright (goods are available, etc.) | -| [errorMessage] | `string` | Error message in human readable form | - -### answerInlineQuery - -Use this method to send answers to an inline query. - -`telegram.answerInlineQuery(inlineQueryId, results, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| inlineQueryId | `string` | Query id | -| results | `object[]` | Results | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answerinlinequery)| - -### createNewStickerSet - -Use this method to create new sticker set owned by a user. - -`telegram.createNewStickerSet(ownerId, name, title, stickerData, [isMasks]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#createnewstickerset) - -| Param | Type | Description | -| --- | --- | --- | -| ownerId | `string` | User identifier of sticker set owner | -| name | `string` | Sticker set name | -| title | `string` | Sticker set title | -| stickerData | `object` | Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) | -| [isMasks] | `bool` | Pass True, if a set of mask stickers should be created | - -### deleteChatStickerSet - -Use this method to delete a group sticker set from a supergroup. - -`telegram.deleteChatStickerSet(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletechatstickerset) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -### deleteMessage - -Use this method to delete bot messages. - -`telegram.deleteMessage(chatId, messageId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletemessage) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | - -### setStickerSetThumb - -Use this method to set the thumbnail of a sticker set. - -`telegram.setStickerSetThumb(name, userId, [thumb]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setstickersetthumb) - -| Param | Type | Description | -| --- | --- | --- | -| name | `string` | Sticker set name | -| userId | `string` | User identifier of the sticker set owner | -| thumb | `File` | A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size | - -### deleteStickerFromSet - -Use this method to delete a sticker from a set created by the bot. - -`telegram.deleteStickerFromSet(stickerId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletestickerfromset) - -| Param | Type | Description | -| --- | --- | --- | -| stickerId | `string` | File identifier of the sticker | - -### editMessageCaption - -Use this method to edit captions of messages sent by the bot or via the bot. - -`telegram.editMessageCaption(chatId, messageId, inlineMessageId, caption, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| caption | `string` | Caption | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagecaption)| - -### editMessageMedia - -Use this method to edit media of messages sent by the bot or via the bot. - -`telegram.editMessageMedia(chatId, messageId, inlineMessageId, media, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| media | `InputMedia` | [InputMedia](https://core.telegram.org/bots/api#inputmedia) | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagemedia)| - -### editMessageLiveLocation - -Use this method to edit live location messages sent by the bot or via the bot. - -`telegram.editMessageLiveLocation(latitude, longitude, chatId, messageId, inlineMessageId, [markup]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#editmessagelivelocation) - -| Param | Type | Description | -| --- | --- | --- | -| latitude | `string` | Latitude of new location | -| longitude | `string` | Longitude of new location | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| [markup] | `object` | Keyboard markup | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagelivelocation)| - -### editMessageReplyMarkup - -Use this method to edit only the reply markup of messages sent by the bot or via the bot. - -`telegram.editMessageReplyMarkup(chatId, messageId, inlineMessageId, markup, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| markup | `object` | Keyboard markup | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagereplymarkup)| - -### editMessageText - -Use this method to edit text messages sent by the bot or via the bot. - -`telegram.editMessageText(chatId, messageId, inlineMessageId, text, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| text | `string` | Message | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagetext)| - -### forwardMessage - -Forwards message. - -`telegram.forwardMessage(chatId, fromChatId, messageId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Target Chat id | -| fromChatId | `number/string` | Source Chat id | -| messageId | `number` | Message id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#forwardmessage)| - -### sendCopy - -Sends message copy. - -`telegram.sendCopy(chatId, message, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Target Chat id | -| message | `object` | Message | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| - -### copyMessage - -Use this method to copy messages of any kind. - -`telegram.copyMessage(chatId, message, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Target Chat id | -| fromChatId | `number/string` | Source Chat id | -| messageId | `number` | Message id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#copymessage)| - -### getWebhookInfo - -Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. - -`telegram.getWebhookInfo() => Promise` - -### getChat - -Use this method to get up to date information about the chat (current name of the user for one-on-one conversatio -ns, current username of a user, group or channel, etc.). - -`telegram.getChat(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getchat) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -### getChatAdministrators - -Use this method to get a list of administrators in a chat. On success, returns an Array of 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. - -`telegram.getChatAdministrators(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getchatadministrators) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -### setGameScore - -Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat. - -`telegram.setGameScore(userId, score, inlineMessageId, chatId, messageId, [editMessage], [force]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setgamescore) - -| Param | Type | Description | -| --- | --- | --- | -| userId | `number` | Target User id | -| score | `number` | Target User id | -| inlineMessageId | `string` | Inline message id | -| chatId | `number/string` | Target Chat id | -| messageId | `number/string` | Message id | -| [editMessage] | `boolean` | edit target message, default value is True | -| [force] | `boolean` | Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters | - -### getGameHighScores - -Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. - -`telegram.getGameHighScores(userId, inlineMessageId, chatId, messageId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getgamehighscores) - -| Param | Type | Description | -| --- | --- | --- | -| userId | `number`\ | Target User id | -| inlineMessageId | `string` | Inline message id | -| chatId | `number/string` | Target Chat id | -| messageId | `number/string` | Message id | - -### getChatMember - -Use this method to get information about a member of a chat. - -`telegram.getChatMember(chatId, userId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getchatmember) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User identifier | - -### getChatMembersCount - -Use this method to get the number of members in a chat. - -`telegram.getChatMembersCount(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getchatmemberscount) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -### getFile - -Returns basic info about a file and prepare it for downloading. - -`telegram.getFile(fileId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getfile) - -| Param | Type | Description | -| --- | --- | --- | -| fileId | `string` | File id | - -### getFileLink - -Returns link to file. - -`telegram.getFileLink(fileId) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| fileId | `string/object` | File id or file object | - -### getMe - -Returns basic information about the bot. - -`telegram.getMe() => Promise` -[Official documentation](https://core.telegram.org/bots/api#getme) - -### getMyCommands - -Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success. - -`telegram.getMyCommands() => Promise` -[Official documentation](https://core.telegram.org/bots/api#getmycommands) - -### getStickerSet - -Use this method to get a sticker set. - -`telegram.getStickerSet(name) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| name | `string` | Short name of the sticker set | -[Official documentation](https://core.telegram.org/bots/api#getstickerset) - -### getUserProfilePhotos - -Returns profiles photos for provided user. - -`telegram.getUserProfilePhotos(userId, [offset], [limit]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#getuserprofilephotos) - -| Param | Type | Description | -| --- | --- | --- | -| userId | `number` | Chat id | -| [offset] | `number` | Offset | -| [limit] | `number` | Limit | - -### setChatPermissions - -Use this method to set default chat permissions for all members. - -`telegram.setChatPermissions(chatId, permissions) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| permissions | `object` | [New default chat permissions](https://core.telegram.org/bots/api#chatpermissions)| - -### kickChatMember - -Use this method to kick a user from a group or a supergroup. - -`telegram.kickChatMember(chatId, userId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#kickchatmember)| - -### restrictChatMember - -Use this method to restrict a user in a supergroup. - -`telegram.restrictChatMember(chatId, userId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#restrictchatmember)| - -### promoteChatMember - -Use this method to promote or demote a user in a supergroup or a channel. - -`telegram.promoteChatMember(chatId, userId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#promotechatmember)| - -### setChatAdministratorCustomTitle - -New custom title for the administrator; 0-16 characters, emoji are not allowed - -`telegram.setChatAdministratorCustomTitle(chatId, userId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| title | `string` | Custom title | - -### exportChatInviteLink - -Use this method to export an invite link to a supergroup or a channel. - -`telegram.exportChatInviteLink(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#exportchatinvitelink) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -### setChatPhoto - -Use this method to set a new profile photo for the chat. - -`telegram.setChatPhoto(chatId, photo) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setchatphoto) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| photo | `File` | New chat photo | - -### deleteChatPhoto - -Use this method to delete a chat photo. - -`telegram.deleteChatPhoto(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletechatphoto) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -### setChatTitle - -Use this method to change the title of a chat. - -`telegram.setChatTitle(chatId, title) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setchattitle) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| title | `string` | New chat title, 1-255 characters | - -### setChatDescription - -Use this method to change the description of a supergroup or a channel. - -`telegram.setChatDescription(chatId, description) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setchattitle) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| description | `string` | New chat description, 0-255 characters | - -### setChatStickerSet - -Use this method to set a new group sticker set for a supergroup. - -`telegram.setChatStickerSet(chatId, stickerSetName) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setchatstickerset) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| stickerSetName | `string` | Name of the sticker set | - -### pinChatMessage - -Use this method to pin a message in a supergroup. - -`telegram.pinChatMessage(chatId, messageId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `number` | Message id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#pinchatmessage)| - -### unpinChatMessage - -Use this method to unpin a message in a supergroup chat. - -`telegram.unpinChatMessage(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#unpinchatmessage) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unpinchatmessage)| - -### unpinAllChatMessages - -Use this method to clear the list of pinned messages in a chat - -`telegram.unpinAllChatMessages(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#unpinallchatmessages) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -### leaveChat - -Use this method for your bot to leave a group, supergroup or channel. - -`telegram.leaveChat(chatId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#leavechat) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | - -### deleteWebhook - -Removes webhook integration. - -`telegram.deleteWebhook() => Promise` -[Official documentation](https://core.telegram.org/bots/api#deletewebhook) - -| Param | Type | Description | -| --- | --- | --- | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#deletewebhook) | - -### sendAudio - -Sends audio. - -`telegram.sendAudio(chatId, audio, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| audio | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendaudio)| - -### sendGame - -Sends game. - -`telegram.sendGame(chatId, gameName, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| gameName | `String` | Game short name | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendgame)| - -### sendChatAction - -Sends chat action. - -`telegram.sendChatAction(chatId, action) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| action | `string` | [Chat action](https://core.telegram.org/bots/api#sendchataction) | - -### sendContact - -Sends document. - -`telegram.sendContact(chatId, phoneNumber, firstName, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| phoneNumber | `string` | Contact phone number | -| firstName | `string` | Contact first name | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendcontact)| - -### sendDice - -Sends dice. - -`telegram.sendDice(chatId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddice)| - -### sendDocument - -Sends document. - -`telegram.sendDocument(chatId, doc, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| doc | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddocument)| - -### sendLocation - -Sends location. - -`telegram.sendLocation(chatId, latitude, longitude, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| latitude | `number` | Latitude | -| longitude | `number` | Longitude | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendlocation)| - -### sendMessage - -Sends text message. - -`telegram.sendMessage(chatId, text, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| text | `string` | Message | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)| - -### sendPhoto - -Sends a photo. - -`telegram.sendPhoto(chatId, photo, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| photo | `File` | Photo | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendphoto)| - -### sendMediaGroup - -Sends media album. - -`telegram.sendMediaGroup(chatId, media, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| media | `InputMedia[]` | Media array | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmediagroup)| - -### sendSticker - -Sends sticker. - -`telegram.sendSticker(chatId, sticker, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| sticker | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendsticker)| - -### setStickerPositionInSet - -Use this method to move a sticker in a set created by the bot to a specific position. - -`telegram.setStickerPositionInSet(sticker, position) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| sticker | `string` | File identifier of the sticker | -| position | `number` | New sticker position in the set, zero-based | - -### sendVenue - -Sends venue information. - -`telegram.sendVenue(chatId, latitude, longitude, title, address, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| latitude | `number` | Latitude | -| longitude | `number` | Longitude | -| title | `string` | Venue title | -| address | `string` | Venue address | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvenue)| - -### sendInvoice - -Sends invoice. - -`telegram.sendInvoice(chatId, invoice) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| invoice | `object` | [Invoice object](https://core.telegram.org/bots/api#sendinvoice) | - -### sendVideo - -Sends video. - -`telegram.sendVideo(chatId, video, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| video | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideo)| - -### sendAnimation - -Sends video. - -`telegram.sendAnimation(chatId, animation, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| animation | `File` | Document | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendanimation)| - -### sendVideoNote - -Sends round video. - -`telegram.sendVideoNote(chatId, video, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| video | `File` | Video note file | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideonote)| - -### sendVoice - -Sends voice. - -`telegram.sendVoice(chatId, voice, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| voice | `File/string` | File, file id or HTTP URL | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvoice)| - -### sendPoll - -Sends a poll. - -`telegram.sendPoll(chatId, question, options, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| question | `string` | Poll question | -| options | `string[]` | Answer options | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| - -### setMyCommands - -Use this method to change the list of the bot's commands - -`telegram.setMyCommands(commands) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| commands | `object[]` | [List of bot commands](https://core.telegram.org/bots/api#setmycommands) | - -### sendQuiz - -Sends quiz. - -`telegram.sendQuiz(chatId, question, options, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| question | `string` | Poll question | -| options | `string[]` | Answer options | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendpoll)| - -### stopPoll - -Stops anonymous poll. - -`telegram.stopPoll(chatId, messageId, [extra]) => Promise` - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Poll message id | -| options| `string[]` | Answer options | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#stoppoll)| - -### stopMessageLiveLocation - -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. - -`telegram.stopMessageLiveLocation(chatId, messageId, inlineMessageId, [markup]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#stopmessagelivelocation) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| messageId | `string` | Message id | -| inlineMessageId | `string` | Inline message id | -| [markup] | `object` | Keyboard markup | - -### uploadStickerFile - -Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods. - -`telegram.uploadStickerFile(ownerId, stickerFile) => Promise` -[Official documentation](https://core.telegram.org/bots/api#uploadstickerfile) - -| Param | Type | Description | -| --- | --- | --- | -| ownerId | `string` | User identifier of sticker file owner | -| stickerFile | `File` | Png image with the sticker | - -### setWebhook - -Specifies an url to receive incoming updates via an outgoing webhook. - -`telegram.setWebhook(url, [extra]) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setwebhook) - -| Param | Type | Description | -| --- | --- | --- | -| url | `string` | Public url for webhook | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#setwebhook) | - -### unbanChatMember - -Use this method to unban a previously kicked user in a supergroup. - -`telegram.unbanChatMember(chatId, userId) => Promise` -[Official documentation](https://core.telegram.org/bots/api#unbanchatmember) - -| Param | Type | Description | -| --- | --- | --- | -| chatId | `number/string` | Chat id | -| userId | `number` | User id | -| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#unbanchatmember) | - -### setPassportDataErrors - -Informs a user that some Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). - -`telegram.setPassportDataErrors(errors) => Promise` -[Official documentation](https://core.telegram.org/bots/api#setpassportdataerrors) - -| Param | Type | Description | -| --- | --- | --- | -| [errors] | `PassportElementError[]` | An array describing the errors | - -## Extra - -Telegram message options helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). - -## Markup - -Telegram markup helper, [see examples](https://github.com/telegraf/telegraf/tree/develop/docs/examples/). - -## Stage - -Simple scene-based control flow middleware. - -```js -const { Telegraf } = require('telegraf') -const session = require('telegraf/session') -const Stage = require('telegraf/stage') -const Scene = require('telegraf/scenes/base') -const { leave } = Stage - -// Greeter scene -const greeter = new Scene('greeter') -greeter.enter((ctx) => ctx.reply('Hi')) -greeter.leave((ctx) => ctx.reply('Bye')) -greeter.hears(/hi/gi, leave()) -greeter.on('message', (ctx) => ctx.reply('Send `hi`')) - -// Create scene manager -const stage = new Stage() -stage.command('cancel', leave()) - -// Scene registration -stage.register(greeter) - -const bot = new Telegraf(process.env.BOT_TOKEN) -bot.use(session()) -bot.use(stage.middleware()) -bot.command('greeter', (ctx) => ctx.scene.enter('greeter')) -bot.startPolling() -``` - -Scenes related context props and functions: - -```js -bot.on('message', (ctx) => { - ctx.scene.state // Current scene state (persistent) - ctx.scene.enter(sceneId, [defaultState, silent]) // Enter scene - ctx.scene.reenter() // Reenter current scene - ctx.scene.leave() // Leave scene -}) -``` From 4802453df389c38009d9556307c67793ad626217 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Mon, 18 Jan 2021 21:23:50 +0300 Subject: [PATCH 69/79] repair urls --- docs/getting-started.md | 194 ++++++++++++++++++++-------------------- 1 file changed, 97 insertions(+), 97 deletions(-) diff --git a/docs/getting-started.md b/docs/getting-started.md index 6de2d45e0..b5b15a05f 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -121,123 +121,123 @@ Context shortcuts for **message** update: | Shortcut | Bound to | | --- | --- | -| `addStickerToSet` | [`telegram.addStickerToSet`](#addstickertoset) | -| `createNewStickerSet` | [`telegram.createNewStickerSet`](#createnewstickerset) | -| `deleteChatPhoto` | [`telegram.deleteChatPhoto`](#deletechatphoto) | -| `deleteMessage` | [`telegram.deleteMessage`](#deletemessage) | -| `deleteStickerFromSet` | [`telegram.deleteStickerFromSet`](#deletestickerfromset) | -| `exportChatInviteLink` | [`telegram.exportChatInviteLink`](#exportchatinvitelink) | -| `forwardMessage` | [`telegram.forwardMessage`](#forwardmessage) | -| `getChat` | [`telegram.getChat`](#getchat) | -| `getChatAdministrators` | [`telegram.getChatAdministrators`](#getchatadministrators) | -| `getChatMember` | [`telegram.getChatMember`](#getchatmember) | -| `getChatMembersCount` | [`telegram.getChatMembersCount`](#getchatmemberscount) | -| `getMyCommands` | [`telegram.getMyCommands`](#getmycommands) | -| `getStickerSet` | [`telegram.getStickerSet`](#getstickerset) | -| `leaveChat` | [`telegram.leaveChat`](#leavechat) | -| `pinChatMessage` | [`telegram.pinChatMessage`](#pinchatmessage) | -| `reply` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithAudio` | [`telegram.sendAudio`](#sendaudio) | -| `replyWithChatAction` | [`telegram.sendChatAction`](#sendchataction) | -| `replyWithDice` | [`telegram.sendDice`](#senddice) | -| `replyWithDocument` | [`telegram.sendDocument`](#senddocument) | -| `replyWithGame` | [`telegram.sendGame`](#sendgame) | -| `replyWithHTML` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithInvoice` | [`telegram.sendInvoice`](#sendinvoice) | -| `replyWithLocation` | [`telegram.sendLocation`](#sendlocation) | -| `replyWithMarkdown` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithMediaGroup` | [`telegram.sendMediaGroup`](#sendmediagroup) | -| `replyWithPhoto` | [`telegram.sendPhoto`](#sendphoto) | -| `replyWithPoll` | [`telegram.sendPoll`](#sendpoll) | -| `replyWithQuiz` | [`telegram.sendQuiz`](#sendquiz) | -| `replyWithSticker` | [`telegram.sendSticker`](#sendsticker) | -| `replyWithVideo` | [`telegram.sendVideo`](#sendvideo) | -| `replyWithVideoNote` | [`telegram.sendVideoNote`](#sendvideonote) | -| `replyWithVoice` | [`telegram.sendVoice`](#sendvoice) | -| `setChatDescription` | [`telegram.setChatDescription`](#setchatdescription) | -| `setChatPhoto` | [`telegram.setChatPhoto`](#setchatphoto) | -| `setChatTitle` | [`telegram.setChatTitle`](#setchattitle) | -| `setMyCommands` | [`telegram.setMyCommands`](#setmycommands) | -| `setPassportDataErrors` | [`telegram.setPassportDataErrors`](#setpassportdataerrors) | -| `setStickerPositionInSet` | [`telegram.setStickerPositionInSet`](#setstickerpositioninset) | -| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | -| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | -| `stopPoll` | [`telegram.stopPoll`](#stoppoll) | -| `unpinChatMessage` | [`telegram.unpinChatMessage`](#unpinchatmessage) | -| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](#unpinallchatmessages) | -| `uploadStickerFile` | [`telegram.uploadStickerFile`](#uploadstickerfile) | -| `unbanChatMember` | [`telegram.unbanChatMember`](#unbanchatmember) | +| `addStickerToSet` | [`telegram.addStickerToSet`](telegram.md#addstickertoset) | +| `createNewStickerSet` | [`telegram.createNewStickerSet`](telegram.md#createnewstickerset) | +| `deleteChatPhoto` | [`telegram.deleteChatPhoto`](telegram.md#deletechatphoto) | +| `deleteMessage` | [`telegram.deleteMessage`](telegram.md#deletemessage) | +| `deleteStickerFromSet` | [`telegram.deleteStickerFromSet`](telegram.md#deletestickerfromset) | +| `exportChatInviteLink` | [`telegram.exportChatInviteLink`](telegram.md#exportchatinvitelink) | +| `forwardMessage` | [`telegram.forwardMessage`](telegram.md#forwardmessage) | +| `getChat` | [`telegram.getChat`](telegram.md#getchat) | +| `getChatAdministrators` | [`telegram.getChatAdministrators`](telegram.md#getchatadministrators) | +| `getChatMember` | [`telegram.getChatMember`](telegram.md#getchatmember) | +| `getChatMembersCount` | [`telegram.getChatMembersCount`](telegram.md#getchatmemberscount) | +| `getMyCommands` | [`telegram.getMyCommands`](telegram.md#getmycommands) | +| `getStickerSet` | [`telegram.getStickerSet`](telegram.md#getstickerset) | +| `leaveChat` | [`telegram.leaveChat`](telegram.md#leavechat) | +| `pinChatMessage` | [`telegram.pinChatMessage`](telegram.md#pinchatmessage) | +| `reply` | [`telegram.sendMessage`](telegram.md#sendmessage) | +| `replyWithAudio` | [`telegram.sendAudio`](telegram.md#sendaudio) | +| `replyWithChatAction` | [`telegram.sendChatAction`](telegram.md#sendchataction) | +| `replyWithDice` | [`telegram.sendDice`](telegram.md#senddice) | +| `replyWithDocument` | [`telegram.sendDocument`](telegram.md#senddocument) | +| `replyWithGame` | [`telegram.sendGame`](telegram.md#sendgame) | +| `replyWithHTML` | [`telegram.sendMessage`](telegram.md#sendmessage) | +| `replyWithInvoice` | [`telegram.sendInvoice`](telegram.md#sendinvoice) | +| `replyWithLocation` | [`telegram.sendLocation`](telegram.md#sendlocation) | +| `replyWithMarkdown` | [`telegram.sendMessage`](telegram.md#sendmessage) | +| `replyWithMediaGroup` | [`telegram.sendMediaGroup`](telegram.md#sendmediagroup) | +| `replyWithPhoto` | [`telegram.sendPhoto`](telegram.md#sendphoto) | +| `replyWithPoll` | [`telegram.sendPoll`](telegram.md#sendpoll) | +| `replyWithQuiz` | [`telegram.sendQuiz`](telegram.md#sendquiz) | +| `replyWithSticker` | [`telegram.sendSticker`](telegram.md#sendsticker) | +| `replyWithVideo` | [`telegram.sendVideo`](telegram.md#sendvideo) | +| `replyWithVideoNote` | [`telegram.sendVideoNote`](telegram.md#sendvideonote) | +| `replyWithVoice` | [`telegram.sendVoice`](telegram.md#sendvoice) | +| `setChatDescription` | [`telegram.setChatDescription`](telegram.md#setchatdescription) | +| `setChatPhoto` | [`telegram.setChatPhoto`](telegram.md#setchatphoto) | +| `setChatTitle` | [`telegram.setChatTitle`](telegram.md#setchattitle) | +| `setMyCommands` | [`telegram.setMyCommands`](telegram.md#setmycommands) | +| `setPassportDataErrors` | [`telegram.setPassportDataErrors`](telegram.md#setpassportdataerrors) | +| `setStickerPositionInSet` | [`telegram.setStickerPositionInSet`](telegram.md#setstickerpositioninset) | +| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](telegram.md#setstickersetthumb) | +| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](telegram.md#setstickersetthumb) | +| `stopPoll` | [`telegram.stopPoll`](telegram.md#stoppoll) | +| `unpinChatMessage` | [`telegram.unpinChatMessage`](telegram.md#unpinchatmessage) | +| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](telegram.md#unpinallchatmessages) | +| `uploadStickerFile` | [`telegram.uploadStickerFile`](telegram.md#uploadstickerfile) | +| `unbanChatMember` | [`telegram.unbanChatMember`](telegram.md#unbanchatmember) | Context shortcuts for **callback_query** update: | Shortcut | Bound to | | --- | --- | -| `addStickerToSet` | [`telegram.addStickerToSet`](#addstickertoset) | -| `answerCbQuery` | [`telegram.answerCbQuery`](#answercbquery) | -| `answerGameQuery` | [`telegram.answerGameQuery`](#answergamequery) | -| `createNewStickerSet` | [`telegram.createNewStickerSet`](#createnewstickerset) | -| `deleteChatPhoto` | [`telegram.deleteChatPhoto`](#deletechatphoto) | -| `deleteMessage` | [`telegram.deleteMessage`](#deletemessage) | -| `deleteStickerFromSet` | [`telegram.deleteStickerFromSet`](#deletestickerfromset) | -| `editMessageCaption` | [`telegram.editMessageCaption`](#editmessagecaption) | -| `editMessageMedia` | [`telegram.editMessageMedia`](#editmessagemedia) | -| `editMessageReplyMarkup` | [`telegram.editMessageReplyMarkup`](#editmessagereplymarkup) | -| `editMessageText` | [`telegram.editMessageText`](#editmessagetext) | -| `exportChatInviteLink` | [`telegram.exportChatInviteLink`](#exportchatinvitelink) | -| `forwardMessage` | [`telegram.forwardMessage`](#forwardmessage) | -| `getChat` | [`telegram.getChat`](#getchat) | -| `getChatAdministrators` | [`telegram.getChatAdministrators`](#getchatadministrators) | -| `getChatMember` | [`telegram.getChatMember`](#getchatmember) | -| `getChatMembersCount` | [`telegram.getChatMembersCount`](#getchatmemberscount) | -| `getStickerSet` | [`telegram.getStickerSet`](#getstickerset) | -| `leaveChat` | [`telegram.leaveChat`](#leavechat) | -| `pinChatMessage` | [`telegram.pinChatMessage`](#pinchatmessage) | -| `reply` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithAnimation` | [`telegram.sendAnimation`](#sendanimation) | -| `replyWithAudio` | [`telegram.sendAudio`](#sendaudio) | -| `replyWithChatAction` | [`telegram.sendChatAction`](#sendchataction) | -| `replyWithDice` | [`telegram.sendDice`](#senddice) | -| `replyWithDocument` | [`telegram.sendDocument`](#senddocument) | -| `replyWithGame` | [`telegram.sendGame`](#sendgame) | -| `replyWithHTML` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithInvoice` | [`telegram.sendInvoice`](#sendinvoice) | -| `replyWithLocation` | [`telegram.sendLocation`](#sendlocation) | -| `replyWithMarkdown` | [`telegram.sendMessage`](#sendmessage) | -| `replyWithMediaGroup` | [`telegram.sendMediaGroup`](#sendmediagroup) | -| `replyWithPhoto` | [`telegram.sendPhoto`](#sendphoto) | -| `replyWithPoll` | [`telegram.sendPoll`](#sendpoll) | -| `replyWithSticker` | [`telegram.sendSticker`](#sendsticker) | -| `replyWithVideo` | [`telegram.sendVideo`](#sendvideo) | -| `replyWithVideoNote` | [`telegram.sendVideoNote`](#sendvideonote) | -| `replyWithVoice` | [`telegram.sendVoice`](#sendvoice) | -| `setChatDescription` | [`telegram.setChatDescription`](#setchatdescription) | -| `setChatPhoto` | [`telegram.setChatPhoto`](#setchatphoto) | -| `setChatTitle` | [`telegram.setChatTitle`](#setchattitle) | -| `setStickerPositionInSet` | [`telegram.setStickerPositionInSet`](#setstickerpositioninset) | -| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](#setstickersetthumb) | -| `stopPoll` | [`telegram.stopPoll`](#stoppoll) | -| `unpinChatMessage` | [`telegram.unpinChatMessage`](#unpinchatmessage) | -| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](#unpinallchatmessages) | -| `uploadStickerFile` | [`telegram.uploadStickerFile`](#uploadstickerfile) | -| `unbanChatMember` | [`telegram.unbanChatMember`](#unbanchatmember) | +| `addStickerToSet` | [`telegram.addStickerToSet`](telegram.md#addstickertoset) | +| `answerCbQuery` | [`telegram.answerCbQuery`](telegram.md#answercbquery) | +| `answerGameQuery` | [`telegram.answerGameQuery`](telegram.md#answergamequery) | +| `createNewStickerSet` | [`telegram.createNewStickerSet`](telegram.md#createnewstickerset) | +| `deleteChatPhoto` | [`telegram.deleteChatPhoto`](telegram.md#deletechatphoto) | +| `deleteMessage` | [`telegram.deleteMessage`](telegram.md#deletemessage) | +| `deleteStickerFromSet` | [`telegram.deleteStickerFromSet`](telegram.md#deletestickerfromset) | +| `editMessageCaption` | [`telegram.editMessageCaption`](telegram.md#editmessagecaption) | +| `editMessageMedia` | [`telegram.editMessageMedia`](telegram.md#editmessagemedia) | +| `editMessageReplyMarkup` | [`telegram.editMessageReplyMarkup`](telegram.md#editmessagereplymarkup) | +| `editMessageText` | [`telegram.editMessageText`](telegram.md#editmessagetext) | +| `exportChatInviteLink` | [`telegram.exportChatInviteLink`](telegram.md#exportchatinvitelink) | +| `forwardMessage` | [`telegram.forwardMessage`](telegram.md#forwardmessage) | +| `getChat` | [`telegram.getChat`](telegram.md#getchat) | +| `getChatAdministrators` | [`telegram.getChatAdministrators`](telegram.md#getchatadministrators) | +| `getChatMember` | [`telegram.getChatMember`](telegram.md#getchatmember) | +| `getChatMembersCount` | [`telegram.getChatMembersCount`](telegram.md#getchatmemberscount) | +| `getStickerSet` | [`telegram.getStickerSet`](telegram.md#getstickerset) | +| `leaveChat` | [`telegram.leaveChat`](telegram.md#leavechat) | +| `pinChatMessage` | [`telegram.pinChatMessage`](telegram.md#pinchatmessage) | +| `reply` | [`telegram.sendMessage`](telegram.md#sendmessage) | +| `replyWithAnimation` | [`telegram.sendAnimation`](telegram.md#sendanimation) | +| `replyWithAudio` | [`telegram.sendAudio`](telegram.md#sendaudio) | +| `replyWithChatAction` | [`telegram.sendChatAction`](telegram.md#sendchataction) | +| `replyWithDice` | [`telegram.sendDice`](telegram.md#senddice) | +| `replyWithDocument` | [`telegram.sendDocument`](telegram.md#senddocument) | +| `replyWithGame` | [`telegram.sendGame`](telegram.md#sendgame) | +| `replyWithHTML` | [`telegram.sendMessage`](telegram.md#sendmessage) | +| `replyWithInvoice` | [`telegram.sendInvoice`](telegram.md#sendinvoice) | +| `replyWithLocation` | [`telegram.sendLocation`](telegram.md#sendlocation) | +| `replyWithMarkdown` | [`telegram.sendMessage`](telegram.md#sendmessage) | +| `replyWithMediaGroup` | [`telegram.sendMediaGroup`](telegram.md#sendmediagroup) | +| `replyWithPhoto` | [`telegram.sendPhoto`](telegram.md#sendphoto) | +| `replyWithPoll` | [`telegram.sendPoll`](telegram.md#sendpoll) | +| `replyWithSticker` | [`telegram.sendSticker`](telegram.md#sendsticker) | +| `replyWithVideo` | [`telegram.sendVideo`](telegram.md#sendvideo) | +| `replyWithVideoNote` | [`telegram.sendVideoNote`](telegram.md#sendvideonote) | +| `replyWithVoice` | [`telegram.sendVoice`](telegram.md#sendvoice) | +| `setChatDescription` | [`telegram.setChatDescription`](telegram.md#setchatdescription) | +| `setChatPhoto` | [`telegram.setChatPhoto`](telegram.md#setchatphoto) | +| `setChatTitle` | [`telegram.setChatTitle`](telegram.md#setchattitle) | +| `setStickerPositionInSet` | [`telegram.setStickerPositionInSet`](telegram.md#setstickerpositioninset) | +| `setStickerSetThumb` | [`telegram.setStickerSetThumb`](telegram.md#setstickersetthumb) | +| `stopPoll` | [`telegram.stopPoll`](telegram.md#stoppoll) | +| `unpinChatMessage` | [`telegram.unpinChatMessage`](telegram.md#unpinchatmessage) | +| `unpinAllChatMessages` | [`telegram.unpinAllChatMessages`](telegram.md#unpinallchatmessages) | +| `uploadStickerFile` | [`telegram.uploadStickerFile`](telegram.md#uploadstickerfile) | +| `unbanChatMember` | [`telegram.unbanChatMember`](telegram.md#unbanchatmember) | Context shortcuts for **inline_query** update: | Shortcut | Bound to | | --- | --- | -| `answerInlineQuery` | [`telegram.answerInlineQuery`](#answerinlinequery) | +| `answerInlineQuery` | [`telegram.answerInlineQuery`](telegram.md#answerinlinequery) | Context shortcuts for **shipping_query** update: | Shortcut | Bound to | | --- | --- | -| `answerShippingQuery` | [`telegram.answerShippingQuery`](#answershippingquery) | +| `answerShippingQuery` | [`telegram.answerShippingQuery`](telegram.md#answershippingquery) | Context shortcuts for **pre_checkout_query** update: | Shortcut | Bound to | | --- | --- | -| `answerPreCheckoutQuery` | [`telegram.answerPreCheckoutQuery`](#answerprecheckoutquery) | +| `answerPreCheckoutQuery` | [`telegram.answerPreCheckoutQuery`](telegram.md#answerprecheckoutquery) | #### Shortcuts usage example From 195d977d759f023a051b26daa0da2d978d7d47ce Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Mon, 18 Jan 2021 21:39:58 +0300 Subject: [PATCH 70/79] add router doc --- docs/_sidebar.md | 1 + docs/router.md | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 docs/router.md diff --git a/docs/_sidebar.md b/docs/_sidebar.md index bcbcc3a0b..cdfb6091d 100644 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -5,4 +5,5 @@ - [Telegram](telegram.md) - [Extra](extra.md) - [Markup](markup.md) + - [Router](router.md) - [Stage](stage.md) diff --git a/docs/router.md b/docs/router.md new file mode 100644 index 000000000..65239c1da --- /dev/null +++ b/docs/router.md @@ -0,0 +1,30 @@ +# Router + +Router is used to direct the flow of update. It accepts as arguments a routing function and, optionally, a Map with predefined routes and handlers. Routing function accepts [context](getting-started.md#context) and return object with route property set to String value. Handler for a specific route is just another middleware. + +Basic usage: + +```js +const Router = require('telegraf/router') + +// can be any function that returns { route: String } +function routeFn(ctx) { + return { route: ctx.updateType } +} + +const router = new Router(routeFn) + +// registering 'callback_query' route +const middlewareCb = function (ctx, next) { ... } +router.on('callback_query', middlewareCb) + +// registering 'message' route +const middlewareMessage = new Composer(...) +router.on('message', middlewareMessage) + +// setting handler for routes that are not registered +const middlewareDefault = someOtherRouter +router.otherwise(middlewareDefault) +``` + +As `Router` object is itself a middleware, routers can be nested, e.g., `router1.on('yo', router2)`. Thus, they allow for very deep, well-structured and flexible logic of updates processing. Possible usecases include multilevel menus, setting different levels of access for bot users and much much more. From 0f500be06e437730d9763a07cb3ee65477752061 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Tue, 19 Jan 2021 01:40:40 +0300 Subject: [PATCH 71/79] ever best example --- docs/examples/custom-router-bot.js | 61 ++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docs/examples/custom-router-bot.js diff --git a/docs/examples/custom-router-bot.js b/docs/examples/custom-router-bot.js new file mode 100644 index 000000000..7f70960be --- /dev/null +++ b/docs/examples/custom-router-bot.js @@ -0,0 +1,61 @@ +const { Telegraf, Router, Extra, session } = require('telegraf') + +const markup = Extra + .HTML() + .markup((m) => m.inlineKeyboard([ + m.callbackButton('Add 1', 'add:1'), + m.callbackButton('Add 10', 'add:10'), + m.callbackButton('Add 100', 'add:100'), + m.callbackButton('Subtract 1', 'sub:1'), + m.callbackButton('Subtract 10', 'sub:10'), + m.callbackButton('Subtract 100', 'sub:100'), + m.callbackButton('🐈', Math.random().toString(36).slice(2)), + m.callbackButton('Clear', 'clear') + ], { columns: 3 })) + +const calculator = new Router(({ callbackQuery }) => { + if (!callbackQuery.data) { + return + } + const parts = callbackQuery.data.split(':') + return { + route: parts[0], + state: { + amount: parseInt(parts[1], 10) || 0 + } + } +}) + +calculator.on('add', (ctx) => { + ctx.session.value = (ctx.session.value || 0) + ctx.state.amount + return editText(ctx) +}) + +calculator.on('sub', (ctx) => { + ctx.session.value = (ctx.session.value || 0) - ctx.state.amount + return editText(ctx) +}) + +calculator.on('clear', (ctx) => { + ctx.session.value = 0 + return editText(ctx) +}) + +calculator.otherwise((ctx) => ctx.reply('🌯')) + +function editText (ctx) { + if (ctx.session.value === 42) { + return ctx.answerCbQuery('Answer to the Ultimate Question of Life, the Universe, and Everything', true) + .then(() => ctx.editMessageText('🎆')) + } + return ctx.editMessageText(`Value: ${ctx.session.value}`, markup).catch(() => undefined) +} + +const bot = new Telegraf(process.env.BOT_TOKEN) +bot.use(session({ ttl: 10 })) +bot.start((ctx) => { + ctx.session.value = 0 + return ctx.reply(`Value: ${ctx.session.value}`, markup) +}) +bot.on('callback_query', calculator) +bot.launch() From 2d771fe48ebded0dd743ba4ce2f3b0e78cc5cc95 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sat, 23 Jan 2021 16:04:30 +0300 Subject: [PATCH 72/79] ever best example --- docs/examples/custom-router-bot.js | 61 ++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docs/examples/custom-router-bot.js diff --git a/docs/examples/custom-router-bot.js b/docs/examples/custom-router-bot.js new file mode 100644 index 000000000..7f70960be --- /dev/null +++ b/docs/examples/custom-router-bot.js @@ -0,0 +1,61 @@ +const { Telegraf, Router, Extra, session } = require('telegraf') + +const markup = Extra + .HTML() + .markup((m) => m.inlineKeyboard([ + m.callbackButton('Add 1', 'add:1'), + m.callbackButton('Add 10', 'add:10'), + m.callbackButton('Add 100', 'add:100'), + m.callbackButton('Subtract 1', 'sub:1'), + m.callbackButton('Subtract 10', 'sub:10'), + m.callbackButton('Subtract 100', 'sub:100'), + m.callbackButton('🐈', Math.random().toString(36).slice(2)), + m.callbackButton('Clear', 'clear') + ], { columns: 3 })) + +const calculator = new Router(({ callbackQuery }) => { + if (!callbackQuery.data) { + return + } + const parts = callbackQuery.data.split(':') + return { + route: parts[0], + state: { + amount: parseInt(parts[1], 10) || 0 + } + } +}) + +calculator.on('add', (ctx) => { + ctx.session.value = (ctx.session.value || 0) + ctx.state.amount + return editText(ctx) +}) + +calculator.on('sub', (ctx) => { + ctx.session.value = (ctx.session.value || 0) - ctx.state.amount + return editText(ctx) +}) + +calculator.on('clear', (ctx) => { + ctx.session.value = 0 + return editText(ctx) +}) + +calculator.otherwise((ctx) => ctx.reply('🌯')) + +function editText (ctx) { + if (ctx.session.value === 42) { + return ctx.answerCbQuery('Answer to the Ultimate Question of Life, the Universe, and Everything', true) + .then(() => ctx.editMessageText('🎆')) + } + return ctx.editMessageText(`Value: ${ctx.session.value}`, markup).catch(() => undefined) +} + +const bot = new Telegraf(process.env.BOT_TOKEN) +bot.use(session({ ttl: 10 })) +bot.start((ctx) => { + ctx.session.value = 0 + return ctx.reply(`Value: ${ctx.session.value}`, markup) +}) +bot.on('callback_query', calculator) +bot.launch() From 9521a44370935845825b1abf462e3fbefcfe2151 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sat, 23 Jan 2021 16:04:52 +0300 Subject: [PATCH 73/79] Revert "ever best example" This reverts commit 0f500be06e437730d9763a07cb3ee65477752061. --- docs/examples/custom-router-bot.js | 61 ------------------------------ 1 file changed, 61 deletions(-) delete mode 100644 docs/examples/custom-router-bot.js diff --git a/docs/examples/custom-router-bot.js b/docs/examples/custom-router-bot.js deleted file mode 100644 index 7f70960be..000000000 --- a/docs/examples/custom-router-bot.js +++ /dev/null @@ -1,61 +0,0 @@ -const { Telegraf, Router, Extra, session } = require('telegraf') - -const markup = Extra - .HTML() - .markup((m) => m.inlineKeyboard([ - m.callbackButton('Add 1', 'add:1'), - m.callbackButton('Add 10', 'add:10'), - m.callbackButton('Add 100', 'add:100'), - m.callbackButton('Subtract 1', 'sub:1'), - m.callbackButton('Subtract 10', 'sub:10'), - m.callbackButton('Subtract 100', 'sub:100'), - m.callbackButton('🐈', Math.random().toString(36).slice(2)), - m.callbackButton('Clear', 'clear') - ], { columns: 3 })) - -const calculator = new Router(({ callbackQuery }) => { - if (!callbackQuery.data) { - return - } - const parts = callbackQuery.data.split(':') - return { - route: parts[0], - state: { - amount: parseInt(parts[1], 10) || 0 - } - } -}) - -calculator.on('add', (ctx) => { - ctx.session.value = (ctx.session.value || 0) + ctx.state.amount - return editText(ctx) -}) - -calculator.on('sub', (ctx) => { - ctx.session.value = (ctx.session.value || 0) - ctx.state.amount - return editText(ctx) -}) - -calculator.on('clear', (ctx) => { - ctx.session.value = 0 - return editText(ctx) -}) - -calculator.otherwise((ctx) => ctx.reply('🌯')) - -function editText (ctx) { - if (ctx.session.value === 42) { - return ctx.answerCbQuery('Answer to the Ultimate Question of Life, the Universe, and Everything', true) - .then(() => ctx.editMessageText('🎆')) - } - return ctx.editMessageText(`Value: ${ctx.session.value}`, markup).catch(() => undefined) -} - -const bot = new Telegraf(process.env.BOT_TOKEN) -bot.use(session({ ttl: 10 })) -bot.start((ctx) => { - ctx.session.value = 0 - return ctx.reply(`Value: ${ctx.session.value}`, markup) -}) -bot.on('callback_query', calculator) -bot.launch() From f5c1c140827c5e3e15487d8b9dd9f7ec629c64f1 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sat, 23 Jan 2021 16:12:39 +0300 Subject: [PATCH 74/79] change media path --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index ee9dcf222..5461847cf 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -![Telegraf](docs/header.png) +![Telegraf](docs/media/header.png) [![Bot API Version](https://img.shields.io/badge/Bot%20API-v4.8-f36caf.svg?style=flat-square)](https://core.telegram.org/bots/api) [![NPM Version](https://img.shields.io/npm/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf) [![node](https://img.shields.io/node/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf) From b72a1bcb6e348691f7156d088989570cac1b95de Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sat, 23 Jan 2021 16:17:01 +0300 Subject: [PATCH 75/79] support v5.0 --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 5461847cf..bb404fc50 100644 --- a/readme.md +++ b/readme.md @@ -1,5 +1,5 @@ ![Telegraf](docs/media/header.png) -[![Bot API Version](https://img.shields.io/badge/Bot%20API-v4.8-f36caf.svg?style=flat-square)](https://core.telegram.org/bots/api) +[![Bot API Version](https://img.shields.io/badge/Bot%20API-v5.0-f36caf.svg?style=flat-square)](https://core.telegram.org/bots/api) [![NPM Version](https://img.shields.io/npm/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf) [![node](https://img.shields.io/node/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf) [![Build Status](https://img.shields.io/travis/telegraf/telegraf.svg?branch=master&style=flat-square)](https://travis-ci.org/telegraf/telegraf) From 4d3b81665ada9005eb78d84d0af9be201d567720 Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sat, 23 Jan 2021 16:22:02 +0300 Subject: [PATCH 76/79] typos --- readme.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/readme.md b/readme.md index bb404fc50..3f8c0b378 100644 --- a/readme.md +++ b/readme.md @@ -8,9 +8,7 @@ ## Introduction -Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically. -Users can interact with bots by sending them command messages in private or group chats. -These accounts serve as an interface for code running somewhere on your server. +Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server. ### Features @@ -26,12 +24,14 @@ These accounts serve as an interface for code running somewhere on your server. ### Installation +```bash +npm install telegraf ``` -$ npm install telegraf -``` + or using `yarn`: -``` -$ yarn add telegraf + +```bash +yarn add telegraf ``` ### Documentation From c9877a409d49a3c1cc4664ecd87a5bf63981078e Mon Sep 17 00:00:00 2001 From: Josh Dies Date: Sat, 23 Jan 2021 18:40:06 +0300 Subject: [PATCH 77/79] support v5.0 --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 3f8c0b378..87437fb9f 100644 --- a/readme.md +++ b/readme.md @@ -12,7 +12,7 @@ Bots are special [Telegram](https://telegram.org) accounts designed to handle me ### Features -- Full [Telegram Bot API 4.8](https://core.telegram.org/bots/api) support +- Full [Telegram Bot API 5.0](https://core.telegram.org/bots/api) support - [Telegram Payment Platform](https://telegram.org/blog/payments) - [HTML5 Games](https://core.telegram.org/bots/api#games) - [Inline mode](https://core.telegram.org/bots/api#inline-mode) From 146d71dcdb9bee06f51b1c586b4af6283aeb8ef2 Mon Sep 17 00:00:00 2001 From: Oscar Sultanov Date: Thu, 11 Feb 2021 00:25:20 +0500 Subject: [PATCH 78/79] Add async await --- docs/getting-started.md | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/docs/getting-started.md b/docs/getting-started.md index b5b15a05f..13338fdfc 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -244,37 +244,37 @@ Context shortcuts for **pre_checkout_query** update: ```js const bot = new Telegraf(process.env.BOT_TOKEN) -bot.command('quit', (ctx) => { +bot.command('quit', async (ctx) => { // Explicit usage - ctx.telegram.leaveChat(ctx.message.chat.id) + await ctx.telegram.leaveChat(ctx.message.chat.id) // Using context shortcut - ctx.leaveChat() + await ctx.leaveChat() }) -bot.on('text', (ctx) => { +bot.on('text', async (ctx) => { // Explicit usage - ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`) + await ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`) // Using context shortcut - ctx.reply(`Hello ${ctx.state.role}`) + await ctx.reply(`Hello ${ctx.state.role}`) }) -bot.on('callback_query', (ctx) => { +bot.on('callback_query', async (ctx) => { // Explicit usage - ctx.telegram.answerCbQuery(ctx.callbackQuery.id) + await ctx.telegram.answerCbQuery(ctx.callbackQuery.id) // Using context shortcut - ctx.answerCbQuery() + await ctx.answerCbQuery() }) -bot.on('inline_query', (ctx) => { +bot.on('inline_query', async (ctx) => { const result = [] // Explicit usage - ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result) + await ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result) // Using context shortcut - ctx.answerInlineQuery(result) + await ctx.answerInlineQuery(result) }) bot.launch() @@ -516,28 +516,28 @@ Supported file sources: Also, you can provide an optional name of file as `filename`. ```js -bot.on('message', (ctx) => { +bot.on('message', async (ctx) => { // resend existing file by file_id - ctx.replyWithSticker('123123jkbhj6b') + await ctx.replyWithSticker('123123jkbhj6b') // send file - ctx.replyWithVideo({ source: '/path/to/video.mp4' }) + await ctx.replyWithVideo({ source: '/path/to/video.mp4' }) // send stream - ctx.replyWithVideo({ + await ctx.replyWithVideo({ source: fs.createReadStream('/path/to/video.mp4') }) // send buffer - ctx.replyWithVoice({ + await ctx.replyWithVoice({ source: Buffer.alloc() }) // send url via Telegram server - ctx.replyWithPhoto('https://picsum.photos/200/300/') + await ctx.replyWithPhoto('https://picsum.photos/200/300/') // pipe url content - ctx.replyWithPhoto({ + await ctx.replyWithPhoto({ url: 'https://picsum.photos/200/300/?random', filename: 'kitten.jpg' }) From 2a9fb9f4000c6c8dd3dd1e0971f0abe8d19cff4c Mon Sep 17 00:00:00 2001 From: Oscar Sultanov Date: Thu, 11 Feb 2021 00:29:00 +0500 Subject: [PATCH 79/79] Fix examples --- docs/examples/custom-context-bot.js | 4 ++-- docs/examples/deeplink-bot.js | 2 +- docs/examples/echo-bot.js | 2 +- docs/examples/example-bot.js | 4 +--- docs/examples/game-bot.js | 4 +--- docs/examples/inline-bot.js | 3 +-- docs/examples/keyboard-bot.js | 4 +--- 7 files changed, 8 insertions(+), 15 deletions(-) diff --git a/docs/examples/custom-context-bot.js b/docs/examples/custom-context-bot.js index 1a614f1b1..c3225ef7f 100644 --- a/docs/examples/custom-context-bot.js +++ b/docs/examples/custom-context-bot.js @@ -1,6 +1,6 @@ -const Telegraf = require('telegraf') +const { Telegraf, Context } = require('telegraf') -class CustomContext extends Telegraf.Context { +class CustomContext extends Context { constructor (update, telegram, options) { console.log('Creating contexy for %j', update) super(update, telegram, options) diff --git a/docs/examples/deeplink-bot.js b/docs/examples/deeplink-bot.js index a95ec7d67..e1d59d7b0 100644 --- a/docs/examples/deeplink-bot.js +++ b/docs/examples/deeplink-bot.js @@ -1,5 +1,5 @@ // https://core.telegram.org/bots#deep-linking -const Telegraf = require('telegraf') +const { Telegraf } = require('telegraf') const bot = new Telegraf(process.env.BOT_TOKEN) bot.start((ctx) => ctx.reply(`Deep link payload: ${ctx.startPayload}`)) diff --git a/docs/examples/echo-bot.js b/docs/examples/echo-bot.js index 3660ee3e1..be7a0ed8e 100644 --- a/docs/examples/echo-bot.js +++ b/docs/examples/echo-bot.js @@ -1,4 +1,4 @@ -const { Telegraf, Extra, Markup } = require('../../telegraf') +const { Telegraf, Extra, Markup } = require('telegraf') const keyboard = Markup.inlineKeyboard([ Markup.urlButton('❤️', 'http://telegraf.js.org'), diff --git a/docs/examples/example-bot.js b/docs/examples/example-bot.js index 777bd454a..dc51a2b3b 100644 --- a/docs/examples/example-bot.js +++ b/docs/examples/example-bot.js @@ -1,6 +1,4 @@ -const Telegraf = require('telegraf') -const Extra = require('telegraf/extra') -const session = require('telegraf/session') +const { Telegraf, Extra, session } = require('telegraf') const { reply, fork } = Telegraf const randomPhoto = 'https://picsum.photos/200/300/?random' diff --git a/docs/examples/game-bot.js b/docs/examples/game-bot.js index 0caff23cb..749afd8c5 100644 --- a/docs/examples/game-bot.js +++ b/docs/examples/game-bot.js @@ -1,6 +1,4 @@ -const Telegraf = require('telegraf') -const Extra = require('telegraf/extra') -const Markup = require('telegraf/markup') +const { Telegraf, Markup } = require('telegraf') const gameShortName = 'your-game' const gameUrl = 'https://your-game.tld' diff --git a/docs/examples/inline-bot.js b/docs/examples/inline-bot.js index befa22949..9aee7299c 100644 --- a/docs/examples/inline-bot.js +++ b/docs/examples/inline-bot.js @@ -1,5 +1,4 @@ -const Telegraf = require('telegraf') -const Markup = require('telegraf/markup') +const { Telegraf, Markup } = require('telegraf') const fetch = require('node-fetch') const bot = new Telegraf(process.env.BOT_TOKEN) diff --git a/docs/examples/keyboard-bot.js b/docs/examples/keyboard-bot.js index 29b44bcac..6d5c453ba 100644 --- a/docs/examples/keyboard-bot.js +++ b/docs/examples/keyboard-bot.js @@ -1,6 +1,4 @@ -const Telegraf = require('telegraf') -const Extra = require('telegraf/extra') -const Markup = require('telegraf/markup') +const { Telegraf, Extra, Markup } = require('telegraf') const bot = new Telegraf(process.env.BOT_TOKEN)