yageorgiy / botman-vk-community-callback-driver Goto Github PK
View Code? Open in Web Editor NEWA VK community callback API driver for botman.io framework
License: MIT License
A VK community callback API driver for botman.io framework
License: MIT License
Describe the bug
Иногда ВКонтакте отправляет несколько одинаков запросов c одинаковыми "event_id" в результате все рушится. Из-за того что пуступают одинаковые команды. А у меня бот-викторина. И происходит ответ на следующие вопросы сам по себе.
Ошибка может не проявлятся несколько дней. А потом ВК начинает слать по несколько раз. Например сегодня постоянно шлет одинаковые запросы пачками.
To Reproduce
Вот например:
Пожалуйста помогите.
Спасибо.
Describe the bug
A clear and concise description of what the bug is.
Бот отправляет сообщение в беседу несколько раз, перед этим он их уже кидал.
Иногда это происходит, а иногда нет. Может выкинуть то же что я писал 5 минут назад.
To Reproduce
Steps to reproduce the behavior:
Ошибок нет, что бы повторить достаточно написать в беседу.
Expected behavior
A clear and concise description of what you expected to happen.
Чтобы он не отправлял сообщения, на которые уже прочитал.
Screenshots
If applicable, add screenshots to help explain your problem.
Environment
Additional context
Add any other context about the problem here.
В логах вк это сообщение также отправляется боту, видимо несколько раз, но не думаю что это баг вконтакте.
Request string
{"type":"message_new","object":{"message":{"date":1600265466,"from_id":11111111,"id":65,"out":0,"peer_id":11111111,"text":"Начать","conversation_message_id":1,"fwd_messages":[],"important":false,"random_id":0,"attachments":[],"payload":"{\"command\":\"start\"}","is_hidden":false},"client_info":{"button_actions":["text","vkpay","open_app","location","open_link"],"keyboard":true,"inline_keyboard":true,"carousel":false,"lang_id":0}},"group_id":11111,"event_id":"82d32482992f91243a","secret":"asdyhauihsdiyasd"}
Error str
[stacktrace]
#0 vendor\\yageorgiy\\botman-vk-community-callback-driver\\src\\VkCommunityCallbackDriver.php(242): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(8, 'Undefined index...', 'C:\\\\Data\\\\Dev\\\\lnu...', 242, Array)
#1 vendor\\botman\\botman\\src\\BotMan.php(192): BotMan\\Drivers\\VK\\VkCommunityCallbackDriver->getMessages()
#2 vendor\\botman\\botman\\src\\Traits\\HandlesConversations.php(170): BotMan\\BotMan\\BotMan->getMessages()
#3 vendor\\botman\\botman\\src\\BotMan.php(422): BotMan\\BotMan\\BotMan->loadActiveConversation()
#4 app\\Http\\Controllers\\BotManController.php(18): BotMan\\BotMan\\BotMan->listen()```
In class VkCommunityCallbackDriver field payload will never be null, because constructor call method buildPayload()
which fill this field. But in method hasMatchingEvent() you do next check
public function hasMatchingEvent() {
if (!is_null($this->payload)) {
//...
}
return false;
}
Due to the fact that the payload is never null, the method never returns false and always matches. This leads to inoperability of other drivers.
When adding a bot to a chat, I got the error in markSeen method() "VK API returned error when processing method 'messages.markAsRead': One of the parameters specified was missing or invalid: message_ids is undefined."
I found several errors in this method.
Firstly, $matchingMessage->getPayload()->get("id")
returns nothing because payload is json like
{
"type": "message_new",
"object": {
"message": {
"date": <int>,
"from_id": <int>,
"id": <int>,
...
}
}
and id fields locate inside object.message. To get it we need to use $matchingMessage->getPayload()->get("object")['message']['id']
.
Secondly, 'message_ids' fields is deprecated from version 5.80 (https://vk.com/dev/messages.markAsRead).
(It's funny, but this is not written in the English version of the documentation)
Third, I don't know how to make this method work in chat. Maybe because messages from chats are not stored for bots and their id is always equals to zero.
Botman(не студия) | PHP 7.3.11 | "version" => "5.103"
В документации сказано:
Sending links | ✔ Supported
See VK documentation page for available colours, types and other features. Just add new fields in array of additional parameters as it is shown in the example above.
Оба способа выставления Type не работают:
$buttons = array(
Button::create('pay')->additionalParameters(["action" => ["type" => "open_link", "url" => "https://vk.com", "label" => "test"])
);
$question = Question::create('test')->addButtons($buttons);
$open_link = ["type" => "open_link", "url" => "https://vk.com", "label" => "test"];
$keyboard->addRows(
new VKKeyboardRow([
( new VKKeyboardButton() )->setRawAction($open_link)->setPayload(json_encode(["action"=>$open_link]))->setColor(null)
])
);
Судя по коду драйвер принудительно выставляет цвет, что возможно противоречит той же информации по ссылке от ВК:
//class VKKeyboardButton
const COLOR_PRIMARY = "primary";
protected $color = self::COLOR_PRIMARY;
public function toArray(){
return [
"color" => $this->color,
"action" => $this->action
];
}
цвет кнопки. Параметр используется только для кнопок с type: text и callback.
Если убрать обязательное требование цвета, то некоторые Type вроде open_app удалось заставить работать, но open_link даже так почему-то не работает:
public function toArray(){
if( !isset($this->color) ){
return [
"action" => $this->action
];
}
return [
"color" => $this->color,
"action" => $this->action
];
}
// без обязательного цвета кнопки этот пример из ВК работает
$open_app = [
"type" => "open_app",
"app_id" => 6232540,
"owner_id" => -157525928,
"hash" => "123",
"label" => "LiveWidget"
];
$keyboard->addRows(
new VKKeyboardRow([
( new VKKeyboardButton() )->setRawAction($open_link)->setPayload(json_encode(["action"=>$open_app]))->setColor(null)
])
);
Code:
$attachment = new File('http://url');
$message = OutgoingMessage::create($text, $attachment);
$botman->say($message, $vkId);
Error:
[content:protected] => {\"error\":{\"error_code\":100,\"error_msg\":\"One of the parameters specified was missing or invalid: you should specify correct user_id, chat_id, or domain param\",\"request_params\":[{\"key\":\"method\",\"value\":\"messages.setActivity\"},{\"key\":\"oauth\",\"value\":\"1\"},{\"key\":\"peer_id\",\"value\":\"\"},{\"key\":\"type\",\"value\":\"typing\"},{\"key\":\"v\",\"value\":\"5.103\"}]}}
[version:protected] => 1.0
[statusCode:protected] => 200
[statusText:protected] => OK
[charset:protected] =>
)
at vendor\\yageorgiy\\botman-vk-community-callback-driver\\src\\VkCommunityCallbackDriver.php:1117)
[stacktrace]
#0 vendor\\yageorgiy\\botman-vk-community-callback-driver\\src\\VkCommunityCallbackDriver.php(1053): BotMan\\Drivers\\VK\\VkCommunityCallbackDriver->api('messages.setAct...', Array, true)
#1 vendor\\yageorgiy\\botman-vk-community-callback-driver\\src\\VkCommunityCallbackDriver.php(980): BotMan\\Drivers\\VK\\VkCommunityCallbackDriver->types(Object(BotMan\\BotMan\\Messages\\Incoming\\IncomingMessage))
#2 vendor\\yageorgiy\\botman-vk-community-callback-driver\\src\\VkCommunityCallbackDriver.php(850): BotMan\\Drivers\\VK\\VkCommunityCallbackDriver->prepareAttachments(Object(BotMan\\BotMan\\Messages\\Incoming\\IncomingMessage), Object(BotMan\\BotMan\\Messages\\Attachments\\File))
#3 vendor\\botman\\botman\\src\\BotMan.php(642): BotMan\\Drivers\\VK\\VkCommunityCallbackDriver->buildServicePayload(Object(BotMan\\BotMan\\Messages\\Outgoing\\OutgoingMessage), Object(BotMan\\BotMan\\Messages\\Incoming\\IncomingMessage), Array)
#4 vendor\\botman\\botman\\src\\BotMan.php(560): BotMan\\BotMan\\BotMan->reply(Object(BotMan\\BotMan\\Messages\\Outgoing\\OutgoingMessage), Array)
Debug:
public function types(IncomingMessage $matchingMessage)
{
dd($matchingMessage);
$this->api("messages.setActivity", [
"peer_id" => $matchingMessage->getRecipient(),
"type" => "typing"
], true);
return true;
}
Debug output:
BotMan\BotMan\Messages\Incoming\IncomingMessage {#1901
#message: ""
#sender: 412312311
#recipient: ""
#images: []
#videos: []
#payload: null
My solution:
public function types(IncomingMessage $matchingMessage)
{
$this->api("messages.setActivity", [
"peer_id" => !empty($matchingMessage->getRecipient()) ? $matchingMessage->getRecipient() : $matchingMessage->getSender(),
"type" => "typing"
], true);
return true;
}
AND The same error when uploading file. Code trying to call getRecipient:
private function prepareAttachments($matchingMessage, $attachment){
$ret = [];
$peer_id = $matchingMessage->getRecipient();
Must be replaced to:
$peer_id = !empty($matchingMessage->getRecipient()) ? $matchingMessage->getRecipient() : $matchingMessage->getSender();
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.