bogdaan / viber-bot-php Goto Github PK
View Code? Open in Web Editor NEWPhp bot interface to work with Viber API
License: MIT License
Php bot interface to work with Viber API
License: MIT License
А послать с php сайта сообщение на чей то viber можно?
типо как с функцией php mail
How to use the library without "composer require bogdaan/viber-bot-php"?
Apply for a Public Account - не там такого
Связался, вопрос снят
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
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' => [],
]);
....
Can I use this library to send sms to my viber number?
Доброго времени суток.
Исходя из REST API существует возможность передачи боту таких типов сообщений
text, picture, video, contact, URL and location
В SDK есть методы бота
on, onText, onSubscribe, onConversation
Каким образом можно словить, например, изображение?
Спасибо!
При попытке установить 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;
}
}
}
При запросе контактных данных, и нажатии на кнопку, не отправляются контактные данные пользователя.
$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('Отправить номер телефона')
])
)
);
Привет.
Не получается отправить сообщение по расписанию.
В лог валится "Signature header not found"
При обычном общении через чат (когда WebHook присылает сообщение) все нормально работает.
Добрый день. При регистрации хука для бота возвращается ответ
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" } }
Добрый день!
При попытке 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";
}
Добрый день
Не могу запустить 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
Не как не могу разобраться.
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.
Hello there i was really wondering if we really need this line as it is working without it too and why we need this line when we define $bot two lines below?
viber-bot-php/examples/bot-plus.php
Line 31 in 984b6bc
Save param event.message.text to value:
viber-bot-php/src/Api/Message/Contact.php
Line 111 in 984b6bc
При установки webhook выдает 500 ошибку (HTTP_X_VIBER_CONTENT_SIGNATURE header not found).
Как с этим бороться?
hi
how i can share my location with custom keyboard button ?
$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')
])
)
);
https://github.com/Bogdaan/viber-bot-php/blob/master/src/Bot.php#L91
When income message with sticker, got exception
Call to undefined method Viber\Api\Message\Sticker::getText()
Добрый день.
Пытаюсь выполнить вот такой код:
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
В чем может быть проблема? Сертификат валидный, пути правильные, токен рабочий ..
Попробовал дописать в Button.php соответствующее поле с сеттером и геттером.
Ошибок не возникло, но и Silent не заработал.
How can I implement the function of inviting a user to a public account?
It is possible?
Добрый день! Функция onText обрабатывает только англоязычный ввод текста. А как вводить произвольный текст на русском? как вообще извлечь пользовательский ввод произвольного текста, для дальнейшей обработки, например записи в БД?
В файле Bot.php на 227 строке break обрывает обход обработчиков. Так задумано?
Как эту бибилотеку использовать вместе с botman.io как драйвкер для viber?
onConversation how to greet with the name.
eg: Hi, (sender_name)
Доброго времени суток!
После того как пользователь отправит первое сообщение, при попытке отправить ответное сообщение возникает, следующая ошибка:
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
Is it possible to repeat a keyboard without writing whole setKeyboard in each.
like
$menu = new Keyboard
and repeat by calling setKeyboard($menu)
Система 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/
В чем проблема может быть? Спасибо
Привет!
Скачал архив с Гитхаба. Пробую выполнить 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. Я так понимаю, они появятся если загрузить проект через Композер. Но мои попытки сделать это, успехом не увенчались.
Вы бы не могли выложить архив, который получается в результате скачивания проекта Композером? Ну или что-нибудь, чтобы оно заработало :)
I was wondering, how to enter a new line when sending a text message?
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?
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?
Как мне дописать метод unset_webhook(), чтоб снять вебхук с адреса
https://developers.viber.com/docs/api/python-bot-api/#apiunset_webhook(
Приветствую.
При получении телефона от пользователя имеем 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 и не попадёт в свойства объекта
Hi! Is there a way to close a Viber internal browser programmatically?
Здравствуйте!
Кто-нибудь может подсказать, через кнопку share-phone по мобильному приложению номер телефона передается без проблем, через десктопную версию программы номер по кнопке не передается, приходит пустота. (десктопная версия зарегистрирована на тот же номер, что и мобильная)
Как отправить номер телефона через viber установленный на обычном PC ?
Здравствуйте!
Используя пример из документации (за исключением того, что установил маску /.*/ для onText) запустил бота и вместо одного сообщения ответа он шлет несколько (2-4). Причем логирование показывает, что именно viber шлет одно и тоже сообщение от пользователя, а бот соответственно отвечает на каждый запрос. Не подскажите, в каком направлении копать?
Добрый день
Большое спасибо за SDK!
У меня file_get_contents("php://input") всегда пустой, когда пользователь отправляет боту сообщение.
При чем и HTTP заголовки и query string приходят как положено
В php.ini allow_url_fopen разрешен
Не подскажите, в чем может быть загвоздка?
Спасибо!
Собственно сабж в заголовке. Спасибо.
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.
После установки 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 сертификатом.
Что делать?
viber-bot-php/examples/bot-plus.php
Keyboards почему-то вообще не приходит, все с примера брал.
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" но все ломается.
А пример у Вас найти не могу.
Спасибо.
При получении данных контакта, заполняется только номер телефона.
viber-bot-php/src/Api/Message/Contact.php
Lines 104 to 117 in 984b6bc
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.