In my previous question I asked about the meaning of Facebook messenger bot error code 2018144, which turned out to be about sending limits. This time I'm trying to understand why sending messages works from my local computer, but very mysteriously stops working after I upload my code to App Engine.
Here's the bot message sending code (send_message.py):
import requests
def send_message():
url = "https://graph.facebook.com/me/messages"
querystring = {"access_token":"ACCESS TOKEN HERE"}
payload = """{
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"buttons": [
{
"type": "game_play",
"title": "Play"
}
],
"title": "Hello StackOverflow!"
}
]
}
}
},
"recipient": {
"id": "1647209385355472"
}
}"""
headers = {'Content-Type': 'application/json'}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
return response.text
if __name__ == '__main__':
print send_message()
When I run this code, it prints this out and I receive a message on Facebook:
> python2.7 send_message.py
{"recipient_id":"1647209385355472","message_id":"mid.$cAACstl6Vojpotk0niFihQfeszW_t"}
To turn this into an App Engine app, I use exactly the same code as before, except add a route to call the previous code when I receive a GET request and patch the requests library to work with App Engine.
import webapp2
from requests_toolbelt.adapters import appengine
appengine.monkeypatch()
from send_message import send_message
class MsgTest(webapp2.RequestHandler):
def get(self):
self.response.write(send_message())
app = webapp2.WSGIApplication([
('/msgtest', MsgTest)
])
When I start dev_appserver.py and visit my app in the browser, it also works.
Now if I deploy the code (gcloud app deploy) and then visit the deployed app, it should work because it is running the same code as before. However, it always fails, even if I open and close the game in between to reset any possible sending limits.
How could this be? The same API call with the same credentials works locally, but fails when called from the cloud.
I discovered that something (probably App Engine) was caching the POST request. When the posting didn't work once, the answer was cached so that it seemed to never work. When I added cache_breaker to the request URL, bot messages started working.
It does seem a bit odd that POST requests would be cached, and so intensely that I never got a single working request through, so it's also possible that Facebook just changed something right when I made my own cache breaker change. In either case, it seems to work now.