From 848313dfd442d25f664bd105f40f80e7f14d169e Mon Sep 17 00:00:00 2001 From: Ryan Barrett Date: Tue, 6 Aug 2024 17:51:59 -0700 Subject: [PATCH] ATProto.send_chat: handle 400 from getConvoForMembers, sendMessage for #1024, #966, etc --- atproto.py | 19 +++++++++++++------ tests/test_atproto.py | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/atproto.py b/atproto.py index a1707da7..d7abb6cf 100644 --- a/atproto.py +++ b/atproto.py @@ -864,10 +864,17 @@ def send_chat(self, msg, from_user): 'User-Agent': USER_AGENT, 'Authorization': f'Bearer {token}', }) - convo = client.chat.bsky.convo.getConvoForMembers(members=[to_did]) - output = client.chat.bsky.convo.sendMessage({ - 'convoId': convo['convo']['id'], - 'message': msg, - }) - logger.info(f'Sent chat message from {from_user.handle} to {self.handle} {to_did}: {json_dumps(output)}') + + try: + convo = client.chat.bsky.convo.getConvoForMembers(members=[to_did]) + sent = client.chat.bsky.convo.sendMessage({ + 'convoId': convo['convo']['id'], + 'message': msg, + }) + except RequestException as e: + # getConvoForMembers returns eg 400 if the recipient has disabled chat + util.interpret_http_exception(e) + return False + + logger.info(f'Sent chat message from {from_user.handle} to {self.handle} {to_did}: {json_dumps(sent)}') return True diff --git a/tests/test_atproto.py b/tests/test_atproto.py index e4600fdd..bcca45c6 100644 --- a/tests/test_atproto.py +++ b/tests/test_atproto.py @@ -1790,6 +1790,24 @@ def test_send_chat(self, mock_get, mock_post): 'Authorization': ANY, }) + # getConvoForMembers + @patch('requests.get', return_value=requests_response({ + 'error': 'InvalidRequest', + 'message': 'recipient has disabled incoming messages', + }, status=400)) + def test_send_chat_recipient_disabled(self, mock_get): + user = self.make_user_and_repo() + alice = ATProto(id='did:plc:alice') + + self.assertFalse(alice.send_chat({ + '$type': 'chat.bsky.convo.defs#messageInput', + 'text': 'hello world', + }, from_user=user)) + + mock_get.assert_any_call( + 'https://chat.service.local/xrpc/chat.bsky.convo.getConvoForMembers?members=did%3Aplc%3Aalice', + json=None, data=None, headers=ANY) + def test_datastore_client_get_record_datastore_object(self): self.make_user_and_repo() post = {