Pull to refresh

Телеграм Бот (для уведомлений, PHP)

Задача:


Написать Telegram бота, который умеет:
1. Авторизация пользователя
2. Уведомлять пользователя после авторизации
3. Команды тип /start и т.д.

Решение:


Для того, чтобы решить данный вопрос достаточно будет обычного PHP кода и командной строки в консоле с использованием CURL.

Шаги:
1. Регистрируем бота в @BotFather командой /newbot и сохраняем полученный TOKEN
2. Мы должны настроить Webhook(точка входа в ваше приложение, url) куда будут сыпаться все ваши события из telegram. Для этого через консоль отправим POST запрос вида:



curl -d "url=https://{YOUR_DOMAIN}?secret={YOUR_SECRET}" https://api.telegram.org/{YOUR_TOKEN}/setWebhook


где
YOUR_DOMAIN — ваш адрес сайта (обязательно HTTPS),
YOUR_SECRET — секретный ключ, который не позволит другим людям слать спам по этой ссылке,
YOUR_TOKEN — ваш токен бота

3. Далее к вам на указанный URL начнуть падать запросы типа POST и вам необходимо будет сделать разбор данных.

4. Пример кода PHP(Laravel 5.*) и отправка (вместо 1000 слов):

<?php

namespace App\Library;

class TelegramService
{

    var $bot_api_key = '{YOUR_TOKEN}';
    var $bot_username = '';
    var $api_url = 'https://api.telegram.org/bot';

    public function __construct()
    {

    }

    public function sendMessage($chat_id, $text)
    {
        file_get_contents($this->api_url . $this->bot_api_key . "/sendmessage?chat_id=" . $chat_id . "&text=" . $text);
    }

}


код из webhook:

<?php

namespace App\Http\Controllers\Api\V1\Controllers\Webhooks;

use App\Http\Controllers\Controller;
use App\Library\TelegramService;
use App\Models\Main\MysqlUsers;
use App\Models\Main\Project;
use App\Models\Main\TelegramBotChats;
use App\Models\Main\TelegramBotTokens;
use App\Models\Main\User;
use Illuminate\Support\Facades\Config;
use Illuminate\Http\Request;
use App\Models\Mailer as MailGunService;
use App\Support\Controller\TenantConnector;
use Carbon;
use Longman\TelegramBot\Exception\TelegramException;


class TelegramBotController extends Controller
{
    use TenantConnector;

    var $telegramService;

    public function __construct()
    {
        $this->telegramService = new TelegramService();
    }

    public function messageRead(Request $request)
    {

        try {

            $all = $request->all();

            if (isset($all['secret']) && $all['secret'] == '{YOUR_SECRET}') {
                $message = $all['message'];
                $chat_id = $message['chat']['id'];
                $text = $message['text'];

                if (TelegramBotChats::where('chat_id', $chat_id)->exists()) {
                    $this->telegramService->sendMessage($chat_id, ' Привет! В данный момент, я умею только уведомлять!');
                } else {
                    if ($text == '/start') {
                        $this->telegramService->sendMessage($chat_id, ' Привет, пользователь! Введите ваш токен...');
                    } else {
                        $this->runAuth($chat_id, $text);
                    }
                }
            }


        } catch (TelegramException $e) {
            // Silence is golden!
            // log telegram errors
            // echo $e->getMessage();
        }

    }

    public function runAuth($chat_id, $text)
    {

        $flag = true;

        if (strlen($text) == 10) {

            $telegramBotToken = TelegramBotTokens::where(['token' => $text])->first();

            if ($telegramBotToken) {

                TelegramBotChats::create([
                    'user_id' => $telegramBotToken->user_id,
                    'chat_id' => $chat_id
                ]);

                $telegramBotToken->delete();

                $flag = false;

                $this->telegramService->sendMessage($chat_id, ' Авторизация прошла успешно! Ожидайте уведомления из системы...');

            }

        }

        if ($flag) {
            $this->telegramService->sendMessage($chat_id, ' Неверный токен! Пожалуйста повторите попытку...');
        }

    }


}


Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.
Change theme settings