H
H
hollanditkzn2017-08-02 12:53:59
Yii
hollanditkzn, 2017-08-02 12:53:59

How to implement save chat_id telegram bot on yii2?

I changed the approach a little, looked at the example docs.mirocow.com/doku.php?id=php:telegram and somewhere I was told that the controller needs to register all this, since I implemented everything incorrectly and understood why the controller is in this example, how It would not be clear at first this example. I am currently using the widget https://github.com/SonkoDmitry/yii2-telegram-bot-api turns out to apply. I don't know what is the reason for this situation.
Having written a little code, I got the following
In the config, I specified
frontend/config/main.php

'components' => [
'bot' => [
            'class' => 'frontend\components\TelegramComponent',
            'apiToken' => '414134665:AAHfOIdeikQD04NdKckL8wadhqzggvmSqw0',
        ],
]

In frontend/components/TelegramComponent.php
<?php

namespace frontend\components;

use SonkoDmitry\Yii\TelegramBot\Component;


class TelegramComponent extends Component
{
    public function sendMessage(
        $chatId,
        $text,
        $parseMode = null,
        $disablePreview = false,
        $replyToMessageId = null,
        $replyMarkup = null,
        $disableNotification = false
    )
    {
        return parent::sendMessage(
            $chatId,
            $text,
            $parseMode,
            $disablePreview,
            $replyToMessageId,
            $replyMarkup,
            $disableNotification
        );
    }
}

And in the controller frontend/controllers/TelegramController.php
<?php

namespace frontend\controllers;

use app\models\User;
use frontend\components\TelegramComponent;
use yii\db\Exception;
use yii\web\Controller;

class TelegramController extends Controller
{
    public function actionWebhook()
    {
        try{
            $bot = new TelegramComponent();
            echo $bot->setWebhook(['url' => ['web-hook']]);
        } catch (Exception $e){
            $e->getMessage();
        }
    }

    public function actionIndex()
    {
        try{
            $content = file_get_contents('php://input');
            $chatId = $content['message']['chat']['id'];

            $user = User::findOne(\Yii::$app->user->id);
            $user->telegram_chat_id = $chatId;
            $user->save();
        } catch (Exception $e){
            $e->getMessage();
        }
    }
}

And in the address bar of the browser, I indicated https://api.telegram.org/bot414134665:AAHfOIdeikQD...
But the question is, it still does not work, it does not record chat_id

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hollanditkzn, 2017-08-09
@hollanditkzn

The solution to this issue, in the controller TelegramController.php

use app\models\User;
use frontend\components\TelegramComponent;
use yii\db\Exception;
use yii\filters\AccessControl;
use yii\web\Controller;
use frontend\models\Telegram;

class TelegramController extends Controller
{
    public function beforeAction($action)//Обязательно нужно отключить Csr валидацию, так не будет работать
    {
        $this->enableCsrfValidation = ($action->id !== "webhook");
        return parent::beforeAction($action);
    }

       public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['webhook'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                ],
            ],
        ];
    }
    
    public function actionWebhook()
    {
        $data = json_decode(file_get_contents('php://input'), true);//Обязательно json формат
       if(isset($data['message']['chat']['id']))
        {
            $chatId = $data['message']['chat']['id'];//Получаем chat_id
            $message = isset($data['message']['text']) ? $data['message']['text'] : false;

            $send = false;

            if (strpos($message, '/start') !== false) {//Возвращает позицию
                $explode = explode(' ', $message);//Разбивает строку на подстроки
                $token = isset($explode[1]) ? $explode[1] : false;//Получаем токен
                $data = [
                    'raw' => $token,
                    'chat_id' => $chatId,
                ];
                $send = Telegram::start($data);//Сравниваем токен и если имеется схожесть то сохраняем telegram_chat_id в бд
            } else {
                $send = 'Комманда не найдена. Если Вы уверены в том, что ошибка, обратитесь в тех поддержку';
            }
            $send = $send ? '' : 'Что-то пошло не по плану. Обратитесь в тех.поддержку';
        }
    }
}

In the Telegram.php model
<?php 
namespace frontend\models;

use common\models\User;

class Telegram
{
    public static function start($data){
    	return self::login($data);
    }
    public static function login($data)
    {
    	$token = $data['raw'];//берем токен который отправляем
    	if ($token && $user = User::findOne(['token' => $token])) {//сравниваем
    		if ($user->telegram_chat_id) {
                return "Уважаемый $user->name, Вы уже авторизованы в системе. ";
            }
            $user->telegram_chat_id = $data['chat_id'];//сохраняем chat_id в бд
            $user->save();
            return "Добро пожаловать, $user->name. Вы успешно авторизовались!";   
    	} else {
    		return "Извините, не удалось найти данный токен!";
    	}
    }
}

And yes, the token that we create ourselves must be written to the database. A separate user token that the system will check for this user and if it matches, then saves this user

L
Lander, 2017-08-02
@usdglander

Just yesterday I came across

$message = $content['message'];
$chatId = $message['chat']['id'];

Not true. It will be right:
$message = $content['callback_query']['message'];
$chatId = $message['chat']['id'];

D
Dmitry, 2017-08-07
@ExileeD

You point the bot to
frontend/web/telegram/webhook
And you yourself wait for a response from it to
frontend/web/telegram/index

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question