Comments (3)
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.
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.
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)
- Отправка сообщений на почту
- Обновление зависимостей HOT 6
- Uncaught exception 'RuntimeException' with message 'Signature header not found'
- При нажатии на кнопку ее текст выводиться в чате HOT 1
- onConversation() dont send welcome message. HOT 1
- How to send one message to several people?
- Не работает setInputFieldState HOT 2
- Как добавить значение из массива в кнопки для вайбер бота HOT 1
- viber
- Как обрабатывать нажатие на кнопки?
- Misspelled Failure event classsproperty dsc
- Как отправить сразу несколько изображений!??
- Ссылка на телефон в сообщении
- [Viber Bug] Web hook URL query parameters
- Подскажите как отследить отписку? HOT 4
- There is a problem with return types while extending Bot class
- Перенос бота HOT 1
- Не подключает файлы autoload
- Как удалить старый вебхук
- java.util.concurrent.TimeoutException
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from viber-bot-php.