Page MenuHomePhabricator (Chris)

No OneTemporary

Authored By
Unknown
Size
176 KB
Referenced Files
None
Subscribers
None
diff --git a/src/DB.php b/src/DB.php
index 8aeefdc..25e5713 100644
--- a/src/DB.php
+++ b/src/DB.php
@@ -1,1627 +1,1725 @@
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
* Written by Marco Boretto <marco.bore@gmail.com>
*/
namespace Longman\TelegramBot;
use Longman\TelegramBot\Entities\CallbackQuery;
use Longman\TelegramBot\Entities\Chat;
+use Longman\TelegramBot\Entities\ChatBoostRemoved;
+use Longman\TelegramBot\Entities\ChatBoostUpdated;
use Longman\TelegramBot\Entities\ChatJoinRequest;
use Longman\TelegramBot\Entities\ChatMemberUpdated;
use Longman\TelegramBot\Entities\ChosenInlineResult;
use Longman\TelegramBot\Entities\InlineQuery;
use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\MessageReactionCountUpdated;
use Longman\TelegramBot\Entities\MessageReactionUpdated;
use Longman\TelegramBot\Entities\Payments\PreCheckoutQuery;
use Longman\TelegramBot\Entities\Payments\ShippingQuery;
use Longman\TelegramBot\Entities\Poll;
use Longman\TelegramBot\Entities\PollAnswer;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Entities\User;
use Longman\TelegramBot\Exception\TelegramException;
use PDO;
use PDOException;
class DB
{
/**
* MySQL credentials
*
* @var array
*/
protected static $mysql_credentials = [];
/**
* PDO object
*
* @var PDO
*/
protected static $pdo;
/**
* Table prefix
*
* @var string
*/
protected static $table_prefix;
/**
* Telegram class object
*
* @var Telegram
*/
protected static $telegram;
/**
* Initialize
*
* @param array $credentials Database connection details
* @param Telegram $telegram Telegram object to connect with this object
* @param string $table_prefix Table prefix
* @param string $encoding Database character encoding
*
* @return PDO PDO database object
* @throws TelegramException
*/
public static function initialize(
array $credentials,
Telegram $telegram,
$table_prefix = '',
$encoding = 'utf8mb4'
): PDO {
if (empty($credentials)) {
throw new TelegramException('MySQL credentials not provided!');
}
if (isset($credentials['unix_socket'])) {
$dsn = 'mysql:unix_socket=' . $credentials['unix_socket'];
} else {
$dsn = 'mysql:host=' . $credentials['host'];
}
$dsn .= ';dbname=' . $credentials['database'];
if (!empty($credentials['port'])) {
$dsn .= ';port=' . $credentials['port'];
}
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $encoding];
try {
$pdo = new PDO($dsn, $credentials['user'], $credentials['password'], $options);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
self::$pdo = $pdo;
self::$telegram = $telegram;
self::$mysql_credentials = $credentials;
self::$table_prefix = $table_prefix;
self::defineTables();
return self::$pdo;
}
/**
* External Initialize
*
* Let you use the class with an external already existing Pdo Mysql connection.
*
* @param PDO $external_pdo_connection PDO database object
* @param Telegram $telegram Telegram object to connect with this object
* @param string $table_prefix Table prefix
*
* @return PDO PDO database object
* @throws TelegramException
*/
public static function externalInitialize(
PDO $external_pdo_connection,
Telegram $telegram,
string $table_prefix = ''
): PDO {
if ($external_pdo_connection === null) {
throw new TelegramException('MySQL external connection not provided!');
}
self::$pdo = $external_pdo_connection;
self::$telegram = $telegram;
self::$mysql_credentials = [];
self::$table_prefix = $table_prefix;
self::defineTables();
return self::$pdo;
}
/**
* Define all the tables with the proper prefix
*/
protected static function defineTables(): void
{
$tables = [
'callback_query',
'chat',
+ 'chat_boost_updated',
+ 'chat_boost_removed',
'chat_join_request',
'chat_member_updated',
'chosen_inline_result',
'edited_message',
'inline_query',
'message',
'message_reaction',
'message_reaction_count',
'poll',
'poll_answer',
'pre_checkout_query',
'request_limiter',
'shipping_query',
'telegram_update',
'user',
'user_chat',
];
foreach ($tables as $table) {
$table_name = 'TB_' . strtoupper($table);
if (!defined($table_name)) {
define($table_name, self::$table_prefix . $table);
}
}
}
/**
* Check if database connection has been created
*
* @return bool
*/
public static function isDbConnected(): bool
{
return self::$pdo !== null;
}
/**
* Get the PDO object of the connected database
*
* @return PDO|null
*/
public static function getPdo(): ?PDO
{
return self::$pdo;
}
/**
* Fetch update(s) from DB
*
* @param int $limit Limit the number of updates to fetch
* @param string $id Check for unique update id
*
* @return array|bool Fetched data or false if not connected
* @throws TelegramException
*/
public static function selectTelegramUpdate(int $limit = 0, string $id = '')
{
if (!self::isDbConnected()) {
return false;
}
try {
$sql = '
SELECT `id`
FROM `' . TB_TELEGRAM_UPDATE . '`
';
if ($id !== '') {
$sql .= ' WHERE `id` = :id';
} else {
$sql .= ' ORDER BY `id` DESC';
}
if ($limit > 0) {
$sql .= ' LIMIT :limit';
}
$sth = self::$pdo->prepare($sql);
if ($limit > 0) {
$sth->bindValue(':limit', $limit, PDO::PARAM_INT);
}
if ($id !== '') {
$sth->bindValue(':id', $id);
}
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Fetch message(s) from DB
*
* @param int $limit Limit the number of messages to fetch
*
* @return array|bool Fetched data or false if not connected
* @throws TelegramException
*/
public static function selectMessages(int $limit = 0)
{
if (!self::isDbConnected()) {
return false;
}
try {
$sql = '
SELECT *
FROM `' . TB_MESSAGE . '`
ORDER BY `id` DESC
';
if ($limit > 0) {
$sql .= ' LIMIT :limit';
}
$sth = self::$pdo->prepare($sql);
if ($limit > 0) {
$sth->bindValue(':limit', $limit, PDO::PARAM_INT);
}
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Convert from unix timestamp to timestamp
*
* @param ?int $unixtime Unix timestamp (if empty, current timestamp is used)
*
* @return string
*/
protected static function getTimestamp(?int $unixtime = null): string
{
return date('Y-m-d H:i:s', $unixtime ?? time());
}
/**
* Convert array of Entity items to a JSON array
*
* @todo Find a better way, as json_* functions are very heavy
*
* @param array $entities
* @param mixed $default
*
* @return mixed
*/
public static function entitiesArrayToJson(array $entities, $default = null)
{
if (empty($entities)) {
return $default;
}
// Convert each Entity item into an object based on its JSON reflection
$json_entities = array_map(function ($entity) {
return json_decode($entity, true);
}, $entities);
return json_encode($json_entities);
}
/**
* Insert entry to telegram_update table
*
* @throws TelegramException
*/
protected static function insertTelegramUpdate(
int $update_id,
?int $chat_id = null,
?int $message_id = null,
?int $edited_message_id = null,
?int $channel_post_id = null,
?int $edited_channel_post_id = null,
?string $message_reaction_id = null,
?string $message_reaction_count_id = null,
?string $inline_query_id = null,
?string $chosen_inline_result_id = null,
?string $callback_query_id = null,
?string $shipping_query_id = null,
?string $pre_checkout_query_id = null,
?string $poll_id = null,
?string $poll_answer_poll_id = null,
?string $my_chat_member_updated_id = null,
?string $chat_member_updated_id = null,
- ?string $chat_join_request_id = null
+ ?string $chat_join_request_id = null,
+ ?string $chat_boost_updated_id = null,
+ ?string $chat_boost_removed_id = null
): ?bool {
- if ($message_id === null && $edited_message_id === null && $channel_post_id === null && $edited_channel_post_id === null && $message_reaction_id === null && $message_reaction_count_id === null && $inline_query_id === null && $chosen_inline_result_id === null && $callback_query_id === null && $shipping_query_id === null && $pre_checkout_query_id === null && $poll_id === null && $poll_answer_poll_id === null && $my_chat_member_updated_id === null && $chat_member_updated_id === null && $chat_join_request_id === null) {
- throw new TelegramException('message_id, edited_message_id, channel_post_id, edited_channel_post_id, message_reaction_id, message_reaction_count_id, inline_query_id, chosen_inline_result_id, callback_query_id, shipping_query_id, pre_checkout_query_id, poll_id, poll_answer_poll_id, my_chat_member_updated_id, chat_member_updated_id are all null');
+ if ($message_id === null && $edited_message_id === null && $channel_post_id === null && $edited_channel_post_id === null && $message_reaction_id === null && $message_reaction_count_id === null && $inline_query_id === null && $chosen_inline_result_id === null && $callback_query_id === null && $shipping_query_id === null && $pre_checkout_query_id === null && $poll_id === null && $poll_answer_poll_id === null && $my_chat_member_updated_id === null && $chat_member_updated_id === null && $chat_join_request_id === null && $chat_boost_updated_id === null && $chat_boost_removed_id === null) {
+ throw new TelegramException('message_id, edited_message_id, channel_post_id, edited_channel_post_id, message_reaction_id, message_reaction_count_id, inline_query_id, chosen_inline_result_id, callback_query_id, shipping_query_id, pre_checkout_query_id, poll_id, poll_answer_poll_id, my_chat_member_updated_id, chat_member_updated_id, chat_join_request_id, chat_boost_updated_id, chat_boost_removed_id are all null');
}
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_TELEGRAM_UPDATE . '`
(
`id`, `chat_id`, `message_id`, `edited_message_id`,
`channel_post_id`, `edited_channel_post_id`, `message_reaction_id`, `message_reaction_count_id`,
`inline_query_id`, `chosen_inline_result_id`,
`callback_query_id`, `shipping_query_id`, `pre_checkout_query_id`,
`poll_id`, `poll_answer_poll_id`, `my_chat_member_updated_id`, `chat_member_updated_id`,
- `chat_join_request_id`
+ `chat_join_request_id`, `chat_boost_updated_id`, `chat_boost_removed_id`
) VALUES (
:id, :chat_id, :message_id, :edited_message_id,
:channel_post_id, :edited_channel_post_id, :message_reaction_id, :message_reaction_count_id,
:inline_query_id, :chosen_inline_result_id,
:callback_query_id, :shipping_query_id, :pre_checkout_query_id,
:poll_id, :poll_answer_poll_id, :my_chat_member_updated_id, :chat_member_updated_id,
- :chat_join_request_id
+ :chat_join_request_id, :chat_boost_updated_id, :chat_boost_removed_id
)
');
$sth->bindValue(':id', $update_id);
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':message_id', $message_id);
$sth->bindValue(':edited_message_id', $edited_message_id);
$sth->bindValue(':channel_post_id', $channel_post_id);
$sth->bindValue(':edited_channel_post_id', $edited_channel_post_id);
$sth->bindValue(':message_reaction_id', $message_reaction_id);
$sth->bindValue(':message_reaction_count_id', $message_reaction_count_id);
$sth->bindValue(':inline_query_id', $inline_query_id);
$sth->bindValue(':chosen_inline_result_id', $chosen_inline_result_id);
$sth->bindValue(':callback_query_id', $callback_query_id);
$sth->bindValue(':shipping_query_id', $shipping_query_id);
$sth->bindValue(':pre_checkout_query_id', $pre_checkout_query_id);
$sth->bindValue(':poll_id', $poll_id);
$sth->bindValue(':poll_answer_poll_id', $poll_answer_poll_id);
$sth->bindValue(':my_chat_member_updated_id', $my_chat_member_updated_id);
$sth->bindValue(':chat_member_updated_id', $chat_member_updated_id);
$sth->bindValue(':chat_join_request_id', $chat_join_request_id);
+ $sth->bindValue(':chat_boost_updated_id', $chat_boost_updated_id);
+ $sth->bindValue(':chat_boost_removed_id', $chat_boost_removed_id);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert users and save their connection to chats
*
* @param User $user
* @param string|null $date
* @param Chat|null $chat
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertUser(User $user, ?string $date = null, ?Chat $chat = null): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_USER . '`
(`id`, `is_bot`, `username`, `first_name`, `last_name`, `language_code`, `is_premium`, `added_to_attachment_menu`, `created_at`, `updated_at`)
VALUES
(:id, :is_bot, :username, :first_name, :last_name, :language_code, :is_premium, :added_to_attachment_menu, :created_at, :updated_at)
ON DUPLICATE KEY UPDATE
`is_bot` = VALUES(`is_bot`),
`username` = VALUES(`username`),
`first_name` = VALUES(`first_name`),
`last_name` = VALUES(`last_name`),
`language_code` = VALUES(`language_code`),
`is_premium` = VALUES(`is_premium`),
`added_to_attachment_menu` = VALUES(`added_to_attachment_menu`),
`updated_at` = VALUES(`updated_at`)
');
$sth->bindValue(':id', $user->getId());
$sth->bindValue(':is_bot', $user->getIsBot(), PDO::PARAM_INT);
$sth->bindValue(':username', $user->getUsername());
$sth->bindValue(':first_name', $user->getFirstName());
$sth->bindValue(':last_name', $user->getLastName());
$sth->bindValue(':language_code', $user->getLanguageCode());
$sth->bindValue(':is_premium', $user->getIsPremium(), PDO::PARAM_INT);
$sth->bindValue(':added_to_attachment_menu', $user->getAddedToAttachmentMenu(), PDO::PARAM_INT);
$date = $date ?: self::getTimestamp();
$sth->bindValue(':created_at', $date);
$sth->bindValue(':updated_at', $date);
$status = $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
// Also insert the relationship to the chat into the user_chat table
if ($chat) {
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_USER_CHAT . '`
(`user_id`, `chat_id`)
VALUES
(:user_id, :chat_id)
');
$sth->bindValue(':user_id', $user->getId());
$sth->bindValue(':chat_id', $chat->getId());
$status = $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
return $status;
}
/**
* Insert chat
*
* @param Chat $chat
* @param string|null $date
* @param int|null $migrate_to_chat_id
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertChat(Chat $chat, ?string $date = null, ?int $migrate_to_chat_id = null): ?bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_CHAT . '`
(`id`, `type`, `title`, `username`, `first_name`, `last_name`, `is_forum`, `created_at` ,`updated_at`, `old_id`)
VALUES
(:id, :type, :title, :username, :first_name, :last_name, :is_forum, :created_at, :updated_at, :old_id)
ON DUPLICATE KEY UPDATE
`type` = VALUES(`type`),
`title` = VALUES(`title`),
`username` = VALUES(`username`),
`first_name` = VALUES(`first_name`),
`last_name` = VALUES(`last_name`),
`is_forum` = VALUES(`is_forum`),
`updated_at` = VALUES(`updated_at`)
');
$chat_id = $chat->getId();
$chat_type = $chat->getType();
if ($migrate_to_chat_id !== null) {
$chat_type = 'supergroup';
$sth->bindValue(':id', $migrate_to_chat_id);
$sth->bindValue(':old_id', $chat_id);
} else {
$sth->bindValue(':id', $chat_id);
$sth->bindValue(':old_id', $migrate_to_chat_id);
}
$sth->bindValue(':type', $chat_type);
$sth->bindValue(':title', $chat->getTitle());
$sth->bindValue(':username', $chat->getUsername());
$sth->bindValue(':first_name', $chat->getFirstName());
$sth->bindValue(':last_name', $chat->getLastName());
$sth->bindValue(':is_forum', $chat->getIsForum());
$date = $date ?: self::getTimestamp();
$sth->bindValue(':created_at', $date);
$sth->bindValue(':updated_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert request into database
*
* @todo self::$pdo->lastInsertId() - unsafe usage if expected previous insert fails?
*
* @param Update $update
*
* @return bool
* @throws TelegramException
*/
public static function insertRequest(Update $update): bool
{
if (!self::isDbConnected()) {
return false;
}
$chat_id = null;
$message_id = null;
$edited_message_id = null;
$channel_post_id = null;
$edited_channel_post_id = null;
$message_reaction_id = null;
$message_reaction_count_id = null;
$inline_query_id = null;
$chosen_inline_result_id = null;
$callback_query_id = null;
$shipping_query_id = null;
$pre_checkout_query_id = null;
$poll_id = null;
$poll_answer_poll_id = null;
$my_chat_member_updated_id = null;
$chat_member_updated_id = null;
$chat_join_request_id = null;
+ $chat_boost_updated_id = null;
+ $chat_boost_removed_id = null;
if (($message = $update->getMessage()) && self::insertMessageRequest($message)) {
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
} elseif (($edited_message = $update->getEditedMessage()) && self::insertEditedMessageRequest($edited_message)) {
$chat_id = $edited_message->getChat()->getId();
$edited_message_id = (int) self::$pdo->lastInsertId();
} elseif (($channel_post = $update->getChannelPost()) && self::insertMessageRequest($channel_post)) {
$chat_id = $channel_post->getChat()->getId();
$channel_post_id = $channel_post->getMessageId();
} elseif (($edited_channel_post = $update->getEditedChannelPost()) && self::insertEditedMessageRequest($edited_channel_post)) {
$chat_id = $edited_channel_post->getChat()->getId();
$edited_channel_post_id = (int) self::$pdo->lastInsertId();
} elseif (($message_reaction = $update->getMessageReaction()) && self::insertMessageReaction($message_reaction)) {
$chat_id = $message_reaction->getChat()->getId();
$message_id = $message_reaction->getMessageId();
$message_reaction_id = self::$pdo->lastInsertId();
} elseif (($message_reaction_count = $update->getMessageReactionCount()) && self::insertMessageReactionCount($message_reaction_count)) {
$chat_id = $message_reaction_count->getChat()->getId();
$message_id = $message_reaction_count->getMessageId();
$message_reaction_count_id = self::$pdo->lastInsertId();
} elseif (($inline_query = $update->getInlineQuery()) && self::insertInlineQueryRequest($inline_query)) {
$inline_query_id = $inline_query->getId();
} elseif (($chosen_inline_result = $update->getChosenInlineResult()) && self::insertChosenInlineResultRequest($chosen_inline_result)) {
$chosen_inline_result_id = self::$pdo->lastInsertId();
} elseif (($callback_query = $update->getCallbackQuery()) && self::insertCallbackQueryRequest($callback_query)) {
$callback_query_id = $callback_query->getId();
} elseif (($shipping_query = $update->getShippingQuery()) && self::insertShippingQueryRequest($shipping_query)) {
$shipping_query_id = $shipping_query->getId();
} elseif (($pre_checkout_query = $update->getPreCheckoutQuery()) && self::insertPreCheckoutQueryRequest($pre_checkout_query)) {
$pre_checkout_query_id = $pre_checkout_query->getId();
} elseif (($poll = $update->getPoll()) && self::insertPollRequest($poll)) {
$poll_id = $poll->getId();
} elseif (($poll_answer = $update->getPollAnswer()) && self::insertPollAnswerRequest($poll_answer)) {
$poll_answer_poll_id = $poll_answer->getPollId();
} elseif (($my_chat_member = $update->getMyChatMember()) && self::insertChatMemberUpdatedRequest($my_chat_member)) {
$my_chat_member_updated_id = self::$pdo->lastInsertId();
} elseif (($chat_member = $update->getChatMember()) && self::insertChatMemberUpdatedRequest($chat_member)) {
$chat_member_updated_id = self::$pdo->lastInsertId();
} elseif (($chat_join_request = $update->getChatJoinRequest()) && self::insertChatJoinRequestRequest($chat_join_request)) {
$chat_join_request_id = self::$pdo->lastInsertId();
+ } elseif (($chat_boost_updated = $update->getChatBoost()) && self::insertChatBoostUpdatedRequest($chat_boost_updated)) {
+ $chat_boost_updated_id = self::$pdo->lastInsertId();
+ } elseif (($chat_boost_removed = $update->getRemovedChatBoost()) && self::insertChatBoostRemovedRequest($chat_boost_removed)) {
+ $chat_boost_removed_id = self::$pdo->lastInsertId();
} else {
return false;
}
return self::insertTelegramUpdate(
$update->getUpdateId(),
$chat_id,
$message_id,
$edited_message_id,
$channel_post_id,
$edited_channel_post_id,
$message_reaction_id,
$message_reaction_count_id,
$inline_query_id,
$chosen_inline_result_id,
$callback_query_id,
$shipping_query_id,
$pre_checkout_query_id,
$poll_id,
$poll_answer_poll_id,
$my_chat_member_updated_id,
$chat_member_updated_id,
- $chat_join_request_id
+ $chat_join_request_id,
+ $chat_boost_updated_id,
+ $chat_boost_removed_id
);
}
public static function insertMessageReaction(MessageReactionUpdated $message_reaction): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_MESSAGE_REACTION . '`
(`chat_id`, `message_id`, `user_id`, `actor_chat_id`, `old_reaction`, `new_reaction`, `created_at`)
VALUES
(:chat_id, :message_id, :user_id, :actor_chat_id, :old_reaction, :new_reaction, :created_at)
');
$date = self::getTimestamp($message_reaction->getDate());
$chat_id = null;
$user_id = null;
$actor_chat_id = null;
if ($chat = $message_reaction->getChat()) {
$chat_id = $chat->getId();
self::insertChat($chat, $date);
}
if ($user = $message_reaction->getUser()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
if ($actor_chat = $message_reaction->getActorChat()) {
$actor_chat_id = $actor_chat->getId();
self::insertChat($actor_chat, $date);
}
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':message_id', $message_reaction->getMessageId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':actor_chat_id', $actor_chat_id);
$sth->bindValue(':old_reaction', self::entitiesArrayToJson($message_reaction->getOldReaction() ?: []));
$sth->bindValue(':new_reaction', self::entitiesArrayToJson($message_reaction->getNewReaction() ?: []));
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
public static function insertMessageReactionCount(MessageReactionCountUpdated $message_reaction_count): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_MESSAGE_REACTION_COUNT . '`
(`chat_id`, `message_id`, `reactions`, `created_at`)
VALUES
(:chat_id, :message_id, :reactions, :created_at)
');
$date = self::getTimestamp($message_reaction_count->getDate());
$chat_id = null;
if ($chat = $message_reaction->getChat()) {
$chat_id = $chat->getId();
self::insertChat($chat, $date);
}
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':message_id', $message_reaction_count->getMessageId());
$sth->bindValue(':reactions', $message_reaction_count->getReactions());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert inline query request into database
*
* @param InlineQuery $inline_query
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertInlineQueryRequest(InlineQuery $inline_query): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_INLINE_QUERY . '`
(`id`, `user_id`, `location`, `query`, `offset`, `chat_type`, `created_at`)
VALUES
(:id, :user_id, :location, :query, :offset, :chat_type, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $inline_query->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':id', $inline_query->getId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':location', $inline_query->getLocation());
$sth->bindValue(':query', $inline_query->getQuery());
$sth->bindValue(':offset', $inline_query->getOffset());
$sth->bindValue(':chat_type', $inline_query->getChatType());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert chosen inline result request into database
*
* @param ChosenInlineResult $chosen_inline_result
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertChosenInlineResultRequest(ChosenInlineResult $chosen_inline_result): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_CHOSEN_INLINE_RESULT . '`
(`result_id`, `user_id`, `location`, `inline_message_id`, `query`, `created_at`)
VALUES
(:result_id, :user_id, :location, :inline_message_id, :query, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $chosen_inline_result->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':result_id', $chosen_inline_result->getResultId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':location', $chosen_inline_result->getLocation());
$sth->bindValue(':inline_message_id', $chosen_inline_result->getInlineMessageId());
$sth->bindValue(':query', $chosen_inline_result->getQuery());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert callback query request into database
*
* @param CallbackQuery $callback_query
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertCallbackQueryRequest(CallbackQuery $callback_query): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_CALLBACK_QUERY . '`
(`id`, `user_id`, `chat_id`, `message_id`, `inline_message_id`, `chat_instance`, `data`, `game_short_name`, `created_at`)
VALUES
(:id, :user_id, :chat_id, :message_id, :inline_message_id, :chat_instance, :data, :game_short_name, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $callback_query->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$chat_id = null;
$message_id = null;
if ($message = $callback_query->getMessage()) {
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$is_message = self::$pdo->query('
SELECT *
FROM `' . TB_MESSAGE . '`
WHERE `id` = ' . $message_id . '
AND `chat_id` = ' . $chat_id . '
LIMIT 1
')->rowCount();
if ($is_message) {
self::insertEditedMessageRequest($message);
} else {
self::insertMessageRequest($message);
}
}
$sth->bindValue(':id', $callback_query->getId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':message_id', $message_id);
$sth->bindValue(':inline_message_id', $callback_query->getInlineMessageId());
$sth->bindValue(':chat_instance', $callback_query->getChatInstance());
$sth->bindValue(':data', $callback_query->getData());
$sth->bindValue(':game_short_name', $callback_query->getGameShortName());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert shipping query request into database
*
* @param ShippingQuery $shipping_query
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertShippingQueryRequest(ShippingQuery $shipping_query): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_SHIPPING_QUERY . '`
(`id`, `user_id`, `invoice_payload`, `shipping_address`, `created_at`)
VALUES
(:id, :user_id, :invoice_payload, :shipping_address, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $shipping_query->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':id', $shipping_query->getId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':invoice_payload', $shipping_query->getInvoicePayload());
$sth->bindValue(':shipping_address', $shipping_query->getShippingAddress());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert pre checkout query request into database
*
* @param PreCheckoutQuery $pre_checkout_query
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertPreCheckoutQueryRequest(PreCheckoutQuery $pre_checkout_query): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_PRE_CHECKOUT_QUERY . '`
(`id`, `user_id`, `currency`, `total_amount`, `invoice_payload`, `shipping_option_id`, `order_info`, `created_at`)
VALUES
(:id, :user_id, :currency, :total_amount, :invoice_payload, :shipping_option_id, :order_info, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $pre_checkout_query->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':id', $pre_checkout_query->getId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':currency', $pre_checkout_query->getCurrency());
$sth->bindValue(':total_amount', $pre_checkout_query->getTotalAmount());
$sth->bindValue(':invoice_payload', $pre_checkout_query->getInvoicePayload());
$sth->bindValue(':shipping_option_id', $pre_checkout_query->getShippingOptionId());
$sth->bindValue(':order_info', $pre_checkout_query->getOrderInfo());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert poll request into database
*
* @param Poll $poll
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertPollRequest(Poll $poll): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_POLL . '`
(`id`, `question`, `options`, `total_voter_count`, `is_closed`, `is_anonymous`, `type`, `allows_multiple_answers`, `correct_option_id`, `explanation`, `explanation_entities`, `open_period`, `close_date`, `created_at`)
VALUES
(:id, :question, :options, :total_voter_count, :is_closed, :is_anonymous, :type, :allows_multiple_answers, :correct_option_id, :explanation, :explanation_entities, :open_period, :close_date, :created_at)
ON DUPLICATE KEY UPDATE
`options` = VALUES(`options`),
`total_voter_count` = VALUES(`total_voter_count`),
`is_closed` = VALUES(`is_closed`),
`is_anonymous` = VALUES(`is_anonymous`),
`type` = VALUES(`type`),
`allows_multiple_answers` = VALUES(`allows_multiple_answers`),
`correct_option_id` = VALUES(`correct_option_id`),
`explanation` = VALUES(`explanation`),
`explanation_entities` = VALUES(`explanation_entities`),
`open_period` = VALUES(`open_period`),
`close_date` = VALUES(`close_date`)
');
$sth->bindValue(':id', $poll->getId());
$sth->bindValue(':question', $poll->getQuestion());
$sth->bindValue(':options', self::entitiesArrayToJson($poll->getOptions() ?: []));
$sth->bindValue(':total_voter_count', $poll->getTotalVoterCount());
$sth->bindValue(':is_closed', $poll->getIsClosed(), PDO::PARAM_INT);
$sth->bindValue(':is_anonymous', $poll->getIsAnonymous(), PDO::PARAM_INT);
$sth->bindValue(':type', $poll->getType());
$sth->bindValue(':allows_multiple_answers', $poll->getAllowsMultipleAnswers(), PDO::PARAM_INT);
$sth->bindValue(':correct_option_id', $poll->getCorrectOptionId());
$sth->bindValue(':explanation', $poll->getExplanation());
$sth->bindValue(':explanation_entities', self::entitiesArrayToJson($poll->getExplanationEntities() ?: []));
$sth->bindValue(':open_period', $poll->getOpenPeriod());
$sth->bindValue(':close_date', self::getTimestamp($poll->getCloseDate()));
$sth->bindValue(':created_at', self::getTimestamp());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert poll answer request into database
*
* @param PollAnswer $poll_answer
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertPollAnswerRequest(PollAnswer $poll_answer): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_POLL_ANSWER . '`
(`poll_id`, `user_id`, `option_ids`, `created_at`)
VALUES
(:poll_id, :user_id, :option_ids, :created_at)
ON DUPLICATE KEY UPDATE
`option_ids` = VALUES(`option_ids`)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $poll_answer->getUser()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':poll_id', $poll_answer->getPollId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':option_ids', json_encode($poll_answer->getOptionIds()));
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert chat member updated request into database
*
* @param ChatMemberUpdated $chat_member_updated
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertChatMemberUpdatedRequest(ChatMemberUpdated $chat_member_updated): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_CHAT_MEMBER_UPDATED . '`
(`chat_id`, `user_id`, `date`, `old_chat_member`, `new_chat_member`, `invite_link`, `created_at`)
VALUES
(:chat_id, :user_id, :date, :old_chat_member, :new_chat_member, :invite_link, :created_at)
');
$date = self::getTimestamp();
$chat_id = null;
$user_id = null;
if ($chat = $chat_member_updated->getChat()) {
$chat_id = $chat->getId();
self::insertChat($chat, $date);
}
if ($user = $chat_member_updated->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':date', self::getTimestamp($chat_member_updated->getDate()));
$sth->bindValue(':old_chat_member', $chat_member_updated->getOldChatMember());
$sth->bindValue(':new_chat_member', $chat_member_updated->getNewChatMember());
$sth->bindValue(':invite_link', $chat_member_updated->getInviteLink());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert chat join request into database
*
* @param ChatJoinRequest $chat_join_request
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertChatJoinRequestRequest(ChatJoinRequest $chat_join_request): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_CHAT_JOIN_REQUEST . '`
(`chat_id`, `user_id`, `date`, `bio`, `invite_link`, `created_at`)
VALUES
(:chat_id, :user_id, :date, :bio, :invite_link, :created_at)
');
$date = self::getTimestamp();
$chat_id = null;
$user_id = null;
if ($chat = $chat_join_request->getChat()) {
$chat_id = $chat->getId();
self::insertChat($chat, $date);
}
if ($user = $chat_join_request->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':date', self::getTimestamp($chat_join_request->getDate()));
$sth->bindValue(':bio', $chat_join_request->getBio());
$sth->bindValue(':invite_link', $chat_join_request->getInviteLink());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
+ /**
+ * Insert chat boost updated into database
+ *
+ * @param ChatBoostUpdated $chat_boost_updated
+ *
+ * @return bool If the insert was successful
+ * @throws TelegramException
+ */
+ public static function insertChatBoostUpdatedRequest(ChatBoostUpdated $chat_boost_updated): bool
+ {
+ if (!self::isDbConnected()) {
+ return false;
+ }
+
+ try {
+ $sth = self::$pdo->prepare('
+ INSERT INTO `' . TB_CHAT_BOOST_UPDATED . '`
+ (`chat_id`, `boost`, `created_at`)
+ VALUES
+ (:chat_id, :boost, :created_at)
+ ');
+
+ $date = self::getTimestamp();
+ $chat_id = null;
+
+ if ($chat = $chat_boost_updated->getChat()) {
+ $chat_id = $chat->getId();
+ self::insertChat($chat, $date);
+ }
+
+ $sth->bindValue(':chat_id', $chat_id);
+ $sth->bindValue(':boost', $chat_boost_updated->getBoost());
+ $sth->bindValue(':created_at', $date);
+
+ return $sth->execute();
+ } catch (PDOException $e) {
+ throw new TelegramException($e->getMessage());
+ }
+ }
+
+ /**
+ * Insert chat boost removed into database
+ *
+ * @param ChatBoostRemoved $chat_boost_removed
+ *
+ * @return bool If the insert was successful
+ * @throws TelegramException
+ */
+ public static function insertChatBoostRemovedRequest(ChatBoostRemoved $chat_boost_removed): bool
+ {
+ if (!self::isDbConnected()) {
+ return false;
+ }
+
+ try {
+ $sth = self::$pdo->prepare('
+ INSERT INTO `' . TB_CHAT_BOOST_REMOVED . '`
+ (`chat_id`, `boost_id`, `remove_date`, `source`, `created_at`)
+ VALUES
+ (:chat_id, :boost_id, :remove_date, :source, :created_at)
+ ');
+
+ $date = self::getTimestamp();
+ $chat_id = null;
+
+ if ($chat = $chat_boost_removed->getChat()) {
+ $chat_id = $chat->getId();
+ self::insertChat($chat, $date);
+ }
+
+ $sth->bindValue(':chat_id', $chat_id);
+ $sth->bindValue(':boost_id', $chat_boost_removed->getBoostId());
+ $sth->bindValue(':remove_date', self::getTimestamp($chat_boost_removed->getRemoveDate()));
+ $sth->bindValue(':source', $chat_boost_removed->getSource());
+ $sth->bindValue(':created_at', $date);
+
+ return $sth->execute();
+ } catch (PDOException $e) {
+ throw new TelegramException($e->getMessage());
+ }
+ }
+
/**
* Insert Message request in db
*
* @param Message $message
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertMessageRequest(Message $message): bool
{
if (!self::isDbConnected()) {
return false;
}
$date = self::getTimestamp($message->getDate());
// Insert chat, update chat id in case it migrated
$chat = $message->getChat();
self::insertChat($chat, $date, $message->getMigrateToChatId());
$sender_chat_id = null;
if ($sender_chat = $message->getSenderChat()) {
self::insertChat($sender_chat);
$sender_chat_id = $sender_chat->getId();
}
// Insert user and the relation with the chat
if ($user = $message->getFrom()) {
self::insertUser($user, $date, $chat);
}
// Insert the forwarded message user in users table
$forward_date = $message->getForwardDate() ? self::getTimestamp($message->getForwardDate()) : null;
if ($forward_from = $message->getForwardFrom()) {
self::insertUser($forward_from);
$forward_from = $forward_from->getId();
}
if ($forward_from_chat = $message->getForwardFromChat()) {
self::insertChat($forward_from_chat);
$forward_from_chat = $forward_from_chat->getId();
}
$via_bot_id = null;
if ($via_bot = $message->getViaBot()) {
self::insertUser($via_bot);
$via_bot_id = $via_bot->getId();
}
// New and left chat member
$new_chat_members_ids = null;
$left_chat_member_id = null;
$new_chat_members = $message->getNewChatMembers();
$left_chat_member = $message->getLeftChatMember();
if (!empty($new_chat_members)) {
foreach ($new_chat_members as $new_chat_member) {
if ($new_chat_member instanceof User) {
// Insert the new chat user
self::insertUser($new_chat_member, $date, $chat);
$new_chat_members_ids[] = $new_chat_member->getId();
}
}
$new_chat_members_ids = implode(',', $new_chat_members_ids);
} elseif ($left_chat_member) {
// Insert the left chat user
self::insertUser($left_chat_member, $date, $chat);
$left_chat_member_id = $left_chat_member->getId();
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_MESSAGE . '`
(
`id`, `user_id`, `chat_id`, `message_thread_id`, `sender_chat_id`, `date`, `forward_from`, `forward_from_chat`, `forward_from_message_id`,
`forward_signature`, `forward_sender_name`, `forward_date`, `is_topic_message`,
`reply_to_chat`, `reply_to_message`, `external_reply`, `via_bot`, `link_preview_options`, `edit_date`, `media_group_id`, `author_signature`, `text`, `entities`, `caption_entities`,
`audio`, `document`, `animation`, `game`, `photo`, `sticker`, `story`, `video`, `voice`, `video_note`, `caption`, `has_media_spoiler`, `contact`,
`location`, `venue`, `poll`, `dice`, `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`, `user_shared`, `chat_shared`, `connected_website`, `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`
) VALUES (
:message_id, :user_id, :chat_id, :message_thread_id, :sender_chat_id, :date, :forward_from, :forward_from_chat, :forward_from_message_id,
:forward_signature, :forward_sender_name, :forward_date, :is_topic_message,
:reply_to_chat, :reply_to_message, :external_reply, :via_bot, :link_preview_options, :edit_date, :media_group_id, :author_signature, :text, :entities, :caption_entities,
:audio, :document, :animation, :game, :photo, :sticker, :story, :video, :voice, :video_note, :caption, :has_media_spoiler, :contact,
:location, :venue, :poll, :dice, :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, :user_shared, :chat_shared, :connected_website, :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
)
');
$user_id = $user ? $user->getId() : null;
$chat_id = $chat->getId();
$reply_to_message_id = null;
if ($reply_to_message = $message->getReplyToMessage()) {
$reply_to_message_id = $reply_to_message->getMessageId();
// please notice that, as explained in the documentation, reply_to_message don't contain other
// reply_to_message field so recursion deep is 1
self::insertMessageRequest($reply_to_message);
}
$sth->bindValue(':message_id', $message->getMessageId());
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':sender_chat_id', $sender_chat_id);
$sth->bindValue(':message_thread_id', $message->getMessageThreadId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':date', $date);
$sth->bindValue(':forward_from', $forward_from);
$sth->bindValue(':forward_from_chat', $forward_from_chat);
$sth->bindValue(':forward_from_message_id', $message->getForwardFromMessageId());
$sth->bindValue(':forward_signature', $message->getForwardSignature());
$sth->bindValue(':forward_sender_name', $message->getForwardSenderName());
$sth->bindValue(':forward_date', $forward_date);
$sth->bindValue(':is_topic_message', $message->getIsTopicMessage());
$reply_to_chat_id = null;
if ($reply_to_message_id !== null) {
$reply_to_chat_id = $chat_id;
}
$sth->bindValue(':reply_to_chat', $reply_to_chat_id);
$sth->bindValue(':reply_to_message', $reply_to_message_id);
$sth->bindValue(':external_reply', $message->getExternalReply());
$sth->bindValue(':via_bot', $via_bot_id);
$sth->bindValue(':link_preview_options', $message->getLinkPreviewOptions());
$sth->bindValue(':edit_date', self::getTimestamp($message->getEditDate()));
$sth->bindValue(':media_group_id', $message->getMediaGroupId());
$sth->bindValue(':author_signature', $message->getAuthorSignature());
$sth->bindValue(':text', $message->getText());
$sth->bindValue(':entities', self::entitiesArrayToJson($message->getEntities() ?: []));
$sth->bindValue(':caption_entities', self::entitiesArrayToJson($message->getCaptionEntities() ?: []));
$sth->bindValue(':audio', $message->getAudio());
$sth->bindValue(':document', $message->getDocument());
$sth->bindValue(':animation', $message->getAnimation());
$sth->bindValue(':game', $message->getGame());
$sth->bindValue(':photo', self::entitiesArrayToJson($message->getPhoto() ?: []));
$sth->bindValue(':sticker', $message->getSticker());
$sth->bindValue(':story', $message->getStory());
$sth->bindValue(':video', $message->getVideo());
$sth->bindValue(':voice', $message->getVoice());
$sth->bindValue(':video_note', $message->getVideoNote());
$sth->bindValue(':caption', $message->getCaption());
$sth->bindValue(':has_media_spoiler', $message->getHasMediaSpoiler());
$sth->bindValue(':contact', $message->getContact());
$sth->bindValue(':location', $message->getLocation());
$sth->bindValue(':venue', $message->getVenue());
$sth->bindValue(':poll', $message->getPoll());
$sth->bindValue(':dice', $message->getDice());
$sth->bindValue(':new_chat_members', $new_chat_members_ids);
$sth->bindValue(':left_chat_member', $left_chat_member_id);
$sth->bindValue(':new_chat_title', $message->getNewChatTitle());
$sth->bindValue(':new_chat_photo', self::entitiesArrayToJson($message->getNewChatPhoto() ?: []));
$sth->bindValue(':delete_chat_photo', $message->getDeleteChatPhoto());
$sth->bindValue(':group_chat_created', $message->getGroupChatCreated());
$sth->bindValue(':supergroup_chat_created', $message->getSupergroupChatCreated());
$sth->bindValue(':channel_chat_created', $message->getChannelChatCreated());
$sth->bindValue(':message_auto_delete_timer_changed', $message->getMessageAutoDeleteTimerChanged());
$sth->bindValue(':migrate_to_chat_id', $message->getMigrateToChatId());
$sth->bindValue(':migrate_from_chat_id', $message->getMigrateFromChatId());
$sth->bindValue(':pinned_message', $message->getPinnedMessage());
$sth->bindValue(':invoice', $message->getInvoice());
$sth->bindValue(':successful_payment', $message->getSuccessfulPayment());
$sth->bindValue(':user_shared', $message->getUserShared());
$sth->bindValue(':chat_shared', $message->getChatShared());
$sth->bindValue(':connected_website', $message->getConnectedWebsite());
$sth->bindValue(':write_access_allowed', $message->getWriteAccessAllowed());
$sth->bindValue(':passport_data', $message->getPassportData());
$sth->bindValue(':proximity_alert_triggered', $message->getProximityAlertTriggered());
$sth->bindValue(':forum_topic_created', $message->getForumTopicCreated());
$sth->bindValue(':forum_topic_edited', $message->getForumTopicEdited());
$sth->bindValue(':forum_topic_closed', $message->getForumTopicClosed());
$sth->bindValue(':forum_topic_reopened', $message->getForumTopicReopened());
$sth->bindValue(':general_forum_topic_hidden', $message->getGeneralForumTopicHidden());
$sth->bindValue(':general_forum_topic_unhidden', $message->getGeneralForumTopicUnhidden());
$sth->bindValue(':video_chat_scheduled', $message->getVideoChatScheduled());
$sth->bindValue(':video_chat_started', $message->getVideoChatStarted());
$sth->bindValue(':video_chat_ended', $message->getVideoChatEnded());
$sth->bindValue(':video_chat_participants_invited', $message->getVideoChatParticipantsInvited());
$sth->bindValue(':web_app_data', $message->getWebAppData());
$sth->bindValue(':reply_markup', $message->getReplyMarkup());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert Edited Message request in db
*
* @param Message $edited_message
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertEditedMessageRequest(Message $edited_message): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$edit_date = self::getTimestamp($edited_message->getEditDate());
// Insert chat
$chat = $edited_message->getChat();
self::insertChat($chat, $edit_date);
// Insert user and the relation with the chat
if ($user = $edited_message->getFrom()) {
self::insertUser($user, $edit_date, $chat);
}
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_EDITED_MESSAGE . '`
(`chat_id`, `message_id`, `user_id`, `edit_date`, `text`, `entities`, `caption`)
VALUES
(:chat_id, :message_id, :user_id, :edit_date, :text, :entities, :caption)
');
$user_id = $user ? $user->getId() : null;
$sth->bindValue(':chat_id', $chat->getId());
$sth->bindValue(':message_id', $edited_message->getMessageId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':edit_date', $edit_date);
$sth->bindValue(':text', $edited_message->getText());
$sth->bindValue(':entities', self::entitiesArrayToJson($edited_message->getEntities() ?: []));
$sth->bindValue(':caption', $edited_message->getCaption());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Select Groups, Supergroups, Channels and/or single user Chats (also by ID or text)
*
* @param $select_chats_params
*
* @return array|bool
* @throws TelegramException
*/
public static function selectChats($select_chats_params)
{
if (!self::isDbConnected()) {
return false;
}
// Set defaults for omitted values.
$select = array_merge([
'groups' => true,
'supergroups' => true,
'channels' => true,
'users' => true,
'date_from' => null,
'date_to' => null,
'chat_id' => null,
'text' => null,
'language' => null,
], $select_chats_params);
if (!$select['groups'] && !$select['users'] && !$select['supergroups'] && !$select['channels']) {
return false;
}
try {
$query = '
SELECT * ,
' . TB_CHAT . '.`id` AS `chat_id`,
' . TB_CHAT . '.`username` AS `chat_username`,
' . TB_CHAT . '.`created_at` AS `chat_created_at`,
' . TB_CHAT . '.`updated_at` AS `chat_updated_at`
';
if ($select['users']) {
$query .= '
, ' . TB_USER . '.`id` AS `user_id`
FROM `' . TB_CHAT . '`
LEFT JOIN `' . TB_USER . '`
ON ' . TB_CHAT . '.`id`=' . TB_USER . '.`id`
';
} else {
$query .= 'FROM `' . TB_CHAT . '`';
}
// Building parts of query
$where = [];
$tokens = [];
if (!$select['groups'] || !$select['users'] || !$select['supergroups'] || !$select['channels']) {
$chat_or_user = [];
$select['groups'] && $chat_or_user[] = TB_CHAT . '.`type` = "group"';
$select['supergroups'] && $chat_or_user[] = TB_CHAT . '.`type` = "supergroup"';
$select['channels'] && $chat_or_user[] = TB_CHAT . '.`type` = "channel"';
$select['users'] && $chat_or_user[] = TB_CHAT . '.`type` = "private"';
$where[] = '(' . implode(' OR ', $chat_or_user) . ')';
}
if (null !== $select['date_from']) {
$where[] = TB_CHAT . '.`updated_at` >= :date_from';
$tokens[':date_from'] = $select['date_from'];
}
if (null !== $select['date_to']) {
$where[] = TB_CHAT . '.`updated_at` <= :date_to';
$tokens[':date_to'] = $select['date_to'];
}
if (null !== $select['chat_id']) {
$where[] = TB_CHAT . '.`id` = :chat_id';
$tokens[':chat_id'] = $select['chat_id'];
}
if ($select['users'] && null !== $select['language']) {
$where[] = TB_USER . '.`language_code` = :language';
$tokens[':language'] = $select['language'];
}
if (null !== $select['text']) {
$text_like = '%' . strtolower($select['text']) . '%';
if ($select['users']) {
$where[] = '(
LOWER(' . TB_CHAT . '.`title`) LIKE :text1
OR LOWER(' . TB_USER . '.`first_name`) LIKE :text2
OR LOWER(' . TB_USER . '.`last_name`) LIKE :text3
OR LOWER(' . TB_USER . '.`username`) LIKE :text4
)';
$tokens[':text1'] = $text_like;
$tokens[':text2'] = $text_like;
$tokens[':text3'] = $text_like;
$tokens[':text4'] = $text_like;
} else {
$where[] = 'LOWER(' . TB_CHAT . '.`title`) LIKE :text';
$tokens[':text'] = $text_like;
}
}
if (!empty($where)) {
$query .= ' WHERE ' . implode(' AND ', $where);
}
$query .= ' ORDER BY ' . TB_CHAT . '.`updated_at` ASC';
$sth = self::$pdo->prepare($query);
$sth->execute($tokens);
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Get Telegram API request count for current chat / message
*
* @param int|string|null $chat_id
* @param string|null $inline_message_id
*
* @return array|bool Array containing TOTAL and CURRENT fields or false on invalid arguments
* @throws TelegramException
*/
public static function getTelegramRequestCount($chat_id = null, string $inline_message_id = null)
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('SELECT
(SELECT COUNT(DISTINCT `chat_id`) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_1) AS LIMIT_PER_SEC_ALL,
(SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_2 AND ((`chat_id` = :chat_id_1 AND `inline_message_id` IS NULL) OR (`inline_message_id` = :inline_message_id AND `chat_id` IS NULL))) AS LIMIT_PER_SEC,
(SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_minute AND `chat_id` = :chat_id_2) AS LIMIT_PER_MINUTE
');
$date = self::getTimestamp();
$date_minute = self::getTimestamp(strtotime('-1 minute'));
$sth->bindValue(':chat_id_1', $chat_id);
$sth->bindValue(':chat_id_2', $chat_id);
$sth->bindValue(':inline_message_id', $inline_message_id);
$sth->bindValue(':created_at_1', $date);
$sth->bindValue(':created_at_2', $date);
$sth->bindValue(':created_at_minute', $date_minute);
$sth->execute();
return $sth->fetch();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert Telegram API request in db
*
* @param string $method
* @param array $data
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertTelegramRequest(string $method, array $data): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('INSERT INTO `' . TB_REQUEST_LIMITER . '`
(`method`, `chat_id`, `inline_message_id`, `created_at`)
VALUES
(:method, :chat_id, :inline_message_id, :created_at);
');
$chat_id = $data['chat_id'] ?? null;
$inline_message_id = $data['inline_message_id'] ?? null;
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':inline_message_id', $inline_message_id);
$sth->bindValue(':method', $method);
$sth->bindValue(':created_at', self::getTimestamp());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Bulk update the entries of any table
*
* @param string $table
* @param array $fields_values
* @param array $where_fields_values
*
* @return bool
* @throws TelegramException
*/
public static function update(string $table, array $fields_values, array $where_fields_values): bool
{
if (empty($fields_values) || !self::isDbConnected()) {
return false;
}
try {
// Building parts of query
$tokens = $fields = $where = [];
// Fields with values to update
foreach ($fields_values as $field => $value) {
$token = ':' . count($tokens);
$fields[] = "`{$field}` = {$token}";
$tokens[$token] = $value;
}
// Where conditions
foreach ($where_fields_values as $field => $value) {
$token = ':' . count($tokens);
$where[] = "`{$field}` = {$token}";
$tokens[$token] = $value;
}
$sql = 'UPDATE `' . $table . '` SET ' . implode(', ', $fields);
$sql .= count($where) > 0 ? ' WHERE ' . implode(' AND ', $where) : '';
return self::$pdo->prepare($sql)->execute($tokens);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
}
diff --git a/src/Entities/ChatBoost.php b/src/Entities/ChatBoost.php
new file mode 100644
index 0000000..adfbddb
--- /dev/null
+++ b/src/Entities/ChatBoost.php
@@ -0,0 +1,37 @@
+<?php
+
+/**
+ * This file is part of the TelegramBot package.
+ *
+ * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
+ *
+ * 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\ChatBoostSource\Factory as ChatBoostSourceFactory;
+
+/**
+ * This object contains information about a chat boost.
+ *
+ * @link https://core.telegram.org/bots/api#chatboost
+ *
+ * @method string getBoostId() Unique identifier of the boost
+ * @method int getAddDate() Point in time (Unix timestamp) when the chat was boosted
+ * @method int getExpirationDate() Point in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged
+ * @method ChatBoostSource getSource() Source of the added boost
+ */
+class ChatBoost extends Entity
+{
+ /**
+ * {@inheritdoc}
+ */
+ protected function subEntities(): array
+ {
+ return [
+ 'source' => ChatBoostSourceFactory::class,
+ ];
+ }
+}
diff --git a/src/Entities/ChatBoostRemoved.php b/src/Entities/ChatBoostRemoved.php
new file mode 100644
index 0000000..2b893cc
--- /dev/null
+++ b/src/Entities/ChatBoostRemoved.php
@@ -0,0 +1,38 @@
+<?php
+
+/**
+ * This file is part of the TelegramBot package.
+ *
+ * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
+ *
+ * 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\ChatBoostSource\Factory as ChatBoostSourceFactory;
+
+/**
+ * This object represents a boost removed from a chat.
+ *
+ * @link https://core.telegram.org/bots/api#chatboostremoved
+ *
+ * @method Chat getChat() Chat which was boosted
+ * @method string getBoostId() Unique identifier of the boost
+ * @method int getRemoveDate() Point in time (Unix timestamp) when the boost was removed
+ * @method ChatBoostSource getSource() Source of the removed boost
+ */
+class ChatBoostRemoved extends Entity
+{
+ /**
+ * {@inheritdoc}
+ */
+ protected function subEntities(): array
+ {
+ return [
+ 'chat' => Chat::class,
+ 'source' => ChatBoostSourceFactory::class,
+ ];
+ }
+}
diff --git a/src/Entities/ChatBoostSource/ChatBoostSource.php b/src/Entities/ChatBoostSource/ChatBoostSource.php
new file mode 100644
index 0000000..dae048a
--- /dev/null
+++ b/src/Entities/ChatBoostSource/ChatBoostSource.php
@@ -0,0 +1,16 @@
+<?php
+
+namespace Longman\TelegramBot\Entities\ChatBoostSource;
+
+use Longman\TelegramBot\Entities\User;
+
+/**
+ * Interface ChatBoostSource
+ *
+ * @method string getSource() Source of the boost
+ * @method User getUser() Information about the user
+ */
+interface ChatBoostSource
+{
+ //
+}
diff --git a/src/Entities/ChatBoostSource/ChatBoostSourceGiftCode.php b/src/Entities/ChatBoostSource/ChatBoostSourceGiftCode.php
new file mode 100644
index 0000000..0228f71
--- /dev/null
+++ b/src/Entities/ChatBoostSource/ChatBoostSourceGiftCode.php
@@ -0,0 +1,27 @@
+<?php
+
+namespace Longman\TelegramBot\Entities\ChatBoostSource;
+
+use Longman\TelegramBot\Entities\Entity;
+use Longman\TelegramBot\Entities\User;
+
+/**
+ * The boost was obtained by the creation of Telegram Premium gift codes to boost a chat.
+ *
+ * @link https://core.telegram.org/bots/api#chatboostsourcegiftcode
+ *
+ * @method string getSource() Source of the boost, always “gift_code”
+ * @method User getUser() User for which the gift code was created
+ */
+class ChatBoostSourceGiftCode extends Entity implements ChatBoostSource
+{
+ /**
+ * {@inheritdoc}
+ */
+ protected function subEntities(): array
+ {
+ return [
+ 'user' => User::class,
+ ];
+ }
+}
diff --git a/src/Entities/ChatBoostSource/ChatBoostSourceGiveaway.php b/src/Entities/ChatBoostSource/ChatBoostSourceGiveaway.php
new file mode 100644
index 0000000..7e40548
--- /dev/null
+++ b/src/Entities/ChatBoostSource/ChatBoostSourceGiveaway.php
@@ -0,0 +1,29 @@
+<?php
+
+namespace Longman\TelegramBot\Entities\ChatBoostSource;
+
+use Longman\TelegramBot\Entities\Entity;
+use Longman\TelegramBot\Entities\User;
+
+/**
+ * The boost was obtained by the creation of a Telegram Premium giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription.
+ *
+ * @link https://core.telegram.org/bots/api#chatboostsourcegiveaway
+ *
+ * @method string getSource() Source of the boost, always “giveaway”
+ * @method int getGiveawayMessageId() Identifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet.
+ * @method User getUser() Optional. User that won the prize in the giveaway if any
+ * @method bool getIsUnclaimed() Optional. True, if the giveaway was completed, but there was no user to win the prize
+ */
+class ChatBoostSourceGiveaway extends Entity implements ChatBoostSource
+{
+ /**
+ * {@inheritdoc}
+ */
+ protected function subEntities(): array
+ {
+ return [
+ 'user' => User::class,
+ ];
+ }
+}
diff --git a/src/Entities/ChatBoostSource/ChatBoostSourceNotImplemented.php b/src/Entities/ChatBoostSource/ChatBoostSourceNotImplemented.php
new file mode 100644
index 0000000..e045fcc
--- /dev/null
+++ b/src/Entities/ChatBoostSource/ChatBoostSourceNotImplemented.php
@@ -0,0 +1,15 @@
+<?php
+
+namespace Longman\TelegramBot\Entities\ChatBoostSource;
+
+use Longman\TelegramBot\Entities\Entity;
+use Longman\TelegramBot\Entities\User;
+
+/**
+ * @method string getSource() Source of the boost
+ * @method User getUser() Information about the user
+ */
+class ChatBoostSourceNotImplemented extends Entity implements ChatBoostSource
+{
+ //
+}
diff --git a/src/Entities/ChatBoostSource/ChatBoostSourcePremium.php b/src/Entities/ChatBoostSource/ChatBoostSourcePremium.php
new file mode 100644
index 0000000..5e76eb1
--- /dev/null
+++ b/src/Entities/ChatBoostSource/ChatBoostSourcePremium.php
@@ -0,0 +1,27 @@
+<?php
+
+namespace Longman\TelegramBot\Entities\ChatBoostSource;
+
+use Longman\TelegramBot\Entities\Entity;
+use Longman\TelegramBot\Entities\User;
+
+/**
+ * The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user.
+ *
+ * @link https://core.telegram.org/bots/api#chatboostsourcepremium
+ *
+ * @method string getSource() Source of the boost, always “premium”
+ * @method User getUser() User that boosted the chat
+ */
+class ChatBoostSourcePremium extends Entity implements ChatBoostSource
+{
+ /**
+ * {@inheritdoc}
+ */
+ protected function subEntities(): array
+ {
+ return [
+ 'user' => User::class,
+ ];
+ }
+}
diff --git a/src/Entities/ChatBoostSource/Factory.php b/src/Entities/ChatBoostSource/Factory.php
new file mode 100644
index 0000000..11e5af7
--- /dev/null
+++ b/src/Entities/ChatBoostSource/Factory.php
@@ -0,0 +1,24 @@
+<?php
+
+namespace Longman\TelegramBot\Entities\ChatBoostSource;
+
+use Longman\TelegramBot\Entities\Entity;
+
+class Factory extends \Longman\TelegramBot\Entities\Factory
+{
+ public static function make(array $data, string $bot_username): Entity
+ {
+ $type = [
+ 'premium' => ChatBoostSourcePremium::class,
+ 'gift_code' => ChatBoostSourceGiftCode::class,
+ 'giveaway' => ChatBoostSourceGiveaway::class,
+ ];
+
+ if (!isset($type[$data['source'] ?? ''])) {
+ return new ChatBoostSourceNotImplemented($data, $bot_username);
+ }
+
+ $class = $type[$data['source']];
+ return new $class($data, $bot_username);
+ }
+}
diff --git a/src/Entities/ChatBoostUpdated.php b/src/Entities/ChatBoostUpdated.php
new file mode 100644
index 0000000..5228b95
--- /dev/null
+++ b/src/Entities/ChatBoostUpdated.php
@@ -0,0 +1,34 @@
+<?php
+
+/**
+ * This file is part of the TelegramBot package.
+ *
+ * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Longman\TelegramBot\Entities;
+
+/**
+ * This object represents a boost added to a chat or changed.
+ *
+ * @link https://core.telegram.org/bots/api#chatboostupdated
+ *
+ * @method Chat getChat() Chat which was boosted
+ * @method ChatBoost getBoost() Information about the chat boost
+ */
+class ChatBoostUpdated extends Entity
+{
+ /**
+ * {@inheritdoc}
+ */
+ protected function subEntities(): array
+ {
+ return [
+ 'chat' => Chat::class,
+ 'chat_boost' => ChatBoost::class,
+ ];
+ }
+}
diff --git a/src/Entities/UserChatBoosts.php b/src/Entities/UserChatBoosts.php
new file mode 100644
index 0000000..de45ddb
--- /dev/null
+++ b/src/Entities/UserChatBoosts.php
@@ -0,0 +1,32 @@
+<?php
+
+/**
+ * This file is part of the TelegramBot package.
+ *
+ * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Longman\TelegramBot\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
+ {
+ return [
+ 'boosts' => [ChatBoost::class],
+ ];
+ }
+}
diff --git a/src/Request.php b/src/Request.php
index bf0bd27..4cad3dd 100644
--- a/src/Request.php
+++ b/src/Request.php
@@ -1,1032 +1,1034 @@
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\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<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
* @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 (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/structure.sql b/structure.sql
index b3f4976..ae76698 100644
--- a/structure.sql
+++ b/structure.sql
@@ -1,412 +1,438 @@
CREATE TABLE IF NOT EXISTS `user` (
`id` bigint COMMENT 'Unique identifier for this user or bot',
`is_bot` tinyint(1) DEFAULT 0 COMMENT 'True, if this user is a bot',
`first_name` CHAR(255) NOT NULL DEFAULT '' COMMENT 'User''s or bot''s first name',
`last_name` CHAR(255) DEFAULT NULL COMMENT 'User''s or bot''s last name',
`username` CHAR(191) DEFAULT NULL COMMENT 'User''s or bot''s username',
`language_code` CHAR(10) DEFAULT NULL COMMENT 'IETF language tag of the user''s language',
`is_premium` tinyint(1) DEFAULT 0 COMMENT 'True, if this user is a Telegram Premium user',
`added_to_attachment_menu` tinyint(1) DEFAULT 0 COMMENT 'True, if this user added the bot to the attachment menu',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
`updated_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date update',
PRIMARY KEY (`id`),
KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `chat` (
`id` bigint COMMENT 'Unique identifier for this chat',
`type` ENUM('private', 'group', 'supergroup', 'channel') NOT NULL COMMENT 'Type of chat, can be either private, group, supergroup or channel',
`title` CHAR(255) DEFAULT '' COMMENT 'Title, for supergroups, channels and group chats',
`username` CHAR(255) DEFAULT NULL COMMENT 'Username, for private chats, supergroups and channels if available',
`first_name` CHAR(255) DEFAULT NULL COMMENT 'First name of the other party in a private chat',
`last_name` CHAR(255) DEFAULT NULL COMMENT 'Last name of the other party in a private chat',
`is_forum` TINYINT(1) DEFAULT 0 COMMENT 'True, if the supergroup chat is a forum (has topics enabled)',
`all_members_are_administrators` tinyint(1) DEFAULT 0 COMMENT 'True if a all members of this group are admins',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
`updated_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date update',
`old_id` bigint DEFAULT NULL COMMENT 'Unique chat identifier, this is filled when a group is converted to a supergroup',
PRIMARY KEY (`id`),
KEY `old_id` (`old_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `user_chat` (
`user_id` bigint COMMENT 'Unique user identifier',
`chat_id` bigint COMMENT 'Unique user or chat identifier',
PRIMARY KEY (`user_id`, `chat_id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
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 `inline_query` (
`id` bigint UNSIGNED COMMENT 'Unique identifier for this query',
`user_id` bigint NULL COMMENT 'Unique user identifier',
`location` CHAR(255) NULL DEFAULT NULL COMMENT 'Location of the user',
`query` TEXT NOT NULL COMMENT 'Text of the query',
`offset` CHAR(255) NULL DEFAULT NULL COMMENT 'Offset of the result',
`chat_type` CHAR(255) NULL DEFAULT NULL COMMENT 'Optional. Type of the chat, from which the inline query was sent.',
`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 `chosen_inline_result` (
`id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
`result_id` CHAR(255) NOT NULL DEFAULT '' COMMENT 'The unique identifier for the result that was chosen',
`user_id` bigint NULL COMMENT 'The user that chose the result',
`location` CHAR(255) NULL DEFAULT NULL COMMENT 'Sender location, only for bots that require user location',
`inline_message_id` CHAR(255) NULL DEFAULT NULL COMMENT 'Identifier of the sent inline message',
`query` TEXT NOT NULL COMMENT 'The query that was used to obtain the result',
`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 `message` (
`chat_id` bigint COMMENT 'Unique chat identifier',
`sender_chat_id` bigint COMMENT 'Sender of the message, sent on behalf of a chat',
`id` bigint UNSIGNED COMMENT 'Unique message identifier',
`message_thread_id` bigint(20) DEFAULT NULL COMMENT 'Unique identifier of a message thread to which the message belongs; for supergroups only',
`user_id` bigint NULL COMMENT 'Unique user identifier',
`date` timestamp NULL DEFAULT NULL COMMENT 'Date the message was sent in timestamp format',
`forward_from` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier, sender of the original message',
`forward_from_chat` bigint NULL DEFAULT NULL COMMENT 'Unique chat identifier, chat the original message belongs to',
`forward_from_message_id` bigint NULL DEFAULT NULL COMMENT 'Unique chat identifier of the original message in the channel',
`forward_signature` TEXT NULL DEFAULT NULL COMMENT 'For messages forwarded from channels, signature of the post author if present',
`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',
`forward_date` timestamp NULL DEFAULT NULL COMMENT 'date the original message was sent in timestamp format',
`is_topic_message` tinyint(1) DEFAULT 0 COMMENT 'True, if the message is sent to a forum topic',
`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',
`reply_to_chat` bigint NULL DEFAULT NULL COMMENT 'Unique chat identifier',
`reply_to_message` bigint UNSIGNED DEFAULT NULL COMMENT 'Message that this message is reply to',
`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',
`via_bot` bigint NULL DEFAULT NULL COMMENT 'Optional. Bot through which the message was sent',
`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',
`edit_date` timestamp NULL DEFAULT NULL COMMENT 'Date the message was last edited in Unix time',
`has_protected_content` tinyint(1) DEFAULT 0 COMMENT 'True, if the message can''t be forwarded',
`media_group_id` TEXT COMMENT 'The unique identifier of a media message group this message belongs to',
`author_signature` TEXT COMMENT 'Signature of the post author for messages in channels',
`text` TEXT COMMENT 'For text messages, the actual UTF-8 text of the message max message length 4096 char utf8mb4',
`entities` TEXT COMMENT 'For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text',
`caption_entities` TEXT COMMENT 'For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption',
`audio` TEXT COMMENT 'Audio object. Message is an audio file, information about the file',
`document` TEXT COMMENT 'Document object. Message is a general file, information about the file',
`animation` TEXT COMMENT 'Message is an animation, information about the animation',
`game` TEXT COMMENT 'Game object. Message is a game, information about the game',
`photo` TEXT COMMENT 'Array of PhotoSize objects. Message is a photo, available sizes of the photo',
`sticker` TEXT COMMENT 'Sticker object. Message is a sticker, information about the sticker',
`story` TEXT COMMENT 'Story object. Message is a forwarded story',
`video` TEXT COMMENT 'Video object. Message is a video, information about the video',
`voice` TEXT COMMENT 'Voice Object. Message is a Voice, information about the Voice',
`video_note` TEXT COMMENT 'VoiceNote Object. Message is a Video Note, information about the Video Note',
`caption` TEXT COMMENT 'For message with caption, the actual UTF-8 text of the caption',
`has_media_spoiler` tinyint(1) DEFAULT 0 COMMENT 'True, if the message media is covered by a spoiler animation',
`contact` TEXT COMMENT 'Contact object. Message is a shared contact, information about the contact',
`location` TEXT COMMENT 'Location object. Message is a shared location, information about the location',
`venue` TEXT COMMENT 'Venue object. Message is a Venue, information about the Venue',
`poll` TEXT COMMENT 'Poll object. Message is a native poll, information about the poll',
`dice` TEXT COMMENT 'Message is a dice with random value from 1 to 6',
`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)',
`left_chat_member` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier, a member was removed from the group, information about them (this member may be the bot itself)',
`new_chat_title` CHAR(255) DEFAULT NULL COMMENT 'A chat title was changed to this value',
`new_chat_photo` TEXT COMMENT 'Array of PhotoSize objects. A chat photo was change to this value',
`delete_chat_photo` tinyint(1) DEFAULT 0 COMMENT 'Informs that the chat photo was deleted',
`group_chat_created` tinyint(1) DEFAULT 0 COMMENT 'Informs that the group has been created',
`supergroup_chat_created` tinyint(1) DEFAULT 0 COMMENT 'Informs that the supergroup has been created',
`channel_chat_created` tinyint(1) DEFAULT 0 COMMENT 'Informs that the channel chat has been created',
`message_auto_delete_timer_changed` TEXT COMMENT 'MessageAutoDeleteTimerChanged object. Message is a service message: auto-delete timer settings changed in the chat',
`migrate_to_chat_id` bigint NULL DEFAULT NULL COMMENT 'Migrate to chat identifier. The group has been migrated to a supergroup with the specified identifier',
`migrate_from_chat_id` bigint NULL DEFAULT NULL COMMENT 'Migrate from chat identifier. The supergroup has been migrated from a group with the specified identifier',
`pinned_message` TEXT NULL COMMENT 'Message object. Specified message was pinned',
`invoice` TEXT NULL COMMENT 'Message is an invoice for a payment, information about the invoice',
`successful_payment` TEXT NULL COMMENT 'Message is a service message about a successful payment, information about the payment',
`users_shared` TEXT NULL COMMENT 'Optional. Service message: users were shared with the bot',
`chat_shared` TEXT NULL COMMENT 'Optional. Service message: a chat was shared with the bot',
`connected_website` TEXT NULL COMMENT 'The domain name of the website on which the user has logged in.',
`write_access_allowed` TEXT DEFAULT NULL COMMENT 'Service message: the user allowed the bot added to the attachment menu to write messages',
`passport_data` TEXT NULL COMMENT 'Telegram Passport data',
`proximity_alert_triggered` TEXT NULL COMMENT 'Service message. A user in the chat triggered another user''s proximity alert while sharing Live Location.',
`forum_topic_created` TEXT DEFAULT NULL COMMENT 'Service message: forum topic created',
`forum_topic_edited` TEXT DEFAULT NULL COMMENT 'Service message: forum topic edited',
`forum_topic_closed` TEXT DEFAULT NULL COMMENT 'Service message: forum topic closed',
`forum_topic_reopened` TEXT DEFAULT NULL COMMENT 'Service message: forum topic reopened',
`general_forum_topic_hidden` TEXT DEFAULT NULL COMMENT 'Service message: the General forum topic hidden',
`general_forum_topic_unhidden` TEXT DEFAULT NULL COMMENT 'Service message: the General forum topic unhidden',
`video_chat_scheduled` TEXT COMMENT 'Service message: video chat scheduled',
`video_chat_started` TEXT COMMENT 'Service message: video chat started',
`video_chat_ended` TEXT COMMENT 'Service message: video chat ended',
`video_chat_participants_invited` TEXT COMMENT 'Service message: new participants invited to a video chat',
`web_app_data` TEXT COMMENT 'Service message: data sent by a Web App',
`reply_markup` TEXT NULL COMMENT 'Inline keyboard attached to the message',
PRIMARY KEY (`chat_id`, `id`),
KEY `user_id` (`user_id`),
KEY `forward_from` (`forward_from`),
KEY `forward_from_chat` (`forward_from_chat`),
KEY `reply_to_chat` (`reply_to_chat`),
KEY `reply_to_message` (`reply_to_message`),
KEY `via_bot` (`via_bot`),
KEY `left_chat_member` (`left_chat_member`),
KEY `migrate_from_chat_id` (`migrate_from_chat_id`),
KEY `migrate_to_chat_id` (`migrate_to_chat_id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`),
FOREIGN KEY (`forward_from`) REFERENCES `user` (`id`),
FOREIGN KEY (`forward_from_chat`) REFERENCES `chat` (`id`),
FOREIGN KEY (`reply_to_chat`, `reply_to_message`) REFERENCES `message` (`chat_id`, `id`),
FOREIGN KEY (`via_bot`) REFERENCES `user` (`id`),
FOREIGN KEY (`left_chat_member`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `edited_message` (
`id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
`chat_id` bigint COMMENT 'Unique chat identifier',
`message_id` bigint UNSIGNED COMMENT 'Unique message identifier',
`user_id` bigint NULL COMMENT 'Unique user identifier',
`edit_date` timestamp NULL DEFAULT NULL COMMENT 'Date the message was edited in timestamp format',
`text` TEXT COMMENT 'For text messages, the actual UTF-8 text of the message max message length 4096 char utf8',
`entities` TEXT COMMENT 'For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text',
`caption` TEXT COMMENT 'For message with caption, the actual UTF-8 text of the caption',
PRIMARY KEY (`id`),
KEY `chat_id` (`chat_id`),
KEY `message_id` (`message_id`),
KEY `user_id` (`user_id`),
FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`),
FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `callback_query` (
`id` bigint UNSIGNED COMMENT 'Unique identifier for this query',
`user_id` bigint NULL COMMENT 'Unique user identifier',
`chat_id` bigint NULL COMMENT 'Unique chat identifier',
`message_id` bigint UNSIGNED COMMENT 'Unique message identifier',
`inline_message_id` CHAR(255) NULL DEFAULT NULL COMMENT 'Identifier of the message sent via the bot in inline mode, that originated the query',
`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',
`data` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Data associated with the callback button',
`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',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `chat_id` (`chat_id`),
KEY `message_id` (`message_id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
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` text NOT NULL COMMENT 'Poll question',
`options` text NOT NULL COMMENT 'List of poll options',
`total_voter_count` int UNSIGNED COMMENT 'Total number of users that voted in the poll',
`is_closed` tinyint(1) DEFAULT 0 COMMENT 'True, if the poll is closed',
`is_anonymous` tinyint(1) DEFAULT 1 COMMENT 'True, if the poll is anonymous',
`type` char(255) COMMENT 'Poll type, currently can be “regular” or “quiz”',
`allows_multiple_answers` tinyint(1) DEFAULT 0 COMMENT 'True, if the poll allows multiple answers',
`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.',
`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',
`explanation_entities` text DEFAULT NULL COMMENT 'Special entities like usernames, URLs, bot commands, etc. that appear in the explanation',
`open_period` int UNSIGNED DEFAULT NULL COMMENT 'Amount of time in seconds the poll will be active after creation',
`close_date` timestamp NULL DEFAULT NULL COMMENT 'Point in time (Unix timestamp) when the poll will be automatically closed',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
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`, `user_id`),
FOREIGN KEY (`poll_id`) REFERENCES `poll` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
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;
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;
+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 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;
+
CREATE TABLE IF NOT EXISTS `telegram_update` (
`id` bigint UNSIGNED COMMENT 'Update''s unique identifier',
`chat_id` bigint NULL DEFAULT NULL COMMENT 'Unique chat identifier',
`message_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming message of any kind - text, photo, sticker, etc.',
`edited_message_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New version of a message that is known to the bot and was edited',
`channel_post_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming channel post of any kind - text, photo, sticker, etc.',
`edited_channel_post_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New version of a channel post that is known to the bot and was edited',
`message_reaction_id` bigint UNSIGNED DEFAULT NULL COMMENT 'A reaction to a message was changed by a user',
`message_reaction_count_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Reactions to a message with anonymous reactions were changed',
`inline_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming inline query',
`chosen_inline_result_id` bigint UNSIGNED DEFAULT NULL COMMENT 'The result of an inline query that was chosen by a user and sent to their chat partner',
`callback_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming callback query',
`shipping_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming shipping query. Only for invoices with flexible price',
`pre_checkout_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New incoming pre-checkout query. Contains full information about checkout',
`poll_id` bigint UNSIGNED DEFAULT NULL COMMENT 'New poll state. Bots receive only updates about polls, which are sent or stopped by the bot',
`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.',
`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.',
`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.',
`chat_join_request_id` BIGINT UNSIGNED NULL COMMENT 'A request to join the chat has been sent',
PRIMARY KEY (`id`),
KEY `message_id` (`message_id`),
KEY `chat_message_id` (`chat_id`, `message_id`),
KEY `edited_message_id` (`edited_message_id`),
KEY `channel_post_id` (`channel_post_id`),
KEY `edited_channel_post_id` (`edited_channel_post_id`),
KEY `inline_query_id` (`inline_query_id`),
KEY `chosen_inline_result_id` (`chosen_inline_result_id`),
KEY `callback_query_id` (`callback_query_id`),
KEY `shipping_query_id` (`shipping_query_id`),
KEY `pre_checkout_query_id` (`pre_checkout_query_id`),
KEY `poll_id` (`poll_id`),
KEY `poll_answer_poll_id` (`poll_answer_poll_id`),
KEY `my_chat_member_updated_id` (`my_chat_member_updated_id`),
KEY `chat_member_updated_id` (`chat_member_updated_id`),
KEY `chat_join_request_id` (`chat_join_request_id`),
FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `id`),
FOREIGN KEY (`edited_message_id`) REFERENCES `edited_message` (`id`),
FOREIGN KEY (`chat_id`, `channel_post_id`) REFERENCES `message` (`chat_id`, `id`),
FOREIGN KEY (`edited_channel_post_id`) REFERENCES `edited_message` (`id`),
FOREIGN KEY (`inline_query_id`) REFERENCES `inline_query` (`id`),
FOREIGN KEY (`chosen_inline_result_id`) REFERENCES `chosen_inline_result` (`id`),
FOREIGN KEY (`callback_query_id`) REFERENCES `callback_query` (`id`),
FOREIGN KEY (`shipping_query_id`) REFERENCES `shipping_query` (`id`),
FOREIGN KEY (`pre_checkout_query_id`) REFERENCES `pre_checkout_query` (`id`),
FOREIGN KEY (`poll_id`) REFERENCES `poll` (`id`),
FOREIGN KEY (`poll_answer_poll_id`) REFERENCES `poll_answer` (`poll_id`),
FOREIGN KEY (`my_chat_member_updated_id`) REFERENCES `chat_member_updated` (`id`),
FOREIGN KEY (`chat_member_updated_id`) REFERENCES `chat_member_updated` (`id`),
FOREIGN KEY (`chat_join_request_id`) REFERENCES `chat_join_request` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `conversation` (
`id` bigint(20) unsigned AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
`user_id` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier',
`chat_id` bigint NULL DEFAULT NULL COMMENT 'Unique user or chat identifier',
`status` ENUM('active', 'cancelled', 'stopped') NOT NULL DEFAULT 'active' COMMENT 'Conversation state',
`command` varchar(160) DEFAULT '' COMMENT 'Default command to execute',
`notes` text DEFAULT NULL COMMENT 'Data stored from command',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
`updated_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date update',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `chat_id` (`chat_id`),
KEY `status` (`status`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `request_limiter` (
`id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
`chat_id` char(255) NULL DEFAULT NULL COMMENT 'Unique chat identifier',
`inline_message_id` char(255) NULL DEFAULT NULL COMMENT 'Identifier of the sent inline message',
`method` char(255) DEFAULT NULL COMMENT 'Request method',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
diff --git a/utils/db-schema-update/0.82.0-unreleased.sql b/utils/db-schema-update/0.82.0-unreleased.sql
index 81dde11..e58df27 100644
--- a/utils/db-schema-update/0.82.0-unreleased.sql
+++ b/utils/db-schema-update/0.82.0-unreleased.sql
@@ -1,41 +1,67 @@
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 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`,
RENAME COLUMN `user_shared` TO `users_shared`;
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`;

File Metadata

Mime Type
text/x-diff
Expires
Sun, Nov 15, 6:46 AM (37 m, 46 s)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
148791
Default Alt Text
(176 KB)

Event Timeline