google-apps-scriptgoogle-hangoutshangouts-api

If user DM bot, bot must post that message to a specified room (Hangouts Chat)


This is the code which I got from the template

function onMessage(event) {
  var name = "";

  if (event.space.type == "DM") {
    name = "You";
  } else {
    name = event.user.displayName;
  }
  var message = name + " said \"" + event.message.text + "\"";

  return { "text": message };

And when i DM the bot, it replies correctly and even when added to a room and it is mentioned via @bot_name, it responds correctly. But I want this functionality if i message the bot via DM, it should post that message in a specific chat room. How do i edit the above function to get the bot to post the message to a specific chat room?

Thanks!


Solution

  • I was able to do it via a webhook call. There seems to be no way of doing it via any other way that I know of or that the document reads.

    var message = " Someone says \"" + event.message.text + "\"";
    var url = "<Webhook_URL>";
      var options = {
        'method' : 'post',
        'contentType' : 'application/json',
        'payload' : JSON.stringify({
          "text": message
        })
      };
    UrlFetchApp.fetch(url, options);
    

    For more information about webhooks, please refer to this URL