Passed
Push — develop ( 873c3d...57a649 )
by Armando
02:46 queued 23s
created

Request   F

Complexity

Total Complexity 94

Size/Duplication

Total Lines 878
Duplicated Lines 0 %

Test Coverage

Coverage 9.32%

Importance

Changes 41
Bugs 2 Features 1
Metric Value
eloc 366
c 41
b 2
f 1
dl 0
loc 878
ccs 22
cts 236
cp 0.0932
rs 2
wmc 94

22 Methods

Rating   Name   Duplication   Size   Complexity  
A setLimiter() 0 15 4
A getInput() 0 5 2
A setCustomBotApiUri() 0 5 2
A setClient() 0 3 1
A sendToActiveChats() 0 18 3
A downloadFile() 0 31 5
A ensureNonEmptyData() 0 4 2
A execute() 0 27 6
A ensureValidAction() 0 4 2
A initialize() 0 4 2
A __callStatic() 0 4 2
A sendMessage() 0 26 3
A generateGeneralFakeServerResponse() 0 29 3
C setUpRequestParams() 0 30 12
A getCurrentAction() 0 3 1
B send() 0 44 10
A encodeFile() 0 8 2
A kickChatMember() 0 3 1
A emptyResponse() 0 3 1
C limitTelegramRequests() 0 71 16
B mediaInputHelper() 0 38 11
A addDummyParamIfNecessary() 0 5 3

How to fix   Complexity   

Complex Class

Complex classes like Request often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Request, and based on these observations, apply Extract Interface, too.

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 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.
39
 * @method static ServerResponse sendPhoto(array $data)                       Use this method to send photos. On success, the sent Message is returned.
40
 * @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.
41
 * @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.
42
 * @method static ServerResponse sendSticker(array $data)                     Use this method to send .webp stickers. On success, the sent Message is returned.
43
 * @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.
44
 * @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.
45
 * @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.
46
 * @method static ServerResponse sendVideoNote(array $data)                   Use this method to send video messages. On success, the sent Message is returned.
47
 * @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.
48
 * @method static ServerResponse sendLocation(array $data)                    Use this method to send point on the map. On success, the sent Message is returned.
49
 * @method static ServerResponse editMessageLiveLocation(array $data)         Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
50
 * @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.
51
 * @method static ServerResponse sendVenue(array $data)                       Use this method to send information about a venue. On success, the sent Message is returned.
52
 * @method static ServerResponse sendContact(array $data)                     Use this method to send phone contacts. On success, the sent Message is returned.
53
 * @method static ServerResponse sendPoll(array $data)                        Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent Message is returned.
54
 * @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.
55
 * @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.
56
 * @method static ServerResponse getUserProfilePhotos(array $data)            Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
57
 * @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.
58
 * @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.
59
 * @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.
60
 * @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.
61
 * @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.
62
 * @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.
63
 * @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.
64
 * @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.
65
 * @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.
66
 * @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.
67
 * @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.
68
 * @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.
69
 * @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.
70
 * @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.
71
 * @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.
72
 * @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.
73
 * @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.
74
 * @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.
75
 * @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.
76
 * @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.
77
 * @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.
78
 * @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.
79
 * @method static ServerResponse leaveChat(array $data)                       Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
80
 * @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 Chat object on success.
81
 * @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.
82
 * @method static ServerResponse getChatMemberCount(array $data)              Use this method to get the number of members in a chat. Returns Int on success.
83
 * @method static ServerResponse getChatMember(array $data)                   Use this method to get information about a member of a chat. Returns a ChatMember object on success.
84
 * @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.
85
 * @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.
86
 * @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
87
 * @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.
88
 * @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.
89
 * @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.
90
 * @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.
91
 * @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.
92
 * @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.
93
 * @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.
94
 * @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.
95
 * @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.
96
 * @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.
97
 * @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.
98
 * @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.
99
 * @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.
100
 * @method static ServerResponse answerInlineQuery(array $data)               Use this method to send answers to an inline query. On success, True is returned.
101
 * @method static ServerResponse setMyCommands(array $data)                   Use this method to change the list of the bot's commands. Returns True on success.
102
 * @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.
103
 * @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.
104
 * @method static ServerResponse setMyName(array $data)                       Use this method to change the bot's name. Returns True on success.
105
 * @method static ServerResponse getMyName(array $data)                       Use this method to get the current bot name for the given user language. Returns BotName on success.
106
 * @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.
107
 * @method static ServerResponse getMyDescription(array $data)                Use this method to get the current bot description for the given user language. Returns BotDescription on success.
108
 * @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.
109
 * @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.
110
 * @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.
111
 * @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.
112
 * @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.
113
 * @method static ServerResponse getMyDefaultAdministratorRights(array $data) Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
114
 * @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.
115
 * @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.
116
 * @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.
117
 * @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.
118
 * @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.
119
 * @method static ServerResponse deleteMessage(array $data)                   Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
120
 * @method static ServerResponse getStickerSet(array $data)                   Use this method to get a sticker set. On success, a StickerSet object is returned.
121
 * @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.
122
 * @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.
123
 * @method static ServerResponse createNewStickerSet(array $data)             Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
124
 * @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.
125
 * @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.
126
 * @method static ServerResponse deleteStickerFromSet(array $data)            Use this method to delete a sticker from a set created by the bot. Returns True on success.
127
 * @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.
128
 * @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.
129
 * @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.
130
 * @method static ServerResponse setStickerSetTitle(array $data)              Use this method to set the title of a created sticker set. Returns True on success.
131
 * @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.
132
 * @method static ServerResponse setCustomEmojiStickerSetThumbnail(array $data) Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success.
133
 * @method static ServerResponse deleteStickerSet(array $data)                Use this method to delete a sticker set that was created by the bot. Returns True on success.
134
 * @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.
135
 * @method static ServerResponse sendInvoice(array $data)                     Use this method to send invoices. On success, the sent Message is returned.
136
 * @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.
137
 * @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.
138
 * @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.
139
 * @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.
140
 * @method static ServerResponse sendGame(array $data)                        Use this method to send a game. On success, the sent Message is returned.
141
 * @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.
142
 * @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.
143
 */
144
class Request
145
{
146
    /**
147
     * Telegram object
148
     *
149
     * @var Telegram
150
     */
151
    private static $telegram;
152
153
    /**
154
     * URI of the Telegram API
155
     *
156
     * @var string
157
     */
158
    private static $api_base_uri = 'https://api.telegram.org';
159
160
    /**
161
     * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
162
     *
163
     * @var string
164
     */
165
    private static $api_base_download_uri = '/file/bot{API_KEY}';
166
167
    /**
168
     * Guzzle Client object
169
     *
170
     * @var ClientInterface
171
     */
172
    private static $client;
173
174
    /**
175
     * Request limiter
176
     *
177
     * @var bool
178
     */
179
    private static $limiter_enabled;
180
181
    /**
182
     * Request limiter's interval between checks
183
     *
184
     * @var float
185
     */
186
    private static $limiter_interval;
187
188
    /**
189
     * The current action that is being executed
190
     *
191
     * @var string
192
     */
193
    private static $current_action = '';
194
195
    /**
196
     * Available actions to send
197
     *
198
     * This is basically the list of all methods listed on the official API documentation.
199
     *
200
     * @link https://core.telegram.org/bots/api
201
     *
202
     * @var array
203
     */
204
    private static $actions = [
205
        'getUpdates',
206
        'setWebhook',
207
        'deleteWebhook',
208
        'getWebhookInfo',
209
        'getMe',
210
        'logOut',
211
        'close',
212
        'sendMessage',
213
        'forwardMessage',
214
        'copyMessage',
215
        'sendPhoto',
216
        'sendAudio',
217
        'sendDocument',
218
        'sendSticker',
219
        'sendVideo',
220
        'sendAnimation',
221
        'sendVoice',
222
        'sendVideoNote',
223
        'sendMediaGroup',
224
        'sendLocation',
225
        'editMessageLiveLocation',
226
        'stopMessageLiveLocation',
227
        'sendVenue',
228
        'sendContact',
229
        'sendPoll',
230
        'sendDice',
231
        'sendChatAction',
232
        'getUserProfilePhotos',
233
        'getFile',
234
        'banChatMember',
235
        'unbanChatMember',
236
        'restrictChatMember',
237
        'promoteChatMember',
238
        'setChatAdministratorCustomTitle',
239
        'banChatSenderChat',
240
        'unbanChatSenderChat',
241
        'setChatPermissions',
242
        'exportChatInviteLink',
243
        'createChatInviteLink',
244
        'editChatInviteLink',
245
        'revokeChatInviteLink',
246
        'approveChatJoinRequest',
247
        'declineChatJoinRequest',
248
        'setChatPhoto',
249
        'deleteChatPhoto',
250
        'setChatTitle',
251
        'setChatDescription',
252
        'pinChatMessage',
253
        'unpinChatMessage',
254
        'unpinAllChatMessages',
255
        'leaveChat',
256
        'getChat',
257
        'getChatAdministrators',
258
        'getChatMemberCount',
259
        'getChatMember',
260
        'setChatStickerSet',
261
        'deleteChatStickerSet',
262
        'getForumTopicIconStickers',
263
        'createForumTopic',
264
        'editForumTopic',
265
        'closeForumTopic',
266
        'reopenForumTopic',
267
        'deleteForumTopic',
268
        'unpinAllForumTopicMessages',
269
        'editGeneralForumTopic',
270
        'closeGeneralForumTopic',
271
        'reopenGeneralForumTopic',
272
        'hideGeneralForumTopic',
273
        'unhideGeneralForumTopic',
274
        'unpinAllGeneralForumTopicMessages',
275
        'answerCallbackQuery',
276
        'answerInlineQuery',
277
        'setMyCommands',
278
        'deleteMyCommands',
279
        'getMyCommands',
280
        'setMyName',
281
        'getMyName',
282
        'setMyDescription',
283
        'getMyDescription',
284
        'setMyShortDescription',
285
        'getMyShortDescription',
286
        'setChatMenuButton',
287
        'getChatMenuButton',
288
        'setMyDefaultAdministratorRights',
289
        'getMyDefaultAdministratorRights',
290
        'editMessageText',
291
        'editMessageCaption',
292
        'editMessageMedia',
293
        'editMessageReplyMarkup',
294
        'stopPoll',
295
        'deleteMessage',
296
        'getStickerSet',
297
        'getCustomEmojiStickers',
298
        'uploadStickerFile',
299
        'createNewStickerSet',
300
        'addStickerToSet',
301
        'setStickerPositionInSet',
302
        'deleteStickerFromSet',
303
        'setStickerEmojiList',
304
        'setStickerKeywords',
305
        'setStickerMaskPosition',
306
        'setStickerSetTitle',
307
        'setStickerSetThumbnail',
308
        'setCustomEmojiStickerSetThumbnail',
309
        'deleteStickerSet',
310
        'answerWebAppQuery',
311
        'sendInvoice',
312
        'createInvoiceLink',
313
        'answerShippingQuery',
314
        'answerPreCheckoutQuery',
315
        'setPassportDataErrors',
316
        'sendGame',
317
        'setGameScore',
318
        'getGameHighScores',
319
    ];
320
321
    /**
322
     * Methods that don't require any data need a dummy param due to certain cURL issues.
323
     *
324
     * @see Request::addDummyParamIfNecessary()
325
     *
326
     * @var array
327
     */
328
    private static $actions_need_dummy_param = [
329
        'deleteWebhook',
330
        'getWebhookInfo',
331
        'getMe',
332
        'logOut',
333
        'close',
334
        'deleteMyCommands',
335
        'getMyCommands',
336
        'setMyName',
337
        'getMyName',
338
        'setMyDescription',
339
        'getMyDescription',
340
        'setMyShortDescription',
341
        'getMyShortDescription',
342
        'setChatMenuButton',
343
        'getChatMenuButton',
344
        'setMyDefaultAdministratorRights',
345
        'getMyDefaultAdministratorRights',
346
    ];
347
348
    /**
349
     * Available fields for InputFile helper
350
     *
351
     * This is basically the list of all fields that allow InputFile objects
352
     * for which input can be simplified by providing local path directly as string.
353
     *
354
     * @var array
355
     */
356
    private static $input_file_fields = [
357
        'setWebhook'          => ['certificate'],
358
        'sendPhoto'           => ['photo'],
359
        'sendAudio'           => ['audio', 'thumbnail'],
360
        'sendDocument'        => ['document', 'thumbnail'],
361
        'sendVideo'           => ['video', 'thumbnail'],
362
        'sendAnimation'       => ['animation', 'thumbnail'],
363
        'sendVoice'           => ['voice'],
364
        'sendVideoNote'       => ['video_note', 'thumbnail'],
365
        'setChatPhoto'        => ['photo'],
366
        'sendSticker'         => ['sticker'],
367
        'uploadStickerFile'   => ['sticker'],
368
        // @todo Look into new InputSticker field and see if we can do the same there.
369
        // 'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
370
        // 'addStickerToSet'     => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
371
        'setStickerSetThumbnail' => ['thumbnail'],
372
    ];
373
374
    /**
375
     * Initialize
376
     *
377
     * @param Telegram $telegram
378
     */
379 33
    public static function initialize(Telegram $telegram): void
380
    {
381 33
        self::$telegram = $telegram;
382 33
        self::setClient(self::$client ?: new Client(['base_uri' => self::$api_base_uri]));
383
    }
384
385
    /**
386
     * Set a custom Guzzle HTTP Client object
387
     *
388
     * @param ClientInterface $client
389
     */
390 33
    public static function setClient(ClientInterface $client): void
391
    {
392 33
        self::$client = $client;
393
    }
394
395
    /**
396
     * Set a custom Bot API URL
397
     *
398
     * @param string $api_base_uri
399
     * @param string $api_base_download_uri
400
     */
401
    public static function setCustomBotApiUri(string $api_base_uri, string $api_base_download_uri = ''): void
402
    {
403
        self::$api_base_uri = $api_base_uri;
404
        if ($api_base_download_uri !== '') {
405
            self::$api_base_download_uri = $api_base_download_uri;
406
        }
407
    }
408
409
    /**
410
     * Get input from custom input or stdin and return it
411
     *
412
     * @return string
413
     */
414
    public static function getInput(): string
415
    {
416
        // First check if a custom input has been set, else get the PHP input.
417
        return self::$telegram->getCustomInput()
418
            ?: file_get_contents('php://input');
419
    }
420
421
    /**
422
     * Generate general fake server response
423
     *
424
     * @param array $data Data to add to fake response
425
     *
426
     * @return array Fake response data
427
     */
428 1
    public static function generateGeneralFakeServerResponse(array $data = []): array
429
    {
430
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
431
        //Maybe this is not the best possible implementation
432
433
        //No value set in $data ie testing setWebhook
434
        //Provided $data['chat_id'] ie testing sendMessage
435
436 1
        $fake_response = ['ok' => true]; // :)
437
438 1
        if ($data === []) {
439 1
            $fake_response['result'] = true;
440
        }
441
442
        //some data to initialize the class method SendMessage
443 1
        if (isset($data['chat_id'])) {
444 1
            $data['message_id'] = '1234';
445 1
            $data['date']       = '1441378360';
446 1
            $data['from']       = [
447 1
                'id'         => 123456789,
448 1
                'first_name' => 'botname',
449 1
                'username'   => 'namebot',
450 1
            ];
451 1
            $data['chat']       = ['id' => $data['chat_id']];
452
453 1
            $fake_response['result'] = $data;
454
        }
455
456 1
        return $fake_response;
457
    }
458
459
    /**
460
     * Properly set up the request params
461
     *
462
     * If any item of the array is a resource, reformat it to a multipart request.
463
     * Else, just return the passed data as form params.
464
     *
465
     * @param array $data
466
     *
467
     * @return array
468
     * @throws TelegramException
469
     */
470
    private static function setUpRequestParams(array $data): array
471
    {
472
        $has_resource = false;
473
        $multipart    = [];
474
475
        foreach ($data as $key => &$item) {
476
            if ($key === 'media') {
477
                // Magical media input helper.
478
                $item = self::mediaInputHelper($item, $has_resource, $multipart);
479
            } elseif (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
480
                // Allow absolute paths to local files.
481
                if (is_string($item) && file_exists($item)) {
482
                    $item = new Stream(self::encodeFile($item));
483
                }
484
            } elseif (is_array($item) || is_object($item)) {
485
                // Convert any nested arrays or objects into JSON strings.
486
                $item = json_encode($item);
487
            }
488
489
            // Reformat data array in multipart way if it contains a resource
490
            $has_resource = $has_resource || is_resource($item) || $item instanceof Stream;
491
            $multipart[]  = ['name' => $key, 'contents' => $item];
492
        }
493
        unset($item);
494
495
        if ($has_resource) {
496
            return ['multipart' => $multipart];
497
        }
498
499
        return ['form_params' => $data];
500
    }
501
502
    /**
503
     * Magical input media helper to simplify passing media.
504
     *
505
     * This allows the following:
506
     * Request::editMessageMedia([
507
     *     ...
508
     *     'media' => new InputMediaPhoto([
509
     *         'caption' => 'Caption!',
510
     *         'media'   => Request::encodeFile($local_photo),
511
     *     ]),
512
     * ]);
513
     * and
514
     * Request::sendMediaGroup([
515
     *     'media'   => [
516
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_1)]),
517
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_2)]),
518
     *         new InputMediaVideo(['media' => Request::encodeFile($local_video_1)]),
519
     *     ],
520
     * ]);
521
     * and even
522
     * Request::sendMediaGroup([
523
     *     'media'   => [
524
     *         new InputMediaPhoto(['media' => $local_photo_1]),
525
     *         new InputMediaPhoto(['media' => $local_photo_2]),
526
     *         new InputMediaVideo(['media' => $local_video_1]),
527
     *     ],
528
     * ]);
529
     *
530
     * @param mixed $item
531
     * @param bool  $has_resource
532
     * @param array $multipart
533
     *
534
     * @return mixed
535
     * @throws TelegramException
536
     */
537
    private static function mediaInputHelper($item, bool &$has_resource, array &$multipart)
538
    {
539
        $was_array = is_array($item);
540
        $was_array || $item = [$item];
541
542
        /** @var InputMedia|null $media_item */
543
        foreach ($item as $media_item) {
544
            if (!($media_item instanceof InputMedia)) {
545
                continue;
546
            }
547
548
            // Make a list of all possible media that can be handled by the helper.
549
            $possible_medias = array_filter([
550
                '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

550
                'media'     => $media_item->/** @scrutinizer ignore-call */ getMedia(),
Loading history...
551
                '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

551
                'thumbnail' => $media_item->/** @scrutinizer ignore-call */ getThumbnail(),
Loading history...
552
            ]);
553
554
            foreach ($possible_medias as $type => $media) {
555
                // Allow absolute paths to local files.
556
                if (is_string($media) && strpos($media, 'attach://') !== 0 && file_exists($media)) {
557
                    $media = new Stream(self::encodeFile($media));
558
                }
559
560
                if (is_resource($media) || $media instanceof Stream) {
561
                    $has_resource = true;
562
                    $unique_key   = uniqid($type . '_', false);
563
                    $multipart[]  = ['name' => $unique_key, 'contents' => $media];
564
565
                    // We're literally overwriting the passed media type data!
566
                    $media_item->$type           = 'attach://' . $unique_key;
567
                    $media_item->raw_data[$type] = 'attach://' . $unique_key;
568
                }
569
            }
570
        }
571
572
        $was_array || $item = reset($item);
573
574
        return json_encode($item);
575
    }
576
577
    /**
578
     * Get the current action that's being executed
579
     *
580
     * @return string
581
     */
582 7
    public static function getCurrentAction(): string
583
    {
584 7
        return self::$current_action;
585
    }
586
587
    /**
588
     * Execute HTTP Request
589
     *
590
     * @param string $action Action to execute
591
     * @param array  $data   Data to attach to the execution
592
     *
593
     * @return string Result of the HTTP Request
594
     * @throws TelegramException
595
     */
596
    public static function execute(string $action, array $data = []): string
597
    {
598
        $request_params          = self::setUpRequestParams($data);
599
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
600
601
        try {
602
            $response = self::$client->post(
603
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
604
                $request_params
605
            );
606
            $result   = (string) $response->getBody();
607
        } catch (ConnectException $e) {
608
            $response = null;
609
            $result   = $e->getMessage();
610
        } catch (RequestException $e) {
611
            $response = null;
612
            $result   = $e->getResponse() ? (string) $e->getResponse()->getBody() : '';
613
        }
614
615
        //Logging verbose debug output
616
        if (TelegramLog::$always_log_request_and_response || $response === null) {
617
            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

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

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

990
                    $requests = array_map('intval', /** @scrutinizer ignore-type */ $requests);
Loading history...
991
992
                    $chat_per_second   = ($requests['LIMIT_PER_SEC'] === 0);    // No more than one message per second inside a particular chat
993
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30); // No more than 30 messages per second to different chats
994
                    $groups_per_minute = (((is_numeric($chat_id) && $chat_id > 0) || $inline_message_id !== null) || ((!is_numeric($chat_id) || $chat_id < 0) && $requests['LIMIT_PER_MINUTE'] < 20));    // No more than 20 messages per minute in groups and channels
995
996
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
997
                        break;
998
                    }
999
1000
                    $timeout--;
1001
                    usleep((int) (self::$limiter_interval * 1000000));
1002
                }
1003
1004
                DB::insertTelegramRequest($action, $data);
1005
            }
1006
        }
1007
    }
1008
1009
    /**
1010
     * 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.
1011
     *
1012
     * @deprecated
1013
     * @see Request::banChatMember()
1014
     *
1015
     * @param array $data
1016
     *
1017
     * @return ServerResponse
1018
     */
1019
    public static function kickChatMember(array $data = []): ServerResponse
1020
    {
1021
        return static::banChatMember($data);
1022
    }
1023
}
1024