0

I have created a chat bot for google chat to our gsuite. When I type @DadJokes it returns random dadjoke from an API

Problem is that only I can see the returned joke and I cannot find info about this in the documentation.

Can anyone navigate me to the right path?

Thank you

function getDadJoke() {
  var response = UrlFetchApp.fetch('https://icanhazdadjoke.com/', {
    method: 'get',
    headers: { 'Accept': 'text/plain' },
    contentType: 'plain/text',
  });
  
 return response.getContentText();
}

/**
 * Responds to a MESSAGE event in Hangouts Chat.
 *
 * @param {Object} event the event object from Hangouts Chat
 */
function onMessage(event) {
  console.log(getDadJoke());
  return { "text": getDadJoke() };
}

/**
 * Responds to an ADDED_TO_SPACE event in Hangouts Chat.
 *
 * @param {Object} event the event object from Hangouts Chat
 */
function onAddToSpace(event) {
  return { "text": getDadJoke() };
}

/**
 * Responds to a REMOVED_FROM_SPACE event in Hangouts Chat.
 *
 * @param {Object} event the event object from Hangouts Chat
 */
function onRemoveFromSpace(event) {
  console.info("Bot removed from ",(event.space.name ? event.space.name : "this chat"));
}

UPDATE

I got it working using async messages, but now others receive the joke sooner then my own message where I typed @DadJokes. So that means i type @DadJokes, chat participants recieve the joke from bot, then they receive my message @DadJokes

function getDadJoke() {
  var response = UrlFetchApp.fetch('https://icanhazdadjoke.com/', {
    method: 'get',
    headers: { 'Accept': 'text/plain' },
    contentType: 'plain/text',
  });
  
 return response.getContentText();
}

function sendDadJoke(spaceId) {
 
   var service = OAuth2.createService('chat')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
      .setClientId(SERVICE_ACCOUNT_EMAIL)
      .setPropertyStore(PropertiesService.getUserProperties())
      .setScope(SCOPE);
  
  if (!service.hasAccess()) {
    Logger.log('Authentication error: %s', service.getLastError());
    return;
  }
  
  var url = 'https://chat.googleapis.com/v1/' + spaceId + '/messages';
  
  UrlFetchApp.fetch(url, {
    method: 'post',
    headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
    contentType: 'application/json',
    payload: JSON.stringify({ "text": getDadJoke() }),
  });
  
}


/**
 * Responds to a MESSAGE event in Hangouts Chat.
 *
 * @param {Object} event the event object from Hangouts Chat
 */
function onMessage(event) {
  
  sendDadJoke(event.space.name);
  
  return {"message": "Okay here it comes!"};
}

/**
 * Responds to an ADDED_TO_SPACE event in Hangouts Chat.
 *
 * @param {Object} event the event object from Hangouts Chat
 */
function onAddToSpace(event) {
 
  sendDadJoke(event.space.name);
  
  return {"message": "Okay here it comes!"};
}

/**
 * Responds to a REMOVED_FROM_SPACE event in Hangouts Chat.
 *
 * @param {Object} event the event object from Hangouts Chat
 */
function onRemoveFromSpace(event) {
  console.info("Bot removed from ",(event.space.name ? event.space.name : "this chat"));
}
Erik Kubica
  • 1,180
  • 3
  • 15
  • 39
  • What are your Hangouts Chat API configuration setitngs in GCP for your project? – Rafa Guillermo Jul 16 '20 at 08:18
  • @RafaGuillermo status - available to users | functionality - works with DM, works in rooms and DM with multiple users | Connection - Apps Script | Permission - Everyone in *my gsuite*...... In credentials I have also OAuth 2.0 Client IDs created. – Erik Kubica Jul 16 '20 at 12:06
  • Are you using the Head deployment, or have you created a new deployment? – Rafa Guillermo Jul 16 '20 at 12:48
  • Created new, if i use head it says that i cannot use had for the whole domain. – Erik Kubica Jul 16 '20 at 19:32
  • What scopes are you using for the project? If you have any, have your other users authorised them? They can do this by messagin the bot and following the prompt – Rafa Guillermo Jul 17 '20 at 07:24
  • I don't know what you mean under scopes. About the authorization thing, I am authorized, my coworker also tried the @DadJokes command, he saw the joke, but I did not see, so in theory both of us were authorized. I seen only that he wrote "@DadJokes", and it works like this vice-versa – Erik Kubica Jul 17 '20 at 11:35
  • What do you have listed when you follow the `File > Project properties > Scopes` menu item fro mthe Apps Script editor? – Rafa Guillermo Jul 20 '20 at 07:57
  • @RafaGuillermo "OAuth Scope required by script: https://www.googleapis.com/auth/script.external_request" – Erik Kubica Jul 21 '20 at 08:28
  • Can you add `https://www.googleapis.com/auth/chat.bot`? – Rafa Guillermo Jul 21 '20 at 08:36
  • @RafaGuillermo Authorization Error Error 400: invalid_scope Some requested scopes cannot be shown: [https://www.googleapis.com/auth/chat.bot] Added this scope using appsscript.json under oauthScopes, then deployed new version, updated app in console to new ID, then tried @ DadJokes, it asked for config then during authorization it threw error above. – Erik Kubica Jul 21 '20 at 14:15
  • Did you include the `https://www.`? – Rafa Guillermo Jul 21 '20 at 14:18
  • @RafaGuillermo yes https://ibb.co/frKKrC3 – Erik Kubica Jul 21 '20 at 14:23
  • You need to *add* the scope, not replace. Make sure to keep `https://www.googleapis.com/auth/script.external_request` as well – Rafa Guillermo Jul 21 '20 at 14:24
  • @RafaGuillermo my bad, but still Error 400: invalid_scope Some requested scopes cannot be shown: [https://www.googleapis.com/auth/chat.bot, https://www.googleapis.com/auth/script.external_request] – Erik Kubica Jul 21 '20 at 14:33
  • @RafaGuillermo i have upgraded the code to send the message async using service user. It works, but a weird thing is happenning. the bot reply shows first then my message. like its sending the reply from bot sooner than my own message where i request the joke – Erik Kubica Jul 21 '20 at 15:39
  • Are you sure that isn't a result of the API being called when adding the bot to a room? It's not possible for the bot to answer before you message it ;) Also, I think you may need to change the `https://www.googleapis.com/auth/chat.bot` scope to just `https://www.googleapis.com/auth/chat`. – Rafa Guillermo Jul 23 '20 at 10:38
  • @RafaGuillermo I am calling api when bot is added to automatically send a joke, so the bot does not need to mentioned twice on the first time. But on further messages when I mention the bot, the bot sends the message and it's displayed in correct order (in my chat window) but not for the recepient. After i refresh the window the order of messages is wrong. But I can live with that, it's just for fun – Erik Kubica Jul 28 '20 at 09:51
  • Can you see the timestamps of the messages? – Rafa Guillermo Jul 28 '20 at 10:12
  • @RafaGuillermo nah, only the minutes, even if i hover it does not show the seconds or miliseconds. A stupid idea, but is it plausible that the sendDadJoke ajax to fetch the joke + the rest api request that sends the joke as message executes faster (getting saved to google database) than then the message that mentions the bot – Erik Kubica Jul 28 '20 at 12:33

0 Answers0