📜 ⬆️ ⬇️

Development of chat bots for Telegram and Slack using PHP

general information

This article describes how to create simple chat bots for Telegram and Slack services using the example of checking IP | Email for spam using the CleanTalk anti-spam service.


Telegram

The first step is to create your bot (in our case, @CleanTalkBot) - for this, there is the @BotFather bot in Telegram. Add it to your Telegram account and set the / newbot command. The bot will ask you to enter the name of the bot - enter the name. After that we enter the bot's username - we have made the bot's name and bot's username the same - while the username must end in bot or Bot - for example, HabrArticleBot or CleanTalkBot. After entering the username, the bot will be created and you will be given a token, which will be used later for identification.



The second step is to install the so-called webhook - in other words, the request handler that comes into the chat bot from users. When a user sets a command to your chat bot, Telegram addresses the address that was set as the webhook, sends the user message and service information, your handler generates a response and sends back Telegram, after which Telegram responds to the user. This is done using the curl command in the terminal -


curl -d "url=https://example.com/telegramwaiter.php" https://api.telegram.org/botYOUR_TELEGRAM_TOKEN/setWebhook 

where YOUR_TELEGRAM_TOKEN is the same token that was given to you by the @BotFather bot earlier, and https://example.com/telegramwaiter.php is the address that Telegram will address with requests. In response, Telegram should return a json type string


 {"ok":true,"result":true,"description":"Webhook is set"} 

which means - the handler for your chat bot has been successfully installed.


Here you need to add that Telegram works only on https - if you have a certificate issued by special organizations (not self-signed), then everything is fine, if you want to use self-signed certificates - please refer to the documentation here https://core.telegram.org/ bots / self-signed .


The third step is to write the request handler from Telegram telegramwaiter.php - a sample script in PHP looks like this


 <?php set_time_limit(0); //   $botToken = "YOUR_TELEGRAM_TOKEN"; $website = "https://api.telegram.org/bot".$botToken; //    Telegram $content = file_get_contents("php://input"); $update = json_decode($content, TRUE); $message = $update["message"]; //     Telegram  ,     $chatId = $message["chat"]["id"]; $text = $message["text"]; //    /start if ($text == '/start') { $welcomemessage = 'Welcome!!! Check IP/Email for spam giving "check IP/Email" command'; //      Telegram  file_get_contents($website."/sendmessage?chat_id=".$chatId."&text=".$welcomemessage); } ?> 

The order is as follows: in the $ text variable, we receive a command from the user in the chat, form a message according to the required logic, and give it back to the user using the file_get_contents () function.


How all this works can be done by adding the @CleanTalkBot bot to the Telegram - enter the command check IP | Email and get information about whether the specified IP | Email is spam.


Response example


 Email stop_email@example.com is BLACKLISTED. Frequency 999. Updated Apr 24 2019. https://cleantalk.org/blacklists/stop_email@example.com. 

Slack


The Slack service has a slightly different approach to creating chat bots.


Go here - https://api.slack.com/apps/new - and create a new Slack application.



AppName is the name of the application.
Short description - a short description of the application.
Describe what your app does on Slack - a complete description of the application.
Link to clear instructions for your Slack app.
Link to support for your Slack app - two links to pages with a description of the installation and use of this application.


In the list of applications https://api.slack.com/apps, select our application and go to the menu on the right by the link Slash Commands and click the button Create new command.



In the form that appears, the following fields



Command - enter the command starting with / - for example / ctcheck.


Request URL - the URL of the command request handler is analogous to a webhook Telegram (for example https://cleantalk.org/slackwaiter.php ).


Short description - a short description of what can be done with the help of the command created.


Save the command. Please note - your site should work on https - while self-signed certificates are NOT SUPPORTED by the Slack service.


You can get the identification token on the command list page - under the list of commands there is the Verification token field - then it appears as YOUR_SLACK_TOKEN.


Writing slackwaiter.php handler in PHP


 <?php set_time_limit(0); //    Slack        Slack if ($_POST['token'] == 'YOUR_SLACK_TOKEN') { // $param -   ,     //    /ctcheck 127.0.0.1 //  $param = 127.0.0.1 $param = $_POST['text']; //         $slackresponse = '   '; } else $slackresponse = ''; $response = array(); $response['text'] = $slackresponse; header('Content-Type: application/json'); echo json_encode($response); ?> 

Next we go here https://api.slack.com/docs/slack-button and in the Add the Slack button section we tick the incoming webhook and commands - Slack forms the html-code of the button, by clicking on which other teams can integrate your application into your Slack account.


The above button is placed on your site - by pressing it, the following picture opens



For authorization, you need to select the channel where you can use the application.


By clicking on the Authorize Slack button redirect the user to the Redirect URI (s) page, which is set by you (the developer) here - https://apilack.com/apps , select your application and follow the link App Credentials - we see the following picture



Slack does not just redirect the user to this page, but adds a GET-variable code with a value that should later be processed by a script - for example


 https://cleantalk.org/authscript.php?code=Slack_Code 

Below is the sample script code authscript.php. CLIENT_ID and CLIENT_SECRET are taken from the corresponding fields in the previous image.


 <?php if (isset($_GET['code'])) { $client_id = 'CLIENT_ID'; $client_secret = 'CLIENT_SECRET'; $code = $_GET['code']; $response = file_get_contents("https://slack.com/api/oauth.access?client_id=".$client_id."& client_secret=".$client_secret."&code=".$code); $responsearr = json_decode($response, true); if (isset($responsearr['team_name'])){ header('Location: https://'.$responsearr['team_name'].'.slack.com'); exit(); } else { echo '.'; exit(); } } else exit(); ?> 

The order is this - we get the code variable from Slack GET and with two more parameters - client_id and client_secret - we send GET with a request to https://slack.com/api/oauth.access . In response, Slack will send a json string with multiple fields - something like this


 {'ok': true, 'team_name': 'your_team_name'} 

after which we just get the name of the command and redirect the user to the main page of his team https://your_team_name.slack.com - the application is authorized, you can use the application commands.


The Cleantalk service team hopes that this information will be useful for anyone interested in chat bots development.


')

Source: https://habr.com/ru/post/302870/


All Articles