Viber Bot on PHP. onConversation problem with return welcome message

394 Views Asked by At

The event onConversation fires, but nothing comes to the user. I tried to fix the error, but the message has not send. All other bot`s functions are working fine.

Please tell me where is the error and how can i fix it.

$bot = new Bot(['token' => $apiKey]);
    $bot
        ->onConversation(function ($event) use ($bot, $botSender, $log ) {

            $log->info('onConversation ' . var_export($event, true));

            $context = $event->getContext();
            if ($context != "" && $context != null) {
                add_with_referral($event->getSender()->getId(), $event->getSender()->getName(), $context);
            } else {
                add_user($event->getSender()->getId(), $event->getSender()->getName(), $log);
            }

            return (new \Viber\Api\Message\Text)
                ->setSender($botSender)
                ->setText("Can i help you?");
        })

I use SDK Bogdaan/viber-bot

1

There are 1 best solutions below

0
On

Нашел решение. Удаляем стандартное событие bot->onConversation(). В самое начало файла bot.php пишем вот этот код:

file_put_contents("viber.json",file_get_contents("php://input"));
$viber = file_get_contents("viber.json");
$viber = JSON_decode($viber);

function send($message){

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://chatapi.viber.com/pa/send_message",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => JSON_encode($message),
        CURLOPT_HTTPHEADER => array(
            "Cache-Control: no-cache",
            "Content-Type: application/JSON",
            "X-Viber-Auth-Token: YOUR VIBER TOKEN"
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);


    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        echo $response;
    }

}

$main_menu = [[
    "Columns"=> 6,
    "Rows"=> 2,
    "BgColor" => "#808B96",
    "ActionType" => "reply",
    "ActionBody" => "subscribe_button",
    "Text" => "<font color=\"#F8F9F9\"><b>Subscribe</b></font>",
    "TextSize" => "regular"
]];

if ($viber->event == "conversation_started"){
    $message['receiver'] = $viber->user->id;
    $message['type'] = "text";
    $message['text'] = "text";
    $message['keyboard'] = [
        "Type" => "keyboard",
        "Revision" => 1,
        "DefaultHeight" => false,
        "Buttons" => $main_menu
    ];
    send($message);
    exit;
}