如何在Python中通过Dialogflow实现从Google Assistant发送推送通知

发布于 2021-01-29 15:04:34

我正在google
Dialogflow中开发chatbot以获得google的帮助,我已经按照此文档显示了推送通知。我已经请求了许可,但是现在我陷入了Exchange the key for an access token and send a notification该文档的最后一步()。

谁能帮我做到这一点。我应该从Python履行代码发送哪个JSON响应?

关注者
0
被浏览
69
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    最后解决了问题。@matthewayne发布的代码有一些错误,例如,请求必须是“
    POST”方法,并且需要更改有效负载和标头中的某些参数,因此它起作用了!在这里,我更改了一些代码并尝试请求和它打了一个通知!

    我参考了此文档以使其起作用!

    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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看