GithubHelp home page GithubHelp logo

viber-bot-php's Introduction

PHP sdk for Viber api

Build Status

Library to develop a bot for the Viber platform. Create you first Viber bot step by step, see demo at viber://pa?chatURI=viber-bot-php&context=github.com

Installation

composer require bogdaan/viber-bot-php

Example

<?php

require_once("../vendor/autoload.php");

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

$apiKey = '<PLACE-YOU-API-KEY-HERE>';

// reply name
$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) {
        // this event fires if user open chat, you can return "welcome message"
        // to user, but you can't send more messages!
        return (new \Viber\Api\Message\Text())
            ->setSender($botSender)
            ->setText("Can i help you?");
    })
    ->onText('|whois .*|si', function ($event) use ($bot, $botSender) {
        // match by template, for example "whois Bogdaan"
        $bot->getClient()->sendMessage(
            (new \Viber\Api\Message\Text())
            ->setSender($botSender)
            ->setReceiver($event->getSender()->getId())
            ->setText("I do not know )")
        );
    })
    ->run();
} catch (Exception $e) {
    // todo - log exceptions
}

See more in examples directory.

Library structure

.
├── Api
│   ├── Entity.php               
│   ├── Event                     # all remote events ("callbacks")
│   │   ├── Conversation.php      # fires when user open 1v1 chat
│   │   ├── Delivered.php         # fires when message delivered (for each device)
│   │   ├── Factory.php           # Event factory
│   │   ├── Failed.php            # fires when delivery failed (for each device)
│   │   ├── Message.php           # fires when user send message
│   │   ├── Seen.php              # fires when user read message (for each device)
│   │   ├── Subscribed.php        # fires when user subscribe to PA
│   │   ├── Type.php              # available types
│   │   └── Unsubscribed.php      # fires when user unsubscribed
│   ├── Event.php                 # base class for all events
│   ├── Exception                 #
│   │   └── ApiException.php      # remote or logic error
│   ├── Keyboard                  #
│   │   └── Button.php            # all types of buttons here
│   ├── Keyboard.php              # button container
│   ├── Message                   #
│   │   ├── CarouselContent.php   #
│   │   ├── Contact.php           #
│   │   ├── Factory.php           #
│   │   ├── File.php              #
│   │   ├── Location.php          #
│   │   ├── Picture.php           #
│   │   ├── Sticker.php           #
│   │   ├── Text.php              #
│   │   ├── Type.php              # available message types
│   │   ├── Url.php               #
│   │   └── Video.php             #
│   ├── Message.php               # base class for all messages
│   ├── Response.php              # wrap api response
│   ├── Sender.php                # represent bot-sender
│   ├── Signature.php             # signature helper (verify or create sign)
│   ├── User                      #
│   │   └── State.php             # user state (online/offline etc)
│   └── User.php                  # viber user
├── Bot                           #
│   └── Manager.php               # manage bot closures
├── Bot.php                       # bot class
└── Client.php                    # api client

Read more

Features

  • all api entities
  • validate request and response signs
  • provide webhook interface
  • provide event interface
  • wrap all api response to entities
  • validate api entities before submit?
  • implement log levels with monolog?
  • post on public page

Contributing

Pull requests are welcome.

viber-bot-php's People

Contributors

90zlaya avatar bogdaan avatar bpteam avatar bulgariamitko avatar ellrion avatar gt-volk avatar hoangthienan avatar ildarkhasanshin avatar killer-djon avatar nickender avatar vampirus avatar xdump avatar yarkm13 avatar ypylypenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

viber-bot-php's Issues

Keyboard

Is it possible to repeat a keyboard without writing whole setKeyboard in each.

like

$menu = new Keyboard

and repeat by calling setKeyboard($menu)

Uncaught RuntimeException: HTTP_X_VIBER_CONTENT_SIGNATURE header not found

После установки Webhook выдает такую ошибку.
Fatal error: Uncaught RuntimeException: HTTP_X_VIBER_CONTENT_SIGNATURE header not found in /storage/ssd1/364/3374364/public_html/src/Bot.php:136 Stack trace: #0 /storage/ssd1/364/3374364/public_html/examples/bot-plus.php(207): Viber\Bot->getSignHeaderValue() #1 {main} thrown in /storage/ssd1/364/3374364/public_html/src/Bot.php on line 136
Веб сервер работает по https с корректным SSL сертификатом.

Что делать?

Call to undefined method Viber\Api\Exception\ApiException::getError()

При попытке установить webhook получаю в ответ такую ошибку:
Call to undefined method Viber\Api\Exception\ApiException::getError()

Проект на YII2 (2.0.13.1), PHP 7.2.

Скрипт Setup запускаю как консольное приложение.

Код:

namespace console\controllers;

use Yii;
use yii\console{Controller, ExitCode};
use yii\helpers\Console;
use Viber\Client;

class ViberController extends Controller {

public function actionSetup() {
    try {
        $client = new Client(['token' => Yii::$app->params['viberSetup']['apiKey']]);
        $result = $client->setWebhook(Yii::$app->params['viberSetup']['webhookUrl']);
        $this->stdout("Success!\n", Console::BOLD);

        return ExitCode::OK;
    } catch (\Exception $e) {
        $this->stdout("Error: ". $e->getError() ."\n", Console::BOLD);

        return ExitCode::UNSPECIFIED_ERROR;
    }
}

}

php use statement

Hii
Thanks for sharing this plugin.
I tried the plugin but I get errors when it comes to 'use' statements.
Do you know how to replace the use statement with other functions that will help me using the plugin properly?

setup 500 Internal Server Error

Добрый день!
При попытке php setup.php
Error: Remote error: Result[HttpRequest[POST /bots/viber/bot.php HTTP/1.1]@572b5ac2 > HttpResponse[HTTP/1.1 500 Internal Server Error]@1323ed84] null

require_once("./vendor/autoload.php");
use Viber\Client;
$apiKey = 'myapi'; // <- PLACE-YOU-API-KEY-HERE
$webhookUrl = 'https://mysite,ru/bots/viber/bot.php'; // <- PLACE-YOU-HTTPS-URL
try {
$client = new Client([ 'token' => $apiKey ]);
$result = $client->setWebhook($webhookUrl);
echo "Success!\n";
} catch (Exception $e) {
echo "Error: ". $e->getMessage() ."\n";
}

How to call from text file?

Is there a way to call from text from a txt file.

My plan is to add many words to a text file and when a user type anyword from that txt file, a message to send. Like filtering bad words from a file.

Its difficult to add all words in the bot.php file.

I believe it is possible to explode text and check for preg match

Не отправляются контактные данные

При запросе контактных данных, и нажатии на кнопку, не отправляются контактные данные пользователя.

$client = $bot->getClient();
$receiverId = $event->getSender()->getId();
$bot->getClient()->sendMessage(
(new \Viber\Api\Message\Text())
->setSender($botSender)
->setReceiver($event->getSender()->getId())
->setMinApiVersion(3)
->setText("Нам необходим Ваш номер телефона.")
->setKeyboard(
(new \Viber\Api\Keyboard())
->setButtons([
(new \Viber\Api\Keyboard\Button())
->setActionType('share-phone')
->setActionBody('reply')
->setText('Отправить номер телефона')
])
)
);

Получение изображения и других типов сообщений ботом от пользователей

Доброго времени суток.
Исходя из REST API существует возможность передачи боту таких типов сообщений

text, picture, video, contact, URL and location

В SDK есть методы бота

on, onText, onSubscribe, onConversation

Каким образом можно словить, например, изображение?
Спасибо!

Регистрация

Добрый день.
Пытаюсь выполнить вот такой код:

    public function registerBot()
    {
        try {
            $client = new Client(['token' => env('VIBER_TOKEN', false)]);
//            dd($client);
            $result = $client->setWebhook('https://bot.XXXX.com/viberHook');
            echo "Success!\n"; // print_r($result);
        } catch (Exception $e) {
            echo 'Error: ' . $e->getMessage() . "\n";
        }
    }

В итоге ловлю Exception

Viber \ Api \ Exception \ ApiException (1)
Remote error: Result[HttpRequest[POST /viberHook HTTP/1.1]@351848d8 > HttpResponse[HTTP/1.1 419 unknown status]@20d79eb3] null

В чем может быть проблема? Сертификат валидный, пути правильные, токен рабочий ..

Не могу запустит setup.php

Добрый день

Не могу запустить setup.php, при запуске выходит ошибка.

PHP Fatal error: Uncaught Error: Call to undefined method Viber\Api\Exception\ApiException::getError() in /var/www/html/viber/setup.php:14 Stack trace: #0 {main} thrown in /var/www/html/viber/setup.php on line 14

Не как не могу разобраться.

Не отправляется номер телефона через share-phone с десктопной версии viber

Здравствуйте!

Кто-нибудь может подсказать, через кнопку share-phone по мобильному приложению номер телефона передается без проблем, через десктопную версию программы номер по кнопке не передается, приходит пустота. (десктопная версия зарегистрирована на тот же номер, что и мобильная)

Как отправить номер телефона через viber установленный на обычном PC ?

Remote http request and several answers ...

In ->onText I do smth like

$ch = curl_init( $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
.....................................
$content = curl_exec( $ch )
............................
->setText($content)

The script on remote server answer after 1-4 sec
But the Bot sends curl request several times but i want have one request

Не приходит message от пользователя

Добрый день
Большое спасибо за SDK!
У меня file_get_contents("php://input") всегда пустой, когда пользователь отправляет боту сообщение.
При чем и HTTP заголовки и query string приходят как положено
В php.ini allow_url_fopen разрешен
Не подскажите, в чем может быть загвоздка?
Спасибо!

Yii2

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.

Не работают кнопки

viber-bot-php/examples/bot-plus.php
Keyboards почему-то вообще не приходит, все с примера брал.

Проблема при регистрации хука

Добрый день. При регистрации хука для бота возвращается ответ

Error: Remote error: Result[HttpRequest[POST /sc/default/hook HTTP/1.1]@5c321cb9 > HttpResponse[null 0 null]@bb6fdb] javax.net.ssl.SSLHandshakeException: General SSLEngine problem

Сертификат валидный. Можете подсказать в чем может быть проблема?

p.s. находил Ваш ответ с ссылкой на проверку сертификата, вот результат https://www.ssllabs.com/ssltest/analyze.html?d=sc.mfc61.ru

Вот массив данных которые идут на регистрацию хука:
array(2) { ["url"]=> string(35) "https://sc.mfc61.ru/sc/default/hook" ["event_types"]=> array(3) { [0]=> string(10) "subscribed" [1]=> string(20) "conversation_started" [2]=> string(7) "message" } }

Button -> Silent

Попробовал дописать в Button.php соответствующее поле с сеттером и геттером.
Ошибок не возникло, но и Silent не заработал.

Media content in forwarded message

Bot not receive links to media if user forwarded message to bot.
For example, user sending forwarded message and bot receive next array:

[message:protected] => Viber\Api\Message\Picture Object
        (
            [text:protected] => 
            [media:protected] => 
            [thumbnail:protected] => 
            [receiver:protected] => 
            [type:protected] => picture
            [sender:protected] => 
            [tracking_data:protected] => 
            [min_api_version:protected] => 1
            [keyboard:protected] => 
            [propertiesMap:protected] => Array
                (
                )

        )

How to figure out what was sent and how to work with it I don't know. Have an idea?
Maybe problem not in your library but I'm confused.

====
Если пользователь пересылает сообщение с каким-то контентом (например изображение) то бот получает пустой объект с которым не понятно что делать и как его можно обрабатывать. Скорее всего это проблема не в библиотеке, а в апи вайбера, но может всё таки есть какие-то идеи как с этим бороться?

Координаты пользователя.

Добрый день.
Никак не получается получить координаты пользователя. (Кнопка отправить координаты) В документации сказано можно использовать "location-picker" но все ломается.
А пример у Вас найти не могу.
Спасибо.

Call Name

onConversation how to greet with the name.

eg: Hi, (sender_name)

Дублирование сообщений

Здравствуйте!

Используя пример из документации (за исключением того, что установил маску /.*/ для onText) запустил бота и вместо одного сообщения ответа он шлет несколько (2-4). Причем логирование показывает, что именно viber шлет одно и тоже сообщение от пользователя, а бот соответственно отвечает на каждый запрос. Не подскажите, в каком направлении копать?

Не могу установить веб хук

Привет!

Скачал архив с Гитхаба. Пробую выполнить examples/setup.php, но получаю ошибку об отсутствии файла ../vendor/autoload.php.

Warning: require_once(../vendor/autoload.php): failed to open stream: No such file or directory in ...\examples\setup.php on line 10

Его действительно нету, как и папки vendor. Я так понимаю, они появятся если загрузить проект через Композер. Но мои попытки сделать это, успехом не увенчались.

Вы бы не могли выложить архив, который получается в результате скачивания проекта Композером? Ну или что-нибудь, чтобы оно заработало :)

onText ввод русскоязычного текста

Добрый день! Функция onText обрабатывает только англоязычный ввод текста. А как вводить произвольный текст на русском? как вообще извлечь пользовательский ввод произвольного текста, для дальнейшей обработки, например записи в БД?

->onConversation don't work

Don't work
->onConversation(function ($event) use ($bot, $botSender, $log) {
#$log->info('onConversation ');
return (new \Viber\Api\Message\Text())
->setSender($botSender)
->setText('same text');
})
Work:
->onConversation(function ($event) use ($bot, $botSender, $log) {
#$log->info('onConversation ');
return (new \Viber\Api\Message\Text())
->setSender($botSender)
->setText('same text');
})

why so?

Broadcast message

Hi,

Is there any way to send broadcast message for all subscribers?

For example i want to trigger bot.php externaly to send all subscribers some message.

Thanks.

How to get user phone from this example?

$bot->getClient()->sendMessage(
    (new \Viber\Api\Message\Text())
    ->setSender($botSender)
    ->setReceiver($event->getSender()->getId())
    ->setMinApiVersion(3)
    ->setText("We need your phone number")
    ->setKeyboard(
    (new \Viber\Api\Keyboard())
        ->setButtons([
            (new \Viber\Api\Keyboard\Button())
                    ->setActionType('share-phone')
                    ->setActionBody('reply')
                    ->setText('Send phone number')
                ])
    )
);

Remote error: notSubscribed

Доброго времени суток!
После того как пользователь отправит первое сообщение, при попытке отправить ответное сообщение возникает, следующая ошибка:
exception 'Viber\Api\Exception\ApiException' with message 'Remote error: notSubscribed' in /var/www/html/viber/vendor/bogdaan/viber-bot-php/src/Api/Response.php:37
Stack trace:
#0 /var/www/html/viber/vendor/bogdaan/viber-bot-php/src/Client.php(89): Viber\Api\Response::create(Object(GuzzleHttp\Psr7\Response))
#1 /var/www/html/viber/vendor/bogdaan/viber-bot-php/src/Client.php(176): Viber\Client->call('send_message', Array)
#2 /var/www/html/viber/bot.php(211): Viber\Client->sendMessage(Object(Viber\Api\Message\Text))
#3 [internal function]: {closure}(Object(Viber\Api\Event\Message))
#4 /var/www/html/viber/vendor/bogdaan/viber-bot-php/src/Bot/Manager.php(83): call_user_func(Object(Closure), Object(Viber\Api\Event\Message))
#5 /var/www/html/viber/vendor/bogdaan/viber-bot-php/src/Bot.php(201): Viber\Bot\Manager->runHandler(Object(Viber\Api\Event\Message))
#6 /var/www/html/viber/bot.php(213): Viber\Bot->run()
#7 {main}

Мобильный клиент, версия API 1

Fail on get_account_info request

Remote error: Invalid JSON or missing necessary fields. Error: could not parse json [""

it because emty array in json look like [], but as see from response, viber require "{}",
https://github.com/Bogdaan/viber-bot-php/blob/master/src/Client.php#L87
As work solution - use 'form_params' option instead of json for this request, it`s work success

use GuzzleHttp\Client;

$client = new Client(['base_uri' => 'https://chatapi.viber.com/pa/']);
$response = $client->request('POST', 'get_account_info', [
            'headers' => [
                'X-Viber-Auth-Token' => $this->service->getToken(),
            ],
            'form_params' => [],
        ]);
....

Отправка сообщений по Cron

Привет.
Не получается отправить сообщение по расписанию.
В лог валится "Signature header not found"
При обычном общении через чат (когда WebHook присылает сообщение) все нормально работает.

Contact message type

Приветствую.
При получении телефона от пользователя имеем event:

array (
  'event' => 'message',
  'timestamp' => 1509809895427,
  'message_token' => 5107xxxx5658825983,
  'sender' => 
  array (
    'id' => '4pHBbn2gf2343dsW+tWggw==',
    'name' => 'Николай',
    'language' => 'en',
    'country' => 'RU',
    'api_version' => 4,
  ),
  'message' => 
  array (
    'text' => 'reply',
    'type' => 'contact',
    'contact' => 
    array (
      'phone_number' => 'xxxxxx',
    ),
  ),
  'silent' => false,
)

т.е. в phone_number вложен в contact и не попадёт в свойства объекта

Ошибки при запуске

Система Deb 8 64
Vesta CP
php 5.6.30
Ставлю
composer require bogdaan/viber-bot-php
composer require monolog/monolog
composer require php-console/php-console
Делаю setup.php.
Получаю 500 ошибку
[client 52.0.253.232:47674] PHP Warning: is_dir(): open_basedir restriction in effect. File(/tmp) is not within the allowed path(s):
[client 52.0.253.232:47674] PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'There is no existing directory at "/tmp" and its not buildable
PHP Fatal error: Call to undefined method Viber\Api\Exception\ApiException::getError() in
Права стоят. Даже пробовал 777/
В чем проблема может быть? Спасибо

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.