Search code examples
google-apps-scriptgoogle-apigoogle-hangouts

Hangouts Chat Bot image card not refreshing


I am building a bot for Hangouts Chat. My bot will display a random image from a free image api. The api's URL is the same URL on each call but will get a new image. Unfortunately, my bot will not update the image. It just repost the same image on each call. I am using Google's App Script to deploy the bot. My image code is as follows:

function buildImageCard(url) {
    return {
        cards: [
            {
                sections: [
                    {
                        widgets: [
                            {
                                image: {
                                    imageUrl: url

                                }
                            }
                        ]
                    }
                ]
            }
        ]
    };
}

The random image shows up just like it should. The only issue is when I wan to call it again, it shows the same image. I can't seem to find a way to refresh the card. I have seen this method:

actionResponse: {type: shouldUpdate ? 'UPDATE_MESSAGE' : 'NEW_MESSAGE'},

Then pass shouldUpdate to buildImageCard. Although, nothing happens if shouldUpdate is true. What am I missing?


Solution

  • It seems that the problem is related with cache. Hangouts Chat is caching images so it doesn't need to download them everytime. You can try it by clearing the browser cache and updating the card with the chatbot. You should see the new image.

    One thing you can do is to include a cachebreaker at the end of the url:

    widgets: [
                 {
                    image: {
                       imageUrl: url + new Date().getTime()
    
                    }
                 }
             ]
    

    As it's suggested here.

    Also, in the same post, someone commented that this is not a good practice "as it will swamp caches (both local and upstream)". And they recommend a better solution, but in this case we cannot control Cache-Control headers.

    I don't know how Hangouts Chat is managing the cache, but I guess they are taking care of it in case a bot uploads tons of different images. For example, in your case, it would be the same if you generate a new URL everytime you want to update it in the card, so I believe the cachebreaker could work for you.

    I hope it helps!