javascriptnode.jsbotsvk

How can I solve the problem with forwarding messages?


I'm created a chat-bot using 'botact' library, but when I'm trying to verificate my bot on vk-community API working page I receive an error in 'Windows PowerShell' (Here I started the server for bot):

TypeError: Cannot read property 'fwd_messages' of undefined
 at Botact.getLastMessage (C:\Users\whoami\Desktop\Bot-test\node_modules\botact\lib\utils\getLastMessage.js:2:11)
    at Botact.module.exports (C:\Users\whoami\Desktop\Bot-test\node_modules\botact\lib\methods\listen.js:29:28).

The file 'getLastMessage.js' contains this code:

    const getLastMessage = (msg) => {
      if (msg.fwd_messages && msg.fwd_messages.length) {
        return getLastMessage(msg.fwd_messages[0])
      }

      return msg
    }

module.exports = getLastMessage

Solution

  • So I don't know much about botact but according to the code when you are hitting the / route, you need to pass a body containing an object property.

    Now as this is bot framework for vk bots maybe it automatically sends the request body. You can make sure by logging the request body.

    server.post('/', async (req,res)=>{
        console.dir(req.body);
        await bot.listen(req, res);
    });
    

    /lib/methods/listen.js:

    const { type, secret, object, group_id } = framework === 'koa'
        ? args[0].request.body
        : args[0].body
    ...
    ...
    ...
    const { events, middlewares } = actions
    const forwarded = this.getLastMessage(object)
    

    Now, when you do bot.listen express passes req as first argument. and { type, secret, object, group_id } these fields get distructured from the req.body.

    And then object is getting passed to the getLastMessage function.

    So for the request body in minimum you would need

    { "object": {} }
    

    Here is the 200 OK output that I got after added that to the request body from Postman

    postman request example

    POC Code:

    const express = require("express");
    const bodyParser = require("body-parser");
    const { Botact } = require("botact");
    const server = express();
    const bot = new Botact({
      token: "token_for_my_group_i_just_hided_it",
      confirmation: "code_for_my_group_i_just_hided_it"
    });
    server.use(bodyParser.json());
    
    server.post("/",bot.listen);
    server.listen(8080);