-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadapter.py
More file actions
2701 lines (2318 loc) · 97.3 KB
/
adapter.py
File metadata and controls
2701 lines (2318 loc) · 97.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Google Chat adapter for chat SDK.
Supports messaging via the Google Chat API with service account, ADC, or custom auth.
Handles direct webhooks, Pub/Sub push messages from Workspace Events, card button clicks,
reactions, DMs, and message threading.
Python port of packages/adapter-gchat/src/index.ts.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import os
import re
import time
from collections.abc import AsyncIterable, Awaitable, Callable
from datetime import UTC, datetime
from typing import Any
from chat_sdk.adapters.google_chat.cards import card_to_google_card
from chat_sdk.adapters.google_chat.format_converter import GoogleChatFormatConverter
from chat_sdk.adapters.google_chat.thread_utils import (
GoogleChatThreadId,
decode_thread_id,
encode_thread_id,
is_dm_thread,
)
from chat_sdk.adapters.google_chat.types import (
GoogleChatAdapterConfig,
ServiceAccountCredentials,
)
from chat_sdk.adapters.google_chat.user_info import UserInfoCache
from chat_sdk.adapters.google_chat.workspace_events import (
CreateSpaceSubscriptionOptions,
WorkspaceEventNotification,
WorkspaceEventsAuthADC,
WorkspaceEventsAuthCredentials,
WorkspaceEventsAuthOptions,
create_space_subscription,
decode_pub_sub_message,
list_space_subscriptions,
)
from chat_sdk.emoji import (
convert_emoji_placeholders,
emoji_to_gchat,
resolve_emoji_from_gchat,
)
from chat_sdk.logger import ConsoleLogger, Logger
from chat_sdk.shared.adapter_utils import extract_card, extract_files
from chat_sdk.shared.errors import (
AdapterRateLimitError,
AuthenticationError,
NetworkError,
ValidationError,
)
from chat_sdk.types import (
ActionEvent,
AdapterPostableMessage,
Attachment,
Author,
ChannelInfo,
ChatInstance,
EmojiValue,
EphemeralMessage,
FetchOptions,
FetchResult,
FormattedContent,
ListThreadsOptions,
ListThreadsResult,
Message,
RawMessage,
ReactionEvent,
StateAdapter,
StreamChunk,
StreamOptions,
ThreadInfo,
ThreadSummary,
WebhookOptions,
)
# How long before expiry to refresh subscriptions (1 hour)
SUBSCRIPTION_REFRESH_BUFFER_MS = 60 * 60 * 1000
# TTL for subscription cache entries (25 hours - longer than max subscription lifetime)
SUBSCRIPTION_CACHE_TTL_MS = 25 * 60 * 60 * 1000
# Key prefix for space subscription cache
SPACE_SUB_KEY_PREFIX = "gchat:space-sub:"
# Regex for extracting message name from reaction resource name
REACTION_MESSAGE_NAME_PATTERN = re.compile(r"(spaces/[^/]+/messages/[^/]+)")
# Google Chat API base URL
GCHAT_API_BASE = "https://chat.googleapis.com/v1"
# Google Chat API scopes
GCHAT_SCOPES = [
"https://www.googleapis.com/auth/chat.bot",
"https://www.googleapis.com/auth/chat.messages.readonly",
"https://www.googleapis.com/auth/chat.messages.reactions.create",
"https://www.googleapis.com/auth/chat.messages.reactions",
"https://www.googleapis.com/auth/chat.spaces.create",
]
GCHAT_IMPERSONATION_SCOPES = [
"https://www.googleapis.com/auth/chat.spaces",
"https://www.googleapis.com/auth/chat.spaces.create",
"https://www.googleapis.com/auth/chat.messages.readonly",
]
class GoogleChatAdapter:
"""Google Chat adapter for chat SDK.
Implements the Adapter interface for Google Chat API.
Supports service account credentials, Application Default Credentials (ADC),
and custom auth providers.
"""
def __init__(self, config: GoogleChatAdapterConfig | None = None) -> None:
if config is None:
config = GoogleChatAdapterConfig()
self._name = "gchat"
self._lock_scope: str | None = None
self._persist_message_history: bool | None = None
self._logger: Logger = config.logger or ConsoleLogger("info").child("gchat")
self._user_name = config.user_name or "bot"
self._bot_user_id: str | None = None
self._chat: ChatInstance | None = None
self._state: StateAdapter | None = None
self._format_converter = GoogleChatFormatConverter()
# User info cache (updated in initialize with state adapter)
self._user_info_cache = UserInfoCache(None, self._logger)
# Pub/Sub and Workspace Events config
self._pubsub_topic = config.pubsub_topic or os.environ.get("GOOGLE_CHAT_PUBSUB_TOPIC")
self._impersonate_user = config.impersonate_user or os.environ.get("GOOGLE_CHAT_IMPERSONATE_USER")
self._endpoint_url = config.endpoint_url
self._google_chat_project_number = config.google_chat_project_number or os.environ.get(
"GOOGLE_CHAT_PROJECT_NUMBER"
)
self._pubsub_audience = config.pubsub_audience or os.environ.get("GOOGLE_CHAT_PUBSUB_AUDIENCE")
# In-progress subscription creations to prevent duplicate requests
self._pending_subscriptions: dict[str, Any] = {}
# Verification warning tracking
self._warned_no_webhook_verification = False
self._warned_no_pubsub_verification = False
# Cached JWKS client for JWT verification (lazy init on first use)
self._jwks_client: Any | None = None
# Auth setup
self._credentials: ServiceAccountCredentials | None = None
self._use_adc = False
self._custom_auth: Any = None
self._access_token: str | None = None
self._access_token_expires: float = 0
self._impersonated_access_token: str | None = None
self._impersonated_access_token_expires: float = 0
if config.credentials:
self._credentials = config.credentials
elif config.use_application_default_credentials:
self._use_adc = True
elif os.environ.get("GOOGLE_CHAT_CREDENTIALS"):
creds_json = json.loads(os.environ["GOOGLE_CHAT_CREDENTIALS"])
self._credentials = ServiceAccountCredentials(
client_email=creds_json["client_email"],
private_key=creds_json["private_key"],
project_id=creds_json.get("project_id"),
)
elif os.environ.get("GOOGLE_CHAT_USE_ADC") == "true":
self._use_adc = True
else:
raise ValidationError(
"gchat",
"Authentication is required. Set GOOGLE_CHAT_CREDENTIALS or "
"GOOGLE_CHAT_USE_ADC=true, or provide credentials/auth in config.",
)
# =========================================================================
# Properties (Adapter interface)
# =========================================================================
@property
def name(self) -> str:
return self._name
@property
def user_name(self) -> str:
return self._user_name
@property
def bot_user_id(self) -> str | None:
return self._bot_user_id
@property
def lock_scope(self) -> str | None:
return self._lock_scope
@property
def persist_message_history(self) -> bool | None:
return self._persist_message_history
# =========================================================================
# Auth token management
# =========================================================================
async def _get_access_token(self) -> str:
"""Get an access token for Google Chat API calls.
Caches tokens and refreshes when expired.
"""
now = time.time()
if self._access_token and now < self._access_token_expires - 60:
return self._access_token
if self._credentials:
token = await self._get_service_account_token(self._credentials, GCHAT_SCOPES)
elif self._use_adc:
token = await self._get_adc_token(GCHAT_SCOPES)
else:
raise AuthenticationError("gchat", "No auth configured")
self._access_token = token
self._access_token_expires = now + 3500 # ~58 minutes
return token
async def _get_impersonated_access_token(self) -> str:
"""Get an access token with user impersonation for DM/listing operations."""
now = time.time()
if self._impersonated_access_token and now < self._impersonated_access_token_expires - 60:
return self._impersonated_access_token
if self._credentials and self._impersonate_user:
token = await self._get_service_account_token(
self._credentials,
GCHAT_IMPERSONATION_SCOPES,
subject=self._impersonate_user,
)
elif self._use_adc:
token = await self._get_adc_token(GCHAT_IMPERSONATION_SCOPES)
else:
raise AuthenticationError("gchat", "No impersonation auth configured")
self._impersonated_access_token = token
self._impersonated_access_token_expires = now + 3500
return token
async def _get_service_account_token(
self,
credentials: ServiceAccountCredentials,
scopes: list[str],
subject: str | None = None,
) -> str:
"""Get an access token using service account credentials (JWT flow)."""
import aiohttp
import jwt as pyjwt
now = int(time.time())
claims: dict[str, Any] = {
"iss": credentials.client_email,
"scope": " ".join(scopes),
"aud": "https://oauth2.googleapis.com/token",
"iat": now,
"exp": now + 3600,
}
if subject:
claims["sub"] = subject
token = pyjwt.encode(
claims,
credentials.private_key,
algorithm="RS256",
)
try:
async with (
aiohttp.ClientSession() as session,
session.post(
"https://oauth2.googleapis.com/token",
data={
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": token,
},
) as response,
):
response.raise_for_status()
data = await response.json()
return data["access_token"]
except aiohttp.ClientError as exc:
raise AuthenticationError(
"gchat",
f"Failed to obtain service account token: {exc}",
) from exc
async def _get_adc_token(self, scopes: list[str]) -> str:
"""Get an access token using Application Default Credentials."""
try:
import google.auth
import google.auth.transport.requests
creds, _ = google.auth.default(scopes=scopes)
request = google.auth.transport.requests.Request()
await asyncio.to_thread(creds.refresh, request)
return creds.token
except ImportError:
pass
# Fallback: metadata server (GCE, Cloud Run, etc.)
import aiohttp
url = (
"http://metadata.google.internal/computeMetadata/v1/"
"instance/service-accounts/default/token"
f"?scopes={','.join(scopes)}"
)
try:
async with (
aiohttp.ClientSession() as session,
session.get(
url,
headers={"Metadata-Flavor": "Google"},
) as response,
):
response.raise_for_status()
data = await response.json()
return data["access_token"]
except aiohttp.ClientError as exc:
raise AuthenticationError(
"gchat",
f"Failed to obtain ADC token from metadata server: {exc}",
) from exc
# =========================================================================
# Google Chat API request helpers
# =========================================================================
async def _gchat_api_request(
self,
method: str,
path: str,
*,
body: dict[str, Any] | None = None,
params: dict[str, str] | None = None,
use_impersonation: bool = False,
) -> dict[str, Any]:
"""Make an authenticated request to the Google Chat API.
Args:
method: HTTP method (GET, POST, PUT, PATCH, DELETE).
path: API path (e.g., "spaces/AAAA/messages").
body: JSON request body.
params: Query parameters.
use_impersonation: Use impersonated credentials.
Returns:
JSON response as dict.
"""
import aiohttp
if use_impersonation and self._impersonate_user:
token = await self._get_impersonated_access_token()
else:
token = await self._get_access_token()
url = f"{GCHAT_API_BASE}/{path}"
headers: dict[str, str] = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
async with (
aiohttp.ClientSession() as session,
session.request(
method,
url,
json=body,
params=params,
headers=headers,
) as response,
):
if response.status == 204:
return {}
result = await response.json()
if response.status >= 400:
error_msg = result.get("error", {}).get("message", str(result))
error_code = result.get("error", {}).get("code", response.status)
raise _GoogleApiError(
message=error_msg,
code=error_code,
errors=result.get("error", {}).get("errors"),
)
return result
# =========================================================================
# Lifecycle
# =========================================================================
async def initialize(self, chat: ChatInstance) -> None:
"""Initialize the adapter with the Chat instance."""
self._chat = chat
self._state = chat.get_state()
# Update user info cache to use the state adapter for persistence
self._user_info_cache = UserInfoCache(self._state, self._logger)
# Restore persisted bot user ID from state (for serverless environments)
if not self._bot_user_id:
saved_bot_user_id = await self._state.get("gchat:botUserId")
if saved_bot_user_id:
self._bot_user_id = saved_bot_user_id
self._logger.debug(
"Restored bot user ID from state",
{"botUserId": self._bot_user_id},
)
async def disconnect(self) -> None:
"""Disconnect the adapter (no-op for Google Chat)."""
# =========================================================================
# Thread subscription (Workspace Events)
# =========================================================================
async def on_thread_subscribe(self, thread_id: str) -> None:
"""Called when a thread is subscribed to.
Ensures the space has a Workspace Events subscription so we receive
all messages.
"""
self._logger.info(
"onThreadSubscribe called",
{"threadId": thread_id, "hasPubsubTopic": bool(self._pubsub_topic)},
)
if not self._pubsub_topic:
self._logger.warn(
"No pubsubTopic configured, skipping space subscription. Set GOOGLE_CHAT_PUBSUB_TOPIC env var."
)
return
decoded = self.decode_thread_id(thread_id)
await self._ensure_space_subscription(decoded.space_name)
async def _ensure_space_subscription(self, space_name: str) -> None:
"""Ensure a Workspace Events subscription exists for a space.
Creates one if it doesn't exist or is about to expire.
"""
self._logger.info(
"ensureSpaceSubscription called",
{
"spaceName": space_name,
"hasPubsubTopic": bool(self._pubsub_topic),
"hasState": bool(self._state),
"hasCredentials": bool(self._credentials),
"hasADC": self._use_adc,
},
)
if not (self._pubsub_topic and self._state):
self._logger.warn(
"ensureSpaceSubscription skipped - missing config",
{
"hasPubsubTopic": bool(self._pubsub_topic),
"hasState": bool(self._state),
},
)
return
cache_key = f"{SPACE_SUB_KEY_PREFIX}{space_name}"
# Check if we already have a valid subscription
cached = await self._state.get(cache_key)
if cached:
expire_time = (
cached.get("expire_time", 0) if isinstance(cached, dict) else getattr(cached, "expire_time", 0)
)
time_until_expiry = expire_time - int(time.time() * 1000)
if time_until_expiry > SUBSCRIPTION_REFRESH_BUFFER_MS:
self._logger.debug(
"Space subscription still valid",
{
"spaceName": space_name,
"expiresIn": round(time_until_expiry / 1000 / 60),
},
)
return
self._logger.debug(
"Space subscription expiring soon, will refresh",
{
"spaceName": space_name,
"expiresIn": round(time_until_expiry / 1000 / 60),
},
)
# Check if we're already creating a subscription for this space
if space_name in self._pending_subscriptions:
self._logger.debug(
"Subscription creation already in progress, waiting",
{"spaceName": space_name},
)
pending = self._pending_subscriptions[space_name]
await pending["event"].wait()
if pending.get("error"):
raise pending["error"]
return
# Create the subscription
pending_entry: dict[str, Any] = {"event": asyncio.Event(), "error": None}
self._pending_subscriptions[space_name] = pending_entry
try:
await self._create_space_subscription_with_cache(space_name, cache_key)
except Exception as e:
pending_entry["error"] = e
raise
finally:
pending_entry["event"].set()
self._pending_subscriptions.pop(space_name, None)
async def _create_space_subscription_with_cache(
self,
space_name: str,
cache_key: str,
) -> None:
"""Create a Workspace Events subscription and cache the result."""
auth_options = self._get_auth_options()
self._logger.info(
"createSpaceSubscriptionWithCache",
{
"spaceName": space_name,
"hasAuthOptions": bool(auth_options),
"hasCredentials": bool(self._credentials),
"hasADC": self._use_adc,
},
)
if not auth_options:
self._logger.error(
"Cannot create subscription: no auth configured. "
"Use GOOGLE_CHAT_CREDENTIALS, GOOGLE_CHAT_USE_ADC=true, or custom auth."
)
return
pubsub_topic = self._pubsub_topic
if not pubsub_topic:
return
try:
# First check if a subscription already exists via the API
existing = await self._find_existing_subscription(space_name, auth_options)
if existing:
self._logger.debug(
"Found existing subscription",
{
"spaceName": space_name,
"subscriptionName": existing["subscription_name"],
},
)
if self._state:
await self._state.set(cache_key, existing, SUBSCRIPTION_CACHE_TTL_MS)
return
self._logger.info(
"Creating Workspace Events subscription",
{"spaceName": space_name},
)
result = await create_space_subscription(
CreateSpaceSubscriptionOptions(
space_name=space_name,
pubsub_topic=pubsub_topic,
),
auth_options,
)
subscription_info = {
"subscription_name": result.name,
"expire_time": int(datetime.fromisoformat(result.expire_time.replace("Z", "+00:00")).timestamp() * 1000)
if result.expire_time
else 0,
}
if self._state:
await self._state.set(cache_key, subscription_info, SUBSCRIPTION_CACHE_TTL_MS)
self._logger.info(
"Workspace Events subscription created",
{
"spaceName": space_name,
"subscriptionName": result.name,
"expireTime": result.expire_time,
},
)
except Exception as error:
self._logger.error(
"Failed to create Workspace Events subscription",
{"spaceName": space_name, "error": error},
)
# Don't raise - subscription failure shouldn't break the main flow
async def _find_existing_subscription(
self,
space_name: str,
auth_options: WorkspaceEventsAuthOptions,
) -> dict[str, Any] | None:
"""Check if a subscription already exists for this space."""
try:
subscriptions = await list_space_subscriptions(space_name, auth_options)
for sub in subscriptions:
expire_time_str = sub.get("expire_time", "")
if expire_time_str:
expire_time = int(datetime.fromisoformat(expire_time_str.replace("Z", "+00:00")).timestamp() * 1000)
if expire_time > int(time.time() * 1000) + SUBSCRIPTION_REFRESH_BUFFER_MS:
return {
"subscription_name": sub.get("name", ""),
"expire_time": expire_time,
}
except Exception as error:
self._logger.error("Error checking existing subscriptions", {"error": error})
return None
def _get_auth_options(self) -> WorkspaceEventsAuthOptions | None:
"""Get auth options for Workspace Events API calls."""
if self._credentials:
return WorkspaceEventsAuthCredentials(
credentials=self._credentials,
impersonate_user=self._impersonate_user,
)
if self._use_adc:
return WorkspaceEventsAuthADC(
use_application_default_credentials=True,
impersonate_user=self._impersonate_user,
)
if self._custom_auth:
return {"auth": self._custom_auth}
return None
# =========================================================================
# JWT verification
# =========================================================================
async def _verify_bearer_token(
self,
request: Any,
expected_audience: str,
) -> bool:
"""Verify a Google-signed JWT Bearer token from the Authorization header.
Used for both direct Google Chat webhooks and Pub/Sub push messages.
"""
# Extract authorization header
auth_header: str | None = None
if hasattr(request, "headers"):
headers = request.headers
if isinstance(headers, dict) or hasattr(headers, "get"):
auth_header = headers.get("authorization") or headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
self._logger.warn("Missing or invalid Authorization header")
return False
token = auth_header[7:]
try:
import jwt as pyjwt
from jwt import PyJWKClient
# Lazily create and cache the JWKS client (avoid per-request instantiation)
if self._jwks_client is None:
self._jwks_client = PyJWKClient("https://www.googleapis.com/oauth2/v3/certs")
signing_key = self._jwks_client.get_signing_key_from_jwt(token)
payload = pyjwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
audience=expected_audience,
)
self._logger.debug(
"JWT verified",
{
"iss": payload.get("iss"),
"aud": payload.get("aud"),
"email": payload.get("email"),
},
)
return True
except Exception as error:
self._logger.warn("JWT verification failed", {"error": error})
return False
# =========================================================================
# Webhook handling
# =========================================================================
async def handle_webhook(
self,
request: Any,
options: WebhookOptions | None = None,
) -> dict[str, Any]:
"""Handle incoming webhook from Google Chat.
Handles direct Google Chat webhooks, Pub/Sub push messages from
Workspace Events subscriptions, and card button clicks.
Args:
request: The incoming HTTP request (dict or request-like object).
options: Webhook options including wait_until callback.
Returns:
Response dict with body and status keys.
"""
# Auto-detect endpoint URL from incoming request for button click routing
if not self._endpoint_url:
try:
if hasattr(request, "url"):
url_str = str(request.url)
self._endpoint_url = url_str
self._logger.debug(
"Auto-detected endpoint URL",
{"endpointUrl": self._endpoint_url},
)
except Exception:
pass
# Parse request body
body: str
if hasattr(request, "text") and callable(request.text):
body = await request.text()
elif hasattr(request, "body"):
raw_body = request.body
body = raw_body.decode("utf-8") if isinstance(raw_body, bytes) else str(raw_body)
elif isinstance(request, dict):
body = json.dumps(request)
else:
body = str(request)
self._logger.debug("GChat webhook raw body", {"body": body})
try:
parsed = json.loads(body)
except (json.JSONDecodeError, TypeError):
return {"body": "Invalid JSON", "status": 400}
# Check if this is a Pub/Sub push message (from Workspace Events subscription)
if (
isinstance(parsed, dict)
and isinstance(parsed.get("message"), dict)
and parsed["message"].get("data")
and parsed.get("subscription")
):
# Verify Pub/Sub JWT if audience is configured
if self._pubsub_audience:
valid = await self._verify_bearer_token(request, self._pubsub_audience)
if not valid:
return {"body": "Unauthorized", "status": 401}
elif not self._warned_no_pubsub_verification:
self._warned_no_pubsub_verification = True
self._logger.warn(
"Pub/Sub webhook verification is disabled. "
"Set GOOGLE_CHAT_PUBSUB_AUDIENCE or pubsubAudience to verify incoming requests."
)
return self._handle_pub_sub_message(parsed, options)
# Verify direct Google Chat webhook JWT if project number is configured
if self._google_chat_project_number:
valid = await self._verify_bearer_token(request, self._google_chat_project_number)
if not valid:
return {"body": "Unauthorized", "status": 401}
elif not self._warned_no_webhook_verification:
self._warned_no_webhook_verification = True
self._logger.warn(
"Google Chat webhook verification is disabled. "
"Set GOOGLE_CHAT_PROJECT_NUMBER or googleChatProjectNumber "
"to verify incoming requests."
)
# Treat as a direct Google Chat webhook event
event: dict[str, Any] = parsed
# Handle ADDED_TO_SPACE - automatically create subscription
added_payload = (event.get("chat") or {}).get("addedToSpacePayload")
if added_payload:
space = added_payload.get("space", {})
self._logger.debug(
"Bot added to space",
{"space": space.get("name"), "spaceType": space.get("type")},
)
self._handle_added_to_space(space, options)
# Handle REMOVED_FROM_SPACE (for logging)
removed_payload = (event.get("chat") or {}).get("removedFromSpacePayload")
if removed_payload:
space = removed_payload.get("space", {})
self._logger.debug("Bot removed from space", {"space": space.get("name")})
# Handle card button clicks
button_clicked_payload = (event.get("chat") or {}).get("buttonClickedPayload")
invoked_function = (event.get("commonEventObject") or {}).get("invokedFunction")
if button_clicked_payload or invoked_function:
self._handle_card_click(event, options)
return {"body": json.dumps({}), "status": 200}
# Check for message payload in the Add-ons format
message_payload = (event.get("chat") or {}).get("messagePayload")
if message_payload:
self._logger.debug(
"message event",
{
"space": message_payload.get("space", {}).get("name"),
"sender": (message_payload.get("message") or {}).get("sender", {}).get("displayName"),
"text": (message_payload.get("message") or {}).get("text", "")[:50],
},
)
self._handle_message_event(event, options)
elif not (added_payload or removed_payload):
self._logger.debug(
"Non-message event received",
{
"hasChat": bool(event.get("chat")),
"hasCommonEventObject": bool(event.get("commonEventObject")),
},
)
# Google Chat expects an empty response or a message response
return {"body": json.dumps({}), "status": 200}
# =========================================================================
# Pub/Sub message handling
# =========================================================================
def _handle_pub_sub_message(
self,
push_message: dict[str, Any],
options: WebhookOptions | None = None,
) -> dict[str, Any]:
"""Handle Pub/Sub push messages from Workspace Events subscriptions.
These contain all messages in a space, not just @mentions.
"""
# Early filter: Check event type BEFORE base64 decoding to save CPU
event_type = (push_message.get("message") or {}).get("attributes", {}).get("ce-type")
allowed_event_types = [
"google.workspace.chat.message.v1.created",
"google.workspace.chat.reaction.v1.created",
"google.workspace.chat.reaction.v1.deleted",
]
if event_type and event_type not in allowed_event_types:
self._logger.debug("Skipping unsupported Pub/Sub event", {"eventType": event_type})
return {"body": json.dumps({"success": True}), "status": 200}
try:
notification = decode_pub_sub_message(push_message)
self._logger.debug(
"Pub/Sub notification decoded",
{
"eventType": notification.event_type,
"messageId": (notification.message or {}).get("name") if notification.message else None,
"reactionName": (notification.reaction or {}).get("name") if notification.reaction else None,
},
)
# Handle message.created events
if notification.message:
self._handle_pub_sub_message_event(notification, options)
# Handle reaction events
if notification.reaction:
self._handle_pub_sub_reaction_event(notification, options)
# Acknowledge the message
return {"body": json.dumps({"success": True}), "status": 200}
except Exception as error:
self._logger.error("Error processing Pub/Sub message", {"error": error})
# Return 200 to avoid retries for malformed messages
return {
"body": json.dumps({"error": "Processing failed"}),
"status": 200,
}
def _handle_pub_sub_message_event(
self,
notification: WorkspaceEventNotification,
options: WebhookOptions | None = None,
) -> None:
"""Handle message events received via Pub/Sub (Workspace Events)."""
if not (self._chat and notification.message):
return
message = notification.message
# Extract space name from targetResource: "//chat.googleapis.com/spaces/AAAA"
space_name = (notification.target_resource or "").replace("//chat.googleapis.com/", "")
thread_name = (message.get("thread") or {}).get("name") or message.get("name")
thread_id = self.encode_thread_id(
GoogleChatThreadId(
space_name=space_name or (message.get("space") or {}).get("name", ""),
thread_name=thread_name,
)
)
# Refresh subscription if needed (runs in background)
resolved_space_name = space_name or (message.get("space") or {}).get("name")
if resolved_space_name and options and options.wait_until:
async def _refresh() -> None:
try:
await self._ensure_space_subscription(resolved_space_name)
except Exception as err:
self._logger.error(
"Subscription refresh failed",
{"spaceName": resolved_space_name, "error": err},
)
options.wait_until(_refresh())
# Let Chat class handle async processing and waitUntil
# Use factory function since parsePubSubMessage is async
self._chat.process_message(
self,
thread_id,
lambda: self._parse_pub_sub_message(notification, thread_id),
options,
)
def _handle_pub_sub_reaction_event(
self,
notification: WorkspaceEventNotification,
options: WebhookOptions | None = None,
) -> None:
"""Handle reaction events received via Pub/Sub (Workspace Events).
Fetches the message to get thread context for proper reply threading.
"""
if not (self._chat and notification.reaction):
return
reaction = notification.reaction
raw_emoji = (reaction.get("emoji") or {}).get("unicode", "")
normalized_emoji = resolve_emoji_from_gchat(raw_emoji)
# Extract message name from reaction name
# Format: spaces/{space}/messages/{message}/reactions/{reaction}
reaction_name = reaction.get("name", "")
message_name_match = REACTION_MESSAGE_NAME_PATTERN.search(reaction_name)
message_name = message_name_match.group(1) if message_name_match else ""
# Extract space name from targetResource
space_name = (notification.target_resource or "").replace("//chat.googleapis.com/", "")
# Check if reaction is from this bot
is_me = self._bot_user_id is not None and (reaction.get("user") or {}).get("name") == self._bot_user_id
# Determine if this is an add or remove
added = "created" in notification.event_type
chat = self._chat
async def build_reaction_event() -> ReactionEvent:
thread_id: str
if message_name:
try:
message_response = await self._gchat_api_request("GET", message_name)
thread_name = (message_response.get("thread") or {}).get("name")
thread_id = self.encode_thread_id(
GoogleChatThreadId(
space_name=space_name or "",
thread_name=thread_name,
)
)
self._logger.debug(
"Fetched thread context for reaction",
{
"messageName": message_name,
"threadName": thread_name,
"threadId": thread_id,
},
)
except Exception as error:
self._logger.warn(
"Failed to fetch message for thread context",
{"messageName": message_name, "error": error},
)
thread_id = self.encode_thread_id(GoogleChatThreadId(space_name=space_name or ""))
else:
thread_id = self.encode_thread_id(GoogleChatThreadId(space_name=space_name or ""))
reaction_user = reaction.get("user") or {}
return ReactionEvent(
adapter=self,
thread=None,
thread_id=thread_id,
message_id=message_name,
user=Author(
user_id=reaction_user.get("name", "unknown"),
user_name=reaction_user.get("displayName", "unknown"),
full_name=reaction_user.get("displayName", "unknown"),
is_bot=reaction_user.get("type") == "BOT",
is_me=is_me,
),
emoji=normalized_emoji,