diff --git a/.editorconfig b/.editorconfig
deleted file mode 100644
index d84f8aa61..000000000
--- a/.editorconfig
+++ /dev/null
@@ -1,12 +0,0 @@
-root = true
-
-[*]
-end_of_line = lf
-insert_final_newline = true
-charset = utf-8
-indent_style = space
-indent_size = 4
-trim_trailing_whitespace = true
-
-[*.{yml, yaml}]
-indent_size = 2
diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index 74350b724..000000000
--- a/.gitattributes
+++ /dev/null
@@ -1,5 +0,0 @@
-/.* export-ignore
-/composer.lock export-ignore
-/phpcs.xml.dist export-ignore
-/phpunit.xml.dist export-ignore
-/tests export-ignore
diff --git a/.github/ISSUE_TEMPLATE/BC_Break.md b/.github/ISSUE_TEMPLATE/BC_Break.md
deleted file mode 100644
index 01457d033..000000000
--- a/.github/ISSUE_TEMPLATE/BC_Break.md
+++ /dev/null
@@ -1,56 +0,0 @@
----
-name: 💥 BC Break
-about: Have you encountered an issue during an upgrade? 💣
-labels: bc break
----
-
-
-
-### 💥 BC Break Report
-
-<--
-❗ NEVER put your Telegram API key or any other private details here. (like passwords, user IDs, etc.)
-Substitute them like
+ A Telegram Bot based on the official Telegram Bot API
+
- PHP Telegram Bot
-
-A Telegram Bot based on the official [Telegram Bot API]
-
-[](https://core.telegram.org/bots/api-changelog#september-22-2023)
-[](https://telegram.me/PHP_Telegram_Bot_Support)
-[](#donate)
-
-[](https://github.com/php-telegram-bot/core/actions/workflows/tests.yaml)
-[](https://scrutinizer-ci.com/g/php-telegram-bot/core/?b=master)
-[](https://scrutinizer-ci.com/g/php-telegram-bot/core/?b=master)
-[](https://packagist.org/packages/longman/telegram-bot)
-[][Tidelift]
-[](https://packagist.org/packages/longman/telegram-bot)
-[](https://packagist.org/packages/longman/telegram-bot)
-[](https://php.net/)
-[](https://github.com/php-telegram-bot/core/LICENSE)
-
-## Table of Contents
-- [Introduction](#introduction)
-- [Instructions](#instructions)
- - [Create your first bot](#create-your-first-bot)
- - [Require this package with Composer](#require-this-package-with-composer)
- - [Choose how to retrieve Telegram updates](#choose-how-to-retrieve-telegram-updates)
-- [Using a custom Bot API server](#using-a-custom-bot-api-server)
-- [Webhook installation](#webhook-installation)
- - [Self Signed Certificate](#self-signed-certificate)
- - [Unset Webhook](#unset-webhook)
-- [getUpdates installation](#getupdates-installation)
- - [getUpdates without database](#getupdates-without-database)
-- [Filter Update](#filter-update)
-- [Support](#support)
- - [Types](#types)
- - [Inline Query](#inline-query)
- - [Methods](#methods)
- - [Send Message](#send-message)
- - [Send Photo](#send-photo)
- - [Send Chat Action](#send-chat-action)
- - [getUserProfilePhoto](#getuserprofilephoto)
- - [getFile and downloadFile](#getfile-and-downloadfile)
- - [Send message to all active chats](#send-message-to-all-active-chats)
-- [Utils](#utils)
- - [MySQL storage (Recommended)](#mysql-storage-recommended)
- - [External Database connection](#external-database-connection)
- - [Channels Support](#channels-support)
-- [Commands](#commands)
- - [Predefined Commands](#predefined-commands)
- - [Custom Commands](#custom-commands)
- - [Commands Configuration](#commands-configuration)
- - [Admin Commands](#admin-commands)
- - [Set Admins](#set-admins)
- - [Channel Administration](#channel-administration)
-- [Upload and Download directory path](#upload-and-download-directory-path)
-- [Logging](doc/01-utils.md)
-- [Documentation](#documentation)
-- [Assets](#assets)
-- [Example bot](#example-bot)
-- [Projects with this library](#projects-with-this-library)
-- [Troubleshooting](#troubleshooting)
-- [Contributing](#contributing)
-- [Security](#security)
-- [Donate](#donate)
-- [For enterprise](#for-enterprise)
-- [License](#license)
-- [Credits](#credits)
-
-## Introduction
-
-This is a pure PHP Telegram Bot, fully extensible via plugins.
-
-Telegram announced official support for a [Bot API](https://telegram.org/blog/bot-revolution), allowing integrators of all sorts to bring automated interactions to the mobile platform.
-This Bot aims to provide a platform where one can simply write a bot and have interactions in a matter of minutes.
-
-The Bot can:
-- Retrieve updates with [webhook](#webhook-installation) and [getUpdates](#getupdates-installation) methods.
-- Supports all types and methods according to Telegram Bot API 6.9 (September 2023).
-- Supports supergroups.
-- Handle commands in chat with other bots.
-- Manage Channel from the bot admin interface.
-- Full support for **inline bots**.
-- Inline keyboard.
-- Messages, InlineQuery and ChosenInlineQuery are stored in the Database.
-- Conversation feature.
-
----
-
-This code is available on [GitHub](https://github.com/php-telegram-bot/core). Pull requests are welcome.
-
-## Instructions
-
-### Create your first bot
-
-1. Message [`@BotFather`](https://telegram.me/BotFather) with the following text: `/newbot`
-
- If you don't know how to message by username, click the search field on your Telegram app and type `@BotFather`, where you should be able to initiate a conversation. Be careful not to send it to the wrong contact, because some users have similar usernames to `BotFather`.
-
- 
-
-2. `@BotFather` replies with:
-
- ```
- Alright, a new bot. How are we going to call it? Please choose a name for your bot.
- ```
-
-3. Type whatever name you want for your bot.
-
-4. `@BotFather` replies with:
-
- ```
- Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
- ```
-
-5. Type whatever username you want for your bot, minimum 5 characters, and must end with `bot`. For example: `telesample_bot`
-
-6. `@BotFather` replies with:
-
- ```
- Done! Congratulations on your new bot. You will find it at
- telegram.me/telesample_bot. You can now add a description, about
- section and profile picture for your bot, see /help for a list of
- commands.
+
+
- Use this token to access the HTTP API:
- 123456789:AAG90e14-0f8-40183D-18491dDE
- For a description of the Bot API, see this page:
- https://core.telegram.org/bots/api
- ```
-7. Note down the 'token' mentioned above.
+
+[![Contributors][contributors-shield]][contributors-url]
+[![Forks][forks-shield]][forks-url]
+[![Stargazers][stars-shield]][stars-url]
+[![Issues][issues-shield]][issues-url]
+[![MIT License][license-shield]][license-url]
-*Optionally set the bot privacy:*
-1. Send `/setprivacy` to `@BotFather`.
- 
+
+
-
-
-
-
+
+
-2. `@BotFather` replies with:
+PHP Telegram Bot
- ```
- Choose a bot to change group messages settings.
- ```
+
+
+ View Demo
+ ·
+ Report Bug
+ ·
+ Request Feature
+ Table of Contents
+
+
+
+
+
- * $data = [
- * 'id' => '',
- * 'title' => '',
- * 'input_message_content' => ,
- * 'reply_markup' => ,
- * 'url' => '',
- * 'hide_url' => true,
- * 'description' => '',
- * 'thumbnail_url' => '',
- * 'thumbnail_width' => 30,
- * 'thumbnail_height' => 30,
- * ];
- *
- *
- * @method string getType() Type of the result, must be article
- * @method string getId() Unique identifier for this result, 1-64 Bytes
- * @method string getTitle() Title of the result
- * @method InputMessageContent getInputMessageContent() Content of the message to be sent
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method string getUrl() Optional. URL of the result
- * @method bool getHideUrl() Optional. Pass True, if you don't want the URL to be shown in the message
- * @method string getDescription() Optional. Short description of the result
- * @method string getThumbnailUrl() Optional. Url of the thumbnail for the result
- * @method int getThumbnailWidth() Optional. Thumbnail width
- * @method int getThumbnailHeight() Optional. Thumbnail height
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 Bytes
- * @method $this setTitle(string $title) Title of the result
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Content of the message to be sent
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setUrl(string $url) Optional. URL of the result
- * @method $this setHideUrl(bool $hide_url) Optional. Pass True, if you don't want the URL to be shown in the message
- * @method $this setDescription(string $description) Optional. Short description of the result
- * @method $this setThumbnailUrl(string $thumbnail_url) Optional. Url of the thumbnail for the result
- * @method $this setThumbnailWidth(int $thumbnail_width) Optional. Thumbnail width
- * @method $this setThumbnailHeight(int $thumbnail_height) Optional. Thumbnail height
- */
-class InlineQueryResultArticle extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultArticle constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'article';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultAudio.php b/src/Entities/InlineQuery/InlineQueryResultAudio.php
deleted file mode 100644
index c0a38e2b8..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultAudio.php
+++ /dev/null
@@ -1,70 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultAudio
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultaudio
- *
- *
- * $data = [
- * 'id' => '',
- * 'audio_url' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'performer' => '',
- * 'audio_duration' => 123,
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be audio
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getAudioUrl() A valid URL for the audio file
- * @method string getTitle() Title
- * @method string getCaption() Optional. Caption, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the audio caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method string getPerformer() Optional. Performer
- * @method int getAudioDuration() Optional. Audio duration in seconds
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the audio
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setAudioUrl(string $audio_url) A valid URL for the audio file
- * @method $this setTitle(string $title) Title
- * @method $this setCaption(string $caption) Optional. Caption, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the audio caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setPerformer(string $performer) Optional. Performer
- * @method $this setAudioDuration(int $audio_duration) Optional. Audio duration in seconds
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the audio
- */
-class InlineQueryResultAudio extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultAudio constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'audio';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php b/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php
deleted file mode 100644
index 0f5525712..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php
+++ /dev/null
@@ -1,61 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultCachedAudio
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcachedaudio
- *
- *
- * $data = [
- * 'id' => '',
- * 'audio_file_id' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be audio
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getAudioFileId() A valid file identifier for the audio file
- * @method string getCaption() Optional. Caption, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the audio caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the audio
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setAudioFileId(string $audio_file_id) A valid file identifier for the audio file
- * @method $this setCaption(string $caption) Optional. Caption, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the audio caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the audio
- */
-class InlineQueryResultCachedAudio extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultCachedAudio constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'audio';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php b/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php
deleted file mode 100644
index e16b9bf64..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php
+++ /dev/null
@@ -1,67 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultCachedDocument
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcacheddocument
- *
- *
- * $data = [
- * 'id' => '',
- * 'title' => '',
- * 'document_file_id' => '',
- * 'description' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be document
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getTitle() Title for the result
- * @method string getDocumentFileId() A valid file identifier for the file
- * @method string getDescription() Optional. Short description of the result
- * @method string getCaption() Optional. Caption of the document to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the document caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the file
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setTitle(string $title) Title for the result
- * @method $this setDocumentFileId(string $document_file_id) A valid file identifier for the file
- * @method $this setDescription(string $description) Optional. Short description of the result
- * @method $this setCaption(string $caption) Optional. Caption of the document to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the document caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the file
- */
-class InlineQueryResultCachedDocument extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultCachedDocument constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'document';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultCachedGif.php b/src/Entities/InlineQuery/InlineQueryResultCachedGif.php
deleted file mode 100644
index f1b114b3f..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultCachedGif.php
+++ /dev/null
@@ -1,64 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultCachedGif
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcachedgif
- *
- *
- * $data = [
- * 'id' => '',
- * 'gif_file_id' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be gif
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getGifFileId() A valid file identifier for the GIF file
- * @method string getTitle() Optional. Title for the result
- * @method string getCaption() Optional. Caption of the GIF file to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the GIF animation
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setGifFileId(string $gif_file_id) A valid file identifier for the GIF file
- * @method $this setTitle(string $title) Optional. Title for the result
- * @method $this setCaption(string $caption) Optional. Caption of the GIF file to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the GIF animation
- */
-class InlineQueryResultCachedGif extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultCachedGif constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'gif';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php b/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php
deleted file mode 100644
index cf01fcf6f..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php
+++ /dev/null
@@ -1,64 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultCachedMpeg4Gif
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcachedmpeg4gif
- *
- *
- * $data = [
- * 'id' => '',
- * 'mpeg4_file_id' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be mpeg4_gif
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getMpeg4FileId() A valid file identifier for the MP4 file
- * @method string getTitle() Optional. Title for the result
- * @method string getCaption() Optional. Caption of the MPEG-4 file to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the video animation
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setMpeg4FileId(string $mpeg4_file_id) A valid file identifier for the MP4 file
- * @method $this setTitle(string $title) Optional. Title for the result
- * @method $this setCaption(string $caption) Optional. Caption of the MPEG-4 file to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the video animation
- */
-class InlineQueryResultCachedMpeg4Gif extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultCachedMpeg4Gif constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'mpeg4_gif';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php b/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php
deleted file mode 100644
index 0eda7b59b..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php
+++ /dev/null
@@ -1,67 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultCachedPhoto
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcachedphoto
- *
- *
- * $data = [
- * 'id' => '',
- * 'photo_file_id' => '',
- * 'title' => '',
- * 'description' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be photo
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getPhotoFileId() A valid file identifier of the photo
- * @method string getTitle() Optional. Title for the result
- * @method string getDescription() Optional. Short description of the result
- * @method string getCaption() Optional. Caption of the photo to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the photo caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the photo
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setPhotoFileId(string $photo_file_id) A valid file identifier of the photo
- * @method $this setTitle(string $title) Optional. Title for the result
- * @method $this setDescription(string $description) Optional. Short description of the result
- * @method $this setCaption(string $caption) Optional. Caption of the photo to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the photo caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the photo
- */
-class InlineQueryResultCachedPhoto extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultCachedPhoto constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'photo';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php b/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php
deleted file mode 100644
index 8d7c577c0..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php
+++ /dev/null
@@ -1,54 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultCachedSticker
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcachedsticker
- *
- *
- * $data = [
- * 'id' => '',
- * 'sticker_file_id' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be sticker
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getStickerFileId() A valid file identifier of the sticker
- * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the sticker
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setStickerFileId(string $sticker_file_id) A valid file identifier of the sticker
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the sticker
- */
-class InlineQueryResultCachedSticker extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultCachedSticker constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'sticker';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php b/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php
deleted file mode 100644
index 13163c1ac..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php
+++ /dev/null
@@ -1,67 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultCachedVideo
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcachedvideo
- *
- *
- * $data = [
- * 'id' => '',
- * 'video_file_id' => '',
- * 'title' => '',
- * 'description' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be video
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getVideoFileId() A valid file identifier for the video file
- * @method string getTitle() Title for the result
- * @method string getDescription() Optional. Short description of the result
- * @method string getCaption() Optional. Caption of the video to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the video caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the video
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setVideoFileId(string $video_file_id) A valid file identifier for the video file
- * @method $this setTitle(string $title) Title for the result
- * @method $this setDescription(string $description) Optional. Short description of the result
- * @method $this setCaption(string $caption) Optional. Caption of the video to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the video caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the video
- */
-class InlineQueryResultCachedVideo extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultCachedVideo constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'video';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php b/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php
deleted file mode 100644
index 6ab041487..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php
+++ /dev/null
@@ -1,64 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultCachedVoice
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcachedvoice
- *
- *
- * $data = [
- * 'id' => '',
- * 'voice_file_id' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be voice
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getVoiceFileId() A valid file identifier for the voice message
- * @method string getTitle() Voice message title
- * @method string getCaption() Optional. Caption, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the voice caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the voice message
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setVoiceFileId(string $voice_file_id) A valid file identifier for the voice message
- * @method $this setTitle(string $title) Voice message title
- * @method $this setCaption(string $caption) Optional. Caption, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the voice caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the voice message
- */
-class InlineQueryResultCachedVoice extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultCachedVoice constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'voice';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultContact.php b/src/Entities/InlineQuery/InlineQueryResultContact.php
deleted file mode 100644
index b4d6cfa85..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultContact.php
+++ /dev/null
@@ -1,71 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultContact
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultcontact
- *
- *
- * $data = [
- * 'id' => '',
- * 'phone_number' => '',
- * 'first_name' => '',
- * 'last_name' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * 'thumbnail_url' => '',
- * 'thumbnail_width' => 30,
- * 'thumbnail_height' => 30,
- * ];
- *
- *
- * @method string getType() Type of the result, must be contact
- * @method string getId() Unique identifier for this result, 1-64 Bytes
- * @method string getPhoneNumber() Contact's phone number
- * @method string getFirstName() Contact's first name
- * @method string getLastName() Optional. Contact's last name
- * @method string getVcard() Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the contact
- * @method string getThumbnailUrl() Optional. Url of the thumbnail for the result
- * @method int getThumbnailWidth() Optional. Thumbnail width
- * @method int getThumbnailHeight() Optional. Thumbnail height
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 Bytes
- * @method $this setPhoneNumber(string $phone_number) Contact's phone number
- * @method $this setFirstName(string $first_name) Contact's first name
- * @method $this setLastName(string $last_name) Optional. Contact's last name
- * @method $this setVcard(string $vcard) Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the contact
- * @method $this setThumbnailUrl(string $thumbnail_url) Optional. Url of the thumbnail for the result
- * @method $this setThumbnailWidth(int $thumbnail_width) Optional. Thumbnail width
- * @method $this setThumbnailHeight(int $thumbnail_height) Optional. Thumbnail height
- */
-class InlineQueryResultContact extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultContact constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'contact';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultDocument.php b/src/Entities/InlineQuery/InlineQueryResultDocument.php
deleted file mode 100644
index 8db76febe..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultDocument.php
+++ /dev/null
@@ -1,79 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultDocument
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultdocument
- *
- *
- * $data = [
- * 'id' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'document_url' => '',
- * 'mime_type' => '',
- * 'description' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * 'thumbnail_url' => '',
- * 'thumbnail_width' => 30,
- * 'thumbnail_height' => 30,
- * ];
- *
- *
- * @method string getType() Type of the result, must be document
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getTitle() Title for the result
- * @method string getCaption() Optional. Caption of the document to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the document caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method string getDocumentUrl() A valid URL for the file
- * @method string getMimeType() Mime type of the content of the file, either “application/pdf” or “application/zip”
- * @method string getDescription() Optional. Short description of the result
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the file
- * @method string getThumbnailUrl() Optional. URL of the thumbnail (jpeg only) for the file
- * @method int getThumbnailWidth() Optional. Thumbnail width
- * @method int getThumbnailHeight() Optional. Thumbnail height
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setTitle(string $title) Title for the result
- * @method $this setCaption(string $caption) Optional. Caption of the document to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the document caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setDocumentUrl(string $document_url) A valid URL for the file
- * @method $this setMimeType(string $mime_type) Mime type of the content of the file, either “application/pdf” or “application/zip”
- * @method $this setDescription(string $description) Optional. Short description of the result
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the file
- * @method $this setThumbnailUrl(string $thumbnail_url) Optional. URL of the thumbnail (jpeg only) for the file
- * @method $this setThumbnailWidth(int $thumbnail_width) Optional. Thumbnail width
- * @method $this setThumbnailHeight(int $thumbnail_height) Optional. Thumbnail height
- */
-class InlineQueryResultDocument extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultDocument constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'document';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultGame.php b/src/Entities/InlineQuery/InlineQueryResultGame.php
deleted file mode 100644
index d40860fe4..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultGame.php
+++ /dev/null
@@ -1,50 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-
-/**
- * Class InlineQueryResultGame
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultgame
- *
- *
- * $data = [
- * 'id' => '',
- * 'game_short_name' => '',
- * 'reply_markup' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be game
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getGameShortName() Short name of the game
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setGameShortName(string $game_short_name) Short name of the game
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- */
-class InlineQueryResultGame extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultGame constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'game';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultGif.php b/src/Entities/InlineQuery/InlineQueryResultGif.php
deleted file mode 100644
index 34c9810cc..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultGif.php
+++ /dev/null
@@ -1,77 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultGif
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultgif
- *
- *
- * $data = [
- * 'id' => '',
- * 'gif_url' => '',
- * 'gif_width' => 30,
- * 'gif_height' => 30,
- * 'thumbnail_url' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be gif
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getGifUrl() A valid URL for the GIF file. File size must not exceed 1MB
- * @method int getGifWidth() Optional. Width of the GIF
- * @method int getGifHeight() Optional. Height of the GIF
- * @method int getGifDuration() Optional. Duration of the GIF
- * @method string getThumbnailUrl() URL of the static thumbnail for the result (jpeg or gif)
- * @method string getThumbnailMimeType() Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”
- * @method string getTitle() Optional. Title for the result
- * @method string getCaption() Optional. Caption of the GIF file to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the GIF animation
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setGifUrl(string $gif_url) A valid URL for the GIF file. File size must not exceed 1MB
- * @method $this setGifWidth(int $gif_width) Optional. Width of the GIF
- * @method $this setGifHeight(int $gif_height) Optional. Height of the GIF
- * @method $this setGifDuration(int $gif_duration) Optional. Duration of the GIF
- * @method $this setThumbnailUrl(string $thumbnail_url) URL of the static thumbnail for the result (jpeg or gif)
- * @method $this setThumbnailMimeType(string $thumbnail_mime_type) Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”
- * @method $this setTitle(string $title) Optional. Title for the result
- * @method $this setCaption(string $caption) Optional. Caption of the GIF file to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the GIF animation
- */
-class InlineQueryResultGif extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultGif constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'gif';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultLocation.php b/src/Entities/InlineQuery/InlineQueryResultLocation.php
deleted file mode 100644
index 888556d4b..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultLocation.php
+++ /dev/null
@@ -1,81 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultLocation
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultlocation
- *
- *
- * $data = [
- * 'id' => '',
- * 'latitude' => 36.0338,
- * 'longitude' => 71.8601,
- * 'title' => '',
- * 'horizontal_accuracy' => 36.9,
- * 'live_period' => 900,
- * 'heading' => 88,
- * 'proximity_alert_radius' => 300,
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * 'thumbnail_url' => '',
- * 'thumbnail_width' => 30,
- * 'thumbnail_height' => 30,
- * ];
- *
- *
- * @method string getType() Type of the result, must be location
- * @method string getId() Unique identifier for this result, 1-64 Bytes
- * @method float getLatitude() Location latitude in degrees
- * @method float getLongitude() Location longitude in degrees
- * @method string getTitle() Location title
- * @method float getHorizontalAccuracy() Optional. The radius of uncertainty for the location, measured in meters; 0-1500
- * @method int getLivePeriod() Optional. Period in seconds for which the location can be updated, should be between 60 and 86400.
- * @method int getHeading() Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
- * @method int getProximityAlertRadius() Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the location
- * @method string getThumbnailUrl() Optional. Url of the thumbnail for the result
- * @method int getThumbnailWidth() Optional. Thumbnail width
- * @method int getThumbnailHeight() Optional. Thumbnail height
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 Bytes
- * @method $this setLatitude(float $latitude) Location latitude in degrees
- * @method $this setLongitude(float $longitude) Location longitude in degrees
- * @method $this setTitle(string $title) Location title
- * @method $this setHorizontalAccuracy(float $horizontal_accuracy) Optional. The radius of uncertainty for the location, measured in meters; 0-1500
- * @method $this setLivePeriod(int $live_period) Optional. Period in seconds for which the location can be updated, should be between 60 and 86400.
- * @method $this setHeading(int $heading) Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
- * @method $this setProximityAlertRadius(int $proximity_alert_radius) Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the location
- * @method $this setThumbnailUrl(string $thumbnail_url) Optional. Url of the thumbnail for the result
- * @method $this setThumbnailWidth(int $thumbnail_width) Optional. Thumbnail width
- * @method $this setThumbnailHeight(int $thumbnail_height) Optional. Thumbnail height
- */
-class InlineQueryResultLocation extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultLocation constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'location';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php b/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php
deleted file mode 100644
index 01015eeca..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php
+++ /dev/null
@@ -1,77 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultMpeg4Gif
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultmpeg4gif
- *
- *
- * $data = [
- * 'id' => '',
- * 'mpeg4_url' => '',
- * 'mpeg4_width' => 30,
- * 'mpeg4_height' => 30,
- * 'thumbnail_url' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be mpeg4_gif
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getMpeg4Url() A valid URL for the MP4 file. File size must not exceed 1MB
- * @method int getMpeg4Width() Optional. Video width
- * @method int getMpeg4Height() Optional. Video height
- * @method int getMpeg4Duration() Optional. Video duration
- * @method string getThumbnailUrl() URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
- * @method string getThumbnailMimeType() Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”
- * @method string getTitle() Optional. Title for the result
- * @method string getCaption() Optional. Caption of the MPEG-4 file to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the video animation
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setMpeg4Url(string $mpeg4_url) A valid URL for the MP4 file. File size must not exceed 1MB
- * @method $this setMpeg4Width(int $mpeg4_width) Optional. Video width
- * @method $this setMpeg4Height(int $mpeg4_height) Optional. Video height
- * @method $this setMpeg4Duration(int $mpeg4_duration) Optional. Video duration
- * @method $this setThumbnailUrl(string $thumbnail_url) URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
- * @method $this setThumbnailMimeType(string $thumbnail_mime_type) Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”
- * @method $this setTitle(string $title) Optional. Title for the result
- * @method $this setCaption(string $caption) Optional. Caption of the MPEG-4 file to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the video animation
- */
-class InlineQueryResultMpeg4Gif extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultMpeg4Gif constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'mpeg4_gif';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultPhoto.php b/src/Entities/InlineQuery/InlineQueryResultPhoto.php
deleted file mode 100644
index 2633ad8a8..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultPhoto.php
+++ /dev/null
@@ -1,76 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultPhoto
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultphoto
- *
- *
- * $data = [
- * 'id' => '',
- * 'photo_url' => '',
- * 'thumbnail_url' => '',
- * 'photo_width' => 30,
- * 'photo_height' => 30,
- * 'title' => '',
- * 'description' => '',
- * 'caption' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be photo
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getPhotoUrl() A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB
- * @method string getThumbnailUrl() URL of the thumbnail for the photo
- * @method int getPhotoWidth() Optional. Width of the photo
- * @method int getPhotoHeight() Optional. Height of the photo
- * @method string getTitle() Optional. Title for the result
- * @method string getDescription() Optional. Short description of the result
- * @method string getCaption() Optional. Caption of the photo to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the photo caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the photo
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setPhotoUrl(string $photo_url) A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB
- * @method $this setThumbnailUrl(string $thumbnail_url) URL of the thumbnail for the photo
- * @method $this setPhotoWidth(int $photo_width) Optional. Width of the photo
- * @method $this setPhotoHeight(int $photo_height) Optional. Height of the photo
- * @method $this setTitle(string $title) Optional. Title for the result
- * @method $this setDescription(string $description) Optional. Short description of the result
- * @method $this setCaption(string $caption) Optional. Caption of the photo to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the photo caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the photo
- */
-class InlineQueryResultPhoto extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultPhoto constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'photo';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultVenue.php b/src/Entities/InlineQuery/InlineQueryResultVenue.php
deleted file mode 100644
index 8ab428b00..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultVenue.php
+++ /dev/null
@@ -1,81 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultVenue
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultvenue
- *
- *
- * $data = [
- * 'id' => '',
- * 'latitude' => 36.0338,
- * 'longitude' => 71.8601,
- * 'title' => '',
- * 'address' => '',
- * 'foursquare_id' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * 'thumbnail_url' => '',
- * 'thumbnail_width' => 30,
- * 'thumbnail_height' => 30,
- * ];
- *
- *
- * @method string getType() Type of the result, must be venue
- * @method string getId() Unique identifier for this result, 1-64 Bytes
- * @method float getLatitude() Latitude of the venue location in degrees
- * @method float getLongitude() Longitude of the venue location in degrees
- * @method string getTitle() Title of the venue
- * @method string getAddress() Address of the venue
- * @method string getFoursquareId() Optional. Foursquare identifier of the venue if known
- * @method string getFoursquareType() Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
- * @method string getGooglePlaceId() Optional. Google Places identifier of the venue
- * @method string getGooglePlaceType() Optional. Google Places type of the venue
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the venue
- * @method string getThumbnailUrl() Optional. Url of the thumbnail for the result
- * @method int getThumbnailWidth() Optional. Thumbnail width
- * @method int getThumbnailHeight() Optional. Thumbnail height
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 Bytes
- * @method $this setLatitude(float $latitude) Latitude of the venue location in degrees
- * @method $this setLongitude(float $longitude) Longitude of the venue location in degrees
- * @method $this setTitle(string $title) Title of the venue
- * @method $this setAddress(string $address) Address of the venue
- * @method $this setFoursquareId(string $foursquare_id) Optional. Foursquare identifier of the venue if known
- * @method $this setFoursquareType(string $foursquare_type) Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
- * @method $this setGooglePlaceId(string $google_place_id) Optional. Google Places identifier of the venue
- * @method $this setGooglePlaceType(string $google_place_type) Optional. Google Places type of the venue
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the venue
- * @method $this setThumbnailUrl(string $thumbnail_url) Optional. Url of the thumbnail for the result
- * @method $this setThumbnailWidth(int $thumbnail_width) Optional. Thumbnail width
- * @method $this setThumbnailHeight(int $thumbnail_height) Optional. Thumbnail height
- */
-class InlineQueryResultVenue extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultVenue constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'venue';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultVideo.php b/src/Entities/InlineQuery/InlineQueryResultVideo.php
deleted file mode 100644
index 9337bd7a4..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultVideo.php
+++ /dev/null
@@ -1,82 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultVideo
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultvideo
- *
- *
- * $data = [
- * 'id' => '',
- * 'video_url' => '',
- * 'mime_type' => '',
- * 'thumbnail_url' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'video_width' => 30,
- * 'video_height' => 30,
- * 'video_duration' => 123,
- * 'description' => '',
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be video
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getVideoUrl() A valid URL for the embedded video player or video file
- * @method string getMimeType() Mime type of the content of video url, “text/html” or “video/mp4”
- * @method string getThumbnailUrl() URL of the thumbnail (jpeg only) for the video
- * @method string getTitle() Title for the result
- * @method string getCaption() Optional. Caption of the video to be sent, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the video caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method int getVideoWidth() Optional. Video width
- * @method int getVideoHeight() Optional. Video height
- * @method int getVideoDuration() Optional. Video duration in seconds
- * @method string getDescription() Optional. Short description of the result
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the video
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setVideoUrl(string $video_url) A valid URL for the embedded video player or video file
- * @method $this setMimeType(string $mime_type) Mime type of the content of video url, “text/html” or “video/mp4”
- * @method $this setThumbnailUrl(string $thumbnail_url) URL of the thumbnail (jpeg only) for the video
- * @method $this setTitle(string $title) Title for the result
- * @method $this setCaption(string $caption) Optional. Caption of the video to be sent, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the video caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setVideoWidth(int $video_width) Optional. Video width
- * @method $this setVideoHeight(int $video_height) Optional. Video height
- * @method $this setVideoDuration(int $video_duration) Optional. Video duration in seconds
- * @method $this setDescription(string $description) Optional. Short description of the result
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the video
- */
-class InlineQueryResultVideo extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultVideo constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'video';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQuery/InlineQueryResultVoice.php b/src/Entities/InlineQuery/InlineQueryResultVoice.php
deleted file mode 100644
index 8fbad6972..000000000
--- a/src/Entities/InlineQuery/InlineQueryResultVoice.php
+++ /dev/null
@@ -1,67 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InlineQuery;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent;
-
-/**
- * Class InlineQueryResultVoice
- *
- * @link https://core.telegram.org/bots/api#inlinequeryresultvoice
- *
- *
- * $data = [
- * 'id' => '',
- * 'voice_url' => '',
- * 'title' => '',
- * 'caption' => '',
- * 'voice_duration' => 123,
- * 'reply_markup' => ,
- * 'input_message_content' => ,
- * ];
- *
- *
- * @method string getType() Type of the result, must be voice
- * @method string getId() Unique identifier for this result, 1-64 bytes
- * @method string getVoiceUrl() A valid URL for the voice recording
- * @method string getTitle() Recording title
- * @method string getCaption() Optional. Caption, 0-200 characters
- * @method string getParseMode() Optional. Mode for parsing entities in the voice caption
- * @method MessageEntity[] getCaptionEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method int getVoiceDuration() Optional. Recording duration in seconds
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message
- * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the voice recording
- *
- * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes
- * @method $this setVoiceUrl(string $voice_url) A valid URL for the voice recording
- * @method $this setTitle(string $title) Recording title
- * @method $this setCaption(string $caption) Optional. Caption, 0-200 characters
- * @method $this setParseMode(string $parse_mode) Optional. Mode for parsing entities in the voice caption
- * @method $this setCaptionEntities(array $caption_entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setVoiceDuration(int $voice_duration) Optional. Recording duration in seconds
- * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message
- * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the voice recording
- */
-class InlineQueryResultVoice extends InlineEntity implements InlineQueryResult
-{
- /**
- * InlineQueryResultVoice constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['type'] = 'voice';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResult.php b/src/Entities/InlineQueryResult/InlineQueryResult.php
new file mode 100644
index 000000000..72f42de4e
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResult.php
@@ -0,0 +1,14 @@
+ InputMessageContent::class,
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'article',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultAudio.php b/src/Entities/InlineQueryResult/InlineQueryResultAudio.php
new file mode 100644
index 000000000..8101ff156
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultAudio.php
@@ -0,0 +1,37 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'audio',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultCachedAudio.php b/src/Entities/InlineQueryResult/InlineQueryResultCachedAudio.php
new file mode 100644
index 000000000..a6ebf9bdb
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultCachedAudio.php
@@ -0,0 +1,34 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'audio',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultCachedDocument.php b/src/Entities/InlineQueryResult/InlineQueryResultCachedDocument.php
new file mode 100644
index 000000000..3976b0a7c
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultCachedDocument.php
@@ -0,0 +1,36 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'document',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultCachedGif.php b/src/Entities/InlineQueryResult/InlineQueryResultCachedGif.php
new file mode 100644
index 000000000..b96e576d9
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultCachedGif.php
@@ -0,0 +1,36 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'gif',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.php b/src/Entities/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.php
new file mode 100644
index 000000000..4c67194c5
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.php
@@ -0,0 +1,36 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'mpeg4_gif',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultCachedPhoto.php b/src/Entities/InlineQueryResult/InlineQueryResultCachedPhoto.php
new file mode 100644
index 000000000..057a5ca1d
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultCachedPhoto.php
@@ -0,0 +1,37 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'photo',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultCachedSticker.php b/src/Entities/InlineQueryResult/InlineQueryResultCachedSticker.php
new file mode 100644
index 000000000..8d4e09eff
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultCachedSticker.php
@@ -0,0 +1,29 @@
+ InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'sticker',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultCachedVideo.php b/src/Entities/InlineQueryResult/InlineQueryResultCachedVideo.php
new file mode 100644
index 000000000..de2794838
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultCachedVideo.php
@@ -0,0 +1,37 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'video',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultCachedVoice.php b/src/Entities/InlineQueryResult/InlineQueryResultCachedVoice.php
new file mode 100644
index 000000000..41910617f
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultCachedVoice.php
@@ -0,0 +1,35 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'voice',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultContact.php b/src/Entities/InlineQueryResult/InlineQueryResultContact.php
new file mode 100644
index 000000000..2d2558214
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultContact.php
@@ -0,0 +1,35 @@
+ InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'contact',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultDocument.php b/src/Entities/InlineQueryResult/InlineQueryResultDocument.php
new file mode 100644
index 000000000..64ffb4e8d
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultDocument.php
@@ -0,0 +1,40 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'document',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultGame.php b/src/Entities/InlineQueryResult/InlineQueryResultGame.php
new file mode 100644
index 000000000..e2bb1df9c
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultGame.php
@@ -0,0 +1,26 @@
+ InlineKeyboardMarkup::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'game',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultGif.php b/src/Entities/InlineQueryResult/InlineQueryResultGif.php
new file mode 100644
index 000000000..d6030f5ba
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultGif.php
@@ -0,0 +1,41 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'gif',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultLocation.php b/src/Entities/InlineQueryResult/InlineQueryResultLocation.php
new file mode 100644
index 000000000..041f2bf8f
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultLocation.php
@@ -0,0 +1,38 @@
+ InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'location',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultMpeg4Gif.php b/src/Entities/InlineQueryResult/InlineQueryResultMpeg4Gif.php
new file mode 100644
index 000000000..d164758f3
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultMpeg4Gif.php
@@ -0,0 +1,41 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'mpeg4_gif',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultPhoto.php b/src/Entities/InlineQueryResult/InlineQueryResultPhoto.php
new file mode 100644
index 000000000..277663c2e
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultPhoto.php
@@ -0,0 +1,40 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'photo',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultVenue.php b/src/Entities/InlineQueryResult/InlineQueryResultVenue.php
new file mode 100644
index 000000000..d82f81f15
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultVenue.php
@@ -0,0 +1,39 @@
+ InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'venue',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultVideo.php b/src/Entities/InlineQueryResult/InlineQueryResultVideo.php
new file mode 100644
index 000000000..e0b92974b
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultVideo.php
@@ -0,0 +1,42 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'video',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResult/InlineQueryResultVoice.php b/src/Entities/InlineQueryResult/InlineQueryResultVoice.php
new file mode 100644
index 000000000..4094e73c3
--- /dev/null
+++ b/src/Entities/InlineQueryResult/InlineQueryResultVoice.php
@@ -0,0 +1,36 @@
+ [MessageEntity::class],
+ 'reply_markup' => InlineKeyboardMarkup::class,
+ 'input_message_content' => InputMessageContent::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => 'voice',
+ ];
+ }
+}
diff --git a/src/Entities/InlineQueryResultsButton.php b/src/Entities/InlineQueryResultsButton.php
index a96222e9c..b85049fc6 100644
--- a/src/Entities/InlineQueryResultsButton.php
+++ b/src/Entities/InlineQueryResultsButton.php
@@ -1,24 +1,15 @@
WebAppInfo::class,
diff --git a/src/Entities/InputFile.php b/src/Entities/InputFile.php
new file mode 100644
index 000000000..aad2a1bd5
--- /dev/null
+++ b/src/Entities/InputFile.php
@@ -0,0 +1,22 @@
+ 'attach://' . $file_id,
+ '__file_' . $file_id => fopen($filepath, 'r'),
+ ];
+ }
+}
diff --git a/src/Entities/InputMedia/InputMedia.php b/src/Entities/InputMedia/InputMedia.php
index b9bd973d1..cc23f8cf8 100644
--- a/src/Entities/InputMedia/InputMedia.php
+++ b/src/Entities/InputMedia/InputMedia.php
@@ -1,8 +1,33 @@
new InputMediaPhoto($data),
+ self::TYPE_VIDEO => new InputMediaVideo($data),
+ self::TYPE_ANIMATION => new InputMediaAnimation($data),
+ self::TYPE_AUDIO => new InputMediaAudio($data),
+ self::TYPE_DOCUMENT => new InputMediaDocument($data),
+ };
+ }
}
diff --git a/src/Entities/InputMedia/InputMediaAnimation.php b/src/Entities/InputMedia/InputMediaAnimation.php
index 7671923cb..c475cf944 100644
--- a/src/Entities/InputMedia/InputMediaAnimation.php
+++ b/src/Entities/InputMedia/InputMediaAnimation.php
@@ -1,66 +1,43 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InputMedia;
+namespace PhpTelegramBot\Core\Entities\InputMedia;
-use Longman\TelegramBot\Entities\Entity;
+use PhpTelegramBot\Core\Contracts\AllowsBypassingGet;
+use PhpTelegramBot\Core\Entities\InputFile;
+use PhpTelegramBot\Core\Entities\MessageEntity;
/**
- * Class InputMediaAnimation
- *
- * @link https://core.telegram.org/bots/api#inputmediaanimation
- *
- *
- * $data = [
- * 'media' => '123abc',
- * 'thumbnail' => '456def',
- * 'caption' => '*Animation* caption',
- * 'parse_mode' => 'markdown',
- * 'width' => 200,
- * 'height' => 150,
- * 'duration' => 11,
- * ];
- *
- *
- * @method string getType() Type of the result, must be animation
- * @method string getMedia() File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://
- * $data = [
- * 'media' => '123abc',
- * 'thumbnail' => '456def',
- * 'caption' => '*Audio* caption',
- * 'parse_mode' => 'markdown',
- * 'duration' => 42,
- * 'performer' => 'John Doe',
- * 'title' => 'The Song',
- * ];
- *
- *
- * @method string getType() Type of the result, must be audio
- * @method string getMedia() File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://
- * $data = [
- * 'media' => '123abc',
- * 'thumbnail' => '456def',
- * 'caption' => '*Document* caption',
- * 'parse_mode' => 'markdown',
- * ];
- *
- *
- * @method string getType() Type of the result, must be document
- * @method string getMedia() File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://
- * $data = [
- * 'media' => '123abc',
- * 'caption' => '*Photo* caption',
- * 'parse_mode' => 'markdown',
- * ];
- *
- *
- * @method string getType() Type of the result, must be photo
- * @method string getMedia() File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://
- * $data = [
- * 'media' => '123abc',
- * 'thumbnail' => '456def',
- * 'caption' => '*Video* caption (streamable)',
- * 'parse_mode' => 'markdown',
- * 'width' => 800,
- * 'height' => 600,
- * 'duration' => 42,
- * 'supports_streaming' => true,
- * ];
- *
- *
- * @method string getType() Type of the result, must be video
- * @method string getMedia() File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://
- * $data = [
- * 'phone_number' => '',
- * 'first_name' => '',
- * 'last_name' => '',
- * 'vcard' => '',
- * ];
- *
- *
- * @method string getPhoneNumber() Contact's phone number
- * @method string getFirstName() Contact's first name
- * @method string getLastName() Optional. Contact's last name
- * @method string getVcard() Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes
- *
- * @method $this setPhoneNumber(string $phone_number) Contact's phone number
- * @method $this setFirstName(string $first_name) Contact's first name
- * @method $this setLastName(string $last_name) Optional. Contact's last name
- * @method $this setVcard(string $vcard) Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes
+ * @method string getPhoneNumber() Contact's phone number
+ * @method string getFirstName() Contact's first name
+ * @method string|null getLastName() Optional. Contact's last name
+ * @method string|null getVcard() Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes
*/
-class InputContactMessageContent extends InlineEntity implements InputMessageContent
+class InputContactMessageContent extends InputMessageContent
{
-
+ //
}
diff --git a/src/Entities/InputMessageContent/InputInvoiceMessageContent.php b/src/Entities/InputMessageContent/InputInvoiceMessageContent.php
index 443635994..ba746d250 100644
--- a/src/Entities/InputMessageContent/InputInvoiceMessageContent.php
+++ b/src/Entities/InputMessageContent/InputInvoiceMessageContent.php
@@ -1,66 +1,45 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InputMessageContent;
+namespace PhpTelegramBot\Core\Entities\InputMessageContent;
-use Longman\TelegramBot\Entities\InlineQuery\InlineEntity;
+use PhpTelegramBot\Core\Contracts\AllowsBypassingGet;
+use PhpTelegramBot\Core\Entities\LabeledPrice;
/**
- * Class InputTextMessageContent
- *
- * @link https://core.telegram.org/bots/api#inputinvoicemessagecontent
- *
* @method string getTitle() Product name, 1-32 characters
* @method string getDescription() Product description, 1-255 characters
* @method string getPayload() Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
- * @method string getProviderToken() Payment provider token, obtained via Botfather
- * @method string getCurrency() Three-letter ISO 4217 currency code, see more on currencies
- * @method LabeledPrice[] getPrices() Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
- * @method int getMaxTipAmount() Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0
- * @method int[] getSuggestedTipAmounts() Optional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
- * @method string getProviderData() Optional. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider.
- * @method string getPhotoUrl() Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
- * @method int getPhotoSize() Optional. Photo size
- * @method int getPhotoWidth() Optional. Photo width
- * @method int getPhotoHeight() Optional. Photo height
- * @method bool getNeedName() Optional. Pass True, if you require the user's full name to complete the order
- * @method bool getNeedPhoneNumber() Optional. Pass True, if you require the user's phone number to complete the order
- * @method bool getNeedEmail() Optional. Pass True, if you require the user's email address to complete the order
- * @method bool getNeedShippingAddress() Optional. Pass True, if you require the user's shipping address to complete the order
- * @method bool getSendPhoneNumberToProvider() Optional. Pass True, if user's phone number should be sent to provider
- * @method bool getSendEmailToProvider() Optional. Pass True, if user's email address should be sent to provider
- * @method bool getIsFlexible() Optional. Pass True, if the final price depends on the shipping method
- *
- * @method $this setTitle(string $title) Product name, 1-32 characters
- * @method $this setDescription(string $description) Product description, 1-255 characters
- * @method $this setPayload(string $payload) Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
- * @method $this setProviderToken(string $provider_token) Payment provider token, obtained via Botfather
- * @method $this setCurrency(string $currency) Three-letter ISO 4217 currency code, see more on currencies
- * @method $this setPrices(LabeledPrice[] $prices) Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
- * @method $this setMaxTipAmount(int $max_tip_amount) Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0
- * @method $this setSuggestedTipAmounts(int[] $suggested_tip_amounts) Optional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
- * @method $this setProviderData(string $provider_data) Optional. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider.
- * @method $this setPhotoUrl(string $photo_url) Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
- * @method $this setPhotoSize(int $photo_size) Optional. Photo size
- * @method $this setPhotoWidth(int $photo_width) Optional. Photo width
- * @method $this setPhotoHeight(int $photo_height) Optional. Photo height
- * @method $this setNeedName(bool $need_name) Optional. Pass True, if you require the user's full name to complete the order
- * @method $this setNeedPhoneNumber(bool $need_phone_number) Optional. Pass True, if you require the user's phone number to complete the order
- * @method $this setNeedEmail(bool $need_email) Optional. Pass True, if you require the user's email address to complete the order
- * @method $this setNeedShippingAddress(bool $need_shipping_address) Optional. Pass True, if you require the user's shipping address to complete the order
- * @method $this setSendPhoneNumberToProvider(bool $send_phone_number_to_provider) Optional. Pass True, if user's phone number should be sent to provider
- * @method $this setSendEmailToProvider(bool $send_email_to_provider) Optional. Pass True, if user's email address should be sent to provider
- * @method $this setIsFlexible(bool $is_flexible) Optional. Pass True, if the final price depends on the shipping method
+ * @method string|null getProviderToken() Optional. Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars.
+ * @method string getCurrency() Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars.
+ * @method LabeledPrice[] getPrices() Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars.
+ * @method int|null getMaxTipAmount() Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars.
+ * @method int[]|null getSuggestedTipAmounts() Optional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
+ * @method string|null getProviderData() Optional. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider.
+ * @method string|null getPhotoUrl() Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service.
+ * @method int|null getPhotoSize() Optional. Photo size in bytes
+ * @method int|null getPhotoWidth() Optional. Photo width
+ * @method int|null getPhotoHeight() Optional. Photo height
+ * @method bool|null getNeedName() Optional. Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars.
+ * @method bool|null getNeedPhoneNumber() Optional. Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars.
+ * @method bool|null getNeedEmail() Optional. Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars.
+ * @method bool|null getNeedShippingAddress() Optional. Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars.
+ * @method bool|null getSendPhoneNumberToProvider() Optional. Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars.
+ * @method bool|null getSendEmailToProvider() Optional. Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars.
+ * @method bool isFlexible() Optional. Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars.
*/
-class InputInvoiceMessageContent extends InlineEntity implements InputMessageContent
+class InputInvoiceMessageContent extends InputMessageContent implements AllowsBypassingGet
{
+ protected static function subEntities(): array
+ {
+ return [
+ 'prices' => [LabeledPrice::class],
+ ];
+ }
+ public static function fieldsBypassingGet(): array
+ {
+ return [
+ 'is_flexible' => false,
+ ];
+ }
}
diff --git a/src/Entities/InputMessageContent/InputLocationMessageContent.php b/src/Entities/InputMessageContent/InputLocationMessageContent.php
index 2ede0d2ae..c6a61109c 100644
--- a/src/Entities/InputMessageContent/InputLocationMessageContent.php
+++ b/src/Entities/InputMessageContent/InputLocationMessageContent.php
@@ -1,48 +1,16 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InputMessageContent;
-
-use Longman\TelegramBot\Entities\InlineQuery\InlineEntity;
+namespace PhpTelegramBot\Core\Entities\InputMessageContent;
/**
- * Class InputLocationMessageContent
- *
- * @link https://core.telegram.org/bots/api#inputlocationmessagecontent
- *
- *
- * $data = [
- * 'latitude' => 36.0338,
- * 'longitude' => 71.8601,
- * 'horizontal_accuracy' => 36.9,
- * 'live_period' => 900,
- * 'heading' => 88,
- * 'proximity_alert_radius' => 300,
- * ];
- *
- * @method float getLatitude() Latitude of the location in degrees
- * @method float getLongitude() Longitude of the location in degrees
- * @method float getHorizontalAccuracy() Optional. The radius of uncertainty for the location, measured in meters; 0-1500
- * @method int getLivePeriod() Optional. Period in seconds for which the location can be updated, should be between 60 and 86400.
- * @method int getHeading() Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
- * @method int getProximityAlertRadius() Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
- *
- * @method $this setLatitude(float $latitude) Latitude of the location in degrees
- * @method $this setLongitude(float $longitude) Longitude of the location in degrees
- * @method $this setHorizontalAccuracy(float $horizontal_accuracy) Optional. The radius of uncertainty for the location, measured in meters; 0-1500
- * @method $this setLivePeriod(int $live_period) Optional. Period in seconds for which the location can be updated, should be between 60 and 86400.
- * @method $this setHeading(int $heading) Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
- * @method $this setProximityAlertRadius(int $proximity_alert_radius) Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
+ * @method float getLatitude() Latitude of the location in degrees
+ * @method float getLongitude() Longitude of the location in degrees
+ * @method float|null getHorizontalAccuracy() Optional. The radius of uncertainty for the location, measured in meters; 0-1500
+ * @method int|null getLivePeriod() Optional. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely.
+ * @method int|null getHeading() Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
+ * @method int|null getProximityAlertRadius() Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
*/
-class InputLocationMessageContent extends InlineEntity implements InputMessageContent
+class InputLocationMessageContent extends InputMessageContent
{
-
+ //
}
diff --git a/src/Entities/InputMessageContent/InputMessageContent.php b/src/Entities/InputMessageContent/InputMessageContent.php
index 3b43be9e9..79604a3a7 100644
--- a/src/Entities/InputMessageContent/InputMessageContent.php
+++ b/src/Entities/InputMessageContent/InputMessageContent.php
@@ -1,8 +1,10 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+namespace PhpTelegramBot\Core\Entities\InputMessageContent;
-namespace Longman\TelegramBot\Entities\InputMessageContent;
-
-use Longman\TelegramBot\Entities\InlineQuery\InlineEntity;
+use PhpTelegramBot\Core\Entities\LinkPreviewOptions;
+use PhpTelegramBot\Core\Entities\MessageEntity;
/**
- * Represents the content of a text message to be sent as the result of an inline query.
- *
- * @link https://core.telegram.org/bots/api#inputtextmessagecontent
- *
- * @method string getMessageText() Text of the message to be sent, 1-4096 characters.
- * @method string getParseMode() Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
- * @method MessageEntity[] getEntities() Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method LinkPreviewOptions getLinkPreviewOptions() Optional. Link preview generation options for the message
- *
- * @method $this setMessageText(string $message_text) Text of the message to be sent, 1-4096 characters.
- * @method $this setParseMode(string $parse_mode) Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
- * @method $this setEntities(array $entities) Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
- * @method $this setLinkPreviewOptions(LinkPreviewOptions $link_preview_options) Optional. Link preview generation options for the message
+ * @method string getMessageText() Text of the message to be sent, 1-4096 characters
+ * @method string|null getParseMode() Optional. Mode for parsing entities in the message text. See formatting options for more details.
+ * @method MessageEntity[]|null getEntities() Optional. List of special entities that appear in message text, which can be specified instead of parse_mode
+ * @method LinkPreviewOptions|null getLinkPreviewOptions() Optional. Link preview generation options for the message
*/
-class InputTextMessageContent extends InlineEntity implements InputMessageContent
+class InputTextMessageContent extends InputMessageContent
{
-
+ protected static function subEntities(): array
+ {
+ return [
+ 'entities' => [MessageEntity::class],
+ 'link_preview_options' => LinkPreviewOptions::class,
+ ];
+ }
}
diff --git a/src/Entities/InputMessageContent/InputVenueMessageContent.php b/src/Entities/InputMessageContent/InputVenueMessageContent.php
index ec5b12a8e..d17fb4f61 100644
--- a/src/Entities/InputMessageContent/InputVenueMessageContent.php
+++ b/src/Entities/InputMessageContent/InputVenueMessageContent.php
@@ -1,53 +1,18 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\InputMessageContent;
-
-use Longman\TelegramBot\Entities\InlineQuery\InlineEntity;
+namespace PhpTelegramBot\Core\Entities\InputMessageContent;
/**
- * Class InputVenueMessageContent
- *
- * @link https://core.telegram.org/bots/api#inputvenuemessagecontent
- *
- *
- * $data = [
- * 'latitude' => 36.0338,
- * 'longitude' => 71.8601,
- * 'title' => '',
- * 'address' => '',
- * 'foursquare_id' => '',
- * 'foursquare_type' => '',
- * ];
- *
- *
- * @method float getLatitude() Latitude of the location in degrees
- * @method float getLongitude() Longitude of the location in degrees
- * @method string getTitle() Name of the venue
- * @method string getAddress() Address of the venue
- * @method string getFoursquareId() Optional. Foursquare identifier of the venue, if known
- * @method string getFoursquareType() Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
- * @method string getGooglePlaceId() Optional. Google Places identifier of the venue
- * @method string getGooglePlaceType() Optional. Google Places type of the venue
- *
- * @method $this setLatitude(float $latitude) Latitude of the location in degrees
- * @method $this setLongitude(float $longitude) Longitude of the location in degrees
- * @method $this setTitle(string $title) Name of the venue
- * @method $this setAddress(string $address) Address of the venue
- * @method $this setFoursquareId(string $foursquare_id) Optional. Foursquare identifier of the venue, if known
- * @method $this setFoursquareType(string $foursquare_type) Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
- * @method $this setGooglePlaceId(string $google_place_id) Optional. Google Places identifier of the venue
- * @method $this setGooglePlaceType(string $google_place_type) Optional. Google Places type of the venue
+ * @method float getLatitude() Latitude of the venue in degrees
+ * @method float getLongitude() Longitude of the venue in degrees
+ * @method string getTitle() Name of the venue
+ * @method string getAddress() Address of the venue
+ * @method string|null getFoursquareId() Optional. Foursquare identifier of the venue, if known
+ * @method string|null getFoursquareType() Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.).
+ * @method string|null getGooglePlaceId() Optional. Google Places identifier of the venue
+ * @method string|null getGooglePlaceType() Optional. Google Places type of the venue. (See supported types.).
*/
-class InputVenueMessageContent extends InlineEntity implements InputMessageContent
+class InputVenueMessageContent extends InputMessageContent
{
-
+ //
}
diff --git a/src/Entities/InputPaidMedia/InputPaidMedia.php b/src/Entities/InputPaidMedia/InputPaidMedia.php
new file mode 100644
index 000000000..17ab2221d
--- /dev/null
+++ b/src/Entities/InputPaidMedia/InputPaidMedia.php
@@ -0,0 +1,15 @@
+” to upload a new one using multipart/form-data under name.
+ */
+class InputPaidMediaPhoto extends InputPaidMedia
+{
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => self::TYPE_PHOTO,
+ ];
+ }
+}
diff --git a/src/Entities/InputPaidMedia/InputPaidMediaVideo.php b/src/Entities/InputPaidMedia/InputPaidMediaVideo.php
new file mode 100644
index 000000000..549bdc4e7
--- /dev/null
+++ b/src/Entities/InputPaidMedia/InputPaidMediaVideo.php
@@ -0,0 +1,38 @@
+” to upload a new one using multipart/form-data under name. More information on Sending Files »
+ * @method InputFile|string getThumbnail() Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »
+ * @method int|null getWidth() Optional. Video width
+ * @method int|null getHeight() Optional. Video height
+ * @method int|null getDuration() Optional. Video duration in seconds
+ * @method bool|null supportsStreaming() Optional. Pass True if the uploaded video is suitable for streaming
+ */
+class InputPaidMediaVideo extends InputPaidMedia implements AllowsBypassingGet
+{
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => self::TYPE_VIDEO,
+ ];
+ }
+
+ protected static function subEntities(): array
+ {
+ return [
+ 'thumbnail' => InputFile::class,
+ ];
+ }
+
+ public static function fieldsBypassingGet(): array
+ {
+ return [
+ 'supports_streaming' => false,
+ ];
+ }
+}
diff --git a/src/Entities/InputPollOption.php b/src/Entities/InputPollOption.php
new file mode 100644
index 000000000..9b8957a09
--- /dev/null
+++ b/src/Entities/InputPollOption.php
@@ -0,0 +1,18 @@
+ [MessageEntity::class],
+ ];
+ }
+}
diff --git a/src/Entities/InputSticker.php b/src/Entities/InputSticker.php
index 2fa40e018..eb40b1470 100644
--- a/src/Entities/InputSticker.php
+++ b/src/Entities/InputSticker.php
@@ -1,20 +1,21 @@
” to upload a new one using multipart/form-data under name. Animated and video stickers can't be uploaded via HTTP URL. More information on Sending Files »
- * @method string[] getEmojiList() List of 1-20 emoji associated with the sticker
- * @method MaskPosition getMaskPosition() Optional. Position where the mask should be placed on faces. For “mask” stickers only.
- * @method string[] getKeywords() Optional. List of 0-20 search keywords for the sticker with total length of up to 64 characters. For “regular” and “custom_emoji” stickers only.
+ * @method InputFile|string getSticker() The added sticker. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, upload a new one using multipart/form-data, or pass “attach://” to upload a new one using multipart/form-data under name. Animated and video stickers can't be uploaded via HTTP URL.
+ * @method string getFormat() Format of the added sticker, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, “video” for a WEBM video
+ * @method string[] getEmojiList() List of 1-20 emoji associated with the sticker
+ * @method MaskPosition|null getMaskPosition() Optional. Position where the mask should be placed on faces. For “mask” stickers only.
+ * @method string[]|null getKeywords() Optional. List of 0-20 search keywords for the sticker with total length of up to 64 characters. For “regular” and “custom_emoji” stickers only.
*/
class InputSticker extends Entity
{
-
+ protected static function subEntities(): array
+ {
+ return [
+ 'sticker' => InputFile::class,
+ 'mask_position' => MaskPosition::class,
+ ];
+ }
}
diff --git a/src/Entities/Invoice.php b/src/Entities/Invoice.php
new file mode 100644
index 000000000..ee34fbf24
--- /dev/null
+++ b/src/Entities/Invoice.php
@@ -0,0 +1,15 @@
+
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- *
- * Written by Marco Boretto
- */
-
-namespace Longman\TelegramBot\Entities;
-
-use Longman\TelegramBot\Exception\TelegramException;
-
-/**
- * Class Keyboard
- *
- * @link https://core.telegram.org/bots/api#replykeyboardmarkup
- *
- * @method bool getIsPersistent() Optional. Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to false, in which case the custom keyboard can be hidden and opened with a keyboard icon.
- * @method bool getResizeKeyboard() Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.
- * @method bool getOneTimeKeyboard() Optional. Requests clients to remove the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat – the user can press a special button in the input field to see the custom keyboard again. Defaults to false.
- * @method string getInputFieldPlaceholder() Optional. The placeholder to be shown in the input field when the keyboard is active; 1-64 characters
- * @method bool getSelective() Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
- *
- * @method $this setIsPersistent(bool $is_persistent) Optional. Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to false, in which case the custom keyboard can be hidden and opened with a keyboard icon.
- * @method $this setResizeKeyboard(bool $resize_keyboard) Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.
- * @method $this setOneTimeKeyboard(bool $one_time_keyboard) Optional. Requests clients to remove the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat – the user can press a special button in the input field to see the custom keyboard again. Defaults to false.
- * @method $this setInputFieldPlaceholder(string $input_field_placeholder) Optional. The placeholder to be shown in the input field when the keyboard is active; 1-64 characters
- * @method $this setSelective(bool $selective) Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
- */
-class Keyboard extends Entity
-{
- public function __construct()
- {
- $data = $this->createFromParams(...func_get_args());
- parent::__construct($data);
-
- // Remove any empty buttons.
- $this->{$this->getKeyboardType()} = array_filter($this->{$this->getKeyboardType()});
- }
-
- /**
- * If this keyboard is an inline keyboard.
- *
- * @return bool
- */
- public function isInlineKeyboard(): bool
- {
- return $this instanceof InlineKeyboard;
- }
-
- /**
- * Get the proper keyboard button class for this keyboard.
- *
- * @return string
- */
- public function getKeyboardButtonClass(): string
- {
- return $this->isInlineKeyboard() ? InlineKeyboardButton::class : KeyboardButton::class;
- }
-
- /**
- * Get the type of keyboard, either "inline_keyboard" or "keyboard".
- *
- * @return string
- */
- public function getKeyboardType(): string
- {
- return $this->isInlineKeyboard() ? 'inline_keyboard' : 'keyboard';
- }
-
- /**
- * If no explicit keyboard is passed, try to create one from the parameters.
- *
- * @return array
- */
- protected function createFromParams(): array
- {
- $keyboard_type = $this->getKeyboardType();
-
- $args = func_get_args();
-
- // Force button parameters into individual rows.
- foreach ($args as &$arg) {
- !is_array($arg) && $arg = [$arg];
- }
- unset($arg);
-
- $data = reset($args);
-
- if ($from_data = array_key_exists($keyboard_type, (array) $data)) {
- $args = $data[$keyboard_type];
-
- // Make sure we're working with a proper row.
- if (!is_array($args)) {
- $args = [];
- }
- }
-
- $new_keyboard = [];
- foreach ($args as $row) {
- $new_keyboard[] = $this->parseRow($row);
- }
-
- if (!empty($new_keyboard)) {
- if (!$from_data) {
- $data = [];
- }
- $data[$keyboard_type] = $new_keyboard;
- }
-
- // If $args was empty, $data still contains `false`
- return $data ?: [];
- }
-
- /**
- * Create a new row in keyboard and add buttons.
- *
- * @return Keyboard
- */
- public function addRow(): Keyboard
- {
- if (($new_row = $this->parseRow(func_get_args())) !== null) {
- // Workaround for "Indirect modification of overloaded property has no effect" notice in PHP 8.2.
- // https://stackoverflow.com/a/19749730/3757422
- $keyboard = $this->{$this->getKeyboardType()};
- $keyboard[] = $new_row;
- $this->{$this->getKeyboardType()} = $keyboard;
- }
-
- return $this;
- }
-
- /**
- * Parse a given row to the correct array format.
- *
- * @param array|string $row
- *
- * @return array|null
- */
- protected function parseRow($row): ?array
- {
- if (!is_array($row)) {
- return null;
- }
-
- $new_row = [];
- foreach ($row as $button) {
- if (($new_button = $this->parseButton($button)) !== null) {
- $new_row[] = $new_button;
- }
- }
-
- return $new_row;
- }
-
- /**
- * Parse a given button to the correct KeyboardButton object type.
- *
- * @param array|string|KeyboardButton $button
- *
- * @return KeyboardButton|null
- */
- protected function parseButton($button): ?KeyboardButton
- {
- $button_class = $this->getKeyboardButtonClass();
-
- if ($button instanceof $button_class) {
- return $button;
- }
-
- if (!$this->isInlineKeyboard() || call_user_func([$button_class, 'couldBe'], $button)) {
- return new $button_class($button);
- }
-
- return null;
- }
-
- /**
- * {@inheritdoc}
- */
- protected function validate(): void
- {
- $keyboard_type = $this->getKeyboardType();
- $keyboard = $this->getProperty($keyboard_type);
-
- if ($keyboard !== null) {
- if (!is_array($keyboard)) {
- throw new TelegramException($keyboard_type . ' field is not an array!');
- }
-
- foreach ($keyboard as $item) {
- if (!is_array($item)) {
- throw new TelegramException($keyboard_type . ' subfield is not an array!');
- }
- }
- }
- }
-
- /**
- * Remove the current custom keyboard and display the default letter-keyboard.
- *
- * @link https://core.telegram.org/bots/api/#replykeyboardremove
- *
- * @param array $data
- *
- * @return Keyboard
- */
- public static function remove(array $data = []): Keyboard
- {
- return new static(array_merge(['keyboard' => [], 'remove_keyboard' => true, 'selective' => false], $data));
- }
-
- /**
- * Display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply').
- *
- * @link https://core.telegram.org/bots/api#forcereply
- *
- * @param array $data
- *
- * @return Keyboard
- */
- public static function forceReply(array $data = []): Keyboard
- {
- return new static(array_merge(['keyboard' => [], 'force_reply' => true, 'selective' => false], $data));
- }
-}
diff --git a/src/Entities/KeyboardButton.php b/src/Entities/KeyboardButton.php
index 25cc7f043..fc9a90813 100644
--- a/src/Entities/KeyboardButton.php
+++ b/src/Entities/KeyboardButton.php
@@ -1,60 +1,19 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class KeyboardButton
- *
- * This object represents one button of the reply keyboard. For simple text buttons String can be used instead of this object to specify text of the button. Optional fields request_contact, request_location, and request_poll are mutually exclusive.
- *
- * @link https://core.telegram.org/bots/api#keyboardbutton
- *
- * @property KeyboardButtonRequestUsers $request_users
- * @property KeyboardButtonRequestChat $request_chat
- * @property bool $request_contact
- * @property bool $request_location
- * @property KeyboardButtonPollType $request_poll
- * @property WebAppInfo $web_app
- *
- * @method string getText() Text of the button. If none of the optional fields are used, it will be sent to the bot as a message when the button is pressed
- * @method KeyboardButtonRequestUsers getRequestUsers() Optional. If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only.
- * @method KeyboardButtonRequestChat getRequestChat() Optional. If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only.
- * @method bool getRequestContact() Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only
- * @method bool getRequestLocation() Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only
- * @method KeyboardButtonPollType getRequestPoll() Optional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only
- * @method WebAppInfo getWebApp() Optional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only.
- *
- * @method $this setText(string $text) Text of the button. If none of the optional fields are used, it will be sent to the bot as a message when the button is pressed
- * @method $this setRequestUsers(KeyboardButtonRequestUsers $request_users) Optional. If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only.
- * @method $this setRequestChat(KeyboardButtonRequestChat $request_chat) Optional. If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only.
- * @method $this setRequestContact(bool $request_contact) Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only
- * @method $this setRequestLocation(bool $request_location) Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only
- * @method $this setRequestPoll(KeyboardButtonPollType $request_poll) Optional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only
- * @method $this setWebApp(WebAppInfo $web_app) Optional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only.
+ * @method string getText() Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed
+ * @method KeyboardButtonRequestUsers|null getRequestUsers() Optional. If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only.
+ * @method KeyboardButtonRequestChat|null getRequestChat() Optional. If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only.
+ * @method bool|null getRequestContact() Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only.
+ * @method bool|null getRequestLocation() Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only.
+ * @method KeyboardButtonPollType|null getRequestPoll() Optional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only.
+ * @method WebAppInfo|null getWebApp() Optional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only.
*/
class KeyboardButton extends Entity
{
- /**
- * @param array|string $data
- */
- public function __construct($data)
- {
- if (is_string($data)) {
- $data = ['text' => $data];
- }
- parent::__construct($data);
- }
-
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'request_users' => KeyboardButtonRequestUsers::class,
@@ -63,29 +22,4 @@ protected function subEntities(): array
'web_app' => WebAppInfo::class,
];
}
-
- /**
- * Check if the passed data array could be a KeyboardButton.
- *
- * @param array $data
- *
- * @return bool
- */
- public static function couldBe(array $data): bool
- {
- return array_key_exists('text', $data);
- }
-
- /**
- * {@inheritdoc}
- */
- public function __call($method, $args)
- {
- // Only 1 of these can be set, so clear the others when setting a new one.
- if (in_array($method, ['setRequestUsers', 'setRequestChat', 'setRequestContact', 'setRequestLocation', 'setRequestPoll', 'setWebApp'], true)) {
- unset($this->request_users, $this->request_chat, $this->request_contact, $this->request_location, $this->request_poll, $this->web_app);
- }
-
- return parent::__call($method, $args);
- }
}
diff --git a/src/Entities/KeyboardButtonPollType.php b/src/Entities/KeyboardButtonPollType.php
index f11023123..361ee418b 100644
--- a/src/Entities/KeyboardButtonPollType.php
+++ b/src/Entities/KeyboardButtonPollType.php
@@ -1,28 +1,11 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class KeyboardButtonPollType
- *
- * This entity represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed.
- *
- * @link https://core.telegram.org/bots/api#keyboardbutton
- *
- * @method string getType() Optional. If 'quiz' is passed, the user will be allowed to create only polls in the quiz mode. If 'regular' is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type.
- *
- * @method $this setType(string $type) Optional. If 'quiz' is passed, the user will be allowed to create only polls in the quiz mode. If 'regular' is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type.
+ * @method string|null getType() Optional. If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type.
*/
class KeyboardButtonPollType extends Entity
{
-
+ //
}
diff --git a/src/Entities/KeyboardButtonRequestChat.php b/src/Entities/KeyboardButtonRequestChat.php
index 02cdf29fe..aa26d4a3e 100644
--- a/src/Entities/KeyboardButtonRequestChat.php
+++ b/src/Entities/KeyboardButtonRequestChat.php
@@ -1,33 +1,27 @@
ChatAdministratorRights::class,
+ 'bot_administrator_rights' => ChatAdministratorRights::class,
+ ];
+ }
}
diff --git a/src/Entities/KeyboardButtonRequestUsers.php b/src/Entities/KeyboardButtonRequestUsers.php
index 945bafa9b..adbb0902c 100644
--- a/src/Entities/KeyboardButtonRequestUsers.php
+++ b/src/Entities/KeyboardButtonRequestUsers.php
@@ -1,23 +1,17 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+namespace PhpTelegramBot\Core\Entities;
-namespace Longman\TelegramBot\Entities;
+use PhpTelegramBot\Core\Contracts\AllowsBypassingGet;
/**
- * Describes the options used for link preview generation.
- *
- * @link https://core.telegram.org/bots/api#linkpreviewoptions
- *
- * @method bool getIsDisabled() Optional. True, if the link preview is disabled
- * @method string getUrl() Optional. URL to use for the link preview. If empty, then the first URL found in the message text will be used
- * @method bool getPreferSmallMedia() Optional. True, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview
- * @method bool getPreferLargeMedia() Optional. True, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview
- * @method bool getShowAboveText() Optional. True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text *
+ * @method bool isDisabled() Optional. True, if the link preview is disabled
+ * @method string|null getUrl() Optional. URL to use for the link preview. If empty, then the first URL found in the message text will be used
+ * @method bool|null getPreferSmallMedia() Optional. True, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview
+ * @method bool|null getPreferLargeMedia() Optional. True, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview
+ * @method bool|null getShowAboveText() Optional. True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text
*/
-class LinkPreviewOptions extends Entity
+class LinkPreviewOptions extends Entity implements AllowsBypassingGet
{
-
+ //
+ public static function fieldsBypassingGet(): array
+ {
+ return [
+ 'is_disabled'=> false,
+ ];
+ }
}
diff --git a/src/Entities/Location.php b/src/Entities/Location.php
index b4c67fe52..57946d02b 100644
--- a/src/Entities/Location.php
+++ b/src/Entities/Location.php
@@ -1,29 +1,16 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class Location
- *
- * @link https://core.telegram.org/bots/api#location
- *
- * @method float getLongitude() Longitude as defined by sender
- * @method float getLatitude() Latitude as defined by sender
- * @method float getHorizontalAccuracy() Optional. The radius of uncertainty for the location, measured in meters; 0-1500
- * @method int getLivePeriod() Optional. Time relative to the message sending date, during which the location can be updated, in seconds. For active live locations only.
- * @method int getHeading() Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only.
- * @method int getProximityAlertRadius() Optional. Maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only.
+ * @method float getLatitude() Latitude as defined by sender
+ * @method float getLongitude() Longitude as defined by sender
+ * @method float|null getHorizontalAccuracy() Optional. The radius of uncertainty for the location, measured in meters; 0-1500
+ * @method int|null getLivePeriod() Optional. Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only.
+ * @method int|null getHeading() Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only.
+ * @method int|null getProximityAlertRadius() Optional. The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only.
*/
class Location extends Entity
{
-
+ //
}
diff --git a/src/Entities/LoginUrl.php b/src/Entities/LoginUrl.php
index 9d4c22a6b..fd34986cf 100644
--- a/src/Entities/LoginUrl.php
+++ b/src/Entities/LoginUrl.php
@@ -1,29 +1,14 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class LoginUrl
- *
- * This object represents a parameter of the inline keyboard button used to automatically authorize a user.
- *
- * @link https://core.telegram.org/bots/api#loginurl
- *
- * @method string getUrl() An HTTP URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data.
- * @method string getForwardText() Optional. New text of the button in forwarded messages.
- * @method string getBotUsername() Optional. Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details.
- * @method bool getRequestWriteAccess() Optional. Pass True to request the permission for your bot to send messages to the user.
+ * @method string getUrl() An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data.
+ * @method string|null getForwardText() Optional. New text of the button in forwarded messages.
+ * @method string|null getBotUsername() Optional. Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details.
+ * @method bool|null getRequestWriteAccess() Optional. Pass True to request the permission for your bot to send messages to the user.
*/
class LoginUrl extends Entity
{
-
+ //
}
diff --git a/src/Entities/MaskPosition.php b/src/Entities/MaskPosition.php
index 76b62425b..a2d623ccb 100644
--- a/src/Entities/MaskPosition.php
+++ b/src/Entities/MaskPosition.php
@@ -1,21 +1,8 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class MaskPosition
- *
- * @link https://core.telegram.org/bots/api#maskposition
- *
* @method string getPoint() The part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or “chin”.
* @method float getXShift() Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position.
* @method float getYShift() Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position.
@@ -23,5 +10,11 @@
*/
class MaskPosition extends Entity
{
+ public const POINT_FOREHEAD = 'forehead';
+
+ public const POINT_EYES = 'eyes';
+
+ public const POINT_MOUTH = 'mouth';
+ public const POINT_CHIN = 'chin';
}
diff --git a/src/Entities/MaybeInaccessibleMessage.php b/src/Entities/MaybeInaccessibleMessage.php
new file mode 100644
index 000000000..41bde29a6
--- /dev/null
+++ b/src/Entities/MaybeInaccessibleMessage.php
@@ -0,0 +1,28 @@
+ new InaccessibleMessage($data),
+ default => new Message($data),
+ };
+ }
+
+ protected static function subEntities(): array
+ {
+ return [
+ 'chat' => Chat::class,
+ ];
+ }
+}
diff --git a/src/Entities/MenuButton/Factory.php b/src/Entities/MenuButton/Factory.php
deleted file mode 100644
index 86fbf9fa4..000000000
--- a/src/Entities/MenuButton/Factory.php
+++ /dev/null
@@ -1,24 +0,0 @@
- MenuButtonCommands::class,
- 'web_app' => MenuButtonWebApp::class,
- 'default' => MenuButtonDefault::class,
- ];
-
- if (! isset($type[$data['type'] ?? ''])) {
- return new MenuButtonNotImplemented($data, $bot_username);
- }
-
- $class = $type[$data['type']];
- return new $class($data, $bot_username);
- }
-}
diff --git a/src/Entities/MenuButton/MenuButton.php b/src/Entities/MenuButton/MenuButton.php
index 216d947ae..31f30fe3e 100644
--- a/src/Entities/MenuButton/MenuButton.php
+++ b/src/Entities/MenuButton/MenuButton.php
@@ -1,15 +1,27 @@
new MenuButtonCommands($data),
+ self::TYPE_WEB_APP => new MenuButtonWebApp($data),
+ self::TYPE_DEFAULT => new MenuButtonDefault($data),
+ };
+ }
}
diff --git a/src/Entities/MenuButton/MenuButtonCommands.php b/src/Entities/MenuButton/MenuButtonCommands.php
index 87a9168c1..21dee21a1 100644
--- a/src/Entities/MenuButton/MenuButtonCommands.php
+++ b/src/Entities/MenuButton/MenuButtonCommands.php
@@ -1,15 +1,13 @@
self::TYPE_COMMANDS,
+ ];
}
}
diff --git a/src/Entities/MenuButton/MenuButtonDefault.php b/src/Entities/MenuButton/MenuButtonDefault.php
index 96df21952..7ce86c2e4 100644
--- a/src/Entities/MenuButton/MenuButtonDefault.php
+++ b/src/Entities/MenuButton/MenuButtonDefault.php
@@ -1,15 +1,13 @@
self::TYPE_DEFAULT,
+ ];
}
}
diff --git a/src/Entities/MenuButton/MenuButtonNotImplemented.php b/src/Entities/MenuButton/MenuButtonNotImplemented.php
deleted file mode 100644
index 8db8ded05..000000000
--- a/src/Entities/MenuButton/MenuButtonNotImplemented.php
+++ /dev/null
@@ -1,8 +0,0 @@
- WebAppInfo::class,
+ ];
}
- protected function subEntities(): array
+ protected static function presetData(): array
{
return [
- 'web_app' => WebAppInfo::class,
+ 'type' => self::TYPE_WEB_APP,
];
}
}
diff --git a/src/Entities/Message.php b/src/Entities/Message.php
index 8f771a305..b8c0b6cbe 100644
--- a/src/Entities/Message.php
+++ b/src/Entities/Message.php
@@ -1,137 +1,117 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+namespace PhpTelegramBot\Core\Entities;
-namespace Longman\TelegramBot\Entities;
-
-use Longman\TelegramBot\Entities\Games\Game;
-use Longman\TelegramBot\Entities\Giveaway\Giveaway;
-use Longman\TelegramBot\Entities\Giveaway\GiveawayCompleted;
-use Longman\TelegramBot\Entities\Giveaway\GiveawayCreated;
-use Longman\TelegramBot\Entities\Giveaway\GiveawayWinners;
-use Longman\TelegramBot\Entities\Message\Factory as MaybeInaccessibleMessageFactory;
-use Longman\TelegramBot\Entities\Message\MaybeInaccessibleMessage;
-use Longman\TelegramBot\Entities\MessageOrigin\Factory as MessageOriginFactory;
-use Longman\TelegramBot\Entities\MessageOrigin\MessageOrigin;
-use Longman\TelegramBot\Entities\Payments\Invoice;
-use Longman\TelegramBot\Entities\Payments\SuccessfulPayment;
-use Longman\TelegramBot\Entities\TelegramPassport\PassportData;
-use Longman\TelegramBot\Entities\Topics\ForumTopicClosed;
-use Longman\TelegramBot\Entities\Topics\ForumTopicCreated;
-use Longman\TelegramBot\Entities\Topics\ForumTopicEdited;
-use Longman\TelegramBot\Entities\Topics\ForumTopicReopened;
-use Longman\TelegramBot\Entities\Topics\GeneralForumTopicHidden;
-use Longman\TelegramBot\Entities\Topics\GeneralForumTopicUnhidden;
+use PhpTelegramBot\Core\Contracts\AllowsBypassingGet;
+use PhpTelegramBot\Core\Entities\MessageOrigin\MessageOrigin;
/**
- * Class Message
- *
- * Represents a message
- *
- * @link https://core.telegram.org/bots/api#message
- *
- * @method int getMessageId() Unique message identifier
- * @method int getMessageThreadId() Optional. Unique identifier of a message thread to which the message belongs; for supergroups only
- * @method User getFrom() Optional. Sender, can be empty for messages sent to channels
- * @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
- * @method int getDate() Date the message was sent in Unix time
- * @method Chat getChat() Conversation the message belongs to
- * @method MessageOrigin getForwardOrigin() Optional. Information about the original message for forwarded messages
- * @method bool getIsTopicMessage() Optional. True, if the message is sent to a forum topic
- * @method bool getIsAutomaticForward() Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
- * @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.
- * @method ExternalReplyInfo getExternalReply() Optional. Information about the message that is being replied to, which may come from another chat or forum topic
- * @method TextQuote getQuote() Optional. For replies that quote part of the original message, the quoted part of the message
- * @method User getViaBot() Optional. Bot through which the message was sent
- * @method int getEditDate() Optional. Date the message was last edited in Unix time
- * @method bool getHasProtectedContent() Optional. True, if the message can't be forwarded
- * @method string getMediaGroupId() Optional. The unique identifier of a media message group this message belongs to
- * @method string getAuthorSignature() Optional. Signature of the post author for messages in channels
- * @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
- * @method MessageEntity[] getEntities() Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
- * @method MessageEntity[] getCaptionEntities() Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
- * @method Audio getAudio() Optional. Message is an audio file, information about the file
- * @method Document getDocument() Optional. Message is a general file, information about the file
- * @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
- * @method Game getGame() Optional. Message is a game, information about the game.
- * @method PhotoSize[] getPhoto() Optional. Message is a photo, available sizes of the photo
- * @method Sticker getSticker() Optional. Message is a sticker, information about the sticker
- * @method Story getStory() Optional. Message is a forwarded story
- * @method Video getVideo() Optional. Message is a video, information about the video
- * @method Voice getVoice() Optional. Message is a voice message, information about the file
- * @method VideoNote getVideoNote() Optional. Message is a video note message, information about the video
- * @method string getCaption() Optional. Caption for the document, photo or video, 0-200 characters
- * @method bool getHasMediaSpoiler() Optional. True, if the message media is covered by a spoiler animation
- * @method Contact getContact() Optional. Message is a shared contact, information about the contact
- * @method Location getLocation() Optional. Message is a shared location, information about the location
- * @method Venue getVenue() Optional. Message is a venue, information about the venue
- * @method Poll getPoll() Optional. Message is a native poll, information about the poll
- * @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
- * @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)
- * @method User getLeftChatMember() Optional. A member was removed from the group, information about them (this member may be the bot itself)
- * @method string getNewChatTitle() Optional. A chat title was changed to this value
- * @method PhotoSize[] getNewChatPhoto() Optional. A chat photo was changed to this value
- * @method MessageAutoDeleteTimerChanged getMessageAutoDeleteTimerChanged() Optional. Service message: auto-delete timer settings changed in the chat
- * @method bool getDeleteChatPhoto() Optional. Service message: the chat photo was deleted
- * @method bool getGroupChatCreated() Optional. Service message: the group has been created
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method Invoice getInvoice() Optional. Message is an invoice for a payment, information about the invoice.
- * @method SuccessfulPayment getSuccessfulPayment() Optional. Message is a service message about a successful payment, information about the payment.
- * @method UsersShared getUsersShared() Optional. Service message: users were shared with the bot
- * @method ChatShared getChatShared() Optional. Service message: a chat was shared with the bot
- * @method string getConnectedWebsite() Optional. The domain name of the website on which the user has logged in.
- * @method WriteAccessAllowed getWriteAccessAllowed() Optional. Service message: the user allowed the bot added to the attachment menu to write messages
- * @method PassportData getPassportData() Optional. Telegram Passport data
- * @method ProximityAlertTriggered getProximityAlertTriggered() Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.
- * @method ForumTopicCreated getForumTopicCreated() Optional. Service message: forum topic created
- * @method ForumTopicEdited getForumTopicEdited() Optional. Service message: forum topic edited
- * @method ForumTopicClosed getForumTopicClosed() Optional. Service message: forum topic closed
- * @method ForumTopicReopened getForumTopicReopened() Optional. Service message: forum topic reopened
- * @method GeneralForumTopicHidden getGeneralForumTopicHidden() Optional. Service message: the 'General' forum topic hidden
- * @method GeneralForumTopicUnhidden getGeneralForumTopicUnhidden() Optional. Service message: the 'General' forum topic unhidden
- * @method GiveawayCreated getGiveawayCreated() Optional. Service message: a scheduled giveaway was created
- * @method Giveaway getGiveaway() Optional. The message is a scheduled giveaway message
- * @method GiveawayWinners getGiveawayWinners() Optional. A giveaway with public winners was completed
- * @method GiveawayCompleted getGiveawayCompleted() Optional. Service message: a giveaway without public winners was completed
- * @method VideoChatScheduled getVideoChatScheduled() Optional. Service message: voice chat scheduled
- * @method VideoChatStarted getVideoChatStarted() Optional. Service message: voice chat started
- * @method VideoChatEnded getVideoChatEnded() Optional. Service message: voice chat ended
- * @method VideoChatParticipantsInvited getVideoChatParticipantsInvited() Optional. Service message: new participants invited to a voice chat
- * @method WebAppData getWebAppData() Optional. Service message: data sent by a Web App
- * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
+ * @method int getMessageId() Unique message identifier inside this chat
+ * @method int|null getMessageThreadId() Optional. Unique identifier of a message thread to which the message belongs; for supergroups only
+ * @method User|null getFrom() Optional. Sender of the message; empty for messages sent to channels. For backward compatibility, the field contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
+ * @method Chat|null getSenderChat() Optional. Sender of the message, sent on behalf of a chat. For example, the channel itself for channel posts, the supergroup itself for messages from anonymous group administrators, the linked channel for messages automatically forwarded to the discussion group. For backward compatibility, the field from contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
+ * @method int|null getSenderBoostCount() Optional. If the sender of the message boosted the chat, the number of boosts added by the user
+ * @method User|null getSenderBusinessBot() Optional. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account.
+ * @method int getDate() Date the message was sent in Unix time. It is always a positive number, representing a valid date.
+ * @method string|null getBusinessConnectionId() Optional. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.
+ * @method Chat getChat() Chat the message belongs to
+ * @method MessageOrigin|null getForwardOrigin() Optional. Information about the original message for forwarded messages
+ * @method bool isTopicMessage() Optional. True, if the message is sent to a forum topic
+ * @method bool isAutomaticForward() Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
+ * @method Message|null getReplyToMessage() Optional. For replies in the same chat and message thread, 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.
+ * @method ExternalReplyInfo|null getExternalReply() Optional. Information about the message that is being replied to, which may come from another chat or forum topic
+ * @method TextQuote|null getQuote() Optional. For replies that quote part of the original message, the quoted part of the message
+ * @method Story|null getReplyToStory() Optional. For replies to a story, the original story
+ * @method User|null getViaBot() Optional. Bot through which the message was sent
+ * @method int|null getEditDate() Optional. Date the message was last edited in Unix time
+ * @method bool hasProtectedContent() Optional. True, if the message can't be forwarded
+ * @method bool isFromOffline() Optional. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message
+ * @method string|null getMediaGroupId() Optional. The unique identifier of a media message group this message belongs to
+ * @method string|null getAuthorSignature() Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator
+ * @method string|null getText() Optional. For text messages, the actual UTF-8 text of the message
+ * @method MessageEntity[]|null getEntities() Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
+ * @method LinkPreviewOptions|null getLinkPreviewOptions() Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed
+ * @method string|null getEffectId() Optional. Unique identifier of the message effect added to the message
+ * @method Animation|null 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
+ * @method Audio|null getAudio() Optional. Message is an audio file, information about the file
+ * @method Document|null getDocument() Optional. Message is a general file, information about the file
+ * @method PaidMediaInfo|null getPaidMedia() Optional. Message contains paid media; information about the paid media
+ * @method PhotoSize[]|null getPhoto() Optional. Message is a photo, available sizes of the photo
+ * @method Sticker|null getSticker() Optional. Message is a sticker, information about the sticker
+ * @method Story|null getStory() Optional. Message is a forwarded story
+ * @method Video|null getVideo() Optional. Message is a video, information about the video
+ * @method VideoNote|null getVideoNote() Optional. Message is a video note, information about the video message
+ * @method Voice|null getVoice() Optional. Message is a voice message, information about the file
+ * @method string|null getCaption() Optional. Caption for the animation, audio, document, photo, video or voice
+ * @method MessageEntity[]|null getCaptionEntities() Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
+ * @method true|null getShowCaptionAboveMedia() Optional. True, if the caption must be shown above the message media
+ * @method bool hasMediaSpoiler() Optional. True, if the message media is covered by a spoiler animation
+ * @method Contact|null getContact() Optional. Message is a shared contact, information about the contact
+ * @method Dice|null getDice() Optional. Message is a dice with random value
+ * @method Game|null getGame() Optional. Message is a game, information about the game.
+ * @method Poll|null getPoll() Optional. Message is a native poll, information about the poll
+ * @method Venue|null getVenue() Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set
+ * @method Location|null getLocation() Optional. Message is a shared location, information about the location
+ * @method User[]|null getNewChatMembers() Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members).
+ * @method User|null getLeftChatMember() Optional. A member was removed from the group, information about them (this member may be the bot itself).
+ * @method string|null getNewChatTitle() Optional. A chat title was changed to this value
+ * @method PhotoSize[]|null getNewChatPhoto() Optional. A chat photo was change to this value
+ * @method true|null getDeleteChatPhoto() Optional. Service message: the chat photo was deleted
+ * @method true|null getGroupChatCreated() Optional. Service message: the group has been created
+ * @method true|null 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.
+ * @method true|null 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.
+ * @method MessageAutoDeleteTimerChanged|null getMessageAutoDeleteTimerChanged() Optional. Service message: auto-delete timer settings changed in the chat
+ * @method int|null getMigrateToChatId() Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
+ * @method int|null getMigrateFromChatId() Optional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
+ * @method MaybeInaccessibleMessage|null 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 itself is a reply.
+ * @method Invoice|null getInvoice() Optional. Message is an invoice for a payment, information about the invoice.
+ * @method SuccessfulPayment|null getSuccessfulPayment() Optional. Message is a service message about a successful payment, information about the payment.
+ * @method UsersShared|null getUsersShared() Optional. Service message: users were shared with the bot
+ * @method ChatShared|null getChatShared() Optional. Service message: a chat was shared with the bot
+ * @method string|null getConnectedWebsite() Optional. The domain name of the website on which the user has logged in.
+ * @method WriteAccessAllowed|null getWriteAccessAllowed() Optional. Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess
+ * @method PassportData|null getPassportData() Optional. Telegram Passport data
+ * @method ProximityAlertTriggered|null getProximityAlertTriggered() Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.
+ * @method ChatBoostAdded|null getBoostAdded() Optional. Service message: user boosted the chat
+ * @method ChatBackground|null getChatBackgroundSet() Optional. Service message: chat background set
+ * @method ForumTopicCreated|null getForumTopicCreated() Optional. Service message: forum topic created
+ * @method ForumTopicEdited|null getForumTopicEdited() Optional. Service message: forum topic edited
+ * @method ForumTopicClosed|null getForumTopicClosed() Optional. Service message: forum topic closed
+ * @method ForumTopicReopened|null getForumTopicReopened() Optional. Service message: forum topic reopened
+ * @method GeneralForumTopicHidden|null getGeneralForumTopicHidden() Optional. Service message: the 'General' forum topic hidden
+ * @method GeneralForumTopicUnhidden|null getGeneralForumTopicUnhidden() Optional. Service message: the 'General' forum topic unhidden
+ * @method GiveawayCreated|null getGiveawayCreated() Optional. Service message: a scheduled giveaway was created
+ * @method Giveaway|null getGiveaway() Optional. The message is a scheduled giveaway message
+ * @method GiveawayWinners|null getGiveawayWinners() Optional. A giveaway with public winners was completed
+ * @method GiveawayCompleted|null getGiveawayCompleted() Optional. Service message: a giveaway without public winners was completed
+ * @method VideoChatScheduled|null getVideoChatScheduled() Optional. Service message: video chat scheduled
+ * @method VideoChatStarted|null getVideoChatStarted() Optional. Service message: video chat started
+ * @method VideoChatEnded|null getVideoChatEnded() Optional. Service message: video chat ended
+ * @method VideoChatParticipantsInvited|null getVideoChatParticipantsInvited() Optional. Service message: new participants invited to a video chat
+ * @method WebAppData|null getWebAppData() Optional. Service message: data sent by a Web App
+ * @method InlineKeyboardMarkup getReplyMarkup() Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
*/
-class Message extends Entity implements MaybeInaccessibleMessage
+class Message extends MaybeInaccessibleMessage implements AllowsBypassingGet
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'from' => User::class,
'sender_chat' => Chat::class,
+ 'sender_business_bot' => User::class,
'chat' => Chat::class,
- 'forward_origin' => MessageOriginFactory::class,
- 'reply_to_message' => ReplyToMessage::class,
+ 'forward_origin' => MessageOrigin::class,
+ 'reply_to_message' => Message::class,
'external_reply' => ExternalReplyInfo::class,
'quote' => TextQuote::class,
+ 'reply_to_story' => Story::class,
'via_bot' => User::class,
- 'link_preview_options' => LinkPreviewOptions::class,
'entities' => [MessageEntity::class],
+ 'link_preview_options' => LinkPreviewOptions::class,
'animation' => Animation::class,
'audio' => Audio::class,
'document' => Document::class,
+ 'paid_media' => PaidMediaInfo::class,
'photo' => [PhotoSize::class],
'sticker' => Sticker::class,
'story' => Story::class,
@@ -149,7 +129,7 @@ protected function subEntities(): array
'left_chat_member' => User::class,
'new_chat_photo' => [PhotoSize::class],
'message_auto_delete_timer_changed' => MessageAutoDeleteTimerChanged::class,
- 'pinned_message' => MaybeInaccessibleMessageFactory::class,
+ 'pinned_message' => MaybeInaccessibleMessage::class,
'invoice' => Invoice::class,
'successful_payment' => SuccessfulPayment::class,
'users_shared' => UsersShared::class,
@@ -157,6 +137,8 @@ protected function subEntities(): array
'write_access_allowed' => WriteAccessAllowed::class,
'passport_data' => PassportData::class,
'proximity_alert_triggered' => ProximityAlertTriggered::class,
+ 'boost_added' => ChatBoostAdded::class,
+ 'chat_background_set' => ChatBackground::class,
'forum_topic_created' => ForumTopicCreated::class,
'forum_topic_edited' => ForumTopicEdited::class,
'forum_topic_closed' => ForumTopicClosed::class,
@@ -172,166 +154,18 @@ protected function subEntities(): array
'video_chat_ended' => VideoChatEnded::class,
'video_chat_participants_invited' => VideoChatParticipantsInvited::class,
'web_app_data' => WebAppData::class,
- 'reply_markup' => InlineKeyboard::class,
+ 'reply_markup' => InlineKeyboardMarkup::class,
];
}
- /**
- * return the entire command like /echo or /echo@bot1 if specified
- *
- * @return string|null
- */
- public function getFullCommand(): ?string
- {
- $text = $this->getProperty('text') ?? '';
- if (strpos($text, '/') !== 0) {
- return null;
- }
-
- $no_EOL = strtok($text, PHP_EOL);
- $no_space = strtok($text, ' ');
-
- //try to understand which separator \n or space divide /command from text
- return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL;
- }
-
- /**
- * Get command
- *
- * @return string|null
- */
- public function getCommand(): ?string
+ public static function fieldsBypassingGet(): array
{
- if ($command = $this->getProperty('command')) {
- return $command;
- }
-
- $full_command = $this->getFullCommand() ?? '';
- if (strpos($full_command, '/') !== 0) {
- return null;
- }
- $full_command = substr($full_command, 1);
-
- //check if command is followed by bot username
- $split_cmd = explode('@', $full_command);
- if (! isset($split_cmd[1])) {
- //command is not followed by name
- return $full_command;
- }
-
- if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) {
- //command is addressed to me
- return $split_cmd[0];
- }
-
- return null;
- }
-
- /**
- * For text messages, the actual UTF-8 text of the message, 0-4096 characters.
- *
- * @param bool $without_cmd
- *
- * @return string|null
- */
- public function getText($without_cmd = false): ?string
- {
- $text = $this->getProperty('text');
-
- if ($without_cmd && $command = $this->getFullCommand()) {
- if (strlen($command) + 1 < strlen($text)) {
- return substr($text, strlen($command) + 1);
- }
-
- return '';
- }
-
- return $text;
- }
-
- /**
- * Bot added in chat
- *
- * @return bool
- */
- public function botAddedInChat(): bool
- {
- foreach ($this->getNewChatMembers() as $member) {
- if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Detect type based on properties.
- *
- * @return string
- */
- public function getType(): string
- {
- $types = [
- 'text',
- 'animation',
- 'audio',
- 'document',
- 'photo',
- 'sticker',
- 'video',
- 'video_note',
- 'voice',
- 'contact',
- 'dice',
- 'game',
- 'poll',
- 'venue',
- 'location',
- 'new_chat_members',
- 'left_chat_member',
- 'new_chat_title',
- 'new_chat_photo',
- 'delete_chat_photo',
- 'group_chat_created',
- 'supergroup_chat_created',
- 'channel_chat_created',
- 'message_auto_delete_timer_changed',
- 'migrate_to_chat_id',
- 'migrate_from_chat_id',
- 'pinned_message',
- 'invoice',
- 'successful_payment',
- 'users_shared',
- 'chat_shared',
- 'write_access_allowed',
- 'passport_data',
- 'proximity_alert_triggered',
- 'forum_topic_created',
- 'forum_topic_edited',
- 'forum_topic_closed',
- 'forum_topic_reopened',
- 'general_forum_topic_hidden',
- 'general_forum_topic_unhidden',
- 'video_chat_scheduled',
- 'video_chat_started',
- 'video_chat_ended',
- 'video_chat_participants_invited',
- 'web_app_data',
- 'reply_markup',
+ return [
+ 'is_topic_message' => false,
+ 'is_automatic_forward' => false,
+ 'has_protected_content' => false,
+ 'is_from_offline' => false,
+ 'has_media_spoiler' => false,
];
-
- $is_command = $this->getCommand() !== null;
- foreach ($types as $type) {
- if ($this->getProperty($type) !== null) {
- if ($is_command && $type === 'text') {
- return 'command';
- }
-
- return $type;
- }
- }
-
- return 'message';
}
}
diff --git a/src/Entities/Message/Factory.php b/src/Entities/Message/Factory.php
deleted file mode 100644
index 63ce362ef..000000000
--- a/src/Entities/Message/Factory.php
+++ /dev/null
@@ -1,21 +0,0 @@
- Chat::class,
- ];
- }
-}
diff --git a/src/Entities/Message/MaybeInaccessibleMessage.php b/src/Entities/Message/MaybeInaccessibleMessage.php
deleted file mode 100644
index 8e9d1b85c..000000000
--- a/src/Entities/Message/MaybeInaccessibleMessage.php
+++ /dev/null
@@ -1,15 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class MessageAutoDeleteTimerChanged
- *
- * Represents a service message about a change in auto-delete timer settings
- *
- * @link https://core.telegram.org/bots/api#messageautodeletetimerchanged
- *
- * @method int getMessageAutoDeleteTime() New auto-delete time for messages in the chat
+ * @method int getMessageAutoDeleteTime() New auto-delete time for messages in the chat; in seconds
*/
class MessageAutoDeleteTimerChanged extends Entity
{
-
+ //
}
diff --git a/src/Entities/MessageEntity.php b/src/Entities/MessageEntity.php
index d09ab4684..0890495ea 100644
--- a/src/Entities/MessageEntity.php
+++ b/src/Entities/MessageEntity.php
@@ -1,35 +1,57 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class MessageEntity
- *
- * @link https://core.telegram.org/bots/api#messageentity
- *
- * @method string getType() Type of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag), “cashtag” ($USD), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames), “custom_emoji” (for inline custom emoji stickers)
- * @method int getOffset() Offset in UTF-16 code units to the start of the entity
- * @method int getLength() Length of the entity in UTF-16 code units
- * @method string getUrl() Optional. For "text_link" only, url that will be opened after user taps on the text
- * @method User getUser() Optional. For "text_mention" only, the mentioned user
- * @method string getLanguage() Optional. For "pre" only, the programming language of the entity text
- * @method string getCustomEmojiId() Optional. For “custom_emoji” only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker
+ * @method string getType() Type of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag), “cashtag” ($USD), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “blockquote” (block quotation), “expandable_blockquote” (collapsed-by-default block quotation), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames), “custom_emoji” (for inline custom emoji stickers)
+ * @method int getOffset() Offset in UTF-16 code units to the start of the entity
+ * @method int getLength() Length of the entity in UTF-16 code units
+ * @method string|null getUrl() Optional. For “text_link” only, URL that will be opened after user taps on the text
+ * @method User|null getUser() Optional. For “text_mention” only, the mentioned user
+ * @method string|null getLanguage() Optional. For “pre” only, the programming language of the entity text
+ * @method string|null getCustomEmojiId() Optional. For “custom_emoji” only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker
*/
class MessageEntity extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ public const TYPE_MENTION = 'mention'; // @username
+
+ public const TYPE_HASHTAG = 'hashtag'; // #hashtag
+
+ public const TYPE_CASHTAG = 'cashtag'; // $USD
+
+ public const TYPE_BOT_COMMAND = 'bot_command'; // /start@jobs_bot
+
+ public const TYPE_URL = 'url'; // https://telegram.org
+
+ public const TYPE_EMAIL = 'email'; // do-not-reply@telegram.org
+
+ public const TYPE_PHONE_NUMBER = 'phone_number'; // +1-212-555-0123
+
+ public const TYPE_BOLD = 'bold'; // bold text
+
+ public const TYPE_ITALIC = 'italic'; // italic text
+
+ public const TYPE_UNDERLINE = 'underline'; // underlined text
+
+ public const TYPE_STRIKETHROUGH = 'strikethrough'; // strikethrough text
+
+ public const TYPE_SPOILER = 'spoiler'; // spoiler message
+
+ public const TYPE_BLOCKQUOTE = 'blockquote'; // block quotation
+
+ public const TYPE_EXPANDABLE_BLOCKQUOTE = 'expandable_blockquote'; // collapsed-by-default block quotation
+
+ public const TYPE_CODE = 'code'; // monowidth string
+
+ public const TYPE_PRE = 'pre'; // monowidth block
+
+ public const TYPE_TEXT_LINK = 'text_link'; // for clickable text URLs
+
+ public const TYPE_TEXT_MENTION = 'text_mention'; // for users without usernames
+
+ public const TYPE_CUSTOM_EMOJI = 'custom_emoji'; // for inline custom emoji stickers
+
+ protected static function subEntities(): array
{
return [
'user' => User::class,
diff --git a/src/Entities/MessageId.php b/src/Entities/MessageId.php
new file mode 100644
index 000000000..2ca56e183
--- /dev/null
+++ b/src/Entities/MessageId.php
@@ -0,0 +1,11 @@
+ MessageOriginUser::class,
- 'hidden_user' => MessageOriginHiddenUser::class,
- 'chat' => MessageOriginChat::class,
- 'channel' => MessageOriginChannel::class,
- ];
-
- if (!isset($type[$data['type'] ?? ''])) {
- return new MessageOriginNotImplemented($data, $bot_username);
- }
-
- $class = $type[$data['type']];
- return new $class($data, $bot_username);
- }
-}
diff --git a/src/Entities/MessageOrigin/MessageOrigin.php b/src/Entities/MessageOrigin/MessageOrigin.php
index a8a468c0f..0ea975b51 100644
--- a/src/Entities/MessageOrigin/MessageOrigin.php
+++ b/src/Entities/MessageOrigin/MessageOrigin.php
@@ -1,14 +1,23 @@
new MessageOriginUser($data),
+ 'hidden_user' => new MessageOriginHiddenUser($data),
+ 'chat' => new MessageOriginChat($data),
+ 'channel' => new MessageOriginChannel($data),
+ };
+ }
}
diff --git a/src/Entities/MessageOrigin/MessageOriginChannel.php b/src/Entities/MessageOrigin/MessageOriginChannel.php
index acb9807f4..66afac5b5 100644
--- a/src/Entities/MessageOrigin/MessageOriginChannel.php
+++ b/src/Entities/MessageOrigin/MessageOriginChannel.php
@@ -1,24 +1,17 @@
Chat::class,
diff --git a/src/Entities/MessageOrigin/MessageOriginChat.php b/src/Entities/MessageOrigin/MessageOriginChat.php
index a0c2b398b..c5a5b0f61 100644
--- a/src/Entities/MessageOrigin/MessageOriginChat.php
+++ b/src/Entities/MessageOrigin/MessageOriginChat.php
@@ -1,23 +1,16 @@
Chat::class,
diff --git a/src/Entities/MessageOrigin/MessageOriginHiddenUser.php b/src/Entities/MessageOrigin/MessageOriginHiddenUser.php
index baff892f0..935dd8c0f 100644
--- a/src/Entities/MessageOrigin/MessageOriginHiddenUser.php
+++ b/src/Entities/MessageOrigin/MessageOriginHiddenUser.php
@@ -1,19 +1,11 @@
User::class,
diff --git a/src/Entities/MessageReactionCountUpdated.php b/src/Entities/MessageReactionCountUpdated.php
index 21dc848bd..35d0f8db6 100644
--- a/src/Entities/MessageReactionCountUpdated.php
+++ b/src/Entities/MessageReactionCountUpdated.php
@@ -1,12 +1,8 @@
Chat::class,
diff --git a/src/Entities/MessageReactionUpdated.php b/src/Entities/MessageReactionUpdated.php
index c5b602147..bb7043869 100644
--- a/src/Entities/MessageReactionUpdated.php
+++ b/src/Entities/MessageReactionUpdated.php
@@ -1,33 +1,28 @@
Chat::class,
'user' => User::class,
'actor_chat' => Chat::class,
- 'old_reaction' => [ReactionTypeFactory::class],
- 'new_reaction' => [ReactionTypeFactory::class],
+ 'old_reaction' => [ReactionType::class],
+ 'new_reaction' => [ReactionType::class],
];
}
}
diff --git a/src/Entities/OrderInfo.php b/src/Entities/OrderInfo.php
new file mode 100644
index 000000000..6a3050c34
--- /dev/null
+++ b/src/Entities/OrderInfo.php
@@ -0,0 +1,19 @@
+ ShippingAddress::class,
+ ];
+ }
+}
diff --git a/src/Entities/PaidMedia/PaidMedia.php b/src/Entities/PaidMedia/PaidMedia.php
new file mode 100644
index 000000000..30d01e95d
--- /dev/null
+++ b/src/Entities/PaidMedia/PaidMedia.php
@@ -0,0 +1,27 @@
+ new PaidMediaPreview($data),
+ self::TYPE_PHOTO => new PaidMediaPhoto($data),
+ self::TYPE_VIDEO => new PaidMediaVideo($data),
+ };
+ }
+}
diff --git a/src/Entities/PaidMedia/PaidMediaPhoto.php b/src/Entities/PaidMedia/PaidMediaPhoto.php
new file mode 100644
index 000000000..ea5a0b239
--- /dev/null
+++ b/src/Entities/PaidMedia/PaidMediaPhoto.php
@@ -0,0 +1,25 @@
+ [PhotoSize::class],
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => self::TYPE_PHOTO,
+ ];
+ }
+}
diff --git a/src/Entities/PaidMedia/PaidMediaPreview.php b/src/Entities/PaidMedia/PaidMediaPreview.php
new file mode 100644
index 000000000..4753a30d5
--- /dev/null
+++ b/src/Entities/PaidMedia/PaidMediaPreview.php
@@ -0,0 +1,18 @@
+ self::TYPE_PREVIEW,
+ ];
+ }
+}
diff --git a/src/Entities/PaidMedia/PaidMediaVideo.php b/src/Entities/PaidMedia/PaidMediaVideo.php
new file mode 100644
index 000000000..bc5f4bf0f
--- /dev/null
+++ b/src/Entities/PaidMedia/PaidMediaVideo.php
@@ -0,0 +1,25 @@
+ Video::class,
+ ];
+ }
+
+ protected static function presetData(): array
+ {
+ return [
+ 'type' => self::TYPE_VIDEO,
+ ];
+ }
+}
diff --git a/src/Entities/PaidMediaInfo.php b/src/Entities/PaidMediaInfo.php
new file mode 100644
index 000000000..40f727232
--- /dev/null
+++ b/src/Entities/PaidMediaInfo.php
@@ -0,0 +1,19 @@
+ [PaidMedia::class],
+ ];
+ }
+}
diff --git a/src/Entities/PassportData.php b/src/Entities/PassportData.php
new file mode 100644
index 000000000..ed7758999
--- /dev/null
+++ b/src/Entities/PassportData.php
@@ -0,0 +1,18 @@
+ [EncryptedPassportElement::class],
+ 'credentials' => EncryptedCredentials::class,
+ ];
+ }
+}
diff --git a/src/Entities/PassportFile.php b/src/Entities/PassportFile.php
new file mode 100644
index 000000000..28feed109
--- /dev/null
+++ b/src/Entities/PassportFile.php
@@ -0,0 +1,14 @@
+
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\Payments;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class Invoice
- *
- * This object contains basic information about an invoice.
- *
- * @link https://core.telegram.org/bots/api#invoice
- *
- * @method string getTitle() Product name
- * @method string getDescription() Product description
- * @method string getStartParameter() Unique bot deep-linking parameter that can be used to generate this invoice
- * @method string getCurrency() Three-letter ISO 4217 currency code
- * @method int getTotalAmount() Total price in the smallest units of the currency (integer, not float/double).
- **/
-class Invoice extends Entity
-{
-
-}
diff --git a/src/Entities/Payments/LabeledPrice.php b/src/Entities/Payments/LabeledPrice.php
deleted file mode 100644
index a78d647d3..000000000
--- a/src/Entities/Payments/LabeledPrice.php
+++ /dev/null
@@ -1,29 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\Payments;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class LabeledPrice
- *
- * This object represents a portion of the price for goods or services.
- *
- * @link https://core.telegram.org/bots/api#labeledprice
- *
- * @method string getLabel() Portion label
- * @method int getAmount() Price of the product in the smallest units of the currency (integer, not float/double).
- **/
-class LabeledPrice extends Entity
-{
-
-}
diff --git a/src/Entities/Payments/OrderInfo.php b/src/Entities/Payments/OrderInfo.php
deleted file mode 100644
index e539d4927..000000000
--- a/src/Entities/Payments/OrderInfo.php
+++ /dev/null
@@ -1,39 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\Payments;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class OrderInfo
- *
- * This object represents information about an order.
- *
- * @link https://core.telegram.org/bots/api#orderinfo
- *
- * @method string getName() Optional. User name
- * @method string getPhoneNumber() Optional. User's phone number
- * @method string getEmail() Optional. User email
- * @method ShippingAddress getShippingAddress() Optional. User shipping address
- **/
-class OrderInfo extends Entity
-{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
- {
- return [
- 'shipping_address' => ShippingAddress::class,
- ];
- }
-}
diff --git a/src/Entities/Payments/PreCheckoutQuery.php b/src/Entities/Payments/PreCheckoutQuery.php
deleted file mode 100644
index b58357101..000000000
--- a/src/Entities/Payments/PreCheckoutQuery.php
+++ /dev/null
@@ -1,62 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\Payments;
-
-use Longman\TelegramBot\Entities\Entity;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Entities\User;
-use Longman\TelegramBot\Request;
-
-/**
- * Class PreCheckoutQuery
- *
- * This object contains information about an incoming pre-checkout query.
- *
- * @link https://core.telegram.org/bots/api#precheckoutquery
- *
- * @method string getId() Unique query identifier
- * @method User getFrom() User who sent the query
- * @method string getCurrency() Three-letter ISO 4217 currency code
- * @method int getTotalAmount() Total price in the smallest units of the currency (integer, not float/double).
- * @method string getInvoicePayload() Bot specified invoice payload
- * @method string getShippingOptionId() Optional. Identifier of the shipping option chosen by the user
- * @method OrderInfo getOrderInfo() Optional. Order info provided by the user
- **/
-class PreCheckoutQuery extends Entity
-{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
- {
- return [
- 'from' => User::class,
- 'order_info' => OrderInfo::class,
- ];
- }
-
- /**
- * Answer this pre-checkout query.
- *
- * @param bool $ok
- * @param array $data
- *
- * @return ServerResponse
- */
- public function answer(bool $ok, array $data = []): ServerResponse
- {
- return Request::answerPreCheckoutQuery(array_merge([
- 'pre_checkout_query_id' => $this->getId(),
- 'ok' => $ok,
- ], $data));
- }
-}
diff --git a/src/Entities/Payments/ShippingAddress.php b/src/Entities/Payments/ShippingAddress.php
deleted file mode 100644
index e48f64e7f..000000000
--- a/src/Entities/Payments/ShippingAddress.php
+++ /dev/null
@@ -1,33 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\Payments;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class ShippingAddress
- *
- * This object represents a shipping address.
- *
- * @link https://core.telegram.org/bots/api#shippingaddress
- *
- * @method string getCountryCode() ISO 3166-1 alpha-2 country code
- * @method string getState() State, if applicable
- * @method string getCity() City
- * @method string getStreetLine1() First line for the address
- * @method string getStreetLine2() Second line for the address
- * @method string getPostCode() Address post code
- **/
-class ShippingAddress extends Entity
-{
-
-}
diff --git a/src/Entities/Payments/ShippingOption.php b/src/Entities/Payments/ShippingOption.php
deleted file mode 100644
index f49eaf4d9..000000000
--- a/src/Entities/Payments/ShippingOption.php
+++ /dev/null
@@ -1,38 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\Payments;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class ShippingOption
- *
- * This object represents one shipping option.
- *
- * @link https://core.telegram.org/bots/api#shippingoption
- *
- * @method string getId() Shipping option identifier
- * @method string getTitle() Option title
- * @method LabeledPrice[] getPrices() List of price portions
- **/
-class ShippingOption extends Entity
-{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
- {
- return [
- 'prices' => [LabeledPrice::class],
- ];
- }
-}
diff --git a/src/Entities/Payments/ShippingQuery.php b/src/Entities/Payments/ShippingQuery.php
deleted file mode 100644
index f096f6613..000000000
--- a/src/Entities/Payments/ShippingQuery.php
+++ /dev/null
@@ -1,59 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\Payments;
-
-use Longman\TelegramBot\Entities\Entity;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Entities\User;
-use Longman\TelegramBot\Request;
-
-/**
- * Class ShippingQuery
- *
- * This object contains information about an incoming shipping query.
- *
- * @link https://core.telegram.org/bots/api#shippingquery
- *
- * @method string getId() Unique query identifier
- * @method User getFrom() User who sent the query
- * @method string getInvoicePayload() Bot specified invoice payload
- * @method ShippingAddress getShippingAddress() User specified shipping address
- **/
-class ShippingQuery extends Entity
-{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
- {
- return [
- 'from' => User::class,
- 'shipping_address' => ShippingAddress::class,
- ];
- }
-
- /**
- * Answer this shipping query.
- *
- * @param bool $ok
- * @param array $data
- *
- * @return ServerResponse
- */
- public function answer(bool $ok, array $data = []): ServerResponse
- {
- return Request::answerShippingQuery(array_merge([
- 'shipping_query_id' => $this->getId(),
- 'ok' => $ok,
- ], $data));
- }
-}
diff --git a/src/Entities/Payments/SuccessfulPayment.php b/src/Entities/Payments/SuccessfulPayment.php
deleted file mode 100644
index 8f2b5335e..000000000
--- a/src/Entities/Payments/SuccessfulPayment.php
+++ /dev/null
@@ -1,42 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\Payments;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class SuccessfulPayment
- *
- * This object contains basic information about a successful payment.
- *
- * @link https://core.telegram.org/bots/api#successfulpayment
- *
- * @method string getCurrency() Three-letter ISO 4217 currency code
- * @method int getTotalAmount() Total price in the smallest units of the currency (integer, not float/double).
- * @method string getInvoicePayload() Bot specified invoice payload
- * @method string getShippingOptionId() Optional. Identifier of the shipping option chosen by the user
- * @method OrderInfo getOrderInfo() Optional. Order info provided by the user
- * @method string getTelegramPaymentChargeId() Telegram payment identifier
- * @method string getProviderPaymentChargeId() Provider payment identifier
- **/
-class SuccessfulPayment extends Entity
-{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
- {
- return [
- 'order_info' => OrderInfo::class,
- ];
- }
-}
diff --git a/src/Entities/PhotoSize.php b/src/Entities/PhotoSize.php
index 21718d28f..1a70fe9a1 100644
--- a/src/Entities/PhotoSize.php
+++ b/src/Entities/PhotoSize.php
@@ -1,28 +1,15 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class PhotoSize
- *
- * @link https://core.telegram.org/bots/api#photosize
- *
- * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
- * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
- * @method int getWidth() Photo width
- * @method int getHeight() Photo height
- * @method int getFileSize() Optional. File size
+ * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
+ * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
+ * @method int getWidth() Photo width
+ * @method int getHeight() Photo height
+ * @method int|null getFileSize() Optional. File size in bytes
*/
class PhotoSize extends Entity
{
-
+ //
}
diff --git a/src/Entities/Poll.php b/src/Entities/Poll.php
index 35313bc00..ace697074 100644
--- a/src/Entities/Poll.php
+++ b/src/Entities/Poll.php
@@ -1,47 +1,45 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+namespace PhpTelegramBot\Core\Entities;
-namespace Longman\TelegramBot\Entities;
+use PhpTelegramBot\Core\Contracts\AllowsBypassingGet;
/**
- * Class Poll
- *
- * This entity contains information about a poll.
- *
- * @link https://core.telegram.org/bots/api#poll
- *
- * @method string getId() Unique poll identifier
- * @method string getQuestion() Poll question, 1-255 characters
- * @method PollOption[] getOptions() List of poll options
- * @method int getTotalVoterCount() Total number of users that voted in the poll
- * @method bool getIsClosed() True, if the poll is closed
- * @method bool getIsAnonymous() True, if the poll is anonymous
- * @method string getType() Poll type, currently can be “regular” or “quiz”
- * @method bool getAllowsMultipleAnswers() True, if the poll allows multiple answers
- * @method int getCorrectOptionId() Optional. 0-based identifier of the correct answer option. Available only for polls in the quiz mode, which are closed, or was sent (not forwarded) by the bot or to the private chat with the bot.
- * @method string getExplanation() Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters
- * @method MessageEntity[] getExplanationEntities() Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the explanation
- * @method int getOpenPeriod() Optional. Amount of time in seconds the poll will be active after creation
- * @method int getCloseDate() Optional. Point in time (Unix timestamp) when the poll will be automatically closed
+ * @method string getId() Unique poll identifier
+ * @method string getQuestion() Poll question, 1-300 characters
+ * @method MessageEntity[]|null getQuestionEntities() Optional. Special entities that appear in the question. Currently, only custom emoji entities are allowed in poll questions
+ * @method PollOption[] getOptions() List of poll options
+ * @method int getTotalVoterCount() Total number of users that voted in the poll
+ * @method bool isClosed() True, if the poll is closed
+ * @method bool isAnonymous() True, if the poll is anonymous
+ * @method string getType() Poll type, currently can be “regular” or “quiz”
+ * @method bool getAllowsMultipleAnswers() True, if the poll allows multiple answers
+ * @method int|null getCorrectOptionId() Optional. 0-based identifier of the correct answer option. Available only for polls in the quiz mode, which are closed, or was sent (not forwarded), by the bot or to the private chat with the bot.
+ * @method string|null getExplanation() Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters
+ * @method MessageEntity[]|null getExplanationEntities() Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the explanation
+ * @method int|null getOpenPeriod() Optional. Amount of time in seconds the poll will be active after creation
+ * @method int|null getCloseDate() Optional. Point in time (Unix timestamp), when the poll will be automatically closed
*/
-class Poll extends Entity
+class Poll extends Entity implements AllowsBypassingGet
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ public const TYPE_REGULAR = 'regular';
+
+ public const TYPE_QUIZ = 'quiz';
+
+ protected static function subEntities(): array
{
return [
+ 'question_entities' => [MessageEntity::class],
'options' => [PollOption::class],
'explanation_entities' => [MessageEntity::class],
];
}
+
+ public static function fieldsBypassingGet(): array
+ {
+ return [
+ 'is_closed' => false,
+ 'is_anonymous' => false,
+ ];
+ }
}
diff --git a/src/Entities/PollAnswer.php b/src/Entities/PollAnswer.php
index f55fe916f..1031d5ff8 100644
--- a/src/Entities/PollAnswer.php
+++ b/src/Entities/PollAnswer.php
@@ -1,34 +1,16 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class PollAnswer
- *
- * This entity represents an answer of a user in a non-anonymous poll.
- *
- * @link https://core.telegram.org/bots/api#pollanswer
- *
- * @method string getPollId() Unique poll identifier
- * @method Chat getVoterChat() Optional. The chat that changed the answer to the poll, if the voter is anonymous
- * @method User getUser() Optional. The user, who changed the answer to the poll
- * @method array getOptionIds() 0-based identifiers of answer options, chosen by the user. May be empty if the user retracted their vote.
+ * @method string getPollId() Unique poll identifier
+ * @method Chat|null getVoterChat() Optional. The chat that changed the answer to the poll, if the voter is anonymous
+ * @method User|null getUser() Optional. The user that changed the answer to the poll, if the voter isn't anonymous
+ * @method int[] getOptionIds() 0-based identifiers of chosen answer options. May be empty if the vote was retracted.
*/
class PollAnswer extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'voter_chat' => Chat::class,
diff --git a/src/Entities/PollOption.php b/src/Entities/PollOption.php
index 8af5f978b..c1352098c 100644
--- a/src/Entities/PollOption.php
+++ b/src/Entities/PollOption.php
@@ -1,27 +1,18 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class PollOption
- *
- * This entity contains information about one answer option in a poll.
- *
- * @link https://core.telegram.org/bots/api#polloption
- *
- * @method string getText() Option text, 1-100 characters
- * @method int getVoterCount() Number of users that voted for this option
+ * @method string getText() Option text, 1-100 characters
+ * @method MessageEntity[]|null getTextEntities() Optional. Special entities that appear in the option text. Currently, only custom emoji entities are allowed in poll option texts
+ * @method int getVoterCount() Number of users that voted for this option
*/
class PollOption extends Entity
{
-
+ protected static function subEntities(): array
+ {
+ return [
+ 'text_entities' => [MessageEntity::class],
+ ];
+ }
}
diff --git a/src/Entities/PreCheckoutQuery.php b/src/Entities/PreCheckoutQuery.php
new file mode 100644
index 000000000..77d13e02d
--- /dev/null
+++ b/src/Entities/PreCheckoutQuery.php
@@ -0,0 +1,23 @@
+ User::class,
+ 'order_info' => OrderInfo::class,
+ ];
+ }
+}
diff --git a/src/Entities/ProximityAlertTriggered.php b/src/Entities/ProximityAlertTriggered.php
index 6aa14e312..eaf0c885f 100644
--- a/src/Entities/ProximityAlertTriggered.php
+++ b/src/Entities/ProximityAlertTriggered.php
@@ -1,33 +1,15 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class ProximityAlertTriggered
- *
- * Represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user.
- *
- * @link https://core.telegram.org/bots/api#proximityalerttriggered
- *
* @method User getTraveler() User that triggered the alert
* @method User getWatcher() User that set the alert
* @method int getDistance() The distance between the users
*/
class ProximityAlertTriggered extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'traveler' => User::class,
diff --git a/src/Entities/ReactionCount.php b/src/Entities/ReactionCount.php
index c99e67d3d..dd32d35e4 100644
--- a/src/Entities/ReactionCount.php
+++ b/src/Entities/ReactionCount.php
@@ -1,24 +1,19 @@
ReactionTypeFactory::class,
+ 'type' => ReactionType::class,
];
}
}
diff --git a/src/Entities/ReactionType/Factory.php b/src/Entities/ReactionType/Factory.php
deleted file mode 100644
index f61cf368b..000000000
--- a/src/Entities/ReactionType/Factory.php
+++ /dev/null
@@ -1,23 +0,0 @@
- ReactionTypeEmoji::class,
- 'custom_emoji' => ReactionTypeCustomEmoji::class,
- ];
-
- if (!isset($type[$data['type'] ?? ''])) {
- return new ReactionTypeNotImplemented($data, $bot_username);
- }
-
- $class = $type[$data['type']];
- return new $class($data, $bot_username);
- }
-}
diff --git a/src/Entities/ReactionType/ReactionType.php b/src/Entities/ReactionType/ReactionType.php
index 901f951de..77e38a401 100644
--- a/src/Entities/ReactionType/ReactionType.php
+++ b/src/Entities/ReactionType/ReactionType.php
@@ -1,15 +1,24 @@
new ReactionTypeEmoji($data),
+ self::TYPE_CUSTOM_EMOJI => new ReactionTypeCustomEmoji($data),
+ };
+ }
}
diff --git a/src/Entities/ReactionType/ReactionTypeCustomEmoji.php b/src/Entities/ReactionType/ReactionTypeCustomEmoji.php
index 6a23e521c..8186f0ada 100644
--- a/src/Entities/ReactionType/ReactionTypeCustomEmoji.php
+++ b/src/Entities/ReactionType/ReactionTypeCustomEmoji.php
@@ -1,22 +1,11 @@
[[KeyboardButton::class]],
+ ];
+ }
+
+ public static function fieldsBypassingGet(): array
+ {
+ return [
+ 'is_persistent' => false,
+ ];
+ }
+}
diff --git a/src/Entities/ReplyKeyboardRemove.php b/src/Entities/ReplyKeyboardRemove.php
new file mode 100644
index 000000000..0980dcc3a
--- /dev/null
+++ b/src/Entities/ReplyKeyboardRemove.php
@@ -0,0 +1,12 @@
+
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Describes reply parameters for the message that is being sent.
- *
- * @link https://core.telegram.org/bots/api#replyparameters
- *
- * @method int getMessageId() Identifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified
- * @method int|string getChatId() Optional. If the message to be replied to is from a different chat, unique identifier for the chat or username of the channel (in the format @channelusername)
- * @method bool getAllowSendingWithoutReply() Optional. Pass True if the message should be sent even if the specified message to be replied to is not found; can be used only for replies in the same chat and forum topic.
- * @method string getQuote() Optional. Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including bold, italic, underline, strikethrough, spoiler, and custom_emoji entities. The message will fail to send if the quote isn't found in the original message.
- * @method string getQuoteParseMode() Optional. Mode for parsing entities in the quote. See formatting options for more details.
- * @method MessageEntity[] getQuoteEntities() Optional. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode.
- * @method int getQuotePosition() Optional. Position of the quote in the original message in UTF-16 code units
+ * @method int getMessageId() Identifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified
+ * @method int|string|null getChatId() Optional. If the message to be replied to is from a different chat, unique identifier for the chat or username of the channel (in the format @channelusername). Not supported for messages sent on behalf of a business account.
+ * @method bool|null getAllowSendingWithoutReply() Optional. Pass True if the message should be sent even if the specified message to be replied to is not found. Always False for replies in another chat or forum topic. Always True for messages sent on behalf of a business account.
+ * @method string|null getQuote() Optional. Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including bold, italic, underline, strikethrough, spoiler, and custom_emoji entities. The message will fail to send if the quote isn't found in the original message.
+ * @method string|null getQuoteParseMode() Optional. Mode for parsing entities in the quote. See formatting options for more details.
+ * @method MessageEntity[]|null getQuoteEntities() Optional. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode.
+ * @method int|null getQuotePosition() Optional. Position of the quote in the original message in UTF-16 code units
*/
class ReplyParameters extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'quote_entities' => [MessageEntity::class],
diff --git a/src/Entities/ReplyToMessage.php b/src/Entities/ReplyToMessage.php
deleted file mode 100644
index 5dc914b0a..000000000
--- a/src/Entities/ReplyToMessage.php
+++ /dev/null
@@ -1,35 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
-
-/**
- * Class ReplyToMessage
- *
- * @todo Is this even required?!
- */
-class ReplyToMessage extends Message
-{
- /**
- * ReplyToMessage constructor.
- *
- * @param array $data
- * @param string $bot_username
- */
- public function __construct(array $data, string $bot_username = '')
- {
- //As explained in the documentation
- //Reply to message can't contain other reply to message entities
- unset($data['reply_to_message']);
-
- parent::__construct($data, $bot_username);
- }
-}
diff --git a/src/Entities/ResponseParameters.php b/src/Entities/ResponseParameters.php
new file mode 100644
index 000000000..38dbd1c9c
--- /dev/null
+++ b/src/Entities/ResponseParameters.php
@@ -0,0 +1,12 @@
+ new RevenueWithdrawalStatePending($data),
+ self::TYPE_SUCCEEDED => new RevenueWithdrawalStateSucceeded($data),
+ self::TYPE_FAILED => new RevenueWithdrawalStateFailed($data),
+ };
+ }
+}
diff --git a/src/Entities/RevenueWithdrawalState/RevenueWithdrawalStateFailed.php b/src/Entities/RevenueWithdrawalState/RevenueWithdrawalStateFailed.php
new file mode 100644
index 000000000..f19e40017
--- /dev/null
+++ b/src/Entities/RevenueWithdrawalState/RevenueWithdrawalStateFailed.php
@@ -0,0 +1,8 @@
+
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
-
-use Longman\TelegramBot\Entities\ChatMember\ChatMember;
-use Longman\TelegramBot\Entities\ChatMember\Factory as ChatMemberFactory;
-use Longman\TelegramBot\Entities\Games\GameHighScore;
-use Longman\TelegramBot\Entities\MenuButton\Factory as MenuButtonFactory;
-use Longman\TelegramBot\Request;
-
-/**
- * Class ServerResponse
- *
- * @link https://core.telegram.org/bots/api#making-requests
- *
- * @method bool getOk() If the request was successful
- * @method mixed getResult() The result of the query
- * @method int getErrorCode() Error code of the unsuccessful request
- * @method string getDescription() Human-readable description of the result / unsuccessful request
- *
- * @todo method ResponseParameters getParameters() Field which can help to automatically handle the error
- */
-class ServerResponse extends Entity
-{
- /**
- * ServerResponse constructor.
- *
- * @param array $data
- * @param string $bot_username
- */
- public function __construct(array $data, string $bot_username = '')
- {
- $is_ok = (bool) ($data['ok'] ?? false);
- $result = $data['result'] ?? null;
-
- if ($is_ok && is_array($result)) {
- if ($this->isAssoc($result)) {
- $data['result'] = $this->createResultObject($result, $bot_username);
- } else {
- $data['result'] = $this->createResultObjects($result, $bot_username);
- }
- }
-
- parent::__construct($data, $bot_username);
- }
-
- /**
- * Check if array is associative
- *
- * @link https://stackoverflow.com/a/4254008
- *
- * @param array $array
- *
- * @return bool
- */
- protected function isAssoc(array $array): bool
- {
- return count(array_filter(array_keys($array), 'is_string')) > 0;
- }
-
- /**
- * If response is ok
- *
- * @return bool
- */
- public function isOk(): bool
- {
- return (bool) $this->getOk();
- }
-
- /**
- * Print error
- *
- * @see https://secure.php.net/manual/en/function.print-r.php
- *
- * @param bool $return
- *
- * @return bool|string
- */
- public function printError($return = false)
- {
- $error = sprintf('Error N: %s, Description: %s', $this->getErrorCode(), $this->getDescription());
-
- if ($return) {
- return $error;
- }
-
- echo $error;
-
- return true;
- }
-
- /**
- * Create and return the object of the received result
- *
- * @param array $result
- * @param string $bot_username
- *
- * @return BotDescription|BotName|BotShortDescription|Chat|ChatAdministratorRights|ChatMember|File|Message|MenuButton|Poll|SentWebAppMessage|StickerSet|User|UserProfilePhotos|WebhookInfo
- */
- private function createResultObject(array $result, string $bot_username): Entity
- {
- $result_object_types = [
- 'getWebhookInfo' => WebhookInfo::class,
- 'getMe' => User::class,
- 'getUserProfilePhotos' => UserProfilePhotos::class,
- 'getFile' => File::class,
- 'getChat' => Chat::class,
- 'getChatMember' => ChatMemberFactory::class,
- 'getMyName' => BotName::class,
- 'getMyDescription' => BotDescription::class,
- 'getMyShortDescription' => BotShortDescription::class,
- 'getChatMenuButton' => MenuButtonFactory::class,
- 'getMyDefaultAdministratorRights' => ChatAdministratorRights::class,
- 'getStickerSet' => StickerSet::class,
- 'stopPoll' => Poll::class,
- 'answerWebAppQuery' => SentWebAppMessage::class,
- ];
-
- $action = Request::getCurrentAction();
- $object_class = $result_object_types[$action] ?? Message::class;
-
- return Factory::resolveEntityClass($object_class, $result, $bot_username);
- }
-
- /**
- * Create and return the objects array of the received result
- *
- * @param array $results
- * @param string $bot_username
- *
- * @return BotCommand[]|ChatMember[]|GameHighScore[]|Message[]|Sticker[]|Update[]
- */
- private function createResultObjects(array $results, string $bot_username): array
- {
- $result_object_types = [
- 'getUpdates' => Update::class,
- 'getChatAdministrators' => ChatMemberFactory::class,
- 'getForumTopicIconStickers' => Sticker::class,
- 'getMyCommands' => BotCommand::class,
- 'getCustomEmojiStickers' => Sticker::class,
- 'getGameHighScores' => GameHighScore::class,
- 'sendMediaGroup' => Message::class,
- ];
-
- $action = Request::getCurrentAction();
- $object_class = $result_object_types[$action] ?? Update::class;
-
- $objects = [];
-
- foreach ($results as $result) {
- $objects[] = Factory::resolveEntityClass($object_class, $result, $bot_username);
- }
-
- return $objects;
- }
-}
diff --git a/src/Entities/SharedUser.php b/src/Entities/SharedUser.php
new file mode 100644
index 000000000..4ba8f6055
--- /dev/null
+++ b/src/Entities/SharedUser.php
@@ -0,0 +1,20 @@
+ [PhotoSize::class],
+ ];
+ }
+}
diff --git a/src/Entities/ShippingAddress.php b/src/Entities/ShippingAddress.php
new file mode 100644
index 000000000..05c69d92c
--- /dev/null
+++ b/src/Entities/ShippingAddress.php
@@ -0,0 +1,16 @@
+ [LabeledPrice::class],
+ ];
+ }
+}
diff --git a/src/Entities/ShippingQuery.php b/src/Entities/ShippingQuery.php
new file mode 100644
index 000000000..85ee1c4af
--- /dev/null
+++ b/src/Entities/ShippingQuery.php
@@ -0,0 +1,20 @@
+ User::class,
+ 'shipping_address' => ShippingAddress::class,
+ ];
+ }
+}
diff --git a/src/Entities/StarTransaction.php b/src/Entities/StarTransaction.php
new file mode 100644
index 000000000..d97c3e6b0
--- /dev/null
+++ b/src/Entities/StarTransaction.php
@@ -0,0 +1,23 @@
+ TransactionPartner::class,
+ 'receiver' => TransactionPartner::class,
+ ];
+ }
+}
diff --git a/src/Entities/StarTransactions.php b/src/Entities/StarTransactions.php
new file mode 100644
index 000000000..bd2e4bf19
--- /dev/null
+++ b/src/Entities/StarTransactions.php
@@ -0,0 +1,13 @@
+ [StarTransaction::class],
+ ];
+ }
+}
diff --git a/src/Entities/Sticker.php b/src/Entities/Sticker.php
index 3671c9523..69e727605 100644
--- a/src/Entities/Sticker.php
+++ b/src/Entities/Sticker.php
@@ -1,43 +1,33 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class Sticker
- *
- * @link https://core.telegram.org/bots/api#sticker
- *
- * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
- * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
- * @method string getType() Type of the sticker, currently one of “regular”, “mask”, “custom_emoji”. The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video.
- * @method int getWidth() Sticker width
- * @method int getHeight() Sticker height
- * @method bool getIsAnimated() True, if the sticker is animated
- * @method bool getIsVideo() True, if the sticker is a video sticker
- * @method PhotoSize getThumbnail() Optional. Sticker thumbnail in .webp or .jpg format
- * @method string getEmoji() Optional. Emoji associated with the sticker
- * @method string getSetName() Optional. Name of the sticker set to which the sticker belongs
- * @method File getPremiumAnimation() Optional. Premium animation for the sticker, if the sticker is premium
- * @method MaskPosition getMaskPosition() Optional. For mask stickers, the position where the mask should be placed
- * @method string getCustomEmojiId() Optional. For custom emoji stickers, unique identifier of the custom emoji
- * @method bool getNeedsRepainting() Optional. True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places
- * @method int getFileSize() Optional. File size
+ * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
+ * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
+ * @method string getType() Type of the sticker, currently one of “regular”, “mask”, “custom_emoji”. The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video.
+ * @method int getWidth() Sticker width
+ * @method int getHeight() Sticker height
+ * @method bool getIsAnimated() True, if the sticker is animated
+ * @method bool getIsVideo() True, if the sticker is a video sticker
+ * @method PhotoSize|null getThumbnail() Optional. Sticker thumbnail in the .WEBP or .JPG format
+ * @method string|null getEmoji() Optional. Emoji associated with the sticker
+ * @method string|null getSetName() Optional. Name of the sticker set to which the sticker belongs
+ * @method File|null getPremiumAnimation() Optional. For premium regular stickers, premium animation for the sticker
+ * @method MaskPosition|null getMaskPosition() Optional. For mask stickers, the position where the mask should be placed
+ * @method string|null getCustomEmojiId() Optional. For custom emoji stickers, unique identifier of the custom emoji
+ * @method true|null getNeedsRepainting() Optional. True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places
+ * @method int|null getFileSize() Optional. File size in bytes
*/
class Sticker extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ public const TYPE_REGULAR = 'regular';
+
+ public const TYPE_MASK = 'mask';
+
+ public const TYPE_CUSTOM_EMOJI = 'custom_emoji';
+
+ protected static function subEntities(): array
{
return [
'thumbnail' => PhotoSize::class,
diff --git a/src/Entities/StickerSet.php b/src/Entities/StickerSet.php
index 8bb35ec4d..c76387e3b 100644
--- a/src/Entities/StickerSet.php
+++ b/src/Entities/StickerSet.php
@@ -1,35 +1,17 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class StickerSet
- *
- * @link https://core.telegram.org/bots/api#stickerset
- *
- * @method string getName() Sticker set name
- * @method string getTitle() Sticker set title
- * @method string getStickerType() Type of stickers in the set, currently one of “regular”, “mask”, “custom_emoji”
- * @method bool getIsAnimated() True, if the sticker set contains animated stickers
- * @method bool getIsVideo() True, if the sticker set contains video stickers
- * @method Sticker[] getStickers() List of all set stickers
- * @method PhotoSize getThumbnail() Optional. Sticker set thumbnail in the .WEBP or .TGS format
+ * @method string getName() Sticker set name
+ * @method string getTitle() Sticker set title
+ * @method string getStickerType() Type of stickers in the set, currently one of “regular”, “mask”, “custom_emoji”
+ * @method Sticker[] getStickers() List of all set stickers
+ * @method PhotoSize getThumbnail() Optional. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format
*/
class StickerSet extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'stickers' => [Sticker::class],
diff --git a/src/Entities/Story.php b/src/Entities/Story.php
index 5647db224..263a3e28a 100644
--- a/src/Entities/Story.php
+++ b/src/Entities/Story.php
@@ -1,22 +1,17 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class Story
- *
- * @link https://core.telegram.org/bots/api#story
+ * @method Chat getChat() Chat that posted the story
+ * @method int getId() Unique identifier for the story in the chat
*/
class Story extends Entity
{
-
+ protected static function subEntities(): array
+ {
+ return [
+ 'chat' => Chat::class,
+ ];
+ }
}
diff --git a/src/Entities/SuccessfulPayment.php b/src/Entities/SuccessfulPayment.php
new file mode 100644
index 000000000..8a03b1d72
--- /dev/null
+++ b/src/Entities/SuccessfulPayment.php
@@ -0,0 +1,22 @@
+ OrderInfo::class,
+ ];
+ }
+}
diff --git a/src/Entities/SwitchInlineQueryChosenChat.php b/src/Entities/SwitchInlineQueryChosenChat.php
index 49218f6df..60d9fe106 100644
--- a/src/Entities/SwitchInlineQueryChosenChat.php
+++ b/src/Entities/SwitchInlineQueryChosenChat.php
@@ -1,21 +1,15 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\TelegramPassport;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class EncryptedCredentials
- *
- * Contains data required for decrypting and authenticating EncryptedCredentials. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes.
- *
- * @link https://core.telegram.org/bots/api#encryptedcredentials
- *
- * @method string getData() Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication
- * @method string getHash() Base64-encoded data hash for data authentication
- * @method string getSecret() Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption
- **/
-class EncryptedCredentials extends Entity
-{
-
-}
diff --git a/src/Entities/TelegramPassport/EncryptedPassportElement.php b/src/Entities/TelegramPassport/EncryptedPassportElement.php
deleted file mode 100644
index 42a169cfd..000000000
--- a/src/Entities/TelegramPassport/EncryptedPassportElement.php
+++ /dev/null
@@ -1,49 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\TelegramPassport;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class EncryptedPassportElement
- *
- * Contains information about documents or other Telegram Passport elements shared with the bot by the user.
- *
- * @link https://core.telegram.org/bots/api#encryptedpassportelement
- *
- * @method string getType() Element type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email”.
- * @method string getData() Optional. Base64-encoded encrypted Telegram Passport element data provided by the user, available for “personal_details”, “passport”, “driver_license”, “identity_card”, “identity_passport” and “address” types. Can be decrypted and verified using the accompanying EncryptedCredentials.
- * @method string getPhoneNumber() Optional. User's verified phone number, available only for “phone_number” type
- * @method string getEmail() Optional. User's verified email address, available only for “email” type
- * @method PassportFile[] getFiles() Optional. Array of encrypted files with documents provided by the user, available for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials.
- * @method PassportFile getFrontSide() Optional. Encrypted file with the front side of the document, provided by the user. Available for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
- * @method PassportFile getReverseSide() Optional. Encrypted file with the reverse side of the document, provided by the user. Available for “driver_license” and “identity_card”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
- * @method PassportFile getSelfie() Optional. Encrypted file with the selfie of the user holding a document, provided by the user; available for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
- * @method PassportFile[] getTranslation() Optional. Array of encrypted files with translated versions of documents provided by the user. Available if requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials.
- * @method string getHash() Base64-encoded element hash for using in PassportElementErrorUnspecified
- **/
-class EncryptedPassportElement extends Entity
-{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
- {
- return [
- 'files' => [PassportFile::class],
- 'front_side' => PassportFile::class,
- 'reverse_side' => PassportFile::class,
- 'selfie' => PassportFile::class,
- 'translation' => [PassportFile::class],
- ];
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportData.php b/src/Entities/TelegramPassport/PassportData.php
deleted file mode 100644
index a845e1ed7..000000000
--- a/src/Entities/TelegramPassport/PassportData.php
+++ /dev/null
@@ -1,38 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\TelegramPassport;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportData
- *
- * Contains information about Telegram Passport data shared with the bot by the user.
- *
- * @link https://core.telegram.org/bots/api#passportdata
- *
- * @method EncryptedPassportElement[] getData() Array with information about documents and other Telegram Passport elements that was shared with the bot
- * @method EncryptedCredentials getCredentials() Encrypted credentials required to decrypt the data
- **/
-class PassportData extends Entity
-{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
- {
- return [
- 'data' => [EncryptedPassportElement::class],
- 'credentials' => EncryptedCredentials::class,
- ];
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementError.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementError.php
deleted file mode 100644
index e69e92de3..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementError.php
+++ /dev/null
@@ -1,17 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-interface PassportElementError
-{
-
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorDataField.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorDataField.php
deleted file mode 100644
index d39881482..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorDataField.php
+++ /dev/null
@@ -1,41 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorDataField
- *
- * Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrordatafield
- *
- * @method string getSource() Error source, must be data
- * @method string getType() The section of the user's Telegram Passport which has the error, one of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”
- * @method string getFieldName() Name of the data field which has the error
- * @method string getDataHash() Base64-encoded data hash
- * @method string getMessage() Error message
- */
-class PassportElementErrorDataField extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorDataField constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'data';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFile.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFile.php
deleted file mode 100644
index eb980dd62..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFile.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorFile
- *
- * Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrorfile
- *
- * @method string getSource() Error source, must be file
- * @method string getType() The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
- * @method string getFileHash() Base64-encoded file hash
- * @method string getMessage() Error message
- */
-class PassportElementErrorFile extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorFile constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'file';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFiles.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFiles.php
deleted file mode 100644
index 10ecc53ce..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFiles.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorFiles
- *
- * Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrorfiles
- *
- * @method string getSource() Error source, must be files
- * @method string getType() The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
- * @method string[] getFileHashes() List of base64-encoded file hashes
- * @method string getMessage() Error message
- */
-class PassportElementErrorFiles extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorFiles constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'files';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFrontSide.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFrontSide.php
deleted file mode 100644
index a05ea4f25..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorFrontSide.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorFrontSide
- *
- * Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrorfrontside
- *
- * @method string getSource() Error source, must be front_side
- * @method string getType() The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”
- * @method string getFileHash() Base64-encoded hash of the file with the front side of the document
- * @method string getMessage() Error message
- */
-class PassportElementErrorFrontSide extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorFrontSide constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'front_side';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorReverseSide.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorReverseSide.php
deleted file mode 100644
index e57d80ace..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorReverseSide.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorReverseSide
- *
- * Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrorreverseside
- *
- * @method string getSource() Error source, must be reverse_side
- * @method string getType() The section of the user's Telegram Passport which has the issue, one of “driver_license”, “identity_card”
- * @method string getFileHash() Base64-encoded hash of the file with the reverse side of the document
- * @method string getMessage() Error message
- */
-class PassportElementErrorReverseSide extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorReverseSide constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'reverse_side';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorSelfie.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorSelfie.php
deleted file mode 100644
index a7c9897bd..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorSelfie.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorSelfie
- *
- * Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrorselfie
- *
- * @method string getSource() Error source, must be selfie
- * @method string getType() The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”
- * @method string getFileHash() Base64-encoded hash of the file with the selfie
- * @method string getMessage() Error message
- */
-class PassportElementErrorSelfie extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorSelfie constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'selfie';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorTranslationFile.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorTranslationFile.php
deleted file mode 100644
index 267c342ce..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorTranslationFile.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorTranslationFile
- *
- * Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrortranslationfile
- *
- * @method string getSource() Error source, must be translation_file
- * @method string getType() Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
- * @method string getFileHash() Base64-encoded translation_file hash
- * @method string getMessage() Error message
- */
-class PassportElementErrorTranslationFile extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorTranslationFile constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'translation_file';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorTranslationFiles.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorTranslationFiles.php
deleted file mode 100644
index dd7b4de97..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorTranslationFiles.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorTranslationFiles
- *
- * Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrortranslationfiles
- *
- * @method string getSource() Error source, must be translation_files
- * @method string getType() Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
- * @method string[] getFileHashes() List of base64-encoded file hashes
- * @method string getMessage() Error message
- */
-class PassportElementErrorTranslationFiles extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorTranslationFiles constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'translation_files';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorUnspecified.php b/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorUnspecified.php
deleted file mode 100644
index c804dd2dd..000000000
--- a/src/Entities/TelegramPassport/PassportElementError/PassportElementErrorUnspecified.php
+++ /dev/null
@@ -1,40 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Entities\TelegramPassport\PassportElementError;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportElementErrorUnspecified
- *
- * Represents an issue in an unspecified place. The error is considered resolved when new data is added.
- *
- * @link https://core.telegram.org/bots/api#passportelementerrorunspecified
- *
- * @method string getSource() Error source, must be unspecified
- * @method string getType() Type of element of the user's Telegram Passport which has the issue
- * @method string getElementHash() Base64-encoded element hash
- * @method string getMessage() Error message
- */
-class PassportElementErrorUnspecified extends Entity implements PassportElementError
-{
- /**
- * PassportElementErrorUnspecified constructor
- *
- * @param array $data
- */
- public function __construct(array $data = [])
- {
- $data['source'] = 'unspecified';
- parent::__construct($data);
- }
-}
diff --git a/src/Entities/TelegramPassport/PassportFile.php b/src/Entities/TelegramPassport/PassportFile.php
deleted file mode 100644
index 13f6fa230..000000000
--- a/src/Entities/TelegramPassport/PassportFile.php
+++ /dev/null
@@ -1,31 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities\TelegramPassport;
-
-use Longman\TelegramBot\Entities\Entity;
-
-/**
- * Class PassportFile
- *
- * This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB.
- *
- * @link https://core.telegram.org/bots/api#passportfile
- *
- * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
- * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
- * @method int getFileSize() File size
- * @method int getFileDate() Unix time when the file was uploaded
- **/
-class PassportFile extends Entity
-{
-
-}
diff --git a/src/Entities/TextQuote.php b/src/Entities/TextQuote.php
index 9e237d795..2136e6884 100644
--- a/src/Entities/TextQuote.php
+++ b/src/Entities/TextQuote.php
@@ -1,35 +1,28 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+namespace PhpTelegramBot\Core\Entities;
-namespace Longman\TelegramBot\Entities;
+use PhpTelegramBot\Core\Contracts\AllowsBypassingGet;
/**
- * This object contains information about the quoted part of a message that is replied to by the given message.
- *
- * @link https://core.telegram.org/bots/api#textquote
- *
- * @method string getText() Text of the quoted part of a message that is replied to by the given message
- * @method MessageEntity[] getEntities() Optional. Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, and custom_emoji entities are kept in quotes.
- * @method int getPosition() Approximate quote position in the original message in UTF-16 code units as specified by the sender
- * @method bool getIsManual() Optional. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server.
+ * @method string getText() Text of the quoted part of a message that is replied to by the given message
+ * @method MessageEntity[]|null getEntities() Optional. Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, and custom_emoji entities are kept in quotes.
+ * @method int getPosition() Approximate quote position in the original message in UTF-16 code units as specified by the sender
+ * @method bool isManual() Optional. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server.
*/
-class TextQuote extends Entity
+class TextQuote extends Entity implements AllowsBypassingGet
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'entities' => [MessageEntity::class],
];
}
+
+ public static function fieldsBypassingGet(): array
+ {
+ return [
+ 'is_manual' => false,
+ ];
+ }
}
diff --git a/src/Entities/Topics/ForumTopicClosed.php b/src/Entities/Topics/ForumTopicClosed.php
deleted file mode 100644
index 7adf25b66..000000000
--- a/src/Entities/Topics/ForumTopicClosed.php
+++ /dev/null
@@ -1,15 +0,0 @@
- new TransactionPartnerUser($data),
+ self::TYPE_FRAGMENT => new TransactionPartnerFragment($data),
+ self::TYPE_TELEGRAM_ADS => new TransactionPartnerTelegramAds($data),
+ self::TYPE_OTHER => new TransactionPartnerOther($data),
+ };
+ }
+}
diff --git a/src/Entities/TransactionPartner/TransactionPartnerFragment.php b/src/Entities/TransactionPartner/TransactionPartnerFragment.php
new file mode 100644
index 000000000..c63b2694c
--- /dev/null
+++ b/src/Entities/TransactionPartner/TransactionPartnerFragment.php
@@ -0,0 +1,18 @@
+ RevenueWithdrawalState::class,
+ ];
+ }
+}
diff --git a/src/Entities/TransactionPartner/TransactionPartnerOther.php b/src/Entities/TransactionPartner/TransactionPartnerOther.php
new file mode 100644
index 000000000..51e2a5ad6
--- /dev/null
+++ b/src/Entities/TransactionPartner/TransactionPartnerOther.php
@@ -0,0 +1,8 @@
+ User::class,
+ ];
+ }
+}
diff --git a/src/Entities/Update.php b/src/Entities/Update.php
index 716b1830d..65b1b8e2e 100644
--- a/src/Entities/Update.php
+++ b/src/Entities/Update.php
@@ -1,132 +1,59 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
-
-use Longman\TelegramBot\Entities\Payments\PreCheckoutQuery;
-use Longman\TelegramBot\Entities\Payments\ShippingQuery;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class Update
- *
- * @link https://core.telegram.org/bots/api#update
- *
- * @method int getUpdateId() The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
- * @method Message getMessage() Optional. New incoming message of any kind — text, photo, sticker, etc.
- * @method Message getEditedMessage() Optional. New version of a message that is known to the bot and was edited
- * @method Message getChannelPost() Optional. New post in the channel, can be any kind — text, photo, sticker, etc.
- * @method Message getEditedChannelPost() Optional. New version of a post in the channel that is known to the bot and was edited
- * @method MessageReactionUpdated getMessageReaction() Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify "message_reaction" in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots.
- * @method MessageReactionCountUpdated getMessageReactionCount() Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify "message_reaction_count" in the list of allowed_updates to receive these updates. The updates are grouped and can be sent with delay up to a few minutes.
- * @method InlineQuery getInlineQuery() Optional. New incoming inline query
- * @method ChosenInlineResult getChosenInlineResult() Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
- * @method CallbackQuery getCallbackQuery() Optional. New incoming callback query
- * @method ShippingQuery getShippingQuery() Optional. New incoming shipping query. Only for invoices with flexible price
- * @method PreCheckoutQuery getPreCheckoutQuery() Optional. New incoming pre-checkout query. Contains full information about checkout
- * @method Poll getPoll() Optional. New poll state. Bots receive only updates about polls, which are sent or stopped by the bot
- * @method PollAnswer getPollAnswer() Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.
- * @method ChatMemberUpdated getMyChatMember() Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.
- * @method ChatMemberUpdated getChatMember() Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates.
- * @method ChatJoinRequest getChatJoinRequest() Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.
- * @method ChatBoostUpdated getChatBoost() Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.
- * @method ChatBoostRemoved getRemovedChatBoost() Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.
+ * @method int getUpdateId() The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This identifier becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.
+ * @method Message|null getMessage() Optional. New incoming message of any kind - text, photo, sticker, etc.
+ * @method Message|null getEditedMessage() Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.
+ * @method Message|null getChannelPost() Optional. New incoming channel post of any kind - text, photo, sticker, etc.
+ * @method Message|null getEditedChannelPost() Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.
+ * @method BusinessConnection|null getBusinessConnection() Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot
+ * @method Message|null getBusinessMessage() Optional. New message from a connected business account
+ * @method Message|null getEditedBusinessMessage() Optional. New version of a message from a connected business account
+ * @method BusinessMessagesDeleted|null getDeletedBusinessMessages() Optional. Messages were deleted from a connected business account
+ * @method MessageReactionUpdated getMessageReaction() Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify "message_reaction" in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots.
+ * @method MessageReactionCountUpdated getMessageReactionCount() Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify "message_reaction_count" in the list of allowed_updates to receive these updates. The updates are grouped and can be sent with delay up to a few minutes.
+ * @method InlineQuery|null getInlineQuery() Optional. New incoming inline query
+ * @method ChosenInlineResult|null getChosenInlineResult() Optional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot.
+ * @method CallbackQuery|null getCallbackQuery() Optional. New incoming callback query
+ * @method ShippingQuery|null getShippingQuery() Optional. New incoming shipping query. Only for invoices with flexible price
+ * @method PreCheckoutQuery|null getPreCheckoutQuery() Optional. New incoming pre-checkout query. Contains full information about checkout
+ * @method Poll|null getPoll() Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot
+ * @method PollAnswer|null getPollAnswer() Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.
+ * @method ChatMemberUpdated|null getMyChatMember() Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.
+ * @method ChatMemberUpdated|null getChatMember() Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify "chat_member" in the list of allowed_updates to receive these updates.
+ * @method ChatJoinRequest|null getChatJoinRequest() Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.
+ * @method ChatBoostUpdated|null getChatBoost() Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.
+ * @method ChatBoostRemoved|null getRemovedChatBoost() Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.
*/
class Update extends Entity
{
- public const TYPE_MESSAGE = 'message';
- public const TYPE_EDITED_MESSAGE = 'edited_message';
- public const TYPE_CHANNEL_POST = 'channel_post';
- public const TYPE_EDITED_CHANNEL_POST = 'edited_channel_post';
- public const TYPE_MESSAGE_REACTION = 'message_reaction';
- public const TYPE_MESSAGE_REACTION_COUNT = 'message_reaction_count';
- public const TYPE_INLINE_QUERY = 'inline_query';
- public const TYPE_CHOSEN_INLINE_RESULT = 'chosen_inline_result';
- public const TYPE_CALLBACK_QUERY = 'callback_query';
- public const TYPE_SHIPPING_QUERY = 'shipping_query';
- public const TYPE_PRE_CHECKOUT_QUERY = 'pre_checkout_query';
- public const TYPE_POLL = 'poll';
- public const TYPE_POLL_ANSWER = 'poll_answer';
- public const TYPE_MY_CHAT_MEMBER = 'my_chat_member';
- public const TYPE_CHAT_MEMBER = 'chat_member';
- public const TYPE_CHAT_JOIN_REQUEST = 'chat_join_request';
- public const TYPE_CHAT_BOOST = 'chat_boost';
- public const TYPE_REMOVED_CHAT_BOOST = 'removed_chat_boost';
-
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
- self::TYPE_MESSAGE => Message::class,
- self::TYPE_EDITED_MESSAGE => EditedMessage::class,
- self::TYPE_CHANNEL_POST => ChannelPost::class,
- self::TYPE_EDITED_CHANNEL_POST => EditedChannelPost::class,
- self::TYPE_MESSAGE_REACTION => MessageReactionUpdated::class,
- self::TYPE_MESSAGE_REACTION_COUNT => MessageReactionCountUpdated::class,
- self::TYPE_INLINE_QUERY => InlineQuery::class,
- self::TYPE_CHOSEN_INLINE_RESULT => ChosenInlineResult::class,
- self::TYPE_CALLBACK_QUERY => CallbackQuery::class,
- self::TYPE_SHIPPING_QUERY => ShippingQuery::class,
- self::TYPE_PRE_CHECKOUT_QUERY => PreCheckoutQuery::class,
- self::TYPE_POLL => Poll::class,
- self::TYPE_POLL_ANSWER => PollAnswer::class,
- self::TYPE_MY_CHAT_MEMBER => ChatMemberUpdated::class,
- self::TYPE_CHAT_MEMBER => ChatMemberUpdated::class,
- self::TYPE_CHAT_JOIN_REQUEST => ChatJoinRequest::class,
- self::TYPE_CHAT_BOOST => ChatBoostUpdated::class,
- self::TYPE_REMOVED_CHAT_BOOST => ChatBoostRemoved::class,
+ 'message' => Message::class,
+ 'edited_message' => Message::class,
+ 'channel_post' => Message::class,
+ 'edited_channel_post' => Message::class,
+ 'business_connection' => BusinessConnection::class,
+ 'business_message' => Message::class,
+ 'edited_business_message' => Message::class,
+ 'deleted_business_messages' => BusinessMessagesDeleted::class,
+ 'message_reaction' => MessageReactionUpdated::class,
+ 'message_reaction_count' => MessageReactionCountUpdated::class,
+ 'inline_query' => InlineQuery::class,
+ 'chosen_inline_result' => ChosenInlineResult::class,
+ 'callback_query' => CallbackQuery::class,
+ 'shipping_query' => ShippingQuery::class,
+ 'pre_checkout_query' => PreCheckoutQuery::class,
+ 'poll' => Poll::class,
+ 'poll_answer' => PollAnswer::class,
+ 'my_chat_member' => ChatMemberUpdated::class,
+ 'chat_member' => ChatMemberUpdated::class,
+ 'chat_join_request' => ChatJoinRequest::class,
+ 'chat_boost' => ChatBoostUpdated::class,
+ 'removed_chat_boost' => ChatBoostRemoved::class,
];
}
-
- /**
- * Get the list of all available update types
- *
- * @return string[]
- */
- public static function getUpdateTypes(): array
- {
- return array_keys((new self([]))->subEntities());
- }
-
- /**
- * Get the update type based on the set properties
- *
- * @return string|null
- */
- public function getUpdateType(): ?string
- {
- foreach (self::getUpdateTypes() as $type) {
- if ($this->getProperty($type)) {
- return $type;
- }
- }
-
- return null;
- }
-
- /**
- * Get update content
- *
- * @return Message|EditedMessage|ChannelPost|EditedChannelPost|MessageReactionUpdated|MessageReactionCountUpdated|InlineQuery|ChosenInlineResult|CallbackQuery|ShippingQuery|PreCheckoutQuery|Poll|PollAnswer|ChatMemberUpdated|ChatJoinRequest|ChatBoostUpdated|ChatBoostRemoved
- */
- public function getUpdateContent()
- {
- if ($update_type = $this->getUpdateType()) {
- // Instead of just getting the property as an array,
- // use the __call method to get the correct Entity object.
- $method = 'get' . str_replace('_', '', ucwords($update_type, '_'));
- return $this->$method();
- }
-
- return null;
- }
}
diff --git a/src/Entities/User.php b/src/Entities/User.php
index bc412b01f..f124796ba 100644
--- a/src/Entities/User.php
+++ b/src/Entities/User.php
@@ -1,34 +1,33 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+namespace PhpTelegramBot\Core\Entities;
-namespace Longman\TelegramBot\Entities;
+use PhpTelegramBot\Core\Contracts\AllowsBypassingGet;
/**
- * Class User
- *
- * @link https://core.telegram.org/bots/api#user
- *
- * @method int getId() Unique identifier for this user or bot
- * @method bool getIsBot() True, if this user is a bot
- * @method string getFirstName() User's or bot’s first name
- * @method string getLastName() Optional. User's or bot’s last name
- * @method string getUsername() Optional. User's or bot’s username
- * @method string getLanguageCode() Optional. IETF language tag of the user's language
- * @method bool getIsPremium() Optional. True, if this user is a Telegram Premium user
- * @method bool getAddedToAttachmentMenu() Optional. True, if this user added the bot to the attachment menu
- * @method bool getCanJoinGroups() Optional. True, if the bot can be invited to groups. Returned only in getMe.
- * @method bool getCanReadAllGroupMessages() Optional. True, if privacy mode is disabled for the bot. Returned only in getMe.
- * @method bool getSupportsInlineQueries() Optional. True, if the bot supports inline queries. Returned only in getMe.
+ * @method int getId() Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
+ * @method bool isBot() True, if this user is a bot
+ * @method string getFirstName() User's or bot's first name
+ * @method string|null getLastName() Optional. User's or bot's last name
+ * @method string|null getUsername() Optional. User's or bot's username
+ * @method string|null getLanguageCode() Optional. IETF language tag of the user's language
+ * @method bool isPremium() Optional. True, if this user is a Telegram Premium user
+ * @method true|null getAddedToAttachmentMenu() Optional. True, if this user added the bot to the attachment menu
+ * @method bool canJoinGroups() Optional. True, if the bot can be invited to groups. Returned only in getMe.
+ * @method bool canReadAllGroupMessages() Optional. True, if privacy mode is disabled for the bot. Returned only in getMe.
+ * @method bool|null getSupportsInlineQueries() Optional. True, if the bot supports inline queries. Returned only in getMe.
+ * @method bool canConnectToBusiness() Optional. True, if the bot can be connected to a Telegram Business account to receive its messages. Returned only in getMe.
*/
-class User extends Entity
+class User extends Entity implements AllowsBypassingGet
{
-
+ public static function fieldsBypassingGet(): array
+ {
+ return [
+ 'is_bot' => false,
+ 'is_premium' => false,
+ 'can_join_groups' => false,
+ 'can_read_all_group_messages' => false,
+ 'can_connect_to_business' => false,
+ ];
+ }
}
diff --git a/src/Entities/UserChatBoosts.php b/src/Entities/UserChatBoosts.php
index de45ddb14..32d013e25 100644
--- a/src/Entities/UserChatBoosts.php
+++ b/src/Entities/UserChatBoosts.php
@@ -1,29 +1,13 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * This object represents a list of boosts added to a chat by a user.
- *
- * @link https://core.telegram.org/bots/api#userchatboosts
- *
* @method ChatBoost[] getBoosts() The list of boosts added to the chat by the user
*/
class UserChatBoosts extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'boosts' => [ChatBoost::class],
diff --git a/src/Entities/UserProfilePhotos.php b/src/Entities/UserProfilePhotos.php
index e39dfc8eb..03d27987e 100644
--- a/src/Entities/UserProfilePhotos.php
+++ b/src/Entities/UserProfilePhotos.php
@@ -1,54 +1,17 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class UserProfilePhotos
- *
- * @link https://core.telegram.org/bots/api#userprofilephotos
- *
- * @method int getTotalCount() Total number of profile pictures the target user has
+ * @method int getTotalCount() Total number of profile pictures the target user has
+ * @method array[] getPhotos() Requested profile pictures (in up to 4 sizes each).
*/
class UserProfilePhotos extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
- 'photos' => PhotoSize::class,
+ 'photos' => [[PhotoSize::class]],
];
}
-
- /**
- * Requested profile pictures (in up to 4 sizes each)
- *
- * This method overrides the default getPhotos method and returns a nice array
- *
- * @return PhotoSize[][]
- */
- public function getPhotos(): array
- {
- $all_photos = [];
-
- if ($these_photos = $this->getProperty('photos')) {
- foreach ($these_photos as $photos) {
- $all_photos[] = array_map(function ($photo) {
- return new PhotoSize($photo);
- }, $photos);
- }
- }
-
- return $all_photos;
- }
}
diff --git a/src/Entities/UsersShared.php b/src/Entities/UsersShared.php
index ab32c2c90..571d41726 100644
--- a/src/Entities/UsersShared.php
+++ b/src/Entities/UsersShared.php
@@ -1,16 +1,17 @@
[SharedUser::class],
+ ];
+ }
}
diff --git a/src/Entities/Venue.php b/src/Entities/Venue.php
index 00925702d..d727ef8de 100644
--- a/src/Entities/Venue.php
+++ b/src/Entities/Venue.php
@@ -1,35 +1,19 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class Venue
- *
- * @link https://core.telegram.org/bots/api#venue
- *
- * @method Location getLocation() Venue location
- * @method string getTitle() Name of the venue
- * @method string getAddress() Address of the venue
- * @method string getFoursquareId() Optional. Foursquare identifier of the venue
- * @method string getFoursquareType() Optional. Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
- * @method string getGooglePlaceId() Optional. Google Places identifier of the venue
- * @method string getGooglePlaceType() Optional. Google Places type of the venue
+ * @method Location getLocation() Venue location. Can't be a live location
+ * @method string getTitle() Name of the venue
+ * @method string getAddress() Address of the venue
+ * @method string|null getFoursquareId() Optional. Foursquare identifier of the venue
+ * @method string|null getFoursquareType() Optional. Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
+ * @method string|null getGooglePlaceId() Optional. Google Places identifier of the venue
+ * @method string|null getGooglePlaceType() Optional. Google Places type of the venue. (See supported types.)
*/
class Venue extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'location' => Location::class,
diff --git a/src/Entities/Video.php b/src/Entities/Video.php
index 972f04da8..7a46e9878 100644
--- a/src/Entities/Video.php
+++ b/src/Entities/Video.php
@@ -1,37 +1,21 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class Video
- *
- * @link https://core.telegram.org/bots/api#video
- *
- * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
- * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
- * @method int getWidth() Video width as defined by sender
- * @method int getHeight() Video height as defined by sender
- * @method int getDuration() Duration of the video in seconds as defined by sender
- * @method PhotoSize getThumbnail() Optional. Video thumbnail
- * @method string getFileName() Optional. Original filename as defined by sender
- * @method string getMimeType() Optional. Mime type of a file as defined by sender
- * @method int getFileSize() Optional. File size
+ * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
+ * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
+ * @method int getWidth() Video width as defined by sender
+ * @method int getHeight() Video height as defined by sender
+ * @method int getDuration() Duration of the video in seconds as defined by sender
+ * @method PhotoSize|null getThumbnail() Optional. Video thumbnail
+ * @method string|null getFileName() Optional. Original filename as defined by sender
+ * @method string|null getMimeType() Optional. MIME type of the file as defined by sender
+ * @method int|null getFileSize() Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
*/
class Video extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'thumbnail' => PhotoSize::class,
diff --git a/src/Entities/VideoChatEnded.php b/src/Entities/VideoChatEnded.php
index 5f3a52773..171c351ee 100644
--- a/src/Entities/VideoChatEnded.php
+++ b/src/Entities/VideoChatEnded.php
@@ -1,24 +1,11 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * This object represents a service message about a video chat ended in the chat.
- *
- * @link https://core.telegram.org/bots/api#videochatended
- *
- * @method int getDuration() Video chat duration in seconds
+ * @method int getDuration() Video chat duration in seconds
*/
class VideoChatEnded extends Entity
{
-
+ //
}
diff --git a/src/Entities/VideoChatParticipantsInvited.php b/src/Entities/VideoChatParticipantsInvited.php
index 36a67b58e..dca1cd6da 100644
--- a/src/Entities/VideoChatParticipantsInvited.php
+++ b/src/Entities/VideoChatParticipantsInvited.php
@@ -1,29 +1,13 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * This object represents a service message about new members invited to a video chat.
- *
- * @link https://core.telegram.org/bots/api#videochatparticipantsinvited
- *
- * @method User[] getUsers() New members that were invited to the video chat
+ * @method User[] getUsers() New members that were invited to the video chat
*/
class VideoChatParticipantsInvited extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'users' => [User::class],
diff --git a/src/Entities/VideoChatScheduled.php b/src/Entities/VideoChatScheduled.php
index 6ac750197..652c7fcaf 100644
--- a/src/Entities/VideoChatScheduled.php
+++ b/src/Entities/VideoChatScheduled.php
@@ -1,24 +1,11 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * This object represents a service message about a video chat scheduled in the chat.
- *
- * @link https://core.telegram.org/bots/api#videochatscheduled
- *
* @method int getStartDate() Point in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator
*/
class VideoChatScheduled extends Entity
{
-
+ //
}
diff --git a/src/Entities/VideoChatStarted.php b/src/Entities/VideoChatStarted.php
index 4e10aa8d5..ee783f383 100644
--- a/src/Entities/VideoChatStarted.php
+++ b/src/Entities/VideoChatStarted.php
@@ -1,22 +1,8 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+namespace PhpTelegramBot\Core\Entities;
-namespace Longman\TelegramBot\Entities;
-
-/**
- * This object represents a service message about a video chat started in the chat. Currently holds no information.
- *
- * @link https://core.telegram.org/bots/api#videochatstarted
- */
class VideoChatStarted extends Entity
{
-
+ //
}
diff --git a/src/Entities/VideoNote.php b/src/Entities/VideoNote.php
index 164934967..aa4e5685c 100644
--- a/src/Entities/VideoNote.php
+++ b/src/Entities/VideoNote.php
@@ -1,34 +1,18 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class VideoNote
- *
- * @link https://core.telegram.org/bots/api#videonote
- *
- * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
- * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
- * @method int getLength() Video width and height as defined by sender
- * @method int getDuration() Duration of the audio in seconds as defined by sender
- * @method PhotoSize getThumbnail() Optional. Video thumbnail as defined by sender
- * @method int getFileSize() Optional. File size
+ * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
+ * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
+ * @method int getLength() Video width and height (diameter of the video message), as defined by sender
+ * @method int getDuration() Duration of the video in seconds as defined by sender
+ * @method PhotoSize|null getThumbnail() Optional. Video thumbnail
+ * @method int|null getFileSize() Optional. File size in bytes
*/
class VideoNote extends Entity
{
- /**
- * {@inheritdoc}
- */
- protected function subEntities(): array
+ protected static function subEntities(): array
{
return [
'thumbnail' => PhotoSize::class,
diff --git a/src/Entities/Voice.php b/src/Entities/Voice.php
index 1aab3b21e..ac6834e3c 100644
--- a/src/Entities/Voice.php
+++ b/src/Entities/Voice.php
@@ -1,28 +1,15 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Entities;
+namespace PhpTelegramBot\Core\Entities;
/**
- * Class Voice
- *
- * @link https://core.telegram.org/bots/api#voice
- *
- * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
- * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
- * @method int getDuration() Duration of the audio in seconds as defined by sender
- * @method string getMimeType() Optional. MIME type of the file as defined by sender
- * @method int getFileSize() Optional. File size
+ * @method string getFileId() Identifier for this file, which can be used to download or reuse the file
+ * @method string getFileUniqueId() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
+ * @method int getDuration() Duration of the audio in seconds as defined by sender
+ * @method string|null getMimeType() Optional. MIME type of the file as defined by sender
+ * @method int|null getFileSize() Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
*/
-class Voice extends Entity
+class Voice
{
-
+ //
}
diff --git a/src/Entities/WebAppData.php b/src/Entities/WebAppData.php
index e23ec53c8..6dc3ca4f4 100644
--- a/src/Entities/WebAppData.php
+++ b/src/Entities/WebAppData.php
@@ -1,21 +1,12 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+namespace PhpTelegramBot\Core\Entities;
-namespace Longman\TelegramBot\Entities;
+use PhpTelegramBot\Core\Contracts\AllowsBypassingGet;
/**
- * Class WebhookInfo
- *
- * @link https://core.telegram.org/bots/api#webhookinfo
- *
- * @method string getUrl() Webhook URL, may be empty if webhook is not set up
- * @method bool getHasCustomCertificate() True, if a custom certificate was provided for webhook certificate checks
- * @method int getPendingUpdateCount() Number of updates awaiting delivery
- * @method string getIpAddress() Optional. Currently used webhook IP address
- * @method int getLastErrorDate() Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook
- * @method string getLastErrorMessage() Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook
- * @method int getLastSynchronizationErrorDate() Optional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters
- * @method int getMaxConnections() Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery
- * @method string[] getAllowedUpdates() Optional. A list of update types the bot is subscribed to. Defaults to all update types
+ * @method string getUrl() Webhook URL, may be empty if webhook is not set up
+ * @method bool hasCustomCertificate() True, if a custom certificate was provided for webhook certificate checks
+ * @method int getPendingUpdateCount() Number of updates awaiting delivery
+ * @method string|null getIpAddress() Optional. Currently used webhook IP address
+ * @method int|null getLastErrorDate() Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook
+ * @method string|null getLastErrorMessage() Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook
+ * @method int|null getLastSynchronizationErrorDate() Optional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters
+ * @method int|null getMaxConnections() Optional. The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery
+ * @method string[]|null getAllowedUpdates() Optional. A list of update types the bot is subscribed to. Defaults to all update types except chat_member
*/
-class WebhookInfo extends Entity
+class WebhookInfo extends Entity implements AllowsBypassingGet
{
-
+ //
+ public static function fieldsBypassingGet(): array
+ {
+ return [
+ 'has_custom_certificate' => false,
+ ];
+ }
}
diff --git a/src/Entities/WriteAccessAllowed.php b/src/Entities/WriteAccessAllowed.php
index 5785732eb..c0d9dca90 100644
--- a/src/Entities/WriteAccessAllowed.php
+++ b/src/Entities/WriteAccessAllowed.php
@@ -1,19 +1,13 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Exception;
-
-/**
- * Thrown when bot token is invalid
- */
-class InvalidBotTokenException extends TelegramException
-{
- /**
- * InvalidBotTokenException constructor
- */
- public function __construct()
- {
- parent::__construct('Invalid bot token!');
- }
-}
diff --git a/src/Exception/TelegramException.php b/src/Exception/TelegramException.php
deleted file mode 100644
index fb0acbec1..000000000
--- a/src/Exception/TelegramException.php
+++ /dev/null
@@ -1,22 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Exception;
-
-use Exception;
-
-/**
- * Main exception class used for exception handling
- */
-class TelegramException extends Exception
-{
-
-}
diff --git a/src/Exception/TelegramLogException.php b/src/Exception/TelegramLogException.php
deleted file mode 100644
index 282ab5557..000000000
--- a/src/Exception/TelegramLogException.php
+++ /dev/null
@@ -1,20 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Exception;
-
-/**
- * Main exception class used for exception handling
- */
-class TelegramLogException extends TelegramException
-{
-
-}
diff --git a/src/Exceptions/InvalidArgumentException.php b/src/Exceptions/InvalidArgumentException.php
new file mode 100644
index 000000000..b3217772e
--- /dev/null
+++ b/src/Exceptions/InvalidArgumentException.php
@@ -0,0 +1,8 @@
+client ??= Psr18ClientDiscovery::find();
+ $this->requestFactory ??= Psr17FactoryDiscovery::findRequestFactory();
+ $this->streamFactory ??= Psr17FactoryDiscovery::findStreamFactory();
+ }
+
+ public function get(string $uri): ResponseInterface
+ {
+ return $this->client->sendRequest(
+ $this->requestFactory->createRequest('GET', $uri)
+ );
+ }
+
+ public function postJson(string $uri, array $data): ResponseInterface
+ {
+ $json = json_encode($data);
+
+ return $this->client->sendRequest(
+ $this->requestFactory->createRequest('POST', $uri)
+ ->withHeader('Content-Type', 'application/json')
+ ->withBody(
+ $this->streamFactory->createStream($json)
+ )
+ );
+ }
+
+ /**
+ * @param array $streams
+ *
+ * @throws \Psr\Http\Client\ClientExceptionInterface
+ */
+ public function postMultipart(string $uri, array $data, array $streams): ResponseInterface
+ {
+ $builder = new MultipartStreamBuilder($this->streamFactory);
+
+ // Add data
+ foreach ($data as $key => $value) {
+ $value = match (true) {
+ is_array($value) => json_encode($value),
+ default => (string) $value,
+ };
+
+ $builder->addResource($key, $value);
+ }
+
+ // Add file streams
+ foreach ($streams as $fileId => $stream) {
+ $builder->addResource($fileId, $stream);
+ }
+
+ $boundary = $builder->getBoundary();
+
+ return $this->client->sendRequest(
+ $this->requestFactory->createRequest('POST', $uri)
+ ->withHeader('Content-Type', "multipart/form-data; boundary=\"$boundary\"")
+ ->withBody($builder->build())
+ );
+ }
+
+ public function streamFactory(): StreamFactoryInterface
+ {
+ return $this->streamFactory;
+ }
+}
diff --git a/src/Request.php b/src/Request.php
deleted file mode 100644
index 21a7a5f7a..000000000
--- a/src/Request.php
+++ /dev/null
@@ -1,1038 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot;
-
-use GuzzleHttp\Client;
-use GuzzleHttp\ClientInterface;
-use GuzzleHttp\Exception\ConnectException;
-use GuzzleHttp\Exception\RequestException;
-use GuzzleHttp\Psr7\Stream;
-use Longman\TelegramBot\Entities\File;
-use Longman\TelegramBot\Entities\InputMedia\InputMedia;
-use Longman\TelegramBot\Entities\Message;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Exception\InvalidBotTokenException;
-use Longman\TelegramBot\Exception\TelegramException;
-use Throwable;
-
-/**
- * Class Request
- *
- * @method static ServerResponse getUpdates(array $data) Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse forwardMessage(array $data) Use this method to forward messages of any kind. On success, the sent Message is returned.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse sendPhoto(array $data) Use this method to send photos. On success, the sent Message is returned.
- * @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.
- * @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.
- * @method static ServerResponse sendSticker(array $data) Use this method to send .webp stickers. On success, the sent Message is returned.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse sendVideoNote(array $data) Use this method to send video messages. On success, the sent Message is returned.
- * @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.
- * @method static ServerResponse sendLocation(array $data) Use this method to send point on the map. On success, the sent Message is returned.
- * @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.
- * @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.
- * @method static ServerResponse sendVenue(array $data) Use this method to send information about a venue. On success, the sent Message is returned.
- * @method static ServerResponse sendContact(array $data) Use this method to send phone contacts. On success, the sent Message is returned.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse getUserProfilePhotos(array $data) Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
- * @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/, where 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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse leaveChat(array $data) Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
- * @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.
- * @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.
- * @method static ServerResponse getChatMemberCount(array $data) Use this method to get the number of members in a chat. Returns Int on success.
- * @method static ServerResponse getChatMember(array $data) Use this method to get information about a member of a chat. Returns a ChatMember object on success.
- * @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.
- * @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.
- * @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
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse answerInlineQuery(array $data) Use this method to send answers to an inline query. On success, True is returned.
- * @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.
- * @method static ServerResponse setMyCommands(array $data) Use this method to change the list of the bot's commands. Returns True on success.
- * @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.
- * @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.
- * @method static ServerResponse setMyName(array $data) Use this method to change the bot's name. Returns True on success.
- * @method static ServerResponse getMyName(array $data) Use this method to get the current bot name for the given user language. Returns BotName on success.
- * @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.
- * @method static ServerResponse getMyDescription(array $data) Use this method to get the current bot description for the given user language. Returns BotDescription on success.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse getMyDefaultAdministratorRights(array $data) Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse deleteMessage(array $data) Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
- * @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.
- * @method static ServerResponse getStickerSet(array $data) Use this method to get a sticker set. On success, a StickerSet object is returned.
- * @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.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse deleteStickerFromSet(array $data) Use this method to delete a sticker from a set created by the bot. Returns True on success.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse setStickerSetTitle(array $data) Use this method to set the title of a created sticker set. Returns True on success.
- * @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.
- * @method static ServerResponse setCustomEmojiStickerSetThumbnail(array $data) Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success.
- * @method static ServerResponse deleteStickerSet(array $data) Use this method to delete a sticker set that was created by the bot. Returns True on success.
- * @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.
- * @method static ServerResponse sendInvoice(array $data) Use this method to send invoices. On success, the sent Message is returned.
- * @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.
- * @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.
- * @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.
- * @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.
- * @method static ServerResponse sendGame(array $data) Use this method to send a game. On success, the sent Message is returned.
- * @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.
- * @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.
- */
-class Request
-{
- /**
- * Telegram object
- *
- * @var Telegram
- */
- private static $telegram;
-
- /**
- * URI of the Telegram API
- *
- * @var string
- */
- private static $api_base_uri = 'https://api.telegram.org';
-
- /**
- * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
- *
- * @var string
- */
- private static $api_base_download_uri = '/file/bot{API_KEY}';
-
- /**
- * Guzzle Client object
- *
- * @var ClientInterface
- */
- private static $client;
-
- /**
- * Request limiter
- *
- * @var bool
- */
- private static $limiter_enabled;
-
- /**
- * Request limiter's interval between checks
- *
- * @var float
- */
- private static $limiter_interval;
-
- /**
- * The current action that is being executed
- *
- * @var string
- */
- private static $current_action = '';
-
- /**
- * Available actions to send
- *
- * This is basically the list of all methods listed on the official API documentation.
- *
- * @link https://core.telegram.org/bots/api
- *
- * @var array
- */
- private static $actions = [
- 'getUpdates',
- 'setWebhook',
- 'deleteWebhook',
- 'getWebhookInfo',
- 'getMe',
- 'logOut',
- 'close',
- 'sendMessage',
- 'forwardMessage',
- 'forwardMessages',
- 'copyMessage',
- 'copyMessages',
- 'sendPhoto',
- 'sendAudio',
- 'sendDocument',
- 'sendSticker',
- 'sendVideo',
- 'sendAnimation',
- 'sendVoice',
- 'sendVideoNote',
- 'sendMediaGroup',
- 'sendLocation',
- 'editMessageLiveLocation',
- 'stopMessageLiveLocation',
- 'sendVenue',
- 'sendContact',
- 'sendPoll',
- 'sendDice',
- 'sendChatAction',
- 'setMessageReaction',
- 'getUserProfilePhotos',
- 'getFile',
- 'banChatMember',
- 'unbanChatMember',
- 'restrictChatMember',
- 'promoteChatMember',
- 'setChatAdministratorCustomTitle',
- 'banChatSenderChat',
- 'unbanChatSenderChat',
- 'setChatPermissions',
- 'exportChatInviteLink',
- 'createChatInviteLink',
- 'editChatInviteLink',
- 'revokeChatInviteLink',
- 'approveChatJoinRequest',
- 'declineChatJoinRequest',
- 'setChatPhoto',
- 'deleteChatPhoto',
- 'setChatTitle',
- 'setChatDescription',
- 'pinChatMessage',
- 'unpinChatMessage',
- 'unpinAllChatMessages',
- 'leaveChat',
- 'getChat',
- 'getChatAdministrators',
- 'getChatMemberCount',
- 'getChatMember',
- 'setChatStickerSet',
- 'deleteChatStickerSet',
- 'getForumTopicIconStickers',
- 'createForumTopic',
- 'editForumTopic',
- 'closeForumTopic',
- 'reopenForumTopic',
- 'deleteForumTopic',
- 'unpinAllForumTopicMessages',
- 'editGeneralForumTopic',
- 'closeGeneralForumTopic',
- 'reopenGeneralForumTopic',
- 'hideGeneralForumTopic',
- 'unhideGeneralForumTopic',
- 'unpinAllGeneralForumTopicMessages',
- 'answerCallbackQuery',
- 'answerInlineQuery',
- 'getUserChatBoosts',
- 'setMyCommands',
- 'deleteMyCommands',
- 'getMyCommands',
- 'setMyName',
- 'getMyName',
- 'setMyDescription',
- 'getMyDescription',
- 'setMyShortDescription',
- 'getMyShortDescription',
- 'setChatMenuButton',
- 'getChatMenuButton',
- 'setMyDefaultAdministratorRights',
- 'getMyDefaultAdministratorRights',
- 'editMessageText',
- 'editMessageCaption',
- 'editMessageMedia',
- 'editMessageReplyMarkup',
- 'stopPoll',
- 'deleteMessage',
- 'deleteMessages',
- 'getStickerSet',
- 'getCustomEmojiStickers',
- 'uploadStickerFile',
- 'createNewStickerSet',
- 'addStickerToSet',
- 'setStickerPositionInSet',
- 'deleteStickerFromSet',
- 'setStickerEmojiList',
- 'setStickerKeywords',
- 'setStickerMaskPosition',
- 'setStickerSetTitle',
- 'setStickerSetThumbnail',
- 'setCustomEmojiStickerSetThumbnail',
- 'deleteStickerSet',
- 'answerWebAppQuery',
- 'sendInvoice',
- 'createInvoiceLink',
- 'answerShippingQuery',
- 'answerPreCheckoutQuery',
- 'setPassportDataErrors',
- 'sendGame',
- 'setGameScore',
- 'getGameHighScores',
- ];
-
- /**
- * Methods that don't require any data need a dummy param due to certain cURL issues.
- *
- * @see Request::addDummyParamIfNecessary()
- *
- * @var array
- */
- private static $actions_need_dummy_param = [
- 'deleteWebhook',
- 'getWebhookInfo',
- 'getMe',
- 'logOut',
- 'close',
- 'deleteMyCommands',
- 'getMyCommands',
- 'setMyName',
- 'getMyName',
- 'setMyDescription',
- 'getMyDescription',
- 'setMyShortDescription',
- 'getMyShortDescription',
- 'setChatMenuButton',
- 'getChatMenuButton',
- 'setMyDefaultAdministratorRights',
- 'getMyDefaultAdministratorRights',
- ];
-
- /**
- * Available fields for InputFile helper
- *
- * This is basically the list of all fields that allow InputFile objects
- * for which input can be simplified by providing local path directly as string.
- *
- * @var array
- */
- private static $input_file_fields = [
- 'setWebhook' => ['certificate'],
- 'sendPhoto' => ['photo'],
- 'sendAudio' => ['audio', 'thumbnail'],
- 'sendDocument' => ['document', 'thumbnail'],
- 'sendVideo' => ['video', 'thumbnail'],
- 'sendAnimation' => ['animation', 'thumbnail'],
- 'sendVoice' => ['voice'],
- 'sendVideoNote' => ['video_note', 'thumbnail'],
- 'setChatPhoto' => ['photo'],
- 'sendSticker' => ['sticker'],
- 'uploadStickerFile' => ['sticker'],
- // @todo Look into new InputSticker field and see if we can do the same there.
- // 'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
- // 'addStickerToSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
- 'setStickerSetThumbnail' => ['thumbnail'],
- ];
-
- /**
- * Initialize
- *
- * @param Telegram $telegram
- */
- public static function initialize(Telegram $telegram): void
- {
- self::$telegram = $telegram;
- self::setClient(self::$client ?: new Client(['base_uri' => self::$api_base_uri]));
- }
-
- /**
- * Set a custom Guzzle HTTP Client object
- *
- * @param ClientInterface $client
- */
- public static function setClient(ClientInterface $client): void
- {
- self::$client = $client;
- }
-
- /**
- * Set a custom Bot API URL
- *
- * @param string $api_base_uri
- * @param string $api_base_download_uri
- */
- public static function setCustomBotApiUri(string $api_base_uri, string $api_base_download_uri = ''): void
- {
- self::$api_base_uri = $api_base_uri;
- if ($api_base_download_uri !== '') {
- self::$api_base_download_uri = $api_base_download_uri;
- }
- }
-
- /**
- * Get input from custom input or stdin and return it
- *
- * @return string
- */
- public static function getInput(): string
- {
- // First check if a custom input has been set, else get the PHP input.
- return self::$telegram->getCustomInput()
- ?: file_get_contents('php://input');
- }
-
- /**
- * Generate general fake server response
- *
- * @param array $data Data to add to fake response
- *
- * @return array Fake response data
- */
- public static function generateGeneralFakeServerResponse(array $data = []): array
- {
- //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
- //Maybe this is not the best possible implementation
-
- //No value set in $data ie testing setWebhook
- //Provided $data['chat_id'] ie testing sendMessage
-
- $fake_response = ['ok' => true]; // :)
-
- if ($data === []) {
- $fake_response['result'] = true;
- }
-
- //some data to initialize the class method SendMessage
- if (isset($data['chat_id'])) {
- $data['message_id'] = '1234';
- $data['date'] = '1441378360';
- $data['from'] = [
- 'id' => 123456789,
- 'first_name' => 'botname',
- 'username' => 'namebot',
- ];
- $data['chat'] = ['id' => $data['chat_id']];
-
- $fake_response['result'] = $data;
- }
-
- return $fake_response;
- }
-
- /**
- * Properly set up the request params
- *
- * If any item of the array is a resource, reformat it to a multipart request.
- * Else, just return the passed data as form params.
- *
- * @param array $data
- *
- * @return array
- * @throws TelegramException
- */
- private static function setUpRequestParams(array $data): array
- {
- $has_resource = false;
- $multipart = [];
-
- foreach ($data as $key => &$item) {
- if ($key === 'media') {
- // Magical media input helper.
- $item = self::mediaInputHelper($item, $has_resource, $multipart);
- } elseif (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
- // Allow absolute paths to local files.
- if (is_string($item) && file_exists($item)) {
- $item = new Stream(self::encodeFile($item));
- }
- } elseif (is_array($item) || is_object($item)) {
- // Convert any nested arrays or objects into JSON strings.
- $item = json_encode($item);
- }
-
- // Reformat data array in multipart way if it contains a resource
- $has_resource = $has_resource || is_resource($item) || $item instanceof Stream;
- $multipart[] = ['name' => $key, 'contents' => $item];
- }
- unset($item);
-
- if ($has_resource) {
- return ['multipart' => $multipart];
- }
-
- return ['form_params' => $data];
- }
-
- /**
- * Magical input media helper to simplify passing media.
- *
- * This allows the following:
- * Request::editMessageMedia([
- * ...
- * 'media' => new InputMediaPhoto([
- * 'caption' => 'Caption!',
- * 'media' => Request::encodeFile($local_photo),
- * ]),
- * ]);
- * and
- * Request::sendMediaGroup([
- * 'media' => [
- * new InputMediaPhoto(['media' => Request::encodeFile($local_photo_1)]),
- * new InputMediaPhoto(['media' => Request::encodeFile($local_photo_2)]),
- * new InputMediaVideo(['media' => Request::encodeFile($local_video_1)]),
- * ],
- * ]);
- * and even
- * Request::sendMediaGroup([
- * 'media' => [
- * new InputMediaPhoto(['media' => $local_photo_1]),
- * new InputMediaPhoto(['media' => $local_photo_2]),
- * new InputMediaVideo(['media' => $local_video_1]),
- * ],
- * ]);
- *
- * @param mixed $item
- * @param bool $has_resource
- * @param array $multipart
- *
- * @return mixed
- * @throws TelegramException
- */
- private static function mediaInputHelper($item, bool &$has_resource, array &$multipart)
- {
- $was_array = is_array($item);
- $was_array || $item = [$item];
-
- /** @var InputMedia|null $media_item */
- foreach ($item as $media_item) {
- if (!($media_item instanceof InputMedia)) {
- continue;
- }
-
- // Make a list of all possible media that can be handled by the helper.
- $possible_medias = array_filter([
- 'media' => $media_item->getMedia(),
- 'thumbnail' => $media_item->getThumbnail(),
- ]);
-
- foreach ($possible_medias as $type => $media) {
- // Allow absolute paths to local files.
- if (is_string($media) && strpos($media, 'attach://') !== 0 && file_exists($media)) {
- $media = new Stream(self::encodeFile($media));
- }
-
- if (is_resource($media) || $media instanceof Stream) {
- $has_resource = true;
- $unique_key = uniqid($type . '_', false);
- $multipart[] = ['name' => $unique_key, 'contents' => $media];
-
- // We're literally overwriting the passed media type data!
- $media_item->$type = 'attach://' . $unique_key;
- $media_item->raw_data[$type] = 'attach://' . $unique_key;
- }
- }
- }
-
- $was_array || $item = reset($item);
-
- return json_encode($item);
- }
-
- /**
- * Get the current action that's being executed
- *
- * @return string
- */
- public static function getCurrentAction(): string
- {
- return self::$current_action;
- }
-
- /**
- * Execute HTTP Request
- *
- * @param string $action Action to execute
- * @param array $data Data to attach to the execution
- *
- * @return string Result of the HTTP Request
- * @throws TelegramException
- */
- public static function execute(string $action, array $data = []): string
- {
- $request_params = self::setUpRequestParams($data);
- $request_params['debug'] = TelegramLog::getDebugLogTempStream();
-
- try {
- $response = self::$client->post(
- '/bot' . self::$telegram->getApiKey() . '/' . $action,
- $request_params
- );
- $result = (string) $response->getBody();
- } catch (ConnectException $e) {
- $response = null;
- $result = $e->getMessage();
- } catch (RequestException $e) {
- $response = null;
- $result = $e->getResponse() ? (string) $e->getResponse()->getBody() : '';
- }
-
- //Logging verbose debug output
- if (TelegramLog::$always_log_request_and_response || $response === null) {
- TelegramLog::debug('Request data:' . PHP_EOL . print_r($data, true));
- TelegramLog::debug('Response data:' . PHP_EOL . $result);
- TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
- }
-
- return $result;
- }
-
- /**
- * Download file
- *
- * @param File $file
- *
- * @return bool
- * @throws TelegramException
- */
- public static function downloadFile(File $file): bool
- {
- if (empty($download_path = self::$telegram->getDownloadPath())) {
- throw new TelegramException('Download path not set!');
- }
-
- $tg_file_path = $file->getFilePath();
- $file_path = $download_path . '/' . $tg_file_path;
-
- $file_dir = dirname($file_path);
- //For safety reasons, first try to create the directory, then check that it exists.
- //This is in case some other process has created the folder in the meantime.
- if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
- throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
- }
-
- $debug_handle = TelegramLog::getDebugLogTempStream();
-
- try {
- $base_download_uri = str_replace('{API_KEY}', self::$telegram->getApiKey(), self::$api_base_download_uri);
- self::$client->get(
- "{$base_download_uri}/{$tg_file_path}",
- ['debug' => $debug_handle, 'sink' => $file_path]
- );
-
- return filesize($file_path) > 0;
- } catch (Throwable $e) {
- return false;
- } finally {
- //Logging verbose debug output
- TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
- }
- }
-
- /**
- * Encode file
- *
- * @param string $file
- *
- * @return resource
- * @throws TelegramException
- */
- public static function encodeFile(string $file)
- {
- $fp = fopen($file, 'rb');
- if ($fp === false) {
- throw new TelegramException('Cannot open "' . $file . '" for reading');
- }
-
- return $fp;
- }
-
- /**
- * Send command
- *
- * @todo Fake response doesn't need json encoding?
- * @todo Write debug entry on failure
- *
- * @param string $action
- * @param array $data
- *
- * @return ServerResponse
- * @throws TelegramException
- */
- public static function send(string $action, array $data = []): ServerResponse
- {
- self::ensureValidAction($action);
- self::addDummyParamIfNecessary($action, $data);
-
- $bot_username = self::$telegram->getBotUsername();
-
- if (defined('PHPUNIT_TESTSUITE')) {
- $fake_response = self::generateGeneralFakeServerResponse($data);
-
- return new ServerResponse($fake_response, $bot_username);
- }
-
- self::ensureNonEmptyData($data);
-
- self::limitTelegramRequests($action, $data);
-
- // Remember which action is currently being executed.
- self::$current_action = $action;
-
- $raw_response = self::execute($action, $data);
- $response = json_decode($raw_response, true);
-
- if (null === $response) {
- TelegramLog::debug($raw_response);
- throw new TelegramException('Telegram returned an invalid response!');
- }
-
- $response = new ServerResponse($response, $bot_username);
-
- if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
- throw new InvalidBotTokenException();
- }
-
- // Special case for sent polls, which need to be saved specially.
- // @todo Take into account if DB gets extracted into separate module.
- if ($response->isOk() && ($message = $response->getResult()) && ($message instanceof Message) && $poll = $message->getPoll()) {
- DB::insertPollRequest($poll);
- }
-
- // Reset current action after completion.
- self::$current_action = '';
-
- return $response;
- }
-
- /**
- * Add a dummy parameter if the passed action requires it.
- *
- * If a method doesn't require parameters, we need to add a dummy one anyway,
- * because of some cURL version failed POST request without parameters.
- *
- * @link https://github.com/php-telegram-bot/core/pull/228
- *
- * @todo Would be nice to find a better solution for this!
- *
- * @param string $action
- * @param array $data
- */
- protected static function addDummyParamIfNecessary(string $action, array &$data): void
- {
- if (empty($data) && in_array($action, self::$actions_need_dummy_param, true)) {
- // Can be anything, using a single letter to minimise request size.
- $data = ['d'];
- }
- }
-
- /**
- * Make sure the data isn't empty, else throw an exception
- *
- * @param array $data
- *
- * @throws TelegramException
- */
- private static function ensureNonEmptyData(array $data): void
- {
- if (count($data) === 0) {
- throw new TelegramException('Data is empty!');
- }
- }
-
- /**
- * Make sure the action is valid, else throw an exception
- *
- * @param string $action
- *
- * @throws TelegramException
- */
- private static function ensureValidAction(string $action): void
- {
- if (!in_array($action, self::$actions, true)) {
- throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
- }
- }
-
- /**
- * Use this method to send text messages. On success, the last sent Message is returned
- *
- * All message responses are saved in `$extras['responses']`.
- * Custom encoding can be defined in `$extras['encoding']` (default: `mb_internal_encoding()`)
- * Custom splitting can be defined in `$extras['split']` (default: 4096)
- * `$extras['split'] = null;` // force to not split message at all!
- * `$extras['split'] = 200;` // split message into 200 character chunks
- *
- * @link https://core.telegram.org/bots/api#sendmessage
- *
- * @todo Splitting formatted text may break the message.
- *
- * @param array $data
- * @param array|null $extras
- *
- * @return ServerResponse
- * @throws TelegramException
- */
- public static function sendMessage(array $data, ?array &$extras = []): ServerResponse
- {
- $extras = array_merge([
- 'split' => 4096,
- 'encoding' => mb_internal_encoding(),
- ], (array) $extras);
-
- $text = $data['text'];
- $encoding = $extras['encoding'];
- $max_length = $extras['split'] ?: mb_strlen($text, $encoding);
-
- $responses = [];
-
- do {
- // Chop off and send the first message.
- $data['text'] = mb_substr($text, 0, $max_length, $encoding);
- $responses[] = self::send('sendMessage', $data);
-
- // Prepare the next message.
- $text = mb_substr($text, $max_length, null, $encoding);
- } while ($text !== '');
-
- // Add all response objects to referenced variable.
- $extras['responses'] = $responses;
-
- return end($responses);
- }
-
- /**
- * Any statically called method should be relayed to the `send` method.
- *
- * @param string $action
- * @param array $data
- *
- * @return ServerResponse
- * @throws TelegramException
- */
- public static function __callStatic(string $action, array $data): ServerResponse
- {
- // Only argument should be the data array, ignore any others.
- return static::send($action, reset($data) ?: []);
- }
-
- /**
- * Return an empty Server Response
- *
- * No request is sent to Telegram.
- * This function is used in commands that don't need to fire a message after execution
- *
- * @return ServerResponse
- */
- public static function emptyResponse(): ServerResponse
- {
- return new ServerResponse(['ok' => true, 'result' => true]);
- }
-
- /**
- * Send message to all active chats
- *
- * @param string $callback_function
- * @param array $data
- * @param array $select_chats_params
- *
- * @return array
- * @throws TelegramException
- */
- public static function sendToActiveChats(
- string $callback_function,
- array $data,
- array $select_chats_params
- ): array {
- self::ensureValidAction($callback_function);
-
- $chats = DB::selectChats($select_chats_params);
-
- $results = [];
- if (is_array($chats)) {
- foreach ($chats as $row) {
- $data['chat_id'] = $row['chat_id'];
- $results[] = self::send($callback_function, $data);
- }
- }
-
- return $results;
- }
-
- /**
- * Enable request limiter
- *
- * @param bool $enable
- * @param array $options
- *
- * @throws TelegramException
- */
- public static function setLimiter(bool $enable = true, array $options = []): void
- {
- if (DB::isDbConnected()) {
- $options_default = [
- 'interval' => 1,
- ];
-
- $options = array_merge($options_default, $options);
-
- if (!is_numeric($options['interval']) || $options['interval'] <= 0) {
- throw new TelegramException('Interval must be a number and must be greater than zero!');
- }
-
- self::$limiter_interval = $options['interval'];
- self::$limiter_enabled = $enable;
- }
- }
-
- /**
- * This functions delays API requests to prevent reaching Telegram API limits
- * Can be disabled while in execution by 'Request::setLimiter(false)'
- *
- * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
- *
- * @param string $action
- * @param array $data
- *
- * @throws TelegramException
- */
- private static function limitTelegramRequests(string $action, array $data = []): void
- {
- if (self::$limiter_enabled) {
- $limited_methods = [
- 'sendMessage',
- 'forwardMessage',
- 'forwardMessages',
- 'copyMessage',
- 'copyMessages',
- 'sendPhoto',
- 'sendAudio',
- 'sendDocument',
- 'sendSticker',
- 'sendVideo',
- 'sendAnimation',
- 'sendVoice',
- 'sendVideoNote',
- 'sendMediaGroup',
- 'sendLocation',
- 'editMessageLiveLocation',
- 'stopMessageLiveLocation',
- 'sendVenue',
- 'sendContact',
- 'sendPoll',
- 'sendDice',
- 'setMessageReaction',
- 'sendInvoice',
- 'sendGame',
- 'setGameScore',
- 'setMyCommands',
- 'deleteMyCommands',
- 'editMessageText',
- 'editMessageCaption',
- 'editMessageMedia',
- 'editMessageReplyMarkup',
- 'stopPoll',
- 'deleteMessage',
- 'deleteMessages',
- 'setChatTitle',
- 'setChatDescription',
- 'setChatStickerSet',
- 'deleteChatStickerSet',
- 'setPassportDataErrors',
- ];
-
- $chat_id = $data['chat_id'] ?? null;
- $inline_message_id = $data['inline_message_id'] ?? null;
-
- if (($chat_id || $inline_message_id) && in_array($action, $limited_methods, true)) {
- $timeout = 60;
-
- while (true) {
- if ($timeout <= 0) {
- throw new TelegramException('Timed out while waiting for a request spot!');
- }
-
- if (!($requests = DB::getTelegramRequestCount($chat_id, $inline_message_id))) {
- break;
- }
-
- // Make sure we're handling integers here.
- $requests = array_map('intval', $requests);
-
- $chat_per_second = ($requests['LIMIT_PER_SEC'] === 0); // No more than one message per second inside a particular chat
- $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30); // No more than 30 messages per second to different chats
- $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
-
- if ($chat_per_second && $global_per_second && $groups_per_minute) {
- break;
- }
-
- $timeout--;
- usleep((int) (self::$limiter_interval * 1000000));
- }
-
- DB::insertTelegramRequest($action, $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.
- *
- * @deprecated
- * @see Request::banChatMember()
- *
- * @param array $data
- *
- * @return ServerResponse
- */
- public static function kickChatMember(array $data = []): ServerResponse
- {
- return static::banChatMember($data);
- }
-}
diff --git a/src/Telegram.php b/src/Telegram.php
index bbc948052..704ffdc09 100644
--- a/src/Telegram.php
+++ b/src/Telegram.php
@@ -1,1336 +1,418 @@
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot;
-
-defined('TB_BASE_PATH') || define('TB_BASE_PATH', __DIR__);
-defined('TB_BASE_COMMANDS_PATH') || define('TB_BASE_COMMANDS_PATH', TB_BASE_PATH . '/Commands');
-
-use Exception;
-use InvalidArgumentException;
-use Longman\TelegramBot\Commands\AdminCommand;
-use Longman\TelegramBot\Commands\Command;
-use Longman\TelegramBot\Commands\SystemCommand;
-use Longman\TelegramBot\Commands\UserCommand;
-use Longman\TelegramBot\Entities\Chat;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Entities\Update;
-use Longman\TelegramBot\Entities\User;
-use Longman\TelegramBot\Exception\TelegramException;
-use PDO;
-use RecursiveDirectoryIterator;
-use RecursiveIteratorIterator;
-use RegexIterator;
+namespace PhpTelegramBot\Core;
+
+use PhpTelegramBot\Core\ApiMethods\AnswersInlineQueries;
+use PhpTelegramBot\Core\ApiMethods\SendsInvoices;
+use PhpTelegramBot\Core\ApiMethods\SendsMessages;
+use PhpTelegramBot\Core\ApiMethods\SendsStickers;
+use PhpTelegramBot\Core\ApiMethods\UpdatesMessages;
+use PhpTelegramBot\Core\Contracts\Factory;
+use PhpTelegramBot\Core\Entities\Update;
+use PhpTelegramBot\Core\Events\Event;
+use PhpTelegramBot\Core\Events\IncomingUpdate;
+use PhpTelegramBot\Core\Events\UnregisteredCommand;
+use PhpTelegramBot\Core\Events\UnregisteredMessageType;
+use PhpTelegramBot\Core\Events\UnregisteredUpdateType;
+use PhpTelegramBot\Core\Exceptions\InvalidArgumentException;
+use PhpTelegramBot\Core\Exceptions\TelegramException;
+use Psr\Http\Message\StreamInterface;
+
+use function PhpTelegramBot\Core\Helpers\array_is_assoc;
class Telegram
{
- /**
- * Version
- *
- * @var string
- */
- protected $version = '0.82.0';
-
- /**
- * Telegram API key
- *
- * @var string
- */
- protected $api_key = '';
-
- /**
- * Telegram Bot username
- *
- * @var string
- */
- protected $bot_username = '';
-
- /**
- * Telegram Bot id
- *
- * @var int
- */
- protected $bot_id = 0;
-
- /**
- * Raw request data (json) for webhook methods
- *
- * @var string
- */
- protected $input = '';
-
- /**
- * Custom commands paths
- *
- * @var array
- */
- protected $commands_paths = [];
-
- /**
- * Custom command class names
- * ```
- * [
- * 'User' => [
- * // command_name => command_class
- * 'start' => 'name\space\to\StartCommand',
- * ],
- * 'Admin' => [], //etc
- * ]
- * ```
- *
- * @var array
- */
- protected $command_classes = [
- Command::AUTH_USER => [],
- Command::AUTH_ADMIN => [],
- Command::AUTH_SYSTEM => [],
- ];
-
- /**
- * Custom commands objects
- *
- * @var array
- */
- protected $commands_objects = [];
-
- /**
- * Current Update object
- *
- * @var Update
- */
- protected $update;
-
- /**
- * Upload path
- *
- * @var string
- */
- protected $upload_path = '';
-
- /**
- * Download path
- *
- * @var string
- */
- protected $download_path = '';
-
- /**
- * MySQL integration
- *
- * @var bool
- */
- protected $mysql_enabled = false;
-
- /**
- * PDO object
- *
- * @var PDO
- */
- protected $pdo;
-
- /**
- * Commands config
- *
- * @var array
- */
- protected $commands_config = [];
-
- /**
- * Admins list
- *
- * @var array
- */
- protected $admins_list = [];
-
- /**
- * ServerResponse of the last Command execution
- *
- * @var ServerResponse
- */
- protected $last_command_response;
-
- /**
- * Check if runCommands() is running in this session
- *
- * @var bool
- */
- protected $run_commands = false;
-
- /**
- * Is running getUpdates without DB enabled
- *
- * @var bool
- */
- protected $getupdates_without_database = false;
-
- /**
- * Last update ID
- * Only used when running getUpdates without a database
- *
- * @var int
- */
- protected $last_update_id;
-
- /**
- * The command to be executed when there's a new message update and nothing more suitable is found
- */
- public const GENERIC_MESSAGE_COMMAND = 'genericmessage';
-
- /**
- * The command to be executed by default (when no other relevant commands are applicable)
- */
- public const GENERIC_COMMAND = 'generic';
-
- /**
- * Update filter method
- *
- * @var callable
- */
- protected $update_filter;
-
- /**
- * Telegram constructor.
- *
- * @param string $api_key
- * @param string $bot_username
- *
- * @throws TelegramException
- */
- public function __construct(string $api_key, string $bot_username = '')
- {
- if (empty($api_key)) {
- throw new TelegramException('API KEY not defined!');
- }
- preg_match('/(\d+):[\w\-]+/', $api_key, $matches);
- if (!isset($matches[1])) {
- throw new TelegramException('Invalid API KEY defined!');
- }
- $this->bot_id = (int) $matches[1];
- $this->api_key = $api_key;
-
- $this->bot_username = $bot_username;
-
- //Add default system commands path
- $this->addCommandsPath(TB_BASE_COMMANDS_PATH . '/SystemCommands');
-
- Request::initialize($this);
- }
+ use AnswersInlineQueries;
+ use SendsInvoices;
+ use SendsMessages;
+ use SendsStickers;
+ use UpdatesMessages;
+
+ protected string $apiBaseUri = 'https://api.telegram.org';
+
+ public static function inputFileFields(): array
+ {
+ return [
+ 'addStickerToSet' => [
+ 'sticker' => ['sticker'],
+ ],
+ 'createNewStickerSet' => [
+ 'stickers' => ['sticker'],
+ ],
+ 'editMessageMedia' => [
+ 'media' => ['media'],
+ ],
+ 'replaceStickerInSet' => [
+ 'sticker' => ['sticker'],
+ ],
+ 'sendAnimation' => ['animation', 'thumbnail'],
+ 'sendAudio' => ['audio', 'thumbnail'],
+ 'sendDocument' => ['document', 'thumbnail'],
+ 'sendMediaGroup' => [
+ 'media' => ['media', 'thumbnail'],
+ ],
+ 'sendPhoto' => ['photo'],
+ 'sendSticker' => ['sticker'],
+ 'sendVideo' => ['video', 'thumbnail'],
+ 'sendVideoNote' => ['video_note', 'thumbnail'],
+ 'sendPaidMedia' => [
+ 'media' => ['media', 'thumbnail'],
+ ],
+ 'sendVoice' => ['voice'],
+ 'setChatPhoto' => ['photo'],
+ 'setStickerSetThumbnail' => ['thumbnail'],
+ 'setWebhook' => ['certificate'],
+ 'uploadStickerFile' => ['sticker'],
+ ];
+ }
+ // .media
+
+ public function __construct(
+ #[\SensitiveParameter]
+ protected string $botToken,
+ protected ?string $botUsername = null,
+ protected ?HttpClient $client = null,
+ ) {
+ $this->client ??= new HttpClient();
+ }
+
+ public function __call(string $methodName, array $arguments): mixed
+ {
+ return $this->send($methodName, $arguments[0] ?? null, $arguments[1] ?? null);
+ }
+
+ /**
+ * @return StreamInterface[]
+ */
+ protected function extractFiles(array $fields, array &$data): array
+ {
+ $streams = [];
+ foreach ($fields as $key => $value) {
+
+ if (is_string($value)) {
+ if (! isset($data[$value])) {
+ continue;
+ }
- /**
- * Initialize Database connection
- *
- * @param array $credentials
- * @param string $table_prefix
- * @param string $encoding
- *
- * @return Telegram
- * @throws TelegramException
- */
- public function enableMySql(array $credentials, string $table_prefix = '', string $encoding = 'utf8mb4'): Telegram
- {
- $this->pdo = DB::initialize($credentials, $this, $table_prefix, $encoding);
- ConversationDB::initializeConversation();
- $this->mysql_enabled = true;
+ $file = $data[$value];
- return $this;
- }
+ if (is_string($file) && is_file($file) || is_resource($file) || $file instanceof StreamInterface) {
+ $fileId = uniqid($value . '_');
+ $data[$value] = 'attach://' . $fileId;
- /**
- * Initialize Database external connection
- *
- * @param PDO $external_pdo_connection PDO database object
- * @param string $table_prefix
- *
- * @return Telegram
- * @throws TelegramException
- */
- public function enableExternalMySql(PDO $external_pdo_connection, string $table_prefix = ''): Telegram
- {
- $this->pdo = DB::externalInitialize($external_pdo_connection, $this, $table_prefix);
- ConversationDB::initializeConversation();
- $this->mysql_enabled = true;
-
- return $this;
- }
-
- /**
- * Get commands list
- *
- * @return array $commands
- * @throws TelegramException
- */
- public function getCommandsList(): array
- {
- $commands = [];
-
- foreach ($this->commands_paths as $path) {
- try {
- //Get all "*Command.php" files
- $files = new RegexIterator(
- new RecursiveIteratorIterator(
- new RecursiveDirectoryIterator($path)
- ),
- '/^.+Command.php$/'
- );
-
- foreach ($files as $file) {
- // Convert filename to command
- $command = $this->classNameToCommandName(substr($file->getFilename(), 0, -4));
-
- // Invalid Classname
- if (is_null($command)) {
- continue;
- }
+ $streams[$fileId] = match (true) {
+ is_string($file) && is_file($file) => $this->client->streamFactory()->createStreamFromFile($file),
+ is_resource($file) => $this->client->streamFactory()->createStreamFromResource($file),
+ $file instanceof StreamInterface => $file,
+ };
+ }
+ } elseif (! array_is_assoc($data[$key])) {
- // Already registered
- if (array_key_exists($command, $commands)) {
- continue;
- }
+ foreach ($data[$key] as &$item) {
+ $streams += $this->extractFiles($value, $item);
+ }
- require_once $file->getPathname();
+ } else {
- $command_obj = $this->getCommandObject($command, $file->getPathname());
- if ($command_obj instanceof Command) {
- $commands[$command] = $command_obj;
- }
- }
- } catch (Exception $e) {
- throw new TelegramException('Error getting commands from path: ' . $path, 0, $e);
+ $streams += $this->extractFiles($value, $data[$key]);
}
}
- return $commands;
+ return $streams;
}
- /**
- * Get classname of predefined commands
- *
- * @see command_classes
- *
- * @param string $auth Auth of command
- * @param string $command Command name
- * @param string $filepath Path to the command file
- *
- * @return string|null
- */
- public function getCommandClassName(string $auth, string $command, string $filepath = ''): ?string
+ protected function send(string $methodName, ?array $data = null, string|array|null $returnType = null): mixed
{
- $command = mb_strtolower($command);
-
- // Invalid command
- if (trim($command) === '') {
- return null;
- }
+ $requestUri = $this->apiBaseUri . '/bot' . $this->botToken . '/' . $methodName;
- $auth = $this->ucFirstUnicode($auth);
+ $streams = $this->extractFiles(self::inputFileFields()[$methodName] ?? [], $data);
- // First, check for directly assigned command class.
- if ($command_class = $this->command_classes[$auth][$command] ?? null) {
- return $command_class;
- }
+ $response = match (true) {
+ empty($data) => $this->client->get($requestUri),
+ count($streams) > 0 => $this->client->postMultipart($requestUri, $data, $streams),
+ default => $this->client->postJson($requestUri, $data),
+ };
- // Start with default namespace.
- $command_namespace = __NAMESPACE__ . '\\Commands\\' . $auth . 'Commands';
+ $result = json_decode($response->getBody()->getContents(), true);
- // Check if we can get the namespace from the file (if passed).
- if ($filepath && !($command_namespace = $this->getFileNamespace($filepath))) {
- return null;
+ if ($result === null || $result['ok'] !== true) {
+ throw new TelegramException(
+ $result['description'] ?? $response->getReasonPhrase(),
+ $result['error_code'] ?? $response->getStatusCode(),
+ );
}
- $command_class = $command_namespace . '\\' . $this->commandNameToClassName($command);
-
- if (class_exists($command_class)) {
- return $command_class;
+ if ($returnType === null) {
+ return $result['result'];
}
- return null;
- }
+ if (is_array($returnType)) {
+ $returnType = $returnType[0];
- /**
- * Get an object instance of the passed command
- *
- * @param string $command
- * @param string $filepath
- *
- * @return Command|null
- */
- public function getCommandObject(string $command, string $filepath = ''): ?Command
- {
- if (isset($this->commands_objects[$command])) {
- return $this->commands_objects[$command];
+ return array_map(fn ($item) => $this->makeResultObject($item, $returnType), $result['result']);
}
- $which = [Command::AUTH_SYSTEM];
- $this->isAdmin() && $which[] = Command::AUTH_ADMIN;
- $which[] = Command::AUTH_USER;
-
- foreach ($which as $auth) {
- $command_class = $this->getCommandClassName($auth, $command, $filepath);
-
- if ($command_class) {
- $command_obj = new $command_class($this, $this->update);
-
- if ($auth === Command::AUTH_SYSTEM && $command_obj instanceof SystemCommand) {
- return $command_obj;
- }
- if ($auth === Command::AUTH_ADMIN && $command_obj instanceof AdminCommand) {
- return $command_obj;
- }
- if ($auth === Command::AUTH_USER && $command_obj instanceof UserCommand) {
- return $command_obj;
- }
- }
- }
-
- return null;
+ return $this->makeResultObject($result['result'], $returnType);
}
- /**
- * Get namespace from php file by src path
- *
- * @param string $src (absolute path to file)
- *
- * @return string|null ("Longman\TelegramBot\Commands\SystemCommands" for example)
- */
- protected function getFileNamespace(string $src): ?string
+ protected function makeResultObject(mixed $result, string|array|null $returnType = null): mixed
{
- $content = file_get_contents($src);
- if (preg_match('#^\s*namespace\s+(.+?);#m', $content, $m)) {
- return $m[1];
+ if (! is_array($result)) {
+ return $result;
}
- return null;
- }
-
- /**
- * Set custom input string for debug purposes
- *
- * @param string $input (json format)
- *
- * @return Telegram
- */
- public function setCustomInput(string $input): Telegram
- {
- $this->input = $input;
-
- return $this;
- }
-
- /**
- * Get custom input string for debug purposes
- *
- * @return string
- */
- public function getCustomInput(): string
- {
- return $this->input;
- }
+ if (is_subclass_of($returnType, Factory::class)) {
+ return $returnType::make($result);
+ }
- /**
- * Get the ServerResponse of the last Command execution
- *
- * @return ServerResponse
- */
- public function getLastCommandResponse(): ServerResponse
- {
- return $this->last_command_response;
+ return new $returnType($result);
}
- /**
- * Handle getUpdates method
- *
- * @todo Remove backwards compatibility for old signature and force $data to be an array.
- *
- * @param array|int|null $data
- * @param int|null $timeout
- *
- * @return ServerResponse
- * @throws TelegramException
- */
- public function handleGetUpdates($data = null, ?int $timeout = null): ServerResponse
+ public function handleGetUpdates(int $pollingInterval = 30, ?array $allowedUpdates = null)
{
- if (empty($this->bot_username)) {
- throw new TelegramException('Bot Username is not defined!');
- }
-
- if (!DB::isDbConnected() && !$this->getupdates_without_database) {
- return new ServerResponse(
- [
- 'ok' => false,
- 'description' => 'getUpdates needs MySQL connection! (This can be overridden - see documentation)',
- ],
- $this->bot_username
- );
- }
-
- $offset = 0;
- $limit = null;
-
- // By default, get update types sent by Telegram.
- $allowed_updates = [];
-
- // @todo Backwards compatibility for old signature, remove in next version.
- if (!is_array($data)) {
- $limit = $data;
-
- @trigger_error(
- sprintf('Use of $limit and $timeout parameters in %s is deprecated. Use $data array instead.', __METHOD__),
- E_USER_DEPRECATED
- );
- } else {
- $offset = $data['offset'] ?? $offset;
- $limit = $data['limit'] ?? $limit;
- $timeout = $data['timeout'] ?? $timeout;
- $allowed_updates = $data['allowed_updates'] ?? $allowed_updates;
- }
-
- // Take custom input into account.
- if ($custom_input = $this->getCustomInput()) {
- try {
- $input = json_decode($this->input, true, 512, JSON_THROW_ON_ERROR);
- if (empty($input)) {
- throw new TelegramException('Custom input is empty');
- }
- $response = new ServerResponse($input, $this->bot_username);
- } catch (\Throwable $e) {
- throw new TelegramException('Invalid custom input JSON: ' . $e->getMessage());
- }
- } else {
- if (DB::isDbConnected() && $last_update = DB::selectTelegramUpdate(1)) {
- // Get last Update id from the database.
- $last_update = reset($last_update);
- $this->last_update_id = $last_update['id'] ?? null;
- }
-
- if ($this->last_update_id !== null) {
- $offset = $this->last_update_id + 1; // As explained in the telegram bot API documentation.
- }
-
- $response = Request::getUpdates(compact('offset', 'limit', 'timeout', 'allowed_updates'));
- }
-
- if ($response->isOk()) {
- // Log update.
- TelegramLog::update($response->toJson());
+ $offset = null;
+ while (true) {
+ $updates = $this->getUpdates([
+ 'offset' => $offset,
+ 'timeout' => $pollingInterval,
+ 'allowed_updates' => $allowedUpdates,
+ ]);
- // Process all updates
- /** @var Update $update */
- foreach ($response->getResult() as $update) {
+ foreach ($updates as $update) {
$this->processUpdate($update);
- }
-
- if (!DB::isDbConnected() && !$custom_input && $this->last_update_id !== null && $offset === 0) {
- // Mark update(s) as read after handling
- $offset = $this->last_update_id + 1;
- $limit = 1;
-
- Request::getUpdates(compact('offset', 'limit', 'timeout', 'allowed_updates'));
+ $offset = $update->getUpdateId() + 1;
}
}
-
- return $response;
}
- /**
- * Handle bot request from webhook
- *
- * @return bool
- *
- * @throws TelegramException
- */
- public function handle(): bool
+ public function handle()
{
- if ($this->bot_username === '') {
- throw new TelegramException('Bot Username is not defined!');
- }
+ $data = file_get_contents('php://input');
- $input = Request::getInput();
- if (empty($input)) {
- throw new TelegramException('Input is empty! The webhook must not be called manually, only by Telegram.');
+ if (empty($data)) {
+ return;
}
- // Log update.
- TelegramLog::update($input);
-
- $post = json_decode($input, true);
- if (empty($post)) {
- throw new TelegramException('Invalid input JSON! The webhook must not be called manually, only by Telegram.');
- }
+ $json = json_decode($data, true);
- if ($response = $this->processUpdate(new Update($post, $this->bot_username))) {
- return $response->isOk();
- }
+ $update = new Update($json);
- return false;
+ $this->processUpdate($update);
}
- /**
- * Get the command name from the command type
- *
- * @param string $type
- *
- * @return string
- */
- protected function getCommandFromType(string $type): string
+ protected function dispatch(Event $event)
{
- return $this->ucFirstUnicode(str_replace('_', '', $type));
+ $listeners = $this->eventListeners[$event::class] ?? [];
+
+ foreach ($listeners as $callback) {
+ $callback($event, $this);
+ }
}
- /**
- * Process bot Update request
- *
- * @param Update $update
- *
- * @return ServerResponse
- * @throws TelegramException
- */
- public function processUpdate(Update $update): ServerResponse
+ protected function processUpdate(Update $update)
{
- $this->update = $update;
- $this->last_update_id = $update->getUpdateId();
-
- if (is_callable($this->update_filter)) {
- $reason = 'Update denied by update_filter';
- try {
- $allowed = (bool) call_user_func_array($this->update_filter, [$update, $this, &$reason]);
- } catch (Exception $e) {
- $allowed = false;
- }
+ // IncomingUpdate Event
+ $this->dispatch(new IncomingUpdate($update));
- if (!$allowed) {
- TelegramLog::debug($reason);
- return new ServerResponse(['ok' => false, 'description' => 'denied']);
+ // Update Types
+ $registeredUpdateType = false;
+ foreach ($this->updateTypeCallbacks as $key => $callbacks) {
+ if (! is_null($update->$key)) {
+ $registeredUpdateType = true;
+ foreach ($callbacks as $callback) {
+ $callback($update, $this);
+ }
}
}
- //Load admin commands
- if ($this->isAdmin()) {
- $this->addCommandsPath(TB_BASE_COMMANDS_PATH . '/AdminCommands', false);
+ if (! $registeredUpdateType) {
+ $this->dispatch(new UnregisteredUpdateType($update));
}
- //Make sure we have an up-to-date command list
- //This is necessary to "require" all the necessary command files!
- $this->commands_objects = $this->getCommandsList();
-
- //If all else fails, it's a generic message.
- $command = self::GENERIC_MESSAGE_COMMAND;
-
- $update_type = $this->update->getUpdateType();
- if ($update_type === 'message') {
- $message = $this->update->getMessage();
- $type = $message->getType();
-
- // Let's check if the message object has the type field we're looking for...
- $command_tmp = $type === 'command' ? $message->getCommand() : $this->getCommandFromType($type);
- // ...and if a fitting command class is available.
- $command_obj = $command_tmp ? $this->getCommandObject($command_tmp) : null;
-
- // Empty usage string denotes a non-executable command.
- // @see https://github.com/php-telegram-bot/core/issues/772#issuecomment-388616072
- if (
- ($command_obj === null && $type === 'command')
- || ($command_obj !== null && $command_obj->getUsage() !== '')
- ) {
- $command = $command_tmp;
+ // Message Types
+ $registeredMessageType = false;
+ $message = $update->getMessage();
+ if ($message !== null) {
+ foreach ($this->messageTypeCallbacks as $key => $callbacks) {
+ if (! is_null($message->$key)) {
+ $registeredMessageType = true;
+ foreach ($callbacks as $callback) {
+ $callback($update, $this);
+ }
+ }
}
- } elseif ($update_type !== null) {
- $command = $this->getCommandFromType($update_type);
}
- //Make sure we don't try to process update that was already processed
- $last_id = DB::selectTelegramUpdate(1, $this->update->getUpdateId());
- if ($last_id && count($last_id) === 1) {
- TelegramLog::debug('Duplicate update received, processing aborted!');
- return Request::emptyResponse();
+ if (! $registeredMessageType) {
+ $this->dispatch(new UnregisteredMessageType($update));
}
- DB::insertRequest($this->update);
+ // Commands
+ $registeredCommand = false;
+ $command = $update->getMessage()?->getText() ?? null;
+ if ($command !== null && str_starts_with($command, '/')) {
+ // Cut / from beginning
+ $command = ltrim($command, '/');
- return $this->executeCommand($command);
- }
+ // Cut username
+ $command = explode(' ', $command, 2)[0];
+ [$command, $username] = explode('@', $command, 2) + [null, null];
- /**
- * Execute /command
- *
- * @param string $command
- *
- * @return ServerResponse
- * @throws TelegramException
- */
- public function executeCommand(string $command): ServerResponse
- {
- $command = mb_strtolower($command);
+ // TODO: Check if the username belongs to this bot...
- $command_obj = $this->commands_objects[$command] ?? $this->getCommandObject($command);
+ // Get callbacks
+ $callbacks = $this->commandCallbacks[$command] ?? [];
- if (!$command_obj || !$command_obj->isEnabled()) {
- //Failsafe in case the Generic command can't be found
- if ($command === self::GENERIC_COMMAND) {
- throw new TelegramException('Generic command missing!');
+ if (! empty($callbacks)) {
+ $registeredCommand = true;
}
- //Handle a generic command or non existing one
- $this->last_command_response = $this->executeCommand(self::GENERIC_COMMAND);
- } else {
- //execute() method is executed after preExecute()
- //This is to prevent executing a DB query without a valid connection
- if ($this->update) {
- $this->last_command_response = $command_obj->setUpdate($this->update)->preExecute();
- } else {
- $this->last_command_response = $command_obj->preExecute();
+ foreach ($callbacks as $callback) {
+ $callback($update, $this);
}
}
- return $this->last_command_response;
- }
-
- /**
- * @deprecated
- *
- * @param string $command
- *
- * @return string
- */
- protected function sanitizeCommand(string $command): string
- {
- return str_replace(' ', '', $this->ucWordsUnicode(str_replace('_', ' ', $command)));
- }
-
- /**
- * Enable a single Admin account
- *
- * @param int $admin_id Single admin id
- *
- * @return Telegram
- */
- public function enableAdmin(int $admin_id): Telegram
- {
- if ($admin_id <= 0) {
- TelegramLog::error('Invalid value "' . $admin_id . '" for admin.');
- } elseif (!in_array($admin_id, $this->admins_list, true)) {
- $this->admins_list[] = $admin_id;
- }
-
- return $this;
- }
-
- /**
- * Enable a list of Admin Accounts
- *
- * @param array $admin_ids List of admin ids
- *
- * @return Telegram
- */
- public function enableAdmins(array $admin_ids): Telegram
- {
- foreach ($admin_ids as $admin_id) {
- $this->enableAdmin($admin_id);
+ if (! $registeredCommand) {
+ $this->dispatch(new UnregisteredCommand($update));
}
-
- return $this;
}
/**
- * Get list of admins
- *
- * @return array
+ * @var array, array>
*/
- public function getAdminList(): array
- {
- return $this->admins_list;
- }
+ protected array $eventListeners = [];
/**
- * Check if the passed user is an admin
- *
- * If no user id is passed, the current update is checked for a valid message sender.
- *
- * @param int|null $user_id
- *
- * @return bool
+ * @param class-string $event
+ * @param callable|array $callback
+ * @return $this
*/
- public function isAdmin($user_id = null): bool
+ public function registerEventListener(string $event, callable|array $callback): static
{
- if ($user_id === null && $this->update !== null) {
- //Try to figure out if the user is an admin
- $update_methods = [
- 'getMessage',
- 'getEditedMessage',
- 'getChannelPost',
- 'getEditedChannelPost',
- 'getInlineQuery',
- 'getChosenInlineResult',
- 'getCallbackQuery',
- ];
- foreach ($update_methods as $update_method) {
- $object = call_user_func([$this->update, $update_method]);
- if ($object !== null && $from = $object->getFrom()) {
- $user_id = $from->getId();
- break;
- }
- }
+ if (is_callable($callback)) {
+ $callback = [$callback];
}
- return ($user_id === null) ? false : in_array($user_id, $this->admins_list, true);
- }
-
- /**
- * Check if user required the db connection
- *
- * @return bool
- */
- public function isDbEnabled(): bool
- {
- return $this->mysql_enabled;
- }
-
- /**
- * Add a single custom command class
- *
- * @param string $command_class Full command class name
- *
- * @return Telegram
- */
- public function addCommandClass(string $command_class): Telegram
- {
- if (!$command_class || !class_exists($command_class)) {
- $error = sprintf('Command class "%s" does not exist.', $command_class);
- TelegramLog::error($error);
- throw new InvalidArgumentException($error);
- }
-
- if (!is_a($command_class, Command::class, true)) {
- $error = sprintf('Command class "%s" does not extend "%s".', $command_class, Command::class);
- TelegramLog::error($error);
- throw new InvalidArgumentException($error);
+ if (! is_subclass_of($event, Event::class)) {
+ throw new InvalidArgumentException("$event is not a PhpTelegramBot Event");
}
- // Dummy object to get data from.
- $command_object = new $command_class($this);
-
- $auth = null;
- $command_object->isSystemCommand() && $auth = Command::AUTH_SYSTEM;
- $command_object->isAdminCommand() && $auth = Command::AUTH_ADMIN;
- $command_object->isUserCommand() && $auth = Command::AUTH_USER;
-
- if ($auth) {
- $command = mb_strtolower($command_object->getName());
-
- $this->command_classes[$auth][$command] = $command_class;
- }
+ $this->eventListeners[$event] = array_merge($this->eventListeners[$event] ?? [], $callback);
return $this;
}
/**
- * Add multiple custom command classes
- *
- * @param array $command_classes List of full command class names
- *
- * @return Telegram
+ * @param array, callable|array> $callbacks
+ * @return $this
*/
- public function addCommandClasses(array $command_classes): Telegram
+ public function registerEventListeners(array $callbacks): static
{
- foreach ($command_classes as $command_class) {
- $this->addCommandClass($command_class);
+ foreach ($callbacks as $event => $callback) {
+ $this->registerEventListener($event, $callback);
}
return $this;
}
/**
- * Set a single custom commands path
- *
- * @param string $path Custom commands path to set
- *
- * @return Telegram
+ * @var array>
*/
- public function setCommandsPath(string $path): Telegram
- {
- $this->commands_paths = [];
-
- $this->addCommandsPath($path);
-
- return $this;
- }
+ protected array $updateTypeCallbacks = [];
/**
- * Add a single custom commands path
- *
- * @param string $path Custom commands path to add
- * @param bool $before If the path should be prepended or appended to the list
- *
- * @return Telegram
+ * @param callable|array $callback
+ * @return $this
*/
- public function addCommandsPath(string $path, bool $before = true): Telegram
+ public function registerUpdateType(string $updateType, callable|array $callback): static
{
- if (!is_dir($path)) {
- TelegramLog::error('Commands path "' . $path . '" does not exist.');
- } elseif (!in_array($path, $this->commands_paths, true)) {
- if ($before) {
- array_unshift($this->commands_paths, $path);
- } else {
- $this->commands_paths[] = $path;
- }
+ if (is_callable($callback)) {
+ $callback = [$callback];
}
- return $this;
- }
-
- /**
- * Set multiple custom commands paths
- *
- * @param array $paths Custom commands paths to add
- *
- * @return Telegram
- */
- public function setCommandsPaths(array $paths): Telegram
- {
- $this->commands_paths = [];
-
- $this->addCommandsPaths($paths);
+ $this->updateTypeCallbacks[$updateType] = array_merge($this->updateTypeCallbacks[$updateType] ?? [], $callback);
return $this;
}
/**
- * Add multiple custom commands paths
- *
- * @param array $paths Custom commands paths to add
- * @param bool $before If the paths should be prepended or appended to the list
- *
- * @return Telegram
+ * @param array> $callbacks
+ * @return $this
*/
- public function addCommandsPaths(array $paths, bool $before = true): Telegram
+ public function registerUpdateTypes(array $callbacks): Telegram
{
- foreach ($paths as $path) {
- $this->addCommandsPath($path, $before);
+ foreach ($callbacks as $type => $callback) {
+ $this->registerUpdateType($type, $callback);
}
return $this;
}
/**
- * Return the list of commands paths
- *
- * @return array
- */
- public function getCommandsPaths(): array
- {
- return $this->commands_paths;
- }
-
- /**
- * Return the list of command classes
- *
- * @return array
- */
- public function getCommandClasses(): array
- {
- return $this->command_classes;
- }
-
- /**
- * Set custom upload path
- *
- * @param string $path Custom upload path
- *
- * @return Telegram
+ * @var array>
*/
- public function setUploadPath(string $path): Telegram
- {
- $this->upload_path = $path;
-
- return $this;
- }
+ protected array $messageTypeCallbacks = [];
/**
- * Get custom upload path
- *
- * @return string
+ * @param callable|array $callback
+ * @return $this
*/
- public function getUploadPath(): string
+ public function registerMessageType(string $messageType, array|callable $callback): static
{
- return $this->upload_path;
- }
+ if (is_callable($callback)) {
+ $callback = [$callback];
+ }
- /**
- * Set custom download path
- *
- * @param string $path Custom download path
- *
- * @return Telegram
- */
- public function setDownloadPath(string $path): Telegram
- {
- $this->download_path = $path;
+ $this->messageTypeCallbacks[$messageType] = array_merge($this->messageTypeCallbacks[$messageType] ?? [], $callback);
return $this;
}
/**
- * Get custom download path
- *
- * @return string
+ * @param array> $callbacks
+ * @return $this
*/
- public function getDownloadPath(): string
+ public function registerMessageTypes(array $callbacks): static
{
- return $this->download_path;
- }
-
- /**
- * Set command config
- *
- * Provide further variables to a particular commands.
- * For example you can add the channel name at the command /sendtochannel
- * Or you can add the api key for external service.
- *
- * @param string $command
- * @param array $config
- *
- * @return Telegram
- */
- public function setCommandConfig(string $command, array $config): Telegram
- {
- $this->commands_config[$command] = $config;
+ foreach ($callbacks as $messageType => $callback) {
+ $this->registerMessageType($messageType, $callback);
+ }
return $this;
}
/**
- * Get command config
- *
- * @param string $command
- *
- * @return array
- */
- public function getCommandConfig(string $command): array
- {
- return $this->commands_config[$command] ?? [];
- }
-
- /**
- * Get API key
- *
- * @return string
- */
- public function getApiKey(): string
- {
- return $this->api_key;
- }
-
- /**
- * Get Bot name
- *
- * @return string
- */
- public function getBotUsername(): string
- {
- return $this->bot_username;
- }
-
- /**
- * Get Bot Id
- *
- * @return int
- */
- public function getBotId(): int
- {
- return $this->bot_id;
- }
-
- /**
- * Get Version
- *
- * @return string
- */
- public function getVersion(): string
- {
- return $this->version;
- }
-
- /**
- * Set Webhook for bot
- *
- * @param string $url
- * @param array $data Optional parameters.
- *
- * @return ServerResponse
- * @throws TelegramException
+ * @var array>
*/
- public function setWebhook(string $url, array $data = []): ServerResponse
- {
- if ($url === '') {
- throw new TelegramException('Hook url is empty!');
- }
-
- $data = array_intersect_key($data, array_flip([
- 'certificate',
- 'ip_address',
- 'max_connections',
- 'allowed_updates',
- 'drop_pending_updates',
- 'secret_token',
- ]));
- $data['url'] = $url;
-
- // If the certificate is passed as a path, encode and add the file to the data array.
- if (!empty($data['certificate']) && is_string($data['certificate'])) {
- $data['certificate'] = Request::encodeFile($data['certificate']);
- }
-
- $result = Request::setWebhook($data);
-
- if (!$result->isOk()) {
- throw new TelegramException(
- 'Webhook was not set! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
- );
- }
-
- return $result;
- }
+ protected array $commandCallbacks = [];
/**
- * Delete any assigned webhook
- *
- * @param array $data
- *
- * @return ServerResponse
- * @throws TelegramException
+ * @param callable|array $callback
+ * @return $this
*/
- public function deleteWebhook(array $data = []): ServerResponse
+ public function registerCommand(string $command, callable|array $callback): static
{
- $result = Request::deleteWebhook($data);
+ $command = ltrim($command, '/');
- if (!$result->isOk()) {
- throw new TelegramException(
- 'Webhook was not deleted! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
- );
+ if (is_callable($callback)) {
+ $callback = [$callback];
}
- return $result;
- }
-
- /**
- * Replace function `ucwords` for UTF-8 characters in the class definition and commands
- *
- * @param string $str
- * @param string $encoding (default = 'UTF-8')
- *
- * @return string
- */
- protected function ucWordsUnicode(string $str, string $encoding = 'UTF-8'): string
- {
- return mb_convert_case($str, MB_CASE_TITLE, $encoding);
- }
-
- /**
- * Replace function `ucfirst` for UTF-8 characters in the class definition and commands
- *
- * @param string $str
- * @param string $encoding (default = 'UTF-8')
- *
- * @return string
- */
- protected function ucFirstUnicode(string $str, string $encoding = 'UTF-8'): string
- {
- return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding)
- . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
- }
-
- /**
- * Enable requests limiter
- *
- * @param array $options
- *
- * @return Telegram
- * @throws TelegramException
- */
- public function enableLimiter(array $options = []): Telegram
- {
- Request::setLimiter(true, $options);
+ $this->commandCallbacks[$command] = array_merge($this->commandCallbacks[$command] ?? [], $callback);
return $this;
}
/**
- * Run provided commands
- *
- * @param array $commands
- *
- * @return ServerResponse[]
- *
- * @throws TelegramException
+ * @param array> $callbacks
+ * @return $this
*/
- public function runCommands(array $commands): array
+ public function registerCommands(array $callbacks): static
{
- if (empty($commands)) {
- throw new TelegramException('No command(s) provided!');
- }
-
- $this->run_commands = true;
-
- // Check if this request has a user Update / comes from Telegram.
- if ($userUpdate = $this->update) {
- $from = $this->update->getMessage()->getFrom();
- $chat = $this->update->getMessage()->getChat();
- } else {
- // Fall back to the Bot user.
- $from = new User([
- 'id' => $this->getBotId(),
- 'first_name' => $this->getBotUsername(),
- 'username' => $this->getBotUsername(),
- ]);
-
- // Try to get "live" Bot info.
- $response = Request::getMe();
- if ($response->isOk()) {
- /** @var User $result */
- $result = $response->getResult();
-
- $from = new User([
- 'id' => $result->getId(),
- 'first_name' => $result->getFirstName(),
- 'username' => $result->getUsername(),
- ]);
- }
-
- // Give Bot access to admin commands.
- $this->enableAdmin($from->getId());
-
- // Lock the bot to a private chat context.
- $chat = new Chat([
- 'id' => $from->getId(),
- 'type' => 'private',
- ]);
- }
-
- $newUpdate = static function ($text = '') use ($from, $chat) {
- return new Update([
- 'update_id' => -1,
- 'message' => [
- 'message_id' => -1,
- 'date' => time(),
- 'from' => json_decode($from->toJson(), true),
- 'chat' => json_decode($chat->toJson(), true),
- 'text' => $text,
- ],
- ]);
- };
-
- $responses = [];
-
- foreach ($commands as $command) {
- $this->update = $newUpdate($command);
-
- // Refresh commands list for new Update object.
- $this->commands_objects = $this->getCommandsList();
-
- $responses[] = $this->executeCommand($this->update->getMessage()->getCommand());
+ foreach ($callbacks as $command => $callback) {
+ $this->registerCommand($command, $callback);
}
- // Reset Update to initial context.
- $this->update = $userUpdate;
-
- return $responses;
- }
-
- /**
- * Is this session initiated by runCommands()
- *
- * @return bool
- */
- public function isRunCommands(): bool
- {
- return $this->run_commands;
- }
-
- /**
- * Switch to enable running getUpdates without a database
- *
- * @param bool $enable
- *
- * @return Telegram
- */
- public function useGetUpdatesWithoutDatabase(bool $enable = true): Telegram
- {
- $this->getupdates_without_database = $enable;
-
return $this;
}
-
- /**
- * Return last update id
- *
- * @return int|null
- */
- public function getLastUpdateId(): ?int
- {
- return $this->last_update_id;
- }
-
- /**
- * Set an update filter callback
- *
- * @param callable $callback
- *
- * @return Telegram
- */
- public function setUpdateFilter(callable $callback): Telegram
- {
- $this->update_filter = $callback;
-
- return $this;
- }
-
- /**
- * Return update filter callback
- *
- * @return callable|null
- */
- public function getUpdateFilter(): ?callable
- {
- return $this->update_filter;
- }
-
- /**
- * Converts the name of a class into the name of a command.
- *
- * @param string $class For example FooBarCommand
- *
- * @return string|null for example foo_bar. In case of errors, returns null.
- */
- protected function classNameToCommandName(string $class): ?string
- {
- // If $class doesn't end with 'Command'
- if (substr($class, -7) !== 'Command') {
- return null;
- }
-
- return mb_strtolower(preg_replace('/(.)(?=[\p{Lu}])/u', '$1_', substr($class, 0, -7)));
- }
-
- /**
- * Converts a command name into the name of a class.
- *
- * @param string $command For example foo_bar
- *
- * @return string|null for example FooBarCommand. In case of errors, returns null.
- */
- protected function commandNameToClassName(string $command): ?string
- {
- if (trim($command) === '') {
- return null;
- }
-
- return str_replace(' ', '', $this->ucWordsUnicode(str_replace('_', ' ', $command))) . 'Command';
- }
}
diff --git a/src/TelegramLog.php b/src/TelegramLog.php
deleted file mode 100644
index 449256ee9..000000000
--- a/src/TelegramLog.php
+++ /dev/null
@@ -1,168 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot;
-
-use Psr\Log\LoggerInterface;
-use Psr\Log\NullLogger;
-
-/**
- * Class TelegramLog
- *
- * @method static void emergency(string $message, array $context = [])
- * @method static void alert(string $message, array $context = [])
- * @method static void critical(string $message, array $context = [])
- * @method static void error(string $message, array $context = [])
- * @method static void warning(string $message, array $context = [])
- * @method static void notice(string $message, array $context = [])
- * @method static void info(string $message, array $context = [])
- * @method static void debug(string $message, array $context = [])
- * @method static void update(string $message, array $context = [])
- */
-class TelegramLog
-{
- /**
- * Logger instance
- *
- * @var LoggerInterface
- */
- protected static $logger;
-
- /**
- * Logger instance for update
- *
- * @var LoggerInterface
- */
- protected static $update_logger;
-
- /**
- * Always log the request and response data to the debug log, also for successful requests
- *
- * @var bool
- */
- public static $always_log_request_and_response = false;
-
- /**
- * Temporary stream handle for debug log
- *
- * @var resource|null
- */
- protected static $debug_log_temp_stream_handle;
-
- /**
- * Remove bot token from debug stream
- *
- * @var bool
- */
- public static $remove_bot_token = true;
-
- /**
- * Initialise logging.
- *
- * @param LoggerInterface|null $logger
- * @param LoggerInterface|null $update_logger
- */
- public static function initialize(LoggerInterface $logger = null, LoggerInterface $update_logger = null): void
- {
- self::$logger = $logger ?: new NullLogger();
- self::$update_logger = $update_logger ?: new NullLogger();
- }
-
- /**
- * Get the stream handle of the temporary debug output
- *
- * @return mixed The stream if debug is active, else false
- */
- public static function getDebugLogTempStream()
- {
- if ((self::$debug_log_temp_stream_handle === null) && $temp_stream_handle = fopen('php://temp', 'wb+')) {
- self::$debug_log_temp_stream_handle = $temp_stream_handle;
- }
-
- return self::$debug_log_temp_stream_handle;
- }
-
- /**
- * Write the temporary debug stream to log and close the stream handle
- *
- * @param string $message Message (with placeholder) to write to the debug log
- */
- public static function endDebugLogTempStream($message = '%s'): void
- {
- if (is_resource(self::$debug_log_temp_stream_handle)) {
- rewind(self::$debug_log_temp_stream_handle);
- $stream_contents = stream_get_contents(self::$debug_log_temp_stream_handle);
-
- if (self::$remove_bot_token) {
- $stream_contents = preg_replace('/\/bot(\d+):[\w\-]+\//', '/botBOT_TOKEN_REMOVED/', $stream_contents);
- }
-
- self::debug(sprintf($message, $stream_contents));
- fclose(self::$debug_log_temp_stream_handle);
- self::$debug_log_temp_stream_handle = null;
- }
- }
-
- /**
- * Handle any logging method call.
- *
- * @param string $name
- * @param array $arguments
- */
- public static function __callStatic(string $name, array $arguments)
- {
- // Get the correct logger instance.
- $logger = null;
- if (in_array($name, ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug',], true)) {
- $logger = self::$logger;
- } elseif ($name === 'update') {
- $logger = self::$update_logger;
- $name = 'info';
- }
-
- // Clearly we have no logging enabled.
- if ($logger === null) {
- return;
- }
-
- // Replace any placeholders from the passed context.
- if (count($arguments) >= 2) {
- $arguments[0] = self::interpolate($arguments[0], $arguments[1]);
- }
-
- call_user_func_array([$logger, $name], $arguments);
- }
-
- /**
- * Interpolates context values into the message placeholders.
- *
- * @see https://www.php-fig.org/psr/psr-3/#12-message
- *
- * @param string $message
- * @param array $context
- *
- * @return string
- */
- protected static function interpolate(string $message, array $context = []): string
- {
- // Build a replacement array with braces around the context keys.
- $replace = [];
- foreach ($context as $key => $val) {
- // check that the value can be casted to string
- if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
- $replace["{{$key}}"] = $val;
- }
- }
-
- // Interpolate replacement values into the message and return.
- return strtr($message, $replace);
- }
-}
diff --git a/src/helpers.php b/src/helpers.php
new file mode 100644
index 000000000..0c1d793f2
--- /dev/null
+++ b/src/helpers.php
@@ -0,0 +1,10 @@
+
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Commands;
-
-use Longman\TelegramBot\Commands\Command;
-use Longman\TelegramBot\Telegram;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-use Longman\TelegramBot\Tests\Unit\TestHelpers;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class CommandTest extends TestCase
-{
- /**
- * @var string
- */
- private $command_namespace = Command::class;
-
- /**
- * @var Telegram
- */
- private $telegram;
-
- /**
- * @var Command
- */
- private $command_stub;
-
- /**
- * @var Telegram
- */
- private $telegram_with_config;
-
- /**
- * @var Command
- */
- private $command_stub_with_config;
-
- public function setUp(): void
- {
- //Default command object
- $this->telegram = new Telegram(self::$dummy_api_key, 'testbot');
- $this->command_stub = $this->getMockForAbstractClass($this->command_namespace, [$this->telegram]);
-
- //Create separate command object that contain a command config
- $this->telegram_with_config = new Telegram(self::$dummy_api_key, 'testbot');
- $this->telegram_with_config->setCommandConfig('command_name', ['config_key' => 'config_value']);
- $this->command_stub_with_config = $this->getMockBuilder($this->command_namespace)
- ->disableOriginalConstructor()
- ->getMockForAbstractClass();
- //Set a name for the object property so that the constructor can set the config correctly
- TestHelpers::setObjectProperty($this->command_stub_with_config, 'name', 'command_name');
- $this->command_stub_with_config->__construct($this->telegram_with_config);
- }
-
- // Test idea from here: http://stackoverflow.com/a/4371606
- public function testCommandConstructorNeedsTelegramObject(): void
- {
- $exception_count = 0;
- $params_to_test = [
- [],
- [null],
- [12345],
- ['something'],
- [new \stdClass()],
- [$this->telegram], // only this one is valid
- ];
-
- foreach ($params_to_test as $param) {
- try {
- $this->getMockForAbstractClass($this->command_namespace, $param);
- } catch (\Throwable $e) {
- $exception_count++;
- }
- }
-
- self::assertEquals(5, $exception_count);
- }
-
- public function testCommandHasCorrectTelegramObject(): void
- {
- self::assertSame($this->telegram, $this->command_stub->getTelegram());
- }
-
- public function testDefaultCommandName(): void
- {
- self::assertEmpty($this->command_stub->getName());
- }
-
- public function testDefaultCommandDescription(): void
- {
- self::assertEquals('Command description', $this->command_stub->getDescription());
- }
-
- public function testDefaultCommandUsage(): void
- {
- self::assertEquals('Command usage', $this->command_stub->getUsage());
- }
-
- public function testDefaultCommandVersion(): void
- {
- self::assertEquals('1.0.0', $this->command_stub->getVersion());
- }
-
- public function testDefaultCommandIsEnabled(): void
- {
- self::assertTrue($this->command_stub->isEnabled());
- }
-
- public function testDefaultCommandShownInHelp(): void
- {
- self::assertTrue($this->command_stub->showInHelp());
- }
-
- public function testDefaultCommandNeedsMysql(): void
- {
- self::markTestSkipped('Think about better test');
- }
-
- public function testDefaultCommandEmptyConfig(): void
- {
- self::assertSame([], $this->command_stub->getConfig());
- }
-
- public function testDefaultCommandUpdateNull(): void
- {
- self::assertNull($this->command_stub->getUpdate());
- }
-
- public function testCommandSetUpdateAndMessage(): void
- {
- $stub = $this->command_stub;
-
- self::assertEquals(null, $stub->getUpdate());
- self::assertEquals(null, $stub->getMessage());
-
- $update = TestHelpers::getFakeUpdateObject();
- $message = $update->getMessage();
- $stub->setUpdate($update);
- self::assertEquals($update, $stub->getUpdate());
- self::assertEquals($message, $stub->getMessage());
- }
-
- public function testCommandWithConfigNotEmptyConfig(): void
- {
- self::assertNotEmpty($this->command_stub_with_config->getConfig());
- }
-
- public function testCommandWithConfigCorrectConfig(): void
- {
- self::assertEquals(['config_key' => 'config_value'], $this->command_stub_with_config->getConfig());
- self::assertEquals(['config_key' => 'config_value'], $this->command_stub_with_config->getConfig(null));
- self::assertEquals(['config_key' => 'config_value'], $this->command_stub_with_config->getConfig());
- self::assertEquals('config_value', $this->command_stub_with_config->getConfig('config_key'));
- self::assertEquals(null, $this->command_stub_with_config->getConfig('not_config_key'));
- }
-}
diff --git a/tests/Unit/Commands/CommandTestCase.php b/tests/Unit/Commands/CommandTestCase.php
deleted file mode 100644
index 782347d31..000000000
--- a/tests/Unit/Commands/CommandTestCase.php
+++ /dev/null
@@ -1,56 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Commands;
-
-use Longman\TelegramBot\Commands\Command;
-use Longman\TelegramBot\Telegram;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @package TelegramTest
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @link https://github.com/php-telegram-bot/core
- */
-class CommandTestCase extends TestCase
-{
- /**
- * @var Telegram
- */
- protected $telegram;
-
- /**
- * @var Command
- */
- protected $command;
-
- /**
- * setUp
- */
- public function setUp(): void
- {
- $this->telegram = new Telegram(self::$dummy_api_key, 'testbot');
-
- // Add custom commands dedicated to do some tests.
- $this->telegram->addCommandsPath(__DIR__ . '/CustomTestCommands');
- $this->telegram->getCommandsList();
- }
-
- /**
- * Make sure the version number is in the format x.x.x, x.x or x
- */
- public function testVersionNumberFormat(): void
- {
- self::assertRegExp('/^(\d+\\.)?(\d+\\.)?(\d+)$/', $this->command->getVersion());
- }
-}
diff --git a/tests/Unit/Commands/CustomTestCommands/DummyAdminCommand.php b/tests/Unit/Commands/CustomTestCommands/DummyAdminCommand.php
deleted file mode 100644
index b81114d2a..000000000
--- a/tests/Unit/Commands/CustomTestCommands/DummyAdminCommand.php
+++ /dev/null
@@ -1,47 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Dummy\AdminCommands;
-
-use Longman\TelegramBot\Commands\AdminCommand;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Request;
-
-/**
- * Test "/dummy_admin" command
- */
-class DummyAdminCommand extends AdminCommand
-{
- /**
- * @var string
- */
- protected $name = 'dummy_admin';
-
- /**
- * @var string
- */
- protected $description = 'Dummy AdminCommand';
-
- /**
- * @var string
- */
- protected $usage = '/dummy_admin';
-
- /**
- * Command execute method
- *
- * @return mixed
- */
- public function execute(): ServerResponse
- {
- return Request::emptyResponse();
- }
-}
diff --git a/tests/Unit/Commands/CustomTestCommands/DummySystemCommand.php b/tests/Unit/Commands/CustomTestCommands/DummySystemCommand.php
deleted file mode 100644
index d9ed58597..000000000
--- a/tests/Unit/Commands/CustomTestCommands/DummySystemCommand.php
+++ /dev/null
@@ -1,47 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Dummy\SystemCommands;
-
-use Longman\TelegramBot\Commands\SystemCommand;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Request;
-
-/**
- * Test "/dummy_system" command
- */
-class DummySystemCommand extends SystemCommand
-{
- /**
- * @var string
- */
- protected $name = 'dummy_system';
-
- /**
- * @var string
- */
- protected $description = 'Dummy SystemCommand';
-
- /**
- * @var string
- */
- protected $usage = '/dummy_system';
-
- /**
- * Command execute method
- *
- * @return mixed
- */
- public function execute(): ServerResponse
- {
- return Request::emptyResponse();
- }
-}
diff --git a/tests/Unit/Commands/CustomTestCommands/DummyUserCommand.php b/tests/Unit/Commands/CustomTestCommands/DummyUserCommand.php
deleted file mode 100644
index 7a20b1ba8..000000000
--- a/tests/Unit/Commands/CustomTestCommands/DummyUserCommand.php
+++ /dev/null
@@ -1,47 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Dummy\UserCommands;
-
-use Longman\TelegramBot\Commands\UserCommand;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Request;
-
-/**
- * Test "/dummy_user" command
- */
-class DummyUserCommand extends UserCommand
-{
- /**
- * @var string
- */
- protected $name = 'dummy_user';
-
- /**
- * @var string
- */
- protected $description = 'Dummy UserCommand';
-
- /**
- * @var string
- */
- protected $usage = '/dummy_user';
-
- /**
- * Command execute method
- *
- * @return mixed
- */
- public function execute(): ServerResponse
- {
- return Request::emptyResponse();
- }
-}
diff --git a/tests/Unit/Commands/CustomTestCommands/HiddenCommand.php b/tests/Unit/Commands/CustomTestCommands/HiddenCommand.php
deleted file mode 100644
index 46f11dfc8..000000000
--- a/tests/Unit/Commands/CustomTestCommands/HiddenCommand.php
+++ /dev/null
@@ -1,57 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Commands\UserCommands;
-
-use Longman\TelegramBot\Commands\UserCommand;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Request;
-
-/**
- * Test "/hidden" command to test $show_in_help
- */
-class HiddenCommand extends UserCommand
-{
- /**
- * @var string
- */
- protected $name = 'hidden';
-
- /**
- * @var string
- */
- protected $description = 'This command is hidden in help';
-
- /**
- * @var string
- */
- protected $usage = '/hidden';
-
- /**
- * @var string
- */
- protected $version = '1.0.0';
-
- /**
- * @var bool
- */
- protected $show_in_help = false;
-
- /**
- * Command execute method
- *
- * @return mixed
- */
- public function execute(): ServerResponse
- {
- return Request::emptyResponse();
- }
-}
diff --git a/tests/Unit/Commands/CustomTestCommands/VisibleCommand.php b/tests/Unit/Commands/CustomTestCommands/VisibleCommand.php
deleted file mode 100644
index 3900c616d..000000000
--- a/tests/Unit/Commands/CustomTestCommands/VisibleCommand.php
+++ /dev/null
@@ -1,57 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Commands\UserCommands;
-
-use Longman\TelegramBot\Commands\UserCommand;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Request;
-
-/**
- * Test "/visible" command to test $show_in_help
- */
-class VisibleCommand extends UserCommand
-{
- /**
- * @var string
- */
- protected $name = 'visible';
-
- /**
- * @var string
- */
- protected $description = 'This command is visible in help';
-
- /**
- * @var string
- */
- protected $usage = '/visible';
-
- /**
- * @var string
- */
- protected $version = '1.0.0';
-
- /**
- * @var bool
- */
- protected $show_in_help = true;
-
- /**
- * Command execute method
- *
- * @return mixed
- */
- public function execute(): ServerResponse
- {
- return Request::emptyResponse();
- }
-}
diff --git a/tests/Unit/ConversationTest.php b/tests/Unit/ConversationTest.php
deleted file mode 100644
index f5205ffae..000000000
--- a/tests/Unit/ConversationTest.php
+++ /dev/null
@@ -1,126 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit;
-
-use Longman\TelegramBot\Conversation;
-use Longman\TelegramBot\Exception\TelegramException;
-use Longman\TelegramBot\Telegram;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class ConversationTest extends TestCase
-{
-
- protected function setUp(): void
- {
- $credentials = [
- 'host' => PHPUNIT_DB_HOST,
- 'port' => PHPUNIT_DB_PORT,
- 'database' => PHPUNIT_DB_NAME,
- 'user' => PHPUNIT_DB_USER,
- 'password' => PHPUNIT_DB_PASS,
- ];
-
- $telegram = new Telegram(self::$dummy_api_key, 'testbot');
- $telegram->enableMySql($credentials);
-
- //Make sure we start with an empty DB for each test.
- TestHelpers::emptyDb($credentials);
- }
-
- public function testConversationThatDoesntExistPropertiesSetCorrectly(): void
- {
- $conversation = new Conversation(123, 456);
- self::assertSame(123, $conversation->getUserId());
- self::assertSame(456, $conversation->getChatId());
- self::assertEmpty($conversation->getCommand());
- }
-
- public function testConversationThatExistsPropertiesSetCorrectly(): void
- {
- $info = TestHelpers::startFakeConversation();
- $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
- self::assertSame($info['user_id'], $conversation->getUserId());
- self::assertSame($info['chat_id'], $conversation->getChatId());
- self::assertSame('command', $conversation->getCommand());
- }
-
- public function testConversationThatDoesntExistWithoutCommand(): void
- {
- $conversation = new Conversation(1, 1);
- self::assertFalse($conversation->exists());
- self::assertEmpty($conversation->getCommand());
- }
-
- public function testConversationThatDoesntExistWithCommand(): void
- {
- $this->expectException(TelegramException::class);
- new Conversation(1, 1, 'command');
- }
-
- public function testNewConversationThatWontExistWithoutCommand(): void
- {
- TestHelpers::startFakeConversation();
- $conversation = new Conversation(0, 0);
- self::assertFalse($conversation->exists());
- self::assertEmpty($conversation->getCommand());
- }
-
- public function testNewConversationThatWillExistWithCommand(): void
- {
- $info = TestHelpers::startFakeConversation();
- $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
- self::assertTrue($conversation->exists());
- self::assertEquals('command', $conversation->getCommand());
- }
-
- public function testStopConversation(): void
- {
- $info = TestHelpers::startFakeConversation();
- $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
- self::assertTrue($conversation->exists());
- $conversation->stop();
-
- $conversation2 = new Conversation($info['user_id'], $info['chat_id']);
- self::assertFalse($conversation2->exists());
- }
-
- public function testCancelConversation(): void
- {
- $info = TestHelpers::startFakeConversation();
- $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
- self::assertTrue($conversation->exists());
- $conversation->cancel();
-
- $conversation2 = new Conversation($info['user_id'], $info['chat_id']);
- self::assertFalse($conversation2->exists());
- }
-
- public function testUpdateConversationNotes(): void
- {
- $info = TestHelpers::startFakeConversation();
- $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
- $conversation->notes = 'newnote';
- $conversation->update();
-
- $conversation2 = new Conversation($info['user_id'], $info['chat_id'], 'command');
- self::assertSame('newnote', $conversation2->notes);
-
- $conversation3 = new Conversation($info['user_id'], $info['chat_id']);
- self::assertSame('newnote', $conversation3->notes);
- }
-}
diff --git a/tests/Unit/Entities/AudioTest.php b/tests/Unit/Entities/AudioTest.php
deleted file mode 100644
index ce9eb64b7..000000000
--- a/tests/Unit/Entities/AudioTest.php
+++ /dev/null
@@ -1,53 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\Audio;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-use Longman\TelegramBot\Tests\Unit\TestHelpers;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Baev Nikolay
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class AudioTest extends TestCase
-{
- /**
- * @var array
- */
- private $record;
-
- public function setUp(): void
- {
- $this->record = TestHelpers::getFakeRecordedAudio();
- }
-
- public function testInstance(): void
- {
- $audio = new Audio($this->record);
- self::assertInstanceOf(Audio::class, $audio);
- }
-
- public function testGetProperties(): void
- {
- $audio = new Audio($this->record);
- self::assertEquals($this->record['file_id'], $audio->getFileId());
- self::assertEquals($this->record['duration'], $audio->getDuration());
- self::assertEquals($this->record['performer'], $audio->getPerformer());
- self::assertEquals($this->record['title'], $audio->getTitle());
- self::assertEquals($this->record['mime_type'], $audio->getMimeType());
- self::assertEquals($this->record['file_size'], $audio->getFileSize());
- }
-}
diff --git a/tests/Unit/Entities/ChatTest.php b/tests/Unit/Entities/ChatTest.php
deleted file mode 100644
index 0f2c03aa6..000000000
--- a/tests/Unit/Entities/ChatTest.php
+++ /dev/null
@@ -1,74 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Tests\Unit\TestCase;
-use Longman\TelegramBot\Tests\Unit\TestHelpers;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class ChatTest extends TestCase
-{
- public function testChatType(): void
- {
- $chat = TestHelpers::getFakeChatObject();
- self::assertEquals('private', $chat->getType());
-
- $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => null]);
- self::assertEquals('group', $chat->getType());
-
- $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => 'supergroup']);
- self::assertEquals('supergroup', $chat->getType());
-
- $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => 'channel']);
- self::assertEquals('channel', $chat->getType());
- }
-
- public function testIsChatType(): void
- {
- $chat = TestHelpers::getFakeChatObject();
- self::assertTrue($chat->isPrivateChat());
-
- $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => null]);
- self::assertTrue($chat->isGroupChat());
-
- $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => 'supergroup']);
- self::assertTrue($chat->isSuperGroup());
-
- $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => 'channel']);
- self::assertTrue($chat->isChannel());
- }
-
- public function testTryMention(): void
- {
- // Username.
- $chat = TestHelpers::getFakeChatObject(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor', 'username' => 'jtaylor']);
- self::assertEquals('@jtaylor', $chat->tryMention());
-
- // First name.
- $chat = TestHelpers::getFakeChatObject(['id' => 1, 'first_name' => 'John', 'last_name' => null, 'username' => null]);
- self::assertEquals('John', $chat->tryMention());
-
- // First and Last name.
- $chat = TestHelpers::getFakeChatObject(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor', 'username' => null]);
- self::assertEquals('John Taylor', $chat->tryMention());
-
- // Non-private chat should return title.
- $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => null, 'title' => 'My group chat']);
- self::assertSame('My group chat', $chat->tryMention());
- }
-}
diff --git a/tests/Unit/Entities/EntityTest.php b/tests/Unit/Entities/EntityTest.php
deleted file mode 100644
index 47299c878..000000000
--- a/tests/Unit/Entities/EntityTest.php
+++ /dev/null
@@ -1,54 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\Entity;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Baev Nikolay
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class EntityTest extends TestCase
-{
- public function testEscapeMarkdown(): void
- {
- // Make sure all characters that need escaping are escaped.
-
- // Markdown V1
- self::assertEquals('\[\`\*\_', Entity::escapeMarkdown('[`*_'));
- self::assertEquals('\*mark\*\_down\_~test~', Entity::escapeMarkdown('*mark*_down_~test~'));
-
- // Markdown V2
- self::assertEquals('\_\*\[\]\(\)\~\`\>\#\+\-\=\|\{\}\.\!', Entity::escapeMarkdownV2('_*[]()~`>#+-=|{}.!'));
- self::assertEquals('\*mark\*\_down\_\~test\~', Entity::escapeMarkdownV2('*mark*_down_~test~'));
- }
-
- public function testSettingDynamicParameterWorks(): void
- {
- $entity = new class ( [] ) extends Entity { }; // phpcs:ignore
-
- $entity->newParameter = 'test';
-
- $this->assertEquals('test', $entity->newParameter);
- }
-
- public function testGettingUnknownDynamicParameterReturnsNull(): void
- {
- $entity = new class ( [] ) extends Entity { }; // phpcs:ignore
-
- $this->assertNull($entity->unknownParameter);
- }
-}
diff --git a/tests/Unit/Entities/FileTest.php b/tests/Unit/Entities/FileTest.php
deleted file mode 100644
index 822f4fac5..000000000
--- a/tests/Unit/Entities/FileTest.php
+++ /dev/null
@@ -1,84 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\File;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Baev Nikolay
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class FileTest extends TestCase
-{
- /**
- * @var array
- */
- private $data;
-
- public function setUp(): void
- {
- $this->data = [
- 'file_id' => (int) mt_rand(1, 99),
- 'file_size' => (int) mt_rand(100, 99999),
- 'file_path' => 'home' . DIRECTORY_SEPARATOR . 'phpunit',
- ];
- }
-
- public function testBaseStageLocation(): void
- {
- $file = new File($this->data);
- self::assertInstanceOf(File::class, $file);
- }
-
- public function testGetFileId(): void
- {
- $file = new File($this->data);
- $id = $file->getFileId();
- self::assertIsInt($id);
- self::assertEquals($this->data['file_id'], $id);
- }
-
- public function testGetFileSize(): void
- {
- $file = new File($this->data);
- $size = $file->getFileSize();
- self::assertIsInt($size);
- self::assertEquals($this->data['file_size'], $size);
- }
-
- public function testGetFilePath(): void
- {
- $file = new File($this->data);
- $path = $file->getFilePath();
- self::assertEquals($this->data['file_path'], $path);
- }
-
- public function testGetFileSizeWithoutData(): void
- {
- unset($this->data['file_size']);
- $file = new File($this->data);
- $id = $file->getFileSize();
- self::assertNull($id);
- }
-
- public function testGetFilePathWithoutData(): void
- {
- unset($this->data['file_path']);
- $file = new File($this->data);
- $path = $file->getFilePath();
- self::assertNull($path);
- }
-}
diff --git a/tests/Unit/Entities/InlineKeyboardButtonTest.php b/tests/Unit/Entities/InlineKeyboardButtonTest.php
deleted file mode 100644
index 384430aa5..000000000
--- a/tests/Unit/Entities/InlineKeyboardButtonTest.php
+++ /dev/null
@@ -1,95 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\Games\CallbackGame;
-use Longman\TelegramBot\Entities\InlineKeyboardButton;
-use Longman\TelegramBot\Entities\SwitchInlineQueryChosenChat;
-use Longman\TelegramBot\Exception\TelegramException;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class InlineKeyboardButtonTest extends TestCase
-{
- public function testInlineKeyboardButtonSuccess(): void
- {
- new InlineKeyboardButton(['text' => 'message', 'url' => 'url_value']);
- new InlineKeyboardButton(['text' => 'message', 'callback_data' => 'callback_data_value']);
- new InlineKeyboardButton(['text' => 'message', 'switch_inline_query' => 'switch_inline_query_value']);
- new InlineKeyboardButton(['text' => 'message', 'switch_inline_query' => '']); // Allow empty string.
- new InlineKeyboardButton(['text' => 'message', 'switch_inline_query_current_chat' => 'switch_inline_query_current_chat_value']);
- new InlineKeyboardButton(['text' => 'message', 'switch_inline_query_current_chat' => '']); // Allow empty string.
- new InlineKeyboardButton(['text' => 'message', 'switch_inline_query_chosen_chat' => new SwitchInlineQueryChosenChat([])]); // Allow empty string.
- new InlineKeyboardButton(['text' => 'message', 'callback_game' => new CallbackGame([])]);
- new InlineKeyboardButton(['text' => 'message', 'pay' => true]);
- self::assertTrue(true);
- }
-
- public function testInlineKeyboardButtonCouldBe(): void
- {
- self::assertTrue(InlineKeyboardButton::couldBe(
- ['text' => 'message', 'url' => 'url_value']
- ));
- self::assertTrue(InlineKeyboardButton::couldBe(
- ['text' => 'message', 'callback_data' => 'callback_data_value']
- ));
- self::assertTrue(InlineKeyboardButton::couldBe(
- ['text' => 'message', 'switch_inline_query' => 'switch_inline_query_value']
- ));
- self::assertTrue(InlineKeyboardButton::couldBe(
- ['text' => 'message', 'switch_inline_query_current_chat' => 'switch_inline_query_current_chat_value']
- ));
- self::assertTrue(InlineKeyboardButton::couldBe(
- ['text' => 'message', 'switch_inline_query_chosen_chat' => new SwitchInlineQueryChosenChat([])]
- ));
- self::assertTrue(InlineKeyboardButton::couldBe(
- ['text' => 'message', 'callback_game' => new CallbackGame([])]
- ));
- self::assertTrue(InlineKeyboardButton::couldBe(
- ['text' => 'message', 'pay' => true]
- ));
-
- self::assertFalse(InlineKeyboardButton::couldBe(['no_text' => 'message']));
- self::assertFalse(InlineKeyboardButton::couldBe(['text' => 'message']));
- self::assertFalse(InlineKeyboardButton::couldBe(['url' => 'url_value']));
- self::assertFalse(InlineKeyboardButton::couldBe([
- 'callback_data' => 'callback_data_value'
- ]));
- self::assertFalse(InlineKeyboardButton::couldBe([
- 'switch_inline_query' => 'switch_inline_query_value'
- ]));
- self::assertFalse(InlineKeyboardButton::couldBe([
- 'switch_inline_query_current_chat' => 'switch_inline_query_current_chat_value'
- ]));
- self::assertFalse(InlineKeyboardButton::couldBe([
- 'switch_inline_query_chosen_chat' => new SwitchInlineQueryChosenChat([])
- ]));
- self::assertFalse(InlineKeyboardButton::couldBe(['callback_game' => new CallbackGame([])]));
- self::assertFalse(InlineKeyboardButton::couldBe(['pay' => true]));
-
- self::assertFalse(InlineKeyboardButton::couldBe([
- 'url' => 'url_value',
- 'callback_data' => 'callback_data_value',
- 'switch_inline_query' => 'switch_inline_query_value',
- 'switch_inline_query_current_chat' => 'switch_inline_query_current_chat_value',
- 'switch_inline_query_chosen_chat' => new SwitchInlineQueryChosenChat([]),
- 'callback_game' => new CallbackGame([]),
- 'pay' => true,
- ]));
- }
-}
diff --git a/tests/Unit/Entities/InlineKeyboardTest.php b/tests/Unit/Entities/InlineKeyboardTest.php
deleted file mode 100644
index 9e30ced4e..000000000
--- a/tests/Unit/Entities/InlineKeyboardTest.php
+++ /dev/null
@@ -1,137 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\InlineKeyboard;
-use Longman\TelegramBot\Entities\InlineKeyboardButton;
-use Longman\TelegramBot\Exception\TelegramException;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class InlineKeyboardTest extends TestCase
-{
- private function getRandomButton($text): InlineKeyboardButton
- {
- $random_params = ['url', 'callback_data', 'switch_inline_query', 'switch_inline_query_current_chat', 'pay'];
- $param = $random_params[array_rand($random_params, 1)];
- $data = [
- 'text' => $text,
- $param => 'random_param',
- ];
-
- return new InlineKeyboardButton($data);
- }
-
- public function testInlineKeyboardDataMalformedField(): void
- {
- $this->expectException(TelegramException::class);
- $this->expectExceptionMessage('inline_keyboard field is not an array!');
- new InlineKeyboard(['inline_keyboard' => 'wrong']);
- }
-
- public function testInlineKeyboardDataMalformedSubfield(): void
- {
- $this->expectException(TelegramException::class);
- $this->expectExceptionMessage('inline_keyboard subfield is not an array!');
- new InlineKeyboard(['inline_keyboard' => ['wrong']]);
- }
-
- public function testInlineKeyboardSingleButtonSingleRow(): void
- {
- $inline_keyboard = (new InlineKeyboard(
- $this->getRandomButton('Button Text 1')
- ))->getProperty('inline_keyboard');
- self::assertSame('Button Text 1', $inline_keyboard[0][0]->getText());
-
- $inline_keyboard = (new InlineKeyboard(
- [$this->getRandomButton('Button Text 2')]
- ))->getProperty('inline_keyboard');
- self::assertSame('Button Text 2', $inline_keyboard[0][0]->getText());
- }
-
- public function testInlineKeyboardSingleButtonMultipleRows(): void
- {
- $keyboard = (new InlineKeyboard(
- $this->getRandomButton('Button Text 1'),
- $this->getRandomButton('Button Text 2'),
- $this->getRandomButton('Button Text 3')
- ))->getProperty('inline_keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
- self::assertSame('Button Text 2', $keyboard[1][0]->getText());
- self::assertSame('Button Text 3', $keyboard[2][0]->getText());
-
- $keyboard = (new InlineKeyboard(
- [$this->getRandomButton('Button Text 4')],
- [$this->getRandomButton('Button Text 5')],
- [$this->getRandomButton('Button Text 6')]
- ))->getProperty('inline_keyboard');
- self::assertSame('Button Text 4', $keyboard[0][0]->getText());
- self::assertSame('Button Text 5', $keyboard[1][0]->getText());
- self::assertSame('Button Text 6', $keyboard[2][0]->getText());
- }
-
- public function testInlineKeyboardMultipleButtonsSingleRow(): void
- {
- $keyboard = (new InlineKeyboard([
- $this->getRandomButton('Button Text 1'),
- $this->getRandomButton('Button Text 2'),
- ]))->getProperty('inline_keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
- self::assertSame('Button Text 2', $keyboard[0][1]->getText());
- }
-
- public function testInlineKeyboardMultipleButtonsMultipleRows(): void
- {
- $keyboard = (new InlineKeyboard(
- [
- $this->getRandomButton('Button Text 1'),
- $this->getRandomButton('Button Text 2'),
- ],
- [
- $this->getRandomButton('Button Text 3'),
- $this->getRandomButton('Button Text 4'),
- ]
- ))->getProperty('inline_keyboard');
-
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
- self::assertSame('Button Text 2', $keyboard[0][1]->getText());
- self::assertSame('Button Text 3', $keyboard[1][0]->getText());
- self::assertSame('Button Text 4', $keyboard[1][1]->getText());
- }
-
- public function testInlineKeyboardAddRows(): void
- {
- $keyboard_obj = new InlineKeyboard([]);
-
- $keyboard_obj->addRow($this->getRandomButton('Button Text 1'));
- $keyboard = $keyboard_obj->getProperty('inline_keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
-
- $keyboard_obj->addRow(
- $this->getRandomButton('Button Text 2'),
- $this->getRandomButton('Button Text 3')
- );
- $keyboard = $keyboard_obj->getProperty('inline_keyboard');
- self::assertSame('Button Text 2', $keyboard[1][0]->getText());
- self::assertSame('Button Text 3', $keyboard[1][1]->getText());
-
- $keyboard_obj->addRow($this->getRandomButton('Button Text 4'));
- $keyboard = $keyboard_obj->getProperty('inline_keyboard');
- self::assertSame('Button Text 4', $keyboard[2][0]->getText());
- }
-}
diff --git a/tests/Unit/Entities/KeyboardButtonTest.php b/tests/Unit/Entities/KeyboardButtonTest.php
deleted file mode 100644
index e7cd907b1..000000000
--- a/tests/Unit/Entities/KeyboardButtonTest.php
+++ /dev/null
@@ -1,67 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\KeyboardButton;
-use Longman\TelegramBot\Entities\KeyboardButtonPollType;
-use Longman\TelegramBot\Entities\KeyboardButtonRequestChat;
-use Longman\TelegramBot\Entities\KeyboardButtonRequestUsers;
-use Longman\TelegramBot\Entities\WebAppInfo;
-use Longman\TelegramBot\Exception\TelegramException;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class KeyboardButtonTest extends TestCase
-{
- public function testKeyboardButtonSuccess(): void
- {
- new KeyboardButton(['text' => 'message']);
- new KeyboardButton(['text' => 'message', 'request_users' => new KeyboardButtonRequestUsers([])]);
- new KeyboardButton(['text' => 'message', 'request_chat' => new KeyboardButtonRequestChat([])]);
- new KeyboardButton(['text' => 'message', 'request_contact' => true]);
- new KeyboardButton(['text' => 'message', 'request_location' => true]);
- new KeyboardButton(['text' => 'message', 'request_poll' => new KeyboardButtonPollType([])]);
- new KeyboardButton(['text' => 'message', 'web_app' => new WebAppInfo([])]);
- self::assertTrue(true);
- }
-
- public function testInlineKeyboardButtonCouldBe(): void
- {
- self::assertTrue(KeyboardButton::couldBe(['text' => 'message']));
- self::assertFalse(KeyboardButton::couldBe(['no_text' => 'message']));
- }
-
- public function testReturnsSubentitiesOnArray()
- {
- $button = new KeyboardButton('message');
- $button->request_users = [];
- $this->assertInstanceOf(KeyboardButtonRequestUsers::class, $button->getRequestUsers());
-
- $button = new KeyboardButton('message');
- $button->request_chat = [];
- $this->assertInstanceOf(KeyboardButtonRequestChat::class, $button->getRequestChat());
-
- $button = new KeyboardButton('message');
- $button->request_poll = [];
- $this->assertInstanceOf(KeyboardButtonPollType::class, $button->getRequestPoll());
-
- $button = new KeyboardButton('message');
- $button->web_app = [];
- $this->assertInstanceOf(WebAppInfo::class, $button->getWebApp());
- }
-}
diff --git a/tests/Unit/Entities/KeyboardTest.php b/tests/Unit/Entities/KeyboardTest.php
deleted file mode 100644
index c5afa90e9..000000000
--- a/tests/Unit/Entities/KeyboardTest.php
+++ /dev/null
@@ -1,208 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\Keyboard;
-use Longman\TelegramBot\Entities\KeyboardButton;
-use Longman\TelegramBot\Exception\TelegramException;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class KeyboardTest extends TestCase
-{
- public function testKeyboardDataMalformedField(): void
- {
- $this->expectException(TelegramException::class);
- $this->expectExceptionMessage('keyboard field is not an array!');
- new Keyboard(['keyboard' => 'wrong']);
- }
-
- public function testKeyboardDataMalformedSubfield(): void
- {
- $this->expectException(TelegramException::class);
- $this->expectExceptionMessage('keyboard subfield is not an array!');
- new Keyboard(['keyboard' => ['wrong']]);
- }
-
- public function testKeyboardSingleButtonSingleRow(): void
- {
- $keyboard = (new Keyboard('Button Text 1'))->getProperty('keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
-
- $keyboard = (new Keyboard(['Button Text 2']))->getProperty('keyboard');
- self::assertSame('Button Text 2', $keyboard[0][0]->getText());
- }
-
- public function testKeyboardSingleButtonMultipleRows(): void
- {
- $keyboard = (new Keyboard(
- 'Button Text 1',
- 'Button Text 2',
- 'Button Text 3'
- ))->getProperty('keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
- self::assertSame('Button Text 2', $keyboard[1][0]->getText());
- self::assertSame('Button Text 3', $keyboard[2][0]->getText());
-
- $keyboard = (new Keyboard(
- ['Button Text 4'],
- ['Button Text 5'],
- ['Button Text 6']
- ))->getProperty('keyboard');
- self::assertSame('Button Text 4', $keyboard[0][0]->getText());
- self::assertSame('Button Text 5', $keyboard[1][0]->getText());
- self::assertSame('Button Text 6', $keyboard[2][0]->getText());
- }
-
- public function testKeyboardMultipleButtonsSingleRow(): void
- {
- $keyboard = (new Keyboard(['Button Text 1', 'Button Text 2']))->getProperty('keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
- self::assertSame('Button Text 2', $keyboard[0][1]->getText());
- }
-
- public function testKeyboardMultipleButtonsMultipleRows(): void
- {
- $keyboard = (new Keyboard(
- ['Button Text 1', 'Button Text 2'],
- ['Button Text 3', 'Button Text 4']
- ))->getProperty('keyboard');
-
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
- self::assertSame('Button Text 2', $keyboard[0][1]->getText());
- self::assertSame('Button Text 3', $keyboard[1][0]->getText());
- self::assertSame('Button Text 4', $keyboard[1][1]->getText());
- }
-
- public function testKeyboardWithButtonObjects(): void
- {
- $keyboard = (new Keyboard(
- new KeyboardButton('Button Text 1')
- ))->getProperty('keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
-
- $keyboard = (new Keyboard(
- new KeyboardButton('Button Text 2'),
- new KeyboardButton('Button Text 3')
- ))->getProperty('keyboard');
- self::assertSame('Button Text 2', $keyboard[0][0]->getText());
- self::assertSame('Button Text 3', $keyboard[1][0]->getText());
-
- $keyboard = (new Keyboard(
- [new KeyboardButton('Button Text 4')],
- [new KeyboardButton('Button Text 5'), new KeyboardButton('Button Text 6')]
- ))->getProperty('keyboard');
- self::assertSame('Button Text 4', $keyboard[0][0]->getText());
- self::assertSame('Button Text 5', $keyboard[1][0]->getText());
- self::assertSame('Button Text 6', $keyboard[1][1]->getText());
- }
-
- public function testKeyboardWithDataArray(): void
- {
- $resize_keyboard = (bool) mt_rand(0, 1);
- $one_time_keyboard = (bool) mt_rand(0, 1);
- $input_field_placeholder = 'placeholder';
- $selective = (bool) mt_rand(0, 1);
-
- $keyboard_obj = new Keyboard([
- 'resize_keyboard' => $resize_keyboard,
- 'one_time_keyboard' => $one_time_keyboard,
- 'input_field_placeholder' => $input_field_placeholder,
- 'selective' => $selective,
- 'keyboard' => [['Button Text 1']],
- ]);
-
- $keyboard = $keyboard_obj->getProperty('keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
-
- self::assertSame($resize_keyboard, $keyboard_obj->getResizeKeyboard());
- self::assertSame($one_time_keyboard, $keyboard_obj->getOneTimeKeyboard());
- self::assertSame($input_field_placeholder, $keyboard_obj->getInputFieldPlaceholder());
- self::assertSame($selective, $keyboard_obj->getSelective());
- }
-
- public function testPredefinedKeyboards(): void
- {
- $keyboard_remove = Keyboard::remove();
- self::assertTrue($keyboard_remove->getProperty('remove_keyboard'));
-
- $keyboard_force_reply = Keyboard::forceReply();
- self::assertTrue($keyboard_force_reply->getProperty('force_reply'));
- }
-
- public function testKeyboardMethods(): void
- {
- $keyboard_obj = new Keyboard([]);
-
- self::assertEmpty($keyboard_obj->getOneTimeKeyboard());
- self::assertEmpty($keyboard_obj->getResizeKeyboard());
- self::assertEmpty($keyboard_obj->getSelective());
-
- $keyboard_obj->setOneTimeKeyboard(true);
- self::assertTrue($keyboard_obj->getOneTimeKeyboard());
- $keyboard_obj->setOneTimeKeyboard(false);
- self::assertFalse($keyboard_obj->getOneTimeKeyboard());
-
- $keyboard_obj->setResizeKeyboard(true);
- self::assertTrue($keyboard_obj->getResizeKeyboard());
- $keyboard_obj->setResizeKeyboard(false);
- self::assertFalse($keyboard_obj->getResizeKeyboard());
-
- $keyboard_obj->setSelective(true);
- self::assertTrue($keyboard_obj->getSelective());
- $keyboard_obj->setSelective(false);
- self::assertFalse($keyboard_obj->getSelective());
- }
-
- public function testKeyboardAddRows(): void
- {
- $keyboard_obj = new Keyboard([]);
-
- $keyboard_obj->addRow('Button Text 1');
- $keyboard = $keyboard_obj->getProperty('keyboard');
- self::assertSame('Button Text 1', $keyboard[0][0]->getText());
-
- $keyboard_obj->addRow('Button Text 2', 'Button Text 3');
- $keyboard = $keyboard_obj->getProperty('keyboard');
- self::assertSame('Button Text 2', $keyboard[1][0]->getText());
- self::assertSame('Button Text 3', $keyboard[1][1]->getText());
-
- $keyboard_obj->addRow(['text' => 'Button Text 4']);
- $keyboard = $keyboard_obj->getProperty('keyboard');
- self::assertSame('Button Text 4', $keyboard[2][0]->getText());
- }
-
- public function testSetterMethods(): void
- {
- $keyboard = (new Keyboard(
- [
- ['text' => 'One'],
- ]
- ))->setResizeKeyboard(true);
-
- $array = json_decode($keyboard->toJson(), true);
-
- $this->assertIsArray($array);
-
- $this->assertArrayHasKey('keyboard', $array);
- $this->assertArrayHasKey('resize_keyboard', $array);
-
- $this->assertIsArray($array['keyboard']);
- $this->assertEquals(true, $array['resize_keyboard']);
- }
-}
diff --git a/tests/Unit/Entities/LocationTest.php b/tests/Unit/Entities/LocationTest.php
deleted file mode 100644
index 20cb94240..000000000
--- a/tests/Unit/Entities/LocationTest.php
+++ /dev/null
@@ -1,57 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\Location;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Baev Nikolay
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class LocationTest extends TestCase
-{
- private $coordinates;
-
- public function setUp(): void
- {
- $this->coordinates = [
- 'longitude' => (float) mt_rand(10, 69),
- 'latitude' => (float) mt_rand(10, 48),
- ];
- }
-
- public function testBaseStageLocation(): void
- {
- $location = new Location($this->coordinates);
- self::assertInstanceOf(Location::class, $location);
- }
-
- public function testGetLongitude(): void
- {
- $location = new Location($this->coordinates);
- $long = $location->getLongitude();
- self::assertIsFloat($long);
- self::assertEquals($this->coordinates['longitude'], $long);
- }
-
- public function testGetLatitude(): void
- {
- $location = new Location($this->coordinates);
- $lat = $location->getLatitude();
- self::assertIsFloat($lat);
- self::assertEquals($this->coordinates['latitude'], $lat);
- }
-}
diff --git a/tests/Unit/Entities/MessageTest.php b/tests/Unit/Entities/MessageTest.php
deleted file mode 100644
index ba73d8146..000000000
--- a/tests/Unit/Entities/MessageTest.php
+++ /dev/null
@@ -1,96 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Tests\Unit\TestCase;
-use Longman\TelegramBot\Tests\Unit\TestHelpers;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class MessageTest extends TestCase
-{
- public function testTextAndCommandRecognise(): void
- {
- // /command
- $message = TestHelpers::getFakeMessageObject(['text' => '/help']);
- self::assertEquals('/help', $message->getFullCommand());
- self::assertEquals('help', $message->getCommand());
- self::assertEquals('/help', $message->getText());
- self::assertEquals('', $message->getText(true));
-
- // text
- $message = TestHelpers::getFakeMessageObject(['text' => 'some text']);
- self::assertNull($message->getFullCommand());
- self::assertNull($message->getCommand());
- self::assertEquals('some text', $message->getText());
- self::assertEquals('some text', $message->getText(true));
-
- // /command@bot
- $message = TestHelpers::getFakeMessageObject(['text' => '/help@testbot']);
- self::assertEquals('/help@testbot', $message->getFullCommand());
- self::assertEquals('help', $message->getCommand());
- self::assertEquals('/help@testbot', $message->getText());
- self::assertEquals('', $message->getText(true));
-
- // /command text
- $message = TestHelpers::getFakeMessageObject(['text' => '/help some text']);
- self::assertEquals('/help', $message->getFullCommand());
- self::assertEquals('help', $message->getCommand());
- self::assertEquals('/help some text', $message->getText());
- self::assertEquals('some text', $message->getText(true));
-
- // /command@bot some text
- $message = TestHelpers::getFakeMessageObject(['text' => '/help@testbot some text']);
- self::assertEquals('/help@testbot', $message->getFullCommand());
- self::assertEquals('help', $message->getCommand());
- self::assertEquals('/help@testbot some text', $message->getText());
- self::assertEquals('some text', $message->getText(true));
-
- // /command\n text
- $message = TestHelpers::getFakeMessageObject(['text' => "/help\n some text"]);
- self::assertEquals('/help', $message->getFullCommand());
- self::assertEquals('help', $message->getCommand());
- self::assertEquals("/help\n some text", $message->getText());
- self::assertEquals(' some text', $message->getText(true));
-
- // /command@bot\nsome text
- $message = TestHelpers::getFakeMessageObject(['text' => "/help@testbot\nsome text"]);
- self::assertEquals('/help@testbot', $message->getFullCommand());
- self::assertEquals('help', $message->getCommand());
- self::assertEquals("/help@testbot\nsome text", $message->getText());
- self::assertEquals('some text', $message->getText(true));
-
- // /command@bot \nsome text
- $message = TestHelpers::getFakeMessageObject(['text' => "/help@testbot \nsome text"]);
- self::assertEquals('/help@testbot', $message->getFullCommand());
- self::assertEquals('help', $message->getCommand());
- self::assertEquals("/help@testbot \nsome text", $message->getText());
- self::assertEquals("\nsome text", $message->getText(true));
- }
-
- public function testGetType(): void
- {
- $message = TestHelpers::getFakeMessageObject(['text' => null]);
- self::assertSame('message', $message->getType());
-
- $message = TestHelpers::getFakeMessageObject(['text' => '/help']);
- self::assertSame('command', $message->getType());
-
- $message = TestHelpers::getFakeMessageObject(['text' => 'some text']);
- self::assertSame('text', $message->getType());
- }
-}
diff --git a/tests/Unit/Entities/ReplyToMessageTest.php b/tests/Unit/Entities/ReplyToMessageTest.php
deleted file mode 100644
index 70b6f3f7e..000000000
--- a/tests/Unit/Entities/ReplyToMessageTest.php
+++ /dev/null
@@ -1,51 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\Update;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class ReplyToMessageTest extends TestCase
-{
- public function testChatType(): void
- {
- $json = '{
- "update_id":137809335,
- "message":{
- "message_id":4479,
- "from":{"id":123,"first_name":"John","username":"MJohn"},
- "chat":{"id":-123,"title":"MyChat","type":"group"},
- "date":1449092987,
- "reply_to_message":{
- "message_id":11,
- "from":{"id":121,"first_name":"Myname","username":"mybot"},
- "chat":{"id":-123,"title":"MyChat","type":"group"},
- "date":1449092984,
- "text":"type some text"
- },
- "text":"some text"
- }
- }';
-
- $update = new Update(json_decode($json, true), 'mybot');
- $reply_to_message = $update->getMessage()->getReplyToMessage();
-
- self::assertNull($reply_to_message->getReplyToMessage());
- }
-}
diff --git a/tests/Unit/Entities/ServerResponseTest.php b/tests/Unit/Entities/ServerResponseTest.php
deleted file mode 100644
index 6412885d0..000000000
--- a/tests/Unit/Entities/ServerResponseTest.php
+++ /dev/null
@@ -1,386 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- *
- * Written by Marco Boretto
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\File;
-use Longman\TelegramBot\Entities\Message;
-use Longman\TelegramBot\Entities\PhotoSize;
-use Longman\TelegramBot\Entities\ServerResponse;
-use Longman\TelegramBot\Entities\Sticker;
-use Longman\TelegramBot\Entities\StickerSet;
-use Longman\TelegramBot\Entities\Update;
-use Longman\TelegramBot\Entities\UserProfilePhotos;
-use Longman\TelegramBot\Request;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-use Longman\TelegramBot\Tests\Unit\TestHelpers;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class ServerResponseTest extends TestCase
-{
- protected function setUp(): void
- {
- // Make sure the current action in the Request class is unset.
- TestHelpers::setStaticProperty(Request::class, 'current_action', '');
- }
-
- public function sendMessageOk(): string
- {
- return '{
- "ok":true,
- "result":{
- "message_id":1234,
- "from":{"id":123456789,"first_name":"botname","username":"namebot"},
- "chat":{"id":123456789,"first_name":"john","username":"Mjohn"},
- "date":1441378360,
- "text":"hello"
- }
- }';
- }
-
- public function testSendMessageOk(): void
- {
- $result = $this->sendMessageOk();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
- $server_result = $server->getResult();
-
- self::assertTrue($server->isOk());
- self::assertNull($server->getErrorCode());
- self::assertNull($server->getDescription());
- self::assertInstanceOf(Message::class, $server_result);
-
- //Message
- self::assertEquals('1234', $server_result->getMessageId());
- self::assertEquals('123456789', $server_result->getFrom()->getId());
- self::assertEquals('botname', $server_result->getFrom()->getFirstName());
- self::assertEquals('namebot', $server_result->getFrom()->getUsername());
- self::assertEquals('123456789', $server_result->getChat()->getId());
- self::assertEquals('john', $server_result->getChat()->getFirstName());
- self::assertEquals('Mjohn', $server_result->getChat()->getUsername());
- self::assertEquals('1441378360', $server_result->getDate());
- self::assertEquals('hello', $server_result->getText());
-
- //... they are not finished...
- }
-
- public function sendMessageFail(): string
- {
- return '{
- "ok":false,
- "error_code":400,
- "description":"Error: Bad Request: wrong chat id"
- }';
- }
-
- public function testSendMessageFail(): void
- {
- $result = $this->sendMessageFail();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
-
- self::assertFalse($server->isOk());
- self::assertNull($server->getResult());
- self::assertEquals('400', $server->getErrorCode());
- self::assertEquals('Error: Bad Request: wrong chat id', $server->getDescription());
- }
-
- public function setWebhookOk(): string
- {
- return '{"ok":true,"result":true,"description":"Webhook was set"}';
- }
-
- public function testSetWebhookOk(): void
- {
- $result = $this->setWebhookOk();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
-
- self::assertTrue($server->isOk());
- self::assertTrue($server->getResult());
- self::assertNull($server->getErrorCode());
- self::assertEquals('Webhook was set', $server->getDescription());
- }
-
- public function setWebhookFail(): string
- {
- return '{
- "ok":false,
- "error_code":400,
- "description":"Error: Bad request: https:\/\/domain.host.org\/dir\/hook.php"
- }';
- }
-
- public function testSetWebhookFail(): void
- {
- $result = $this->setWebhookFail();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
-
- self::assertFalse($server->isOk());
- self::assertNull($server->getResult());
- self::assertEquals(400, $server->getErrorCode());
- self::assertEquals('Error: Bad request: https://domain.host.org/dir/hook.php', $server->getDescription());
- }
-
- public function getUpdatesArray(): string
- {
- return '{
- "ok":true,
- "result":[
- {
- "update_id":123,
- "message":{
- "message_id":90,
- "from":{"id":123456789,"first_name":"John","username":"Mjohn"},
- "chat":{"id":123456789,"first_name":"John","username":"Mjohn"},
- "date":1441569067,
- "text":"\/start"
- }
- },
- {
- "update_id":124,
- "message":{
- "message_id":91,
- "from":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
- "chat":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
- "date":1441569073,
- "text":"Hello!"
- }
- },
- {
- "update_id":125,
- "message":{
- "message_id":92,
- "from":{"id":123456789,"first_name":"John","username":"MJohn"},
- "chat":{"id":123456789,"first_name":"John","username":"MJohn"},
- "date":1441569094,
- "text":"\/echo hello!"
- }
- },
- {
- "update_id":126,
- "message":{
- "message_id":93,
- "from":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
- "chat":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
- "date":1441569112,
- "text":"\/echo the best"
- }
- }
- ]
- }';
- }
-
- public function testGetUpdatesArray(): void
- {
- $result = $this->getUpdatesArray();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
-
- self::assertCount(4, $server->getResult());
- self::assertInstanceOf(Update::class, $server->getResult()[0]);
- }
-
- public function getUpdatesEmpty(): string
- {
- return '{"ok":true,"result":[]}';
- }
-
- public function testGetUpdatesEmpty(): void
- {
- $result = $this->getUpdatesEmpty();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
-
- self::assertEmpty($server->getResult());
- }
-
- public function getUserProfilePhotos(): string
- {
- TestHelpers::setStaticProperty(Request::class, 'current_action', 'getUserProfilePhotos');
- return '{
- "ok":true,
- "result":{
- "total_count":3,
- "photos":[
- [
- {"file_id":"AgADBG6_vmQaVf3qOGVurBRzHqgg5uEju-8IBAAEC","file_size":7402,"width":160,"height":160},
- {"file_id":"AgADBG6_vmQaVf3qOGVurBRzHWMuphij6_MIBAAEC","file_size":15882,"width":320,"height":320},
- {"file_id":"AgADBG6_vmQaVf3qOGVurBRzHNWdpQ9jz_cIBAAEC","file_size":46680,"width":640,"height":640}
- ],
- [
- {"file_id":"AgADBAADr6cxG6_vmH-bksDdiYzAABO8UCGz_JLAAgI","file_size":7324,"width":160,"height":160},
- {"file_id":"AgADBAADr6cxG6_vmH-bksDdiYzAABAlhB5Q_K0AAgI","file_size":15816,"width":320,"height":320},
- {"file_id":"AgADBAADr6cxG6_vmH-bksDdiYzAABIIxOSHyayAAgI","file_size":46620,"width":640,"height":640}
- ],
- [
- {"file_id":"AgABxG6_vmQaL2X0CUTAABMhd1n2RLaRSj6cAAgI","file_size":2710,"width":160,"height":160},
- {"file_id":"AgADcxG6_vmQaL2X0EUTAABPXm1og0O7qwjKcAAgI","file_size":11660,"width":320,"height":320},
- {"file_id":"AgADxG6_vmQaL2X0CUTAABMOtcfUmoPrcjacAAgI","file_size":37150,"width":640,"height":640}
- ]
- ]
- }
- }';
- }
-
- public function testGetUserProfilePhotos(): void
- {
- $result = $this->getUserProfilePhotos();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
- $server_result = $server->getResult();
-
- $photos = $server_result->getPhotos();
-
- //Photo count
- self::assertEquals(3, $server_result->getTotalCount());
- self::assertCount(3, $photos);
- //Photo size count
- self::assertCount(3, $photos[0]);
-
- self::assertInstanceOf(UserProfilePhotos::class, $server_result);
- self::assertInstanceOf(PhotoSize::class, $photos[0][0]);
- }
-
- public function getFile(): string
- {
- TestHelpers::setStaticProperty(Request::class, 'current_action', 'getFile');
- return '{
- "ok":true,
- "result":{
- "file_id":"AgADBxG6_vmQaVf3qRzHYTAABD1hNWdpQ9qz_cIBAAEC",
- "file_size":46680,
- "file_path":"photo\/file_1.jpg"
- }
- }';
- }
-
- public function testGetFile(): void
- {
- $result = $this->getFile();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
-
- self::assertInstanceOf(File::class, $server->getResult());
- }
-
- public function testSetGeneralTestFakeResponse(): void
- {
- //setWebhook ok
- $fake_response = Request::generateGeneralFakeServerResponse();
-
- $server = new ServerResponse($fake_response, 'testbot');
-
- self::assertTrue($server->isOk());
- self::assertTrue($server->getResult());
- self::assertNull($server->getErrorCode());
- self::assertEquals('', $server->getDescription());
-
- //sendMessage ok
- $fake_response = Request::generateGeneralFakeServerResponse(['chat_id' => 123456789, 'text' => 'hello']);
-
- $server = new ServerResponse($fake_response, 'testbot');
-
- /** @var Message $server_result */
- $server_result = $server->getResult();
-
- self::assertTrue($server->isOk());
- self::assertNull($server->getErrorCode());
- self::assertNull($server->getDescription());
- self::assertInstanceOf(Message::class, $server_result);
-
- //Message
- self::assertEquals('1234', $server_result->getMessageId());
- self::assertEquals('1441378360', $server_result->getDate());
- self::assertEquals('hello', $server_result->getText());
-
- //Message //User
- self::assertEquals('123456789', $server_result->getFrom()->getId());
- self::assertEquals('botname', $server_result->getFrom()->getFirstName());
- self::assertEquals('namebot', $server_result->getFrom()->getUsername());
-
- //Message //Chat
- self::assertEquals('123456789', $server_result->getChat()->getId());
- self::assertEquals('', $server_result->getChat()->getFirstName());
- self::assertEquals('', $server_result->getChat()->getUsername());
-
- //... they are not finished...
- }
-
- public function getStickerSet(): string
- {
- TestHelpers::setStaticProperty(Request::class, 'current_action', 'getStickerSet');
- return '{
- "ok":true,
- "result":{
- "name":"stickerset_name",
- "title":"Some name",
- "contains_masks":false,
- "stickers":[
- {
- "width":512,
- "height":324,
- "emoji":"\ud83d\ude33",
- "set_name":"stickerset_name",
- "thumb":{"file_id":"AAQEABOKTFsZAASfA4t3pp1_VlH1AAIC","file_size":3120,"width":128,"height":81},
- "file_id":"CAADBAADzAIAAph_7gOATSb9ehxv5QI",
- "file_size":14246
- },
- {
- "width":419,
- "height":512,
- "emoji":"\u2764",
- "set_name":"stickerset_name",
- "thumb":{"file_id":"AAQEABMj8qoZAASePUHuDSJ2uGIKAAIC","file_size":3500,"width":105,"height":128},
- "file_id":"CAADBAADzQIAAph_7gNPFguft4qtjAI",
- "file_size":17814
- },
- {
- "width":512,
- "height":276,
- "emoji":"\ud83d\ude36",
- "set_name":"stickerset_name",
- "thumb":{"file_id":"AAQEABMiaWcZAATNUEPkYkd0Fh2JBAABAg","file_size":2642,"file_path":"thumbnails\/file_8.jpg","width":128,"height":69},
- "file_id":"CAADBAADzwIAAph_7gOClxA3gK5wqAI",
- "file_size":12258
- },
- {
- "width":512,
- "height":327,
- "emoji":"\ud83d\udcbb",
- "set_name":"stickerset_name",
- "thumb":{"file_id":"AAQEABPC3d8ZAAQUJJnFB1VfII2RAAIC","file_size":3824,"file_path":"thumbnails\/file_10.jpg","width":128,"height":82},
- "file_id":"CAADBAAD0QIAAph_7gO-vBJGkTeWqwI",
- "file_size":18282
- }
- ]
- }
- }';
- }
-
- public function testGetStickerSet(): void
- {
- $result = $this->getStickerSet();
- $server = new ServerResponse(json_decode($result, true), 'testbot');
-
- $server_result = $server->getResult();
-
- self::assertInstanceOf(StickerSet::class, $server_result);
- self::assertEquals('stickerset_name', $server_result->getName());
- self::assertEquals('Some name', $server_result->getTitle());
- self::assertFalse($server_result->getContainsMasks());
-
- $stickers = $server_result->getStickers();
- self::assertCount(4, $stickers);
- self::assertInstanceOf(Sticker::class, $stickers[0]);
- }
-}
diff --git a/tests/Unit/Entities/UpdateTest.php b/tests/Unit/Entities/UpdateTest.php
deleted file mode 100644
index f05e59585..000000000
--- a/tests/Unit/Entities/UpdateTest.php
+++ /dev/null
@@ -1,52 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\Update;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class UpdateTest extends TestCase
-{
- public function testUpdateCast(): void
- {
- $json = '{
- "update_id":137809336,
- "message":{
- "message_id":4479,
- "from":{"id":123,"first_name":"John","username":"MJohn"},
- "chat":{"id":-123,"title":"MyChat","type":"group"},
- "date":1449092987,
- "reply_to_message":{
- "message_id":11,
- "from":{"id":121,"first_name":"Myname","username":"mybot"},
- "chat":{"id":-123,"title":"MyChat","type":"group"},
- "date":1449092984,
- "text":"type some text"
- },
- "text":"some text"
- }
- }';
-
- $struct = json_decode($json, true);
- $update = new Update($struct, 'mybot');
-
- $array_string_after = json_decode($update->toJson(), true);
- self::assertEquals($struct, $array_string_after);
- }
-}
diff --git a/tests/Unit/Entities/UserTest.php b/tests/Unit/Entities/UserTest.php
deleted file mode 100644
index 41c957ac8..000000000
--- a/tests/Unit/Entities/UserTest.php
+++ /dev/null
@@ -1,85 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\User;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class UserTest extends TestCase
-{
- public function testInstance(): void
- {
- $user = new User(['id' => 1]);
- self::assertInstanceOf(User::class, $user);
- }
-
- public function testGetId(): void
- {
- $user = new User(['id' => 123]);
- self::assertEquals(123, $user->getId());
- }
-
- public function testTryMention(): void
- {
- // Username
- $user = new User(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor', 'username' => 'jtaylor']);
- self::assertEquals('@jtaylor', $user->tryMention());
-
- // First name.
- $user = new User(['id' => 1, 'first_name' => 'John']);
- self::assertEquals('John', $user->tryMention());
-
- // First and Last name.
- $user = new User(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor']);
- self::assertEquals('John Taylor', $user->tryMention());
- }
-
- public function testEscapeMarkdown(): void
- {
- // Username.
- $user = new User(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor', 'username' => 'j_taylor']);
- self::assertEquals('@j_taylor', $user->tryMention());
- self::assertEquals('@j\_taylor', $user->tryMention(true));
-
- // First name.
- $user = new User(['id' => 1, 'first_name' => 'John[']);
- self::assertEquals('John[', $user->tryMention());
- self::assertEquals('John\[', $user->tryMention(true));
-
- // First and Last name.
- $user = new User(['id' => 1, 'first_name' => 'John', 'last_name' => '`Taylor`']);
- self::assertEquals('John `Taylor`', $user->tryMention());
- self::assertEquals('John \`Taylor\`', $user->tryMention(true));
- }
-
- public function testGetProperties(): void
- {
- // Username.
- $user = new User(['id' => 1, 'username' => 'name_phpunit']);
- self::assertEquals('name_phpunit', $user->getUsername());
-
- // First name.
- $user = new User(['id' => 1, 'first_name' => 'name_phpunit']);
- self::assertEquals('name_phpunit', $user->getFirstName());
-
- // Last name.
- $user = new User(['id' => 1, 'last_name' => 'name_phpunit']);
- self::assertEquals('name_phpunit', $user->getLastName());
- }
-}
diff --git a/tests/Unit/Entities/WebhookInfoTest.php b/tests/Unit/Entities/WebhookInfoTest.php
deleted file mode 100644
index 6a931b019..000000000
--- a/tests/Unit/Entities/WebhookInfoTest.php
+++ /dev/null
@@ -1,143 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit\Entities;
-
-use Longman\TelegramBot\Entities\WebhookInfo;
-use Longman\TelegramBot\Tests\Unit\TestCase;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Baev Nikolay
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class WebhookInfoTest extends TestCase
-{
- /**
- * @var array Webhook data
- */
- public $data;
-
- public function setUp(): void
- {
- $this->data = [
- 'url' => 'http://phpunit',
- 'has_custom_certificate' => (bool) mt_rand(0, 1),
- 'pending_update_count' => (int) mt_rand(1, 9),
- 'ip_address' => '1.2.3.4',
- 'last_error_date' => time(),
- 'last_error_message' => 'Some_error_message',
- 'max_connections' => (int) mt_rand(1, 100),
- 'allowed_updates' => ['message', 'edited_channel_post', 'callback_query'],
- ];
- }
-
- public function testBaseStageWebhookInfo(): void
- {
- $webhook = new WebhookInfo($this->data);
- self::assertInstanceOf(WebhookInfo::class, $webhook);
- }
-
- public function testGetUrl(): void
- {
- $webhook = new WebhookInfo($this->data);
- $url = $webhook->getUrl();
- self::assertEquals($this->data['url'], $url);
- }
-
- public function testGetHasCustomCertificate(): void
- {
- $webhook = new WebhookInfo($this->data);
- $custom_certificate = $webhook->getHasCustomCertificate();
- self::assertIsBool($custom_certificate);
- self::assertEquals($this->data['has_custom_certificate'], $custom_certificate);
- }
-
- public function testGetPendingUpdateCount(): void
- {
- $webhook = new WebhookInfo($this->data);
- $update_count = $webhook->getPendingUpdateCount();
- self::assertIsInt($update_count);
- self::assertEquals($this->data['pending_update_count'], $update_count);
- }
-
- public function testGetIpAddress(): void
- {
- $webhook = new WebhookInfo($this->data);
- $ip_address = $webhook->getIpAddress();
- self::assertIsString($ip_address);
- self::assertEquals($this->data['ip_address'], $ip_address);
- }
-
- public function testGetLastErrorDate(): void
- {
- $webhook = new WebhookInfo($this->data);
- $error_date = $webhook->getLastErrorDate();
- self::assertIsInt($error_date);
- self::assertEquals($this->data['last_error_date'], $error_date);
- }
-
- public function testGetLastErrorMessage(): void
- {
- $webhook = new WebhookInfo($this->data);
- $error_msg = $webhook->getLastErrorMessage();
- self::assertIsString($error_msg);
- self::assertEquals($this->data['last_error_message'], $error_msg);
- }
-
- public function testGetMaxConnections(): void
- {
- $webhook = new WebhookInfo($this->data);
- $max_connections = $webhook->getMaxConnections();
- self::assertIsInt($max_connections);
- self::assertEquals($this->data['max_connections'], $max_connections);
- }
-
- public function testGetAllowedUpdates(): void
- {
- $webhook = new WebhookInfo($this->data);
- $allowed_updates = $webhook->getAllowedUpdates();
- self::assertIsArray($allowed_updates);
- self::assertEquals($this->data['allowed_updates'], $allowed_updates);
- }
-
- public function testGetDataWithoutParams(): void
- {
- // Make a copy to not risk failed tests if not run in proper order.
- $data = $this->data;
-
- unset($data['url']);
- self::assertNull((new WebhookInfo($data))->getUrl());
-
- unset($data['has_custom_certificate']);
- self::assertNull((new WebhookInfo($data))->getHasCustomCertificate());
-
- unset($data['pending_update_count']);
- self::assertNull((new WebhookInfo($data))->getPendingUpdateCount());
-
- unset($data['ip_address']);
- self::assertNull((new WebhookInfo($data))->getIpAddress());
-
- unset($data['last_error_date']);
- self::assertNull((new WebhookInfo($data))->getLastErrorDate());
-
- unset($data['last_error_message']);
- self::assertNull((new WebhookInfo($data))->getLastErrorMessage());
-
- unset($data['max_connections']);
- self::assertNull((new WebhookInfo($data))->getMaxConnections());
-
- unset($data['allowed_updates']);
- self::assertNull((new WebhookInfo($data))->getAllowedUpdates());
- }
-}
diff --git a/tests/Unit/TelegramLogTest.php b/tests/Unit/TelegramLogTest.php
deleted file mode 100644
index 209cac5f1..000000000
--- a/tests/Unit/TelegramLogTest.php
+++ /dev/null
@@ -1,116 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit;
-
-use Longman\TelegramBot\TelegramLog;
-use Monolog\Formatter\LineFormatter;
-use Monolog\Handler\StreamHandler;
-use Monolog\Logger;
-
-/**
- * @package TelegramTest
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @link https://github.com/php-telegram-bot/core
- */
-class TelegramLogTest extends TestCase
-{
- /**
- * @var array Dummy logfile paths
- */
- private static $logfiles = [
- 'debug' => '/tmp/php-telegram-bot-debug.log',
- 'error' => '/tmp/php-telegram-bot-error.log',
- 'update' => '/tmp/php-telegram-bot-update.log',
- ];
-
- protected function setUp(): void
- {
- TelegramLog::initialize(
- new Logger('bot_log', [
- (new StreamHandler(self::$logfiles['debug'], Logger::DEBUG))->setFormatter(new LineFormatter(null, null, true)),
- (new StreamHandler(self::$logfiles['error'], Logger::ERROR))->setFormatter(new LineFormatter(null, null, true)),
- ]),
- new Logger('bot_log_updates', [
- (new StreamHandler(self::$logfiles['update'], Logger::INFO))->setFormatter(new LineFormatter('%message%' . PHP_EOL)),
- ])
- );
- }
-
- protected function tearDown(): void
- {
- // Make sure no logger instance is set after each test.
- TestHelpers::setStaticProperty(TelegramLog::class, 'logger', null);
- TestHelpers::setStaticProperty(TelegramLog::class, 'update_logger', null);
-
- // Make sure no logfiles exist.
- foreach (self::$logfiles as $file) {
- file_exists($file) && unlink($file);
- }
- }
-
- public function testNullLogger(): void
- {
- TelegramLog::initialize(null, null);
-
- TelegramLog::debug('my debug log');
- TelegramLog::error('my error log');
- TelegramLog::update('my update log');
-
- foreach (self::$logfiles as $file) {
- self::assertFileDoesNotExist($file);
- }
- }
-
- public function testDebugStream(): void
- {
- $file = self::$logfiles['debug'];
-
- self::assertFileDoesNotExist($file);
- TelegramLog::debug('my debug log');
- TelegramLog::debug('my {place} {holder} debug log', ['place' => 'custom', 'holder' => 'placeholder']);
-
- self::assertFileExists($file);
- $debug_log = file_get_contents($file);
- self::assertStringContainsString('bot_log.DEBUG: my debug log', $debug_log);
- self::assertStringContainsString('bot_log.DEBUG: my custom placeholder debug log', $debug_log);
- }
-
- public function testErrorStream(): void
- {
- $file = self::$logfiles['error'];
-
- self::assertFileDoesNotExist($file);
- TelegramLog::error('my error log');
- TelegramLog::error('my {place} {holder} error log', ['place' => 'custom', 'holder' => 'placeholder']);
-
- self::assertFileExists($file);
- $error_log = file_get_contents($file);
- self::assertStringContainsString('bot_log.ERROR: my error log', $error_log);
- self::assertStringContainsString('bot_log.ERROR: my custom placeholder error log', $error_log);
- }
-
- public function testUpdateStream(): void
- {
- $file = self::$logfiles['update'];
-
- self::assertFileDoesNotExist($file);
- TelegramLog::update('my update log');
- TelegramLog::update('my {place} {holder} update log', ['place' => 'custom', 'holder' => 'placeholder']);
-
- self::assertFileExists($file);
- $update_log = file_get_contents($file);
- self::assertStringContainsString('my update log', $update_log);
- self::assertStringContainsString('my custom placeholder update log', $update_log);
- }
-}
diff --git a/tests/Unit/TelegramTest.php b/tests/Unit/TelegramTest.php
deleted file mode 100644
index 58855d914..000000000
--- a/tests/Unit/TelegramTest.php
+++ /dev/null
@@ -1,261 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit;
-
-use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts;
-use Dummy\AdminCommands\DummyAdminCommand;
-use Dummy\SystemCommands\DummySystemCommand;
-use Dummy\UserCommands\DummyUserCommand;
-use Longman\TelegramBot\Commands\UserCommands\StartCommand;
-use Longman\TelegramBot\Entities\Update;
-use Longman\TelegramBot\Exception\TelegramException;
-use Longman\TelegramBot\Telegram;
-use Longman\TelegramBot\TelegramLog;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class TelegramTest extends TestCase
-{
- use ArraySubsetAsserts;
-
- /**
- * @var Telegram
- */
- private $telegram;
-
- /**
- * @var array A few dummy custom commands paths
- */
- private $custom_commands_paths = [
- '/tmp/php-telegram-bot-custom-commands-1',
- '/tmp/php-telegram-bot-custom-commands-2',
- '/tmp/php-telegram-bot-custom-commands-3',
- ];
-
- protected function setUp(): void
- {
- $this->telegram = new Telegram(self::$dummy_api_key, 'testbot');
-
- // Create a few dummy custom commands paths.
- foreach ($this->custom_commands_paths as $custom_path) {
- mkdir($custom_path);
- }
- }
-
- protected function tearDown(): void
- {
- // Clean up the custom commands paths.
- foreach ($this->custom_commands_paths as $custom_path) {
- rmdir($custom_path);
- }
- }
-
- public function testNewInstanceWithoutApiKeyParam(): void
- {
- $this->expectException(TelegramException::class);
- $this->expectExceptionMessage('API KEY not defined!');
- new Telegram('');
- }
-
- public function testNewInstanceWithInvalidApiKeyParam(): void
- {
- $this->expectException(TelegramException::class);
- $this->expectExceptionMessage('Invalid API KEY defined!');
- new Telegram('invalid-api-key-format');
- }
-
- public function testGetApiKey(): void
- {
- self::assertEquals(self::$dummy_api_key, $this->telegram->getApiKey());
- }
-
- public function testGetBotUsername(): void
- {
- self::assertEquals('testbot', $this->telegram->getBotUsername());
- }
-
- public function testEnableAdmins(): void
- {
- $tg = $this->telegram;
-
- self::assertEmpty($tg->getAdminList());
-
- // Single
- $tg->enableAdmin(1);
- self::assertCount(1, $tg->getAdminList());
-
- // Multiple
- $tg->enableAdmins([2, 3]);
- self::assertCount(3, $tg->getAdminList());
-
- // Already added
- $tg->enableAdmin(2);
- self::assertCount(3, $tg->getAdminList());
- }
-
- public function testAddCustomCommandsPaths(): void
- {
- $tg = $this->telegram;
-
- self::assertCount(1, $tg->getCommandsPaths());
-
- $tg->addCommandsPath($this->custom_commands_paths[0]);
- self::assertCount(2, $tg->getCommandsPaths());
- self::assertArraySubset(
- [$this->custom_commands_paths[0]],
- $tg->getCommandsPaths()
- );
-
- $tg->addCommandsPath('/invalid/path');
- self::assertCount(2, $tg->getCommandsPaths());
-
- $tg->addCommandsPaths([
- $this->custom_commands_paths[1],
- $this->custom_commands_paths[2],
- ]);
- self::assertCount(4, $tg->getCommandsPaths());
- self::assertArraySubset(
- array_reverse($this->custom_commands_paths),
- $tg->getCommandsPaths()
- );
-
- $tg->addCommandsPath($this->custom_commands_paths[0]);
- self::assertCount(4, $tg->getCommandsPaths());
- }
-
- public function testAddCustomCommandsClass(): void
- {
- $tg = $this->telegram;
-
- // Require dummy commands to test with
- require_once __DIR__ . '/Commands/CustomTestCommands/DummySystemCommand.php';
- require_once __DIR__ . '/Commands/CustomTestCommands/DummyAdminCommand.php';
- require_once __DIR__ . '/Commands/CustomTestCommands/DummyUserCommand.php';
-
- // Test for base arrays (System, Admin, User)
- self::assertCount(3, $tg->getCommandClasses());
-
- // Test for invalid command classes
- try {
- $tg->addCommandClass('');
- } catch (\InvalidArgumentException $ex) {
- }
- self::assertEmpty(array_filter($tg->getCommandClasses()));
-
- try {
- $tg->addCommandClass('not\exist\Class');
- } catch (\InvalidArgumentException $ex) {
- }
- self::assertEmpty(array_filter($tg->getCommandClasses()));
-
- // Add valid command classes
- $tg->addCommandClass(DummySystemCommand::class);
- $tg->addCommandClasses([
- DummyAdminCommand::class,
- DummyUserCommand::class,
- ]);
-
- $command_classes = $tg->getCommandClasses();
- self::assertSame(['dummy_system' => 'Dummy\SystemCommands\DummySystemCommand'], $command_classes['System']);
- self::assertSame(['dummy_admin' => 'Dummy\AdminCommands\DummyAdminCommand'], $command_classes['Admin']);
- self::assertSame(['dummy_user' => 'Dummy\UserCommands\DummyUserCommand'], $command_classes['User']);
- }
-
- public function testSettingDownloadUploadPaths(): void
- {
- self::assertEmpty($this->telegram->getDownloadPath());
- self::assertEmpty($this->telegram->getUploadPath());
-
- $this->telegram->setDownloadPath('/down/below');
- $this->telegram->setUploadPath('/up/above');
-
- self::assertSame('/down/below', $this->telegram->getDownloadPath());
- self::assertSame('/up/above', $this->telegram->getUploadPath());
- }
-
- public function testGetCommandsList(): void
- {
- $commands = $this->telegram->getCommandsList();
- self::assertIsArray($commands);
- self::assertNotCount(0, $commands);
- }
-
- public function testGetCommandClass(): void
- {
- $className = StartCommand::class;
- $commands = $this->telegram->getCommandClasses();
- self::assertIsArray($commands);
- self::assertCount(3, $commands);
-
- $class = $this->telegram->getCommandClassName('user', 'notexist');
- self::assertNull($class);
-
- $this->telegram->addCommandClass($className);
- $class = $this->telegram->getCommandClassName('user', 'start');
- self::assertNotNull($class);
-
- self::assertSame($className, $class);
- }
-
- public function testUpdateFilter(): void
- {
- $rawUpdate = '{
- "update_id": 513400512,
- "message": {
- "message_id": 3,
- "from": {
- "id": 313534466,
- "first_name": "first",
- "last_name": "last",
- "username": "username"
- },
- "chat": {
- "id": 313534466,
- "first_name": "first",
- "last_name": "last",
- "username": "username",
- "type": "private"
- },
- "date": 1499402829,
- "text": "hi"
- }
- }';
-
- $debug_log_file = '/tmp/php-telegram-bot-update-filter-debug.log';
- TelegramLog::initialize(
- new \Monolog\Logger('bot_log', [
- (new \Monolog\Handler\StreamHandler($debug_log_file, \Monolog\Logger::DEBUG))->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, true)),
- ])
- );
-
- $update = new Update(json_decode($rawUpdate, true), $this->telegram->getBotUsername());
- $this->telegram->setUpdateFilter(function (Update $update, Telegram $telegram, &$reason) {
- if ($update->getMessage()->getChat()->getId() === 313534466) {
- $reason = 'Invalid user, update denied.';
- return false;
- }
- return true;
- });
- $response = $this->telegram->processUpdate($update);
- self::assertFalse($response->isOk());
-
- // Check that the reason is written to the debug log.
- $debug_log = file_get_contents($debug_log_file);
- self::assertStringContainsString('Invalid user, update denied.', $debug_log);
- file_exists($debug_log_file) && unlink($debug_log_file);
- }
-}
diff --git a/tests/Unit/TestCase.php b/tests/Unit/TestCase.php
deleted file mode 100644
index fe3ccbecb..000000000
--- a/tests/Unit/TestCase.php
+++ /dev/null
@@ -1,31 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit;
-
-use PHPUnit\Framework\TestCase as BaseTestCase;
-
-class TestCase extends BaseTestCase
-{
- /**
- * @var string
- */
- public static $dummy_api_key = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11';
-
- protected function skip64BitTest(): void
- {
- if (PHP_INT_SIZE === 4) {
- self::markTestSkipped(
- 'Skipping test that can run only on a 64-bit build of PHP.'
- );
- }
- }
-}
diff --git a/tests/Unit/TestHelpers.php b/tests/Unit/TestHelpers.php
deleted file mode 100644
index 5daa3ec13..000000000
--- a/tests/Unit/TestHelpers.php
+++ /dev/null
@@ -1,251 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Longman\TelegramBot\Tests\Unit;
-
-use Longman\TelegramBot\DB;
-use Longman\TelegramBot\Entities\Chat;
-use Longman\TelegramBot\Entities\Message;
-use Longman\TelegramBot\Entities\Update;
-use Longman\TelegramBot\Entities\User;
-use Longman\TelegramBot\Exception\TelegramException;
-
-/**
- * @link https://github.com/php-telegram-bot/core
- * @author Avtandil Kikabidze
- * @copyright Avtandil Kikabidze
- * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
- * @package TelegramTest
- */
-class TestHelpers
-{
- /**
- * Data template of a user.
- *
- * @var array
- */
- protected static $user_template = [
- 'id' => 1,
- 'first_name' => 'first',
- 'last_name' => 'last',
- 'username' => 'user',
- ];
-
- /**
- * Data template of a chat.
- *
- * @var array
- */
- protected static $chat_template = [
- 'id' => 1,
- 'first_name' => 'first',
- 'last_name' => 'last',
- 'username' => 'name',
- 'type' => 'private',
- 'all_members_are_administrators' => false,
- ];
-
- /**
- * Set the value of a private/protected property of an object
- *
- * @param object $object Object that contains the property
- * @param string $property Name of the property who's value we want to set
- * @param mixed $value The value to set to the property
- *
- * @throws \ReflectionException
- */
- public static function setObjectProperty(object $object, string $property, $value): void
- {
- $ref_object = new \ReflectionObject($object);
- $ref_property = $ref_object->getProperty($property);
- $ref_property->setAccessible(true);
- $ref_property->setValue($object, $value);
- }
-
- /**
- * Set the value of a private/protected static property of a class
- *
- * @param string $class Class that contains the static property
- * @param string $property Name of the property who's value we want to set
- * @param mixed $value The value to set to the property
- *
- * @throws \ReflectionException
- */
- public static function setStaticProperty(string $class, string $property, $value): void
- {
- $ref_property = new \ReflectionProperty($class, $property);
- $ref_property->setAccessible(true);
- $ref_property->setValue(null, $value);
- }
-
- /**
- * Return a simple fake Update object
- *
- * @param array $data Pass custom data array if needed
- *
- * @return Update
- */
- public static function getFakeUpdateObject(array $data = []): Update
- {
- $data = $data ?: [
- 'update_id' => mt_rand(),
- 'message' => [
- 'message_id' => mt_rand(),
- 'chat' => [
- 'id' => mt_rand(),
- ],
- 'date' => time(),
- ],
- ];
- return new Update($data, 'testbot');
- }
-
- /**
- * Return a fake command object for the passed command text
- *
- * @param string $command_text
- *
- * @return Update
- */
- public static function getFakeUpdateCommandObject(string $command_text): Update
- {
- $data = [
- 'update_id' => mt_rand(),
- 'message' => [
- 'message_id' => mt_rand(),
- 'from' => self::$user_template,
- 'chat' => self::$chat_template,
- 'date' => time(),
- 'text' => $command_text,
- ],
- ];
- return self::getFakeUpdateObject($data);
- }
-
- /**
- * Return a fake user object.
- *
- * @param array $data Pass custom data array if needed
- *
- * @return User
- */
- public static function getFakeUserObject(array $data = []): User
- {
- ($data === null) && $data = [];
-
- return new User($data + self::$user_template);
- }
-
- /**
- * Return a fake chat object.
- *
- * @param array $data Pass custom data array if needed
- *
- * @return Chat
- */
- public static function getFakeChatObject(array $data = []): Chat
- {
- return new Chat($data + self::$chat_template);
- }
-
- /**
- * Get fake recorded audio track
- *
- * @return array
- */
- public static function getFakeRecordedAudio(): array
- {
- $mime_type = ['audio/ogg', 'audio/mpeg', 'audio/vnd.wave', 'audio/x-ms-wma', 'audio/basic'];
- return [
- 'file_id' => mt_rand(1, 999),
- 'duration' => mt_rand(1, 99) . ':' . mt_rand(1, 60),
- 'performer' => 'phpunit',
- 'title' => 'track from phpunit',
- 'mime_type' => $mime_type[array_rand($mime_type, 1)],
- 'file_size' => mt_rand(1, 99999),
- ];
- }
-
- /**
- * Return a fake message object using the passed ids.
- *
- * @param array $message_data Pass custom message data array if needed
- * @param array $user_data Pass custom user data array if needed
- * @param array $chat_data Pass custom chat data array if needed
- *
- * @return Message
- */
- public static function getFakeMessageObject(array $message_data = [], array $user_data = [], array $chat_data = []): Message
- {
- return new Message($message_data + [
- 'message_id' => mt_rand(),
- 'from' => $user_data + self::$user_template,
- 'chat' => $chat_data + self::$chat_template,
- 'date' => time(),
- 'text' => 'dummy',
- ], 'testbot');
- }
-
- /**
- * Start a fake conversation for the passed command and return the randomly generated ids.
- *
- * @return array|false
- */
- public static function startFakeConversation()
- {
- if (!DB::isDbConnected()) {
- return false;
- }
-
- //Just get some random values.
- $message_id = mt_rand();
- $user_id = mt_rand();
- $chat_id = mt_rand();
-
- try {
- //Make sure we have a valid user and chat available.
- $message = self::getFakeMessageObject(['message_id' => $message_id], ['id' => $user_id], ['id' => $chat_id]);
- DB::insertMessageRequest($message);
- DB::insertUser($message->getFrom(), null, $message->getChat());
-
- return compact('message_id', 'user_id', 'chat_id');
- } catch (TelegramException $e) {
- return false;
- }
- }
-
- /**
- * Empty all tables for the passed database
- *
- * @param array $credentials
- */
- public static function emptyDb(array $credentials): void
- {
- $dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['database'];
- if (!empty($credentials['port'])) {
- $dsn .= ';port=' . $credentials['port'];
- }
-
- $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'];
-
- $pdo = new \PDO($dsn, $credentials['user'], $credentials['password'], $options);
- $pdo->prepare('
- DELETE FROM `conversation`;
- DELETE FROM `telegram_update`;
- DELETE FROM `chosen_inline_result`;
- DELETE FROM `inline_query`;
- DELETE FROM `message`;
- DELETE FROM `user_chat`;
- DELETE FROM `chat`;
- DELETE FROM `user`;
- ')->execute();
- }
-}
diff --git a/utils/db-schema-update/0.44.1-0.45.0.sql b/utils/db-schema-update/0.44.1-0.45.0.sql
deleted file mode 100644
index 98630c2b1..000000000
--- a/utils/db-schema-update/0.44.1-0.45.0.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-ALTER TABLE `user` ADD COLUMN `language_code` CHAR(10) DEFAULT NULL COMMENT 'User''s system language' AFTER `username`;
-ALTER TABLE `message` ADD COLUMN `video_note` TEXT COMMENT 'VoiceNote Object. Message is a Video Note, information about the Video Note' AFTER `voice`;
-ALTER TABLE `message` ADD COLUMN `new_chat_members` TEXT COMMENT 'List of unique user identifiers, new member(s) were added to the group, information about them (one of these members may be the bot itself)' AFTER `new_chat_member`;
-UPDATE `message` SET `new_chat_members` = `new_chat_member`;
diff --git a/utils/db-schema-update/0.47.1-0.48.0.sql b/utils/db-schema-update/0.47.1-0.48.0.sql
deleted file mode 100644
index 85131217c..000000000
--- a/utils/db-schema-update/0.47.1-0.48.0.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `user` ADD COLUMN `is_bot` tinyint(1) DEFAULT 0 COMMENT 'True if this user is a bot' AFTER `id`;
diff --git a/utils/db-schema-update/0.50.0-0.51.0.sql b/utils/db-schema-update/0.50.0-0.51.0.sql
deleted file mode 100644
index 86cae0a0e..000000000
--- a/utils/db-schema-update/0.50.0-0.51.0.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `message` ADD COLUMN `media_group_id` TEXT COMMENT 'The unique identifier of a media message group this message belongs to' AFTER `reply_to_message`;
diff --git a/utils/db-schema-update/0.52.0-0.53.0.sql b/utils/db-schema-update/0.52.0-0.53.0.sql
deleted file mode 100644
index 4b95fafac..000000000
--- a/utils/db-schema-update/0.52.0-0.53.0.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `message` ADD COLUMN `connected_website` TEXT NULL COMMENT 'The domain name of the website on which the user has logged in.' AFTER `pinned_message`;
diff --git a/utils/db-schema-update/0.53.0-0.54.0.sql b/utils/db-schema-update/0.53.0-0.54.0.sql
deleted file mode 100644
index 413978618..000000000
--- a/utils/db-schema-update/0.53.0-0.54.0.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `message` ADD COLUMN `game` TEXT NULL COMMENT 'Message is a game, information about the game.' AFTER `document`;
diff --git a/utils/db-schema-update/0.54.1-0.55.0.sql b/utils/db-schema-update/0.54.1-0.55.0.sql
deleted file mode 100644
index 531465bee..000000000
--- a/utils/db-schema-update/0.54.1-0.55.0.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-ALTER TABLE `message` ADD COLUMN `animation` TEXT NULL COMMENT 'Message is an animation, information about the animation' AFTER `document`;
-ALTER TABLE `message` ADD COLUMN `passport_data` TEXT NULL COMMENT 'Telegram Passport data' AFTER `connected_website`;
diff --git a/utils/db-schema-update/0.56.0-0.57.0.sql b/utils/db-schema-update/0.56.0-0.57.0.sql
deleted file mode 100644
index 120e33721..000000000
--- a/utils/db-schema-update/0.56.0-0.57.0.sql
+++ /dev/null
@@ -1,69 +0,0 @@
-ALTER TABLE `chat` ADD COLUMN `first_name` CHAR(255) DEFAULT NULL COMMENT 'First name of the other party in a private chat' AFTER `username`;
-ALTER TABLE `chat` ADD COLUMN `last_name` CHAR(255) DEFAULT NULL COMMENT 'Last name of the other party in a private chat' AFTER `first_name`;
-ALTER TABLE `message` ADD COLUMN `forward_signature` TEXT NULL DEFAULT NULL COMMENT 'For messages forwarded from channels, signature of the post author if present' AFTER `forward_from_message_id`;
-ALTER TABLE `message` ADD COLUMN `forward_sender_name` TEXT NULL DEFAULT NULL COMMENT 'Sender''s name for messages forwarded from users who disallow adding a link to their account in forwarded messages' AFTER `forward_signature`;
-ALTER TABLE `message` ADD COLUMN `edit_date` bigint UNSIGNED DEFAULT NULL COMMENT 'Date the message was last edited in Unix time' AFTER `reply_to_message`;
-ALTER TABLE `message` ADD COLUMN `author_signature` TEXT COMMENT 'Signature of the post author for messages in channels' AFTER `media_group_id`;
-ALTER TABLE `message` ADD COLUMN `caption_entities` TEXT COMMENT 'For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption';
-ALTER TABLE `message` ADD COLUMN `poll` TEXT COMMENT 'Poll object. Message is a native poll, information about the poll' AFTER `venue`;
-ALTER TABLE `message` ADD COLUMN `invoice` TEXT NULL COMMENT 'Message is an invoice for a payment, information about the invoice' AFTER `pinned_message`;
-ALTER TABLE `message` ADD COLUMN `successful_payment` TEXT NULL COMMENT 'Message is a service message about a successful payment, information about the payment' AFTER `invoice`;
-ALTER TABLE `callback_query` ADD COLUMN `chat_instance` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent' AFTER `inline_message_id`;
-ALTER TABLE `callback_query` ADD COLUMN `game_short_name` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Short name of a Game to be returned, serves as the unique identifier for the game' AFTER `data`;
-
-CREATE TABLE IF NOT EXISTS `shipping_query` (
- `id` bigint UNSIGNED COMMENT 'Unique query identifier',
- `user_id` bigint COMMENT 'User who sent the query',
- `invoice_payload` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Bot specified invoice payload',
- `shipping_address` CHAR(255) NOT NULL DEFAULT '' COMMENT 'User specified shipping address',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`),
- KEY `user_id` (`user_id`),
-
- FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-CREATE TABLE IF NOT EXISTS `pre_checkout_query` (
- `id` bigint UNSIGNED COMMENT 'Unique query identifier',
- `user_id` bigint COMMENT 'User who sent the query',
- `currency` CHAR(3) COMMENT 'Three-letter ISO 4217 currency code',
- `total_amount` bigint COMMENT 'Total price in the smallest units of the currency',
- `invoice_payload` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Bot specified invoice payload',
- `shipping_option_id` CHAR(255) NULL COMMENT 'Identifier of the shipping option chosen by the user',
- `order_info` TEXT NULL COMMENT 'Order info provided by the user',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`),
- KEY `user_id` (`user_id`),
-
- FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-CREATE TABLE IF NOT EXISTS `poll` (
- `id` bigint UNSIGNED COMMENT 'Unique poll identifier',
- `question` char(255) NOT NULL COMMENT 'Poll question',
- `options` text NOT NULL COMMENT 'List of poll options',
- `is_closed` tinyint(1) DEFAULT 0 COMMENT 'True, if the poll is closed',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-ALTER TABLE `telegram_update` ADD COLUMN `channel_post_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming channel post of any kind - text, photo, sticker, etc.';
-ALTER TABLE `telegram_update` ADD COLUMN `edited_channel_post_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New version of a channel post that is known to the bot and was edited';
-ALTER TABLE `telegram_update` ADD COLUMN `shipping_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming shipping query. Only for invoices with flexible price';
-ALTER TABLE `telegram_update` ADD COLUMN `pre_checkout_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming pre-checkout query. Contains full information about checkout';
-ALTER TABLE `telegram_update` ADD COLUMN `poll_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New poll state. Bots receive only updates about polls, which are sent or stopped by the bot';
-
-ALTER TABLE `telegram_update` ADD KEY `channel_post_id` (`channel_post_id`);
-ALTER TABLE `telegram_update` ADD KEY `edited_channel_post_id` (`edited_channel_post_id`);
-ALTER TABLE `telegram_update` ADD KEY `shipping_query_id` (`shipping_query_id`);
-ALTER TABLE `telegram_update` ADD KEY `pre_checkout_query_id` (`pre_checkout_query_id`);
-ALTER TABLE `telegram_update` ADD KEY `poll_id` (`poll_id`);
-
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`chat_id`, `channel_post_id`) REFERENCES `message` (`chat_id`, `id`);
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`edited_channel_post_id`) REFERENCES `edited_message` (`id`);
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`shipping_query_id`) REFERENCES `shipping_query` (`id`);
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`pre_checkout_query_id`) REFERENCES `pre_checkout_query` (`id`);
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`poll_id`) REFERENCES `poll` (`id`);
diff --git a/utils/db-schema-update/0.57.0-0.58.0.sql b/utils/db-schema-update/0.57.0-0.58.0.sql
deleted file mode 100644
index 9d48cd8e7..000000000
--- a/utils/db-schema-update/0.57.0-0.58.0.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE `message` ADD COLUMN `reply_markup` TEXT NULL COMMENT 'Inline keyboard attached to the message' AFTER `passport_data`;
diff --git a/utils/db-schema-update/0.60.0-0.61.0.sql b/utils/db-schema-update/0.60.0-0.61.0.sql
deleted file mode 100644
index 54b0c449c..000000000
--- a/utils/db-schema-update/0.60.0-0.61.0.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-SET FOREIGN_KEY_CHECKS=0;
-
-ALTER TABLE `telegram_update`
-DROP KEY `message_id`;
-
-ALTER TABLE `telegram_update`
-ADD KEY `message_id` (`message_id`),
-ADD KEY `chat_message_id` (`chat_id`, `message_id`);
-
-SET FOREIGN_KEY_CHECKS=1;
diff --git a/utils/db-schema-update/0.61.1-0.62.0.sql b/utils/db-schema-update/0.61.1-0.62.0.sql
deleted file mode 100644
index a38f361e0..000000000
--- a/utils/db-schema-update/0.61.1-0.62.0.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-ALTER TABLE `poll` ADD COLUMN `total_voter_count` int UNSIGNED COMMENT 'Total number of users that voted in the poll' AFTER `options`;
-ALTER TABLE `poll` ADD COLUMN `is_anonymous` tinyint(1) DEFAULT 1 COMMENT 'True, if the poll is anonymous' AFTER `is_closed`;
-ALTER TABLE `poll` ADD COLUMN `type` char(255) COMMENT 'Poll type, currently can be “regular” or “quiz”' AFTER `is_anonymous`;
-ALTER TABLE `poll` ADD COLUMN `allows_multiple_answers` tinyint(1) DEFAULT 0 COMMENT 'True, if the poll allows multiple answers' AFTER `type`;
-ALTER TABLE `poll` ADD COLUMN `correct_option_id` int UNSIGNED COMMENT '0-based identifier of the correct answer option. Available only for polls in the quiz mode, which are closed, or was sent (not forwarded) by the bot or to the private chat with the bot.' AFTER `allows_multiple_answers`;
-ALTER TABLE `message` ADD COLUMN `dice` TEXT COMMENT 'Message is a dice with random value from 1 to 6' AFTER `poll`;
-
-CREATE TABLE IF NOT EXISTS `poll_answer` (
- `poll_id` bigint UNSIGNED COMMENT 'Unique poll identifier',
- `user_id` bigint NOT NULL COMMENT 'The user, who changed the answer to the poll',
- `option_ids` text NOT NULL COMMENT '0-based identifiers of answer options, chosen by the user. May be empty if the user retracted their vote.',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`poll_id`),
- FOREIGN KEY (`poll_id`) REFERENCES `poll` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-ALTER TABLE `telegram_update` ADD COLUMN `poll_answer_poll_id` bigint UNSIGNED DEFAULT NULL COMMENT 'A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.' AFTER `poll_id`;
-ALTER TABLE `telegram_update` ADD KEY `poll_answer_poll_id` (`poll_answer_poll_id`);
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`poll_answer_poll_id`) REFERENCES `poll_answer` (`poll_id`);
diff --git a/utils/db-schema-update/0.62.0-0.63.0.sql b/utils/db-schema-update/0.62.0-0.63.0.sql
deleted file mode 100644
index 6e1ce95b3..000000000
--- a/utils/db-schema-update/0.62.0-0.63.0.sql
+++ /dev/null
@@ -1,15 +0,0 @@
-ALTER TABLE `poll` ADD COLUMN `explanation` varchar(255) DEFAULT NULL COMMENT 'Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters' AFTER `correct_option_id`;
-ALTER TABLE `poll` ADD COLUMN `explanation_entities` text DEFAULT NULL COMMENT 'Special entities like usernames, URLs, bot commands, etc. that appear in the explanation' AFTER `explanation`;
-ALTER TABLE `poll` ADD COLUMN `open_period` int UNSIGNED DEFAULT NULL COMMENT 'Amount of time in seconds the poll will be active after creation' AFTER `explanation_entities`;
-ALTER TABLE `poll` ADD COLUMN `close_date` timestamp NULL DEFAULT NULL COMMENT 'Point in time (Unix timestamp) when the poll will be automatically closed' AFTER `open_period`;
-
-ALTER TABLE `poll_answer` DROP PRIMARY KEY, ADD PRIMARY KEY (`poll_id`, `user_id`);
-
-ALTER TABLE `message`
- DROP FOREIGN KEY IF EXISTS `message_ibfk_6`,
- DROP INDEX IF EXISTS `message_ibfk_6`;
-
-ALTER TABLE `message`
- ADD COLUMN `via_bot` bigint NULL DEFAULT NULL COMMENT 'Optional. Bot through which the message was sent' AFTER `reply_to_message`,
- ADD KEY `via_bot` (`via_bot`),
- ADD FOREIGN KEY (`via_bot`) REFERENCES `user` (`id`);
diff --git a/utils/db-schema-update/0.64.0-0.70.0.sql b/utils/db-schema-update/0.64.0-0.70.0.sql
deleted file mode 100644
index daa708720..000000000
--- a/utils/db-schema-update/0.64.0-0.70.0.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-ALTER TABLE `message` ADD COLUMN `sender_chat_id` bigint COMMENT 'Sender of the message, sent on behalf of a chat' AFTER `chat_id`;
-ALTER TABLE `message` ADD COLUMN `proximity_alert_triggered` TEXT NULL COMMENT 'Service message. A user in the chat triggered another user''s proximity alert while sharing Live Location.' AFTER `passport_data`;
-ALTER TABLE `poll` MODIFY `question` text NOT NULL COMMENT 'Poll question';
diff --git a/utils/db-schema-update/0.71.0-0.72.0.sql b/utils/db-schema-update/0.71.0-0.72.0.sql
deleted file mode 100644
index 0720ae591..000000000
--- a/utils/db-schema-update/0.71.0-0.72.0.sql
+++ /dev/null
@@ -1,27 +0,0 @@
-ALTER TABLE `message` MODIFY `edit_date` timestamp NULL DEFAULT NULL COMMENT 'Date the message was last edited in Unix time';
-
-CREATE TABLE IF NOT EXISTS `chat_member_updated` (
- `id` BIGINT UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
- `chat_id` BIGINT NOT NULL COMMENT 'Chat the user belongs to',
- `user_id` BIGINT NOT NULL COMMENT 'Performer of the action, which resulted in the change',
- `date` TIMESTAMP NOT NULL COMMENT 'Date the change was done in Unix time',
- `old_chat_member` TEXT NOT NULL COMMENT 'Previous information about the chat member',
- `new_chat_member` TEXT NOT NULL COMMENT 'New information about the chat member',
- `invite_link` TEXT NULL COMMENT 'Chat invite link, which was used by the user to join the chat; for joining by invite link events only',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`),
-
- FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`),
- FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-ALTER TABLE `telegram_update` ADD COLUMN `my_chat_member_updated_id` BIGINT UNSIGNED NULL COMMENT 'The bot''s chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.';
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`my_chat_member_updated_id`) REFERENCES `chat_member_updated` (`id`);
-ALTER TABLE `telegram_update` ADD COLUMN `chat_member_updated_id` BIGINT UNSIGNED NULL COMMENT 'A chat member''s status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates.';
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`chat_member_updated_id`) REFERENCES `chat_member_updated` (`id`);
-
-ALTER TABLE `message` ADD COLUMN `message_auto_delete_timer_changed` TEXT COMMENT 'MessageAutoDeleteTimerChanged object. Message is a service message: auto-delete timer settings changed in the chat' AFTER `channel_chat_created`;
-ALTER TABLE `message` ADD COLUMN `voice_chat_started` TEXT COMMENT 'VoiceChatStarted object. Message is a service message: voice chat started' AFTER `proximity_alert_triggered`;
-ALTER TABLE `message` ADD COLUMN `voice_chat_ended` TEXT COMMENT 'VoiceChatEnded object. Message is a service message: voice chat ended' AFTER `voice_chat_started`;
-ALTER TABLE `message` ADD COLUMN `voice_chat_participants_invited` TEXT COMMENT 'VoiceChatParticipantsInvited object. Message is a service message: new participants invited to a voice chat' AFTER `voice_chat_ended`;
diff --git a/utils/db-schema-update/0.72.0-0.73.0.sql b/utils/db-schema-update/0.72.0-0.73.0.sql
deleted file mode 100644
index 2664a990c..000000000
--- a/utils/db-schema-update/0.72.0-0.73.0.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-ALTER TABLE `message` ADD COLUMN `voice_chat_scheduled` TEXT COMMENT 'VoiceChatScheduled object. Message is a service message: voice chat scheduled' AFTER `proximity_alert_triggered`;
-ALTER TABLE `inline_query` ADD COLUMN `chat_type` CHAR(255) NULL DEFAULT NULL COMMENT 'Optional. Type of the chat, from which the inline query was sent.' AFTER `offset`;
diff --git a/utils/db-schema-update/0.74.0-0.75.0.sql b/utils/db-schema-update/0.74.0-0.75.0.sql
deleted file mode 100644
index 6bbf51422..000000000
--- a/utils/db-schema-update/0.74.0-0.75.0.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-CREATE TABLE IF NOT EXISTS `chat_join_request` (
- `id` BIGINT UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
- `chat_id` BIGINT NOT NULL COMMENT 'Chat to which the request was sent',
- `user_id` BIGINT NOT NULL COMMENT 'User that sent the join request',
- `date` TIMESTAMP NOT NULL COMMENT 'Date the request was sent in Unix time',
- `bio` TEXT NULL COMMENT 'Optional. Bio of the user',
- `invite_link` TEXT NULL COMMENT 'Optional. Chat invite link that was used by the user to send the join request',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`),
-
- FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`),
- FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-ALTER TABLE `telegram_update` ADD COLUMN `chat_join_request_id` BIGINT UNSIGNED NULL COMMENT 'A request to join the chat has been sent';
-ALTER TABLE `telegram_update` ADD FOREIGN KEY (`chat_join_request_id`) REFERENCES `chat_join_request` (`id`);
-
-ALTER TABLE `message` ADD COLUMN `is_automatic_forward` tinyint(1) DEFAULT 0 COMMENT 'True, if the message is a channel post that was automatically forwarded to the connected discussion group' AFTER `forward_date`;
-ALTER TABLE `message` ADD COLUMN `has_protected_content` tinyint(1) DEFAULT 0 COMMENT 'True, if the message can''t be forwarded' AFTER `edit_date`;
diff --git a/utils/db-schema-update/0.76.1-0.77.0.sql b/utils/db-schema-update/0.76.1-0.77.0.sql
deleted file mode 100644
index 56c518489..000000000
--- a/utils/db-schema-update/0.76.1-0.77.0.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-ALTER TABLE `message` ADD COLUMN `web_app_data` TEXT NULL DEFAULT NULL COMMENT 'Service message: data sent by a Web App' AFTER `voice_chat_participants_invited`;
-
-ALTER TABLE `message`
- CHANGE `voice_chat_scheduled` `video_chat_scheduled` TEXT COMMENT 'Service message: video chat scheduled',
- CHANGE `voice_chat_started` `video_chat_started` TEXT COMMENT 'Service message: video chat started',
- CHANGE `voice_chat_ended` `video_chat_ended` TEXT COMMENT 'Service message: video chat ended',
- CHANGE `voice_chat_participants_invited` `video_chat_participants_invited` TEXT COMMENT 'Service message: new participants invited to a video chat';
diff --git a/utils/db-schema-update/0.77.1-0.78.0.sql b/utils/db-schema-update/0.77.1-0.78.0.sql
deleted file mode 100644
index 370ee6f73..000000000
--- a/utils/db-schema-update/0.77.1-0.78.0.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-ALTER TABLE `user` ADD COLUMN `is_premium` tinyint(1) DEFAULT 0 COMMENT 'True, if this user is a Telegram Premium user' AFTER `language_code`;
-ALTER TABLE `user` ADD COLUMN `added_to_attachment_menu` tinyint(1) DEFAULT 0 COMMENT 'True, if this user added the bot to the attachment menu' AFTER `is_premium`;
diff --git a/utils/db-schema-update/0.79.0-0.80.0.sql b/utils/db-schema-update/0.79.0-0.80.0.sql
deleted file mode 100644
index bba84eb43..000000000
--- a/utils/db-schema-update/0.79.0-0.80.0.sql
+++ /dev/null
@@ -1,9 +0,0 @@
-ALTER TABLE `message`
- ADD COLUMN `is_topic_message` TINYINT(1) DEFAULT 0 COMMENT 'True, if the message is sent to a forum topic' AFTER `forward_date`,
- ADD COLUMN `message_thread_id` BIGINT(20) NULL DEFAULT NULL COMMENT 'Unique identifier of a message thread to which the message belongs; for supergroups only' AFTER `id`,
- ADD COLUMN `forum_topic_created` TEXT NULL DEFAULT NULL COMMENT 'Service message: forum topic created' AFTER `proximity_alert_triggered`,
- ADD COLUMN `forum_topic_closed` TEXT NULL DEFAULT NULL COMMENT 'Service message: forum topic closed' AFTER `forum_topic_created`,
- ADD COLUMN `forum_topic_reopened` TEXT NULL DEFAULT NULL COMMENT 'Service message: forum topic reopened' AFTER `forum_topic_closed`;
-
-ALTER TABLE `chat`
- ADD COLUMN `is_forum` TINYINT(1) DEFAULT 0 COMMENT 'True, if the supergroup chat is a forum (has topics enabled)' AFTER `last_name`;
diff --git a/utils/db-schema-update/0.80.0-0.81.0.sql b/utils/db-schema-update/0.80.0-0.81.0.sql
deleted file mode 100644
index 4411b1201..000000000
--- a/utils/db-schema-update/0.80.0-0.81.0.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-ALTER TABLE `message`
- ADD COLUMN `has_media_spoiler` TINYINT(1) DEFAULT 0 COMMENT 'True, if the message media is covered by a spoiler animation' AFTER `caption`,
- ADD COLUMN `write_access_allowed` TEXT DEFAULT NULL COMMENT 'Service message: the user allowed the bot added to the attachment menu to write messages' AFTER `connected_website`,
- ADD COLUMN `forum_topic_edited` TEXT DEFAULT NULL COMMENT 'Service message: forum topic edited' AFTER `forum_topic_created`,
- ADD COLUMN `general_forum_topic_hidden` TEXT DEFAULT NULL COMMENT 'Service message: the General forum topic hidden' AFTER `forum_topic_reopened`,
- ADD COLUMN `general_forum_topic_unhidden` TEXT DEFAULT NULL COMMENT 'Service message: the General forum topic unhidden' AFTER `general_forum_topic_hidden`,
- ADD COLUMN `user_shared` TEXT DEFAULT NULL COMMENT 'Optional. Service message: a user was shared with the bot' AFTER `successful_payment`,
- ADD COLUMN `chat_shared` TEXT DEFAULT NULL COMMENT 'Optional. Service message: a chat was shared with the bot' AFTER `user_shared`;
diff --git a/utils/db-schema-update/0.81.0-0.82.0.sql b/utils/db-schema-update/0.81.0-0.82.0.sql
deleted file mode 100644
index bae194cb9..000000000
--- a/utils/db-schema-update/0.81.0-0.82.0.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-ALTER TABLE `message`
- ADD COLUMN `story` TEXT DEFAULT NULL COMMENT 'Story object. Message is a forwarded story' AFTER `sticker`;
diff --git a/utils/db-schema-update/0.82.0-unreleased.sql b/utils/db-schema-update/0.82.0-unreleased.sql
deleted file mode 100644
index 3fb04f377..000000000
--- a/utils/db-schema-update/0.82.0-unreleased.sql
+++ /dev/null
@@ -1,67 +0,0 @@
-CREATE TABLE IF NOT EXISTS `message_reaction` (
- `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
- `chat_id` bigint COMMENT 'The chat containing the message the user reacted to',
- `message_id` bigint COMMENT 'Unique identifier of the message inside the chat',
- `user_id` bigint NULL COMMENT 'Optional. The user that changed the reaction, if the user isn''t anonymous',
- `actor_chat_id` bigint NULL COMMENT 'Optional. The chat on behalf of which the reaction was changed, if the user is anonymous',
- `old_reaction` TEXT NOT NULL COMMENT 'Previous list of reaction types that were set by the user',
- `new_reaction` TEXT NOT NULL COMMENT 'New list of reaction types that have been set by the user',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`),
- KEY `chat_id` (`chat_id`),
- KEY `user_id` (`user_id`),
- KEY `actor_chat_id` (`actor_chat_id`),
-
- FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`),
- FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
- FOREIGN KEY (`actor_chat_id`) REFERENCES `chat` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-CREATE TABLE IF NOT EXISTS `message_reaction_count` (
- `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
- `chat_id` bigint COMMENT 'The chat containing the message',
- `message_id` bigint COMMENT 'Unique message identifier inside the chat',
- `reactions` TEXT NOT NULL COMMENT 'List of reactions that are present on the message',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`),
- KEY `chat_id` (`chat_id`),
-
- FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-CREATE TABLE IF NOT EXISTS `chat_boost_updated` (
- `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
- `chat_id` bigint COMMENT 'Chat which was boosted',
- `boost` TEXT NOT NULL COMMENT 'Information about the chat boost',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`),
- KEY `chat_id` (`chat_id`),
-
- FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-CREATE TABLE IF NOT EXISTS `chat_boost_removed` (
- `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
- `chat_id` bigint COMMENT 'Chat which was boosted',
- `boost_id` varchar(200) NOT NULL COMMENT 'Unique identifier of the boost',
- `remove_date` timestamp NOT NULL COMMENT 'Point in time (Unix timestamp) when the boost was removed',
- `source` TEXT NOT NULL COMMENT 'Source of the removed boost',
- `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
-
- PRIMARY KEY (`id`),
- KEY `chat_id` (`chat_id`),
-
- FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-
-ALTER TABLE `message`
- ADD COLUMN `external_reply` TEXT NULL DEFAULT NULL COMMENT 'Optional. Information about the message that is being replied to, which may come from another chat or forum topic' AFTER `reply_to_message`,
- ADD COLUMN `link_preview_options` TEXT NULL DEFAULT NULL COMMENT 'Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed' AFTER `via_bot`,
- CHANGE COLUMN `user_shared` `users_shared` TEXT;
-
-ALTER TABLE `telegram_update`
- ADD COLUMN `message_reaction_id` bigint UNSIGNED DEFAULT NULL COMMENT 'A reaction to a message was changed by a user' AFTER `edited_channel_post_id`,
- ADD COLUMN `message_reaction_count_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Reactions to a message with anonymous reactions were changed' AFTER `message_reaction_id`;
diff --git a/utils/importFromLog.php b/utils/importFromLog.php
deleted file mode 100644
index 634df0260..000000000
--- a/utils/importFromLog.php
+++ /dev/null
@@ -1,59 +0,0 @@
- 'localhost',
- 'port' => 3306, // optional
- 'user' => 'dbuser',
- 'password' => 'dbpass',
- 'database' => 'dbname',
-];
-
-try {
- // Create dummy Telegram API object and connect to MySQL database.
- (new Telegram('1:A'))->enableMySql($mysql_credentials);
-
- // Load the updates log file to iterate over.
- $updates_log_file = new SplFileObject($updates_log_file_path);
- $updates_log_file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
-
- foreach ($updates_log_file as $update_json) {
- if ($update_arr = json_decode($update_json, true)) {
- echo $update_json . PHP_EOL;
-
- // Get all updates on this line.
- $updates_data = array_filter($update_arr['result'] ?? [$update_arr]);
- foreach ($updates_data as $update_data) {
- $update = new Update($update_data);
- printf(
- 'Update ID %d %s' . PHP_EOL,
- $update->getUpdateId(),
- DB::insertRequest($update) ? '(success)' : '(failed) ' . implode(' ', DB::getPdo()->errorInfo())
- );
- }
- }
- }
-} catch (Throwable $e) {
- // Output any errors.
- echo $e;
-}