From 316ae207e8c7faa2a8aa803ba0f989a9c65db9ed Mon Sep 17 00:00:00 2001 From: Farshad Nematdoust Date: Mon, 26 Jun 2017 20:59:58 +0430 Subject: [PATCH 01/43] typo fixed --- Commands/SurveyCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Commands/SurveyCommand.php b/Commands/SurveyCommand.php index d4403ef..90f2ad8 100644 --- a/Commands/SurveyCommand.php +++ b/Commands/SurveyCommand.php @@ -18,7 +18,7 @@ use Longman\TelegramBot\Request; /** - * User "/survery" command + * User "/survey" command */ class SurveyCommand extends UserCommand { From 8b7a05f44dbcde2224171708b0211333a4f851c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Sat, 1 Jul 2017 20:14:59 +0200 Subject: [PATCH 02/43] Update help command to v1.2.0 --- Commands/HelpCommand.php | 124 +++++++++++++++++++++++---------------- 1 file changed, 72 insertions(+), 52 deletions(-) diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index 5552c07..71c232e 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -37,72 +37,92 @@ class HelpCommand extends UserCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.2.0'; /** - * Command execute method - * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @inheritdoc */ public function execute() { - $message = $this->getMessage(); - $chat_id = $message->getChat()->getId(); - $command = trim($message->getText(true)); - - //Only get enabled Admin and User commands - /** @var Command[] $command_objs */ - $command_objs = array_filter($this->telegram->getCommandsList(), function ($command_obj) { - /** @var Command $command_obj */ - return !$command_obj->isSystemCommand() && $command_obj->isEnabled(); - }); + $message = $this->getMessage(); + $chat_id = $message->getFrom()->getId(); + $command_str = trim($message->getText(true)); - //If no command parameter is passed, show the list - if ($command === '') { - $text = sprintf( - '%s v. %s' . PHP_EOL . PHP_EOL . 'Commands List:' . PHP_EOL, - $this->telegram->getBotUsername(), - $this->telegram->getVersion() - ); + $data = [ + 'chat_id' => $chat_id, + 'parse_mode' => 'markdown', + ]; - foreach ($command_objs as $command) { - if (!$command->showInHelp()) { - continue; - } + list($all_commands, $user_commands, $admin_commands) = $this->getUserAdminCommands(); - $text .= sprintf( - '/%s - %s' . PHP_EOL, - $command->getName(), - $command->getDescription() - ); + // If no command parameter is passed, show the list. + if ($command_str === '') { + $data['text'] = '*Commands List*:' . PHP_EOL; + foreach ($user_commands as $user_command) { + $data['text'] .= '/' . $user_command->getName() . ' - ' . $user_command->getDescription() . PHP_EOL; } - $text .= PHP_EOL . 'For exact command help type: /help '; - } else { - $command = str_replace('/', '', $command); - if (isset($command_objs[$command])) { - /** @var Command $command_obj */ - $command_obj = $command_objs[$command]; - $text = sprintf( - 'Command: %s v%s' . PHP_EOL . - 'Description: %s' . PHP_EOL . - 'Usage: %s', - $command_obj->getName(), - $command_obj->getVersion(), - $command_obj->getDescription(), - $command_obj->getUsage() - ); - } else { - $text = 'No help available: Command /' . $command . ' not found'; + if (count($admin_commands) > 0) { + $data['text'] .= PHP_EOL . '*Admin Commands List*:' . PHP_EOL; + foreach ($admin_commands as $admin_command) { + $data['text'] .= '/' . $admin_command->getName() . ' - ' . $admin_command->getDescription() . PHP_EOL; + } } + + $data['text'] .= PHP_EOL . 'For exact command help type: /help '; + + return Request::sendMessage($data); } - $data = [ - 'chat_id' => $chat_id, - 'text' => $text, - ]; + $command_str = str_replace('/', '', $command_str); + if (isset($all_commands[$command_str])) { + $command = $all_commands[$command_str]; + $data['text'] = sprintf( + 'Command: %s (v%s)' . PHP_EOL . + 'Description: %s' . PHP_EOL . + 'Usage: %s', + $command->getName(), + $command->getVersion(), + $command->getDescription(), + $command->getUsage() + ); + + return Request::sendMessage($data); + } + + $data['text'] = 'No help available: Command /' . $command_str . ' not found'; return Request::sendMessage($data); } + + /** + * Get all available User and Admin commands to display in the help list. + * + * @return Command[][] + */ + protected function getUserAdminCommands() + { + // Only get enabled Admin and User commands that are allowed to be shown. + /** @var Command[] $commands */ + $commands = array_filter($this->telegram->getCommandsList(), function ($command) { + /** @var Command $command */ + return !$command->isSystemCommand() && $command->showInHelp() && $command->isEnabled(); + }); + + $user_commands = array_filter($commands, function ($command) { + /** @var Command $command */ + return $command->isUserCommand(); + }); + + $admin_commands = array_filter($commands, function ($command) { + /** @var Command $command */ + return $command->isAdminCommand(); + }); + + ksort($commands); + ksort($user_commands); + ksort($admin_commands); + + return [$commands, $user_commands, $admin_commands]; + } } From 4c64c25b9a61d1102866604952b7e78ebaf7d8da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Sun, 6 Aug 2017 12:54:58 +0200 Subject: [PATCH 03/43] Update example commands with a small description and code fixtures to be compatible with 0.47.1 of the core library. --- Commands/CallbackqueryCommand.php | 9 ++-- Commands/CancelCommand.php | 14 +++---- Commands/ChannelchatcreatedCommand.php | 4 +- Commands/ChannelpostCommand.php | 4 +- Commands/ChoseninlineresultCommand.php | 9 ++-- Commands/DateCommand.php | 17 ++++---- Commands/DeletechatphotoCommand.php | 4 +- Commands/EchoCommand.php | 2 + Commands/EditedchannelpostCommand.php | 4 +- Commands/EditedmessageCommand.php | 7 ++-- Commands/EditmessageCommand.php | 17 +++++++- Commands/ForcereplyCommand.php | 4 +- Commands/GenericCommand.php | 6 ++- Commands/GenericmessageCommand.php | 4 +- Commands/GroupchatcreatedCommand.php | 4 +- Commands/HelpCommand.php | 2 + Commands/HidekeyboardCommand.php | 2 + Commands/ImageCommand.php | 42 ++++++++++++++----- Commands/InlinekeyboardCommand.php | 2 + Commands/InlinequeryCommand.php | 7 ++-- Commands/KeyboardCommand.php | 2 + Commands/LeftchatmemberCommand.php | 4 +- Commands/MarkdownCommand.php | 2 + Commands/MigratefromchatidCommand.php | 4 +- Commands/MigratetochatidCommand.php | 4 +- ...rCommand.php => NewchatmembersCommand.php} | 19 +++++---- Commands/NewchatphotoCommand.php | 4 +- Commands/NewchattitleCommand.php | 4 +- Commands/PinnedmessageCommand.php | 4 +- Commands/ShortenerCommand.php | 2 + Commands/SlapCommand.php | 2 + Commands/StartCommand.php | 7 ++++ Commands/SupergroupchatcreatedCommand.php | 4 +- Commands/SurveyCommand.php | 7 ++++ Commands/WeatherCommand.php | 3 ++ Commands/WhoamiCommand.php | 7 ++++ 36 files changed, 179 insertions(+), 64 deletions(-) rename Commands/{NewchatmemberCommand.php => NewchatmembersCommand.php} (69%) diff --git a/Commands/CallbackqueryCommand.php b/Commands/CallbackqueryCommand.php index 0afbcae..0b3c768 100644 --- a/Commands/CallbackqueryCommand.php +++ b/Commands/CallbackqueryCommand.php @@ -15,6 +15,10 @@ /** * Callback query command + * + * This command handles all callback queries sent via inline keyboard buttons. + * + * @see InlinekeyboardCommand.php */ class CallbackqueryCommand extends SystemCommand { @@ -31,7 +35,7 @@ class CallbackqueryCommand extends SystemCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.1.1'; /** * Command execute method @@ -41,8 +45,7 @@ class CallbackqueryCommand extends SystemCommand */ public function execute() { - $update = $this->getUpdate(); - $callback_query = $update->getCallbackQuery(); + $callback_query = $this->getCallbackQuery(); $callback_query_id = $callback_query->getId(); $callback_data = $callback_query->getData(); diff --git a/Commands/CancelCommand.php b/Commands/CancelCommand.php index efd9ad4..468f081 100644 --- a/Commands/CancelCommand.php +++ b/Commands/CancelCommand.php @@ -42,7 +42,7 @@ class CancelCommand extends UserCommand /** * @var string */ - protected $version = '0.2.0'; + protected $version = '0.2.1'; /** * @var bool @@ -83,13 +83,11 @@ public function execute() */ private function removeKeyboard($text) { - return Request::sendMessage( - [ - 'reply_markup' => Keyboard::remove(['selective' => true]), - 'chat_id' => $this->getMessage()->getChat()->getId(), - 'text' => $text, - ] - ); + return Request::sendMessage([ + 'reply_markup' => Keyboard::remove(['selective' => true]), + 'chat_id' => $this->getMessage()->getChat()->getId(), + 'text' => $text, + ]); } /** diff --git a/Commands/ChannelchatcreatedCommand.php b/Commands/ChannelchatcreatedCommand.php index ea954a1..8c07884 100644 --- a/Commands/ChannelchatcreatedCommand.php +++ b/Commands/ChannelchatcreatedCommand.php @@ -14,13 +14,15 @@ /** * Channel chat created command + * + * Gets executed when a new channel gets created. */ class ChannelchatcreatedCommand extends SystemCommand { /** * @var string */ - protected $name = 'Channelchatcreated'; + protected $name = 'channelchatcreated'; /** * @var string diff --git a/Commands/ChannelpostCommand.php b/Commands/ChannelpostCommand.php index b76f2c9..10ed436 100644 --- a/Commands/ChannelpostCommand.php +++ b/Commands/ChannelpostCommand.php @@ -14,13 +14,15 @@ /** * Channel post command + * + * Gets executed when a new post is created in a channel. */ class ChannelpostCommand extends SystemCommand { /** * @var string */ - protected $name = 'Channelpost'; + protected $name = 'channelpost'; /** * @var string diff --git a/Commands/ChoseninlineresultCommand.php b/Commands/ChoseninlineresultCommand.php index 16eef59..b1d5cdf 100644 --- a/Commands/ChoseninlineresultCommand.php +++ b/Commands/ChoseninlineresultCommand.php @@ -14,6 +14,8 @@ /** * Chosen inline result command + * + * Gets executed when an item from an inline query is selected. */ class ChoseninlineresultCommand extends SystemCommand { @@ -30,7 +32,7 @@ class ChoseninlineresultCommand extends SystemCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.1.1'; /** * Command execute method @@ -41,9 +43,8 @@ class ChoseninlineresultCommand extends SystemCommand public function execute() { //Information about chosen result is returned - //$update = $this->getUpdate(); - //$inline_query = $update->getChosenInlineResult(); - //$query = $inline_query->getQuery(); + //$inline_query = $this->getChosenInlineResult(); + //$query = $inline_query->getQuery(); return parent::execute(); } diff --git a/Commands/DateCommand.php b/Commands/DateCommand.php index db237da..31d5e49 100644 --- a/Commands/DateCommand.php +++ b/Commands/DateCommand.php @@ -10,8 +10,6 @@ namespace Longman\TelegramBot\Commands\UserCommands; -use DateTime; -use DateTimeZone; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Longman\TelegramBot\Commands\UserCommand; @@ -20,6 +18,11 @@ /** * User "/date" command + * + * Shows the date and time of the location passed as the parameter. + * + * A Google API key is required for this command, and it can be set in your hook file: + * $telegram->setCommandConfig('date', ['google_api_key' => 'your_api_key']); */ class DateCommand extends UserCommand { @@ -41,7 +44,7 @@ class DateCommand extends UserCommand /** * @var string */ - protected $version = '1.4.0'; + protected $version = '1.4.1'; /** * Guzzle Client object @@ -72,7 +75,7 @@ class DateCommand extends UserCommand private $date_format = 'd-m-Y H:i:s'; /** - * Get coordinates + * Get coordinates of passed location * * @param string $location * @@ -109,7 +112,7 @@ private function getCoordinates($location) } /** - * Get date + * Get date for location passed via coordinates * * @param string $lat * @param string $lng @@ -120,7 +123,7 @@ private function getDate($lat, $lng) { $path = 'timezone/json'; - $date_utc = new \DateTime(null, new \DateTimeZone('UTC')); + $date_utc = new \DateTimeImmutable(null, new \DateTimeZone('UTC')); $timestamp = $date_utc->format('U'); $query = [ @@ -195,7 +198,7 @@ private function getFormattedDate($location) list($local_time, $timezone_id) = $this->getDate($lat, $lng); - $date_utc = new DateTime(gmdate('Y-m-d H:i:s', $local_time), new DateTimeZone($timezone_id)); + $date_utc = new \DateTimeImmutable(gmdate('Y-m-d H:i:s', $local_time), new \DateTimeZone($timezone_id)); return 'The local time in ' . $timezone_id . ' is: ' . $date_utc->format($this->date_format); } diff --git a/Commands/DeletechatphotoCommand.php b/Commands/DeletechatphotoCommand.php index 687aa3c..f910715 100644 --- a/Commands/DeletechatphotoCommand.php +++ b/Commands/DeletechatphotoCommand.php @@ -14,13 +14,15 @@ /** * Delete chat photo command + * + * Gets executed when the photo of a group or channel gets deleted. */ class DeletechatphotoCommand extends SystemCommand { /** * @var string */ - protected $name = 'Deletechatphoto'; + protected $name = 'deletechatphoto'; /** * @var string diff --git a/Commands/EchoCommand.php b/Commands/EchoCommand.php index 755da77..ac7864c 100644 --- a/Commands/EchoCommand.php +++ b/Commands/EchoCommand.php @@ -15,6 +15,8 @@ /** * User "/echo" command + * + * Simply echo the input back to the user. */ class EchoCommand extends UserCommand { diff --git a/Commands/EditedchannelpostCommand.php b/Commands/EditedchannelpostCommand.php index 699760f..a85a050 100644 --- a/Commands/EditedchannelpostCommand.php +++ b/Commands/EditedchannelpostCommand.php @@ -14,13 +14,15 @@ /** * Edited channel post command + * + * Gets executed when a post in a channel is edited. */ class EditedchannelpostCommand extends SystemCommand { /** * @var string */ - protected $name = 'Editedchannelpost'; + protected $name = 'editedchannelpost'; /** * @var string diff --git a/Commands/EditedmessageCommand.php b/Commands/EditedmessageCommand.php index 74a13ca..199b590 100644 --- a/Commands/EditedmessageCommand.php +++ b/Commands/EditedmessageCommand.php @@ -14,6 +14,8 @@ /** * Edited message command + * + * Gets executed when a user message is edited. */ class EditedmessageCommand extends SystemCommand { @@ -30,7 +32,7 @@ class EditedmessageCommand extends SystemCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.1.1'; /** * Command execute method @@ -40,8 +42,7 @@ class EditedmessageCommand extends SystemCommand */ public function execute() { - //$update = $this->getUpdate(); - //$edited_message = $update->getEditedMessage(); + //$edited_message = $this->getEditedMessage(); return parent::execute(); } diff --git a/Commands/EditmessageCommand.php b/Commands/EditmessageCommand.php index 2a3fe0f..2b33994 100644 --- a/Commands/EditmessageCommand.php +++ b/Commands/EditmessageCommand.php @@ -15,6 +15,8 @@ /** * User "/editmessage" command + * + * Command to edit a message via bot. */ class EditmessageCommand extends UserCommand { @@ -36,7 +38,7 @@ class EditmessageCommand extends UserCommand /** * @var string */ - protected $version = '1.0.0'; + protected $version = '1.1.0'; /** * Command execute method @@ -58,7 +60,18 @@ public function execute() 'text' => $text ?: 'Edited message', ]; - return Request::editMessageText($data_edit); + // Try to edit selected message. + $result = Request::editMessageText($data_edit); + + if ($result->isOk()) { + // Delete this editing reply message. + Request::deleteMessage([ + 'chat_id' => $chat_id, + 'message_id' => $message->getMessageId(), + ]); + } + + return $result; } $data = [ diff --git a/Commands/ForcereplyCommand.php b/Commands/ForcereplyCommand.php index 4a889c1..a0ca31f 100644 --- a/Commands/ForcereplyCommand.php +++ b/Commands/ForcereplyCommand.php @@ -16,8 +16,10 @@ /** * User "/forcereply" command + * + * Force a reply to a message. */ -class ForceReplyCommand extends UserCommand +class ForcereplyCommand extends UserCommand { /** * @var string diff --git a/Commands/GenericCommand.php b/Commands/GenericCommand.php index 1c921ca..8deb8d8 100644 --- a/Commands/GenericCommand.php +++ b/Commands/GenericCommand.php @@ -15,13 +15,15 @@ /** * Generic command + * + * Gets executed for generic commands, when no other appropriate one is found. */ class GenericCommand extends SystemCommand { /** * @var string */ - protected $name = 'Generic'; + protected $name = 'generic'; /** * @var string @@ -48,7 +50,7 @@ public function execute() $user_id = $message->getFrom()->getId(); $command = $message->getCommand(); - //If the user is and admin and the command is in the format "/whoisXYZ", call the /whois command + //If the user is an admin and the command is in the format "/whoisXYZ", call the /whois command if (stripos($command, 'whois') === 0 && $this->telegram->isAdmin($user_id)) { return $this->telegram->executeCommand('whois'); } diff --git a/Commands/GenericmessageCommand.php b/Commands/GenericmessageCommand.php index 9271395..7c843d9 100644 --- a/Commands/GenericmessageCommand.php +++ b/Commands/GenericmessageCommand.php @@ -16,13 +16,15 @@ /** * Generic message command + * + * Gets executed when any type of message is sent. */ class GenericmessageCommand extends SystemCommand { /** * @var string */ - protected $name = 'Genericmessage'; + protected $name = 'genericmessage'; /** * @var string diff --git a/Commands/GroupchatcreatedCommand.php b/Commands/GroupchatcreatedCommand.php index e17dd03..cbe3ed2 100644 --- a/Commands/GroupchatcreatedCommand.php +++ b/Commands/GroupchatcreatedCommand.php @@ -14,13 +14,15 @@ /** * Group chat created command + * + * Gets executed when a group chat is created. */ class GroupchatcreatedCommand extends SystemCommand { /** * @var string */ - protected $name = 'Groupchatcreated'; + protected $name = 'groupchatcreated'; /** * @var string diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index 71c232e..6b418e6 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -16,6 +16,8 @@ /** * User "/help" command + * + * Command that lists all available commands and displays them in User and Admin sections. */ class HelpCommand extends UserCommand { diff --git a/Commands/HidekeyboardCommand.php b/Commands/HidekeyboardCommand.php index d9515ed..f2190a3 100644 --- a/Commands/HidekeyboardCommand.php +++ b/Commands/HidekeyboardCommand.php @@ -16,6 +16,8 @@ /** * User "/hidekeyboard" command + * + * Command to hide the keyboard. */ class HidekeyboardCommand extends UserCommand { diff --git a/Commands/ImageCommand.php b/Commands/ImageCommand.php index 89c45e4..20ba876 100644 --- a/Commands/ImageCommand.php +++ b/Commands/ImageCommand.php @@ -11,11 +11,12 @@ namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Entities\ReplyKeyboardMarkup; use Longman\TelegramBot\Request; /** * User "/image" command + * + * Fetch any uploaded image from the Uploads path. */ class ImageCommand extends UserCommand { @@ -37,7 +38,7 @@ class ImageCommand extends UserCommand /** * @var string */ - protected $version = '1.0.1'; + protected $version = '1.1.0'; /** * Command execute method @@ -48,16 +49,31 @@ class ImageCommand extends UserCommand public function execute() { $message = $this->getMessage(); - $chat_id = $message->getChat()->getId(); - $text = $message->getText(true); + + // Use any extra parameters as the caption text. + $caption = trim($message->getText(true)); + + // Get a random picture from the telegram->getUploadPath() directory. + $random_image = $this->GetRandomImagePath($this->telegram->getUploadPath()); $data = [ - 'chat_id' => $chat_id, - 'caption' => $text, + 'chat_id' => $message->getChat()->getId(), ]; - //Return a random picture from the telegram->getUploadPath(). - return Request::sendPhoto($data, $this->ShowRandomImage($this->telegram->getUploadPath())); + if (!$random_image) { + $data['text'] = 'No image found!'; + return Request::sendMessage($data); + } + + // If no caption is set, use the filename. + if ($caption === '') { + $caption = basename($random_image); + } + + $data['caption'] = $caption; + $data['photo'] = Request::encodeFile($random_image); + + return Request::sendPhoto($data); } /** @@ -67,10 +83,14 @@ public function execute() * * @return string */ - private function ShowRandomImage($dir) + private function GetRandomImagePath($dir) { - $image_list = scandir($dir); + // Slice off the . and .. "directories" + if ($image_list = array_slice(scandir($dir, SCANDIR_SORT_NONE), 2)) { + shuffle($image_list); + return $dir . '/' . $image_list[0]; + } - return $dir . '/' . $image_list[mt_rand(2, count($image_list) - 1)]; + return ''; } } diff --git a/Commands/InlinekeyboardCommand.php b/Commands/InlinekeyboardCommand.php index 4457c59..a5553fa 100644 --- a/Commands/InlinekeyboardCommand.php +++ b/Commands/InlinekeyboardCommand.php @@ -16,6 +16,8 @@ /** * User "/inlinekeyboard" command + * + * Display an inline keyboard with a few buttons. */ class InlinekeyboardCommand extends UserCommand { diff --git a/Commands/InlinequeryCommand.php b/Commands/InlinequeryCommand.php index 01a6fb7..654e74f 100644 --- a/Commands/InlinequeryCommand.php +++ b/Commands/InlinequeryCommand.php @@ -17,6 +17,8 @@ /** * Inline query command + * + * Command that handles inline queries. */ class InlinequeryCommand extends SystemCommand { @@ -33,7 +35,7 @@ class InlinequeryCommand extends SystemCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.1.1'; /** * Command execute method @@ -43,8 +45,7 @@ class InlinequeryCommand extends SystemCommand */ public function execute() { - $update = $this->getUpdate(); - $inline_query = $update->getInlineQuery(); + $inline_query = $this->getInlineQuery(); $query = $inline_query->getQuery(); $data = ['inline_query_id' => $inline_query->getId()]; diff --git a/Commands/KeyboardCommand.php b/Commands/KeyboardCommand.php index 08fbc50..8b294e0 100644 --- a/Commands/KeyboardCommand.php +++ b/Commands/KeyboardCommand.php @@ -16,6 +16,8 @@ /** * User "/keyboard" command + * + * Display a keyboard with a few buttons. */ class KeyboardCommand extends UserCommand { diff --git a/Commands/LeftchatmemberCommand.php b/Commands/LeftchatmemberCommand.php index 1d9ef73..5062d58 100644 --- a/Commands/LeftchatmemberCommand.php +++ b/Commands/LeftchatmemberCommand.php @@ -14,13 +14,15 @@ /** * Left chat member command + * + * Gets executed when a member leaves the chat. */ class LeftchatmemberCommand extends SystemCommand { /** * @var string */ - protected $name = 'Leftchatmember'; + protected $name = 'leftchatmember'; /** * @var string diff --git a/Commands/MarkdownCommand.php b/Commands/MarkdownCommand.php index 4f03bad..d8c25be 100644 --- a/Commands/MarkdownCommand.php +++ b/Commands/MarkdownCommand.php @@ -16,6 +16,8 @@ /** * User "/markdown" command + * + * Print some markdown text. */ class MarkdownCommand extends UserCommand { diff --git a/Commands/MigratefromchatidCommand.php b/Commands/MigratefromchatidCommand.php index e78b52b..9ee043a 100644 --- a/Commands/MigratefromchatidCommand.php +++ b/Commands/MigratefromchatidCommand.php @@ -14,13 +14,15 @@ /** * Migrate from chat id command + * + * Gets executed when a chat gets migrated. */ class MigratefromchatidCommand extends SystemCommand { /** * @var string */ - protected $name = 'Migratefromchatid'; + protected $name = 'migratefromchatid'; /** * @var string diff --git a/Commands/MigratetochatidCommand.php b/Commands/MigratetochatidCommand.php index eee80fb..cf91478 100644 --- a/Commands/MigratetochatidCommand.php +++ b/Commands/MigratetochatidCommand.php @@ -14,13 +14,15 @@ /** * Migrate to chat id command + * + * Gets executed when a chat gets migrated. */ class MigratetochatidCommand extends SystemCommand { /** * @var string */ - protected $name = 'Migratetochatid'; + protected $name = 'migratetochatid'; /** * @var string diff --git a/Commands/NewchatmemberCommand.php b/Commands/NewchatmembersCommand.php similarity index 69% rename from Commands/NewchatmemberCommand.php rename to Commands/NewchatmembersCommand.php index 344f115..a5f2e13 100644 --- a/Commands/NewchatmemberCommand.php +++ b/Commands/NewchatmembersCommand.php @@ -16,22 +16,22 @@ /** * New chat member command */ -class NewchatmemberCommand extends SystemCommand +class NewchatmembersCommand extends SystemCommand { /** * @var string */ - protected $name = 'Newchatmember'; + protected $name = 'newchatmembers'; /** * @var string */ - protected $description = 'New Chat Member'; + protected $description = 'New Chat Members'; /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.2.0'; /** * Command execute method @@ -44,11 +44,16 @@ public function execute() $message = $this->getMessage(); $chat_id = $message->getChat()->getId(); - $member = $message->getNewChatMember(); - $text = 'Hi there!'; + $members = $message->getNewChatMembers(); + + $text = 'Hi there!'; if (!$message->botAddedInChat()) { - $text = 'Hi ' . $member->tryMention() . '!'; + $member_names = []; + foreach ($members as $member) { + $member_names[] = $member->tryMention(); + } + $text = 'Hi ' . implode(', ', $member_names) . '!'; } $data = [ diff --git a/Commands/NewchatphotoCommand.php b/Commands/NewchatphotoCommand.php index 96c9eb3..31381fc 100644 --- a/Commands/NewchatphotoCommand.php +++ b/Commands/NewchatphotoCommand.php @@ -14,13 +14,15 @@ /** * New chat photo command + * + * Gets executed when the photo of a group or channel gets set. */ class NewchatphotoCommand extends SystemCommand { /** * @var string */ - protected $name = 'Newchatphoto'; + protected $name = 'newchatphoto'; /** * @var string diff --git a/Commands/NewchattitleCommand.php b/Commands/NewchattitleCommand.php index d4b6bd0..0855669 100644 --- a/Commands/NewchattitleCommand.php +++ b/Commands/NewchattitleCommand.php @@ -14,13 +14,15 @@ /** * New chat title command + * + * Gets executed when the title of a group or channel gets set. */ class NewchattitleCommand extends SystemCommand { /** * @var string */ - protected $name = 'Newchattitle'; + protected $name = 'newchattitle'; /** * @var string diff --git a/Commands/PinnedmessageCommand.php b/Commands/PinnedmessageCommand.php index 5cd410d..a5a7f2b 100644 --- a/Commands/PinnedmessageCommand.php +++ b/Commands/PinnedmessageCommand.php @@ -14,13 +14,15 @@ /** * Pinned message command + * + * Gets executed when a message gets pinned. */ class PinnedmessageCommand extends SystemCommand { /** * @var string */ - protected $name = 'Pinnedmessage'; + protected $name = 'pinnedmessage'; /** * @var string diff --git a/Commands/ShortenerCommand.php b/Commands/ShortenerCommand.php index 082eda5..cd4f692 100644 --- a/Commands/ShortenerCommand.php +++ b/Commands/ShortenerCommand.php @@ -16,6 +16,8 @@ /** * User "/shortener" command + * + * Create a shortened URL using Botan. */ class ShortenerCommand extends UserCommand { diff --git a/Commands/SlapCommand.php b/Commands/SlapCommand.php index 563bc98..4bf3452 100644 --- a/Commands/SlapCommand.php +++ b/Commands/SlapCommand.php @@ -15,6 +15,8 @@ /** * User "/slap" command + * + * Slap a user around with a big trout! */ class SlapCommand extends UserCommand { diff --git a/Commands/StartCommand.php b/Commands/StartCommand.php index ade208e..5fe300b 100644 --- a/Commands/StartCommand.php +++ b/Commands/StartCommand.php @@ -15,6 +15,8 @@ /** * Start command + * + * Gets executed when a user first starts using the bot. */ class StartCommand extends SystemCommand { @@ -38,6 +40,11 @@ class StartCommand extends SystemCommand */ protected $version = '1.1.0'; + /** + * @var bool + */ + protected $private_only = true; + /** * Command execute method * diff --git a/Commands/SupergroupchatcreatedCommand.php b/Commands/SupergroupchatcreatedCommand.php index aeef40b..a84661a 100644 --- a/Commands/SupergroupchatcreatedCommand.php +++ b/Commands/SupergroupchatcreatedCommand.php @@ -14,13 +14,15 @@ /** * Super group chat created command + * + * Gets executed when a super group chat is created. */ class SupergroupchatcreatedCommand extends SystemCommand { /** * @var string */ - protected $name = 'Supergroupchatcreated'; + protected $name = 'supergroupchatcreated'; /** * @var string diff --git a/Commands/SurveyCommand.php b/Commands/SurveyCommand.php index 90f2ad8..36a43fb 100644 --- a/Commands/SurveyCommand.php +++ b/Commands/SurveyCommand.php @@ -19,6 +19,8 @@ /** * User "/survey" command + * + * Command that demonstrated the Conversation funtionality in form of a simple survey. */ class SurveyCommand extends UserCommand { @@ -47,6 +49,11 @@ class SurveyCommand extends UserCommand */ protected $need_mysql = true; + /** + * @var bool + */ + protected $private_only = true; + /** * Conversation Object * diff --git a/Commands/WeatherCommand.php b/Commands/WeatherCommand.php index 87837d6..b5021ee 100644 --- a/Commands/WeatherCommand.php +++ b/Commands/WeatherCommand.php @@ -19,6 +19,9 @@ /** * User "/weather" command + * + * Get weather info for any place. + * This command requires an API key to be set via command config. */ class WeatherCommand extends UserCommand { diff --git a/Commands/WhoamiCommand.php b/Commands/WhoamiCommand.php index e91dd21..98bed32 100644 --- a/Commands/WhoamiCommand.php +++ b/Commands/WhoamiCommand.php @@ -20,6 +20,8 @@ /** * User "/whoami" command + * + * Simple command that returns info about the current user. */ class WhoamiCommand extends UserCommand { @@ -43,6 +45,11 @@ class WhoamiCommand extends UserCommand */ protected $version = '1.1.0'; + /** + * @var bool + */ + protected $private_only = true; + /** * Command execute method * From df007d3a4f4a746a98bf07dcee67e8cadde93790 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Thu, 17 Aug 2017 00:01:39 +0200 Subject: [PATCH 04/43] Define bot_username as a variable to reuse for logfile names. --- manager.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/manager.php b/manager.php index 26b99f1..c41515f 100644 --- a/manager.php +++ b/manager.php @@ -11,11 +11,14 @@ // Load composer require_once __DIR__ . '/vendor/autoload.php'; +// Add you bot's username (also to be used for log file names) +$bot_username = 'username_bot'; // Without "@" + try { $bot = new TelegramBot\TelegramBotManager\BotManager([ // Add you bot's API key and name 'api_key' => 'your:bot_api_key', - 'bot_username' => 'username_bot', + 'bot_username' => $bot_username, // Secret key required to access the webhook 'secret' => 'super_secret', @@ -56,9 +59,9 @@ // Logging (Error, Debug and Raw Updates) //'logging' => [ - // 'debug' => __DIR__ . '/{$bot_username}_debug.log', - // 'error' => __DIR__ . '/{$bot_username}_error.log', - // 'update' => __DIR__ . '/{$bot_username}_update.log', + // 'debug' => __DIR__ . "/{$bot_username}_debug.log", + // 'error' => __DIR__ . "/{$bot_username}_error.log", + // 'update' => __DIR__ . "/{$bot_username}_update.log", //], // Set custom Upload and Download paths From a0b90408418e6deff37832f0957fda45d53e2db2 Mon Sep 17 00:00:00 2001 From: 0xEAB Date: Mon, 4 Sep 2017 00:00:03 +0200 Subject: [PATCH 05/43] Fix help command not working in group chats Reply was sent to sender's chat instead of the group. --- Commands/HelpCommand.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index 6b418e6..f18ea4e 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -39,7 +39,7 @@ class HelpCommand extends UserCommand /** * @var string */ - protected $version = '1.2.0'; + protected $version = '1.2.1'; /** * @inheritdoc @@ -47,7 +47,7 @@ class HelpCommand extends UserCommand public function execute() { $message = $this->getMessage(); - $chat_id = $message->getFrom()->getId(); + $chat_id = $message->getChat()->getId(); $command_str = trim($message->getText(true)); $data = [ From daec7ead18197c574c09880ac3d4793a6e06851f Mon Sep 17 00:00:00 2001 From: 0xEAB Date: Mon, 4 Sep 2017 17:54:38 +0200 Subject: [PATCH 06/43] Fix /help leaking admin commands in group chats --- Commands/HelpCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index f18ea4e..cc0a032 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -64,7 +64,7 @@ public function execute() $data['text'] .= '/' . $user_command->getName() . ' - ' . $user_command->getDescription() . PHP_EOL; } - if (count($admin_commands) > 0) { + if ((count($admin_commands) > 0) && !$message->getChat()->isGroupChat() && $this->telegram->isAdmin($message->getFrom()->getId())) { $data['text'] .= PHP_EOL . '*Admin Commands List*:' . PHP_EOL; foreach ($admin_commands as $admin_command) { $data['text'] .= '/' . $admin_command->getName() . ' - ' . $admin_command->getDescription() . PHP_EOL; From 71775506a48f6a4989c0b0cef54900dd48f0e47d Mon Sep 17 00:00:00 2001 From: 0xEAB Date: Mon, 4 Sep 2017 18:45:51 +0200 Subject: [PATCH 07/43] Fix /help leaking in group chats --- Commands/HelpCommand.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index cc0a032..c728808 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -64,7 +64,9 @@ public function execute() $data['text'] .= '/' . $user_command->getName() . ' - ' . $user_command->getDescription() . PHP_EOL; } - if ((count($admin_commands) > 0) && !$message->getChat()->isGroupChat() && $this->telegram->isAdmin($message->getFrom()->getId())) { + if ((count($admin_commands) > 0) && + !$message->getChat()->isGroupChat() && $this->telegram->isAdmin($message->getFrom()->getId())) { + $data['text'] .= PHP_EOL . '*Admin Commands List*:' . PHP_EOL; foreach ($admin_commands as $admin_command) { $data['text'] .= '/' . $admin_command->getName() . ' - ' . $admin_command->getDescription() . PHP_EOL; @@ -77,7 +79,9 @@ public function execute() } $command_str = str_replace('/', '', $command_str); - if (isset($all_commands[$command_str])) { + if (isset($all_commands[$command_str]) && (!$all_commands[$command_str]->isAdminCommand()) || + (!$message->getChat()->isGroupChat() && $this->telegram->isAdmin($message->getFrom()->getId()))) { + $command = $all_commands[$command_str]; $data['text'] = sprintf( 'Command: %s (v%s)' . PHP_EOL . From 38585c8798a75c0660691d2de57fd45da074dee0 Mon Sep 17 00:00:00 2001 From: 0xEAB Date: Mon, 4 Sep 2017 22:43:40 +0200 Subject: [PATCH 08/43] Refactor help command fixes --- Commands/HelpCommand.php | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index c728808..20fcce0 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -50,6 +50,9 @@ public function execute() $chat_id = $message->getChat()->getId(); $command_str = trim($message->getText(true)); + // Admin commands shouldn't be shown in group chats + $safe_to_show = $message->getChat()->isPrivateChat(); + $data = [ 'chat_id' => $chat_id, 'parse_mode' => 'markdown', @@ -64,9 +67,7 @@ public function execute() $data['text'] .= '/' . $user_command->getName() . ' - ' . $user_command->getDescription() . PHP_EOL; } - if ((count($admin_commands) > 0) && - !$message->getChat()->isGroupChat() && $this->telegram->isAdmin($message->getFrom()->getId())) { - + if ((count($admin_commands) > 0) && $safe_to_show) { $data['text'] .= PHP_EOL . '*Admin Commands List*:' . PHP_EOL; foreach ($admin_commands as $admin_command) { $data['text'] .= '/' . $admin_command->getName() . ' - ' . $admin_command->getDescription() . PHP_EOL; @@ -79,9 +80,7 @@ public function execute() } $command_str = str_replace('/', '', $command_str); - if (isset($all_commands[$command_str]) && (!$all_commands[$command_str]->isAdminCommand()) || - (!$message->getChat()->isGroupChat() && $this->telegram->isAdmin($message->getFrom()->getId()))) { - + if (isset($all_commands[$command_str]) && ($safe_to_show || !$all_commands[$command_str]->isAdminCommand())) { $command = $all_commands[$command_str]; $data['text'] = sprintf( 'Command: %s (v%s)' . PHP_EOL . From 8a52baa8b82440bae664006602c8b0ddd312215a Mon Sep 17 00:00:00 2001 From: 0xEAB Date: Tue, 5 Sep 2017 12:57:55 +0200 Subject: [PATCH 09/43] Improve performance (slightly) --- Commands/HelpCommand.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index 20fcce0..a32c093 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -39,7 +39,7 @@ class HelpCommand extends UserCommand /** * @var string */ - protected $version = '1.2.1'; + protected $version = '1.3.0'; /** * @inheritdoc @@ -67,7 +67,7 @@ public function execute() $data['text'] .= '/' . $user_command->getName() . ' - ' . $user_command->getDescription() . PHP_EOL; } - if ((count($admin_commands) > 0) && $safe_to_show) { + if ($safe_to_show && count($admin_commands) > 0) { $data['text'] .= PHP_EOL . '*Admin Commands List*:' . PHP_EOL; foreach ($admin_commands as $admin_command) { $data['text'] .= '/' . $admin_command->getName() . ' - ' . $admin_command->getDescription() . PHP_EOL; From 1adb82f507e72d72b1eb6b2f23dca1020914f45c Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 20 Sep 2017 16:34:16 +0200 Subject: [PATCH 10/43] Uncommented the Commands path line Since the example-bot is meant as a quickstart there is no point in having the example commands excluded, be it even only for a test of the setup before coding a custom command. --- getUpdatesCLI.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/getUpdatesCLI.php b/getUpdatesCLI.php index 7046fa8..6d290dc 100644 --- a/getUpdatesCLI.php +++ b/getUpdatesCLI.php @@ -23,7 +23,7 @@ // Define all paths for your custom commands in this array (leave as empty array if not used) $commands_paths = [ -// __DIR__ . '/Commands/', + __DIR__ . '/Commands/', ]; // Enter your MySQL database credentials From 988a9fc55852c56397ac0f24620d8c1894c4d8dd Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 20 Sep 2017 16:55:56 +0200 Subject: [PATCH 11/43] Added structure.sql to the example-bot repo Since the quickiest method to try out and get into the field with the example-bot is the getUpdates method and it needs a MySQL databse initialized with the structure.sql preset I see no point in excluding it from the repo. --- structure.sql | 223 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 structure.sql diff --git a/structure.sql b/structure.sql new file mode 100644 index 0000000..c90d724 --- /dev/null +++ b/structure.sql @@ -0,0 +1,223 @@ +CREATE TABLE IF NOT EXISTS `user` ( + `id` bigint COMMENT 'Unique user identifier', + `is_bot` tinyint(1) DEFAULT 0 COMMENT 'True if this user is a bot', + `first_name` CHAR(255) NOT NULL DEFAULT '' COMMENT 'User''s first name', + `last_name` CHAR(255) DEFAULT NULL COMMENT 'User''s last name', + `username` CHAR(191) DEFAULT NULL COMMENT 'User''s username', + `language_code` CHAR(10) DEFAULT NULL COMMENT 'User''s system language', + `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 user or chat identifier', + `type` ENUM('private', 'group', 'supergroup', 'channel') NOT NULL COMMENT 'Chat type, either private, group, supergroup or channel', + `title` CHAR(255) DEFAULT '' COMMENT 'Chat (group) title, is null if chat type is private', + `username` CHAR(255) DEFAULT NULL COMMENT 'Username, for private chats, supergroups and channels if available', + `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 `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', + `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 'Identifier for this result', + `user_id` bigint NULL COMMENT 'Unique user identifier', + `location` CHAR(255) NULL DEFAULT NULL COMMENT 'Location object, user''s 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', + `id` bigint UNSIGNED COMMENT 'Unique message identifier', + `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_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', + `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', + `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', + `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', + `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', + `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', + `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)', + `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', + `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', + + 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 `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 (`forward_from`) 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 `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', + `data` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Data associated with the callback button', + `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 `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 `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 'Unique message identifier', + `inline_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Unique inline query identifier', + `chosen_inline_result_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Local chosen inline result identifier', + `callback_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Unique callback query identifier', + `edited_message_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Local edited message identifier', + + PRIMARY KEY (`id`), + KEY `message_id` (`chat_id`, `message_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 `edited_message_id` (`edited_message_id`), + + FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `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 (`edited_message_id`) REFERENCES `edited_message` (`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 `botan_shortener` ( + `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry', + `user_id` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier', + `url` text NOT NULL COMMENT 'Original URL', + `short_url` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Shortened URL', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + + PRIMARY KEY (`id`), + + FOREIGN KEY (`user_id`) REFERENCES `user` (`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; From 07814b9e540fec95cf69034bb9572b89ee5d60b4 Mon Sep 17 00:00:00 2001 From: Maxiride Date: Wed, 20 Sep 2017 22:29:51 +0200 Subject: [PATCH 12/43] Revert "Added structure.sql to the example-bot repo" --- structure.sql | 223 -------------------------------------------------- 1 file changed, 223 deletions(-) delete mode 100644 structure.sql diff --git a/structure.sql b/structure.sql deleted file mode 100644 index c90d724..0000000 --- a/structure.sql +++ /dev/null @@ -1,223 +0,0 @@ -CREATE TABLE IF NOT EXISTS `user` ( - `id` bigint COMMENT 'Unique user identifier', - `is_bot` tinyint(1) DEFAULT 0 COMMENT 'True if this user is a bot', - `first_name` CHAR(255) NOT NULL DEFAULT '' COMMENT 'User''s first name', - `last_name` CHAR(255) DEFAULT NULL COMMENT 'User''s last name', - `username` CHAR(191) DEFAULT NULL COMMENT 'User''s username', - `language_code` CHAR(10) DEFAULT NULL COMMENT 'User''s system language', - `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 user or chat identifier', - `type` ENUM('private', 'group', 'supergroup', 'channel') NOT NULL COMMENT 'Chat type, either private, group, supergroup or channel', - `title` CHAR(255) DEFAULT '' COMMENT 'Chat (group) title, is null if chat type is private', - `username` CHAR(255) DEFAULT NULL COMMENT 'Username, for private chats, supergroups and channels if available', - `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 `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', - `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 'Identifier for this result', - `user_id` bigint NULL COMMENT 'Unique user identifier', - `location` CHAR(255) NULL DEFAULT NULL COMMENT 'Location object, user''s 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', - `id` bigint UNSIGNED COMMENT 'Unique message identifier', - `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_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', - `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', - `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', - `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', - `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', - `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', - `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)', - `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', - `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', - - 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 `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 (`forward_from`) 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 `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', - `data` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Data associated with the callback button', - `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 `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 `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 'Unique message identifier', - `inline_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Unique inline query identifier', - `chosen_inline_result_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Local chosen inline result identifier', - `callback_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Unique callback query identifier', - `edited_message_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Local edited message identifier', - - PRIMARY KEY (`id`), - KEY `message_id` (`chat_id`, `message_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 `edited_message_id` (`edited_message_id`), - - FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `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 (`edited_message_id`) REFERENCES `edited_message` (`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 `botan_shortener` ( - `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry', - `user_id` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier', - `url` text NOT NULL COMMENT 'Original URL', - `short_url` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Shortened URL', - `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', - - PRIMARY KEY (`id`), - - FOREIGN KEY (`user_id`) REFERENCES `user` (`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; From 90bfde028f71bda1aedd51bdc225984a68b5c276 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Tue, 12 Dec 2017 13:19:29 +0100 Subject: [PATCH 13/43] Add Upload command. --- Commands/UploadCommand.php | 85 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Commands/UploadCommand.php diff --git a/Commands/UploadCommand.php b/Commands/UploadCommand.php new file mode 100644 index 0000000..6c65355 --- /dev/null +++ b/Commands/UploadCommand.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Conversation; +use Longman\TelegramBot\Entities\Keyboard; +use Longman\TelegramBot\Request; + +/** + * User "/upload" command + * + * A command that allows users to upload files to your bot, saving them to the bot's "Download" folder. + */ +class UploadCommand extends UserCommand +{ + /**#@+ + * {@inheritdoc} + */ + protected $name = 'upload'; + protected $description = 'Upload and save files'; + protected $usage = '/upload'; + protected $version = '0.1.0'; + protected $need_mysql = true; + /**#@-*/ + + /** + * {@inheritdoc} + */ + public function execute() + { + $message = $this->getMessage(); + $chat = $message->getChat(); + $chat_id = $chat->getId(); + $user_id = $message->getFrom()->getId(); + + // Preparing Response + $data = [ + 'chat_id' => $chat_id, + 'reply_markup' => Keyboard::remove(), + ]; + + if ($chat->isGroupChat() || $chat->isSuperGroup()) { + // Reply to message id is applied by default + $data['reply_to_message_id'] = $message->getMessageId(); + // Force reply is applied by default to so can work with privacy on + $data['reply_markup'] = Keyboard::forceReply(['selective' => true]); + } + + // Start conversation + $conversation = new Conversation($user_id, $chat_id, $this->getName()); + $message_type = $message->getType(); + + if (in_array($message_type, ['audio', 'document', 'photo', 'video', 'voice'], true)) { + $doc = $message->{'get' . ucfirst($message_type)}(); + + // For photos, get the best quality! + ($message_type === 'photo') && $doc = end($doc); + + $file_id = $doc->getFileId(); + $file = Request::getFile(['file_id' => $file_id]); + if ($file->isOk() && Request::downloadFile($file->getResult())) { + $data['text'] = $message_type . ' file is located at: ' . $this->telegram->getDownloadPath() . '/' . $file->getResult()->getFilePath(); + } else { + $data['text'] = 'Failed to download.'; + } + + $conversation->notes['file_id'] = $file_id; + $conversation->update(); + $conversation->stop(); + } else { + $data['text'] = 'Please upload the file now'; + } + + return Request::sendMessage($data); + } +} From f7f282332c4aa793de3b74e72110da49047d27c5 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 4 Mar 2018 23:25:53 +0300 Subject: [PATCH 14/43] Update ImageCommand.php --- Commands/ImageCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Commands/ImageCommand.php b/Commands/ImageCommand.php index 20ba876..e6d2597 100644 --- a/Commands/ImageCommand.php +++ b/Commands/ImageCommand.php @@ -86,7 +86,7 @@ public function execute() private function GetRandomImagePath($dir) { // Slice off the . and .. "directories" - if ($image_list = array_slice(scandir($dir, SCANDIR_SORT_NONE), 2)) { + if ($image_list = array_diff(scandir($dir), array('..', '.'))) { shuffle($image_list); return $dir . '/' . $image_list[0]; } From e5cd51a5b78255ad257d83dc0b143eb82a119fec Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 5 Mar 2018 14:37:33 +0300 Subject: [PATCH 15/43] Update hook.php Since the example-bot is meant as a quickstart there is no point in having the example commands excluded, be it even only for a test of the setup before coding a custom command. Wasted some time figuring out why bot isn't working. --- hook.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hook.php b/hook.php index 6405842..94d2b7c 100644 --- a/hook.php +++ b/hook.php @@ -22,7 +22,7 @@ // Define all paths for your custom commands in this array (leave as empty array if not used) $commands_paths = [ -// __DIR__ . '/Commands/', + __DIR__ . '/Commands/', ]; // Enter your MySQL database credentials From fbda4da63bb017dac0cafb7b5e6e1ea9b902911b Mon Sep 17 00:00:00 2001 From: Jack'lul Date: Tue, 6 Aug 2019 09:31:38 +0200 Subject: [PATCH 16/43] Botan support removed --- Commands/ShortenerCommand.php | 65 ----------------------------------- 1 file changed, 65 deletions(-) delete mode 100644 Commands/ShortenerCommand.php diff --git a/Commands/ShortenerCommand.php b/Commands/ShortenerCommand.php deleted file mode 100644 index cd4f692..0000000 --- a/Commands/ShortenerCommand.php +++ /dev/null @@ -1,65 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Longman\TelegramBot\Commands\UserCommands; - -use Longman\TelegramBot\Botan; -use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Request; - -/** - * User "/shortener" command - * - * Create a shortened URL using Botan. - */ -class ShortenerCommand extends UserCommand -{ - /** - * @var string - */ - protected $name = 'shortener'; - - /** - * @var string - */ - protected $description = 'Botan Shortener example'; - - /** - * @var string - */ - protected $usage = '/shortener'; - - /** - * @var string - */ - protected $version = '1.0.0'; - - /** - * Command execute method - * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException - */ - public function execute() - { - $message = $this->getMessage(); - $chat_id = $message->getChat()->getId(); - $user_id = $message->getFrom()->getId(); - - $text = Botan::shortenUrl('https://github.com/php-telegram-bot/core', $user_id); - - $data = [ - 'chat_id' => $chat_id, - 'text' => $text, - ]; - - return Request::sendMessage($data); - } -} From 5c16b5401b2084fb613606d15a78a67d2d59b566 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Sun, 2 Feb 2020 20:54:17 +0100 Subject: [PATCH 17/43] Fully remove Botan.io from examples --- cron.php | 3 --- getUpdatesCLI.php | 3 --- hook.php | 3 --- manager.php | 5 ----- 4 files changed, 14 deletions(-) diff --git a/cron.php b/cron.php index f88af9c..83ca79f 100644 --- a/cron.php +++ b/cron.php @@ -65,9 +65,6 @@ // e.g. Google geocode/timezone api key for /date command: //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); - // Botan.io integration - //$telegram->enableBotan('your_botan_token'); - // Requests Limiter (tries to prevent reaching Telegram API limits) $telegram->enableLimiter(); diff --git a/getUpdatesCLI.php b/getUpdatesCLI.php index 6d290dc..d9d36cb 100644 --- a/getUpdatesCLI.php +++ b/getUpdatesCLI.php @@ -63,9 +63,6 @@ // e.g. Google geocode/timezone api key for /date command //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); - // Botan.io integration - //$telegram->enableBotan('your_botan_token'); - // Requests Limiter (tries to prevent reaching Telegram API limits) $telegram->enableLimiter(); diff --git a/hook.php b/hook.php index 94d2b7c..5590518 100644 --- a/hook.php +++ b/hook.php @@ -62,9 +62,6 @@ // e.g. Google geocode/timezone api key for /date command //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); - // Botan.io integration - //$telegram->enableBotan('your_botan_token'); - // Requests Limiter (tries to prevent reaching Telegram API limits) $telegram->enableLimiter(); diff --git a/manager.php b/manager.php index c41515f..cf00a14 100644 --- a/manager.php +++ b/manager.php @@ -70,11 +70,6 @@ // 'upload' => __DIR__ . '/Upload', //], - // Botan.io integration - //'botan' => [ - // 'token' => 'your_botan_token', - //], - // Requests Limiter (tries to prevent reaching Telegram API limits) 'limiter' => ['enabled' => true], ]); From f77e1fac625e01c82cd34fa1c9f63a7e5dd1bfd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Mon, 2 Mar 2020 20:55:26 +0100 Subject: [PATCH 18/43] Note about potentially unsafe commands. --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a1b57a5..f03cd7f 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,15 @@ # PHP Telegram Bot Example An A-Z example of Telegram bot using the [PHP Telegram Bot][1] library. -**Important!** Before getting started with this project, make sure you have read the official [readme][2] to understand how the PHP Telegram Bot library works and what is required to run a Telegram bot. - -Let's get started then! :smiley: - This repository aims to demonstrate the usage of all the features offered by the PHP Telegram Bot library and as such contains all example commands. Also, it gives an example setup for both the standard usage and using the [PHP Telegram Bot Manager][3] +**:exclamation: Important!** +- Most of the commands found here are **not to be used exactly as they are**, they are mere demonstrations of features! They are provided as-is and any **extra security measures need to be added by you**, the developer. +- Before getting started with this project, make sure you have read the official [readme][2] to understand how the PHP Telegram Bot library works and what is required to run a Telegram bot. + +Let's get started then! :smiley: + ## 0. Cloning this repository To start off, you can clone this repository using git: From 2b81dd48afe540ed7b26d00a2ff2a2c7e76674be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Mon, 23 Mar 2020 08:59:07 +0100 Subject: [PATCH 19/43] Add new logging initialisation to examples. --- cron.php | 18 ++++++++++++------ getUpdatesCLI.php | 18 ++++++++++++------ hook.php | 18 ++++++++++++------ 3 files changed, 36 insertions(+), 18 deletions(-) diff --git a/cron.php b/cron.php index 83ca79f..56852e1 100644 --- a/cron.php +++ b/cron.php @@ -50,12 +50,18 @@ //$telegram->enableMySql($mysql_credentials); // Logging (Error, Debug and Raw Updates) - //Longman\TelegramBot\TelegramLog::initErrorLog(__DIR__ . "/{$bot_username}_error.log"); - //Longman\TelegramBot\TelegramLog::initDebugLog(__DIR__ . "/{$bot_username}_debug.log"); - //Longman\TelegramBot\TelegramLog::initUpdateLog(__DIR__ . "/{$bot_username}_update.log"); - - // If you are using a custom Monolog instance for logging, use this instead of the above - //Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance); + // https://github.com/php-telegram-bot/core/blob/master/doc/01-utils.md#logging + // + // (this example requires Monolog: composer require monolog/monolog) + //Longman\TelegramBot\TelegramLog::initialize( + // new Monolog\Logger('telegram_bot', [ + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // ]), + // new Monolog\Logger('telegram_bot_updates', [ + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + // ]) + //); // Set custom Upload and Download paths //$telegram->setDownloadPath(__DIR__ . '/Download'); diff --git a/getUpdatesCLI.php b/getUpdatesCLI.php index d9d36cb..39bb0d7 100644 --- a/getUpdatesCLI.php +++ b/getUpdatesCLI.php @@ -48,12 +48,18 @@ $telegram->enableMySql($mysql_credentials); // Logging (Error, Debug and Raw Updates) - //Longman\TelegramBot\TelegramLog::initErrorLog(__DIR__ . "/{$bot_username}_error.log"); - //Longman\TelegramBot\TelegramLog::initDebugLog(__DIR__ . "/{$bot_username}_debug.log"); - //Longman\TelegramBot\TelegramLog::initUpdateLog(__DIR__ . "/{$bot_username}_update.log"); - - // If you are using a custom Monolog instance for logging, use this instead of the above - //Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance); + // https://github.com/php-telegram-bot/core/blob/master/doc/01-utils.md#logging + // + // (this example requires Monolog: composer require monolog/monolog) + //Longman\TelegramBot\TelegramLog::initialize( + // new Monolog\Logger('telegram_bot', [ + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // ]), + // new Monolog\Logger('telegram_bot_updates', [ + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + // ]) + //); // Set custom Upload and Download paths //$telegram->setDownloadPath(__DIR__ . '/Download'); diff --git a/hook.php b/hook.php index 5590518..0b690d1 100644 --- a/hook.php +++ b/hook.php @@ -47,12 +47,18 @@ //$telegram->enableMySql($mysql_credentials); // Logging (Error, Debug and Raw Updates) - //Longman\TelegramBot\TelegramLog::initErrorLog(__DIR__ . "/{$bot_username}_error.log"); - //Longman\TelegramBot\TelegramLog::initDebugLog(__DIR__ . "/{$bot_username}_debug.log"); - //Longman\TelegramBot\TelegramLog::initUpdateLog(__DIR__ . "/{$bot_username}_update.log"); - - // If you are using a custom Monolog instance for logging, use this instead of the above - //Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance); + // https://github.com/php-telegram-bot/core/blob/master/doc/01-utils.md#logging + // + // (this example requires Monolog: composer require monolog/monolog) + //Longman\TelegramBot\TelegramLog::initialize( + // new Monolog\Logger('telegram_bot', [ + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // ]), + // new Monolog\Logger('telegram_bot_updates', [ + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + // ]) + //); // Set custom Upload and Download paths //$telegram->setDownloadPath(__DIR__ . '/Download'); From f74ada3d72f0b65315d6ea6fd07a1e6e9cf81c92 Mon Sep 17 00:00:00 2001 From: Josep Comas Date: Sun, 26 Apr 2020 00:41:39 +0200 Subject: [PATCH 20/43] Update InlinequeryCommand.php Updated to current implementation --- Commands/InlinequeryCommand.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Commands/InlinequeryCommand.php b/Commands/InlinequeryCommand.php index 654e74f..a1976b9 100644 --- a/Commands/InlinequeryCommand.php +++ b/Commands/InlinequeryCommand.php @@ -35,7 +35,7 @@ class InlinequeryCommand extends SystemCommand /** * @var string */ - protected $version = '1.1.1'; + protected $version = '1.1.2'; /** * Command execute method @@ -78,8 +78,6 @@ public function execute() } } - $data['results'] = '[' . implode(',', $results) . ']'; - - return Request::answerInlineQuery($data); + return $this->getInlineQuery()->answer($results, $data); } } From aad411a578d02806ecb0da7f0ec4d9fae0636078 Mon Sep 17 00:00:00 2001 From: Nabi KaramAliZadeh Date: Fri, 1 May 2020 11:12:44 +0430 Subject: [PATCH 21/43] Update hook.php fix namespace --- hook.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hook.php b/hook.php index 0b690d1..186b3ce 100644 --- a/hook.php +++ b/hook.php @@ -52,11 +52,11 @@ // (this example requires Monolog: composer require monolog/monolog) //Longman\TelegramBot\TelegramLog::initialize( // new Monolog\Logger('telegram_bot', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), // ]), // new Monolog\Logger('telegram_bot_updates', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), // ]) //); From 5a8d7b2e75ea880e51d439a32da1f831bc086ff7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Mon, 4 May 2020 12:01:44 +0200 Subject: [PATCH 22/43] Fix namespace for Monolog Logger class --- cron.php | 6 +++--- getUpdatesCLI.php | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cron.php b/cron.php index 56852e1..296e6b9 100644 --- a/cron.php +++ b/cron.php @@ -55,11 +55,11 @@ // (this example requires Monolog: composer require monolog/monolog) //Longman\TelegramBot\TelegramLog::initialize( // new Monolog\Logger('telegram_bot', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), // ]), // new Monolog\Logger('telegram_bot_updates', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), // ]) //); diff --git a/getUpdatesCLI.php b/getUpdatesCLI.php index 39bb0d7..ce5dc1e 100644 --- a/getUpdatesCLI.php +++ b/getUpdatesCLI.php @@ -53,11 +53,11 @@ // (this example requires Monolog: composer require monolog/monolog) //Longman\TelegramBot\TelegramLog::initialize( // new Monolog\Logger('telegram_bot', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), // ]), // new Monolog\Logger('telegram_bot_updates', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), // ]) //); From ca8e244ed9581976ef00a5469bc1116e01a20fbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Sat, 11 Jul 2020 22:32:53 +0200 Subject: [PATCH 23/43] Add example for Telegram Payments Including pre-checkout query, flexible shipping and success message. --- Commands/Payments/GenericmessageCommand.php | 56 ++++++++ Commands/Payments/PaymentCommand.php | 123 ++++++++++++++++++ Commands/Payments/PrecheckoutqueryCommand.php | 54 ++++++++ Commands/Payments/README.md | 39 ++++++ Commands/Payments/ShippingqueryCommand.php | 77 +++++++++++ hook.php | 6 +- manager.php | 4 +- 7 files changed, 356 insertions(+), 3 deletions(-) create mode 100644 Commands/Payments/GenericmessageCommand.php create mode 100644 Commands/Payments/PaymentCommand.php create mode 100644 Commands/Payments/PrecheckoutqueryCommand.php create mode 100644 Commands/Payments/README.md create mode 100644 Commands/Payments/ShippingqueryCommand.php diff --git a/Commands/Payments/GenericmessageCommand.php b/Commands/Payments/GenericmessageCommand.php new file mode 100644 index 0000000..888eca4 --- /dev/null +++ b/Commands/Payments/GenericmessageCommand.php @@ -0,0 +1,56 @@ +getMessage(); + $user_id = $message->getFrom()->getId(); + + // Handle successful payment. + if ($payment = $message->getSuccessfulPayment()) { + return PaymentCommand::handleSuccessfulPayment($payment, $user_id); + } + + return Request::emptyResponse(); + } +} diff --git a/Commands/Payments/PaymentCommand.php b/Commands/Payments/PaymentCommand.php new file mode 100644 index 0000000..cf082c7 --- /dev/null +++ b/Commands/Payments/PaymentCommand.php @@ -0,0 +1,123 @@ +setCommandConfig('payment', ['payment_provider_token' => 'your_payment_provider_token_here']); + * + * You will also need to copy the `Precheckoutquerycommand.php` file. + */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\Payments\LabeledPrice; +use Longman\TelegramBot\Entities\Payments\SuccessfulPayment; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; +use Longman\TelegramBot\Request; + +class PaymentCommand extends UserCommand +{ + /** + * @var string + */ + protected $name = 'payment'; + + /** + * @var string + */ + protected $description = 'Create an invoice for the user using Telegram Payments'; + + /** + * @var string + */ + protected $usage = '/payment'; + + /** + * @var string + */ + protected $version = '0.1.0'; + + /** + * @inheritDoc + */ + public function execute() + { + // Who to send this invoice to. (Use the current user.) + $chat_id = $this->getMessage()->getFrom()->getId(); + + // The currency of this invoice. + // Supported currencies: https://core.telegram.org/bots/payments#supported-currencies + $currency = 'EUR'; + + // List all items that will be shown on your invoice. + // Amounts are in cents. So 1 Euro would be put as 100. + $prices = [ + new LabeledPrice(['label' => 'Small thing', 'amount' => 100]), // 1€ + new LabeledPrice(['label' => 'Bigger thing', 'amount' => 2000]), // 20€ + new LabeledPrice(['label' => 'Huge thing', 'amount' => 50000]), // 500€ + ]; + + // Request a shipping address if necessary. + $need_shipping_address = false; + + // If you have flexible pricing, depending on the shipping method chosen, set this to true. + // You will also require the `ShippingqueryCommand.php` file and adapt it. + $is_flexible = false; + + // Send the actual invoice! + // Adjust any parameters to your needs. + return Request::sendInvoice([ + 'chat_id' => $chat_id, + 'title' => 'Payment with PHP Telegram Bot', + 'description' => 'A simple invoice to test Telegram Payments', + 'payload' => 'payment_demo', + 'start_parameter' => 'payment_demo', + 'provider_token' => $this->getConfig('payment_provider_token'), + 'currency' => $currency, + 'prices' => $prices, + 'need_shipping_address' => $need_shipping_address, + 'is_flexible' => $is_flexible, + ]); + } + + /** + * Send "Thank you" message to user who paid. + * + * You will need to add some code to your custom `GenericmessageCommand::execute()` method. + * Check the `GenericmessageCommand.php` file included in this folder. + * + * @param SuccessfulPayment $payment + * @param int $user_id + * + * @return ServerResponse + * @throws TelegramException + */ + public static function handleSuccessfulPayment($payment, $user_id) + { + // Send a message to the user after they have completed the payment. + return Request::sendMessage([ + 'chat_id' => $user_id, + 'text' => 'Thank you for your order!', + ]); + } +} diff --git a/Commands/Payments/PrecheckoutqueryCommand.php b/Commands/Payments/PrecheckoutqueryCommand.php new file mode 100644 index 0000000..89a003d --- /dev/null +++ b/Commands/Payments/PrecheckoutqueryCommand.php @@ -0,0 +1,54 @@ +getPreCheckoutQuery()->answer(true); + + // If we do make certain checks, you can define the error message displayed to the user like this. + // return $this->getPreCheckoutQuery()->answer(false, [ + // 'error_message' => 'Registration (or whatever) required...', + // ]); + } +} diff --git a/Commands/Payments/README.md b/Commands/Payments/README.md new file mode 100644 index 0000000..1bcfbd6 --- /dev/null +++ b/Commands/Payments/README.md @@ -0,0 +1,39 @@ +# Telegram Payments + +With the files in this folder, you can create and send invoices to your users, require their shipping details, define custom / flexible shipping methods and send a confirmation message after payment. + +## Enable payments for your bot + +Read all about Telegram Payments and follow the setup guide here: +https://core.telegram.org/bots/payments + +## Configuring the `/payment` command + +First of all, as a bare minimum, you need to copy the `PaymentCommand.php` and `PrecheckoutqueryCommand.php` files in this folder to your custom commands folder. + +If you want to allow flexible shipping options, you will also need to copy `ShippingqueryCommand.php` to your custom commands folder. + +Should you want to send a message on a successful payment, you will need to copy the `GenericmessageCommand.php` file as well. +If you already have a `GenericmessageCommand.php` file, you'll need to copy the code from the `execute` method into your file. + +Next, you will need to add the Payment Provider Token (that you received in the previous step when linking your bot), to your `hook.php` or `manager.php` config. + +For `hook.php`: +```php +$telegram->setCommandConfig('payment', ['payment_provider_token' => 'your_payment_provider_token_here']); +``` + +For `manager.php`, in the config array add: +```php +... +'commands' => [ + 'configs' => [ + 'payment' => ['payment_provider_token' => 'your_payment_provider_token_here'], + ], +], +... +``` + +Now, when sending the `/payment` command to your bot, you should receive an invoice. + +Have fun with Telegram Payments! diff --git a/Commands/Payments/ShippingqueryCommand.php b/Commands/Payments/ShippingqueryCommand.php new file mode 100644 index 0000000..1aebcf5 --- /dev/null +++ b/Commands/Payments/ShippingqueryCommand.php @@ -0,0 +1,77 @@ +getShippingQuery()->answer(true, [ + 'shipping_options' => [ + new ShippingOption([ + 'id' => 'basic', + 'title' => 'Basic Shipping', + 'prices' => [ + new LabeledPrice(['label' => 'Basic Shipping', 'amount' => 800]), + ], + ]), + new ShippingOption([ + 'id' => 'premium', + 'title' => 'Premium Shipping', + 'prices' => [ + new LabeledPrice(['label' => 'Premium Shipping', 'amount' => 1500]), + new LabeledPrice(['label' => 'Extra speedy', 'amount' => 300]), + ], + ]), + ], + ]); + + // If we do make certain checks, you can define the error message displayed to the user like this. + // return $this->getShippingQuery()->answer(false, [ + // 'error_message' => 'We do not ship to your location :-(', + // ]); + } +} diff --git a/hook.php b/hook.php index 186b3ce..0edefd4 100644 --- a/hook.php +++ b/hook.php @@ -65,8 +65,10 @@ //$telegram->setUploadPath(__DIR__ . '/Upload'); // Here you can set some command specific parameters - // e.g. Google geocode/timezone api key for /date command - //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); + // - Google geocode/timezone API key for /date command + // $telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); + // - Payment Provider Token for /payment command. + // $telegram->setCommandConfig('payment', ['payment_provider_token' => 'your_payment_provider_token_here']); // Requests Limiter (tries to prevent reaching Telegram API limits) $telegram->enableLimiter(); diff --git a/manager.php b/manager.php index cf00a14..f611fdf 100644 --- a/manager.php +++ b/manager.php @@ -39,8 +39,10 @@ // ], // // Here you can set some command specific parameters // 'configs' => [ - // // e.g. Google geocode/timezone api key for /date command + // - Google geocode/timezone API key for /date command // 'date' => ['google_api_key' => 'your_google_api_key_here'], + // - Payment Provider Token for /payment command. + // 'payment' => ['payment_provider_token' => 'your_payment_provider_token_here'], // ], //], From 8b6ef861577aef55acfdfa5be98af85e475a6bd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Sun, 12 Jul 2020 13:54:26 +0200 Subject: [PATCH 24/43] Add new file headers that mention the example-bot repo --- Commands/CallbackqueryCommand.php | 6 ++++-- Commands/CancelCommand.php | 6 ++++-- Commands/ChannelchatcreatedCommand.php | 6 ++++-- Commands/ChannelpostCommand.php | 6 ++++-- Commands/ChoseninlineresultCommand.php | 6 ++++-- Commands/DateCommand.php | 6 ++++-- Commands/DeletechatphotoCommand.php | 6 ++++-- Commands/EchoCommand.php | 6 ++++-- Commands/EditedchannelpostCommand.php | 6 ++++-- Commands/EditedmessageCommand.php | 6 ++++-- Commands/EditmessageCommand.php | 6 ++++-- Commands/ForcereplyCommand.php | 6 ++++-- Commands/GenericCommand.php | 6 ++++-- Commands/GenericmessageCommand.php | 6 ++++-- Commands/GroupchatcreatedCommand.php | 6 ++++-- Commands/HelpCommand.php | 6 ++++-- Commands/HidekeyboardCommand.php | 6 ++++-- Commands/ImageCommand.php | 6 ++++-- Commands/InlinekeyboardCommand.php | 6 ++++-- Commands/InlinequeryCommand.php | 6 ++++-- Commands/KeyboardCommand.php | 6 ++++-- Commands/LeftchatmemberCommand.php | 6 ++++-- Commands/MarkdownCommand.php | 6 ++++-- Commands/MigratefromchatidCommand.php | 6 ++++-- Commands/MigratetochatidCommand.php | 6 ++++-- Commands/NewchatmembersCommand.php | 6 ++++-- Commands/NewchatphotoCommand.php | 6 ++++-- Commands/NewchattitleCommand.php | 6 ++++-- Commands/Payments/GenericmessageCommand.php | 2 +- Commands/Payments/PaymentCommand.php | 2 +- Commands/Payments/PrecheckoutqueryCommand.php | 2 +- Commands/Payments/ShippingqueryCommand.php | 2 +- Commands/PinnedmessageCommand.php | 6 ++++-- Commands/SlapCommand.php | 6 ++++-- Commands/StartCommand.php | 6 ++++-- Commands/SupergroupchatcreatedCommand.php | 6 ++++-- Commands/SurveyCommand.php | 6 ++++-- Commands/UploadCommand.php | 6 ++++-- Commands/WeatherCommand.php | 6 ++++-- Commands/WhoamiCommand.php | 8 ++++---- LICENSE | 2 +- cron.php | 11 +++++++++++ getUpdatesCLI.php | 11 +++++++++++ hook.php | 11 +++++++++++ manager.php | 11 +++++++++++ set.php | 11 +++++++++++ unset.php | 11 +++++++++++ 47 files changed, 215 insertions(+), 79 deletions(-) diff --git a/Commands/CallbackqueryCommand.php b/Commands/CallbackqueryCommand.php index 0b3c768..41de951 100644 --- a/Commands/CallbackqueryCommand.php +++ b/Commands/CallbackqueryCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/CancelCommand.php b/Commands/CancelCommand.php index 468f081..ea5632a 100644 --- a/Commands/CancelCommand.php +++ b/Commands/CancelCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/ChannelchatcreatedCommand.php b/Commands/ChannelchatcreatedCommand.php index 8c07884..4339119 100644 --- a/Commands/ChannelchatcreatedCommand.php +++ b/Commands/ChannelchatcreatedCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/ChannelpostCommand.php b/Commands/ChannelpostCommand.php index 10ed436..0391e6e 100644 --- a/Commands/ChannelpostCommand.php +++ b/Commands/ChannelpostCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/ChoseninlineresultCommand.php b/Commands/ChoseninlineresultCommand.php index b1d5cdf..3feaa0b 100644 --- a/Commands/ChoseninlineresultCommand.php +++ b/Commands/ChoseninlineresultCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/DateCommand.php b/Commands/DateCommand.php index 31d5e49..e55c9e1 100644 --- a/Commands/DateCommand.php +++ b/Commands/DateCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/DeletechatphotoCommand.php b/Commands/DeletechatphotoCommand.php index f910715..52a819d 100644 --- a/Commands/DeletechatphotoCommand.php +++ b/Commands/DeletechatphotoCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/EchoCommand.php b/Commands/EchoCommand.php index ac7864c..fa6b823 100644 --- a/Commands/EchoCommand.php +++ b/Commands/EchoCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/EditedchannelpostCommand.php b/Commands/EditedchannelpostCommand.php index a85a050..dd9d1db 100644 --- a/Commands/EditedchannelpostCommand.php +++ b/Commands/EditedchannelpostCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/EditedmessageCommand.php b/Commands/EditedmessageCommand.php index 199b590..531557b 100644 --- a/Commands/EditedmessageCommand.php +++ b/Commands/EditedmessageCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/EditmessageCommand.php b/Commands/EditmessageCommand.php index 2b33994..cd1b270 100644 --- a/Commands/EditmessageCommand.php +++ b/Commands/EditmessageCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/ForcereplyCommand.php b/Commands/ForcereplyCommand.php index a0ca31f..a632e63 100644 --- a/Commands/ForcereplyCommand.php +++ b/Commands/ForcereplyCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/GenericCommand.php b/Commands/GenericCommand.php index 8deb8d8..8caedef 100644 --- a/Commands/GenericCommand.php +++ b/Commands/GenericCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/GenericmessageCommand.php b/Commands/GenericmessageCommand.php index 7c843d9..c7dc1be 100644 --- a/Commands/GenericmessageCommand.php +++ b/Commands/GenericmessageCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/GroupchatcreatedCommand.php b/Commands/GroupchatcreatedCommand.php index cbe3ed2..c4423e5 100644 --- a/Commands/GroupchatcreatedCommand.php +++ b/Commands/GroupchatcreatedCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index a32c093..c8fb9cf 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/HidekeyboardCommand.php b/Commands/HidekeyboardCommand.php index f2190a3..cd0e2c2 100644 --- a/Commands/HidekeyboardCommand.php +++ b/Commands/HidekeyboardCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/ImageCommand.php b/Commands/ImageCommand.php index e6d2597..0f2767e 100644 --- a/Commands/ImageCommand.php +++ b/Commands/ImageCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/InlinekeyboardCommand.php b/Commands/InlinekeyboardCommand.php index a5553fa..bf2466e 100644 --- a/Commands/InlinekeyboardCommand.php +++ b/Commands/InlinekeyboardCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/InlinequeryCommand.php b/Commands/InlinequeryCommand.php index a1976b9..6a2fc94 100644 --- a/Commands/InlinequeryCommand.php +++ b/Commands/InlinequeryCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/KeyboardCommand.php b/Commands/KeyboardCommand.php index 8b294e0..c428891 100644 --- a/Commands/KeyboardCommand.php +++ b/Commands/KeyboardCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/LeftchatmemberCommand.php b/Commands/LeftchatmemberCommand.php index 5062d58..da94d96 100644 --- a/Commands/LeftchatmemberCommand.php +++ b/Commands/LeftchatmemberCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/MarkdownCommand.php b/Commands/MarkdownCommand.php index d8c25be..59acd4a 100644 --- a/Commands/MarkdownCommand.php +++ b/Commands/MarkdownCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/MigratefromchatidCommand.php b/Commands/MigratefromchatidCommand.php index 9ee043a..9736157 100644 --- a/Commands/MigratefromchatidCommand.php +++ b/Commands/MigratefromchatidCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/MigratetochatidCommand.php b/Commands/MigratetochatidCommand.php index cf91478..6513dcb 100644 --- a/Commands/MigratetochatidCommand.php +++ b/Commands/MigratetochatidCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/NewchatmembersCommand.php b/Commands/NewchatmembersCommand.php index a5f2e13..5ffda60 100644 --- a/Commands/NewchatmembersCommand.php +++ b/Commands/NewchatmembersCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/NewchatphotoCommand.php b/Commands/NewchatphotoCommand.php index 31381fc..702407c 100644 --- a/Commands/NewchatphotoCommand.php +++ b/Commands/NewchatphotoCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/NewchattitleCommand.php b/Commands/NewchattitleCommand.php index 0855669..19d04a9 100644 --- a/Commands/NewchattitleCommand.php +++ b/Commands/NewchattitleCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/Payments/GenericmessageCommand.php b/Commands/Payments/GenericmessageCommand.php index 888eca4..e33a5a2 100644 --- a/Commands/Payments/GenericmessageCommand.php +++ b/Commands/Payments/GenericmessageCommand.php @@ -4,7 +4,7 @@ * This file is part of the PHP Telegram Bot example-bot package. * https://github.com/php-telegram-bot/example-bot/ * - * (c) PHP Telegram Bot Developers + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/Payments/PaymentCommand.php b/Commands/Payments/PaymentCommand.php index cf082c7..31179c3 100644 --- a/Commands/Payments/PaymentCommand.php +++ b/Commands/Payments/PaymentCommand.php @@ -4,7 +4,7 @@ * This file is part of the PHP Telegram Bot example-bot package. * https://github.com/php-telegram-bot/example-bot/ * - * (c) PHP Telegram Bot Developers + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/Payments/PrecheckoutqueryCommand.php b/Commands/Payments/PrecheckoutqueryCommand.php index 89a003d..7a1f308 100644 --- a/Commands/Payments/PrecheckoutqueryCommand.php +++ b/Commands/Payments/PrecheckoutqueryCommand.php @@ -4,7 +4,7 @@ * This file is part of the PHP Telegram Bot example-bot package. * https://github.com/php-telegram-bot/example-bot/ * - * (c) PHP Telegram Bot Developers + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/Payments/ShippingqueryCommand.php b/Commands/Payments/ShippingqueryCommand.php index 1aebcf5..9f10548 100644 --- a/Commands/Payments/ShippingqueryCommand.php +++ b/Commands/Payments/ShippingqueryCommand.php @@ -4,7 +4,7 @@ * This file is part of the PHP Telegram Bot example-bot package. * https://github.com/php-telegram-bot/example-bot/ * - * (c) PHP Telegram Bot Developers + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/PinnedmessageCommand.php b/Commands/PinnedmessageCommand.php index a5a7f2b..91116e0 100644 --- a/Commands/PinnedmessageCommand.php +++ b/Commands/PinnedmessageCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/SlapCommand.php b/Commands/SlapCommand.php index 4bf3452..dd992e7 100644 --- a/Commands/SlapCommand.php +++ b/Commands/SlapCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/StartCommand.php b/Commands/StartCommand.php index 5fe300b..ca95f82 100644 --- a/Commands/StartCommand.php +++ b/Commands/StartCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/SupergroupchatcreatedCommand.php b/Commands/SupergroupchatcreatedCommand.php index a84661a..d6363b7 100644 --- a/Commands/SupergroupchatcreatedCommand.php +++ b/Commands/SupergroupchatcreatedCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/SurveyCommand.php b/Commands/SurveyCommand.php index 36a43fb..7a9db57 100644 --- a/Commands/SurveyCommand.php +++ b/Commands/SurveyCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/UploadCommand.php b/Commands/UploadCommand.php index 6c65355..3c3fddb 100644 --- a/Commands/UploadCommand.php +++ b/Commands/UploadCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/WeatherCommand.php b/Commands/WeatherCommand.php index b5021ee..d353a9b 100644 --- a/Commands/WeatherCommand.php +++ b/Commands/WeatherCommand.php @@ -1,8 +1,10 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. diff --git a/Commands/WhoamiCommand.php b/Commands/WhoamiCommand.php index 98bed32..1aafae2 100644 --- a/Commands/WhoamiCommand.php +++ b/Commands/WhoamiCommand.php @@ -1,13 +1,13 @@ + * (c) PHP Telegram Bot Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * - * Written by Marco Boretto */ namespace Longman\TelegramBot\Commands\UserCommands; diff --git a/LICENSE b/LICENSE index 5a877f2..6e16d53 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2017 PHP Telegram Bot +Copyright (c) 2020 PHP Telegram Bot Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/cron.php b/cron.php index 296e6b9..25f795d 100644 --- a/cron.php +++ b/cron.php @@ -1,4 +1,15 @@ Date: Sun, 12 Jul 2020 15:00:46 +0200 Subject: [PATCH 25/43] Move all bot configuration to config.php and require it in the individual files. --- .gitignore | 3 +- README.md | 28 ++++++++------- config.example.php | 88 ++++++++++++++++++++++++++++++++++++++++++++++ cron.php | 78 ++++++++-------------------------------- getUpdatesCLI.php | 82 +++++++++--------------------------------- hook.php | 81 ++++++++++++++++-------------------------- manager.php | 80 ++++++----------------------------------- set.php | 30 ++++++++-------- unset.php | 18 ++++------ 9 files changed, 196 insertions(+), 292 deletions(-) create mode 100644 config.example.php diff --git a/.gitignore b/.gitignore index e26f45e..3030116 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ composer.phar -/vendor/ composer.lock +config.php +vendor diff --git a/README.md b/README.md index f03cd7f..38c428f 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # PHP Telegram Bot Example -An A-Z example of Telegram bot using the [PHP Telegram Bot][1] library. +An A-Z example of Telegram bot using the [PHP Telegram Bot][core-github] library. This repository aims to demonstrate the usage of all the features offered by the PHP Telegram Bot library and as such contains all example commands. -Also, it gives an example setup for both the standard usage and using the [PHP Telegram Bot Manager][3] +Also, it gives an example setup for both the standard usage and using the [PHP Telegram Bot Manager][bot-manager-github] **:exclamation: Important!** - Most of the commands found here are **not to be used exactly as they are**, they are mere demonstrations of features! They are provided as-is and any **extra security measures need to be added by you**, the developer. -- Before getting started with this project, make sure you have read the official [readme][2] to understand how the PHP Telegram Bot library works and what is required to run a Telegram bot. +- Before getting started with this project, make sure you have read the official [readme][core-readme-github] to understand how the PHP Telegram Bot library works and what is required to run a Telegram bot. Let's get started then! :smiley: @@ -28,14 +28,16 @@ Unzip the files to the root of your project folder. ## 1. Making it yours -Now you can choose what installation you would like, either the default one or using the [Bot Manager][3] project. +Now you can choose what installation you would like, either the default one or using the [Bot Manager][bot-manager-github] project. Depending on which one you choose, you can delete the files that are not required. --- +First of all, you need to rename `config.example.php` to `config.php` and then replace all necessary values with those of your project. + **Default** -Next, edit the following files, replacing all necessary values with those of your project. -Thanks to reading the main readme file, you should know what these do. +Some of these files require extra configurations to be added. Check `hook.php` how they are loaded. +Thanks to reading the main readme file, you should know what these files do. - `composer.json` (Describes your project and it's dependencies) - `set.php` (Used to set the webhook) @@ -47,7 +49,7 @@ Thanks to reading the main readme file, you should know what these do. **Bot Manager** Using the bot manager makes life much easier, as all configuration goes into a single file, `manager.php`. -If you decide to use the Bot Manager, be sure to [read all about it][4] and change the `require` block in the `composer.json` file: +If you decide to use the Bot Manager, be sure to [read all about it][bot-manager-readme-github] and change the `require` block in the `composer.json` file: ```json "require": { "php-telegram-bot/telegram-bot-manager": "*" @@ -61,15 +63,15 @@ Then, edit the following files, replacing all necessary values with those of you --- -Now you can install all dependencies using [composer][5]: +Now you can install all dependencies using [composer]: ```bash $ composer install ``` ## To be continued! -[1]: https://github.com/php-telegram-bot/core "php-telegram-bot/core" -[2]: https://github.com/php-telegram-bot/core#readme "PHP Telegram Bot - README" -[3]: https://github.com/php-telegram-bot/telegram-bot-manager "php-telegram-bot/telegram-bot-manager" -[4]: https://github.com/php-telegram-bot/telegram-bot-manager#readme "PHP Telegram Bot Manager - README" -[5]: https://getcomposer.org/ "Composer" +[core-github]: https://github.com/php-telegram-bot/core "php-telegram-bot/core" +[core-readme-github]: https://github.com/php-telegram-bot/core#readme "PHP Telegram Bot - README" +[bot-manager-github]: https://github.com/php-telegram-bot/telegram-bot-manager "php-telegram-bot/telegram-bot-manager" +[bot-manager-readme-github]: https://github.com/php-telegram-bot/telegram-bot-manager#readme "PHP Telegram Bot Manager - README" +[composer]: https://getcomposer.org/ "Composer" diff --git a/config.example.php b/config.example.php new file mode 100644 index 0000000..135b8a3 --- /dev/null +++ b/config.example.php @@ -0,0 +1,88 @@ + 'your:bot_api_key', + 'bot_username' => 'username_bot', // Without "@" + + // [Manager Only] Secret key required to access the webhook + 'secret' => 'super_secret', + + // When using the getUpdates method, this can be commented out + 'webhook' => [ + 'url' => 'https://your-domain/path/to/hook-or-manager.php', + // Use self-signed certificate + // 'certificate' => __DIR__ . '/path/to/your/certificate.crt', + // Limit maximum number of connections + // 'max_connections' => 5, + ], + + // All command related configs go here + 'commands' => [ + // Define all paths for your custom commands + 'paths' => [ + // __DIR__ . '/Commands', + ], + // Here you can set any command-specific parameters + 'configs' => [ + // - Google geocode/timezone API key for /date command + // 'date' => ['google_api_key' => 'your_google_api_key_here'], + // - Payment Provider Token for /payment command. + // 'payment' => ['payment_provider_token' => 'your_payment_provider_token_here'], + ], + ], + + // Define all IDs of admin users + 'admins' => [ + // 123, + ], + + // Enter your MySQL database credentials + // 'mysql' => [ + // 'host' => '127.0.0.1', + // 'user' => 'root', + // 'password' => 'root', + // 'database' => 'telegram_bot', + // ], + + // Logging (Debug, Error and Raw Updates) + // 'logging' => [ + // 'debug' => __DIR__ . '/php-telegram-bot-debug.log', + // 'error' => __DIR__ . '/php-telegram-bot-error.log', + // 'update' => __DIR__ . '/php-telegram-bot-update.log', + // ], + + // Set custom Upload and Download paths + 'paths' => [ + 'download' => __DIR__ . '/Download', + 'upload' => __DIR__ . '/Upload', + ], + + // Requests Limiter (tries to prevent reaching Telegram API limits) + 'limiter' => [ + 'enabled' => true, + ], +]; diff --git a/cron.php b/cron.php index 25f795d..1f7b517 100644 --- a/cron.php +++ b/cron.php @@ -11,12 +11,10 @@ */ /** - * README - * This configuration file is intended to run a list of commands with crontab. - * Uncommented parameters must be filled + * This file is used to run a list of commands with crontab. */ -// Your command(s) to run, pass it just like in a message (arguments supported) +// Your command(s) to run, pass them just like in a message (arguments supported) $commands = [ '/whoami', "/echo I'm a bot!", @@ -25,76 +23,28 @@ // Load composer require_once __DIR__ . '/vendor/autoload.php'; -// Add you bot's API key and name -$bot_api_key = 'your:bot_api_key'; -$bot_username = 'username_bot'; - -// Define all IDs of admin users in this array (leave as empty array if not used) -$admin_users = [ -// 123, -]; - -// Define all paths for your custom commands in this array (leave as empty array if not used) -$commands_paths = [ -// __DIR__ . '/Commands/', -]; - -// Enter your MySQL database credentials -//$mysql_credentials = [ -// 'host' => 'localhost', -// 'user' => 'dbuser', -// 'password' => 'dbpass', -// 'database' => 'dbname', -//]; +// Load all configuration options +/** @var array $config */ +$config = require __DIR__ . '/config.php'; try { // Create Telegram API object - $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); - - // Add commands paths containing your custom commands - $telegram->addCommandsPaths($commands_paths); + $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']); - // Enable admin users - $telegram->enableAdmins($admin_users); - - // Enable MySQL - //$telegram->enableMySql($mysql_credentials); - - // Logging (Error, Debug and Raw Updates) - // https://github.com/php-telegram-bot/core/blob/master/doc/01-utils.md#logging - // - // (this example requires Monolog: composer require monolog/monolog) - //Longman\TelegramBot\TelegramLog::initialize( - // new Monolog\Logger('telegram_bot', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // ]), - // new Monolog\Logger('telegram_bot_updates', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), - // ]) - //); - - // Set custom Upload and Download paths - //$telegram->setDownloadPath(__DIR__ . '/Download'); - //$telegram->setUploadPath(__DIR__ . '/Upload'); - - // Here you can set some command specific parameters, - // e.g. Google geocode/timezone api key for /date command: - //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); - - // Requests Limiter (tries to prevent reaching Telegram API limits) - $telegram->enableLimiter(); + /** + * Check `hook.php` for configuration code to be added here. + */ // Run user selected commands $telegram->runCommands($commands); } catch (Longman\TelegramBot\Exception\TelegramException $e) { - // Silence is golden! - //echo $e; // Log telegram errors Longman\TelegramBot\TelegramLog::error($e); + + // Uncomment this to output any errors (ONLY FOR DEVELOPMENT!) + // echo $e; } catch (Longman\TelegramBot\Exception\TelegramLogException $e) { - // Silence is golden! - // Uncomment this to catch log initialisation errors - //echo $e; + // Uncomment this to output log initialisation errors (ONLY FOR DEVELOPMENT!) + // echo $e; } diff --git a/getUpdatesCLI.php b/getUpdatesCLI.php index 2cca144..5ca7bcc 100644 --- a/getUpdatesCLI.php +++ b/getUpdatesCLI.php @@ -12,92 +12,42 @@ */ /** - * README - * This configuration file is intended to run the bot with the getUpdates method. - * Uncommented parameters must be filled - * - * Bash script: - * $ while true; do ./getUpdatesCLI.php; done + * This file is used to run the bot with the getUpdates method. */ // Load composer require_once __DIR__ . '/vendor/autoload.php'; -// Add you bot's API key and name -$bot_api_key = 'your:bot_api_key'; -$bot_username = 'username_bot'; - -// Define all IDs of admin users in this array (leave as empty array if not used) -$admin_users = [ -// 123, -]; - -// Define all paths for your custom commands in this array (leave as empty array if not used) -$commands_paths = [ - __DIR__ . '/Commands/', -]; - -// Enter your MySQL database credentials -$mysql_credentials = [ - 'host' => 'localhost', - 'user' => 'dbuser', - 'password' => 'dbpass', - 'database' => 'dbname', -]; +// Load all configuration options +/** @var array $config */ +$config = require __DIR__ . '/config.php'; try { // Create Telegram API object - $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); - - // Add commands paths containing your custom commands - $telegram->addCommandsPaths($commands_paths); - - // Enable admin users - $telegram->enableAdmins($admin_users); + $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']); - // Enable MySQL - $telegram->enableMySql($mysql_credentials); - - // Logging (Error, Debug and Raw Updates) - // https://github.com/php-telegram-bot/core/blob/master/doc/01-utils.md#logging - // - // (this example requires Monolog: composer require monolog/monolog) - //Longman\TelegramBot\TelegramLog::initialize( - // new Monolog\Logger('telegram_bot', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // ]), - // new Monolog\Logger('telegram_bot_updates', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), - // ]) - //); - - // Set custom Upload and Download paths - //$telegram->setDownloadPath(__DIR__ . '/Download'); - //$telegram->setUploadPath(__DIR__ . '/Upload'); - - // Here you can set some command specific parameters - // e.g. Google geocode/timezone api key for /date command - //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); - - // Requests Limiter (tries to prevent reaching Telegram API limits) - $telegram->enableLimiter(); + /** + * Check `hook.php` for configuration code to be added here. + */ // Handle telegram getUpdates request $server_response = $telegram->handleGetUpdates(); if ($server_response->isOk()) { $update_count = count($server_response->getResult()); - echo date('Y-m-d H:i:s', time()) . ' - Processed ' . $update_count . ' updates'; + echo date('Y-m-d H:i:s') . ' - Processed ' . $update_count . ' updates'; } else { - echo date('Y-m-d H:i:s', time()) . ' - Failed to fetch updates' . PHP_EOL; + echo date('Y-m-d H:i:s') . ' - Failed to fetch updates' . PHP_EOL; echo $server_response->printError(); } + } catch (Longman\TelegramBot\Exception\TelegramException $e) { - echo $e->getMessage(); // Log telegram errors Longman\TelegramBot\TelegramLog::error($e); + + // Uncomment this to output any errors (ONLY FOR DEVELOPMENT!) + // echo $e; } catch (Longman\TelegramBot\Exception\TelegramLogException $e) { - // Catch log initialisation errors - echo $e->getMessage(); + // Uncomment this to output log initialisation errors (ONLY FOR DEVELOPMENT!) + // echo $e; } diff --git a/hook.php b/hook.php index f46018d..4c70f06 100644 --- a/hook.php +++ b/hook.php @@ -11,89 +11,68 @@ */ /** - * README - * This configuration file is intended to run the bot with the webhook method. - * Uncommented parameters must be filled + * This configuration file is used to run the bot with the webhook method. * * Please note that if you open this file with your browser you'll get the "Input is empty!" Exception. - * This is a normal behaviour because this address has to be reached only by the Telegram servers. + * This is perfectly normal and expected, because the hook URL has to be reached only by the Telegram servers. */ // Load composer require_once __DIR__ . '/vendor/autoload.php'; -// Add you bot's API key and name -$bot_api_key = 'your:bot_api_key'; -$bot_username = 'username_bot'; - -// Define all IDs of admin users in this array (leave as empty array if not used) -$admin_users = [ -// 123, -]; - -// Define all paths for your custom commands in this array (leave as empty array if not used) -$commands_paths = [ - __DIR__ . '/Commands/', -]; - -// Enter your MySQL database credentials -//$mysql_credentials = [ -// 'host' => 'localhost', -// 'user' => 'dbuser', -// 'password' => 'dbpass', -// 'database' => 'dbname', -//]; +// Load all configuration options +/** @var array $config */ +$config = require __DIR__ . '/config.php'; try { // Create Telegram API object - $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); - - // Add commands paths containing your custom commands - $telegram->addCommandsPaths($commands_paths); + $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']); // Enable admin users - $telegram->enableAdmins($admin_users); + $telegram->enableAdmins($config['admins']); + + // Add commands paths containing your custom commands + $telegram->addCommandsPaths($config['commands']['paths']); - // Enable MySQL - //$telegram->enableMySql($mysql_credentials); + // Enable MySQL if required + // $telegram->enableMySql($config['mysql']); // Logging (Error, Debug and Raw Updates) // https://github.com/php-telegram-bot/core/blob/master/doc/01-utils.md#logging // // (this example requires Monolog: composer require monolog/monolog) - //Longman\TelegramBot\TelegramLog::initialize( + // Longman\TelegramBot\TelegramLog::initialize( // new Monolog\Logger('telegram_bot', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_debug.log", Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_error.log", Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler($config['logging']['debug']", Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler($config['logging']['error']", Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), // ]), // new Monolog\Logger('telegram_bot_updates', [ - // (new Monolog\Handler\StreamHandler(__DIR__ . "/{$bot_username}_update.log", Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + // (new Monolog\Handler\StreamHandler($config['logging']['update']", Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), // ]) - //); + // ); - // Set custom Upload and Download paths - //$telegram->setDownloadPath(__DIR__ . '/Download'); - //$telegram->setUploadPath(__DIR__ . '/Upload'); + // Set custom Download and Upload paths + // $telegram->setDownloadPath($config['paths']['download']); + // $telegram->setUploadPath($config['paths']['upload']); - // Here you can set some command specific parameters - // - Google geocode/timezone API key for /date command - // $telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); - // - Payment Provider Token for /payment command. - // $telegram->setCommandConfig('payment', ['payment_provider_token' => 'your_payment_provider_token_here']); + // Load all command-specific configurations + // foreach ($config['commands']['configs'] as $command_name => $command_config) { + // $telegram->setCommandConfig($command_name, $command_config); + // } // Requests Limiter (tries to prevent reaching Telegram API limits) - $telegram->enableLimiter(); + $telegram->enableLimiter($config['limiter']); // Handle telegram webhook request $telegram->handle(); } catch (Longman\TelegramBot\Exception\TelegramException $e) { - // Silence is golden! - //echo $e; // Log telegram errors Longman\TelegramBot\TelegramLog::error($e); + + // Uncomment this to output any errors (ONLY FOR DEVELOPMENT!) + // echo $e; } catch (Longman\TelegramBot\Exception\TelegramLogException $e) { - // Silence is golden! - // Uncomment this to catch log initialisation errors - //echo $e; + // Uncomment this to output log initialisation errors (ONLY FOR DEVELOPMENT!) + // echo $e; } diff --git a/manager.php b/manager.php index e901471..06e7ed5 100644 --- a/manager.php +++ b/manager.php @@ -11,9 +11,7 @@ */ /** - * README - * This configuration file is intended to be used as the main script for the PHP Telegram Bot Manager. - * Uncommented parameters must be filled + * This configuration file is used as the main script for the PHP Telegram Bot Manager. * * For the full list of options, go to: * https://github.com/php-telegram-bot/telegram-bot-manager#set-extra-bot-parameters @@ -22,81 +20,23 @@ // Load composer require_once __DIR__ . '/vendor/autoload.php'; -// Add you bot's username (also to be used for log file names) -$bot_username = 'username_bot'; // Without "@" +// Load all configuration options +/** @var array $config */ +$config = require __DIR__ . '/config.php'; try { - $bot = new TelegramBot\TelegramBotManager\BotManager([ - // Add you bot's API key and name - 'api_key' => 'your:bot_api_key', - 'bot_username' => $bot_username, - - // Secret key required to access the webhook - 'secret' => 'super_secret', - - //'webhook' => [ - // // When using webhook, this needs to be uncommented and defined - // 'url' => 'https://your-domain/path/to/manager.php', - // // Use self-signed certificate - // 'certificate' => __DIR__ . '/server.crt', - // // Limit maximum number of connections - // 'max_connections' => 5, - //], - - //'commands' => [ - // // Define all paths for your custom commands - // 'paths' => [ - // __DIR__ . '/Commands', - // ], - // // Here you can set some command specific parameters - // 'configs' => [ - // - Google geocode/timezone API key for /date command - // 'date' => ['google_api_key' => 'your_google_api_key_here'], - // - Payment Provider Token for /payment command. - // 'payment' => ['payment_provider_token' => 'your_payment_provider_token_here'], - // ], - //], - - // Define all IDs of admin users - //'admins' => [ - // 123, - //], - - // Enter your MySQL database credentials - //'mysql' => [ - // 'host' => 'localhost', - // 'user' => 'dbuser', - // 'password' => 'dbpass', - // 'database' => 'dbname', - //], - - // Logging (Error, Debug and Raw Updates) - //'logging' => [ - // 'debug' => __DIR__ . "/{$bot_username}_debug.log", - // 'error' => __DIR__ . "/{$bot_username}_error.log", - // 'update' => __DIR__ . "/{$bot_username}_update.log", - //], - - // Set custom Upload and Download paths - //'paths' => [ - // 'download' => __DIR__ . '/Download', - // 'upload' => __DIR__ . '/Upload', - //], - - // Requests Limiter (tries to prevent reaching Telegram API limits) - 'limiter' => ['enabled' => true], - ]); + $bot = new TelegramBot\TelegramBotManager\BotManager($config); // Run the bot! $bot->run(); } catch (Longman\TelegramBot\Exception\TelegramException $e) { - // Silence is golden! - //echo $e; // Log telegram errors Longman\TelegramBot\TelegramLog::error($e); + + // Uncomment this to output any errors (ONLY FOR DEVELOPMENT!) + // echo $e; } catch (Longman\TelegramBot\Exception\TelegramLogException $e) { - // Silence is golden! - // Uncomment this to catch log initialisation errors - //echo $e; + // Uncomment this to output log initialisation errors (ONLY FOR DEVELOPMENT!) + // echo $e; } diff --git a/set.php b/set.php index 6d80382..6668836 100644 --- a/set.php +++ b/set.php @@ -11,34 +11,32 @@ */ /** - * README - * This file is intended to set the webhook. - * Uncommented parameters must be filled + * This file is used to set the webhook. */ // Load composer require_once __DIR__ . '/vendor/autoload.php'; -// Add you bot's API key and name -$bot_api_key = 'your:bot_api_key'; -$bot_username = 'username_bot'; - -// Define the URL to your hook.php file -$hook_url = 'https://your-domain/path/to/hook.php'; +// Load all configuration options +/** @var array $config */ +$config = require __DIR__ . '/config.php'; try { // Create Telegram API object - $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); + $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']); + + /** + * REMEMBER to define the URL to your hook.php file in: + * config.php: ['webhook']['url'] => 'https://your-domain/path/to/hook.php' + */ - // Set webhook - $result = $telegram->setWebhook($hook_url); + // Set the webhook + $result = $telegram->setWebhook($config['webhook']['url']); // To use a self-signed certificate, use this line instead - //$result = $telegram->setWebhook($hook_url, ['certificate' => $certificate_path]); + // $result = $telegram->setWebhook($config['webhook']['url'], ['certificate' => $config['webhook']['certificate']]); - if ($result->isOk()) { - echo $result->getDescription(); - } + echo $result->getDescription(); } catch (Longman\TelegramBot\Exception\TelegramException $e) { echo $e->getMessage(); } diff --git a/unset.php b/unset.php index 985de6c..02d52e9 100644 --- a/unset.php +++ b/unset.php @@ -11,28 +11,24 @@ */ /** - * README - * This file is intended to unset the webhook. - * Uncommented parameters must be filled + * This file is used to unset / delete the webhook. */ // Load composer require_once __DIR__ . '/vendor/autoload.php'; -// Add you bot's API key and name -$bot_api_key = 'your:bot_api_key'; -$bot_username = 'username_bot'; +// Load all configuration options +/** @var array $config */ +$config = require __DIR__ . '/config.php'; try { // Create Telegram API object - $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); + $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']); - // Delete webhook + // Unset / delete the webhook $result = $telegram->deleteWebhook(); - if ($result->isOk()) { - echo $result->getDescription(); - } + echo $result->getDescription(); } catch (Longman\TelegramBot\Exception\TelegramException $e) { echo $e->getMessage(); } From 7766bb496f704a5ba9587c83a78a64e079beb969 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Mon, 13 Jul 2020 13:57:47 +0200 Subject: [PATCH 26/43] Major overhaul of the example commands, PHP 7.2+ ready --- Commands/CallbackqueryCommand.php | 43 +++++---- Commands/CancelCommand.php | 60 ++++++------- Commands/ChannelchatcreatedCommand.php | 52 ----------- Commands/ChannelpostCommand.php | 21 ++--- Commands/ChoseninlineresultCommand.php | 27 +++--- Commands/DateCommand.php | 43 ++++----- Commands/DeletechatphotoCommand.php | 52 ----------- Commands/EchoCommand.php | 34 ++++--- Commands/EditedchannelpostCommand.php | 21 ++--- Commands/EditedmessageCommand.php | 14 +-- Commands/EditmessageCommand.php | 4 +- Commands/ForcereplyCommand.php | 4 +- Commands/GenericCommand.php | 4 +- Commands/GenericmessageCommand.php | 66 +++++++++++--- Commands/GroupchatcreatedCommand.php | 52 ----------- Commands/HelpCommand.php | 74 ++++++++------- Commands/HidekeyboardCommand.php | 31 +++---- Commands/ImageCommand.php | 68 ++++++++------ Commands/InlinekeyboardCommand.php | 42 ++++----- Commands/InlinequeryCommand.php | 89 +++++++++++-------- Commands/KeyboardCommand.php | 48 +++++----- Commands/LeftchatmemberCommand.php | 30 ++++--- Commands/MarkdownCommand.php | 41 ++++----- Commands/MigratefromchatidCommand.php | 52 ----------- Commands/MigratetochatidCommand.php | 52 ----------- Commands/NewchatmembersCommand.php | 47 +++++----- Commands/NewchatphotoCommand.php | 52 ----------- Commands/NewchattitleCommand.php | 52 ----------- Commands/Payments/GenericmessageCommand.php | 9 +- Commands/Payments/PaymentCommand.php | 12 +-- Commands/Payments/PrecheckoutqueryCommand.php | 9 +- Commands/Payments/ShippingqueryCommand.php | 7 +- Commands/PinnedmessageCommand.php | 52 ----------- Commands/SlapCommand.php | 40 ++++----- Commands/StartCommand.php | 43 ++++----- Commands/SupergroupchatcreatedCommand.php | 52 ----------- Commands/SurveyCommand.php | 78 ++++++++-------- Commands/UploadCommand.php | 64 +++++++++---- Commands/WeatherCommand.php | 71 +++++++-------- Commands/WhoamiCommand.php | 70 ++++++++------- config.example.php | 6 +- 41 files changed, 655 insertions(+), 1033 deletions(-) delete mode 100644 Commands/ChannelchatcreatedCommand.php delete mode 100644 Commands/DeletechatphotoCommand.php delete mode 100644 Commands/GroupchatcreatedCommand.php delete mode 100644 Commands/MigratefromchatidCommand.php delete mode 100644 Commands/MigratetochatidCommand.php delete mode 100644 Commands/NewchatphotoCommand.php delete mode 100644 Commands/NewchattitleCommand.php delete mode 100644 Commands/PinnedmessageCommand.php delete mode 100644 Commands/SupergroupchatcreatedCommand.php diff --git a/Commands/CallbackqueryCommand.php b/Commands/CallbackqueryCommand.php index 41de951..85bf4a0 100644 --- a/Commands/CallbackqueryCommand.php +++ b/Commands/CallbackqueryCommand.php @@ -10,11 +10,6 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\SystemCommands; - -use Longman\TelegramBot\Commands\SystemCommand; -use Longman\TelegramBot\Request; - /** * Callback query command * @@ -22,6 +17,12 @@ * * @see InlinekeyboardCommand.php */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; + class CallbackqueryCommand extends SystemCommand { /** @@ -32,32 +33,28 @@ class CallbackqueryCommand extends SystemCommand /** * @var string */ - protected $description = 'Reply to callback query'; + protected $description = 'Handle the callback query'; /** * @var string */ - protected $version = '1.1.1'; + protected $version = '1.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { - $callback_query = $this->getCallbackQuery(); - $callback_query_id = $callback_query->getId(); - $callback_data = $callback_query->getData(); - - $data = [ - 'callback_query_id' => $callback_query_id, - 'text' => 'Hello World!', - 'show_alert' => $callback_data === 'thumb up', - 'cache_time' => 5, - ]; - - return Request::answerCallbackQuery($data); + // Callback query data can be fetched and handled accordingly. + $callback_query = $this->getCallbackQuery(); + $callback_data = $callback_query->getData(); + + return $callback_query->answer([ + 'text' => 'Hello World!', + 'show_alert' => $callback_data === 'thumb up', + 'cache_time' => 5, + ]); } } diff --git a/Commands/CancelCommand.php b/Commands/CancelCommand.php index ea5632a..2f139f1 100644 --- a/Commands/CancelCommand.php +++ b/Commands/CancelCommand.php @@ -10,20 +10,23 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\UserCommands; - -use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Conversation; -use Longman\TelegramBot\Entities\Keyboard; -use Longman\TelegramBot\Request; - /** * User "/cancel" command * * This command cancels the currently active conversation and * returns a message to let the user know which conversation it was. + * * If no conversation is active, the returned message says so. */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Conversation; +use Longman\TelegramBot\Entities\Keyboard; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; + class CancelCommand extends UserCommand { /** @@ -44,7 +47,7 @@ class CancelCommand extends UserCommand /** * @var string */ - protected $version = '0.2.1'; + protected $version = '0.3.0'; /** * @var bool @@ -52,12 +55,22 @@ class CancelCommand extends UserCommand protected $need_mysql = true; /** - * Command execute method + * Main command execution if no DB connection is available * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @throws TelegramException */ - public function execute() + public function executeNoDb(): ServerResponse + { + return $this->removeKeyboard('Nothing to cancel.'); + } + + /** + * Main command execution + * + * @return ServerResponse + * @throws TelegramException + */ + public function execute(): ServerResponse { $text = 'No active conversation!'; @@ -76,30 +89,17 @@ public function execute() } /** - * Remove the keyboard and output a text + * Remove the keyboard and output a text. * * @param string $text * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - private function removeKeyboard($text) + private function removeKeyboard($text): ServerResponse { - return Request::sendMessage([ + return $this->replyToChat($text, [ 'reply_markup' => Keyboard::remove(['selective' => true]), - 'chat_id' => $this->getMessage()->getChat()->getId(), - 'text' => $text, ]); } - - /** - * Command execute method if MySQL is required but not available - * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException - */ - public function executeNoDb() - { - return $this->removeKeyboard('Nothing to cancel.'); - } } diff --git a/Commands/ChannelchatcreatedCommand.php b/Commands/ChannelchatcreatedCommand.php deleted file mode 100644 index 4339119..0000000 --- a/Commands/ChannelchatcreatedCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$channel_chat_created = $message->getChannelChatCreated(); - - return parent::execute(); - } -} diff --git a/Commands/ChannelpostCommand.php b/Commands/ChannelpostCommand.php index 0391e6e..aafa2d3 100644 --- a/Commands/ChannelpostCommand.php +++ b/Commands/ChannelpostCommand.php @@ -10,15 +10,17 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\SystemCommands; - -use Longman\TelegramBot\Commands\SystemCommand; - /** * Channel post command * * Gets executed when a new post is created in a channel. */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; + class ChannelpostCommand extends SystemCommand { /** @@ -34,17 +36,16 @@ class ChannelpostCommand extends SystemCommand /** * @var string */ - protected $version = '1.0.0'; + protected $version = '1.1.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { - //$channel_post = $this->getUpdate()->getChannelPost(); + // $channel_post = $this->getChannelPost(); return parent::execute(); } diff --git a/Commands/ChoseninlineresultCommand.php b/Commands/ChoseninlineresultCommand.php index 3feaa0b..662390c 100644 --- a/Commands/ChoseninlineresultCommand.php +++ b/Commands/ChoseninlineresultCommand.php @@ -10,15 +10,17 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\SystemCommands; - -use Longman\TelegramBot\Commands\SystemCommand; - /** * Chosen inline result command * * Gets executed when an item from an inline query is selected. */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; + class ChoseninlineresultCommand extends SystemCommand { /** @@ -29,24 +31,23 @@ class ChoseninlineresultCommand extends SystemCommand /** * @var string */ - protected $description = 'Chosen result query'; + protected $description = 'Handle the chosen inline result'; /** * @var string */ - protected $version = '1.1.1'; + protected $version = '1.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { - //Information about chosen result is returned - //$inline_query = $this->getChosenInlineResult(); - //$query = $inline_query->getQuery(); + // Information about the chosen result is returned. + // $inline_query = $this->getChosenInlineResult(); + // $query = $inline_query->getQuery(); return parent::execute(); } diff --git a/Commands/DateCommand.php b/Commands/DateCommand.php index e55c9e1..de3d121 100644 --- a/Commands/DateCommand.php +++ b/Commands/DateCommand.php @@ -10,6 +10,16 @@ * file that was distributed with this source code. */ +/** + * User "/date" command + * + * Shows the date and time of the location passed as the parameter. + * + * A Google API key is required for this command! + * You can be set in your config.php file: + * ['commands']['configs']['date'] => ['google_api_key' => 'your_google_api_key_here'] + */ + namespace Longman\TelegramBot\Commands\UserCommands; use GuzzleHttp\Client; @@ -18,14 +28,6 @@ use Longman\TelegramBot\Request; use Longman\TelegramBot\TelegramLog; -/** - * User "/date" command - * - * Shows the date and time of the location passed as the parameter. - * - * A Google API key is required for this command, and it can be set in your hook file: - * $telegram->setCommandConfig('date', ['google_api_key' => 'your_api_key']); - */ class DateCommand extends UserCommand { /** @@ -46,12 +48,12 @@ class DateCommand extends UserCommand /** * @var string */ - protected $version = '1.4.1'; + protected $version = '1.5.0'; /** * Guzzle Client object * - * @var \GuzzleHttp\Client + * @var Client */ private $client; @@ -83,7 +85,7 @@ class DateCommand extends UserCommand * * @return array */ - private function getCoordinates($location) + private function getCoordinates($location): array { $path = 'geocode/json'; $query = ['address' => urlencode($location)]; @@ -120,8 +122,9 @@ private function getCoordinates($location) * @param string $lng * * @return array + * @throws \Exception */ - private function getDate($lat, $lng) + private function getDate($lat, $lng): array { $path = 'timezone/json'; @@ -161,7 +164,7 @@ private function getDate($lat, $lng) * * @return array */ - private function validateResponseData($data) + private function validateResponseData($data): array { if (empty($data)) { return []; @@ -185,20 +188,20 @@ private function validateResponseData($data) * @param string $location * * @return string - * @throws \Longman\TelegramBot\Exception\TelegramException + * @throws \Exception */ - private function getFormattedDate($location) + private function getFormattedDate($location): string { if ($location === null || $location === '') { return 'The time in nowhere is never'; } - list($lat, $lng) = $this->getCoordinates($location); + [$lat, $lng] = $this->getCoordinates($location); if (empty($lat) || empty($lng)) { return 'It seems that in "' . $location . '" they do not have a concept of time.'; } - list($local_time, $timezone_id) = $this->getDate($lat, $lng); + [$local_time, $timezone_id] = $this->getDate($lat, $lng); $date_utc = new \DateTimeImmutable(gmdate('Y-m-d H:i:s', $local_time), new \DateTimeZone($timezone_id)); @@ -206,14 +209,14 @@ private function getFormattedDate($location) } /** - * Command execute method + * Main command execution * * @return \Longman\TelegramBot\Entities\ServerResponse * @throws \Longman\TelegramBot\Exception\TelegramException */ - public function execute() + public function execute(): \Longman\TelegramBot\Entities\ServerResponse { - //First we set up the necessary member variables. +//First we set up the necessary member variables. $this->client = new Client(['base_uri' => $this->google_api_base_uri]); if (($this->google_api_key = trim($this->getConfig('google_api_key'))) === '') { $this->google_api_key = null; diff --git a/Commands/DeletechatphotoCommand.php b/Commands/DeletechatphotoCommand.php deleted file mode 100644 index 52a819d..0000000 --- a/Commands/DeletechatphotoCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$delete_chat_photo = $message->getDeleteChatPhoto(); - - return parent::execute(); - } -} diff --git a/Commands/EchoCommand.php b/Commands/EchoCommand.php index fa6b823..a3b1d5c 100644 --- a/Commands/EchoCommand.php +++ b/Commands/EchoCommand.php @@ -10,16 +10,18 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\UserCommands; - -use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Request; - /** * User "/echo" command * * Simply echo the input back to the user. */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; + class EchoCommand extends UserCommand { /** @@ -40,29 +42,23 @@ class EchoCommand extends UserCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); - $chat_id = $message->getChat()->getId(); - $text = trim($message->getText(true)); + $text = $message->getText(true); if ($text === '') { - $text = 'Command usage: ' . $this->getUsage(); + return $this->replyToChat('Command usage: ' . $this->getUsage()); } - $data = [ - 'chat_id' => $chat_id, - 'text' => $text, - ]; - - return Request::sendMessage($data); + return $this->replyToChat($text); } } diff --git a/Commands/EditedchannelpostCommand.php b/Commands/EditedchannelpostCommand.php index dd9d1db..6d6e08c 100644 --- a/Commands/EditedchannelpostCommand.php +++ b/Commands/EditedchannelpostCommand.php @@ -10,15 +10,17 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\SystemCommands; - -use Longman\TelegramBot\Commands\SystemCommand; - /** * Edited channel post command * * Gets executed when a post in a channel is edited. */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; + class EditedchannelpostCommand extends SystemCommand { /** @@ -34,17 +36,16 @@ class EditedchannelpostCommand extends SystemCommand /** * @var string */ - protected $version = '1.0.0'; + protected $version = '1.1.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { - //$edited_channel_post = $this->getUpdate()->getEditedChannelPost(); + // $edited_channel_post = $this->getEditedChannelPost(); return parent::execute(); } diff --git a/Commands/EditedmessageCommand.php b/Commands/EditedmessageCommand.php index 531557b..ccbfb2d 100644 --- a/Commands/EditedmessageCommand.php +++ b/Commands/EditedmessageCommand.php @@ -13,6 +13,7 @@ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; /** * Edited message command @@ -29,22 +30,21 @@ class EditedmessageCommand extends SystemCommand /** * @var string */ - protected $description = 'User edited message'; + protected $description = 'Handle edited message'; /** * @var string */ - protected $version = '1.1.1'; + protected $version = '1.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { - //$edited_message = $this->getEditedMessage(); + // $edited_message = $this->getEditedMessage(); return parent::execute(); } diff --git a/Commands/EditmessageCommand.php b/Commands/EditmessageCommand.php index cd1b270..3c3ee1b 100644 --- a/Commands/EditmessageCommand.php +++ b/Commands/EditmessageCommand.php @@ -43,12 +43,12 @@ class EditmessageCommand extends UserCommand protected $version = '1.1.0'; /** - * Command execute method + * Main command execution * * @return \Longman\TelegramBot\Entities\ServerResponse * @throws \Longman\TelegramBot\Exception\TelegramException */ - public function execute() + public function execute(): \Longman\TelegramBot\Entities\ServerResponse { $message = $this->getMessage(); $chat_id = $message->getChat()->getId(); diff --git a/Commands/ForcereplyCommand.php b/Commands/ForcereplyCommand.php index a632e63..59cc662 100644 --- a/Commands/ForcereplyCommand.php +++ b/Commands/ForcereplyCommand.php @@ -44,12 +44,12 @@ class ForcereplyCommand extends UserCommand protected $version = '0.1.0'; /** - * Command execute method + * Main command execution * * @return \Longman\TelegramBot\Entities\ServerResponse * @throws \Longman\TelegramBot\Exception\TelegramException */ - public function execute() + public function execute(): \Longman\TelegramBot\Entities\ServerResponse { $chat_id = $this->getMessage()->getChat()->getId(); diff --git a/Commands/GenericCommand.php b/Commands/GenericCommand.php index 8caedef..808bf52 100644 --- a/Commands/GenericCommand.php +++ b/Commands/GenericCommand.php @@ -38,12 +38,12 @@ class GenericCommand extends SystemCommand protected $version = '1.1.0'; /** - * Command execute method + * Main command execution * * @return \Longman\TelegramBot\Entities\ServerResponse * @throws \Longman\TelegramBot\Exception\TelegramException */ - public function execute() + public function execute(): \Longman\TelegramBot\Entities\ServerResponse { $message = $this->getMessage(); diff --git a/Commands/GenericmessageCommand.php b/Commands/GenericmessageCommand.php index c7dc1be..c24c61a 100644 --- a/Commands/GenericmessageCommand.php +++ b/Commands/GenericmessageCommand.php @@ -10,17 +10,18 @@ * file that was distributed with this source code. */ +/** + * Generic message command + * + * Gets executed when any type of message is sent. + */ + namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Conversation; use Longman\TelegramBot\Request; -/** - * Generic message command - * - * Gets executed when any type of message is sent. - */ class GenericmessageCommand extends SystemCommand { /** @@ -47,33 +48,72 @@ class GenericmessageCommand extends SystemCommand * Command execute method if MySQL is required but not available * * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException */ - public function executeNoDb() + public function executeNoDb(): \Longman\TelegramBot\Entities\ServerResponse { // Do nothing return Request::emptyResponse(); } /** - * Command execute method + * Main command execution * * @return \Longman\TelegramBot\Entities\ServerResponse * @throws \Longman\TelegramBot\Exception\TelegramException */ - public function execute() + public function execute(): \Longman\TelegramBot\Entities\ServerResponse { - //If a conversation is busy, execute the conversation command after handling the message + $message = $this->getMessage(); + + // If a conversation is busy, execute the conversation command after handling the message. $conversation = new Conversation( - $this->getMessage()->getFrom()->getId(), - $this->getMessage()->getChat()->getId() + $message->getFrom()->getId(), + $message->getChat()->getId() ); - //Fetch conversation command if it exists and execute it + // Fetch conversation command if it exists and execute it. if ($conversation->exists() && ($command = $conversation->getCommand())) { return $this->telegram->executeCommand($command); } + /** + * Here, any service messages can be caught and handled. + * + * Service messages are: + * delete_chat_photo - the chat photo was deleted + * group_chat_created - the group has been created + * supergroup_chat_created - the supergroup has been created + * channel_chat_created - the channel has been created + * successful_payment - information about the payment + */ + + /** + * For special message commands, you need to call them from here. + * + * // Handle new chat members + * if ($message->getNewChatMembers()) { + * return $this->getTelegram()->executeCommand('newchatmembers'); + * } + * + * // Handle left chat members + * if ($message->getLeftChatMember()) { + * return $this->getTelegram()->executeCommand('leftchatmember'); + * } + * + * // Handle group actions + * if ($new_chat_photo = $message->getNewChatPhoto()) { + * // Whatever... + * } + * if ($new_chat_title = $message->getNewChatTitle()) { + * // Whatever... + * } + * + * // Message pinning + * if ($pinned_message = $message->getPinnedMessage()) { + * // Whatever... + * } + */ + return Request::emptyResponse(); } } diff --git a/Commands/GroupchatcreatedCommand.php b/Commands/GroupchatcreatedCommand.php deleted file mode 100644 index c4423e5..0000000 --- a/Commands/GroupchatcreatedCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$group_chat_created = $message->getGroupChatCreated(); - - return parent::execute(); - } -} diff --git a/Commands/HelpCommand.php b/Commands/HelpCommand.php index c8fb9cf..7cc99c6 100644 --- a/Commands/HelpCommand.php +++ b/Commands/HelpCommand.php @@ -10,17 +10,19 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\UserCommands; - -use Longman\TelegramBot\Commands\Command; -use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Request; - /** * User "/help" command * * Command that lists all available commands and displays them in User and Admin sections. */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\Command; +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; + class HelpCommand extends UserCommand { /** @@ -41,50 +43,48 @@ class HelpCommand extends UserCommand /** * @var string */ - protected $version = '1.3.0'; + protected $version = '1.4.0'; /** - * @inheritdoc + * Main command execution + * + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); - $chat_id = $message->getChat()->getId(); $command_str = trim($message->getText(true)); // Admin commands shouldn't be shown in group chats $safe_to_show = $message->getChat()->isPrivateChat(); - $data = [ - 'chat_id' => $chat_id, - 'parse_mode' => 'markdown', - ]; - - list($all_commands, $user_commands, $admin_commands) = $this->getUserAdminCommands(); + [$all_commands, $user_commands, $admin_commands] = $this->getUserAndAdminCommands(); // If no command parameter is passed, show the list. if ($command_str === '') { - $data['text'] = '*Commands List*:' . PHP_EOL; + $text = '*Commands List*:' . PHP_EOL; foreach ($user_commands as $user_command) { - $data['text'] .= '/' . $user_command->getName() . ' - ' . $user_command->getDescription() . PHP_EOL; + $text .= '/' . $user_command->getName() . ' - ' . $user_command->getDescription() . PHP_EOL; } if ($safe_to_show && count($admin_commands) > 0) { - $data['text'] .= PHP_EOL . '*Admin Commands List*:' . PHP_EOL; + $text .= PHP_EOL . '*Admin Commands List*:' . PHP_EOL; foreach ($admin_commands as $admin_command) { - $data['text'] .= '/' . $admin_command->getName() . ' - ' . $admin_command->getDescription() . PHP_EOL; + $text .= '/' . $admin_command->getName() . ' - ' . $admin_command->getDescription() . PHP_EOL; } } - $data['text'] .= PHP_EOL . 'For exact command help type: /help '; + $text .= PHP_EOL . 'For exact command help type: /help '; - return Request::sendMessage($data); + return $this->replyToChat($text, ['parse_mode' => 'markdown']); } $command_str = str_replace('/', '', $command_str); if (isset($all_commands[$command_str]) && ($safe_to_show || !$all_commands[$command_str]->isAdminCommand())) { - $command = $all_commands[$command_str]; - $data['text'] = sprintf( + $command = $all_commands[$command_str]; + + return $this->replyToChat(sprintf( 'Command: %s (v%s)' . PHP_EOL . 'Description: %s' . PHP_EOL . 'Usage: %s', @@ -92,37 +92,35 @@ public function execute() $command->getVersion(), $command->getDescription(), $command->getUsage() - ); - - return Request::sendMessage($data); + ), ['parse_mode' => 'markdown']); } - $data['text'] = 'No help available: Command /' . $command_str . ' not found'; - - return Request::sendMessage($data); + return $this->replyToChat('No help available: Command `/' . $command_str . '` not found', ['parse_mode' => 'markdown']); } /** * Get all available User and Admin commands to display in the help list. * * @return Command[][] + * @throws TelegramException */ - protected function getUserAdminCommands() + protected function getUserAndAdminCommands(): array { + /** @var Command[] $all_commands */ + $all_commands = $this->telegram->getCommandsList(); + // Only get enabled Admin and User commands that are allowed to be shown. - /** @var Command[] $commands */ - $commands = array_filter($this->telegram->getCommandsList(), function ($command) { - /** @var Command $command */ + $commands = array_filter($all_commands, function ($command): bool { return !$command->isSystemCommand() && $command->showInHelp() && $command->isEnabled(); }); - $user_commands = array_filter($commands, function ($command) { - /** @var Command $command */ + // Filter out all User commands + $user_commands = array_filter($commands, function ($command): bool { return $command->isUserCommand(); }); - $admin_commands = array_filter($commands, function ($command) { - /** @var Command $command */ + // Filter out all Admin commands + $admin_commands = array_filter($commands, function ($command): bool { return $command->isAdminCommand(); }); diff --git a/Commands/HidekeyboardCommand.php b/Commands/HidekeyboardCommand.php index cd0e2c2..c949db1 100644 --- a/Commands/HidekeyboardCommand.php +++ b/Commands/HidekeyboardCommand.php @@ -12,15 +12,17 @@ namespace Longman\TelegramBot\Commands\UserCommands; -use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Entities\Keyboard; -use Longman\TelegramBot\Request; - /** * User "/hidekeyboard" command * * Command to hide the keyboard. */ + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\Keyboard; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; + class HidekeyboardCommand extends UserCommand { /** @@ -41,24 +43,19 @@ class HidekeyboardCommand extends UserCommand /** * @var string */ - protected $version = '0.1.0'; + protected $version = '0.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { - $chat_id = $this->getMessage()->getChat()->getId(); - - $data = [ - 'chat_id' => $chat_id, - 'text' => 'Keyboard Hidden', + // Remove the keyboard and send a message. + return $this->replyToChat('Keyboard Hidden', [ 'reply_markup' => Keyboard::remove(), - ]; - - return Request::sendMessage($data); + ]); } } diff --git a/Commands/ImageCommand.php b/Commands/ImageCommand.php index 0f2767e..4968f2b 100644 --- a/Commands/ImageCommand.php +++ b/Commands/ImageCommand.php @@ -10,16 +10,19 @@ * file that was distributed with this source code. */ +/** + * User "/image" command + * + * Randomly fetch any uploaded image from the Uploads path and send it to the user. + */ + namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; -/** - * User "/image" command - * - * Fetch any uploaded image from the Uploads path. - */ class ImageCommand extends UserCommand { /** @@ -30,7 +33,7 @@ class ImageCommand extends UserCommand /** * @var string */ - protected $description = 'Send Image'; + protected $description = 'Randomly fetch any uploaded image'; /** * @var string @@ -40,42 +43,43 @@ class ImageCommand extends UserCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); // Use any extra parameters as the caption text. $caption = trim($message->getText(true)); - // Get a random picture from the telegram->getUploadPath() directory. - $random_image = $this->GetRandomImagePath($this->telegram->getUploadPath()); - - $data = [ - 'chat_id' => $message->getChat()->getId(), - ]; + // Make sure the Upload path has been defined and exists. + $upload_path = $this->telegram->getUploadPath(); + if (!is_dir($upload_path)) { + return $this->replyToChat('Upload path has not been defined or does not exist.'); + } - if (!$random_image) { - $data['text'] = 'No image found!'; - return Request::sendMessage($data); + // Get a random picture from the Upload path. + $random_image = $this->getRandomImagePath($upload_path); + if ('' === $random_image) { + return $this->replyToChat('No image found!'); } // If no caption is set, use the filename. - if ($caption === '') { + if ('' === $caption) { $caption = basename($random_image); } - $data['caption'] = $caption; - $data['photo'] = Request::encodeFile($random_image); - - return Request::sendPhoto($data); + return Request::sendPhoto([ + 'chat_id' => $message->getFrom()->getId(), + 'caption' => $caption, + 'photo' => $random_image, + ]); } /** @@ -85,10 +89,18 @@ public function execute() * * @return string */ - private function GetRandomImagePath($dir) + private function getRandomImagePath($dir): string { - // Slice off the . and .. "directories" - if ($image_list = array_diff(scandir($dir), array('..', '.'))) { + if (!is_dir($dir)) { + return ''; + } + + // Filter the file list to only return images. + $image_list = array_filter(scandir($dir), function ($file) { + $extension = pathinfo($file, PATHINFO_EXTENSION); + return in_array($extension, ['png', 'jpg', 'jpeg', 'gif']); + }); + if (!empty($image_list)) { shuffle($image_list); return $dir . '/' . $image_list[0]; } diff --git a/Commands/InlinekeyboardCommand.php b/Commands/InlinekeyboardCommand.php index bf2466e..3c2c787 100644 --- a/Commands/InlinekeyboardCommand.php +++ b/Commands/InlinekeyboardCommand.php @@ -12,15 +12,19 @@ namespace Longman\TelegramBot\Commands\UserCommands; -use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Entities\InlineKeyboard; -use Longman\TelegramBot\Request; - /** * User "/inlinekeyboard" command * * Display an inline keyboard with a few buttons. + * + * This command requires CallbackqueryCommand to work! */ + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; + class InlinekeyboardCommand extends UserCommand { /** @@ -41,34 +45,26 @@ class InlinekeyboardCommand extends UserCommand /** * @var string */ - protected $version = '0.1.0'; + protected $version = '0.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { - $chat_id = $this->getMessage()->getChat()->getId(); - - $switch_element = mt_rand(0, 9) < 5 ? 'true' : 'false'; - $inline_keyboard = new InlineKeyboard([ - ['text' => 'inline', 'switch_inline_query' => $switch_element], - ['text' => 'inline current chat', 'switch_inline_query_current_chat' => $switch_element], + ['text' => 'Inline Query (current chat)', 'switch_inline_query_current_chat' => 'inline query...'], + ['text' => 'Inline Query (other chat)', 'switch_inline_query' => 'inline query...'], ], [ - ['text' => 'callback', 'callback_data' => 'identifier'], - ['text' => 'open url', 'url' => 'https://github.com/php-telegram-bot/core'], + ['text' => 'Callback', 'callback_data' => 'identifier'], + ['text' => 'Open URL', 'url' => 'https://github.com/php-telegram-bot/example-bot'], ]); - $data = [ - 'chat_id' => $chat_id, - 'text' => 'inline keyboard', + return $this->replyToChat('Inline Keyboard', [ 'reply_markup' => $inline_keyboard, - ]; - - return Request::sendMessage($data); + ]); } } diff --git a/Commands/InlinequeryCommand.php b/Commands/InlinequeryCommand.php index 6a2fc94..63f31c1 100644 --- a/Commands/InlinequeryCommand.php +++ b/Commands/InlinequeryCommand.php @@ -10,18 +10,22 @@ * file that was distributed with this source code. */ +/** + * Inline query command + * + * Command that handles inline queries and returns a list of results. + */ + namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Entities\InlineQuery\InlineQueryResultArticle; +use Longman\TelegramBot\Entities\InlineQuery\InlineQueryResultContact; +use Longman\TelegramBot\Entities\InlineQuery\InlineQueryResultLocation; +use Longman\TelegramBot\Entities\InlineQuery\InlineQueryResultVenue; use Longman\TelegramBot\Entities\InputMessageContent\InputTextMessageContent; -use Longman\TelegramBot\Request; +use Longman\TelegramBot\Entities\ServerResponse; -/** - * Inline query command - * - * Command that handles inline queries. - */ class InlinequeryCommand extends SystemCommand { /** @@ -32,54 +36,65 @@ class InlinequeryCommand extends SystemCommand /** * @var string */ - protected $description = 'Reply to inline query'; + protected $description = 'Handle inline query'; /** * @var string */ - protected $version = '1.1.2'; + protected $version = '1.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { $inline_query = $this->getInlineQuery(); $query = $inline_query->getQuery(); - $data = ['inline_query_id' => $inline_query->getId()]; $results = []; if ($query !== '') { - $articles = [ - [ - 'id' => '001', - 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', - 'description' => 'you enter: ' . $query, - 'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]), - ], - [ - 'id' => '002', - 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', - 'description' => 'you enter: ' . $query, - 'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]), - ], - [ - 'id' => '003', - 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', - 'description' => 'you enter: ' . $query, - 'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]), - ], - ]; + // https://core.telegram.org/bots/api#inlinequeryresultarticle + $results[] = new InlineQueryResultArticle([ + 'id' => '001', + 'title' => 'Simple text using InputTextMessageContent', + 'description' => 'this will return Text', + + // Here you can put any other Input...MessageContent you like. + // It will keep the style of an article, but post the specific message type back to the user. + 'input_message_content' => new InputTextMessageContent([ + 'message_text' => 'The query that got you here: ' . $query, + ]), + ]); + + // https://core.telegram.org/bots/api#inlinequeryresultcontact + $results[] = new InlineQueryResultContact([ + 'id' => '002', + 'phone_number' => '12345678', + 'first_name' => 'Best', + 'last_name' => 'Friend', + ]); + + // https://core.telegram.org/bots/api#inlinequeryresultlocation + $results[] = new InlineQueryResultLocation([ + 'id' => '003', + 'title' => 'The center of the world!', + 'latitude' => 40.866667, + 'longitude' => 34.566667, + ]); - foreach ($articles as $article) { - $results[] = new InlineQueryResultArticle($article); - } + // https://core.telegram.org/bots/api#inlinequeryresultvenue + $results[] = new InlineQueryResultVenue([ + 'id' => '004', + 'title' => 'No-Mans-Land', + 'address' => 'In the middle of Nowhere', + 'latitude' => 33, + 'longitude' => -33, + ]); } - return $this->getInlineQuery()->answer($results, $data); + return $inline_query->answer($results); } } diff --git a/Commands/KeyboardCommand.php b/Commands/KeyboardCommand.php index c428891..2a49c47 100644 --- a/Commands/KeyboardCommand.php +++ b/Commands/KeyboardCommand.php @@ -12,15 +12,18 @@ namespace Longman\TelegramBot\Commands\UserCommands; -use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Entities\Keyboard; -use Longman\TelegramBot\Request; - /** * User "/keyboard" command * * Display a keyboard with a few buttons. */ + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\Keyboard; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; +use Longman\TelegramBot\Request; + class KeyboardCommand extends UserCommand { /** @@ -41,21 +44,20 @@ class KeyboardCommand extends UserCommand /** * @var string */ - protected $version = '0.2.0'; + protected $version = '0.3.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { - //Keyboard examples /** @var Keyboard[] $keyboards */ $keyboards = []; - //Example 0 + // Simple digits $keyboards[] = new Keyboard( ['7', '8', '9'], ['4', '5', '6'], @@ -63,7 +65,7 @@ public function execute() [' ', '0', ' '] ); - //Example 1 + // Digits with operations $keyboards[] = new Keyboard( ['7', '8', '9', '+'], ['4', '5', '6', '-'], @@ -71,35 +73,33 @@ public function execute() [' ', '0', ' ', '/'] ); - //Example 2 + // Short version with 1 button per row $keyboards[] = new Keyboard('A', 'B', 'C'); - //Example 3 + // Some different ways of creating rows and buttons $keyboards[] = new Keyboard( ['text' => 'A'], 'B', ['C', 'D'] ); - //Example 4 (bots version 2.0) + // Buttons to perform Contact or Location sharing $keyboards[] = new Keyboard([ ['text' => 'Send my contact', 'request_contact' => true], ['text' => 'Send my location', 'request_location' => true], ]); - //Return a random keyboard. - $keyboard = $keyboards[mt_rand(0, count($keyboards) - 1)] + // Shuffle our example keyboards + shuffle($keyboards); + + // Return a random keyboard + $keyboard = end($keyboards) ->setResizeKeyboard(true) ->setOneTimeKeyboard(true) ->setSelective(false); - $chat_id = $this->getMessage()->getChat()->getId(); - $data = [ - 'chat_id' => $chat_id, - 'text' => 'Press a Button:', + return $this->replyToChat('Press a Button!', [ 'reply_markup' => $keyboard, - ]; - - return Request::sendMessage($data); + ]); } } diff --git a/Commands/LeftchatmemberCommand.php b/Commands/LeftchatmemberCommand.php index da94d96..af41a2d 100644 --- a/Commands/LeftchatmemberCommand.php +++ b/Commands/LeftchatmemberCommand.php @@ -10,15 +10,21 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\SystemCommands; - -use Longman\TelegramBot\Commands\SystemCommand; - /** * Left chat member command * * Gets executed when a member leaves the chat. + * + * NOTE: This command must be called from GenericmessageCommand.php! + * It is only in a separate command file for easier code maintenance. */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; + class LeftchatmemberCommand extends SystemCommand { /** @@ -34,19 +40,19 @@ class LeftchatmemberCommand extends SystemCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { - //$message = $this->getMessage(); - //$member = $message->getLeftChatMember(); + $message = $this->getMessage(); + $member = $message->getLeftChatMember(); - return parent::execute(); + return $this->replyToChat('Sorry to see you go, ' . $member->getFirstName()); } } diff --git a/Commands/MarkdownCommand.php b/Commands/MarkdownCommand.php index 59acd4a..b004ada 100644 --- a/Commands/MarkdownCommand.php +++ b/Commands/MarkdownCommand.php @@ -10,17 +10,19 @@ * file that was distributed with this source code. */ +/** + * User "/markdown" command + * + * Print some text formatted with markdown. + */ + namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Entities\ReplyKeyboardMarkup; -use Longman\TelegramBot\Request; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; -/** - * User "/markdown" command - * - * Print some markdown text. - */ class MarkdownCommand extends UserCommand { /** @@ -31,7 +33,7 @@ class MarkdownCommand extends UserCommand /** * @var string */ - protected $description = 'Print Markdown text'; + protected $description = 'Print Markdown Text'; /** * @var string @@ -41,31 +43,26 @@ class MarkdownCommand extends UserCommand /** * @var string */ - protected $version = '1.0.1'; + protected $version = '1.1.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { - $message = $this->getMessage(); - $chat_id = $message->getChat()->getId(); + return $this->replyToChat(' +*bold* _italic_ `inline fixed width code` - $data = [ - 'chat_id' => $chat_id, - 'parse_mode' => 'MARKDOWN', - 'text' => '*bold* _italic_ `inline fixed width code` ``` preformatted code block code block ``` -[Best Telegram bot api!!](https://github.com/php-telegram-bot/core) -', - ]; - return Request::sendMessage($data); +[Best Telegram bot api!!](https://github.com/php-telegram-bot/core)', [ + 'parse_mode' => 'markdown', + ]); } } diff --git a/Commands/MigratefromchatidCommand.php b/Commands/MigratefromchatidCommand.php deleted file mode 100644 index 9736157..0000000 --- a/Commands/MigratefromchatidCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$migrate_from_chat_id = $message->getMigrateFromChatId(); - - return parent::execute(); - } -} diff --git a/Commands/MigratetochatidCommand.php b/Commands/MigratetochatidCommand.php deleted file mode 100644 index 6513dcb..0000000 --- a/Commands/MigratetochatidCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$migrate_to_chat_id = $message->getMigrateToChatId(); - - return parent::execute(); - } -} diff --git a/Commands/NewchatmembersCommand.php b/Commands/NewchatmembersCommand.php index 5ffda60..6e37b41 100644 --- a/Commands/NewchatmembersCommand.php +++ b/Commands/NewchatmembersCommand.php @@ -10,14 +10,21 @@ * file that was distributed with this source code. */ +/** + * New chat members command + * + * Gets executed when a new member joins the chat. + * + * NOTE: This command must be called from GenericmessageCommand.php! + * It is only in a separate command file for easier code maintenance. + */ + namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; -use Longman\TelegramBot\Request; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; -/** - * New chat member command - */ class NewchatmembersCommand extends SystemCommand { /** @@ -33,36 +40,28 @@ class NewchatmembersCommand extends SystemCommand /** * @var string */ - protected $version = '1.2.0'; + protected $version = '1.3.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); - - $chat_id = $message->getChat()->getId(); $members = $message->getNewChatMembers(); - $text = 'Hi there!'; - - if (!$message->botAddedInChat()) { - $member_names = []; - foreach ($members as $member) { - $member_names[] = $member->tryMention(); - } - $text = 'Hi ' . implode(', ', $member_names) . '!'; + if ($message->botAddedInChat()) { + return $this->replyToChat('Hi there, you BOT!'); } - $data = [ - 'chat_id' => $chat_id, - 'text' => $text, - ]; + $member_names = []; + foreach ($members as $member) { + $member_names[] = $member->tryMention(); + } - return Request::sendMessage($data); + return $this->replyToChat('Hi ' . implode(', ', $member_names) . '!'); } } diff --git a/Commands/NewchatphotoCommand.php b/Commands/NewchatphotoCommand.php deleted file mode 100644 index 702407c..0000000 --- a/Commands/NewchatphotoCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$new_chat_photo = $message->getNewChatPhoto(); - - return parent::execute(); - } -} diff --git a/Commands/NewchattitleCommand.php b/Commands/NewchattitleCommand.php deleted file mode 100644 index 19d04a9..0000000 --- a/Commands/NewchattitleCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$new_chat_title = $message->getNewChatTitle(); - - return parent::execute(); - } -} diff --git a/Commands/Payments/GenericmessageCommand.php b/Commands/Payments/GenericmessageCommand.php index e33a5a2..9ecd0ac 100644 --- a/Commands/Payments/GenericmessageCommand.php +++ b/Commands/Payments/GenericmessageCommand.php @@ -19,6 +19,7 @@ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Request; class GenericmessageCommand extends SystemCommand @@ -39,14 +40,16 @@ class GenericmessageCommand extends SystemCommand protected $version = '0.1.0'; /** - * @inheritDoc + * Main command execution + * + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); $user_id = $message->getFrom()->getId(); - // Handle successful payment. + // Handle successful payment if ($payment = $message->getSuccessfulPayment()) { return PaymentCommand::handleSuccessfulPayment($payment, $user_id); } diff --git a/Commands/Payments/PaymentCommand.php b/Commands/Payments/PaymentCommand.php index 31179c3..bfb827b 100644 --- a/Commands/Payments/PaymentCommand.php +++ b/Commands/Payments/PaymentCommand.php @@ -58,9 +58,11 @@ class PaymentCommand extends UserCommand protected $version = '0.1.0'; /** - * @inheritDoc + * Main command execution + * + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { // Who to send this invoice to. (Use the current user.) $chat_id = $this->getMessage()->getFrom()->getId(); @@ -81,7 +83,7 @@ public function execute() $need_shipping_address = false; // If you have flexible pricing, depending on the shipping method chosen, set this to true. - // You will also require the `ShippingqueryCommand.php` file and adapt it. + // You will also need to copy and adapt the `ShippingqueryCommand.php` file. $is_flexible = false; // Send the actual invoice! @@ -101,7 +103,7 @@ public function execute() } /** - * Send "Thank you" message to user who paid. + * Send "Thank you" message to user who paid * * You will need to add some code to your custom `GenericmessageCommand::execute()` method. * Check the `GenericmessageCommand.php` file included in this folder. @@ -112,7 +114,7 @@ public function execute() * @return ServerResponse * @throws TelegramException */ - public static function handleSuccessfulPayment($payment, $user_id) + public static function handleSuccessfulPayment($payment, $user_id): ServerResponse { // Send a message to the user after they have completed the payment. return Request::sendMessage([ diff --git a/Commands/Payments/PrecheckoutqueryCommand.php b/Commands/Payments/PrecheckoutqueryCommand.php index 7a1f308..5e874e2 100644 --- a/Commands/Payments/PrecheckoutqueryCommand.php +++ b/Commands/Payments/PrecheckoutqueryCommand.php @@ -11,7 +11,7 @@ */ /** - * Pre-checkout query required for "/payment" command. + * Pre-checkout query required for "/payment" command * * In this command you can perform any necessary verifications and checks * to allow or disallow the final checkout and payment of the invoice. @@ -20,6 +20,7 @@ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; class PrecheckoutqueryCommand extends SystemCommand { @@ -39,9 +40,11 @@ class PrecheckoutqueryCommand extends SystemCommand protected $version = '0.1.0'; /** - * @inheritDoc + * Main command execution + * + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { // Simply approve, no need for any checks at this point. return $this->getPreCheckoutQuery()->answer(true); diff --git a/Commands/Payments/ShippingqueryCommand.php b/Commands/Payments/ShippingqueryCommand.php index 9f10548..c47fac2 100644 --- a/Commands/Payments/ShippingqueryCommand.php +++ b/Commands/Payments/ShippingqueryCommand.php @@ -24,6 +24,7 @@ use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Entities\Payments\LabeledPrice; use Longman\TelegramBot\Entities\Payments\ShippingOption; +use Longman\TelegramBot\Entities\ServerResponse; class ShippingqueryCommand extends SystemCommand { @@ -43,9 +44,11 @@ class ShippingqueryCommand extends SystemCommand protected $version = '0.1.0'; /** - * @inheritDoc + * Main command execution + * + * @return ServerResponse */ - public function execute() + public function execute(): ServerResponse { // Here you can check the shipping details and adjust the Shipping Options accordingly. // For this demo, let's simply define some fixed shipping options, a "Basic" and "Premium" shipping method. diff --git a/Commands/PinnedmessageCommand.php b/Commands/PinnedmessageCommand.php deleted file mode 100644 index 91116e0..0000000 --- a/Commands/PinnedmessageCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$pinned_message = $message->getPinnedMessage(); - - return parent::execute(); - } -} diff --git a/Commands/SlapCommand.php b/Commands/SlapCommand.php index dd992e7..be9b37a 100644 --- a/Commands/SlapCommand.php +++ b/Commands/SlapCommand.php @@ -10,16 +10,18 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\UserCommands; - -use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Request; - /** * User "/slap" command * * Slap a user around with a big trout! */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; + class SlapCommand extends UserCommand { /** @@ -40,36 +42,26 @@ class SlapCommand extends UserCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.2.0'; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); - - $chat_id = $message->getChat()->getId(); $text = $message->getText(true); $sender = '@' . $message->getFrom()->getUsername(); - //username validation - $test = preg_match('/@[\w_]{5,}/', $text); - if ($test === 0) { - $text = $sender . ' sorry no one to slap around..'; - } else { - $text = $sender . ' slaps ' . $text . ' around a bit with a large trout'; + // Username validation (simply checking for `@something` in the text) + if (0 === preg_match('/@[\w_]{5,}/', $text)) { + return $this->replyToChat('Sorry, no one to slap around...'); } - $data = [ - 'chat_id' => $chat_id, - 'text' => $text, - ]; - - return Request::sendMessage($data); + return $this->replyToChat($sender . ' slaps ' . $text . ' around a bit with a large trout'); } } diff --git a/Commands/StartCommand.php b/Commands/StartCommand.php index ca95f82..dd51069 100644 --- a/Commands/StartCommand.php +++ b/Commands/StartCommand.php @@ -10,16 +10,23 @@ * file that was distributed with this source code. */ -namespace Longman\TelegramBot\Commands\SystemCommands; - -use Longman\TelegramBot\Commands\SystemCommand; -use Longman\TelegramBot\Request; - /** * Start command * * Gets executed when a user first starts using the bot. + * + * When using deep-linking, the parameter can be accessed by getting the command text. + * + * @see https://core.telegram.org/bots#deep-linking */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; +use Longman\TelegramBot\Request; + class StartCommand extends SystemCommand { /** @@ -40,7 +47,7 @@ class StartCommand extends SystemCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.2.0'; /** * @var bool @@ -48,23 +55,19 @@ class StartCommand extends SystemCommand protected $private_only = true; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { - $message = $this->getMessage(); - - $chat_id = $message->getChat()->getId(); - $text = 'Hi there!' . PHP_EOL . 'Type /help to see all commands!'; - - $data = [ - 'chat_id' => $chat_id, - 'text' => $text, - ]; + // If you use deep-linking, get the parameter like this: + // $deep_linking_parameter = $this->getMessage()->getText(true); - return Request::sendMessage($data); + return $this->replyToChat( + 'Hi there!' . PHP_EOL . + 'Type /help to see all commands!' + ); } } diff --git a/Commands/SupergroupchatcreatedCommand.php b/Commands/SupergroupchatcreatedCommand.php deleted file mode 100644 index d6363b7..0000000 --- a/Commands/SupergroupchatcreatedCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getMessage(); - //$supergroup_chat_created = $message->getSuperGroupChatCreated(); - - return parent::execute(); - } -} diff --git a/Commands/SurveyCommand.php b/Commands/SurveyCommand.php index 7a9db57..e2bc007 100644 --- a/Commands/SurveyCommand.php +++ b/Commands/SurveyCommand.php @@ -10,20 +10,22 @@ * file that was distributed with this source code. */ +/** + * User "/survey" command + * + * Example of the Conversation functionality in form of a simple survey. + */ + namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Conversation; use Longman\TelegramBot\Entities\Keyboard; use Longman\TelegramBot\Entities\KeyboardButton; -use Longman\TelegramBot\Entities\PhotoSize; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; -/** - * User "/survey" command - * - * Command that demonstrated the Conversation funtionality in form of a simple survey. - */ class SurveyCommand extends UserCommand { /** @@ -44,7 +46,7 @@ class SurveyCommand extends UserCommand /** * @var string */ - protected $version = '0.3.0'; + protected $version = '0.4.0'; /** * @var bool @@ -59,17 +61,17 @@ class SurveyCommand extends UserCommand /** * Conversation Object * - * @var \Longman\TelegramBot\Conversation + * @var Conversation */ protected $conversation; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); @@ -79,42 +81,39 @@ public function execute() $chat_id = $chat->getId(); $user_id = $user->getId(); - //Preparing Response + // Preparing response $data = [ - 'chat_id' => $chat_id, + 'chat_id' => $chat_id, + // Remove any keyboard by default + 'reply_markup' => Keyboard::remove(['selective' => true]), ]; if ($chat->isGroupChat() || $chat->isSuperGroup()) { - //reply to message id is applied by default - //Force reply is applied by default so it can work with privacy on + // Force reply is applied by default so it can work with privacy on $data['reply_markup'] = Keyboard::forceReply(['selective' => true]); } - //Conversation start + // Conversation start $this->conversation = new Conversation($user_id, $chat_id, $this->getName()); + // Load any existing notes from this conversation $notes = &$this->conversation->notes; !is_array($notes) && $notes = []; - //cache data from the tracking session if any - $state = 0; - if (isset($notes['state'])) { - $state = $notes['state']; - } + // Load the current state of the conversation + $state = $notes['state'] ?? 0; $result = Request::emptyResponse(); - //State machine - //Entrypoint of the machine state if given by the track - //Every time a step is achieved the track is updated + // State machine + // Every time a step is achieved the state is updated switch ($state) { case 0: if ($text === '') { $notes['state'] = 0; $this->conversation->update(); - $data['text'] = 'Type your name:'; - $data['reply_markup'] = Keyboard::remove(['selective' => true]); + $data['text'] = 'Type your name:'; $result = Request::sendMessage($data); break; @@ -123,7 +122,7 @@ public function execute() $notes['name'] = $text; $text = ''; - // no break + // No break! case 1: if ($text === '') { $notes['state'] = 1; @@ -138,7 +137,7 @@ public function execute() $notes['surname'] = $text; $text = ''; - // no break + // No break! case 2: if ($text === '' || !is_numeric($text)) { $notes['state'] = 2; @@ -146,7 +145,7 @@ public function execute() $data['text'] = 'Type your age:'; if ($text !== '') { - $data['text'] = 'Type your age, must be a number:'; + $data['text'] = 'Age must be a number'; } $result = Request::sendMessage($data); @@ -156,7 +155,7 @@ public function execute() $notes['age'] = $text; $text = ''; - // no break + // No break! case 3: if ($text === '' || !in_array($text, ['M', 'F'], true)) { $notes['state'] = 3; @@ -169,7 +168,7 @@ public function execute() $data['text'] = 'Select your gender:'; if ($text !== '') { - $data['text'] = 'Select your gender, choose a keyboard option:'; + $data['text'] = 'Choose a keyboard option to select your gender'; } $result = Request::sendMessage($data); @@ -178,7 +177,7 @@ public function execute() $notes['gender'] = $text; - // no break + // No break! case 4: if ($message->getLocation() === null) { $notes['state'] = 4; @@ -200,7 +199,7 @@ public function execute() $notes['longitude'] = $message->getLocation()->getLongitude(); $notes['latitude'] = $message->getLocation()->getLatitude(); - // no break + // No break! case 5: if ($message->getPhoto() === null) { $notes['state'] = 5; @@ -212,11 +211,10 @@ public function execute() break; } - /** @var PhotoSize $photo */ $photo = $message->getPhoto()[0]; $notes['photo_id'] = $photo->getFileId(); - // no break + // No break! case 6: if ($message->getContact() === null) { $notes['state'] = 6; @@ -237,7 +235,7 @@ public function execute() $notes['phone_number'] = $message->getContact()->getPhoneNumber(); - // no break + // No break! case 7: $this->conversation->update(); $out_text = '/Survey result:' . PHP_EOL; @@ -246,9 +244,9 @@ public function execute() $out_text .= PHP_EOL . ucfirst($k) . ': ' . $v; } - $data['photo'] = $notes['photo_id']; - $data['reply_markup'] = Keyboard::remove(['selective' => true]); - $data['caption'] = $out_text; + $data['photo'] = $notes['photo_id']; + $data['caption'] = $out_text; + $this->conversation->stop(); $result = Request::sendPhoto($data); diff --git a/Commands/UploadCommand.php b/Commands/UploadCommand.php index 3c3fddb..1eb1d4d 100644 --- a/Commands/UploadCommand.php +++ b/Commands/UploadCommand.php @@ -10,50 +10,78 @@ * file that was distributed with this source code. */ +/** + * User "/upload" command + * + * A command that allows users to upload files to your bot, saving them to the bot's "Download" folder. + * + * IMPORTANT NOTICE + * This is a "demo", do NOT use this as-is in your bot! + * Know the security implications of allowing users to upload arbitrary files to your server! + */ + namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Conversation; use Longman\TelegramBot\Entities\Keyboard; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; -/** - * User "/upload" command - * - * A command that allows users to upload files to your bot, saving them to the bot's "Download" folder. - */ class UploadCommand extends UserCommand { - /**#@+ - * {@inheritdoc} + /** + * @var string */ protected $name = 'upload'; + + /** + * @var string + */ protected $description = 'Upload and save files'; + + /** + * @var string + */ protected $usage = '/upload'; - protected $version = '0.1.0'; + + /** + * @var string + */ + protected $version = '0.2.0'; + + /** + * @var bool + */ protected $need_mysql = true; - /**#@-*/ /** - * {@inheritdoc} + * Main command execution + * + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); $chat = $message->getChat(); $chat_id = $chat->getId(); $user_id = $message->getFrom()->getId(); - // Preparing Response - $data = [ - 'chat_id' => $chat_id, - 'reply_markup' => Keyboard::remove(), - ]; + // Make sure the Download path has been defined and exists + $download_path = $this->telegram->getDownloadPath(); + if (!is_dir($download_path)) { + return $this->replyToChat('Download path has not been defined or does not exist.'); + } + + // Initialise the data array for the response + $data = ['chat_id' => $chat_id]; if ($chat->isGroupChat() || $chat->isSuperGroup()) { // Reply to message id is applied by default $data['reply_to_message_id'] = $message->getMessageId(); - // Force reply is applied by default to so can work with privacy on + // Force reply is applied by default to work with privacy on $data['reply_markup'] = Keyboard::forceReply(['selective' => true]); } @@ -70,7 +98,7 @@ public function execute() $file_id = $doc->getFileId(); $file = Request::getFile(['file_id' => $file_id]); if ($file->isOk() && Request::downloadFile($file->getResult())) { - $data['text'] = $message_type . ' file is located at: ' . $this->telegram->getDownloadPath() . '/' . $file->getResult()->getFilePath(); + $data['text'] = $message_type . ' file is located at: ' . $download_path . '/' . $file->getResult()->getFilePath(); } else { $data['text'] = 'Failed to download.'; } diff --git a/Commands/WeatherCommand.php b/Commands/WeatherCommand.php index d353a9b..ce7df1d 100644 --- a/Commands/WeatherCommand.php +++ b/Commands/WeatherCommand.php @@ -10,21 +10,26 @@ * file that was distributed with this source code. */ +/** + * User "/weather" command + * + * Get weather info for the location passed as the parameter.. + * + * A OpenWeatherMap.org API key is required for this command! + * You can be set in your config.php file: + * ['commands']['configs']['weather'] => ['owm_api_key' => 'your_owm_api_key_here'] + */ + namespace Longman\TelegramBot\Commands\UserCommands; use Exception; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Request; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\TelegramLog; -/** - * User "/weather" command - * - * Get weather info for any place. - * This command requires an API key to be set via command config. - */ class WeatherCommand extends UserCommand { /** @@ -45,7 +50,7 @@ class WeatherCommand extends UserCommand /** * @var string */ - protected $version = '1.2.0'; + protected $version = '1.3.0'; /** * Base URI for OpenWeatherMap API @@ -61,7 +66,7 @@ class WeatherCommand extends UserCommand * * @return string */ - private function getWeatherData($location) + private function getWeatherData($location): string { $client = new Client(['base_uri' => $this->owm_api_base_uri]); $path = 'weather'; @@ -89,7 +94,7 @@ private function getWeatherData($location) * * @return string */ - private function getWeatherString(array $data) + private function getWeatherString(array $data): string { try { if (!(isset($data['cod']) && $data['cod'] === 200)) { @@ -114,7 +119,7 @@ private function getWeatherString(array $data) $data['sys']['country'], //country $data['main']['temp'], //temperature $data['weather'][0]['description'], //description of weather - isset($conditions[$conditions_now]) ? $conditions[$conditions_now] : '' + $conditions[$conditions_now] ?? '' ); } catch (Exception $e) { TelegramLog::error($e->getMessage()); @@ -124,38 +129,28 @@ private function getWeatherString(array $data) } /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { - $message = $this->getMessage(); - $chat_id = $message->getChat()->getId(); - $text = ''; - - if (trim($this->getConfig('owm_api_key'))) { - $location = trim($message->getText(true)); - if ($location !== '') { - if ($weather_data = json_decode($this->getWeatherData($location), true)) { - $text = $this->getWeatherString($weather_data); - } - if ($text === '') { - $text = 'Cannot find weather for location: ' . $location; - } - } else { - $text = 'You must specify location in format: /weather '; - } - } else { - $text = 'OpenWeatherMap API key not defined.'; + // Check to make sure the required OWM API key has been defined. + $owm_api_key = $this->getConfig('owm_api_key'); + if (empty($owm_api_key)) { + return $this->replyToChat('OpenWeatherMap API key not defined.'); } - $data = [ - 'chat_id' => $chat_id, - 'text' => $text, - ]; + $location = trim($this->getMessage()->getText(true)); + if ($location === '') { + return $this->replyToChat('You must specify a location as: ' . $this->getUsage()); + } - return Request::sendMessage($data); + $text = 'Cannot find weather for location: ' . $location; + if ($weather_data = json_decode($this->getWeatherData($location), true)) { + $text = $this->getWeatherString($weather_data); + } + return $this->replyToChat($text); } } diff --git a/Commands/WhoamiCommand.php b/Commands/WhoamiCommand.php index 1aafae2..1ce1b9f 100644 --- a/Commands/WhoamiCommand.php +++ b/Commands/WhoamiCommand.php @@ -10,19 +10,22 @@ * file that was distributed with this source code. */ +/** + * User "/whoami" command + * + * Simple command that returns info about the current user. + */ + namespace Longman\TelegramBot\Commands\UserCommands; +use Longman\TelegramBot\ChatAction; use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Entities\File; -use Longman\TelegramBot\Entities\PhotoSize; +use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Entities\UserProfilePhotos; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; -/** - * User "/whoami" command - * - * Simple command that returns info about the current user. - */ class WhoamiCommand extends UserCommand { /** @@ -43,7 +46,7 @@ class WhoamiCommand extends UserCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.2.0'; /** * @var bool @@ -51,12 +54,12 @@ class WhoamiCommand extends UserCommand protected $private_only = true; /** - * Command execute method + * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute() + public function execute(): ServerResponse { $message = $this->getMessage(); @@ -70,10 +73,10 @@ public function execute() 'reply_to_message_id' => $message_id, ]; - //Send chat action + // Send chat action "typing..." Request::sendChatAction([ 'chat_id' => $chat_id, - 'action' => 'typing', + 'action' => ChatAction::TYPING, ]); $caption = sprintf( @@ -86,26 +89,25 @@ public function execute() $from->getUsername() ); - //Fetch user profile photo - $limit = 10; - $offset = null; - $response = Request::getUserProfilePhotos( - [ - 'user_id' => $user_id, - 'limit' => $limit, - 'offset' => $offset, - ] - ); + // Fetch user profile photo + $limit = 10; + $offset = null; - if ($response->isOk()) { + $user_profile_photos_response = Request::getUserProfilePhotos([ + 'user_id' => $user_id, + 'limit' => $limit, + 'offset' => $offset, + ]); + + if ($user_profile_photos_response->isOk()) { /** @var UserProfilePhotos $user_profile_photos */ - $user_profile_photos = $response->getResult(); + $user_profile_photos = $user_profile_photos_response->getResult(); if ($user_profile_photos->getTotalCount() > 0) { - $photos = $user_profile_photos->getPhotos(); - - /** @var PhotoSize $photo */ - $photo = $photos[0][2]; + $photos = $user_profile_photos->getPhotos(); + // $photo = $photos[0][2]; + // Get the best quality of the first profile photo found + $photo = end($photos[0]); $file_id = $photo->getFileId(); $data['photo'] = $file_id; @@ -113,11 +115,11 @@ public function execute() $result = Request::sendPhoto($data); - //Download the photo after send message response to speedup response - $response2 = Request::getFile(['file_id' => $file_id]); - if ($response2->isOk()) { + // Download the photo after sending the message + $photo_file_response = Request::getFile(['file_id' => $file_id]); + if ($photo_file_response->isOk()) { /** @var File $photo_file */ - $photo_file = $response2->getResult(); + $photo_file = $photo_file_response->getResult(); Request::downloadFile($photo_file); } @@ -125,7 +127,7 @@ public function execute() } } - //No Photo just send text + // No Photo just send text $data['text'] = $caption; return Request::sendMessage($data); diff --git a/config.example.php b/config.example.php index 135b8a3..45bffec 100644 --- a/config.example.php +++ b/config.example.php @@ -48,9 +48,11 @@ ], // Here you can set any command-specific parameters 'configs' => [ - // - Google geocode/timezone API key for /date command + // - Google geocode/timezone API key for /date command (see DateCommand.php) // 'date' => ['google_api_key' => 'your_google_api_key_here'], - // - Payment Provider Token for /payment command. + // - OpenWeatherMap.org API key for /weather command (see WeatherCommand.php) + // 'weather' => ['owm_api_key' => 'your_owm_api_key_here'], + // - Payment Provider Token for /payment command (see Payments/PaymentCommand.php) // 'payment' => ['payment_provider_token' => 'your_payment_provider_token_here'], ], ], From 9e9a8f99437acfbbfbea317f9a12f22bb9b9d85f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Mon, 13 Jul 2020 14:13:38 +0200 Subject: [PATCH 27/43] Add PHPCS to ensure a pretty coding style --- composer.json | 9 +++++++++ phpcs.xml.dist | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 phpcs.xml.dist diff --git a/composer.json b/composer.json index 1689ef2..327f16e 100644 --- a/composer.json +++ b/composer.json @@ -18,5 +18,14 @@ ], "require": { "longman/telegram-bot": "*" + }, + "require-dev": { + "php-parallel-lint/php-parallel-lint": "^1.2", + "squizlabs/php_codesniffer": "^3.5" + }, + "scripts": { + "check-code": [ + "\"vendor/bin/phpcs\"" + ] } } diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..9fb9029 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,26 @@ + + + PHP Code Sniffer + + + + + + + + + . + */vendor/* + + + + + + + + + + + + + From 903a46f40b2c414aa9abf26bdf503a85bbbf9acf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Mon, 13 Jul 2020 14:21:50 +0200 Subject: [PATCH 28/43] Small docBlock fixes --- Commands/DateCommand.php | 8 +++++--- Commands/EditmessageCommand.php | 8 +++++--- Commands/ForcereplyCommand.php | 8 +++++--- Commands/GenericCommand.php | 8 +++++--- Commands/GenericmessageCommand.php | 12 +++++++----- 5 files changed, 27 insertions(+), 17 deletions(-) diff --git a/Commands/DateCommand.php b/Commands/DateCommand.php index de3d121..0fc2d18 100644 --- a/Commands/DateCommand.php +++ b/Commands/DateCommand.php @@ -25,6 +25,8 @@ use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; use Longman\TelegramBot\TelegramLog; @@ -211,10 +213,10 @@ private function getFormattedDate($location): string /** * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute(): \Longman\TelegramBot\Entities\ServerResponse + public function execute(): ServerResponse { //First we set up the necessary member variables. $this->client = new Client(['base_uri' => $this->google_api_base_uri]); diff --git a/Commands/EditmessageCommand.php b/Commands/EditmessageCommand.php index 3c3ee1b..149f3d8 100644 --- a/Commands/EditmessageCommand.php +++ b/Commands/EditmessageCommand.php @@ -13,6 +13,8 @@ namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; /** @@ -45,10 +47,10 @@ class EditmessageCommand extends UserCommand /** * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute(): \Longman\TelegramBot\Entities\ServerResponse + public function execute(): ServerResponse { $message = $this->getMessage(); $chat_id = $message->getChat()->getId(); diff --git a/Commands/ForcereplyCommand.php b/Commands/ForcereplyCommand.php index 59cc662..02e5646 100644 --- a/Commands/ForcereplyCommand.php +++ b/Commands/ForcereplyCommand.php @@ -14,6 +14,8 @@ use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Entities\Keyboard; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; /** @@ -46,10 +48,10 @@ class ForcereplyCommand extends UserCommand /** * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute(): \Longman\TelegramBot\Entities\ServerResponse + public function execute(): ServerResponse { $chat_id = $this->getMessage()->getChat()->getId(); diff --git a/Commands/GenericCommand.php b/Commands/GenericCommand.php index 808bf52..11a06ac 100644 --- a/Commands/GenericCommand.php +++ b/Commands/GenericCommand.php @@ -13,6 +13,8 @@ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; /** @@ -40,10 +42,10 @@ class GenericCommand extends SystemCommand /** * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute(): \Longman\TelegramBot\Entities\ServerResponse + public function execute(): ServerResponse { $message = $this->getMessage(); diff --git a/Commands/GenericmessageCommand.php b/Commands/GenericmessageCommand.php index c24c61a..e84a5d1 100644 --- a/Commands/GenericmessageCommand.php +++ b/Commands/GenericmessageCommand.php @@ -20,6 +20,8 @@ use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Conversation; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; class GenericmessageCommand extends SystemCommand @@ -47,9 +49,9 @@ class GenericmessageCommand extends SystemCommand /** * Command execute method if MySQL is required but not available * - * @return \Longman\TelegramBot\Entities\ServerResponse + * @return ServerResponse */ - public function executeNoDb(): \Longman\TelegramBot\Entities\ServerResponse + public function executeNoDb(): ServerResponse { // Do nothing return Request::emptyResponse(); @@ -58,10 +60,10 @@ public function executeNoDb(): \Longman\TelegramBot\Entities\ServerResponse /** * Main command execution * - * @return \Longman\TelegramBot\Entities\ServerResponse - * @throws \Longman\TelegramBot\Exception\TelegramException + * @return ServerResponse + * @throws TelegramException */ - public function execute(): \Longman\TelegramBot\Entities\ServerResponse + public function execute(): ServerResponse { $message = $this->getMessage(); From abf1c4f2e1d5e4cbe7080283471365be8ab9a011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Fri, 31 Jul 2020 16:58:00 +0200 Subject: [PATCH 29/43] Organise example commands into folders and add a short readme to each folder --- Commands/{ => Config}/DateCommand.php | 2 +- Commands/Config/README.md | 28 +++++++ Commands/{ => Config}/WeatherCommand.php | 0 Commands/{ => Conversation}/CancelCommand.php | 2 +- .../GenericmessageCommand.php | 44 +--------- Commands/Conversation/README.md | 9 ++ Commands/{ => Conversation}/SurveyCommand.php | 0 Commands/GenericCommand.php | 14 +--- Commands/Group/GenericmessageCommand.php | 82 +++++++++++++++++++ .../{ => Group}/LeftchatmemberCommand.php | 0 .../{ => Group}/NewchatmembersCommand.php | 0 Commands/Group/README.md | 6 ++ .../ChoseninlineresultCommand.php | 4 +- .../{ => InlineMode}/InlinequeryCommand.php | 0 Commands/InlineMode/README.md | 7 ++ .../{ => Keyboard}/CallbackqueryCommand.php | 5 +- Commands/{ => Keyboard}/ForcereplyCommand.php | 14 +--- .../{ => Keyboard}/HidekeyboardCommand.php | 2 +- .../{ => Keyboard}/InlinekeyboardCommand.php | 2 + Commands/{ => Keyboard}/KeyboardCommand.php | 5 +- Commands/Keyboard/README.md | 13 +++ Commands/{ => Message}/ChannelpostCommand.php | 3 +- .../EditedchannelpostCommand.php | 3 +- .../{ => Message}/EditedmessageCommand.php | 3 +- Commands/{ => Message}/EditmessageCommand.php | 30 +++---- Commands/Message/GenericmessageCommand.php | 61 ++++++++++++++ Commands/Message/README.md | 15 ++++ Commands/{ => Other}/EchoCommand.php | 0 Commands/{ => Other}/HelpCommand.php | 0 Commands/{ => Other}/ImageCommand.php | 0 Commands/{ => Other}/MarkdownCommand.php | 0 Commands/Other/README.md | 5 ++ Commands/{ => Other}/SlapCommand.php | 0 Commands/{ => Other}/UploadCommand.php | 0 Commands/{ => Other}/WhoamiCommand.php | 23 ++---- Commands/Payments/PaymentCommand.php | 4 +- Commands/Payments/README.md | 8 +- .../ServiceMessages/GenericmessageCommand.php | 74 +++++++++++++++++ Commands/StartCommand.php | 1 - README.md | 11 +++ phpcs.xml.dist | 4 +- 41 files changed, 365 insertions(+), 119 deletions(-) rename Commands/{ => Config}/DateCommand.php (99%) create mode 100644 Commands/Config/README.md rename Commands/{ => Config}/WeatherCommand.php (100%) rename Commands/{ => Conversation}/CancelCommand.php (98%) rename Commands/{ => Conversation}/GenericmessageCommand.php (56%) create mode 100644 Commands/Conversation/README.md rename Commands/{ => Conversation}/SurveyCommand.php (100%) create mode 100644 Commands/Group/GenericmessageCommand.php rename Commands/{ => Group}/LeftchatmemberCommand.php (100%) rename Commands/{ => Group}/NewchatmembersCommand.php (100%) create mode 100644 Commands/Group/README.md rename Commands/{ => InlineMode}/ChoseninlineresultCommand.php (90%) rename Commands/{ => InlineMode}/InlinequeryCommand.php (100%) create mode 100644 Commands/InlineMode/README.md rename Commands/{ => Keyboard}/CallbackqueryCommand.php (86%) rename Commands/{ => Keyboard}/ForcereplyCommand.php (80%) rename Commands/{ => Keyboard}/HidekeyboardCommand.php (96%) rename Commands/{ => Keyboard}/InlinekeyboardCommand.php (98%) rename Commands/{ => Keyboard}/KeyboardCommand.php (95%) create mode 100644 Commands/Keyboard/README.md rename Commands/{ => Message}/ChannelpostCommand.php (92%) rename Commands/{ => Message}/EditedchannelpostCommand.php (91%) rename Commands/{ => Message}/EditedmessageCommand.php (91%) rename Commands/{ => Message}/EditmessageCommand.php (77%) create mode 100644 Commands/Message/GenericmessageCommand.php create mode 100644 Commands/Message/README.md rename Commands/{ => Other}/EchoCommand.php (100%) rename Commands/{ => Other}/HelpCommand.php (100%) rename Commands/{ => Other}/ImageCommand.php (100%) rename Commands/{ => Other}/MarkdownCommand.php (100%) create mode 100644 Commands/Other/README.md rename Commands/{ => Other}/SlapCommand.php (100%) rename Commands/{ => Other}/UploadCommand.php (100%) rename Commands/{ => Other}/WhoamiCommand.php (79%) create mode 100644 Commands/ServiceMessages/GenericmessageCommand.php diff --git a/Commands/DateCommand.php b/Commands/Config/DateCommand.php similarity index 99% rename from Commands/DateCommand.php rename to Commands/Config/DateCommand.php index 0fc2d18..f9f0444 100644 --- a/Commands/DateCommand.php +++ b/Commands/Config/DateCommand.php @@ -218,7 +218,7 @@ private function getFormattedDate($location): string */ public function execute(): ServerResponse { -//First we set up the necessary member variables. + // First we set up the necessary member variables. $this->client = new Client(['base_uri' => $this->google_api_base_uri]); if (($this->google_api_key = trim($this->getConfig('google_api_key'))) === '') { $this->google_api_key = null; diff --git a/Commands/Config/README.md b/Commands/Config/README.md new file mode 100644 index 0000000..b69ccc7 --- /dev/null +++ b/Commands/Config/README.md @@ -0,0 +1,28 @@ +# Config + +Custom configurations can be passed to commands that support them. + +This feature is mainly used to pass secrets or special values to the commands. + +## Adding configurations to your config + +It is very easy to add configurations to `config.php`: +```php +'commands' => [ + 'configs' => [ + 'yourcommand' => ['your_config_key' => 'your_config_value'], + ], +], +``` + +Alternatively, you can set them directly via code in your `hook.php`: +```php +$telegram->setCommandConfig('yourcommand', ['your_config_key' => 'your_config_value']); +``` + +## Reading configurations in your command + +To read any command configurations, you can fetch them from within your command like this: +```php +$my_config = $this->getConfig('your_config_key'); // 'your_config_value' +``` diff --git a/Commands/WeatherCommand.php b/Commands/Config/WeatherCommand.php similarity index 100% rename from Commands/WeatherCommand.php rename to Commands/Config/WeatherCommand.php diff --git a/Commands/CancelCommand.php b/Commands/Conversation/CancelCommand.php similarity index 98% rename from Commands/CancelCommand.php rename to Commands/Conversation/CancelCommand.php index 2f139f1..b74ebf7 100644 --- a/Commands/CancelCommand.php +++ b/Commands/Conversation/CancelCommand.php @@ -74,7 +74,7 @@ public function execute(): ServerResponse { $text = 'No active conversation!'; - //Cancel current conversation if any + // Cancel current conversation if any $conversation = new Conversation( $this->getMessage()->getFrom()->getId(), $this->getMessage()->getChat()->getId() diff --git a/Commands/GenericmessageCommand.php b/Commands/Conversation/GenericmessageCommand.php similarity index 56% rename from Commands/GenericmessageCommand.php rename to Commands/Conversation/GenericmessageCommand.php index e84a5d1..5d10822 100644 --- a/Commands/GenericmessageCommand.php +++ b/Commands/Conversation/GenericmessageCommand.php @@ -14,6 +14,8 @@ * Generic message command * * Gets executed when any type of message is sent. + * + * In this conversation-related context, we must ensure that active conversations get executed correctly. */ namespace Longman\TelegramBot\Commands\SystemCommands; @@ -39,7 +41,7 @@ class GenericmessageCommand extends SystemCommand /** * @var string */ - protected $version = '1.1.0'; + protected $version = '1.0.0'; /** * @var bool @@ -74,48 +76,10 @@ public function execute(): ServerResponse ); // Fetch conversation command if it exists and execute it. - if ($conversation->exists() && ($command = $conversation->getCommand())) { + if ($conversation->exists() && $command = $conversation->getCommand()) { return $this->telegram->executeCommand($command); } - /** - * Here, any service messages can be caught and handled. - * - * Service messages are: - * delete_chat_photo - the chat photo was deleted - * group_chat_created - the group has been created - * supergroup_chat_created - the supergroup has been created - * channel_chat_created - the channel has been created - * successful_payment - information about the payment - */ - - /** - * For special message commands, you need to call them from here. - * - * // Handle new chat members - * if ($message->getNewChatMembers()) { - * return $this->getTelegram()->executeCommand('newchatmembers'); - * } - * - * // Handle left chat members - * if ($message->getLeftChatMember()) { - * return $this->getTelegram()->executeCommand('leftchatmember'); - * } - * - * // Handle group actions - * if ($new_chat_photo = $message->getNewChatPhoto()) { - * // Whatever... - * } - * if ($new_chat_title = $message->getNewChatTitle()) { - * // Whatever... - * } - * - * // Message pinning - * if ($pinned_message = $message->getPinnedMessage()) { - * // Whatever... - * } - */ - return Request::emptyResponse(); } } diff --git a/Commands/Conversation/README.md b/Commands/Conversation/README.md new file mode 100644 index 0000000..ca4e84f --- /dev/null +++ b/Commands/Conversation/README.md @@ -0,0 +1,9 @@ +# Conversation + +Conversations can be used to create dialogues with users, to collect information in a "conversational" style. + +Look at the [`SurveyCommand`](SurveyCommand.php) to see how a conversation can be made. + +For conversations to work, you must add the code provided in [`GenericmessageCommand.php`](GenericmessageCommand.php) at the beginning of your custom `GenericmessageCommand::execute()` method. + +The [`CancelCommand`](CancelCommand.php) allows users to cancel any active conversation. diff --git a/Commands/SurveyCommand.php b/Commands/Conversation/SurveyCommand.php similarity index 100% rename from Commands/SurveyCommand.php rename to Commands/Conversation/SurveyCommand.php diff --git a/Commands/GenericCommand.php b/Commands/GenericCommand.php index 11a06ac..ad1e4aa 100644 --- a/Commands/GenericCommand.php +++ b/Commands/GenericCommand.php @@ -15,7 +15,6 @@ use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Exception\TelegramException; -use Longman\TelegramBot\Request; /** * Generic command @@ -48,22 +47,15 @@ class GenericCommand extends SystemCommand public function execute(): ServerResponse { $message = $this->getMessage(); - - //You can use $command as param - $chat_id = $message->getChat()->getId(); $user_id = $message->getFrom()->getId(); $command = $message->getCommand(); - //If the user is an admin and the command is in the format "/whoisXYZ", call the /whois command + // To enable proper use of the /whois command. + // If the user is an admin and the command is in the format "/whoisXYZ", call the /whois command if (stripos($command, 'whois') === 0 && $this->telegram->isAdmin($user_id)) { return $this->telegram->executeCommand('whois'); } - $data = [ - 'chat_id' => $chat_id, - 'text' => 'Command /' . $command . ' not found.. :(', - ]; - - return Request::sendMessage($data); + return $this->replyToChat("Command /{$command} not found.. :("); } } diff --git a/Commands/Group/GenericmessageCommand.php b/Commands/Group/GenericmessageCommand.php new file mode 100644 index 0000000..0fb5b72 --- /dev/null +++ b/Commands/Group/GenericmessageCommand.php @@ -0,0 +1,82 @@ +getMessage(); + + // Handle new chat members + if ($message->getNewChatMembers()) { + return $this->getTelegram()->executeCommand('newchatmembers'); + } + + // Handle left chat members + if ($message->getLeftChatMember()) { + return $this->getTelegram()->executeCommand('leftchatmember'); + } + + // The chat photo was changed + if ($new_chat_photo = $message->getNewChatPhoto()) { + // Whatever... + } + + // The chat title was changed + if ($new_chat_title = $message->getNewChatTitle()) { + // Whatever... + } + + // A message has been pinned + if ($pinned_message = $message->getPinnedMessage()) { + // Whatever... + } + + return Request::emptyResponse(); + } +} diff --git a/Commands/LeftchatmemberCommand.php b/Commands/Group/LeftchatmemberCommand.php similarity index 100% rename from Commands/LeftchatmemberCommand.php rename to Commands/Group/LeftchatmemberCommand.php diff --git a/Commands/NewchatmembersCommand.php b/Commands/Group/NewchatmembersCommand.php similarity index 100% rename from Commands/NewchatmembersCommand.php rename to Commands/Group/NewchatmembersCommand.php diff --git a/Commands/Group/README.md b/Commands/Group/README.md new file mode 100644 index 0000000..a9bf646 --- /dev/null +++ b/Commands/Group/README.md @@ -0,0 +1,6 @@ +# Group or Channel + +Requests specific to groups and channels all get handled in [`GenericmessageCommand.php`](GenericmessageCommand.php). + +The two extra commands [`NewchatmembersCommand`](NewchatmembersCommand.php) and [`LeftchatmemberCommand`](LeftchatmemberCommand.php) are simply files that can be called as commands from within a command, not by a user. +Have a look at [`GenericmessageCommand.php`](GenericmessageCommand.php) to understand what you can do. diff --git a/Commands/ChoseninlineresultCommand.php b/Commands/InlineMode/ChoseninlineresultCommand.php similarity index 90% rename from Commands/ChoseninlineresultCommand.php rename to Commands/InlineMode/ChoseninlineresultCommand.php index 662390c..2719d05 100644 --- a/Commands/ChoseninlineresultCommand.php +++ b/Commands/InlineMode/ChoseninlineresultCommand.php @@ -46,8 +46,8 @@ class ChoseninlineresultCommand extends SystemCommand public function execute(): ServerResponse { // Information about the chosen result is returned. - // $inline_query = $this->getChosenInlineResult(); - // $query = $inline_query->getQuery(); + $inline_query = $this->getChosenInlineResult(); + $query = $inline_query->getQuery(); return parent::execute(); } diff --git a/Commands/InlinequeryCommand.php b/Commands/InlineMode/InlinequeryCommand.php similarity index 100% rename from Commands/InlinequeryCommand.php rename to Commands/InlineMode/InlinequeryCommand.php diff --git a/Commands/InlineMode/README.md b/Commands/InlineMode/README.md new file mode 100644 index 0000000..24ac74d --- /dev/null +++ b/Commands/InlineMode/README.md @@ -0,0 +1,7 @@ +# Inline Mode + +The files in this folder demonstrate how to use the [inline mode](https://core.telegram.org/bots/api#inline-mode) of your bot. + +The [`InlinequeryCommand.php`](InlinequeryCommand.php) catches any inline queries and answers with a set of results. + +When a result is selected, this selection is then handled by [`ChoseninlineresultCommand.php`](ChoseninlineresultCommand.php). diff --git a/Commands/CallbackqueryCommand.php b/Commands/Keyboard/CallbackqueryCommand.php similarity index 86% rename from Commands/CallbackqueryCommand.php rename to Commands/Keyboard/CallbackqueryCommand.php index 85bf4a0..635a6ac 100644 --- a/Commands/CallbackqueryCommand.php +++ b/Commands/Keyboard/CallbackqueryCommand.php @@ -44,6 +44,7 @@ class CallbackqueryCommand extends SystemCommand * Main command execution * * @return ServerResponse + * @throws \Exception */ public function execute(): ServerResponse { @@ -52,8 +53,8 @@ public function execute(): ServerResponse $callback_data = $callback_query->getData(); return $callback_query->answer([ - 'text' => 'Hello World!', - 'show_alert' => $callback_data === 'thumb up', + 'text' => 'Content of the callback data: ' . $callback_data, + 'show_alert' => (bool) random_int(0, 1), // Randomly show (or not) as an alert. 'cache_time' => 5, ]); } diff --git a/Commands/ForcereplyCommand.php b/Commands/Keyboard/ForcereplyCommand.php similarity index 80% rename from Commands/ForcereplyCommand.php rename to Commands/Keyboard/ForcereplyCommand.php index 02e5646..8d0308c 100644 --- a/Commands/ForcereplyCommand.php +++ b/Commands/Keyboard/ForcereplyCommand.php @@ -16,7 +16,6 @@ use Longman\TelegramBot\Entities\Keyboard; use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Exception\TelegramException; -use Longman\TelegramBot\Request; /** * User "/forcereply" command @@ -43,7 +42,7 @@ class ForcereplyCommand extends UserCommand /** * @var string */ - protected $version = '0.1.0'; + protected $version = '0.2.0'; /** * Main command execution @@ -53,14 +52,9 @@ class ForcereplyCommand extends UserCommand */ public function execute(): ServerResponse { - $chat_id = $this->getMessage()->getChat()->getId(); - - $data = [ - 'chat_id' => $chat_id, - 'text' => 'Write something:', + // Force a reply to the sent message + return $this->replyToChat('Write something in reply:', [ 'reply_markup' => Keyboard::forceReply(), - ]; - - return Request::sendMessage($data); + ]); } } diff --git a/Commands/HidekeyboardCommand.php b/Commands/Keyboard/HidekeyboardCommand.php similarity index 96% rename from Commands/HidekeyboardCommand.php rename to Commands/Keyboard/HidekeyboardCommand.php index c949db1..3593cae 100644 --- a/Commands/HidekeyboardCommand.php +++ b/Commands/Keyboard/HidekeyboardCommand.php @@ -53,7 +53,7 @@ class HidekeyboardCommand extends UserCommand */ public function execute(): ServerResponse { - // Remove the keyboard and send a message. + // Remove the keyboard and send a message return $this->replyToChat('Keyboard Hidden', [ 'reply_markup' => Keyboard::remove(), ]); diff --git a/Commands/InlinekeyboardCommand.php b/Commands/Keyboard/InlinekeyboardCommand.php similarity index 98% rename from Commands/InlinekeyboardCommand.php rename to Commands/Keyboard/InlinekeyboardCommand.php index 3c2c787..af98ac0 100644 --- a/Commands/InlinekeyboardCommand.php +++ b/Commands/Keyboard/InlinekeyboardCommand.php @@ -18,6 +18,8 @@ * Display an inline keyboard with a few buttons. * * This command requires CallbackqueryCommand to work! + * + * @see CallbackqueryCommand.php */ use Longman\TelegramBot\Commands\UserCommand; diff --git a/Commands/KeyboardCommand.php b/Commands/Keyboard/KeyboardCommand.php similarity index 95% rename from Commands/KeyboardCommand.php rename to Commands/Keyboard/KeyboardCommand.php index 2a49c47..579fadc 100644 --- a/Commands/KeyboardCommand.php +++ b/Commands/Keyboard/KeyboardCommand.php @@ -22,7 +22,6 @@ use Longman\TelegramBot\Entities\Keyboard; use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Exception\TelegramException; -use Longman\TelegramBot\Request; class KeyboardCommand extends UserCommand { @@ -89,10 +88,8 @@ public function execute(): ServerResponse ['text' => 'Send my location', 'request_location' => true], ]); - // Shuffle our example keyboards + // Shuffle our example keyboards and return a random one shuffle($keyboards); - - // Return a random keyboard $keyboard = end($keyboards) ->setResizeKeyboard(true) ->setOneTimeKeyboard(true) diff --git a/Commands/Keyboard/README.md b/Commands/Keyboard/README.md new file mode 100644 index 0000000..c7a258b --- /dev/null +++ b/Commands/Keyboard/README.md @@ -0,0 +1,13 @@ +# Keyboards + +The files in this folder demonstrate how to create normal and inline keyboards. + +## Normal Keyboard + +Have a look at [`KeyboardCommand.php`](KeyboardCommand.php) for usage examples. + +## Inline Keyboard + +Have a look at [`InlinekeyboardCommand.php`](InlinekeyboardCommand.php) for usage examples. + +To handle inline keyboard buttons, you need to handle all callbacks inside [`CallbackqueryCommand.php`](CallbackqueryCommand.php). diff --git a/Commands/ChannelpostCommand.php b/Commands/Message/ChannelpostCommand.php similarity index 92% rename from Commands/ChannelpostCommand.php rename to Commands/Message/ChannelpostCommand.php index aafa2d3..5b04ae4 100644 --- a/Commands/ChannelpostCommand.php +++ b/Commands/Message/ChannelpostCommand.php @@ -45,7 +45,8 @@ class ChannelpostCommand extends SystemCommand */ public function execute(): ServerResponse { - // $channel_post = $this->getChannelPost(); + // Get the channel post + $channel_post = $this->getChannelPost(); return parent::execute(); } diff --git a/Commands/EditedchannelpostCommand.php b/Commands/Message/EditedchannelpostCommand.php similarity index 91% rename from Commands/EditedchannelpostCommand.php rename to Commands/Message/EditedchannelpostCommand.php index 6d6e08c..f70d2a3 100644 --- a/Commands/EditedchannelpostCommand.php +++ b/Commands/Message/EditedchannelpostCommand.php @@ -45,7 +45,8 @@ class EditedchannelpostCommand extends SystemCommand */ public function execute(): ServerResponse { - // $edited_channel_post = $this->getEditedChannelPost(); + // Get the edited channel post + $edited_channel_post = $this->getEditedChannelPost(); return parent::execute(); } diff --git a/Commands/EditedmessageCommand.php b/Commands/Message/EditedmessageCommand.php similarity index 91% rename from Commands/EditedmessageCommand.php rename to Commands/Message/EditedmessageCommand.php index ccbfb2d..7d4b565 100644 --- a/Commands/EditedmessageCommand.php +++ b/Commands/Message/EditedmessageCommand.php @@ -44,7 +44,8 @@ class EditedmessageCommand extends SystemCommand */ public function execute(): ServerResponse { - // $edited_message = $this->getEditedMessage(); + // Get the edited message + $edited_message = $this->getEditedMessage(); return parent::execute(); } diff --git a/Commands/EditmessageCommand.php b/Commands/Message/EditmessageCommand.php similarity index 77% rename from Commands/EditmessageCommand.php rename to Commands/Message/EditmessageCommand.php index 149f3d8..8b0432c 100644 --- a/Commands/EditmessageCommand.php +++ b/Commands/Message/EditmessageCommand.php @@ -10,6 +10,12 @@ * file that was distributed with this source code. */ +/** + * User "/editmessage" command + * + * Command to edit a message sent by the bot. + */ + namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; @@ -17,11 +23,6 @@ use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Request; -/** - * User "/editmessage" command - * - * Command to edit a message via bot. - */ class EditmessageCommand extends UserCommand { /** @@ -32,7 +33,7 @@ class EditmessageCommand extends UserCommand /** * @var string */ - protected $description = 'Edit message'; + protected $description = 'Edit a message sent by the bot'; /** * @var string @@ -58,17 +59,15 @@ public function execute(): ServerResponse $text = $message->getText(true); if ($reply_to_message && $message_to_edit = $reply_to_message->getMessageId()) { - $data_edit = [ + // Try to edit the selected message. + $result = Request::editMessageText([ 'chat_id' => $chat_id, 'message_id' => $message_to_edit, 'text' => $text ?: 'Edited message', - ]; - - // Try to edit selected message. - $result = Request::editMessageText($data_edit); + ]); + // If successful, delete this editing reply message. if ($result->isOk()) { - // Delete this editing reply message. Request::deleteMessage([ 'chat_id' => $chat_id, 'message_id' => $message->getMessageId(), @@ -78,11 +77,6 @@ public function execute(): ServerResponse return $result; } - $data = [ - 'chat_id' => $chat_id, - 'text' => sprintf("Reply to any bots' message and use /%s to edit it.", $this->name), - ]; - - return Request::sendMessage($data); + return $this->replyToChat(sprintf("Reply to any bots' message and use /%s to edit it.", $this->getName())); } } diff --git a/Commands/Message/GenericmessageCommand.php b/Commands/Message/GenericmessageCommand.php new file mode 100644 index 0000000..0aa6346 --- /dev/null +++ b/Commands/Message/GenericmessageCommand.php @@ -0,0 +1,61 @@ +getMessage(); + + /** + * Handle any kind of message here + */ + + $message_text = $message->getText(true); + + return Request::emptyResponse(); + } +} diff --git a/Commands/Message/README.md b/Commands/Message/README.md new file mode 100644 index 0000000..574ed1b --- /dev/null +++ b/Commands/Message/README.md @@ -0,0 +1,15 @@ +# Message + +You bot can handle all types of messages. + +## Private and Group chats + +Messages in private and group chats get handled by [`GenericmessageCommand.php`](GenericmessageCommand.php). +When a message gets edited, it gets handled by [`EditedmessageCommand.php`](EditedmessageCommand.php) + +(Have a look at [`EditmessageCommand.php`](EditmessageCommand.php) for an example of how to edit messages via your bot) + +## Channels + +For channels, the messages (or posts) get handled by [`ChannelpostCommand.php`](ChannelpostCommand.php). +When a channel post gets edited, it gets handled by [`EditedchannelpostCommand.php`](EditedchannelpostCommand.php) diff --git a/Commands/EchoCommand.php b/Commands/Other/EchoCommand.php similarity index 100% rename from Commands/EchoCommand.php rename to Commands/Other/EchoCommand.php diff --git a/Commands/HelpCommand.php b/Commands/Other/HelpCommand.php similarity index 100% rename from Commands/HelpCommand.php rename to Commands/Other/HelpCommand.php diff --git a/Commands/ImageCommand.php b/Commands/Other/ImageCommand.php similarity index 100% rename from Commands/ImageCommand.php rename to Commands/Other/ImageCommand.php diff --git a/Commands/MarkdownCommand.php b/Commands/Other/MarkdownCommand.php similarity index 100% rename from Commands/MarkdownCommand.php rename to Commands/Other/MarkdownCommand.php diff --git a/Commands/Other/README.md b/Commands/Other/README.md new file mode 100644 index 0000000..cafac7b --- /dev/null +++ b/Commands/Other/README.md @@ -0,0 +1,5 @@ +# Other Commands + +In this folder you can find a few example commands, that demonstrate how to use different features of the library. + +Best just take a look at them and see what they do! diff --git a/Commands/SlapCommand.php b/Commands/Other/SlapCommand.php similarity index 100% rename from Commands/SlapCommand.php rename to Commands/Other/SlapCommand.php diff --git a/Commands/UploadCommand.php b/Commands/Other/UploadCommand.php similarity index 100% rename from Commands/UploadCommand.php rename to Commands/Other/UploadCommand.php diff --git a/Commands/WhoamiCommand.php b/Commands/Other/WhoamiCommand.php similarity index 79% rename from Commands/WhoamiCommand.php rename to Commands/Other/WhoamiCommand.php index 1ce1b9f..ba75f66 100644 --- a/Commands/WhoamiCommand.php +++ b/Commands/Other/WhoamiCommand.php @@ -20,7 +20,6 @@ use Longman\TelegramBot\ChatAction; use Longman\TelegramBot\Commands\UserCommand; -use Longman\TelegramBot\Entities\File; use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Entities\UserProfilePhotos; use Longman\TelegramBot\Exception\TelegramException; @@ -89,8 +88,8 @@ public function execute(): ServerResponse $from->getUsername() ); - // Fetch user profile photo - $limit = 10; + // Fetch the most recent user profile photo + $limit = 1; $offset = null; $user_profile_photos_response = Request::getUserProfilePhotos([ @@ -104,26 +103,16 @@ public function execute(): ServerResponse $user_profile_photos = $user_profile_photos_response->getResult(); if ($user_profile_photos->getTotalCount() > 0) { - $photos = $user_profile_photos->getPhotos(); - // $photo = $photos[0][2]; - // Get the best quality of the first profile photo found + $photos = $user_profile_photos->getPhotos(); + + // Get the best quality of the profile photo $photo = end($photos[0]); $file_id = $photo->getFileId(); $data['photo'] = $file_id; $data['caption'] = $caption; - $result = Request::sendPhoto($data); - - // Download the photo after sending the message - $photo_file_response = Request::getFile(['file_id' => $file_id]); - if ($photo_file_response->isOk()) { - /** @var File $photo_file */ - $photo_file = $photo_file_response->getResult(); - Request::downloadFile($photo_file); - } - - return $result; + return Request::sendPhoto($data); } } diff --git a/Commands/Payments/PaymentCommand.php b/Commands/Payments/PaymentCommand.php index bfb827b..75c801a 100644 --- a/Commands/Payments/PaymentCommand.php +++ b/Commands/Payments/PaymentCommand.php @@ -19,9 +19,9 @@ * Select your bot and then "Payments". Then choose the provider of your choice. * * @BotFather will then present you with a payment provider token. - * Copy this token and add it to your command config in your hook file: * - * $telegram->setCommandConfig('payment', ['payment_provider_token' => 'your_payment_provider_token_here']); + * Copy this token and set it in your config.php file: + * ['commands']['configs']['payment'] => ['payment_provider_token' => 'your_payment_provider_token_here'] * * You will also need to copy the `Precheckoutquerycommand.php` file. */ diff --git a/Commands/Payments/README.md b/Commands/Payments/README.md index 1bcfbd6..2c936ec 100644 --- a/Commands/Payments/README.md +++ b/Commands/Payments/README.md @@ -9,11 +9,11 @@ https://core.telegram.org/bots/payments ## Configuring the `/payment` command -First of all, as a bare minimum, you need to copy the `PaymentCommand.php` and `PrecheckoutqueryCommand.php` files in this folder to your custom commands folder. +First of all, as a bare minimum, you need to copy the [`PaymentCommand.php`](PaymentCommand.php) and [`PrecheckoutqueryCommand.php`](PrecheckoutqueryCommand.php) files in this folder to your custom commands folder. -If you want to allow flexible shipping options, you will also need to copy `ShippingqueryCommand.php` to your custom commands folder. +If you want to allow flexible shipping options, you will also need to copy [`ShippingqueryCommand.php`](ShippingqueryCommand.php) to your custom commands folder. -Should you want to send a message on a successful payment, you will need to copy the `GenericmessageCommand.php` file as well. +Should you want to send a message on a successful payment, you will need to copy the [`GenericmessageCommand.php`](GenericmessageCommand.php) file as well. If you already have a `GenericmessageCommand.php` file, you'll need to copy the code from the `execute` method into your file. Next, you will need to add the Payment Provider Token (that you received in the previous step when linking your bot), to your `hook.php` or `manager.php` config. @@ -23,7 +23,7 @@ For `hook.php`: $telegram->setCommandConfig('payment', ['payment_provider_token' => 'your_payment_provider_token_here']); ``` -For `manager.php`, in the config array add: +For `manager.php` or using a general `config.php`, in the config array add: ```php ... 'commands' => [ diff --git a/Commands/ServiceMessages/GenericmessageCommand.php b/Commands/ServiceMessages/GenericmessageCommand.php new file mode 100644 index 0000000..dbbf2cf --- /dev/null +++ b/Commands/ServiceMessages/GenericmessageCommand.php @@ -0,0 +1,74 @@ +getMessage(); + + /** + * Catch and handle any service messages here. + */ + + // The chat photo was deleted + $delete_chat_photo = $message->getDeleteChatPhoto(); + + // The group has been created + $group_chat_created = $message->getGroupChatCreated(); + + // The supergroup has been created + $supergroup_chat_created = $message->getSupergroupChatCreated(); + + // The channel has been created + $channel_chat_created = $message->getChannelChatCreated(); + + // Information about the payment + $successful_payment = $message->getSuccessfulPayment(); + + return Request::emptyResponse(); + } +} diff --git a/Commands/StartCommand.php b/Commands/StartCommand.php index dd51069..379a0d7 100644 --- a/Commands/StartCommand.php +++ b/Commands/StartCommand.php @@ -25,7 +25,6 @@ use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Exception\TelegramException; -use Longman\TelegramBot\Request; class StartCommand extends SystemCommand { diff --git a/README.md b/README.md index 38c428f..1a12418 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ # PHP Telegram Bot Example + +> :construction: Work In Progress :construction: + An A-Z example of Telegram bot using the [PHP Telegram Bot][core-github] library. This repository aims to demonstrate the usage of all the features offered by the PHP Telegram Bot library and as such contains all example commands. @@ -68,6 +71,14 @@ Now you can install all dependencies using [composer]: $ composer install ``` +## 2. Adding your own commands + +You can find a few example commands in the [`Commands`](Commands) folder. + +Do **NOT** just copy all of them to your bot, but instead learn from them and only add to your bot what you need. + +Adding any extra commands to your bot that you don't need can be a security risk! + ## To be continued! [core-github]: https://github.com/php-telegram-bot/core "php-telegram-bot/core" diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 9fb9029..434bfc6 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -15,8 +15,8 @@ - - + + From 0927df80d406a0247ad007134b25b22dac79a49c Mon Sep 17 00:00:00 2001 From: massadm <38354121+massadm@users.noreply.github.com> Date: Wed, 17 Feb 2021 19:49:43 +0300 Subject: [PATCH 30/43] Update hook.php Syntax error in commented part related to logging. --- hook.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hook.php b/hook.php index 4c70f06..c8e3ddb 100644 --- a/hook.php +++ b/hook.php @@ -43,11 +43,11 @@ // (this example requires Monolog: composer require monolog/monolog) // Longman\TelegramBot\TelegramLog::initialize( // new Monolog\Logger('telegram_bot', [ - // (new Monolog\Handler\StreamHandler($config['logging']['debug']", Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), - // (new Monolog\Handler\StreamHandler($config['logging']['error']", Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler($config['logging']['debug'], Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + // (new Monolog\Handler\StreamHandler($config['logging']['error'], Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), // ]), // new Monolog\Logger('telegram_bot_updates', [ - // (new Monolog\Handler\StreamHandler($config['logging']['update']", Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + // (new Monolog\Handler\StreamHandler($config['logging']['update'], Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), // ]) // ); From f52791754f09fa4c2a8f3a5309502f0c391ae676 Mon Sep 17 00:00:00 2001 From: Erfan Bahramali Date: Sat, 12 Jun 2021 12:36:56 +0430 Subject: [PATCH 31/43] Fix namespace for PaymentCommand class --- Commands/Payments/GenericmessageCommand.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Commands/Payments/GenericmessageCommand.php b/Commands/Payments/GenericmessageCommand.php index 9ecd0ac..06be16e 100644 --- a/Commands/Payments/GenericmessageCommand.php +++ b/Commands/Payments/GenericmessageCommand.php @@ -19,6 +19,7 @@ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Commands\UserCommands\PaymentCommand; use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Request; From c513b9c5d2f40793fb3853500d38ac25f9ef16c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Mon, 14 Jun 2021 16:18:44 +0200 Subject: [PATCH 32/43] Minor fixes --- Commands/Conversation/CancelCommand.php | 2 +- Commands/Conversation/SurveyCommand.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Commands/Conversation/CancelCommand.php b/Commands/Conversation/CancelCommand.php index b74ebf7..4fa034d 100644 --- a/Commands/Conversation/CancelCommand.php +++ b/Commands/Conversation/CancelCommand.php @@ -96,7 +96,7 @@ public function execute(): ServerResponse * @return ServerResponse * @throws TelegramException */ - private function removeKeyboard($text): ServerResponse + private function removeKeyboard(string $text): ServerResponse { return $this->replyToChat($text, [ 'reply_markup' => Keyboard::remove(['selective' => true]), diff --git a/Commands/Conversation/SurveyCommand.php b/Commands/Conversation/SurveyCommand.php index e2bc007..6dd710c 100644 --- a/Commands/Conversation/SurveyCommand.php +++ b/Commands/Conversation/SurveyCommand.php @@ -36,7 +36,7 @@ class SurveyCommand extends UserCommand /** * @var string */ - protected $description = 'Survery for bot users'; + protected $description = 'Survey for bot users'; /** * @var string From c7b054ffaebcb0cc4a6d0bae4e6cf6bf0fb85cbe Mon Sep 17 00:00:00 2001 From: Hitmare Date: Fri, 12 Nov 2021 14:56:17 +0100 Subject: [PATCH 33/43] Update config.example.php --- config.example.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.example.php b/config.example.php index 45bffec..feaccf1 100644 --- a/config.example.php +++ b/config.example.php @@ -44,7 +44,7 @@ 'commands' => [ // Define all paths for your custom commands 'paths' => [ - // __DIR__ . '/Commands', + // __DIR__ . '/CustomCommands', ], // Here you can set any command-specific parameters 'configs' => [ From a3713da09e2dfdf7d36ba081c4ea1282ad4cca44 Mon Sep 17 00:00:00 2001 From: Hitmare Date: Fri, 12 Nov 2021 15:00:22 +0100 Subject: [PATCH 34/43] Create README.md --- CustomCommands/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 CustomCommands/README.md diff --git a/CustomCommands/README.md b/CustomCommands/README.md new file mode 100644 index 0000000..5b322d4 --- /dev/null +++ b/CustomCommands/README.md @@ -0,0 +1,9 @@ +# CustomCommands +Uncomment line 47 in your config.php from +`// __DIR__ . '/CustomCommands',` +to +`__DIR__ . '/CustomCommands',` +to enable this Folder. +You then can copy example Commands from the Command folder. +**:exclamation: Important!** +DO NOT COPY THE ENTIRE FOLDER CONTENT!! \ No newline at end of file From 71ad26f602dd216885c61566298db14dd498be99 Mon Sep 17 00:00:00 2001 From: Hitmare Date: Fri, 12 Nov 2021 15:01:18 +0100 Subject: [PATCH 35/43] Update README.md --- CustomCommands/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CustomCommands/README.md b/CustomCommands/README.md index 5b322d4..d84445a 100644 --- a/CustomCommands/README.md +++ b/CustomCommands/README.md @@ -5,5 +5,7 @@ to `__DIR__ . '/CustomCommands',` to enable this Folder. You then can copy example Commands from the Command folder. + **:exclamation: Important!** -DO NOT COPY THE ENTIRE FOLDER CONTENT!! \ No newline at end of file + +DO NOT COPY THE ENTIRE FOLDER CONTENT!! From a044bd3d4237f6a5d91840dbc2a87c61f5f885c9 Mon Sep 17 00:00:00 2001 From: Hitmare Date: Fri, 12 Nov 2021 15:02:20 +0100 Subject: [PATCH 36/43] Update README.md --- CustomCommands/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CustomCommands/README.md b/CustomCommands/README.md index d84445a..55c671d 100644 --- a/CustomCommands/README.md +++ b/CustomCommands/README.md @@ -8,4 +8,5 @@ You then can copy example Commands from the Command folder. **:exclamation: Important!** -DO NOT COPY THE ENTIRE FOLDER CONTENT!! +DO NOT COPY THE ENTIRE COMMAND FOLDER CONTENT!! +Some Command Files are Duplicated and may interfere with each other. From 9ba7b242f87ce50e92aa513463a473a3d08dc7eb Mon Sep 17 00:00:00 2001 From: Hitmare Date: Fri, 12 Nov 2021 15:02:29 +0100 Subject: [PATCH 37/43] Update README.md --- CustomCommands/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CustomCommands/README.md b/CustomCommands/README.md index 55c671d..68f6bcc 100644 --- a/CustomCommands/README.md +++ b/CustomCommands/README.md @@ -9,4 +9,5 @@ You then can copy example Commands from the Command folder. **:exclamation: Important!** DO NOT COPY THE ENTIRE COMMAND FOLDER CONTENT!! + Some Command Files are Duplicated and may interfere with each other. From 024efaa46003a8ebd3e25c39798ff9f3a5808b2b Mon Sep 17 00:00:00 2001 From: Hitmare Date: Mon, 10 Jan 2022 16:46:44 +0100 Subject: [PATCH 38/43] Update Readme Updated the Readme "Adding your own commands" with the instruction to use/enable the CustomCommands to be able to use Commands --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1a12418..4fd8b51 100644 --- a/README.md +++ b/README.md @@ -73,10 +73,12 @@ $ composer install ## 2. Adding your own commands -You can find a few example commands in the [`Commands`](Commands) folder. +To use Commands enable the [`CustomCommands`](CustomCommands) folder in the config. +You can find a few example commands in the [`Commands`](Commands) folder. Do **NOT** just copy all of them to your bot, but instead learn from them and only add to your bot what you need. + Adding any extra commands to your bot that you don't need can be a security risk! ## To be continued! From 0b3f3f575a320a766ac10faab194fae26a926662 Mon Sep 17 00:00:00 2001 From: Hitmare Date: Tue, 9 Aug 2022 14:14:09 +0200 Subject: [PATCH 39/43] Update Comment for Command folder Config Update Comment for Command folder Config so its more visible to the User --- config.example.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/config.example.php b/config.example.php index feaccf1..008f2fb 100644 --- a/config.example.php +++ b/config.example.php @@ -43,6 +43,8 @@ // All command related configs go here 'commands' => [ // Define all paths for your custom commands + // DO NOT PUT THE COMMAND FOLDER THERE. IT WILL NOT WORK. + // Copy each needed Commandfile into the CustomCommand folder and uncommend the Line 49 below 'paths' => [ // __DIR__ . '/CustomCommands', ], From 3f8afdd94843c3093c9a9c5121238a330cff0b10 Mon Sep 17 00:00:00 2001 From: Hitmare Date: Tue, 13 Jun 2023 11:55:43 +0200 Subject: [PATCH 40/43] Create README.MD Created File --- Commands/README.MD | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Commands/README.MD diff --git a/Commands/README.MD b/Commands/README.MD new file mode 100644 index 0000000..2ed5fee --- /dev/null +++ b/Commands/README.MD @@ -0,0 +1,19 @@ +This Folder contains some examples how to use the Telegram Bot API + + +** :exclamation: DO NOT USE THE COMMANDS FOLDER ** +As the title says, do not include the Commands folder into your config to use it as it is. +Why? This folder contains some files multiple times which is an issue for the bot software, since every file can only exist once! +For example: GenericmessageCommand.php +This file exist in the following folder: +- Conversation +- Group +- Message +- Payments + +Having any Command file more than once will cause conflicts between those file, causing only one file to be executed and the others ignored. +Please copy each file and/or folder that you need into the CustomCommans folder. +If you want to create your own Command file, please do it so in the CustomCommands folder as well. +If you need for example the GenericmessageCommand.php from the Conversation and Group folder, you will need to compara and merge those files. + + From 30eec10935cc741b8bc060da8e1c9c095d37ff75 Mon Sep 17 00:00:00 2001 From: Hitmare Date: Tue, 13 Jun 2023 11:56:13 +0200 Subject: [PATCH 41/43] Update README.MD 2 --- Commands/README.MD | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Commands/README.MD b/Commands/README.MD index 2ed5fee..1ff6a9c 100644 --- a/Commands/README.MD +++ b/Commands/README.MD @@ -1,7 +1,8 @@ This Folder contains some examples how to use the Telegram Bot API -** :exclamation: DO NOT USE THE COMMANDS FOLDER ** +**:exclamation: DO NOT USE THE COMMANDS FOLDER** + As the title says, do not include the Commands folder into your config to use it as it is. Why? This folder contains some files multiple times which is an issue for the bot software, since every file can only exist once! For example: GenericmessageCommand.php From 8ea6db2385441ed15a3c13e3c798de239f7945e2 Mon Sep 17 00:00:00 2001 From: Hitmare Date: Tue, 13 Jun 2023 11:56:59 +0200 Subject: [PATCH 42/43] Update README.MD 3 --- Commands/README.MD | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Commands/README.MD b/Commands/README.MD index 1ff6a9c..2565b7a 100644 --- a/Commands/README.MD +++ b/Commands/README.MD @@ -1,10 +1,12 @@ -This Folder contains some examples how to use the Telegram Bot API +This Folder contains some examples how to use the Telegram Bot API with the Telegram PHP Bot library **:exclamation: DO NOT USE THE COMMANDS FOLDER** As the title says, do not include the Commands folder into your config to use it as it is. + Why? This folder contains some files multiple times which is an issue for the bot software, since every file can only exist once! + For example: GenericmessageCommand.php This file exist in the following folder: - Conversation @@ -13,8 +15,11 @@ This file exist in the following folder: - Payments Having any Command file more than once will cause conflicts between those file, causing only one file to be executed and the others ignored. -Please copy each file and/or folder that you need into the CustomCommans folder. + +Please copy each file and/or folder that you need into the CustomCommans folder. + If you want to create your own Command file, please do it so in the CustomCommands folder as well. + If you need for example the GenericmessageCommand.php from the Conversation and Group folder, you will need to compara and merge those files. From 7c5a491351242305778e19bb90c8b2cdad3327ac Mon Sep 17 00:00:00 2001 From: Julian Prieber <60265788+JulianPrieber@users.noreply.github.com> Date: Thu, 7 Dec 2023 17:50:11 +0100 Subject: [PATCH 43/43] Minor grammar and spelling fixes --- Commands/README.MD | 9 ++++----- CustomCommands/README.md | 6 +++--- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/Commands/README.MD b/Commands/README.MD index 2565b7a..2c35009 100644 --- a/Commands/README.MD +++ b/Commands/README.MD @@ -1,14 +1,14 @@ -This Folder contains some examples how to use the Telegram Bot API with the Telegram PHP Bot library +This Folder contains some examples of how to use the Telegram Bot API with the Telegram PHP Bot library **:exclamation: DO NOT USE THE COMMANDS FOLDER** As the title says, do not include the Commands folder into your config to use it as it is. -Why? This folder contains some files multiple times which is an issue for the bot software, since every file can only exist once! +Why? This folder contains some files multiple times, which is an issue for the bot software, since every file can only exist once! For example: GenericmessageCommand.php -This file exist in the following folder: +This file exists in the following folder: - Conversation - Group - Message @@ -20,6 +20,5 @@ Please copy each file and/or folder that you need into the CustomCommans folder. If you want to create your own Command file, please do it so in the CustomCommands folder as well. -If you need for example the GenericmessageCommand.php from the Conversation and Group folder, you will need to compara and merge those files. - +If you need, for example, the GenericmessageCommand.php from the Conversation and Group folder, you will need to compare and merge those files. diff --git a/CustomCommands/README.md b/CustomCommands/README.md index 68f6bcc..8794038 100644 --- a/CustomCommands/README.md +++ b/CustomCommands/README.md @@ -3,11 +3,11 @@ Uncomment line 47 in your config.php from `// __DIR__ . '/CustomCommands',` to `__DIR__ . '/CustomCommands',` -to enable this Folder. -You then can copy example Commands from the Command folder. +to enable this folder. +You can then copy example commands from the Command folder. **:exclamation: Important!** DO NOT COPY THE ENTIRE COMMAND FOLDER CONTENT!! -Some Command Files are Duplicated and may interfere with each other. +Some command files are duplicated and may interfere with each other.