Menu blog

The development of chat-bots for Telegram and Slack with PHP

General information

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

Telegram

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

The second step is to install a webhook — in other words, a request handler, coming into the chat-bot from users. When the user sets a command to your chat-bot, Telegram refers to the address that was specified as a webhook, and transmits a user message and service information, your handler generates response and sends back a Telegram, after that Telegram gives the answer to the user. This can be done using the command curl in the terminal –

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

where YOUR_TELEGRAM_TOKEN – the same token that was given to you before the bot @BotFather and https://example.com/telegramwaiter.php – this is the address to which will handle requests Telegram. In response Telegram should return json string type

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

that means the handler for your chat-bot successfully installed.

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

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

<?php set_time_limit(0); // Installing the token $botToken = "YOUR_TELEGRAM_TOKEN"; $website = "https://api.telegram.org/bot".$botToken; // Received a request from Telegram $content = file_get_contents("php://input"); $update = json_decode($content, TRUE); $message = $update["message"]; // Get internal number of the chat Telegram and command entered by the user in the chat $chatId = $message["chat"]["id"]; $text = $message["text"]; // Example of processing the command /start if ($text == '/start') { $welcomemessage = 'Welcome!!! Check IP/Email for spam giving "check IP/Email" command'; // Send the generated message back to the Telegram user file_get_contents($website."/sendmessage?chat_id=".$chatId."&text=".$welcomemessage); } ?>

The procedure is – get in the variable $text command from the user in the chat, form according to the desired logic the message, and give back to the user using the function file_get_contents().

How it works you can see by adding @CleanTalkBot bot in Telegram – enter the command check IP|Email and get the information about is the specified IP|Email spam.

Example of a response

Email *protected email* is BLACKLISTED. Frequency 999. Updated Apr 24 2019. https://cleantalk.org/blacklists/*protected email*.

Slack

The service Slack has a little different approach to creation of chat bots.

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

In the app list https://api.slack.com/apps choose our app and go to the menu on the right for the link Slash Commands and click Create new command.

In the form that appears the following fields

Command – enter the command, beginning with / – for example /cdcheck.

Request URL – URL commands request handler – similar webhook Telegram (eg https://cleantalk.org/slackwaiter.php).

Short description — a brief description of what you can do with the created command.

Save command. Note – your site must be running on the https – in this case self-signed certificates are NOT SUPPORTED by the service Slack.

The token for identification can be found on the page a list of commands – under the list of commands is the field Verification token – then it appears as YOUR_SLACK_TOKEN.

Write handler slackwaiter.php in PHP

<?php set_time_limit(0); // Check input from Slack token for compliance with issued by the dashboard Slack if ($_POST['token'] == 'YOUR_SLACK_TOKEN') { // $param - this is the text that goes after command // for example if the command /ctcheck 127.0.0.1 // then $param = 127.0.0.1 $param = $_POST['text']; // Then according to the internal logic the answer is formed $slackresponse = ‘Here is the response to the command’; } else $slackresponse = ‘Error’; $response = array(); $response['text'] = $slackresponse; header('Content-Type: application/json'); echo json_encode($response); ?>

Then go here https://api.slack.com/docs/slack-button and in the section Add the Slack button check mark incoming webhook and commands – Slack generates html-code of button by clicking on which other commands will be able to integrate your application in account Slack.

The above button is placed on your site – by clicking on button opens next picture

To login you need to select a channel, where you can use the application.

By clicking on the button Authorize Slack redirects the user to a page Redirect URI (s), which is defined by you (the developer) here – https://api.slack.com/apps, select your application and go to the link App Credentials – see the following picture

Slack not simply redirects the user to a given page, and adds a GET-variable code with the value that would later be processed by the script, for example

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

Next, we give an example script code authscript.php. CLIENT_ID CLIENT_SECRET take 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 'Error.'; exit(); } } else exit(); ?>

The procedure is – get from Slack GET variable code and another with two parameters – the client_id and client_secret – send a GET request to the page https://slack.com/api/oauth.access. In response, Slack will send the json-string with a lot of fields – something like this

{‘ok’: true, ‘team_name’: ‘your_team_name’}

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

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