Answer the question
In order to leave comments, you need to log in
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',
],
]
<?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
);
}
}
<?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();
}
}
}
Answer the question
In order to leave comments, you need to log in
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 ? '' : 'Что-то пошло не по плану. Обратитесь в тех.поддержку';
}
}
}
<?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 "Извините, не удалось найти данный токен!";
}
}
}
Just yesterday I came across
$message = $content['message'];
$chatId = $message['chat']['id'];
$message = $content['callback_query']['message'];
$chatId = $message['chat']['id'];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question