Victor Kemp
Victor Kemp

Reputation: 3

Php Viber API bot should get messages

So i have a Viber bot which is being developed, and it should be able to save the messages users are sending to him, but it is not working.

I tried using some debug methods, send POST manually, but id didnt worked, also i am using an HyperHost server but i looked into the error logs of the server, there arent any of them

so here's the code


`<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

file_put_contents('log.txt', "Incoming POST data: " . print_r($_POST, true) . "\n", FILE_APPEND);

$authToken = '519567c55ba7dedd-bac773fe8df25c35-98130217c0617a4b';
$recipientId = '+ilW7lfATztDKWDskZSHjA==';
$savedMessage = $_SESSION['savedMessage'] ?? '';

function sendKeyboardMessage($authToken, $recipientId) {
    $headers = array(
        'Content-Type: application/json',
        'X-Viber-Auth-Token: ' . $authToken
    );

    $data = array(
        'receiver' => $recipientId,
        'type' => 'text',
        'text' => 'Please type your message in the chat box below and hit send.',
        'keyboard' => array(
            'Type' => 'keyboard',
            'Buttons' => array(
                array(
                    'ActionType' => 'reply',
                    'ActionBody' => 'type_message',
                    'Text' => 'Type a message'
                )
            )
        )
    );

    $ch = curl_init('https://chatapi.viber.com/pa/send_message');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'Curl error: ' . curl_error($ch) . "<br>";
    }

    curl_close($ch);

    return $response;
}

echo "Checking request method...<br>";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "Detected POST method.<br>";

    $data = file_get_contents('php://input');
    $jsonData = json_decode($data, true);

    if (isset($jsonData['message']['text'])) {
        $incomingMessage = $jsonData['message']['text'];
        echo "Incoming message detected: $incomingMessage<br>";

        if ($incomingMessage !== 'type_message') {
            $savedMessage = $incomingMessage;
            $_SESSION['savedMessage'] = $savedMessage;
            echo "Message saved: $savedMessage<br>";
        }
    } else {
        echo "No message text detected in the POST data.<br>";
    }

    exit;  // Exit after processing POST data
} else {
    echo "No POST detected. Sending keyboard message...<br>";
    sendKeyboardMessage($authToken, $recipientId);
}

echo "Last saved message: $savedMessage<br>";

?>`

Upvotes: 0

Views: 159

Answers (0)

Related Questions