Issues (36)

src/Entities/Message.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\Entities;
13
14
use Longman\TelegramBot\Entities\Games\Game;
15
use Longman\TelegramBot\Entities\Payments\Invoice;
16
use Longman\TelegramBot\Entities\Payments\SuccessfulPayment;
17
use Longman\TelegramBot\Entities\TelegramPassport\PassportData;
18
use Longman\TelegramBot\Entities\Topics\ForumTopicClosed;
19
use Longman\TelegramBot\Entities\Topics\ForumTopicCreated;
20
use Longman\TelegramBot\Entities\Topics\ForumTopicEdited;
21
use Longman\TelegramBot\Entities\Topics\ForumTopicReopened;
22
use Longman\TelegramBot\Entities\Topics\GeneralForumTopicHidden;
23
use Longman\TelegramBot\Entities\Topics\GeneralForumTopicUnhidden;
24
25
/**
26
 * Class Message
27
 *
28
 * Represents a message
29
 *
30
 * @link https://core.telegram.org/bots/api#message
31
 *
32
 * @method int                                    getMessageId()                              Unique message identifier
33
 * @method int                                    getMessageThreadId()                        Optional. Unique identifier of a message thread to which the message belongs; for supergroups only
34
 * @method User                                   getFrom()                                   Optional. Sender, can be empty for messages sent to channels
35
 * @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
36
 * @method int                                    getDate()                                   Date the message was sent in Unix time
37
 * @method Chat                                   getChat()                                   Conversation the message belongs to
38
 * @method User                                   getForwardFrom()                            Optional. For forwarded messages, sender of the original message
39
 * @method Chat                                   getForwardFromChat()                        Optional. For messages forwarded from a channel, information about the original channel
40
 * @method int                                    getForwardFromMessageId()                   Optional. For forwarded channel posts, identifier of the original message in the channel
41
 * @method string                                 getForwardSignature()                       Optional. For messages forwarded from channels, signature of the post author if present
42
 * @method string                                 getForwardSenderName()                      Optional. Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages
43
 * @method int                                    getForwardDate()                            Optional. For forwarded messages, date the original message was sent in Unix time
44
 * @method bool                                   getIsTopicMessage()                         Optional. True, if the message is sent to a forum topic
45
 * @method bool                                   getIsAutomaticForward()                     Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
46
 * @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.
47
 * @method User                                   getViaBot()                                 Optional. Bot through which the message was sent
48
 * @method int                                    getEditDate()                               Optional. Date the message was last edited in Unix time
49
 * @method bool                                   getHasProtectedContent()                    Optional. True, if the message can't be forwarded
50
 * @method string                                 getMediaGroupId()                           Optional. The unique identifier of a media message group this message belongs to
51
 * @method string                                 getAuthorSignature()                        Optional. Signature of the post author for messages in channels
52
 * @method MessageEntity[]                        getEntities()                               Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
53
 * @method MessageEntity[]                        getCaptionEntities()                        Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
54
 * @method Audio                                  getAudio()                                  Optional. Message is an audio file, information about the file
55
 * @method Document                               getDocument()                               Optional. Message is a general file, information about the file
56
 * @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
57
 * @method Game                                   getGame()                                   Optional. Message is a game, information about the game.
58
 * @method PhotoSize[]                            getPhoto()                                  Optional. Message is a photo, available sizes of the photo
59
 * @method Sticker                                getSticker()                                Optional. Message is a sticker, information about the sticker
60
 * @method Story                                  getStory()                                  Optional. Message is a forwarded story
61
 * @method Video                                  getVideo()                                  Optional. Message is a video, information about the video
62
 * @method Voice                                  getVoice()                                  Optional. Message is a voice message, information about the file
63
 * @method VideoNote                              getVideoNote()                              Optional. Message is a video note message, information about the video
64
 * @method string                                 getCaption()                                Optional. Caption for the document, photo or video, 0-200 characters
65
 * @method bool                                   getHasMediaSpoiler()                        Optional. True, if the message media is covered by a spoiler animation
66
 * @method Contact                                getContact()                                Optional. Message is a shared contact, information about the contact
67
 * @method Location                               getLocation()                               Optional. Message is a shared location, information about the location
68
 * @method Venue                                  getVenue()                                  Optional. Message is a venue, information about the venue
69
 * @method Poll                                   getPoll()                                   Optional. Message is a native poll, information about the poll
70
 * @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
71
 * @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)
72
 * @method User                                   getLeftChatMember()                         Optional. A member was removed from the group, information about them (this member may be the bot itself)
73
 * @method string                                 getNewChatTitle()                           Optional. A chat title was changed to this value
74
 * @method PhotoSize[]                            getNewChatPhoto()                           Optional. A chat photo was changed to this value
75
 * @method MessageAutoDeleteTimerChanged          getMessageAutoDeleteTimerChanged()          Optional. Service message: auto-delete timer settings changed in the chat
76
 * @method bool                                   getDeleteChatPhoto()                        Optional. Service message: the chat photo was deleted
77
 * @method bool                                   getGroupChatCreated()                       Optional. Service message: the group has been created
78
 * @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.
79
 * @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.
80
 * @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.
81
 * @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.
82
 * @method Message                                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.
83
 * @method Invoice                                getInvoice()                                Optional. Message is an invoice for a payment, information about the invoice.
84
 * @method SuccessfulPayment                      getSuccessfulPayment()                      Optional. Message is a service message about a successful payment, information about the payment.
85
 * @method UserShared                             getUserShared()                             Optional. Service message: a user was shared with the bot
86
 * @method ChatShared                             getChatShared()                             Optional. Service message: a chat was shared with the bot
87
 * @method string                                 getConnectedWebsite()                       Optional. The domain name of the website on which the user has logged in.
88
 * @method WriteAccessAllowed                     getWriteAccessAllowed()                     Optional. Service message: the user allowed the bot added to the attachment menu to write messages
89
 * @method PassportData                           getPassportData()                           Optional. Telegram Passport data
90
 * @method ProximityAlertTriggered                getProximityAlertTriggered()                Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.
91
 * @method ForumTopicCreated                      getForumTopicCreated()                      Optional. Service message: forum topic created
92
 * @method ForumTopicEdited                       getForumTopicEdited()                       Optional. Service message: forum topic edited
93
 * @method ForumTopicClosed                       getForumTopicClosed()                       Optional. Service message: forum topic closed
94
 * @method ForumTopicReopened                     getForumTopicReopened()                     Optional. Service message: forum topic reopened
95
 * @method GeneralForumTopicHidden                getGeneralForumTopicHidden()                Optional. Service message: the 'General' forum topic hidden
96
 * @method GeneralForumTopicUnhidden              getGeneralForumTopicUnhidden()              Optional. Service message: the 'General' forum topic unhidden
97
 * @method VideoChatScheduled                     getVideoChatScheduled()                     Optional. Service message: voice chat scheduled
98
 * @method VideoChatStarted                       getVideoChatStarted()                       Optional. Service message: voice chat started
99
 * @method VideoChatEnded                         getVideoChatEnded()                         Optional. Service message: voice chat ended
100
 * @method VideoChatParticipantsInvited           getVideoChatParticipantsInvited()           Optional. Service message: new participants invited to a voice chat
101
 * @method WebAppData                             getWebAppData()                             Optional. Service message: data sent by a Web App
102
 * @method InlineKeyboard                         getReplyMarkup()                            Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
103
 */
104
class Message extends Entity
105
{
106
    /**
107
     * {@inheritdoc}
108
     */
109 11
    protected function subEntities(): array
110
    {
111 11
        return [
112 11
            'from'                              => User::class,
113 11
            'sender_chat'                       => Chat::class,
114 11
            'chat'                              => Chat::class,
115 11
            'forward_from'                      => User::class,
116 11
            'forward_from_chat'                 => Chat::class,
117 11
            'reply_to_message'                  => ReplyToMessage::class,
118 11
            'via_bot'                           => User::class,
119 11
            'entities'                          => [MessageEntity::class],
120 11
            'animation'                         => Animation::class,
121 11
            'audio'                             => Audio::class,
122 11
            'document'                          => Document::class,
123 11
            'photo'                             => [PhotoSize::class],
124 11
            'sticker'                           => Sticker::class,
125 11
            'story'                             => Story::class,
126 11
            'video'                             => Video::class,
127 11
            'video_note'                        => VideoNote::class,
128 11
            'voice'                             => Voice::class,
129 11
            'caption_entities'                  => [MessageEntity::class],
130 11
            'contact'                           => Contact::class,
131 11
            'dice'                              => Dice::class,
132 11
            'game'                              => Game::class,
133 11
            'poll'                              => Poll::class,
134 11
            'venue'                             => Venue::class,
135 11
            'location'                          => Location::class,
136 11
            'new_chat_members'                  => [User::class],
137 11
            'left_chat_member'                  => User::class,
138 11
            'new_chat_photo'                    => [PhotoSize::class],
139 11
            'message_auto_delete_timer_changed' => MessageAutoDeleteTimerChanged::class,
140 11
            'pinned_message'                    => __CLASS__,
141 11
            'invoice'                           => Invoice::class,
142 11
            'successful_payment'                => SuccessfulPayment::class,
143 11
            'user_shared'                       => UserShared::class,
144 11
            'chat_shared'                       => ChatShared::class,
145 11
            'write_access_allowed'              => WriteAccessAllowed::class,
146 11
            'passport_data'                     => PassportData::class,
147 11
            'proximity_alert_triggered'         => ProximityAlertTriggered::class,
148 11
            'forum_topic_created'               => ForumTopicCreated::class,
149 11
            'forum_topic_edited'                => ForumTopicEdited::class,
150 11
            'forum_topic_closed'                => ForumTopicClosed::class,
151 11
            'forum_topic_reopened'              => ForumTopicReopened::class,
152 11
            'general_forum_topic_hidden'        => GeneralForumTopicHidden::class,
153 11
            'general_forum_topic_unhidden'      => GeneralForumTopicUnhidden::class,
154 11
            'video_chat_scheduled'              => VideoChatScheduled::class,
155 11
            'video_chat_started'                => VideoChatStarted::class,
156 11
            'video_chat_ended'                  => VideoChatEnded::class,
157 11
            'video_chat_participants_invited'   => VideoChatParticipantsInvited::class,
158 11
            'web_app_data'                      => WebAppData::class,
159 11
            'reply_markup'                      => InlineKeyboard::class,
160 11
        ];
161
    }
162
163
    /**
164
     * return the entire command like /echo or /echo@bot1 if specified
165
     *
166
     * @return string|null
167
     */
168 2
    public function getFullCommand(): ?string
169
    {
170 2
        $text = $this->getProperty('text') ?? '';
171 2
        if (strpos($text, '/') !== 0) {
172 2
            return null;
173
        }
174
175 2
        $no_EOL = strtok($text, PHP_EOL);
176 2
        $no_space = strtok($text, ' ');
177
178
        //try to understand which separator \n or space divide /command from text
179 2
        return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
180
    }
181
182
    /**
183
     * Get command
184
     *
185
     * @return string|null
186
     */
187 2
    public function getCommand(): ?string
188
    {
189 2
        if ($command = $this->getProperty('command')) {
190
            return $command;
191
        }
192
193 2
        $full_command = $this->getFullCommand() ?? '';
194 2
        if (strpos($full_command, '/') !== 0) {
195 2
            return null;
196
        }
197 2
        $full_command = substr($full_command, 1);
198
199
        //check if command is followed by bot username
200 2
        $split_cmd = explode('@', $full_command);
201 2
        if (! isset($split_cmd[1])) {
202
            //command is not followed by name
203 2
            return $full_command;
204
        }
205
206 1
        if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
207
            //command is addressed to me
208 1
            return $split_cmd[0];
209
        }
210
211
        return null;
212
    }
213
214
    /**
215
     * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
216
     *
217
     * @param  bool  $without_cmd
218
     *
219
     * @return string|null
220
     */
221 9
    public function getText($without_cmd = false): ?string
222
    {
223 9
        $text = $this->getProperty('text');
224
225 9
        if ($without_cmd && $command = $this->getFullCommand()) {
226 1
            if (strlen($command) + 1 < strlen($text)) {
0 ignored issues
show
It seems like $text can also be of type null; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

226
            if (strlen($command) + 1 < strlen(/** @scrutinizer ignore-type */ $text)) {
Loading history...
227 1
                return substr($text, strlen($command) + 1);
0 ignored issues
show
It seems like $text can also be of type null; however, parameter $string of substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

227
                return substr(/** @scrutinizer ignore-type */ $text, strlen($command) + 1);
Loading history...
228
            }
229
230 1
            return '';
231
        }
232
233 9
        return $text;
234
    }
235
236
    /**
237
     * Bot added in chat
238
     *
239
     * @return bool
240
     */
241
    public function botAddedInChat(): bool
242
    {
243
        foreach ($this->getNewChatMembers() as $member) {
244
            if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) {
245
                return true;
246
            }
247
        }
248
249
        return false;
250
    }
251
252
    /**
253
     * Detect type based on properties.
254
     *
255
     * @return string
256
     */
257 1
    public function getType(): string
258
    {
259 1
        $types = [
260 1
            'text',
261 1
            'animation',
262 1
            'audio',
263 1
            'document',
264 1
            'photo',
265 1
            'sticker',
266 1
            'video',
267 1
            'video_note',
268 1
            'voice',
269 1
            'contact',
270 1
            'dice',
271 1
            'game',
272 1
            'poll',
273 1
            'venue',
274 1
            'location',
275 1
            'new_chat_members',
276 1
            'left_chat_member',
277 1
            'new_chat_title',
278 1
            'new_chat_photo',
279 1
            'delete_chat_photo',
280 1
            'group_chat_created',
281 1
            'supergroup_chat_created',
282 1
            'channel_chat_created',
283 1
            'message_auto_delete_timer_changed',
284 1
            'migrate_to_chat_id',
285 1
            'migrate_from_chat_id',
286 1
            'pinned_message',
287 1
            'invoice',
288 1
            'successful_payment',
289 1
            'user_shared',
290 1
            'chat_shared',
291 1
            'write_access_allowed',
292 1
            'passport_data',
293 1
            'proximity_alert_triggered',
294 1
            'forum_topic_created',
295 1
            'forum_topic_edited',
296 1
            'forum_topic_closed',
297 1
            'forum_topic_reopened',
298 1
            'general_forum_topic_hidden',
299 1
            'general_forum_topic_unhidden',
300 1
            'video_chat_scheduled',
301 1
            'video_chat_started',
302 1
            'video_chat_ended',
303 1
            'video_chat_participants_invited',
304 1
            'web_app_data',
305 1
            'reply_markup',
306 1
        ];
307
308 1
        $is_command = $this->getCommand() !== null;
309 1
        foreach ($types as $type) {
310 1
            if ($this->getProperty($type) !== null) {
311 1
                if ($is_command && $type === 'text') {
312 1
                    return 'command';
313
                }
314
315 1
                return $type;
316
            }
317
        }
318
319 1
        return 'message';
320
    }
321
}
322