答案:
您可以使用 spaces.list 获取机器人所属的空间列表,然后使用 spaces.get 获取有关空间的更多信息,或者设置特定于房间的 Webhook。
附加信息:
重要提示: 如果您有 Google Workspace 帐户,则只能使用 Google Hangouts Chat API - 它不能单独与 Gmail 一起使用。第二种解决方案使用 Webhook,需要访问 https://chat.google.com,这仅适用于 Google Workspace 域。不幸的是,这根本不可能使用消费者@gmail.com 帐户。
使用环聊聊天 API:
设置服务帐户as per Step 1 on this page 后,您可以从 Google Cloud Project UI 下载服务帐户的凭据,方法是点击服务帐户名称右侧的 ⋮ 按钮,然后按照Create key 按钮并选择 JSON 作为密钥类型。 请务必妥善保存此文件,因为此密钥只有一份副本。
下载此 JSON 文件后,您可以在 python 代码中使用它作为设置服务对象时的凭据:
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
scopes = 'https://www.googleapis.com/auth/chat.bot'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'credentials.json', scopes)
chat_service = build('chat', 'v1', http=credentials.authorize(Http()))
要发出spaces.list 请求,您可以使用这个新建的chat_service,并从响应中提取空格列表:
def extract(n):
return n['name']
spaces_list = chat_service.spaces().list().execute()
all_spaces = map(extract, spaces_list['spaces'])
然后您可以使用这些空格之一从 python 程序发送消息:
response = chat_service.spaces().messages().create(
parent=all_spaces[0],
body={'text': 'Test message'}).execute()
print(response)
要记住的事情:
使用网络钩子:
您可以代替直接使用 API,而是为特定聊天设置 webhook,并使用硬编码的 URL,从外部脚本向房间发送消息。
完整的步骤已在this page 上列出,但我也会在这里完成。
通过https://chat.google.com转到您要向其发送消息的房间,然后从房间名称旁边的下拉菜单中选择Manage Webhooks。
输入机器人的名称和可选头像,然后按SAVE。这将为您提供一个 webhook URL 以在您的 python 脚本中使用。
在本地,确保您的环境中安装了httplib2,并将以下脚本复制到新的.py 文件中:
from json import dumps
from httplib2 import Http
def main():
"""Hangouts Chat incoming webhook quickstart."""
url = 'webhook-url'
bot_message = {
'text' : 'Hello from a Python script!'}
message_headers = {'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
response = http_obj.request(
uri=url,
method='POST',
headers=message_headers,
body=dumps(bot_message),
)
print(response)
if __name__ == '__main__':
main()
确保将webhook-url 字符串替换为上一步中聊天 UI 中提供的 webhook。
现在您可以保存文件并运行它 - 这会自动向上述聊天空间发送一条消息:
参考资料: