Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Yii2 #1

Closed
isaygo opened this issue Feb 21, 2017 · 3 comments
Closed

Yii2 #1

isaygo opened this issue Feb 21, 2017 · 3 comments
Labels

Comments

@isaygo
Copy link

isaygo commented Feb 21, 2017

How can i integrate viber-bot-php into yii2 action. Many ways, many errors

500
400
i tried _csrf off
now i hav ActiveControoler and with message 'Response content must not be an array.'

In standalone php app the work is OK.

@Bogdaan
Copy link
Owner

Bogdaan commented Feb 21, 2017

First - you dont need put bot code inside controller.

a) You can put yii-related initialization inside bot hook web/bot.php:

defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_ENV') or define('YII_ENV', 'prod');

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

// <--- init yii if you need
// $config = require(__DIR__ . '/../config/web.php');
// $app = (new yii\web\Application($config));

// <--- init bot

b) disable csrf inside beforeAction and disable debug mode:

public function beforeAction($action) {
    // esure YII_DEBUG OFF
    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}

Example "inside controller":

<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;

use Viber\Bot;
use Viber\Api\Sender;

class BotController extends Controller
{
    public function init()
    {
        $this->enableCsrfValidation = false;
        // $headers = \Yii::$app->response->headers;
        // setup other header if you need
        // Content-type: application/json !
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    }

    public function actionUpdate()
    {
        // bot webhook logic
    }
}

@isaygo
Copy link
Author

isaygo commented Feb 21, 2017

Sorry for stoling your time, i'm new in yii2

<?php
namespace frontend\controllers;
use Yii;

use common\models\UsersSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
//use common\extensions\viber\Viberbot;
use Viber\Bot;
use Viber\Api\Sender;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use yii\rest\ActiveController;
//ADDED FOR AUTHENTIFICATION WITH BEHAVIORS
use yii\filters\AccessControl;
use yii\helpers\Json;
/**
 * UsersController implements the CRUD actions for Users model.
 */
class ViberController extends ActiveController
{
	public $modelClass = 'common\models\Users';

     public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
				//'only' => ['index', 'signup'],
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
						'roles' => ['?'],
                    ],
                    [
                        
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],		
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'index' => ['GET','POST','HEAD'],
                ],
            ],
        ];
    } 
public function actionIndex()
{
			Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
			$apiKey = '45942c46e2349e6b-d87008735d9b7257-af19e13d2236196b';
            $botSender = new Sender([
    //'name' => 'Whois bot',
    //'avatar' => 'https://developers.viber.com/img/favicon.ico',
     ]);
try {
    $bot = new Bot(['token' => $apiKey]);
    $bot
    ->onConversation(function ($event) use ($bot, $botSender) {
        // это событие будет вызвано, как только пользователь перейдет в чат
        // вы можете отправить "привествие", но не можете посылать более сообщений
        return (new \Viber\Api\Message\Text())
            ->setSender($botSender)
            ->setText("Can i help you?");
    })
    ->onText('|\d{1}|is', function ($event) use ($bot, $botSender) {
        // это событие будет вызвано если пользователь пошлет сообщение 
        // которое совпадет с регулярным выражением
        $bot->getClient()->sendMessage(
            (new \Viber\Api\Message\Text())
            ->setSender($botSender)
            ->setReceiver($event->getSender()->getId())
            ->setText("I do not know YO!)")
        );
    })
    ->run();
} catch (Exception $e) {
    // todo - log exceptions
}		
    }	
      public function beforeAction($action) {
        if($action->id === 'index'){
			Yii::$app->controller->enableCsrfValidation = false;
		} 
        return parent::beforeAction($action);
    }  	  
}

and i have the error:

exception 'yii\base\InvalidParamException' with message 'Response content must not be an array.' in /home/saygo/i-link.net.ua/billing/vendor/yiisoft/yii2/web/Response.php:1020

Seems that bot is working, but cant fly right response

@Bogdaan
Copy link
Owner

Bogdaan commented Feb 21, 2017

Sory, but i unable to read this spaghetti code. Please use pastebin or gist.
PHP functions return value from last op. Therefore you need return or exit op at the end of action function (better *app()->end()).

<?php
,,,,
public function actionIndex()
{
  // -- bot ops
  return '';
}

Note you must specify Content-type: application/json header (as I explained above)

@Bogdaan Bogdaan closed this as completed Feb 22, 2017
paleHorses pushed a commit to paleHorses/viber-bot-php that referenced this issue Jan 11, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants