I created a google chatbot that is connected to an AI model using cloud run function. I made it to send async messages because the model tends to work for longer than 30 seconds.
I did it with this code:
def send_asynchronous_chat_message(thread_id, body, message_id=None):
space_id = thread_id.split(",")[1]
logging.info("space id %s" % space_id)
space_name = f"spaces/{space_id}"
SCOPES = ['https://www.googleapis.com/auth/chat.bot']
credentials, project = google.auth.default(scopes=SCOPES)
chat = build('chat', 'v1', credentials=credentials)
# update content of an existing message
if message_id:
response_obj = chat.spaces().messages().update(
name=message_id,
updateMask='text',
body=body
).execute()
# create a new message
else:
response_obj = chat.spaces().messages().create(
parent=space_name,
body=body
).execute()
return response_obj.get("name")
It works fine when I use it with a Chat API that is in the same project as the Cloud Run Function but when I try to add the trigger URL to a Chat API that is in another organisation/project I get this error when I send a message.
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://chat.googleapis.com/v1/spaces/XXXXXXXXXX/messages?alt=json returned "This Chat app is not a member of this space.". Details: "This Chat app is not a member of this space.">
The Chat API is enabled on the project.
Is there a solution for this? Wihtout putting my app on the marketplace.
You need a service account with domain-wide delegation enabled.
To enable domain-wide delegation for a service account in Google Workspace, you can: Create a service account in the Google Cloud console Copy the service account's Client ID from the Google Cloud console Sign in to the Google Admin console as a super administrator Go to Menu > Security > Access and data control > API controls Select Manage Domain Wide Delegation Click Add new Enter the service account's Client ID Enter a comma-delimited list of OAuth Scopes in the OAuth Scopes field Click Authorize Domain-wide delegation allows a service account to impersonate any user in a Cloud Identity or Workspace account. This gives the service account access to the user's Google Workspace data, bypassing the user's consent.