Passed
Pull Request — develop (#1491)
by Rabie
14:52
created

Request::ensureValidAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 6
rs 10
1
<?php
2
3
/**
4
 * This file is part of the TelegramBot package.
5
 *
6
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Longman\TelegramBot;
13
14
use GuzzleHttp\Client;
15
use GuzzleHttp\ClientInterface;
16
use GuzzleHttp\Exception\ConnectException;
17
use GuzzleHttp\Exception\RequestException;
18
use GuzzleHttp\Psr7\Stream;
19
use Longman\TelegramBot\Entities\File;
20
use Longman\TelegramBot\Entities\InputMedia\InputMedia;
21
use Longman\TelegramBot\Entities\Message;
22
use Longman\TelegramBot\Entities\ServerResponse;
23
use Longman\TelegramBot\Exception\InvalidBotTokenException;
24
use Longman\TelegramBot\Exception\TelegramException;
25
use Throwable;
26
27
/**
28
 * Class Request
29
 *
30
 * @method static ServerResponse getUpdates(array $data)                      Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
31
 * @method static ServerResponse setWebhook(array $data)                      Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns true.
32
 * @method static ServerResponse deleteWebhook(array $data)                   Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
33
 * @method static ServerResponse 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.
34
 * @method static ServerResponse getMe()                                      A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object.
35
 * @method static ServerResponse logOut()                                     Use this method to log out from the cloud Bot API server before launching the bot locally. Requires no parameters. Returns True on success.
36
 * @method static ServerResponse close()                                      Use this method to close the bot instance before moving it from one local server to another. Requires no parameters. Returns True on success.
37
 * @method static ServerResponse forwardMessage(array $data)                  Use this method to forward messages of any kind. On success, the sent Message is returned.
38
 * @method static ServerResponse forwardMessages(array $data)                 Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned.
39
 * @method static ServerResponse copyMessage(array $data)                     Use this method to copy messages of any kind. The method is analogous to the method forwardMessages, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
40
 * @method static ServerResponse copyMessages(array $data)                    Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned.
41
 * @method static ServerResponse sendPhoto(array $data)                       Use this method to send photos. On success, the sent Message is returned.
42
 * @method static ServerResponse sendAudio(array $data)                       Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
43
 * @method static ServerResponse sendDocument(array $data)                    Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
44
 * @method static ServerResponse sendSticker(array $data)                     Use this method to send .webp stickers. On success, the sent Message is returned.
45
 * @method static ServerResponse sendVideo(array $data)                       Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
46
 * @method static ServerResponse sendAnimation(array $data)                   Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
47
 * @method static ServerResponse sendVoice(array $data)                       Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
48
 * @method static ServerResponse sendVideoNote(array $data)                   Use this method to send video messages. On success, the sent Message is returned.
49
 * @method static ServerResponse sendMediaGroup(array $data)                  Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned.
50
 * @method static ServerResponse sendLocation(array $data)                    Use this method to send point on the map. On success, the sent Message is returned.
51
 * @method static ServerResponse editMessageLiveLocation(array $data)         Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
52
 * @method static ServerResponse stopMessageLiveLocation(array $data)         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. On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned.
53
 * @method static ServerResponse sendVenue(array $data)                       Use this method to send information about a venue. On success, the sent Message is returned.
54
 * @method static ServerResponse sendContact(array $data)                     Use this method to send phone contacts. On success, the sent Message is returned.
55
 * @method static ServerResponse sendPoll(array $data)                        Use this method to send a native poll. On success, the sent Message containing the poll is returned.
56
 * @method static ServerResponse sendDice(array $data)                        Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent Message is returned.
57
 * @method static ServerResponse sendChatAction(array $data)                  Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
58
 * @method static ServerResponse setMessageReaction(array $data)              Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Returns True on success.
59
 * @method static ServerResponse getUserProfilePhotos(array $data)            Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
60
 * @method static ServerResponse getFile(array $data)                         Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
61
 * @method static ServerResponse banChatMember(array $data)                   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. Returns True on success.
62
 * @method static ServerResponse unbanChatMember(array $data)                 Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. Returns True on success.
63
 * @method static ServerResponse restrictChatMember(array $data)              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 permissions to lift restrictions from a user. Returns True on success.
64
 * @method static ServerResponse promoteChatMember(array $data)               Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success.
65
 * @method static ServerResponse setChatAdministratorCustomTitle(array $data) Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
66
 * @method static ServerResponse banChatSenderChat(array $data)               Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.
67
 * @method static ServerResponse unbanChatSenderChat(array $data)             Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.
68
 * @method static ServerResponse setChatPermissions(array $data)              Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members admin rights. Returns True on success.
69
 * @method static ServerResponse exportChatInviteLink(array $data)            Use this method to generate a new invite link for a chat. Any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the new invite link as String on success.
70
 * @method static ServerResponse createChatInviteLink(array $data)            Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
71
 * @method static ServerResponse editChatInviteLink(array $data)              Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the edited invite link as a ChatInviteLink object.
72
 * @method static ServerResponse revokeChatInviteLink(array $data)            Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the revoked invite link as ChatInviteLink object.
73
 * @method static ServerResponse approveChatJoinRequest(array $data)          Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
74
 * @method static ServerResponse declineChatJoinRequest(array $data)          Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
75
 * @method static ServerResponse setChatPhoto(array $data)                    Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
76
 * @method static ServerResponse deleteChatPhoto(array $data)                 Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
77
 * @method static ServerResponse setChatTitle(array $data)                    Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
78
 * @method static ServerResponse setChatDescription(array $data)              Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
79
 * @method static ServerResponse pinChatMessage(array $data)                  Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success.
80
 * @method static ServerResponse unpinChatMessage(array $data)                Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success.
81
 * @method static ServerResponse unpinAllChatMessages(array $data)            Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' admin right in a supergroup or 'can_edit_messages' admin right in a channel. Returns True on success.
82
 * @method static ServerResponse leaveChat(array $data)                       Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
83
 * @method static ServerResponse getChat(array $data)                         Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a ChatFullInfo object on success.
84
 * @method static ServerResponse getChatAdministrators(array $data)           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.
85
 * @method static ServerResponse getChatMemberCount(array $data)              Use this method to get the number of members in a chat. Returns Int on success.
86
 * @method static ServerResponse getChatMember(array $data)                   Use this method to get information about a member of a chat. Returns a ChatMember object on success.
87
 * @method static ServerResponse setChatStickerSet(array $data)               Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
88
 * @method static ServerResponse deleteChatStickerSet(array $data)            Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
89
 * @method static ServerResponse getForumTopicIconStickers(array $data)       Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects
90
 * @method static ServerResponse createForumTopic(array $data)                Use this method to create a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns information about the created topic as a ForumTopic object.
91
 * @method static ServerResponse editForumTopic(array $data)                  Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
92
 * @method static ServerResponse closeForumTopic(array $data)                 Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
93
 * @method static ServerResponse reopenForumTopic(array $data)                Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
94
 * @method static ServerResponse deleteForumTopic(array $data)                Use this method to delete a forum topic along with all its messages in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success.
95
 * @method static ServerResponse unpinAllForumTopicMessages(array $data)      Use this method to clear the list of pinned messages in a forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.
96
 * @method static ServerResponse editGeneralForumTopic(array $data)           Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights. Returns True on success.
97
 * @method static ServerResponse closeGeneralForumTopic(array $data)          Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
98
 * @method static ServerResponse reopenGeneralForumTopic(array $data)         Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success.
99
 * @method static ServerResponse hideGeneralForumTopic(array $data)           Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success.
100
 * @method static ServerResponse unhideGeneralForumTopic(array $data)         Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
101
 * @method static ServerResponse unpinAllGeneralForumTopicMessages(array $data) Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.
102
 * @method static ServerResponse answerCallbackQuery(array $data)             Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
103
 * @method static ServerResponse answerInlineQuery(array $data)               Use this method to send answers to an inline query. On success, True is returned.
104
 * @method static ServerResponse getUserChatBoosts(array $data)               Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object.
105
 * @method static ServerResponse setMyCommands(array $data)                   Use this method to change the list of the bot's commands. Returns True on success.
106
 * @method static ServerResponse deleteMyCommands(array $data)                Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.
107
 * @method static ServerResponse getMyCommands(array $data)                   Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success.
108
 * @method static ServerResponse setMyName(array $data)                       Use this method to change the bot's name. Returns True on success.
109
 * @method static ServerResponse getMyName(array $data)                       Use this method to get the current bot name for the given user language. Returns BotName on success.
110
 * @method static ServerResponse setMyDescription(array $data)                Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success.
111
 * @method static ServerResponse getMyDescription(array $data)                Use this method to get the current bot description for the given user language. Returns BotDescription on success.
112
 * @method static ServerResponse setMyShortDescription(array $data)           Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success.
113
 * @method static ServerResponse getMyShortDescription(array $data)           Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success.
114
 * @method static ServerResponse setChatMenuButton(array $data)               Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
115
 * @method static ServerResponse getChatMenuButton(array $data)               Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
116
 * @method static ServerResponse setMyDefaultAdministratorRights(array $data) Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.
117
 * @method static ServerResponse getMyDefaultAdministratorRights(array $data) Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
118
 * @method static ServerResponse editMessageText(array $data)                 Use this method to edit text and game 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.
119
 * @method static ServerResponse editMessageCaption(array $data)              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.
120
 * @method static ServerResponse editMessageMedia(array $data)                Use this method to edit audio, document, photo, or video messages. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
121
 * @method static ServerResponse editMessageReplyMarkup(array $data)          Use this method to edit only the reply markup 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.
122
 * @method static ServerResponse stopPoll(array $data)                        Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned.
123
 * @method static ServerResponse deleteMessage(array $data)                   Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
124
 * @method static ServerResponse deleteMessages(array $data)                  Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success.
125
 * @method static ServerResponse getStickerSet(array $data)                   Use this method to get a sticker set. On success, a StickerSet object is returned.
126
 * @method static ServerResponse getCustomEmojiStickers(array $data)          Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.
127
 * @method static ServerResponse uploadStickerFile(array $data)               Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
128
 * @method static ServerResponse createNewStickerSet(array $data)             Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Returns True on success.
129
 * @method static ServerResponse addStickerToSet(array $data)                 Use this method to add a new sticker to a set created by the bot. Returns True on success.
130
 * @method static ServerResponse replaceStickerInSet(array $data)             Use this method to replace a sticker in a set created by the bot with a new one. The sticker must be in WEBP, TGS, or WEBM format. Returns True on success.
131
 * @method static ServerResponse setStickerPositionInSet(array $data)         Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
132
 * @method static ServerResponse deleteStickerFromSet(array $data)            Use this method to delete a sticker from a set created by the bot. Returns True on success.
133
 * @method static ServerResponse setStickerEmojiList(array $data)             Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.
134
 * @method static ServerResponse setStickerKeywords(array $data)              Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.
135
 * @method static ServerResponse setStickerMaskPosition(array $data)          Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success.
136
 * @method static ServerResponse setStickerSetTitle(array $data)              Use this method to set the title of a created sticker set. Returns True on success.
137
 * @method static ServerResponse setStickerSetThumbnail(array $data)          Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success.
138
 * @method static ServerResponse setCustomEmojiStickerSetThumbnail(array $data) Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success.
139
 * @method static ServerResponse deleteStickerSet(array $data)                Use this method to delete a sticker set that was created by the bot. Returns True on success.
140
 * @method static ServerResponse answerWebAppQuery(array $data)               Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
141
 * @method static ServerResponse sendInvoice(array $data)                     Use this method to send invoices. On success, the sent Message is returned.
142
 * @method static ServerResponse createInvoiceLink(array $data)               Use this method to create a link for an invoice. Returns the created invoice link as String on success.
143
 * @method static ServerResponse answerShippingQuery(array $data)             If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
144
 * @method static ServerResponse answerPreCheckoutQuery(array $data)          Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned.
145
 * @method static ServerResponse setPassportDataErrors(array $data)           Informs a user that some of the 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). Returns True on success. Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
146
 * @method static ServerResponse sendGame(array $data)                        Use this method to send a game. On success, the sent Message is returned.
147
 * @method static ServerResponse setGameScore(array $data)                    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 and force is False.
148
 * @method static ServerResponse getGameHighScores(array $data)               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.
149
 */
150
class Request
151
{
152
    /**
153
     * Telegram object
154
     *
155
     * @var Telegram
156
     */
157
    private static $telegram;
158
159
    /**
160
     * URI of the Telegram API
161
     *
162
     * @var string
163
     */
164
    private static $api_base_uri = 'https://api.telegram.org';
165
166
    /**
167
     * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
168
     *
169
     * @var string
170
     */
171
    private static $api_base_download_uri = '/file/bot{API_KEY}';
172
173
    /**
174
     * Guzzle Client object
175
     *
176
     * @var ClientInterface
177
     */
178
    private static $client;
179
180
    /**
181
     * Request limiter
182
     *
183
     * @var bool
184
     */
185
    private static $limiter_enabled;
186
187
    /**
188
     * Request limiter's interval between checks
189
     *
190
     * @var float
191
     */
192
    private static $limiter_interval;
193
194
    /**
195
     * The current action that is being executed
196
     *
197
     * @var string
198
     */
199
    private static $current_action = '';
200
201
    /**
202
     * Available actions to send
203
     *
204
     * This is basically the list of all methods listed on the official API documentation.
205
     *
206
     * @link https://core.telegram.org/bots/api
207
     *
208
     * @var array
209
     */
210
    private static $actions = [
211
        'getUpdates',
212
        'setWebhook',
213
        'deleteWebhook',
214
        'getWebhookInfo',
215
        'getMe',
216
        'logOut',
217
        'close',
218
        'sendMessage',
219
        'forwardMessage',
220
        'forwardMessages',
221
        'copyMessage',
222
        'copyMessages',
223
        'sendPhoto',
224
        'sendAudio',
225
        'sendDocument',
226
        'sendSticker',
227
        'sendVideo',
228
        'sendAnimation',
229
        'sendVoice',
230
        'sendVideoNote',
231
        'sendMediaGroup',
232
        'sendLocation',
233
        'editMessageLiveLocation',
234
        'stopMessageLiveLocation',
235
        'sendVenue',
236
        'sendContact',
237
        'sendPoll',
238
        'sendDice',
239
        'sendChatAction',
240
        'setMessageReaction',
241
        'getUserProfilePhotos',
242
        'getFile',
243
        'banChatMember',
244
        'unbanChatMember',
245
        'restrictChatMember',
246
        'promoteChatMember',
247
        'setChatAdministratorCustomTitle',
248
        'banChatSenderChat',
249
        'unbanChatSenderChat',
250
        'setChatPermissions',
251
        'exportChatInviteLink',
252
        'createChatInviteLink',
253
        'editChatInviteLink',
254
        'revokeChatInviteLink',
255
        'approveChatJoinRequest',
256
        'declineChatJoinRequest',
257
        'setChatPhoto',
258
        'deleteChatPhoto',
259
        'setChatTitle',
260
        'setChatDescription',
261
        'pinChatMessage',
262
        'unpinChatMessage',
263
        'unpinAllChatMessages',
264
        'leaveChat',
265
        'getChat',
266
        'getChatAdministrators',
267
        'getChatMemberCount',
268
        'getChatMember',
269
        'setChatStickerSet',
270
        'deleteChatStickerSet',
271
        'getForumTopicIconStickers',
272
        'createForumTopic',
273
        'editForumTopic',
274
        'closeForumTopic',
275
        'reopenForumTopic',
276
        'deleteForumTopic',
277
        'unpinAllForumTopicMessages',
278
        'editGeneralForumTopic',
279
        'closeGeneralForumTopic',
280
        'reopenGeneralForumTopic',
281
        'hideGeneralForumTopic',
282
        'unhideGeneralForumTopic',
283
        'unpinAllGeneralForumTopicMessages',
284
        'answerCallbackQuery',
285
        'answerInlineQuery',
286
        'getUserChatBoosts',
287
        'setMyCommands',
288
        'deleteMyCommands',
289
        'getMyCommands',
290
        'setMyName',
291
        'getMyName',
292
        'setMyDescription',
293
        'getMyDescription',
294
        'setMyShortDescription',
295
        'getMyShortDescription',
296
        'setChatMenuButton',
297
        'getChatMenuButton',
298
        'setMyDefaultAdministratorRights',
299
        'getMyDefaultAdministratorRights',
300
        'editMessageText',
301
        'editMessageCaption',
302
        'editMessageMedia',
303
        'editMessageReplyMarkup',
304
        'stopPoll',
305
        'deleteMessage',
306
        'deleteMessages',
307
        'getStickerSet',
308
        'getCustomEmojiStickers',
309
        'uploadStickerFile',
310
        'createNewStickerSet',
311
        'addStickerToSet',
312
        'replaceStickerInSet',
313
        'setStickerPositionInSet',
314
        'deleteStickerFromSet',
315
        'setStickerEmojiList',
316
        'setStickerKeywords',
317
        'setStickerMaskPosition',
318
        'setStickerSetTitle',
319
        'setStickerSetThumbnail',
320
        'setCustomEmojiStickerSetThumbnail',
321
        'deleteStickerSet',
322
        'answerWebAppQuery',
323
        'sendInvoice',
324
        'createInvoiceLink',
325
        'answerShippingQuery',
326
        'answerPreCheckoutQuery',
327
        'setPassportDataErrors',
328
        'sendGame',
329
        'setGameScore',
330
        'getGameHighScores',
331
        'getBusinessConnection',
332
    ];
333
334
    /**
335
     * Methods that don't require any data need a dummy param due to certain cURL issues.
336
     *
337
     * @see Request::addDummyParamIfNecessary()
338
     *
339
     * @var array
340
     */
341
    private static $actions_need_dummy_param = [
342
        'deleteWebhook',
343
        'getWebhookInfo',
344
        'getMe',
345
        'logOut',
346
        'close',
347
        'deleteMyCommands',
348
        'getMyCommands',
349
        'setMyName',
350
        'getMyName',
351
        'setMyDescription',
352
        'getMyDescription',
353
        'setMyShortDescription',
354
        'getMyShortDescription',
355
        'setChatMenuButton',
356
        'getChatMenuButton',
357
        'setMyDefaultAdministratorRights',
358
        'getMyDefaultAdministratorRights',
359
    ];
360
361
    /**
362
     * Available fields for InputFile helper
363
     *
364
     * This is basically the list of all fields that allow InputFile objects
365
     * for which input can be simplified by providing local path directly as string.
366
     *
367
     * @var array
368
     */
369
    private static $input_file_fields = [
370
        'setWebhook'          => ['certificate'],
371
        'sendPhoto'           => ['photo'],
372
        'sendAudio'           => ['audio', 'thumbnail'],
373
        'sendDocument'        => ['document', 'thumbnail'],
374
        'sendVideo'           => ['video', 'thumbnail'],
375
        'sendAnimation'       => ['animation', 'thumbnail'],
376
        'sendVoice'           => ['voice'],
377
        'sendVideoNote'       => ['video_note', 'thumbnail'],
378
        'setChatPhoto'        => ['photo'],
379 33
        'sendSticker'         => ['sticker'],
380
        'uploadStickerFile'   => ['sticker'],
381 33
        // @todo Look into new InputSticker field and see if we can do the same there.
382 33
        // 'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
383
        // 'addStickerToSet'     => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
384
        'setStickerSetThumbnail' => ['thumbnail'],
385
    ];
386
387
    /**
388
     * Initialize
389
     *
390 33
     * @param Telegram $telegram
391
     */
392 33
    public static function initialize(Telegram $telegram): void
393
    {
394
        self::$telegram = $telegram;
395
        self::setClient(self::$client ?: new Client(['base_uri' => self::$api_base_uri]));
396
    }
397
398
    /**
399
     * Set a custom Guzzle HTTP Client object
400
     *
401
     * @param ClientInterface $client
402
     */
403
    public static function setClient(ClientInterface $client): void
404
    {
405
        self::$client = $client;
406
    }
407
408
    /**
409
     * Set a custom Bot API URL
410
     *
411
     * @param string $api_base_uri
412
     * @param string $api_base_download_uri
413
     */
414
    public static function setCustomBotApiUri(string $api_base_uri, string $api_base_download_uri = ''): void
415
    {
416
        if (self::$client) {
417
            throw new TelegramException('setCustomBotApiUri() needs to be called before the Telegram object gets instantiated.');
418
        }
419
420
        self::$api_base_uri = $api_base_uri;
421
        if ($api_base_download_uri !== '') {
422
            self::$api_base_download_uri = $api_base_download_uri;
423
        }
424
    }
425
426
    /**
427
     * Get input from custom input or stdin and return it
428 1
     *
429
     * @return string
430
     */
431
    public static function getInput(): string
432
    {
433
        // First check if a custom input has been set, else get the PHP input.
434
        return self::$telegram->getCustomInput()
435
            ?: file_get_contents('php://input');
436 1
    }
437
438 1
    /**
439 1
     * Generate general fake server response
440
     *
441
     * @param array $data Data to add to fake response
442
     *
443 1
     * @return array Fake response data
444 1
     */
445 1
    public static function generateGeneralFakeServerResponse(array $data = []): array
446 1
    {
447 1
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
448 1
        //Maybe this is not the best possible implementation
449 1
450 1
        //No value set in $data ie testing setWebhook
451 1
        //Provided $data['chat_id'] ie testing sendMessage
452
453 1
        $fake_response = ['ok' => true]; // :)
454
455
        if ($data === []) {
456 1
            $fake_response['result'] = true;
457
        }
458
459
        //some data to initialize the class method SendMessage
460
        if (isset($data['chat_id'])) {
461
            $data['message_id'] = '1234';
462
            $data['date']       = '1441378360';
463
            $data['from']       = [
464
                'id'         => 123456789,
465
                'first_name' => 'botname',
466
                'username'   => 'namebot',
467
            ];
468
            $data['chat']       = ['id' => $data['chat_id']];
469
470
            $fake_response['result'] = $data;
471
        }
472
473
        return $fake_response;
474
    }
475
476
    /**
477
     * Properly set up the request params
478
     *
479
     * If any item of the array is a resource, reformat it to a multipart request.
480
     * Else, just return the passed data as form params.
481
     *
482
     * @param array $data
483
     *
484
     * @return array
485
     * @throws TelegramException
486
     */
487
    private static function setUpRequestParams(array $data): array
488
    {
489
        $has_resource = false;
490
        $multipart    = [];
491
492
        foreach ($data as $key => &$item) {
493
            if ($key === 'media') {
494
                // Magical media input helper.
495
                $item = self::mediaInputHelper($item, $has_resource, $multipart);
496
            } elseif (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
497
                // Allow absolute paths to local files.
498
                if (is_string($item) && file_exists($item)) {
499
                    $item = new Stream(self::encodeFile($item));
500
                }
501
            } elseif (is_array($item) || is_object($item)) {
502
                // Convert any nested arrays or objects into JSON strings.
503
                $item = json_encode($item);
504
            }
505
506
            // Reformat data array in multipart way if it contains a resource
507
            $has_resource = $has_resource || is_resource($item) || $item instanceof Stream;
508
            $multipart[]  = ['name' => $key, 'contents' => $item];
509
        }
510
        unset($item);
511
512
        if ($has_resource) {
513
            return ['multipart' => $multipart];
514
        }
515
516
        return ['form_params' => $data];
517
    }
518
519
    /**
520
     * Magical input media helper to simplify passing media.
521
     *
522
     * This allows the following:
523
     * Request::editMessageMedia([
524
     *     ...
525
     *     'media' => new InputMediaPhoto([
526
     *         'caption' => 'Caption!',
527
     *         'media'   => Request::encodeFile($local_photo),
528
     *     ]),
529
     * ]);
530
     * and
531
     * Request::sendMediaGroup([
532
     *     'media'   => [
533
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_1)]),
534
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_2)]),
535
     *         new InputMediaVideo(['media' => Request::encodeFile($local_video_1)]),
536
     *     ],
537
     * ]);
538
     * and even
539
     * Request::sendMediaGroup([
540
     *     'media'   => [
541
     *         new InputMediaPhoto(['media' => $local_photo_1]),
542
     *         new InputMediaPhoto(['media' => $local_photo_2]),
543
     *         new InputMediaVideo(['media' => $local_video_1]),
544
     *     ],
545
     * ]);
546
     *
547
     * @param mixed $item
548
     * @param bool  $has_resource
549
     * @param array $multipart
550
     *
551
     * @return mixed
552
     * @throws TelegramException
553
     */
554
    private static function mediaInputHelper($item, bool &$has_resource, array &$multipart)
555
    {
556
        $was_array = is_array($item);
557
        $was_array || $item = [$item];
558
559
        /** @var InputMedia|null $media_item */
560
        foreach ($item as $media_item) {
561
            if (!($media_item instanceof InputMedia)) {
562
                continue;
563
            }
564
565
            // Make a list of all possible media that can be handled by the helper.
566
            $possible_medias = array_filter([
567
                'media'     => $media_item->getMedia(),
0 ignored issues
show
Bug introduced by
The method getMedia() does not exist on Longman\TelegramBot\Entities\InputMedia\InputMedia. Since it exists in all sub-types, consider adding an abstract or default implementation to Longman\TelegramBot\Entities\InputMedia\InputMedia. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

567
                'media'     => $media_item->/** @scrutinizer ignore-call */ getMedia(),
Loading history...
568
                'thumbnail' => $media_item->getThumbnail(),
0 ignored issues
show
Bug introduced by
The method getThumbnail() does not exist on Longman\TelegramBot\Entities\InputMedia\InputMedia. Since it exists in all sub-types, consider adding an abstract or default implementation to Longman\TelegramBot\Entities\InputMedia\InputMedia. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

568
                'thumbnail' => $media_item->/** @scrutinizer ignore-call */ getThumbnail(),
Loading history...
569
            ]);
570
571
            foreach ($possible_medias as $type => $media) {
572
                // Allow absolute paths to local files.
573
                if (is_string($media) && strpos($media, 'attach://') !== 0 && file_exists($media)) {
574
                    $media = new Stream(self::encodeFile($media));
575
                }
576
577
                if (is_resource($media) || $media instanceof Stream) {
578
                    $has_resource = true;
579
                    $unique_key   = uniqid($type . '_', false);
580
                    $multipart[]  = ['name' => $unique_key, 'contents' => $media];
581
582 7
                    // We're literally overwriting the passed media type data!
583
                    $media_item->$type           = 'attach://' . $unique_key;
584 7
                    $media_item->raw_data[$type] = 'attach://' . $unique_key;
585
                }
586
            }
587
        }
588
589
        $was_array || $item = reset($item);
590
591
        return json_encode($item);
592
    }
593
594
    /**
595
     * Get the current action that's being executed
596
     *
597
     * @return string
598
     */
599
    public static function getCurrentAction(): string
600
    {
601
        return self::$current_action;
602
    }
603
604
    /**
605
     * Execute HTTP Request
606
     *
607
     * @param string $action Action to execute
608
     * @param array  $data   Data to attach to the execution
609
     *
610
     * @return string Result of the HTTP Request
611
     * @throws TelegramException
612
     */
613
    public static function execute(string $action, array $data = []): string
614
    {
615
        $request_params          = self::setUpRequestParams($data);
616
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
617
618
        try {
619
            $response = self::$client->post(
620
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
621
                $request_params
622
            );
623
            $result   = (string) $response->getBody();
624
        } catch (ConnectException $e) {
625
            $response = null;
626
            $result   = $e->getMessage();
627
        } catch (RequestException $e) {
628
            $response = null;
629
            $result   = $e->getResponse() ? (string) $e->getResponse()->getBody() : '';
630
        }
631
632
        //Logging verbose debug output
633
        if (TelegramLog::$always_log_request_and_response || $response === null) {
634
            TelegramLog::debug('Request data:' . PHP_EOL . print_r($data, true));
0 ignored issues
show
Bug introduced by
Are you sure print_r($data, true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

634
            TelegramLog::debug('Request data:' . PHP_EOL . /** @scrutinizer ignore-type */ print_r($data, true));
Loading history...
635
            TelegramLog::debug('Response data:' . PHP_EOL . $result);
636
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
637
        }
638
639
        return $result;
640
    }
641
642
    /**
643
     * Download file
644
     *
645
     * @param File $file
646
     *
647
     * @return bool
648
     * @throws TelegramException
649
     */
650
    public static function downloadFile(File $file): bool
651
    {
652
        if (empty($download_path = self::$telegram->getDownloadPath())) {
653
            throw new TelegramException('Download path not set!');
654
        }
655
656
        $tg_file_path = $file->getFilePath();
657
        $file_path    = $download_path . '/' . $tg_file_path;
658
659
        $file_dir = dirname($file_path);
660
        //For safety reasons, first try to create the directory, then check that it exists.
661
        //This is in case some other process has created the folder in the meantime.
662
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
663
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
664
        }
665
666
        $debug_handle = TelegramLog::getDebugLogTempStream();
667
668
        try {
669
            $base_download_uri = str_replace('{API_KEY}', self::$telegram->getApiKey(), self::$api_base_download_uri);
670
            self::$client->get(
671
                "{$base_download_uri}/{$tg_file_path}",
672
                ['debug' => $debug_handle, 'sink' => $file_path]
673
            );
674
675
            return filesize($file_path) > 0;
676
        } catch (Throwable $e) {
677
            return false;
678
        } finally {
679
            //Logging verbose debug output
680
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
681
        }
682
    }
683
684
    /**
685
     * Encode file
686
     *
687
     * @param string $file
688
     *
689
     * @return resource
690
     * @throws TelegramException
691
     */
692
    public static function encodeFile(string $file)
693
    {
694
        $fp = fopen($file, 'rb');
695
        if ($fp === false) {
696
            throw new TelegramException('Cannot open "' . $file . '" for reading');
697
        }
698
699
        return $fp;
700
    }
701
702
    /**
703
     * Send command
704
     *
705
     * @todo Fake response doesn't need json encoding?
706
     * @todo Write debug entry on failure
707
     *
708
     * @param string $action
709
     * @param array  $data
710
     *
711
     * @return ServerResponse
712
     * @throws TelegramException
713
     */
714
    public static function send(string $action, array $data = []): ServerResponse
715
    {
716
        self::ensureValidAction($action);
717
        self::addDummyParamIfNecessary($action, $data);
718
719
        $bot_username = self::$telegram->getBotUsername();
720
721
        if (defined('PHPUNIT_TESTSUITE')) {
722
            $fake_response = self::generateGeneralFakeServerResponse($data);
723
724
            return new ServerResponse($fake_response, $bot_username);
725
        }
726
727
        self::ensureNonEmptyData($data);
728
729
        self::limitTelegramRequests($action, $data);
730
731
        // Remember which action is currently being executed.
732
        self::$current_action = $action;
733
734
        $raw_response = self::execute($action, $data);
735
        $response     = json_decode($raw_response, true);
736
737
        if (null === $response) {
738
            TelegramLog::debug($raw_response);
739
            throw new TelegramException('Telegram returned an invalid response!');
740
        }
741
742
        $response = new ServerResponse($response, $bot_username);
743
744
        if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
745
            throw new InvalidBotTokenException();
746
        }
747
748
        // Special case for sent polls, which need to be saved specially.
749
        // @todo Take into account if DB gets extracted into separate module.
750
        // DB::insertPollRequest($poll); // Database functionality removed
751
752
        // Reset current action after completion.
753
        self::$current_action = '';
754
755
        return $response;
756
    }
757
758
    /**
759
     * Add a dummy parameter if the passed action requires it.
760
     *
761
     * If a method doesn't require parameters, we need to add a dummy one anyway,
762
     * because of some cURL version failed POST request without parameters.
763
     *
764
     * @link https://github.com/php-telegram-bot/core/pull/228
765
     *
766
     * @todo Would be nice to find a better solution for this!
767
     *
768
     * @param string $action
769
     * @param array  $data
770
     */
771
    protected static function addDummyParamIfNecessary(string $action, array &$data): void
772
    {
773
        if (empty($data) && in_array($action, self::$actions_need_dummy_param, true)) {
774
            // Can be anything, using a single letter to minimise request size.
775
            $data = ['d'];
776
        }
777
    }
778
779
    /**
780
     * Make sure the data isn't empty, else throw an exception
781
     *
782
     * @param array $data
783
     *
784
     * @throws TelegramException
785
     */
786
    private static function ensureNonEmptyData(array $data): void
787
    {
788
        if (count($data) === 0) {
789
            throw new TelegramException('Data is empty!');
790
        }
791
    }
792
793
    /**
794
     * Make sure the action is valid, else throw an exception
795
     *
796
     * @param string $action
797
     *
798
     * @throws TelegramException
799
     */
800
    private static function ensureValidAction(string $action): void
801
    {
802
        if (!in_array($action, self::$actions, true)) {
803
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
804
        }
805
    }
806
807
    /**
808
     * Use this method to send text messages. On success, the last sent Message is returned
809
     *
810
     * All message responses are saved in `$extras['responses']`.
811
     * Custom encoding can be defined in `$extras['encoding']` (default: `mb_internal_encoding()`)
812
     * Custom splitting can be defined in `$extras['split']` (default: 4096)
813
     *     `$extras['split'] = null;` // force to not split message at all!
814
     *     `$extras['split'] = 200;`  // split message into 200 character chunks
815
     *
816
     * @link https://core.telegram.org/bots/api#sendmessage
817
     *
818
     * @todo Splitting formatted text may break the message.
819
     *
820
     * @param array      $data
821
     * @param array|null $extras
822
     *
823
     * @return ServerResponse
824
     * @throws TelegramException
825
     */
826
    public static function sendMessage(array $data, ?array &$extras = []): ServerResponse
827
    {
828
        $extras = array_merge([
829
            'split'    => 4096,
830
            'encoding' => mb_internal_encoding(),
831
        ], (array) $extras);
832
833
        $text       = $data['text'];
834
        $encoding   = $extras['encoding'];
835
        $max_length = $extras['split'] ?: mb_strlen($text, $encoding);
836
837
        $responses = [];
838
839
        // business_connection_id should be in all split messages
840
        $business_connection_id = $data['business_connection_id'] ?? null;
841
842
        do {
843
            // Chop off and send the first message.
844
            $current_data = $data; // Create a copy to avoid modifying the original $data array in loop
845
            $current_data['text'] = mb_substr($text, 0, $max_length, $encoding);
846
            if ($business_connection_id !== null) {
847
                $current_data['business_connection_id'] = $business_connection_id;
848
            }
849
            $responses[]  = self::send('sendMessage', $current_data);
850
851
            // Prepare the next message.
852
            $text = mb_substr($text, $max_length, null, $encoding);
853
        } while ($text !== '');
854
855
        // Add all response objects to referenced variable.
856
        $extras['responses'] = $responses;
857
858
        return end($responses);
859
    }
860
861
    /**
862
     * Any statically called method should be relayed to the `send` method.
863
     *
864
     * @param string $action
865
     * @param array  $data
866
     *
867
     * @return ServerResponse
868
     * @throws TelegramException
869
     */
870
    public static function __callStatic(string $action, array $data): ServerResponse
871
    {
872
        // Only argument should be the data array, ignore any others.
873
        return static::send($action, reset($data) ?: []);
874
    }
875
876
    /**
877
     * Return an empty Server Response
878
     *
879
     * No request is sent to Telegram.
880
     * This function is used in commands that don't need to fire a message after execution
881
     *
882
     * @return ServerResponse
883
     */
884
    public static function emptyResponse(): ServerResponse
885
    {
886
        return new ServerResponse(['ok' => true, 'result' => true]);
887
    }
888
889
    /**
890
     * Send message to all active chats
891
     *
892
     * @param string $callback_function
893
     * @param array  $data
894
     * @param array  $select_chats_params
895
     *
896
     * @return array
897
     * @throws TelegramException
898
     */
899
    public static function sendToActiveChats(
900
        string $callback_function,
901
        array $data,
902
        array $select_chats_params
903
    ): array {
904
        // Always return empty array as DB is removed, so no chats to select.
905
        return [];
906
    }
907
908
    /**
909
     * Enable request limiter
910
     *
911
     * @param bool  $enable
912
     * @param array $options
913
     *
914
     * @throws TelegramException
915
     */
916
    public static function setLimiter(bool $enable = true, array $options = []): void
917
    {
918
        // Limiter is disabled as DB is removed
919
        self::$limiter_enabled = false;
920
    }
921
922
    /**
923
     * This functions delays API requests to prevent reaching Telegram API limits
924
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
925
     *
926
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
927
     *
928
     * @param string $action
929
     * @param array  $data
930
     *
931
     * @throws TelegramException
932
     */
933
    private static function limitTelegramRequests(string $action, array $data = []): void
934
    {
935
        if (self::$limiter_enabled) {
936
            $limited_methods = [
937
                'sendMessage',
938
                'forwardMessage',
939
                'forwardMessages',
940
                'copyMessage',
941
                'copyMessages',
942
                'sendPhoto',
943
                'sendAudio',
944
                'sendDocument',
945
                'sendSticker',
946
                'sendVideo',
947
                'sendAnimation',
948
                'sendVoice',
949
                'sendVideoNote',
950
                'sendMediaGroup',
951
                'sendLocation',
952
                'editMessageLiveLocation',
953
                'stopMessageLiveLocation',
954
                'sendVenue',
955
                'sendContact',
956
                'sendPoll',
957
                'sendDice',
958
                'setMessageReaction',
959
                'sendInvoice',
960
                'sendGame',
961
                'setGameScore',
962
                'setMyCommands',
963
                'deleteMyCommands',
964
                'editMessageText',
965
                'editMessageCaption',
966
                'editMessageMedia',
967
                'editMessageReplyMarkup',
968
                'stopPoll',
969
                'deleteMessage',
970
                'deleteMessages',
971
                'setChatTitle',
972
                'setChatDescription',
973
                'setChatStickerSet',
974
                'deleteChatStickerSet',
975
                'setPassportDataErrors',
976
            ];
977
978
            $chat_id           = $data['chat_id'] ?? null;
979
            $inline_message_id = $data['inline_message_id'] ?? null;
980
981
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods, true)) {
982
                $timeout = 60;
983
984
                while (true) {
985
                    if ($timeout <= 0) {
986
                        throw new TelegramException('Timed out while waiting for a request spot!');
987
                    }
988
989
                    // Limiter logic removed as DB is removed
990
                    break;
991
                }
992
            }
993
        }
994
    }
995
996
    /**
997
     * 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. Returns True on success.
998
     *
999
     * @deprecated
1000
     * @see Request::banChatMember()
1001
     *
1002
     * @param array $data
1003
     *
1004
     * @return ServerResponse
1005
     */
1006
    public static function kickChatMember(array $data = []): ServerResponse
1007
    {
1008
        return static::banChatMember($data);
1009
    }
1010
}
1011