D
D
Doniyor Mamatkulov2017-09-23 07:11:58
Yii
Doniyor Mamatkulov, 2017-09-23 07:11:58

Telegram Bot - how to get a message from a user?

Guys, hello everyone!
I want to implement the following: when a user sends the /start command to a bot in Telegram, it is necessary that the bot respond with its chat_id.
So far, I have only managed to send messages to the user, like this:
I took the class for sending messages here
In the Yii2 controller, I write:

$api = new Telegram();
        $api->token = '439152430:AAE***_мой_токен';
        $api->sendMessage(821_мой_чат_id, "Hello, world!") ;

Now I need to receive the /start command from the user and send him his chat_id as a response.
I know that I need to set a webHook and "listen" to JSON from the bot, but it doesn't work ((((
So far on the server https://mywebsite.ru/bot/bot .php I wrote:
json_decode(file_get_contents('php://input'));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Pavlenko, 2017-09-23
@Akdmeh

Yes, you are joking! Just the day before yesterday I was playing with this problem.

<?php
namespace app\telegram_logger;

use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\httpclient\Client;
/**
 * Telegram Bot
 *
 * @author Ali Irani <ali@irani.im>
 */
class TelegramBot extends Component
{
    const API_BASE_URL = 'https://api.telegram.org/bot';
    /**
     * Bot api token secret key
     * @var string
     */
    public $token;

    private $_client;
    /**
     * Check required property
     */
    public function init()
    {
        parent::init();
        if ($this->token === null) {
            throw new InvalidConfigException(self::className() . '::$token property must be set');
        }
    }
    /**
     * @return Client
     */
    public function getClient()
    {
        if ($this->_client) {
            return $this->_client;
        }
        return new Client(['baseUrl' => self::API_BASE_URL . $this->token]);
    }
    /**
     * Send message to the telegram chat or channel
     * @param int|string $chat_id
     * @param string $text
     * @param string $parse_mode
     * @param bool $disable_web_page_preview
     * @param bool $disable_notification
     * @param int $reply_to_message_id
     * @param null $reply_markup
     * @link https://core.telegram.org/bots/api#sendmessage
     * return array
     */
    public function sendMessage($chat_id, $text, $parse_mode = null, $disable_web_page_preview = null, $disable_notification = null, $reply_to_message_id = null, $reply_markup = null)
    {
        $response = $this->getClient()
            ->post('sendMessage', compact('chat_id', 'text', 'parse_mode', 'disable_web_page_preview', 'disable_notification', 'reply_to_message_id', 'reply_markup'))
            ->send();
        return $response->data;
    }

    public function getUpdates($offset, $timeout = 30)
    {
        $response = $this->getClient()
            ->post('getUpdates', ['offset'=>$offset, 'timeout'=>$timeout])
            ->send();
        return $response->data;
    }
}

Then I run the console application:
<?php

namespace app\console;

use Yii;

use app\telegram_logger\TelegramBot;

set_time_limit(0);
ini_set('memory_limit', '512M');

class TelegramController extends \yii\console\Controller
{
    const UPDATE_INFO_FILE = '@runtime/last_telegram_update_id.txt';

    public function actionIndex()
    {
        echo "Start waiting for messages\n";

        $bot = new TelegramBot(['token' => Yii::$app->params['telegram']['botToken']]);

        if (file_exists(Yii::getAlias(self::UPDATE_INFO_FILE))) {
            $last_update_id = Yii::getAlias(self::UPDATE_INFO_FILE);
        } else {
            $last_update_id = 1;
        }

        while (true) {
            echo "Requesting updates\n";
            $data = $bot->getUpdates($last_update_id, 5);
            if (empty($data)) {
                echo "Empty response\n";
            } else {
                if ($data['ok'] == 1) {
                    if (is_array($data['result'])) {
                        foreach ($data['result'] as $update) {
                            if (!empty($update['message']['text']) && $update['message']['text'] == '/getid') {
                                $bot->sendMessage($update['message']['chat']['id'], 'Ваш ID: '.$update['message']['chat']['id']);
                            }
                            $last_update_id = $update['update_id'] + 1;
                        }

                        file_put_contents(Yii::getAlias(self::UPDATE_INFO_FILE), $last_update_id);
                    } else {
                        echo "Result is not array\n";
                    }
                } else {
                    echo 'Error '.$data['error_code'].': '.$data['description']."\n";
                }
            }
        }

        echo "Finished\n";
    }
}

I say right away that the code is bad, I did it on my knee, because it was necessary quite urgently and, as they say, "for yesterday", but you can push off from it. In general, read the Telegram Bot API documentation, although it is confusing.
PS Type yii2-httpclient into composer; I also hope you know how to connect a console application.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question