Giter Site home page Giter Site logo

Yii2 about viber-bot-php HOT 3 CLOSED

bogdaan avatar bogdaan commented on July 25, 2024
Yii2

from viber-bot-php.

Comments (3)

Bogdaan avatar Bogdaan commented on July 25, 2024

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
    }
}

from viber-bot-php.

isaygo avatar isaygo commented on July 25, 2024

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

from viber-bot-php.

Bogdaan avatar Bogdaan commented on July 25, 2024

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)

from viber-bot-php.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.