Giter Club home page Giter Club logo

botman-vk-community-callback-driver's People

Contributors

yageorgiy avatar yui-ezic avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

botman-vk-community-callback-driver's Issues

ВК шлет запросы с одинаковым event_id, а бот считает их разными командами

Describe the bug

Иногда ВКонтакте отправляет несколько одинаков запросов c одинаковыми "event_id" в результате все рушится. Из-за того что пуступают одинаковые команды. А у меня бот-викторина. И происходит ответ на следующие вопросы сам по себе.

Ошибка может не проявлятся несколько дней. А потом ВК начинает слать по несколько раз. Например сегодня постоянно шлет одинаковые запросы пачками.

To Reproduce

Вот например:

  1. 29.01.2023 22:39:36 | message_new
    {
    "group_id": 00000000,
    "type": "message_new",
    "event_id": "beea7f04ba6a1553adcc5445943e118d151169ff",
    "v": "5.103",
    "object": {
    ...
  2. 29.01.2023 22:39:54 message_new
    {
    "group_id": 00000000,
    "type": "message_new",
    "event_id": "beea7f04ba6a1553adcc5445943e118d151169ff",
    "v": "5.103",
    "object": {
    "message": {
    ...

Пожалуйста помогите.

Спасибо.

Бот отправляет сообщение в беседу несколько раз, перед этим он их уже кидал.

Describe the bug
A clear and concise description of what the bug is.

Бот отправляет сообщение в беседу несколько раз, перед этим он их уже кидал.
Иногда это происходит, а иногда нет. Может выкинуть то же что я писал 5 минут назад.

To Reproduce
Steps to reproduce the behavior:

  1. Use method '...' with specific arguments '...' [or] send specific payload '...'
  2. See stack trace error

Ошибок нет, что бы повторить достаточно написать в беседу.

Expected behavior
A clear and concise description of what you expected to happen.

Чтобы он не отправлял сообщения, на которые уже прочитал.

Screenshots
If applicable, add screenshots to help explain your problem.

image

Environment

  • Driver version: [e.g. 1.6.3]
  • VK client: [any, website, mobile website, mobile client, desktop, client, 3d-party client: Name, Version]
  • PHP version: [e.g. 7.4.3] 7.2

Additional context
Add any other context about the problem here.

В логах вк это сообщение также отправляется боту, видимо несколько раз, но не думаю что это баг вконтакте.

Crash when pressing "Start" button, provided by vk bots functionality

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()```

Driver always matching

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.

Different errors in markSeen() method

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).
Screenshot
(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.

Buttons не видит другие Type кроме text и callback

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)
 ])
);

"types" method api error, when sending message with attachment

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();

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.