How to send push notification from google assistant through Dialogflow fulfilment in Python

风格不统一 提交于 2019-12-01 23:02:29

Finally, I've solved the problem. The code posted by @matthewayne has some mistakes like it should be "POST" request and change some payload and header parameters, hence it worked!, here I've changed some code and tried to request and it hit a notification!

I've referred this documentation to make it worked!

import io
import json

import requests
from google.oauth2 import service_account
import google.auth.transport.requests

PATH_TO_SERVICE_ACCOUNT = 'path/to/json/service/account'

REQUIRED_SCOPE = 'https://www.googleapis.com/auth/actions.fulfillment.conversation'

# Get access token
with io.open(PATH_TO_SERVICE_ACCOUNT, 'r', encoding='utf-8') as json_fi:
    credentials_info = json.load(json_fi)
credentials = service_account.Credentials.from_service_account_info(
    credentials_info, scopes=[REQUIRED_SCOPE])
request = google.auth.transport.requests.Request()
credentials.refresh(request)

headers = {
    'Authorization': 'Bearer ' + credentials.token
}

payload = {
    'customPushMessage': {
        'userNotification': {
            'title': 'Notification title',
            'text': 'Simple Text'
        },
        'target': {
            'userId': '<USER_ID>',
            'intent': '<INTENT>',
            # Expects a IETF BCP-47 language code (i.e. en-US)
            'locale': 'en-US'
        }
    }
}

r = requests.request("POST", 'https://actions.googleapis.com/v2/conversations:send', data=json.dumps(payload), headers=headers)

print(str(r.status_code) + ': ' + r.text)

Try this:

import io
import json

import requests
from google.oauth2 import service_account
import google.auth.transport.requests

PATH_TO_SERVICE_ACCOUNT = 'path/to/json/service/account'

REQUIRED_SCOPE = 'https://www.googleapis.com/auth/actions.fulfillment.conversation'

# Get access token
with io.open(PATH_TO_SERVICE_ACCOUNT, 'r', encoding='utf-8') as json_fi:
    credentials_info = json.load(json_fi)
credentials = service_account.Credentials.from_service_account_info(
            credentials_info,  scopes=[REQUIRED_SCOPE])
request = google.auth.transport.requests.Request()
credentials.refresh(request)

headers = {
    'Authorization': 'Bearer: ' + credentials.token
}

payload = {'customPushMessage': {
    'userNotification': {
      'title': '<NOTIFICATION_TITLE>',
    },
    'target': {
      'userId': '<USER_ID>',
      'intent': '<INTENT>',
      # Expects a IETF BCP-47 language code (i.e. en-US)
      'locale': '<LOCALE>'
    },
  }
}

r = requests.get('https://actions.googleapis.com/v2/conversations:send', json=payload, headers=headers)

print(str(r.status_code) + ': ' + r.text)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!