diff --git a/README.md b/README.md index d7077646b..38f209782 100644 --- a/README.md +++ b/README.md @@ -12,29 +12,36 @@ A Telegram Bot based on the official [Telegram Bot API](https://core.telegram.org/bots/api) -### Introduction -This is a pure php Telegram Bot, fully extensible via plugins. +## Introduction + +This is a pure PHP Telegram Bot, fully extensible via plugins. Telegram recently announced official support for a [Bot API](https://telegram.org/blog/bot-revolution) allowing integrators of all sorts to bring automated interactions to the mobile platform. This -Bot aims to provide a platform where one could simply write a plugin +Bot aims to provide a platform where one can simply write a plugin and have interactions in a matter of minutes. + The Bot can: -- retrive update with webhook and getUpdate methods. +- retrieve updates with webhook and getUpdate methods. - supports all types and methods according to Telegram API (20 January 2016). - supports supergroups. - handle commands in chat with other bots. -- manage Channel from the bot admin interface -- Full support for **inline bots** (**new!**) -- Messages, InlineQuery and ChosenInlineQuery are stored in the Database (**new!**) +- manage Channel from the bot admin interface. +- full support for **inline bots**. (**new!**) +- Messages, InlineQuery and ChosenInlineQuery are stored in the Database. (**new!**) + +----- +This code is available on +[Github](https://github.com/akalongman/php-telegram-bot). Pull requests are welcome. ## Instructions + ### Create your first bot 1. Message @botfather https://telegram.me/botfather with the following text: `/newbot` If you don't know how to message by username, click the search -field on your Telegram app and type `@botfather`, you should be able +field on your Telegram app and type `@botfather`, where you should be able to initiate a conversation. Be careful not to send it to the wrong contact, because some users has similar usernames to `botfather`. @@ -45,25 +52,27 @@ call it? Please choose a name for your bot.` 3. Type whatever name you want for your bot. -4. @botfather replies with `Good. Now let's choose a username for your +4. @botfather replies with ```Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or -tetris_bot.` +tetris_bot.``` 5. Type whatever username you want for your bot, minimum 5 characters, and must end with `bot`. For example: `telesample_bot` 6. @botfather replies with: + ``` Done! Congratulations on your new bot. You will find it at -telegram.me/telesample_bot. You can now add a description, about -section and profile picture for your bot, see /help for a list of -commands. + telegram.me/telesample_bot. You can now add a description, about + section and profile picture for your bot, see /help for a list of + commands. Use this token to access the HTTP API: - 123456789:AAG90e14-0f8-40183D-18491dDE + 123456789:AAG90e14-0f8-40183D-18491dDE For a description of the Bot API, see this page: -https://core.telegram.org/bots/api + https://core.telegram.org/bots/api + ``` 7. Note down the 'token' mentioned above. @@ -73,28 +82,29 @@ https://core.telegram.org/bots/api 9. @botfather replies with `Choose a bot to change group messages settings.` -10. Type `@telesample_bot` (change to the username you set at step 5 +10. Type (or select) `@telesample_bot` (change to the username you set at step 5 above, but start it with `@`) 11. @botfather replies with - 'Enable' - your bot will only receive messages that either start -with the '/' symbol or mention the bot by username. + ``` + 'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username. 'Disable' - your bot will receive all messages that people send to groups. Current status is: ENABLED + ``` -12. Type `Disable` to let your bot receive all messages sent to a +12. Type (or select) `Disable` to let your bot receive all messages sent to a group. This step is up to you actually. 13. @botfather replies with `Success! The new status is: DISABLED. /help` - ### Require this package with Composer + Install this package through [Composer](https://getcomposer.org/). Edit your project's `composer.json` file to require `longman/telegram-bot`. -Create *composer.json* file: +Create *composer.json* file ```js { "name": "yourproject/yourproject", @@ -105,40 +115,47 @@ Create *composer.json* file: } } ``` -And run composer update +and run `composer update` + +**or** -**Or** run a command in your command line: +run this command in your command line: ``` composer require longman/telegram-bot ``` ### Choose how to retrieve Telegram updates + The bot can handle updates with **webhook** or **getUpdate** method: | | Webhook | getUpdate | | ---- | :----: | :----: | -| Description | Telegram send the update directy to your host | You have to fetch Telegram updates | +| Description | Telegram sends the updates directly to your host | You have to fetch Telegram updates manually | | Host with https | Required | Not required | -| Mysql | Not required | Required | +| MySQL | Not required | Required | + ## Webhook installation -You need server with https and composer support. -You must set a [WebHook](https://core.telegram.org/bots/api#setwebhook). -Create *set.php* (just copy and edit *examples/set.php*) and put into it: + +In order to set a [Webhook](https://core.telegram.org/bots/api#setwebhook) you need a server with https and composer support. +(For a [self signed certificate](#self-signed-certificate) you need to add some extra code) + +Create *set.php* (or just copy and edit *examples/set.php*) and put into it: ```php setWebHook($link); + + // Set webhook + $result = $telegram->setWebHook($hook_url); if ($result->isOk()) { echo $result->getDescription(); } @@ -147,60 +164,75 @@ try { } ``` -And open your *set.php* via browser. +Open your *set.php* via the browser to register the webhook with Telegram. -After, create *hook.php* (or just copy and edit *examples/hook.php*) and put: +Now, create *hook.php* (or just copy and edit *examples/hook.php*) and put into it: ```php handle(); } catch (Longman\TelegramBot\Exception\TelegramException $e) { + // Silence is golden! // log telegram errors // echo $e; } ``` -###Self Signed Certificate -To upload the certificate, add the certificate path as param in *set.php*: +### Self Signed Certificate + +To upload the certificate, add the certificate path as a parameter in *set.php*: ```php -$result = $telegram->setWebHook($url, $certificate_path); +$result = $telegram->setWebHook($hook_url, $certificate_path); ``` +### Unset Webhook + +Edit *example/unset.php* with your bot credentials and execute it. + ## getUpdate installation -You need the database Mysql active. -Create *getUpdateCLI.php* (just copy and edit *examples/getUpdateCLI.php*) and put into it: +The MySQL database must be active! + +Create *getUpdateCLI.php* (or just copy and edit *examples/getUpdateCLI.php*) and put into it: ```php #!/usr/bin/env php 'localhost', 'user'=>'dbuser', 'password'=>'dbpass', 'database'=>'dbname'); +$mysql_credentials = [ + 'host' => 'localhost', + 'user' => 'dbuser', + 'password' => 'dbpass', + 'database' => 'dbname', +]; try { - // create Telegram API object + // Create Telegram API object $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); - $telegram->enableMySQL($credentials); - // handle telegram getUpdate request + + // Enable MySQL + $telegram->enableMySQL($mysql_credentials); + + // Handle telegram getUpdate request $telegram->handleGetUpdates(); } catch (Longman\TelegramBot\Exception\TelegramException $e) { // log telegram errors - echo $e; + echo $e; } ``` -give to the file the permission for execution: +give the file permission to execute: ``` chmod 775 getUpdateCLI.php ``` @@ -208,91 +240,119 @@ then run ``` ./getUpdateCLI.php ``` + +## Support + ### Types -All types implemented according to Telegram API (20 January 2016). -#### Inline Query +All types are implemented according to Telegram API (20 January 2016). + +### Inline Query + Full support for inline query according to Telegram API (20 January 2016). ### Methods -All methods implemented according to Telegram API (20 January 2016). -####Send Message -Message longer than 4096 characters are splitted in more messages. +All methods are implemented according to Telegram API (20 January 2016). + +#### Send Message + +Messages longer than 4096 characters are split up into multiple messages. ```php $result = Request::sendMessage(['chat_id' => $chat_id, 'text' => 'Your utf8 text 😜 ...']); ``` -####Send Photo -To send a local photo provide the file path as second param: +#### Send Photo + +To send a local photo, provide the file path as the second parameter: ```php -$data['chat_id'] = $chat_id; -$result = Request::sendPhoto($data,$this->telegram->getUploadPath().'/'.'image.jpg'); +$data = ['chat_id' => $chat_id]; +$result = Request::sendPhoto($data, $telegram->getUploadPath() . '/image.jpg'); ``` -If you know the file_id of a previously uploaded file, just provide it in the fist param: +If you know the `file_id` of a previously uploaded file, just include it in the data array: ```php -$data['chat_id'] = $chat_id; -$data['photo'] = $file_id; +$data = [ + 'chat_id' => $chat_id, + 'photo' => $file_id, +]; $result = Request::sendPhoto($data); ``` -*sendAudio*, *sendDocument*, *sendSticker*, *sendVideo* and *sendVoice* works in the same way. -See *ImageCommand.php* for a full example. -####Send Chat Action +*sendAudio*, *sendDocument*, *sendSticker*, *sendVideo* and *sendVoice* all work in the same way. +See *examples/Commands/ImageCommand.php* for a full example. + +#### Send Chat Action ```php Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']); ``` -####getUserProfilePhoto -Retrieve the user photo, see the *WhoamiCommand.php* for a full example. -####GetFile and dowloadFile -Get the file path and download it, see the *WhoamiCommand.php* for a full example. +#### getUserProfilePhoto + +Retrieve the user photo, see *src/Commands/WhoamiCommand.php* for a full example. + +#### getFile and dowloadFile + +Get the file path and download it, see *src/Commands/WhoamiCommand.php* for a full example. #### Send message to all active chats -To do this you have to enable the Mysql connection. + +To do this you have to enable the MySQL connection. Here's an example of use: ```php -$results = $telegram->sendToActiveChats( - 'sendMessage', //callback function to execute (see Request.php methods) - array('text'=>'Hey! Checkout the new feature!!'), //Param to evaluate the request - true, //Send to chats (group chat) - true, //Send to users (single chat) - null, //'yyyy-mm-dd hh:mm:ss' date range from - null //'yyyy-mm-dd hh:mm:ss' date range to +$results = Request::sendToActiveChats( + 'sendMessage', // callback function to execute (see Request.php for available methods) + ['text' => 'Hey! Check out the new features!!'], // Data to pass to the request + true, // Send to chats (group chat) + true, // Send to chats (super group chat) + true, // Send to users (single chat) + null, // 'yyyy-mm-dd hh:mm:ss' date range from + null, // 'yyyy-mm-dd hh:mm:ss' date range to ); ``` -You can also broadcast message to users, from the private chat with your bot. Take a look at the admin interace below. -## Utilis -### MySQL storage (Recomended) -If you want insert in database messages/users/chats for further usage -in commands, create database and import *structure.sql* and enable -Mysql support after object creation and BEFORE handle method: -```php -$credentials = ['host'=>'localhost', 'user'=>'dbuser', -'password'=>'dbpass', 'database'=>'dbname']; +You can also broadcast a message to users, from the private chat with your bot. Take a look at the [admin commands](#admin-commands) below. -$telegram->enableMySQL($credentials); +## Utils + +### MySQL storage (Recommended) + +If you want to save messages/users/chats for further usage +in commands, create a new database, import *structure.sql* and enable +MySQL support after object creation and BEFORE handle method: + +```php +$mysql_credentials = [ + 'host' => 'localhost', + 'user' => 'dbuser', + 'password' => 'dbpass', + 'database' => 'dbname', +]; + +$telegram->enableMySQL($mysql_credentials); ``` -You can set a custom prefix to all the tables while you are enabling Mysql: +You can set a custom prefix to all the tables while you are enabling MySQL: ```php -$telegram->enableMySQL($credentials, $BOT_NAME.'_'); +$telegram->enableMySQL($mysql_credentials, $BOT_NAME . '_'); ``` + Consider to use the *utf8mb4* branch if you find some special characters problems. You can also store inline query and chosen inline query in the database. -### Channels Support -All methods implemented can be used to manage channels. -With admin interface you can manage your channel directly with your bot private chat. + +### Channels Support + +All methods implemented can be used to manage channels. +With [admin commands](#admin-commands) you can manage your channel directly with your bot private chat. ### Commands -The bot is able to recognise commands in chat with multiple bot (/command@mybot ). + +The bot is able to recognise commands in a chat with multiple bots (/command@mybot). It can execute command triggering a chat event. Here's the list: - New chat participant (**NewchatparticipantCommand.php**) @@ -305,90 +365,92 @@ It can execute command triggering a chat event. Here's the list: - Inline query (**InlinequeryCommand.php**) - Chosen inline result (**ChoseninlineresultCommand.php**) - -**GenericCommand.php** let you handle commands that don't exist or to +**GenericCommand.php** lets you handle commands that don't exist or to use commands as a variable: + Favourite colour? **/black, /red** + Favourite number? **/1, /134** -**GenericmessageCommand.php** let you handle any type of message. +**GenericmessageCommand.php** lets you handle any type of message. Maybe you would like to develop your own commands. A good practice is -to store them outside *vendor/*. This can be done adding the method: +to store them outside *vendor/*. This can be done using: ```php -$COMMANDS_FOLDER = __DIR__.'/Commands/'; -$telegram->addCommandsPath($COMMANDS_FOLDER); +$commands_folder = __DIR__ . '/Commands/'; +$telegram->addCommandsPath($commands_folder); ``` -Inside *examples/Commands/* there are some sample that show how to use types. +Inside *examples/Commands/* there are some samples that show how to use types. #### Commands Configuration -With this method you can set some command specified parameters, for + +With this method you can set some command specific parameters, for example, google geocode/timezone api key for date command: ```php $telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); ``` ### Admin Commands -Enabling this feature, the admin bot can perform some super user command like: + +Enabling this feature, the admin bot can perform some super user commands like: - Send message to all chats */sendtoall* - List all the chats started with the bot */chats* - Send a message to a channel */sendtochannel* (NEW! see below how to configure it) -You can specify one or more admin with this option: +You can specify one or more admins with this option: ```php -$telegram->enableAdmins(['your_telegram_user_id','Othersid']); +$telegram->enableAdmins(['your_telegram_user_id', 'other_telegram_user_id']); ``` Telegram user id can be retrieved with the command **/whoami**. Admin commands are stored in *src/Admin/* folder. -To know all the commands avaiable type **/help**. +To get a list of all available commands, type **/help**. + +#### Channel Administration -#### Channel Administration -To enable this feature follow those steps: +To enable this feature follow these steps: - Add your bot as channel administrator, this can be done with any telegram client. - Enable admin interface for your user as explained in the admin section above. -- Enter your channel name as a param for the sendtoall command: +- Enter your channel name as a parameter for the */sendtochannel* command: ```php - $telegram->setCommandConfig('sendtochannel', ['your_channel'=>'@type_here_your_channel']); +$telegram->setCommandConfig('sendtochannel', ['your_channel' => '@type_here_your_channel']); ``` - Enjoy! ### Upload and Download directory path -You can overwrite the default Upload and Download directory with: + +You can override the default Upload and Download directory with: ```php -$telegram->setDownloadPath("yourpath/Download"); -$telegram->setUploadPath("yourpath../Upload"); +$telegram->setDownloadPath('yourpath/Download'); +$telegram->setUploadPath('yourpath/Upload'); ``` -###Unset Webhook -Edit *example/unset.php* with your credential and execute it. ### Logging -Thrown Exception are stored in *TelegramException.log* file (in the base directory). -Incoming update (json string from webhook and getUpdates) can be logged on a text file, set those options with the methods: +Thrown Exceptions are stored in *TelegramException.log* file (in the base directory). + +Incoming update (json string from webhook and getUpdates) can be logged in a text file. Set those options with the methods: ```php $telegram->setLogRequests(true); -$telegram->setLogPath($BOT_NAME.'.log'); +$telegram->setLogPath($BOT_NAME . '.log'); ``` -Set verbosity to 3, to log also curl requests and responses from the bot to Telegram: +Set verbosity to 3 to also log curl requests and responses from the bot to Telegram: ```php $telegram->setLogRequests(true); -$telegram->setLogPath($BOT_NAME.'.log'); +$telegram->setLogPath($BOT_NAME . '.log'); $telegram->setLogVerbosity(3); ``` ------ -This code is available on -[Github](https://github.com/akalongman/php-telegram-bot). Pull requests are welcome. +## Documentation -##Documentation Take a look at the repo [Wiki](https://github.com/akalongman/php-telegram-bot/wiki) for further information and tutorial! Feel free to improve! -##Project with this library +## Projects with this library + Here's a list of projects that feats this library, feel free to add yours! - [Super-Dice-Roll](https://github.com/RafaelDelboni/Super-Dice-Roll) [@superdiceroll_bot](https://telegram.me/superdiceroll_bot) @@ -399,14 +461,13 @@ If you like living on the edge, please report any bugs you find on the ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md) for information. +See [CONTRIBUTING](CONTRIBUTING.md) for more information. ## License Please see the [LICENSE](LICENSE.md) included in this repository for a full copy of the MIT license, which this project is licensed under. - ## Credits Credit list in [CREDITS](CREDITS) diff --git a/examples/getUpdatesCLI.php b/examples/getUpdatesCLI.php index e6bed680e..c34ab3053 100644 --- a/examples/getUpdatesCLI.php +++ b/examples/getUpdatesCLI.php @@ -2,66 +2,65 @@ 'localhost', - 'user'=>'dbuser', - 'password'=>'dbpass', - 'database'=>'dbname' +//$commands_path = __DIR__ . '/Commands/'; +$mysql_credentials = [ + 'host' => 'localhost', + 'user' => 'dbuser', + 'password' => 'dbpass', + 'database' => 'dbname', ]; try { - // create Telegram API object + // Create Telegram API object $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); - ////Options - $telegram->enableMySQL($credentials); - - ////Enable mysql with table prefix - //$telegram->enableMySQL($credentials, $BOT_NAME.'_'); + // Enable MySQL + $telegram->enableMySQL($mysql_credentials); - //$telegram->addCommandsPath($COMMANDS_FOLDER); + //// Enable MySQL with table prefix + //$telegram->enableMySQL($mysql_credentials, $BOT_NAME . '_'); - ////Here you can enable admin interface ache the channel you want to manage + //// Add an additional commands path + //$telegram->addCommandsPath($commands_path); + + //// Here you can enable admin interface for the channel you want to manage //$telegram->enableAdmins(['your_telegram_id']); - //$telegram->setCommandConfig('sendtochannel', ['your_channel'=>'@type_here_your_channel']); + //$telegram->setCommandConfig('sendtochannel', ['your_channel' => '@type_here_your_channel']); - ////Here you can set some command specified parameters, - ////for example, google geocode/timezone api key for date command: - //$telegram->setCommandConfig('date', array('google_api_key'=>'your_google_api_key_here')); + //// Here you can set some command specific parameters, + //// for example, google geocode/timezone api key for date command: + //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); - ////Logging + //// Logging //$telegram->setLogRequests(true); - //$telegram->setLogPath($BOT_NAME.'.log'); + //$telegram->setLogPath($BOT_NAME . '.log'); //$telegram->setLogVerbosity(3); - //$telegram->setDownloadPath("../Download"); - //$telegram->setUploadPath("../Upload"); + //// Set custom Upload and Download path + //$telegram->setDownloadPath('../Download'); + //$telegram->setUploadPath('../Upload'); - // handle telegram getUpdate request + // Handle telegram getUpdate request $ServerResponse = $telegram->handleGetUpdates(); if ($ServerResponse->isOk()) { $n_update = count($ServerResponse->getResult()); - - print(date('Y-m-d H:i:s', time()).' - Processed '.$n_update." updates\n"); + print(date('Y-m-d H:i:s', time()) . ' - Processed ' . $n_update . ' updates' . "\n"); } else { - print(date('Y-m-d H:i:s', time())." - Fail fetch updates\n"); - echo $ServerResponse->printError()."\n"; + print(date('Y-m-d H:i:s', time()) . ' - Failed to fetch updates' . "\n"); + echo $ServerResponse->printError() . "\n"; } - } catch (Longman\TelegramBot\Exception\TelegramException $e) { // log telegram errors - echo $e; + echo $e; } diff --git a/examples/hook.php b/examples/hook.php index dbf273247..b212f7650 100644 --- a/examples/hook.php +++ b/examples/hook.php @@ -1,57 +1,57 @@ 'localhost', -// 'user'=>'dbuser', -// 'password'=>'dbpass', -// 'database'=>'dbname' +//$commands_path = __DIR__ . '/Commands/'; +//$mysql_credentials = [ +// 'host' => 'localhost', +// 'user' => 'dbuser', +// 'password' => 'dbpass', +// 'database' => 'dbname', //]; try { - // create Telegram API object + // Create Telegram API object $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); - ////Options - $telegram->enableMySQL($credentials); - - ////Enable mysql with table prefix - //$telegram->enableMySQL($credentials, $BOT_NAME.'_'); + //// Enable MySQL + //$telegram->enableMySQL($mysql_credentials); - //$telegram->addCommandsPath($COMMANDS_FOLDER); + //// Enable MySQL with table prefix + //$telegram->enableMySQL($mysql_credentials, $BOT_NAME . '_'); - ////Here you can enable admin interface ache the channel you want to manage + //// Add an additional commands path + //$telegram->addCommandsPath($commands_path); + + //// Here you can enable admin interface for the channel you want to manage //$telegram->enableAdmins(['your_telegram_id']); - //$telegram->setCommandConfig('sendtochannel', ['your_channel'=>'@type_here_your_channel']); + //$telegram->setCommandConfig('sendtochannel', ['your_channel' => '@type_here_your_channel']); - ////Here you can set some command specified parameters, - ////for example, google geocode/timezone api key for date command: - //$telegram->setCommandConfig('date', array('google_api_key'=>'your_google_api_key_here')); + //// Here you can set some command specific parameters, + //// for example, google geocode/timezone api key for date command: + //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); - ////Logging + //// Logging //$telegram->setLogRequests(true); - //$telegram->setLogPath($BOT_NAME.'.log'); + //$telegram->setLogPath($BOT_NAME . '.log'); //$telegram->setLogVerbosity(3); - //$telegram->setDownloadPath("../Download"); - //$telegram->setUploadPath("../Upload"); + //// Set custom Upload and Download path + //$telegram->setDownloadPath('../Download'); + //$telegram->setUploadPath('../Upload'); - // handle telegram webhook request + // Handle telegram webhook request $telegram->handle(); - } catch (Longman\TelegramBot\Exception\TelegramException $e) { - //Silence is gold! + // Silence is golden! // log telegram errors // echo $e; } diff --git a/examples/set.php b/examples/set.php index da2d93a27..65e89d2b1 100644 --- a/examples/set.php +++ b/examples/set.php @@ -1,18 +1,20 @@ setWebHook($link); - //Uncomment to use certificate - //$result = $telegram->setWebHook($link, $path_certificate); + + // Set webhook + $result = $telegram->setWebHook($hook_url); + + // Uncomment to use certificate + //$result = $telegram->setWebHook($hook_url, $path_certificate); + if ($result->isOk()) { echo $result->getDescription(); } diff --git a/examples/unset.php b/examples/unset.php index 2a70f908f..b37a564d1 100644 --- a/examples/unset.php +++ b/examples/unset.php @@ -1,16 +1,16 @@ unsetWebHook(); - //Uncomment to use certificate - //$result = $telegram->setWebHook($link, $path_certificate); + if ($result->isOk()) { echo $result->getDescription(); }