Skip to content

Commit 1b4a1a1

Browse files
authored
Merge pull request #84 from AfricasVoices/send_to_multi
Add multi-send
2 parents 716fcd7 + 967f2e0 commit 1b4a1a1

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

rapid_pro_tools/rapid_pro_client.py

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,10 +273,58 @@ def send_message_to_urn(self, message, target_urn, interrupt=False):
273273

274274
log.info("Sending a message to an individual...")
275275
log.debug(f"Sending to '{target_urn}' the message '{message}'...")
276-
response: Broadcast = self.rapid_pro.create_broadcast(message, urns=[target_urn])
276+
response = self.rapid_pro.create_broadcast(message, urns=[target_urn])
277277
log.info(f"Message send request created with broadcast id {response.id}")
278278
return response.id
279279

280+
def send_message_to_urns(self, message, target_urns, interrupt=False):
281+
"""
282+
Sends a message to URNs.
283+
284+
:param message: Text of the message to send.
285+
:type message: str
286+
:param target_urn: URNs to send the message to.
287+
:type target_urn: str
288+
:param interrupt: Whether to interrupt the target_urns from flows before sending the message.
289+
:type interrupt: bool
290+
:return: Ids of the Rapid Pro broadcasts created for this send request.
291+
These ids may be used to check on the status of the broadcast by making further requests to Rapid Pro.
292+
e.g. using get_broadcast_for_broadcast_id.
293+
:rtype: list of int
294+
"""
295+
log.info(f"Sending a message to {len(urns)} URNs...")
296+
log.debug(f"Sending to {urns}...")
297+
batch = []
298+
broadcast_ids = []
299+
interrupted = 0
300+
sent = 0
301+
302+
for urn in urns:
303+
batch.append(urn)
304+
if len(batch) >= 100: # limit of 100 imposed by Rapid Pro's API
305+
if interrupt:
306+
self.rapid_pro.bulk_interrupt_contacts(batch)
307+
interrupted += len(batch)
308+
log.info(f"Interrupted {interrupted} / {len(urns)} URNs")
309+
310+
response = self.rapid_pro.create_broadcast(message, urns=batch)
311+
broadcast_ids.append(response.id)
312+
sent += len(batch)
313+
batch = []
314+
log.info(f"Sent {sent} / {len(urns)} URNs")
315+
if len(batch) > 0:
316+
if interrupt:
317+
self.rapid_pro.bulk_interrupt_contacts(batch)
318+
interrupted += len(batch)
319+
response: Broadcast = self.rapid_pro.create_broadcast(message, urns=batch)
320+
sent += len(batch)
321+
broadcast_ids.append(response.id)
322+
log.info(f"Interrupted {interrupted} / {len(urns)} URNs")
323+
log.info(f"Sent {sent} / {len(urns)} URNs")
324+
325+
log.info(f"Message send request created with broadcast ids {ids}")
326+
return ids
327+
280328
def get_broadcast_for_broadcast_id(self, broadcast_id):
281329
"""
282330
Gets the broadcast with the requested id from Rapid Pro.

0 commit comments

Comments
 (0)