本文整理汇总了Python中temba.msgs.models.Msg.create_incoming方法的典型用法代码示例。如果您正苦于以下问题:Python Msg.create_incoming方法的具体用法?Python Msg.create_incoming怎么用?Python Msg.create_incoming使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类temba.msgs.models.Msg
的用法示例。
在下文中一共展示了Msg.create_incoming方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_resume_with_message_in_subflow
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_resume_with_message_in_subflow(self, mock_report_success, mock_report_failure):
self.get_flow("subflow")
parent_flow = Flow.objects.get(org=self.org, name="Parent Flow")
child_flow = Flow.objects.get(org=self.org, name="Child Flow")
# start the parent flow and then trigger the subflow by picking an option
parent_flow.start([], [self.contact])
Msg.create_incoming(self.channel, "tel:+12065552020", "color")
self.assertEqual(mock_report_success.call_count, 1)
self.assertEqual(mock_report_failure.call_count, 0)
parent_run, child_run = list(FlowRun.objects.order_by("created_on"))
# check the reconstructed session for this run
session = resumes.reconstruct_session(child_run)
self.assertEqual(len(session["runs"]), 2)
self.assertEqual(session["runs"][0]["flow"]["uuid"], str(parent_flow.uuid))
self.assertEqual(session["runs"][1]["flow"]["uuid"], str(child_flow.uuid))
self.assertEqual(session["contact"]["uuid"], str(self.contact.uuid))
self.assertEqual(session["trigger"]["type"], "manual")
self.assertNotIn("results", session)
self.assertNotIn("events", session)
# and then resume by replying
Msg.create_incoming(self.channel, "tel:+12065552020", "I like red")
child_run.refresh_from_db()
parent_run.refresh_from_db()
# subflow run has completed
self.assertIsNotNone(child_run.exited_on)
self.assertIsNone(parent_run.exited_on)
self.assertEqual(mock_report_success.call_count, 2)
self.assertEqual(mock_report_failure.call_count, 0)
示例2: test_msg_events_with_attachments
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_msg_events_with_attachments(self, mock_report_success, mock_report_failure):
# test an outgoing message with media
flow = self.get_flow("color")
flow_json = flow.as_json()
flow_json["action_sets"][2]["actions"][0]["media"] = {"base": "image/jpg:files/blue.jpg"}
flow.update(flow_json)
flow.start([], [self.contact])
Msg.create_incoming(self.channel, "tel:+12065552020", "blue")
self.assertEqual(mock_report_success.call_count, 1)
self.assertEqual(mock_report_failure.call_count, 0)
示例3: handle_async
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def handle_async(self, urn, content, date, message_id):
from temba.msgs.models import Msg, USSD
Msg.create_incoming(
channel=self.channel,
org=self.org,
urn=urn,
text=content or "",
sent_on=date,
connection=self,
msg_type=USSD,
external_id=message_id,
)
示例4: test_webhook_mocking
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_webhook_mocking(self, mock_report_success, mock_report_failure):
flow = self.get_flow("dual_webhook")
# mock the two webhook calls in this flow
self.mockRequest("POST", "/code", '{"code": "ABABUUDDLRS"}', content_type="application/json")
self.mockRequest("GET", "/success", "Success")
flow.start([], [self.contact])
Msg.create_incoming(self.channel, "tel:+12065552020", "Bob")
self.assertAllRequestsMade()
self.assertEqual(mock_report_success.call_count, 1)
self.assertEqual(mock_report_failure.call_count, 0)
示例5: create_unsolicited_incoming
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def create_unsolicited_incoming(self, org):
if not org.cache["contacts"]:
return
self._log(" > Receiving unsolicited incoming message in org %s\n" % org.name)
available_contacts = list(set(org.cache["contacts"]) - set(org.cache["activity"]["started"]))
if available_contacts:
contact = Contact.objects.get(id=self.random_choice(available_contacts))
channel = self.random_choice(org.cache["channels"])
urn = contact.urns.first()
if urn:
text = " ".join([self.random_choice(l) for l in INBOX_MESSAGES])
Msg.create_incoming(channel, str(urn), text)
示例6: test_trial_throttling
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_trial_throttling(self, mock_report_success, mock_report_failure):
# first resume in a suitable flow will be trialled
favorites = self.get_flow("favorites")
favorites.start([], [self.contact], interrupt=True)
Msg.create_incoming(self.channel, "tel:+12065552020", "red")
self.assertEqual(mock_report_success.call_count, 1)
self.assertEqual(mock_report_failure.call_count, 0)
Msg.create_incoming(self.channel, "tel:+12065552020", "primus")
# second won't because its too soon
self.assertEqual(mock_report_success.call_count, 1)
self.assertEqual(mock_report_failure.call_count, 0)
示例7: test_message_incoming
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_message_incoming(self):
num_contacts = 300
with SegmentProfiler("Creating incoming messages from new contacts", self, False, force_profile=True):
for c in range(0, num_contacts):
scheme, path, channel = self.urn_generators[c % len(self.urn_generators)](c)
Msg.create_incoming(channel, (scheme, path), "Thanks #1", self.user)
with SegmentProfiler("Creating incoming messages from existing contacts", self, False, force_profile=True):
for c in range(0, num_contacts):
scheme, path, channel = self.urn_generators[c % len(self.urn_generators)](c)
Msg.create_incoming(channel, (scheme, path), "Thanks #2", self.user)
# check messages for each channel
incoming_total = 2 * num_contacts
self.assertEqual(incoming_total / 3, Msg.objects.filter(direction=INCOMING, channel=self.tel_mtn).count())
self.assertEqual(incoming_total / 3, Msg.objects.filter(direction=INCOMING, channel=self.tel_tigo).count())
self.assertEqual(incoming_total / 3, Msg.objects.filter(direction=INCOMING, channel=self.twitter).count())
示例8: test_resume_with_expiration_in_subflow
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_resume_with_expiration_in_subflow(self, mock_report_success, mock_report_failure):
self.get_flow("subflow")
parent_flow = Flow.objects.get(org=self.org, name="Parent Flow")
# start the parent flow and then trigger the subflow by picking an option
parent_flow.start([], [self.contact])
Msg.create_incoming(self.channel, "tel:+12065552020", "color")
parent_run, child_run = list(FlowRun.objects.order_by("created_on"))
# resume by expiring the child run
child_run.expire()
child_run.refresh_from_db()
parent_run.refresh_from_db()
# which should end both our runs
self.assertIsNotNone(child_run.exited_on)
self.assertIsNotNone(parent_run.exited_on)
self.assertEqual(mock_report_success.call_count, 2)
self.assertEqual(mock_report_failure.call_count, 0)
示例9: test_resume_with_message
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_resume_with_message(self, mock_report_success, mock_report_failure):
favorites = self.get_flow("favorites")
run, = favorites.start([], [self.contact])
# check the reconstructed session for this run
session = resumes.reconstruct_session(run)
self.assertEqual(len(session["runs"]), 1)
self.assertEqual(session["runs"][0]["flow"]["uuid"], str(favorites.uuid))
self.assertEqual(session["contact"]["uuid"], str(self.contact.uuid))
self.assertNotIn("results", session)
self.assertNotIn("events", session)
# and then resume by replying
Msg.create_incoming(
self.channel, "tel:+12065552020", "I like red", attachments=["image/jpeg:http://example.com/red.jpg"]
)
run.refresh_from_db()
self.assertEqual(mock_report_success.call_count, 1)
self.assertEqual(mock_report_failure.call_count, 0)
# and then resume by replying again
Msg.create_incoming(self.channel, "tel:+12065552020", "ooh Primus")
run.refresh_from_db()
self.assertEqual(mock_report_success.call_count, 2)
self.assertEqual(mock_report_failure.call_count, 0)
# simulate session not containing this run
self.assertEqual(set(resumes.compare(run, {"runs": []}).keys()), {"session"})
# simulate differences in the path, results and events
session = resumes.reconstruct_session(run)
session["runs"][0]["path"][0]["node_uuid"] = "wrong node"
session["runs"][0]["results"]["color"]["value"] = "wrong value"
session["runs"][0]["events"][0]["msg"]["text"] = "wrong text"
self.assertTrue(resumes.compare(run, session)["diffs"])
示例10: create_flow_run
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def create_flow_run(self, org):
activity = org.cache["activity"]
flow = activity["flow"]
if activity["unresponded"]:
contact_id = self.random_choice(activity["unresponded"])
activity["unresponded"].remove(contact_id)
contact = Contact.objects.get(id=contact_id)
urn = contact.urns.first()
if urn:
self._log(" > Receiving flow responses for flow %s in org %s\n" % (flow.name, flow.org.name))
inputs = self.random_choice(flow.input_templates)
for text in inputs:
channel = flow.org.cache["channels"][0]
Msg.create_incoming(channel, str(urn), text)
# if more than 10% of contacts have responded, consider flow activity over
if len(activity["unresponded"]) <= (len(activity["started"]) * 0.9):
self.end_flow_activity(flow.org)
示例11: default
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def default(self, line):
"""
Sends a message as the current contact's highest priority URN
"""
urn = self.contact.get_urn()
incoming = Msg.create_incoming(None, (urn.scheme, urn.path), line, date=timezone.now(), org=self.org)
self.echo((Fore.GREEN + "[%s] " + Fore.YELLOW + ">>" + Fore.MAGENTA + " %s" + Fore.WHITE) % (urn.urn, incoming.text))
# look up any message responses
outgoing = Msg.objects.filter(org=self.org, pk__gt=incoming.pk, direction=OUTGOING)
for response in outgoing:
self.echo((Fore.GREEN + "[%s] " + Fore.YELLOW + "<<" + Fore.MAGENTA + " %s" + Fore.WHITE) % (urn.urn, response.text))
示例12: test_trial_fault_tolerance
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_trial_fault_tolerance(self, mock_report_failure):
favorites = self.get_flow("favorites")
# an exception in maybe_start shouldn't prevent normal flow execution
with patch("temba.flows.server.trial.resumes.reconstruct_session") as mock_reconstruct_session:
mock_reconstruct_session.side_effect = ValueError("BOOM")
run, = favorites.start([], [self.contact])
Msg.create_incoming(self.channel, "tel:+12065552020", "I like red")
run.refresh_from_db()
self.assertEqual(len(run.path), 4)
# a flow server exception in end also shouldn't prevent normal flow execution
with patch("temba.flows.server.trial.resumes.resume") as mock_resume:
mock_resume.side_effect = FlowServerException("resume", {}, {"errors": ["Boom!"]})
run, = favorites.start([], [self.contact], restart_participants=True)
Msg.create_incoming(self.channel, "tel:+12065552020", "I like red")
run.refresh_from_db()
self.assertEqual(len(run.path), 4)
# any other exception in end_resume also shouldn't prevent normal flow execution
with patch("temba.flows.server.trial.resumes.resume") as mock_resume:
mock_resume.side_effect = ValueError("BOOM")
run, = favorites.start([], [self.contact], restart_participants=True)
Msg.create_incoming(self.channel, "tel:+12065552020", "I like red")
run.refresh_from_db()
self.assertEqual(len(run.path), 4)
# detected differences should be reported but shouldn't effect normal flow execution
with patch("temba.flows.server.trial.resumes.compare") as mock_compare:
mock_compare.return_value = {"diffs": ["a", "b"]}
run, = favorites.start([], [self.contact], restart_participants=True)
Msg.create_incoming(self.channel, "tel:+12065552020", "I like red")
run.refresh_from_db()
self.assertEqual(len(run.path), 4)
self.assertEqual(mock_report_failure.call_count, 1)
示例13: create_messages_for_ivr_actions
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def create_messages_for_ivr_actions(apps, schema_editor):
from django.contrib.auth.models import User
IVRAction = apps.get_model("ivr", "IVRAction")
# create a one-to-one mapping for any ivr actions as ivr messages
for org in Org.objects.all():
channel = org.get_call_channel()
# print "Processing %s" % org
if channel:
for ivr in IVRAction.objects.filter(org=org):
step = FlowStep.objects.get(pk=ivr.step.pk)
if step.rule_value:
urn = ivr.call.contact_urn
msg_dict = {}
if step.rule_value[0:4] == 'http':
msg_dict['recording_url'] = step.rule_value
user = User.objects.get(pk=ivr.call.created_by_id)
msg = Msg.create_incoming(channel, (urn.scheme, urn.path), step.rule_value,
user=user, topup=ivr.topup, status=HANDLED,
msg_type=IVR, date=ivr.created_on, org=org, **msg_dict)
step.add_message(msg)
示例14: test_resume_in_triggered_session
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
def test_resume_in_triggered_session(self, mock_report_success, mock_report_failure):
parent_flow = self.get_flow("action_packed")
child_flow = Flow.objects.get(org=self.org, name="Favorite Color")
parent_flow.start([], [self.contact], restart_participants=True)
Msg.create_incoming(self.channel, "tel:+12065552020", "Trey Anastasio")
Msg.create_incoming(self.channel, "tel:+12065552020", "Male")
parent_run, child_run = list(FlowRun.objects.order_by("created_on"))
child_contact = Contact.objects.get(name="Oprah Winfrey")
self.assertEqual(parent_run.flow, parent_flow)
self.assertEqual(parent_run.contact, self.contact)
self.assertEqual(child_run.flow, child_flow)
self.assertEqual(child_run.contact, child_contact)
# check that the run which triggered the child run isn't part of its session, but is part of the trigger
session = resumes.reconstruct_session(child_run)
self.assertEqual(len(session["runs"]), 1)
self.assertEqual(session["runs"][0]["flow"]["uuid"], str(child_flow.uuid))
self.assertEqual(session["contact"]["uuid"], str(child_contact.uuid))
self.assertEqual(session["trigger"]["type"], "flow_action")
self.assertNotIn("results", session)
self.assertNotIn("events", session)
with override_settings(FLOW_SERVER_TRIAL="always"):
# resume child run with a message
Msg.create_incoming(self.channel, "tel:+12065552121", "red")
child_run.refresh_from_db()
# and it should now be complete
self.assertIsNotNone(child_run.exited_on)
self.assertEqual(mock_report_success.call_count, 1)
self.assertEqual(mock_report_failure.call_count, 0)
示例15: post
# 需要导入模块: from temba.msgs.models import Msg [as 别名]
# 或者: from temba.msgs.models.Msg import create_incoming [as 别名]
#.........这里部分代码省略.........
response_body = "Missing one of %s in request parameters." % (", ".join(expected_keys))
event = HttpEvent(request_method, request_path, request_body, status, response_body)
log_channel(channel, "Failed to handle event.", event, is_error=True)
return HttpResponse(response_body, status=status)
message_id = data["message_id"]
event_type = data["event_type"]
# look up the message
message = Msg.objects.filter(channel=channel, external_id=message_id).select_related("channel")
if not message:
status = 400
response_body = "Message with external id of '%s' not found" % (message_id,)
event = HttpEvent(request_method, request_path, request_body, status, response_body)
log_channel(channel, "Failed to handle %s event_type." % (event_type), event)
return HttpResponse(response_body, status=status)
if event_type == "submitted":
for message_obj in message:
message_obj.status_sent()
if event_type == "delivery_succeeded":
for message_obj in message:
message_obj.status_delivered()
elif event_type in ["delivery_failed", "rejected"]:
for message_obj in message:
message_obj.status_fail()
response_body = {"status": self.ACK, "message_ids": [message_obj.pk for message_obj in message]}
event = HttpEvent(request_method, request_path, request_body, 200, json.dumps(response_body))
log_channel(channel, "Handled %s event_type." % (event_type), event)
# Let Junebug know we're happy
return JsonResponse(response_body)
# Handle an inbound message
elif action == "inbound":
expected_keys = [
"channel_data",
"from",
"channel_id",
"timestamp",
"content",
"to",
"reply_to",
"message_id",
]
if not set(expected_keys).issubset(data.keys()):
status = 400
response_body = "Missing one of %s in request parameters." % (", ".join(expected_keys))
event = HttpEvent(request_method, request_path, request_body, status, response_body)
log_channel(channel, "Failed to handle message.", event, is_error=True)
return HttpResponse(response_body, status=status)
if is_ussd:
status = {"close": USSDSession.INTERRUPTED, "new": USSDSession.TRIGGERED}.get(
channel_data.get("session_event"), USSDSession.IN_PROGRESS
)
message_date = datetime.strptime(data["timestamp"], "%Y-%m-%d %H:%M:%S.%f")
gmt_date = pytz.timezone("GMT").localize(message_date)
# Use a session id if provided, otherwise fall back to using the `from` address as the identifier
session_id = channel_data.get("session_id") or data["from"]
connection = USSDSession.handle_incoming(
channel=channel,
urn=data["from"],
content=data["content"],
status=status,
date=gmt_date,
external_id=session_id,
message_id=data["message_id"],
starcode=data["to"],
)
if connection:
status = 200
response_body = {"status": self.ACK, "session_id": connection.pk}
event = HttpEvent(request_method, request_path, request_body, status, json.dumps(response_body))
log_channel(
channel, "Handled USSD message of %s session_event" % (channel_data["session_event"],), event
)
return JsonResponse(response_body, status=status)
else:
status = 400
response_body = {"status": self.NACK, "reason": "No suitable session found for this message."}
event = HttpEvent(request_method, request_path, request_body, status, json.dumps(response_body))
log_channel(
channel,
"Failed to handle USSD message of %s session_event" % (channel_data["session_event"],),
event,
)
return JsonResponse(response_body, status=status)
else:
content = data["content"]
message = Msg.create_incoming(channel, URN.from_tel(data["from"]), content)
status = 200
response_body = {"status": self.ACK, "message_id": message.pk}
Msg.objects.filter(pk=message.id).update(external_id=data["message_id"])
event = HttpEvent(request_method, request_path, request_body, status, json.dumps(response_body))
ChannelLog.log_message(message, "Handled inbound message.", event)
return JsonResponse(response_body, status=status)