Это старая версия документа!


Telegram BOT API (Yii2)

@BotFather

Данные получаются в формате JSON через Webhook

file_get_contents('php://input')

Отправка сообщений или команд боту идет по ID чата. Оно же равно ID пользователя.

Простой пример приветствия завязанного на Webhook

class APIController {
 
  public $API_KEY = 'your_bot_api_key';
  public $BOT_NAME = 'namebot';  
 
  public function init(){
 
    try {
        $telegram = new Longman\TelegramBot\Telegram($this->API_KEY, $this->BOT_NAME);
 
        echo $telegram->setWebHook('https://yourdomain/api/init');
    } catch (Longman\TelegramBot\Exception\TelegramException $e) {
        echo $e->getMessage();
    }    
 
  }
 
  public function actionInit(){
 
    try {
        $telegram = new Longman\TelegramBot\Telegram($this->API_KEY, $this->BOT_NAME);
	$telegram->addCommandsPath(Yii::getAlias('@app\commands'));
        $telegram->handle();
    } catch (Longman\TelegramBot\Exception\TelegramException $e) {
        // echo $e->getMessage();
    }    
 
  }  
 
  public function actionHello(){
 
    $gram=json_decode(file_get_contents('php://input'),true);
 
    $message='Hello, '
    .$gram['message']['chat']['last_name'].' '
    .$gram['message']['chat']['first_name'].'. Your ID in Telegram is: '
    .$gram['message']['chat']['id'];
 
    file_get_contents('https://api.telegram.org/botTOKEN/sendMessage?chat_id='
    .$gram['message']['chat']['id'].'&text='
    .urlencode($message))
 
  }
}