首页 > 解决方案 > 如何使用 Viber Bot 发送消息

问题描述

我无法使用 Viber Bot 发送消息。

我试过这个选项:

const TextMessage = require('viber-bot').Message.Text

viber_bot.sendMessage(req.body.viber_user_id, new TextMessage(req.body.message))

结果,错误

UnhandledPromiseRejectionWarning: Error: Invalid arguments passed to sendMessage. 'optionalReceiver' and 'chatId' are Missing.  

像这样尝试过:

viber_bot.sendMessage({
    "receiver": "<my_id>",
    "type": "text",
    "text": "Hello world!"
}

用这种方法,没有错误,但也没有消息,它不来!

PS
请注意,机器人的其余部分工作正常。消息被接受,我可以发送回复。

标签: node.jsviber

解决方案


sendMessage()需要UserProfile而不仅仅是viber_user_id

以下应该工作:

const receiver = "to viber user";
const sampleUserProfile = { id: receiver };
const text = "sample message";
const sampleTrackingData = { value: "sent 1 message" };
const sampleKeyboard = { button: { bgColor: "#FFFFFF" } };
const sampleChatId = "sample chatId";
const sampleMinApiVersion = 2;
const sampleMessage = new TextMessage(text, sampleKeyboard, null, null, null, sampleMinApiVersion);

viber_bot.sendMessage(sampleUserProfile, sampleMessage, sampleTrackingData, sampleChatId);

另请注意,有两种实现可能会给您带来问题,具体取决于您实际使用的内容:

  1. ViberClient.prototype.sendMessage = function (optionalReceiver, messageType, messageData, optionalTrackingData, optionalKeyboard, optionalChatId, optionalMinApiVersion)
    
  2. ViberBot.prototype.sendMessage = function (optionalUserProfile, messages, optionalTrackingData, optionalChatId)
    

推荐阅读