Unverified Commit 488f68d7 authored by Armando Lüscher's avatar Armando Lüscher Committed by GitHub

Merge pull request #948 from noplanman/944-bot_api_4.2_polls

API 4.2 - Polls
parents acde1326 50d732e6
......@@ -4,7 +4,12 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p
Exclamation symbols (:exclamation:) note something of importance e.g. breaking changes. Click them to learn more.
## [Unreleased]
:exclamation: After updating to this version, you will need to execute the [SQL migration script][unreleased-sql-migration] on your database.
### Added
- Bot API 4.2 (Polls).
- `getIsMember()` method to `ChatMember` entity.
- `getForwardSenderName()` method to `Message` entity.
- `forward_sender_name` (and forgotten `forward_signature`) DB fields.
### Changed
### Deprecated
### Removed
......@@ -249,6 +254,7 @@ Exclamation symbols (:exclamation:) note something of importance e.g. breaking c
### Deprecated
- Move `hideKeyboard` to `removeKeyboard`.
[unreleased-sql-migration]: https://github.com/php-telegram-bot/core/tree/develop/utils/db-schema-update/unreleased.sql
[0.55.0-sql-migration]: https://github.com/php-telegram-bot/core/tree/master/utils/db-schema-update/0.54.1-0.55.0.sql
[0.55.0-bc-move-animation-out-of-games-namespace]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#move-animation-out-of-games-namespace
[0.54.0-sql-migration]: https://github.com/php-telegram-bot/core/tree/master/utils/db-schema-update/0.53.0-0.54.0.sql
......
......@@ -17,6 +17,7 @@ use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Entities\ChosenInlineResult;
use Longman\TelegramBot\Entities\InlineQuery;
use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\Poll;
use Longman\TelegramBot\Entities\ReplyToMessage;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Entities\User;
......@@ -141,6 +142,7 @@ class DB
'edited_message',
'inline_query',
'message',
'poll',
'request_limiter',
'telegram_update',
'user',
......@@ -309,6 +311,7 @@ class DB
* @param string $chosen_inline_result_id
* @param string $callback_query_id
* @param string $edited_message_id
* @param string $poll_id
*
* @return bool If the insert was successful
* @throws TelegramException
......@@ -320,10 +323,11 @@ class DB
$inline_query_id = null,
$chosen_inline_result_id = null,
$callback_query_id = null,
$edited_message_id = null
$edited_message_id = null,
$poll_id = null
) {
if ($message_id === null && $inline_query_id === null && $chosen_inline_result_id === null && $callback_query_id === null && $edited_message_id === null) {
throw new TelegramException('message_id, inline_query_id, chosen_inline_result_id, callback_query_id, edited_message_id are all null');
if ($message_id === null && $inline_query_id === null && $chosen_inline_result_id === null && $callback_query_id === null && $edited_message_id === null && $poll_id === null) {
throw new TelegramException('message_id, inline_query_id, chosen_inline_result_id, callback_query_id, edited_message_id, poll_id are all null');
}
if (!self::isDbConnected()) {
......@@ -333,9 +337,9 @@ class DB
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_TELEGRAM_UPDATE . '`
(`id`, `chat_id`, `message_id`, `inline_query_id`, `chosen_inline_result_id`, `callback_query_id`, `edited_message_id`)
(`id`, `chat_id`, `message_id`, `inline_query_id`, `chosen_inline_result_id`, `callback_query_id`, `edited_message_id`, `poll_id`)
VALUES
(:id, :chat_id, :message_id, :inline_query_id, :chosen_inline_result_id, :callback_query_id, :edited_message_id)
(:id, :chat_id, :message_id, :inline_query_id, :chosen_inline_result_id, :callback_query_id, :edited_message_id, :poll_id)
');
$sth->bindValue(':id', $id);
......@@ -345,6 +349,7 @@ class DB
$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(':poll_id', $poll_id);
return $sth->execute();
} catch (PDOException $e) {
......@@ -599,6 +604,23 @@ class DB
$callback_query_id
);
}
} elseif ($update_type === 'poll') {
$poll = $update->getPoll();
if (self::insertPollRequest($poll)) {
$poll_id = $poll->getId();
return self::insertTelegramUpdate(
$update_id,
null,
null,
null,
null,
null,
null,
$poll_id
);
}
}
return false;
......@@ -759,6 +781,43 @@ class DB
}
}
/**
* Insert poll request into database
*
* @param Poll $poll
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertPollRequest(Poll $poll)
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_POLL . '`
(`id`, `question`, `options`, `is_closed`, `created_at`)
VALUES
(:id, :question, :options, :is_closed, :created_at)
ON DUPLICATE KEY UPDATE
`options` = VALUES(`options`),
`is_closed` = VALUES(`is_closed`)
');
$sth->bindValue(':id', $poll->getId());
$sth->bindValue(':question', $poll->getQuestion());
$sth->bindValue(':options', self::entitiesArrayToJson($poll->getOptions(), null));
$sth->bindValue(':is_closed', $poll->getIsClosed());
$sth->bindValue(':created_at', self::getTimestamp());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert Message request in db
*
......@@ -828,17 +887,19 @@ class DB
INSERT IGNORE INTO `' . TB_MESSAGE . '`
(
`id`, `user_id`, `chat_id`, `date`, `forward_from`, `forward_from_chat`, `forward_from_message_id`,
`forward_date`, `reply_to_chat`, `reply_to_message`, `media_group_id`, `text`, `entities`, `audio`, `document`,
`forward_signature`, `forward_sender_name`, `forward_date`,
`reply_to_chat`, `reply_to_message`, `media_group_id`, `text`, `entities`, `audio`, `document`,
`animation`, `game`, `photo`, `sticker`, `video`, `voice`, `video_note`, `caption`, `contact`,
`location`, `venue`, `new_chat_members`, `left_chat_member`,
`location`, `venue`, `poll`, `new_chat_members`, `left_chat_member`,
`new_chat_title`,`new_chat_photo`, `delete_chat_photo`, `group_chat_created`,
`supergroup_chat_created`, `channel_chat_created`,
`migrate_from_chat_id`, `migrate_to_chat_id`, `pinned_message`, `connected_website`, `passport_data`
) VALUES (
:message_id, :user_id, :chat_id, :date, :forward_from, :forward_from_chat, :forward_from_message_id,
:forward_date, :reply_to_chat, :reply_to_message, :media_group_id, :text, :entities, :audio, :document,
:forward_signature, :forward_sender_name, :forward_date,
:reply_to_chat, :reply_to_message, :media_group_id, :text, :entities, :audio, :document,
:animation, :game, :photo, :sticker, :video, :voice, :video_note, :caption, :contact,
:location, :venue, :new_chat_members, :left_chat_member,
:location, :venue, :poll, :new_chat_members, :left_chat_member,
:new_chat_title, :new_chat_photo, :delete_chat_photo, :group_chat_created,
:supergroup_chat_created, :channel_chat_created,
:migrate_from_chat_id, :migrate_to_chat_id, :pinned_message, :connected_website, :passport_data
......@@ -867,6 +928,8 @@ class DB
$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);
$reply_to_chat_id = null;
......@@ -892,6 +955,7 @@ class DB
$sth->bindValue(':contact', $message->getContact());
$sth->bindValue(':location', $message->getLocation());
$sth->bindValue(':venue', $message->getVenue());
$sth->bindValue(':poll', $message->getPoll());
$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());
......
......@@ -27,6 +27,7 @@ namespace Longman\TelegramBot\Entities;
* @method bool getCanRestrictMembers() Optional. Administrators only. True, if the administrator can restrict, ban or unban chat members
* @method bool getCanPinMessages() Optional. Administrators only. True, if the administrator can pin messages, supergroups only
* @method bool getCanPromoteMembers() Optional. Administrators only. True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by the user)
* @method bool getIsMember() Optional. Restricted only. True, if the user is a member of the chat at the moment of the request
* @method bool getCanSendMessages() Optional. Restricted only. True, if the user can send text messages, contacts, locations and venues
* @method bool getCanSendMediaMessages() Optional. Restricted only. True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages
* @method bool getCanSendOtherMessages() Optional. Restricted only. True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages
......
......@@ -28,6 +28,7 @@ use Longman\TelegramBot\Entities\TelegramPassport\PassportData;
* @method Chat getForwardFromChat() Optional. For messages forwarded from a channel, information about the original channel
* @method int getForwardFromMessageId() Optional. For forwarded channel posts, identifier of the original message in the channel
* @method string getForwardSignature() Optional. For messages forwarded from channels, signature of the post author if present
* @method string getForwardSenderName() Optional. Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages
* @method int getForwardDate() Optional. For forwarded messages, date the original message was sent in Unix time
* @method Message getReplyToMessage() Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
* @method int getEditDate() Optional. Date the message was last edited in Unix time
......@@ -45,6 +46,7 @@ use Longman\TelegramBot\Entities\TelegramPassport\PassportData;
* @method Contact getContact() Optional. Message is a shared contact, information about the contact
* @method Location getLocation() Optional. Message is a shared location, information about the location
* @method Venue getVenue() Optional. Message is a venue, information about the venue
* @method Poll getPoll() Optional. Message is a native poll, information about the poll
* @method User getLeftChatMember() Optional. A member was removed from the group, information about them (this member may be the bot itself)
* @method string getNewChatTitle() Optional. A chat title was changed to this value
* @method bool getDeleteChatPhoto() Optional. Service message: the chat photo was deleted
......@@ -86,6 +88,7 @@ class Message extends Entity
'contact' => Contact::class,
'location' => Location::class,
'venue' => Venue::class,
'poll' => Poll::class,
'new_chat_members' => User::class,
'left_chat_member' => User::class,
'new_chat_photo' => PhotoSize::class,
......@@ -295,6 +298,7 @@ class Message extends Entity
'contact',
'location',
'venue',
'poll',
'new_chat_members',
'left_chat_member',
'new_chat_title',
......
<?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;
/**
* Class Poll
*
* This entity contains information about a poll.
*
* @link https://core.telegram.org/bots/api#poll
*
* @method string getId() Unique poll identifier
* @method string getQuestion() Poll question, 1-255 characters
* @method bool getIsClosed() True, if the poll is closed
*/
class Poll extends Entity
{
/**
* {@inheritdoc}
*/
protected function subEntities()
{
return [
'options' => PollOption::class,
];
}
/**
* List of poll options
*
* This method overrides the default getOptions method
* and returns a nice array of PollOption objects.
*
* @return null|PollOption[]
*/
public function getOptions()
{
$pretty_array = $this->makePrettyObjectArray(PollOption::class, 'options');
return empty($pretty_array) ? null : $pretty_array;
}
}
<?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;
/**
* Class PollOption
*
* This entity contains information about one answer option in a poll.
*
* @link https://core.telegram.org/bots/api#polloption
*
* @method string getText() Option text, 1-100 characters
* @method int getVoterCount() Number of users that voted for this option
*/
class PollOption extends Entity
{
}
......@@ -28,6 +28,7 @@ use Longman\TelegramBot\Entities\Payments\ShippingQuery;
* @method CallbackQuery getCallbackQuery() Optional. New incoming callback query
* @method ShippingQuery getShippingQuery() Optional. New incoming shipping query. Only for invoices with flexible price
* @method PreCheckoutQuery getPreCheckoutQuery() Optional. New incoming pre-checkout query. Contains full information about checkout
* @method Poll getPoll() Optional. New poll state. Bots receive only updates about polls, which are sent or stopped by the bot
*/
class Update extends Entity
{
......@@ -46,6 +47,7 @@ class Update extends Entity
'callback_query' => CallbackQuery::class,
'shipping_query' => ShippingQuery::class,
'pre_checkout_query' => PreCheckoutQuery::class,
'poll' => Poll::class,
];
}
......@@ -66,6 +68,7 @@ class Update extends Entity
'callback_query',
'shipping_query',
'pre_checkout_query',
'poll',
];
foreach ($types as $type) {
if ($this->getProperty($type)) {
......
......@@ -42,6 +42,7 @@ use Longman\TelegramBot\Exception\TelegramException;
* @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 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 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.
......@@ -69,6 +70,7 @@ use Longman\TelegramBot\Exception\TelegramException;
* @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 getStickerSet(array $data) Use this method to get a sticker set. On success, a StickerSet object is returned.
* @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.
......@@ -166,6 +168,7 @@ class Request
'stopMessageLiveLocation',
'sendVenue',
'sendContact',
'sendPoll',
'sendChatAction',
'getUserProfilePhotos',
'getFile',
......@@ -193,6 +196,7 @@ class Request
'editMessageCaption',
'editMessageMedia',
'editMessageReplyMarkup',
'stopPoll',
'deleteMessage',
'getStickerSet',
'uploadStickerFile',
......@@ -807,6 +811,7 @@ class Request
'stopMessageLiveLocation',
'sendVenue',
'sendContact',
'sendPoll',
'sendInvoice',
'sendGame',
'setGameScore',
......@@ -814,6 +819,7 @@ class Request
'editMessageCaption',
'editMessageMedia',
'editMessageReplyMarkup',
'stopPoll',
'setChatTitle',
'setChatDescription',
'setChatStickerSet',
......
......@@ -65,6 +65,16 @@ CREATE TABLE IF NOT EXISTS `chosen_inline_result` (
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `poll` (
`id` bigint UNSIGNED COMMENT 'Unique poll identifier',
`question` char(255) NOT NULL COMMENT 'Poll question',
`options` text NOT NULL COMMENT 'List of poll options',
`is_closed` tinyint(1) DEFAULT 0 COMMENT 'True, if the poll is closed',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `message` (
`chat_id` bigint COMMENT 'Unique chat identifier',
`id` bigint UNSIGNED COMMENT 'Unique message identifier',
......@@ -73,6 +83,8 @@ CREATE TABLE IF NOT EXISTS `message` (
`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',
`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',
......@@ -91,6 +103,7 @@ CREATE TABLE IF NOT EXISTS `message` (
`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',
`caption` TEXT COMMENT 'For message with caption, the actual UTF-8 text of the caption',
`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)',
......
ALTER TABLE `message` ADD COLUMN `forward_signature` TEXT NULL DEFAULT NULL COMMENT 'For messages forwarded from channels, signature of the post author if present' AFTER `forward_from_message_id`;
ALTER TABLE `message` ADD COLUMN `forward_sender_name` TEXT NULL DEFAULT NULL COMMENT 'Sender''s name for messages forwarded from users who disallow adding a link to their account in forwarded messages' AFTER `forward_signature`;
ALTER TABLE `message` ADD COLUMN `poll` TEXT COMMENT 'Poll object. Message is a native poll, information about the poll' AFTER `venue`;
CREATE TABLE IF NOT EXISTS `poll` (
`id` bigint UNSIGNED COMMENT 'Unique poll identifier',
`question` char(255) NOT NULL COMMENT 'Poll question',
`options` text NOT NULL COMMENT 'List of poll options',
`is_closed` tinyint(1) DEFAULT 0 COMMENT 'True, if the poll is closed',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment