mirror of
https://github.com/GAM-team/GAM.git
synced 2025-07-10 22:53:34 +00:00
Initial Support for Google Chat API
This commit is contained in:
177
src/gam/gapi/chat.py
Normal file
177
src/gam/gapi/chat.py
Normal file
@ -0,0 +1,177 @@
|
||||
import sys
|
||||
|
||||
import googleapiclient.errors
|
||||
|
||||
import gam
|
||||
from gam.var import *
|
||||
from gam import controlflow
|
||||
from gam import display
|
||||
from gam import fileutils
|
||||
from gam import gapi
|
||||
from gam import utils
|
||||
from gam.gapi import errors as gapi_errors
|
||||
|
||||
# Chat scope isn't in discovery doc so need to manually set
|
||||
CHAT_SCOPES = ['https://www.googleapis.com/auth/chat.bot']
|
||||
|
||||
|
||||
def build():
|
||||
return gam.buildGAPIServiceObject('chat',
|
||||
act_as=None,
|
||||
scopes=CHAT_SCOPES)
|
||||
|
||||
|
||||
THROW_REASONS = [
|
||||
gapi_errors.ErrorReason.FOUR_O_FOUR, # Chat API not configured
|
||||
gapi_errors.ErrorReason.FOUR_O_THREE, # Bot not added to room
|
||||
]
|
||||
|
||||
def _chat_error_handler(chat, err):
|
||||
if err.status_code == 404:
|
||||
project_id = chat._http.credentials.project_id
|
||||
url = f'https://console.cloud.google.com/apis/api/chat.googleapis.com/hangouts-chat?project={project_id}'
|
||||
print('ERROR: you need to configure Google Chat for your API project. Please go to:')
|
||||
print()
|
||||
print(url)
|
||||
print()
|
||||
print('and complete all fields.')
|
||||
elif err.status_code == 403:
|
||||
print('ERROR: no access to that Chat space or message. Make sure your bot created the mesage and the user has chatted the bot first or added it to the Chat room')
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def print_spaces():
|
||||
chat = build()
|
||||
try:
|
||||
spaces = gapi.get_all_pages(chat.spaces(), 'list', 'spaces', throw_reasons=THROW_REASONS)
|
||||
except googleapiclient.errors.HttpError as err:
|
||||
_chat_error_handler(chat, err)
|
||||
if not spaces:
|
||||
print('Bot not added to any Chat rooms or users yet.')
|
||||
else:
|
||||
display.write_csv_file(spaces, spaces[0].keys(), 'Chat Spaces', False)
|
||||
|
||||
|
||||
def print_members():
|
||||
chat = build()
|
||||
space = None
|
||||
i = 3
|
||||
while i < len(sys.argv):
|
||||
myarg = sys.argv[i].lower()
|
||||
if myarg == 'space':
|
||||
space = sys.argv[i+1]
|
||||
if space[:7] != 'spaces/':
|
||||
space = f'spaces/{space}'
|
||||
i += 2
|
||||
else:
|
||||
controlflow.invalid_argument_exit(myarg, "gam print chatmembers")
|
||||
try:
|
||||
results = gapi.get_all_pages(chat.spaces().members(), 'list', 'memberships', parent=space)
|
||||
except googleapiclient.errors.HttpError as err:
|
||||
_chat_error_handler(chat, err)
|
||||
members = []
|
||||
titles = []
|
||||
for result in results:
|
||||
member = utils.flatten_json(result)
|
||||
for key in member:
|
||||
if key not in titles:
|
||||
titles.append(key)
|
||||
members.append(utils.flatten_json(result))
|
||||
display.write_csv_file(members, titles, 'Chat Members', False)
|
||||
|
||||
|
||||
def create_message():
|
||||
chat = build()
|
||||
body = {}
|
||||
i = 3
|
||||
while i < len(sys.argv):
|
||||
myarg = sys.argv[i].lower()
|
||||
if myarg == 'text':
|
||||
body['text'] = sys.argv[i+1]
|
||||
i += 2
|
||||
elif myarg == 'textfile':
|
||||
filename = sys.argv[i + 1]
|
||||
i, encoding = gam.getCharSet(i + 2)
|
||||
body['text'] = fileutils.read_file(filename, encoding=encoding)
|
||||
elif myarg == 'space':
|
||||
space = sys.argv[i+1]
|
||||
if space[:7] != 'spaces/':
|
||||
space = f'spaces/{space}'
|
||||
i += 2
|
||||
elif myarg == 'thread':
|
||||
body['thread'] = {'name': sys.argv[i+1]}
|
||||
i += 2
|
||||
else:
|
||||
controlflow.invalid_argument_exit(myarg, "gam create chat")
|
||||
if len(body['text']) > 4096:
|
||||
body['text'] = body['text'][:4095]
|
||||
print('WARNING: trimmed message longer than 4k to be 4k in length.')
|
||||
try:
|
||||
resp = gapi.call(chat.spaces().messages(),
|
||||
'create',
|
||||
parent=space,
|
||||
body=body,
|
||||
throw_reasons=THROW_REASONS)
|
||||
except googleapiclient.errors.HttpError as err:
|
||||
_chat_error_handler(chat, err)
|
||||
if 'thread' in body:
|
||||
print(f'responded to thread {resp["thread"]["name"]}')
|
||||
else:
|
||||
print(f'started new thread {resp["thread"]["name"]}')
|
||||
print(f'message {resp["name"]}')
|
||||
|
||||
def delete_message():
|
||||
chat = build()
|
||||
name = None
|
||||
i = 3
|
||||
while i < len(sys.argv):
|
||||
myarg = sys.argv[i].lower()
|
||||
if myarg == 'name':
|
||||
name = sys.argv[i+1]
|
||||
i += 2
|
||||
else:
|
||||
controlflow.invalid_argument_exit(myarg, "gam delete chat")
|
||||
try:
|
||||
gapi.call(chat.spaces().messages(),
|
||||
'delete',
|
||||
name=name)
|
||||
except googleapiclient.errors.HttpError as err:
|
||||
_chat_error_handler(chat, err)
|
||||
|
||||
|
||||
def update_message():
|
||||
chat = build()
|
||||
body = {}
|
||||
name = None
|
||||
updateMask = 'text'
|
||||
i = 3
|
||||
while i < len(sys.argv):
|
||||
myarg = sys.argv[i].lower()
|
||||
if myarg == 'text':
|
||||
body['text'] = sys.argv[i+1]
|
||||
i += 2
|
||||
elif myarg == 'textfile':
|
||||
filename = sys.argv[i + 1]
|
||||
i, encoding = gam.getCharSet(i + 2)
|
||||
body['text'] = fileutils.read_file(filename, encoding=encoding)
|
||||
elif myarg == 'name':
|
||||
name = sys.argv[i+1]
|
||||
i += 2
|
||||
else:
|
||||
controlflow.invalid_argument_exit(myarg, "gam update chat")
|
||||
if len(body['text']) > 4096:
|
||||
body['text'] = body['text'][:4095]
|
||||
print('WARNING: trimmed message longer than 4k to be 4k in length.')
|
||||
try:
|
||||
resp = gapi.call(chat.spaces().messages(),
|
||||
'update',
|
||||
name=name,
|
||||
updateMask=updateMask,
|
||||
body=body)
|
||||
except googleapiclient.errors.HttpError as err:
|
||||
_chat_error_handler(chat, err)
|
||||
if 'thread' in body:
|
||||
print(f'updated response to thread {resp["thread"]["name"]}')
|
||||
else:
|
||||
print(f'updated message on thread {resp["thread"]["name"]}')
|
||||
print(f'message {resp["name"]}')
|
Reference in New Issue
Block a user