Issues (50)

src/Request.php (2 issues)

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

560
                'media'     => $media_item->/** @scrutinizer ignore-call */ getMedia(),
Loading history...
561
                'thumbnail' => $media_item->getThumbnail(),
0 ignored issues
show
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

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