Issues (50)

src/Entities/Message.php (1 issue)

Labels
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\Entities;
13
14
use Longman\TelegramBot\Entities\Games\Game;
15
use Longman\TelegramBot\Entities\Giveaway\Giveaway;
16
use Longman\TelegramBot\Entities\Giveaway\GiveawayCompleted;
17
use Longman\TelegramBot\Entities\Giveaway\GiveawayCreated;
18
use Longman\TelegramBot\Entities\Giveaway\GiveawayWinners;
19
use Longman\TelegramBot\Entities\Message\Factory as MaybeInaccessibleMessageFactory;
20
use Longman\TelegramBot\Entities\Message\MaybeInaccessibleMessage;
21
use Longman\TelegramBot\Entities\MessageOrigin\Factory as MessageOriginFactory;
22
use Longman\TelegramBot\Entities\MessageOrigin\MessageOrigin;
23
use Longman\TelegramBot\Entities\Payments\Invoice;
24
use Longman\TelegramBot\Entities\Payments\SuccessfulPayment;
25
use Longman\TelegramBot\Entities\TelegramPassport\PassportData;
26
use Longman\TelegramBot\Entities\Topics\ForumTopicClosed;
27
use Longman\TelegramBot\Entities\Topics\ForumTopicCreated;
28
use Longman\TelegramBot\Entities\Topics\ForumTopicEdited;
29
use Longman\TelegramBot\Entities\Topics\ForumTopicReopened;
30
use Longman\TelegramBot\Entities\Topics\GeneralForumTopicHidden;
31
use Longman\TelegramBot\Entities\Topics\GeneralForumTopicUnhidden;
32
33
/**
34
 * Class Message
35
 *
36
 * Represents a message
37
 *
38
 * @link https://core.telegram.org/bots/api#message
39
 *
40
 * @method int                                    getMessageId()                              Unique message identifier
41
 * @method int                                    getMessageThreadId()                        Optional. Unique identifier of a message thread to which the message belongs; for supergroups only
42
 * @method User                                   getFrom()                                   Optional. Sender, can be empty for messages sent to channels
43
 * @method Chat                                   getSenderChat()                             Optional. Sender of the message, sent on behalf of a chat. The channel itself for channel messages. The supergroup itself for messages from anonymous group administrators. The linked channel for messages automatically forwarded to the discussion group
44
 * @method int                                    getSenderBoostCount()                       Optional. If the sender of the message boosted the chat, the number of boosts added by the user
45
 * @method int                                    getDate()                                   Date the message was sent in Unix time
46
 * @method Chat                                   getChat()                                   Conversation the message belongs to
47
 * @method MessageOrigin                          getForwardOrigin()                          Optional. Information about the original message for forwarded messages
48
 * @method bool                                   getIsTopicMessage()                         Optional. True, if the message is sent to a forum topic
49
 * @method bool                                   getIsAutomaticForward()                     Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
50
 * @method ReplyToMessage                         getReplyToMessage()                         Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
51
 * @method ExternalReplyInfo                      getExternalReply()                          Optional. Information about the message that is being replied to, which may come from another chat or forum topic
52
 * @method TextQuote                              getQuote()                                  Optional. For replies that quote part of the original message, the quoted part of the message
53
 * @method Story                                  getReplyToStory()                           Optional. For replies to a story, the original story
54
 * @method User                                   getViaBot()                                 Optional. Bot through which the message was sent
55
 * @method int                                    getEditDate()                               Optional. Date the message was last edited in Unix time
56
 * @method bool                                   getHasProtectedContent()                    Optional. True, if the message can't be forwarded
57
 * @method string                                 getMediaGroupId()                           Optional. The unique identifier of a media message group this message belongs to
58
 * @method string                                 getAuthorSignature()                        Optional. Signature of the post author for messages in channels
59
 * @method LinkPreviewOptions                     getLinkPreviewOptions()                     Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed
60
 * @method MessageEntity[]                        getEntities()                               Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
61
 * @method MessageEntity[]                        getCaptionEntities()                        Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
62
 * @method Audio                                  getAudio()                                  Optional. Message is an audio file, information about the file
63
 * @method Document                               getDocument()                               Optional. Message is a general file, information about the file
64
 * @method Animation                              getAnimation()                              Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set
65
 * @method Game                                   getGame()                                   Optional. Message is a game, information about the game.
66
 * @method PhotoSize[]                            getPhoto()                                  Optional. Message is a photo, available sizes of the photo
67
 * @method Sticker                                getSticker()                                Optional. Message is a sticker, information about the sticker
68
 * @method Story                                  getStory()                                  Optional. Message is a forwarded story
69
 * @method Video                                  getVideo()                                  Optional. Message is a video, information about the video
70
 * @method Voice                                  getVoice()                                  Optional. Message is a voice message, information about the file
71
 * @method VideoNote                              getVideoNote()                              Optional. Message is a video note message, information about the video
72
 * @method string                                 getCaption()                                Optional. Caption for the document, photo or video, 0-200 characters
73
 * @method bool                                   getHasMediaSpoiler()                        Optional. True, if the message media is covered by a spoiler animation
74
 * @method Contact                                getContact()                                Optional. Message is a shared contact, information about the contact
75
 * @method Location                               getLocation()                               Optional. Message is a shared location, information about the location
76
 * @method Venue                                  getVenue()                                  Optional. Message is a venue, information about the venue
77
 * @method Poll                                   getPoll()                                   Optional. Message is a native poll, information about the poll
78
 * @method Dice                                   getDice()                                   Optional. Message is a dice with random value, 1-6 for “🎲” and “🎯” base emoji, 1-5 for “🏀” and “⚽” base emoji, 1-64 for “🎰” base emoji
79
 * @method User[]                                 getNewChatMembers()                         Optional. A new member(s) was added to the group, information about them (one of this members may be the bot itself)
80
 * @method User                                   getLeftChatMember()                         Optional. A member was removed from the group, information about them (this member may be the bot itself)
81
 * @method string                                 getNewChatTitle()                           Optional. A chat title was changed to this value
82
 * @method PhotoSize[]                            getNewChatPhoto()                           Optional. A chat photo was changed to this value
83
 * @method MessageAutoDeleteTimerChanged          getMessageAutoDeleteTimerChanged()          Optional. Service message: auto-delete timer settings changed in the chat
84
 * @method bool                                   getDeleteChatPhoto()                        Optional. Service message: the chat photo was deleted
85
 * @method bool                                   getGroupChatCreated()                       Optional. Service message: the group has been created
86
 * @method bool                                   getSupergroupChatCreated()                  Optional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.
87
 * @method bool                                   getChannelChatCreated()                     Optional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.
88
 * @method int                                    getMigrateToChatId()                        Optional. The group has been migrated to a supergroup with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
89
 * @method int                                    getMigrateFromChatId()                      Optional. The supergroup has been migrated from a group with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
90
 * @method MaybeInaccessibleMessage               getPinnedMessage()                          Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
91
 * @method Invoice                                getInvoice()                                Optional. Message is an invoice for a payment, information about the invoice.
92
 * @method SuccessfulPayment                      getSuccessfulPayment()                      Optional. Message is a service message about a successful payment, information about the payment.
93
 * @method UsersShared                            getUsersShared()                            Optional. Service message: users were shared with the bot
94
 * @method ChatShared                             getChatShared()                             Optional. Service message: a chat was shared with the bot
95
 * @method string                                 getConnectedWebsite()                       Optional. The domain name of the website on which the user has logged in.
96
 * @method WriteAccessAllowed                     getWriteAccessAllowed()                     Optional. Service message: the user allowed the bot added to the attachment menu to write messages
97
 * @method PassportData                           getPassportData()                           Optional. Telegram Passport data
98
 * @method ProximityAlertTriggered                getProximityAlertTriggered()                Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.
99
 * @method ChatBoostAdded                         getBoostAdded()                             Optional. Service message: user boosted the chat
100
 * @method ForumTopicCreated                      getForumTopicCreated()                      Optional. Service message: forum topic created
101
 * @method ForumTopicEdited                       getForumTopicEdited()                       Optional. Service message: forum topic edited
102
 * @method ForumTopicClosed                       getForumTopicClosed()                       Optional. Service message: forum topic closed
103
 * @method ForumTopicReopened                     getForumTopicReopened()                     Optional. Service message: forum topic reopened
104
 * @method GeneralForumTopicHidden                getGeneralForumTopicHidden()                Optional. Service message: the 'General' forum topic hidden
105
 * @method GeneralForumTopicUnhidden              getGeneralForumTopicUnhidden()              Optional. Service message: the 'General' forum topic unhidden
106
 * @method GiveawayCreated                        getGiveawayCreated()                        Optional. Service message: a scheduled giveaway was created
107
 * @method Giveaway                               getGiveaway()                               Optional. The message is a scheduled giveaway message
108
 * @method GiveawayWinners                        getGiveawayWinners()                        Optional. A giveaway with public winners was completed
109 11
 * @method GiveawayCompleted                      getGiveawayCompleted()                      Optional. Service message: a giveaway without public winners was completed
110
 * @method VideoChatScheduled                     getVideoChatScheduled()                     Optional. Service message: voice chat scheduled
111 11
 * @method VideoChatStarted                       getVideoChatStarted()                       Optional. Service message: voice chat started
112 11
 * @method VideoChatEnded                         getVideoChatEnded()                         Optional. Service message: voice chat ended
113 11
 * @method VideoChatParticipantsInvited           getVideoChatParticipantsInvited()           Optional. Service message: new participants invited to a voice chat
114 11
 * @method WebAppData                             getWebAppData()                             Optional. Service message: data sent by a Web App
115 11
 * @method InlineKeyboard                         getReplyMarkup()                            Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
116 11
 */
117 11
class Message extends Entity implements MaybeInaccessibleMessage
118 11
{
119 11
    /**
120 11
     * {@inheritdoc}
121 11
     */
122 11
    protected function subEntities(): array
123 11
    {
124 11
        return [
125 11
            'from'                              => User::class,
126 11
            'sender_chat'                       => Chat::class,
127 11
            'chat'                              => Chat::class,
128 11
            'forward_origin'                    => MessageOriginFactory::class,
129 11
            'reply_to_message'                  => ReplyToMessage::class,
130 11
            'external_reply'                    => ExternalReplyInfo::class,
131 11
            'quote'                             => TextQuote::class,
132 11
            'reply_to_story'                    => Story::class,
133 11
            'via_bot'                           => User::class,
134 11
            'link_preview_options'              => LinkPreviewOptions::class,
135 11
            'entities'                          => [MessageEntity::class],
136 11
            'animation'                         => Animation::class,
137 11
            'audio'                             => Audio::class,
138 11
            'document'                          => Document::class,
139 11
            'photo'                             => [PhotoSize::class],
140 11
            'sticker'                           => Sticker::class,
141 11
            'story'                             => Story::class,
142 11
            'video'                             => Video::class,
143 11
            'video_note'                        => VideoNote::class,
144 11
            'voice'                             => Voice::class,
145 11
            'caption_entities'                  => [MessageEntity::class],
146 11
            'contact'                           => Contact::class,
147 11
            'dice'                              => Dice::class,
148 11
            'game'                              => Game::class,
149 11
            'poll'                              => Poll::class,
150 11
            'venue'                             => Venue::class,
151 11
            'location'                          => Location::class,
152 11
            'new_chat_members'                  => [User::class],
153 11
            'left_chat_member'                  => User::class,
154 11
            'new_chat_photo'                    => [PhotoSize::class],
155 11
            'message_auto_delete_timer_changed' => MessageAutoDeleteTimerChanged::class,
156 11
            'pinned_message'                    => MaybeInaccessibleMessageFactory::class,
157 11
            'invoice'                           => Invoice::class,
158 11
            'successful_payment'                => SuccessfulPayment::class,
159 11
            'users_shared'                      => UsersShared::class,
160 11
            'chat_shared'                       => ChatShared::class,
161
            'write_access_allowed'              => WriteAccessAllowed::class,
162
            'passport_data'                     => PassportData::class,
163
            'proximity_alert_triggered'         => ProximityAlertTriggered::class,
164
            'boost_added'                       => ChatBoostAdded::class,
165
            'forum_topic_created'               => ForumTopicCreated::class,
166
            'forum_topic_edited'                => ForumTopicEdited::class,
167
            'forum_topic_closed'                => ForumTopicClosed::class,
168 2
            'forum_topic_reopened'              => ForumTopicReopened::class,
169
            'general_forum_topic_hidden'        => GeneralForumTopicHidden::class,
170 2
            'general_forum_topic_unhidden'      => GeneralForumTopicUnhidden::class,
171 2
            'giveaway_created'                  => GiveawayCreated::class,
172 2
            'giveaway'                          => Giveaway::class,
173
            'giveaway_winners'                  => GiveawayWinners::class,
174
            'giveaway_completed'                => GiveawayCompleted::class,
175 2
            'video_chat_scheduled'              => VideoChatScheduled::class,
176 2
            'video_chat_started'                => VideoChatStarted::class,
177
            'video_chat_ended'                  => VideoChatEnded::class,
178
            'video_chat_participants_invited'   => VideoChatParticipantsInvited::class,
179 2
            'web_app_data'                      => WebAppData::class,
180
            'reply_markup'                      => InlineKeyboard::class,
181
        ];
182
    }
183
184
    /**
185
     * return the entire command like /echo or /echo@bot1 if specified
186
     *
187 2
     * @return string|null
188
     */
189 2
    public function getFullCommand(): ?string
190
    {
191
        $text = $this->getProperty('text') ?? '';
192
        if (strpos($text, '/') !== 0) {
193 2
            return null;
194 2
        }
195 2
196
        $no_EOL   = strtok($text, PHP_EOL);
197 2
        $no_space = strtok($text, ' ');
198
199
        //try to understand which separator \n or space divide /command from text
200 2
        return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
201 2
    }
202
203 2
    /**
204
     * Get command
205
     *
206 1
     * @return string|null
207
     */
208 1
    public function getCommand(): ?string
209
    {
210
        if ($command = $this->getProperty('command')) {
211
            return $command;
212
        }
213
214
        $full_command = $this->getFullCommand() ?? '';
215
        if (strpos($full_command, '/') !== 0) {
216
            return null;
217
        }
218
        $full_command = substr($full_command, 1);
219
220
        //check if command is followed by bot username
221 9
        $split_cmd = explode('@', $full_command);
222
        if (!isset($split_cmd[1])) {
223 9
            //command is not followed by name
224
            return $full_command;
225 9
        }
226 1
227 1
        if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
228
            //command is addressed to me
229
            return $split_cmd[0];
230 1
        }
231
232
        return null;
233 9
    }
234
235
    /**
236
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
237
     *
238
     * @param bool $without_cmd
239
     *
240
     * @return string|null
241
     */
242
    public function getText($without_cmd = false): ?string
243
    {
244
        $text = $this->getProperty('text');
245
246
        if ($without_cmd && $command = $this->getFullCommand()) {
247
            if (strlen($command) + 1 < strlen($text)) {
248
                return substr($text, strlen($command) + 1);
249
            }
250
251
            return '';
252
        }
253
254
        return $text;
255
    }
256
257 1
    /**
258
     * Bot added in chat
259 1
     *
260 1
     * @return bool
261 1
     */
262 1
    public function botAddedInChat(): bool
263 1
    {
264 1
        foreach ($this->getNewChatMembers() as $member) {
0 ignored issues
show
The method getNewChatMembers() does not exist on Longman\TelegramBot\Entities\Message. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

264
        foreach ($this->/** @scrutinizer ignore-call */ getNewChatMembers() as $member) {
Loading history...
265 1
            if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) {
266 1
                return true;
267 1
            }
268 1
        }
269 1
270 1
        return false;
271 1
    }
272 1
273 1
    /**
274 1
     * Detect type based on properties.
275 1
     *
276 1
     * @return string
277 1
     */
278 1
    public function getType(): string
279 1
    {
280 1
        $types = [
281 1
            'text',
282 1
            'animation',
283 1
            'audio',
284 1
            'document',
285 1
            'photo',
286 1
            'sticker',
287 1
            'video',
288 1
            'video_note',
289 1
            'voice',
290 1
            'contact',
291 1
            'dice',
292 1
            'game',
293 1
            'poll',
294 1
            'venue',
295 1
            'location',
296 1
            'new_chat_members',
297 1
            'left_chat_member',
298 1
            'new_chat_title',
299 1
            'new_chat_photo',
300 1
            'delete_chat_photo',
301 1
            'group_chat_created',
302 1
            'supergroup_chat_created',
303 1
            'channel_chat_created',
304 1
            'message_auto_delete_timer_changed',
305 1
            'migrate_to_chat_id',
306 1
            'migrate_from_chat_id',
307
            'pinned_message',
308 1
            'invoice',
309 1
            'successful_payment',
310 1
            'users_shared',
311 1
            'chat_shared',
312 1
            'write_access_allowed',
313
            'passport_data',
314
            'proximity_alert_triggered',
315 1
            'boost_added',
316
            'forum_topic_created',
317
            'forum_topic_edited',
318
            'forum_topic_closed',
319 1
            'forum_topic_reopened',
320
            'general_forum_topic_hidden',
321
            'general_forum_topic_unhidden',
322
            'video_chat_scheduled',
323
            'video_chat_started',
324
            'video_chat_ended',
325
            'video_chat_participants_invited',
326
            'web_app_data',
327
            'reply_markup',
328
        ];
329
330
        $is_command = $this->getCommand() !== null;
331
        foreach ($types as $type) {
332
            if ($this->getProperty($type) !== null) {
333
                if ($is_command && $type === 'text') {
334
                    return 'command';
335
                }
336
337
                return $type;
338
            }
339
        }
340
341
        return 'message';
342
    }
343
}
344