def do_send_messages(messages_maybe_none: Sequence[Optional[MutableMapping[(str, Any)]]], email_gateway: bool=False, mark_as_read: Sequence[int]=[]) -> List[int]:
    'See\n    https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html\n    for high-level documentation on this subsystem.\n    '
    messages = [message for message in messages_maybe_none if (message is not None)]
    already_sent_ids: List[int] = []
    new_messages: List[MutableMapping[(str, Any)]] = []
    for message in messages:
        if isinstance(message['message'], int):
            already_sent_ids.append(message['message'])
        else:
            new_messages.append(message)
    messages = new_messages
    links_for_embed: Set[str] = set()
    for message in messages:
        message['rendered_content'] = message.get('rendered_content', None)
        message['stream'] = message.get('stream', None)
        message['local_id'] = message.get('local_id', None)
        message['sender_queue_id'] = message.get('sender_queue_id', None)
        message['realm'] = message.get('realm', message['message'].sender.realm)
        mention_data = MentionData(realm_id=message['realm'].id, content=message['message'].content)
        message['mention_data'] = mention_data
        if message['message'].is_stream_message():
            stream_id = message['message'].recipient.type_id
            stream_topic: Optional[StreamTopicTarget] = StreamTopicTarget(stream_id=stream_id, topic_name=message['message'].topic_name())
        else:
            stream_topic = None
        info = get_recipient_info(recipient=message['message'].recipient, sender_id=message['message'].sender_id, stream_topic=stream_topic, possibly_mentioned_user_ids=mention_data.get_user_ids(), possible_wildcard_mention=mention_data.message_has_wildcards())
        message['active_user_ids'] = info['active_user_ids']
        message['push_notify_user_ids'] = info['push_notify_user_ids']
        message['stream_push_user_ids'] = info['stream_push_user_ids']
        message['stream_email_user_ids'] = info['stream_email_user_ids']
        message['um_eligible_user_ids'] = info['um_eligible_user_ids']
        message['long_term_idle_user_ids'] = info['long_term_idle_user_ids']
        message['default_bot_user_ids'] = info['default_bot_user_ids']
        message['service_bot_tuples'] = info['service_bot_tuples']
        assert (message['message'].rendered_content is None)
        rendered_content = render_incoming_message(message['message'], message['message'].content, message['active_user_ids'], message['realm'], mention_data=message['mention_data'], email_gateway=email_gateway)
        message['message'].rendered_content = rendered_content
        message['message'].rendered_content_version = markdown_version
        links_for_embed |= message['message'].links_for_preview
        for group_id in message['message'].mentions_user_group_ids:
            members = message['mention_data'].get_group_members(group_id)
            message['message'].mentions_user_ids.update(members)
        if message['message'].mentions_wildcard:
            message['wildcard_mention_user_ids'] = info['wildcard_mention_user_ids']
        else:
            message['wildcard_mention_user_ids'] = []
        '\n        Once we have the actual list of mentioned ids from message\n        rendering, we can patch in "default bots" (aka normal bots)\n        who were directly mentioned in this message as eligible to\n        get UserMessage rows.\n        '
        mentioned_user_ids = message['message'].mentions_user_ids
        default_bot_user_ids = message['default_bot_user_ids']
        mentioned_bot_user_ids = (default_bot_user_ids & mentioned_user_ids)
        message['um_eligible_user_ids'] |= mentioned_bot_user_ids
    user_message_flags: Dict[(int, Dict[(int, List[str])])] = defaultdict(dict)
    with transaction.atomic():
        Message.objects.bulk_create([message['message'] for message in messages])
        for message in messages:
            if do_claim_attachments(message['message'], message['message'].potential_attachment_path_ids):
                message['message'].has_attachment = True
                message['message'].save(update_fields=['has_attachment'])
        ums: List[UserMessageLite] = []
        for message in messages:
            mentioned_user_ids = message['message'].mentions_user_ids
            user_messages = create_user_messages(message=message['message'], um_eligible_user_ids=message['um_eligible_user_ids'], long_term_idle_user_ids=message['long_term_idle_user_ids'], stream_push_user_ids=message['stream_push_user_ids'], stream_email_user_ids=message['stream_email_user_ids'], mentioned_user_ids=mentioned_user_ids, mark_as_read=mark_as_read)
            for um in user_messages:
                user_message_flags[message['message'].id][um.user_profile_id] = um.flags_list()
            ums.extend(user_messages)
            message['message'].service_queue_events = get_service_bot_events(sender=message['message'].sender, service_bot_tuples=message['service_bot_tuples'], mentioned_user_ids=mentioned_user_ids, active_user_ids=message['active_user_ids'], recipient_type=message['message'].recipient.type)
        bulk_insert_ums(ums)
        for message in messages:
            do_widget_post_save_actions(message)
    for message in messages:
        realm_id: Optional[int] = None
        if message['message'].is_stream_message():
            if (message['stream'] is None):
                stream_id = message['message'].recipient.type_id
                message['stream'] = Stream.objects.select_related().get(id=stream_id)
            assert (message['stream'] is not None)
            realm_id = message['stream'].realm_id
        wide_message_dict = MessageDict.wide_dict(message['message'], realm_id)
        user_flags = user_message_flags.get(message['message'].id, {})
        sender = message['message'].sender
        message_type = wide_message_dict['type']
        presence_idle_user_ids = get_active_presence_idle_user_ids(realm=sender.realm, sender_id=sender.id, message_type=message_type, active_user_ids=message['active_user_ids'], user_flags=user_flags)
        event = dict(type='message', message=message['message'].id, message_dict=wide_message_dict, presence_idle_user_ids=presence_idle_user_ids)
        "\n        TODO:  We may want to limit user_ids to only those users who have\n               UserMessage rows, if only for minor performance reasons.\n\n               For now we queue events for all subscribers/sendees of the\n               message, since downstream code may still do notifications\n               that don't require UserMessage rows.\n\n               Our automated tests have gotten better on this codepath,\n               but we may have coverage gaps, so we should be careful\n               about changing the next line.\n        "
        user_ids = (message['active_user_ids'] | set(user_flags.keys()))
        users = [dict(id=user_id, flags=user_flags.get(user_id, []), always_push_notify=(user_id in message['push_notify_user_ids']), stream_push_notify=(user_id in message['stream_push_user_ids']), stream_email_notify=(user_id in message['stream_email_user_ids']), wildcard_mention_notify=(user_id in message['wildcard_mention_user_ids'])) for user_id in user_ids]
        if message['message'].is_stream_message():
            assert (message['stream'] is not None)
            if message['stream'].is_public():
                event['realm_id'] = message['stream'].realm_id
                event['stream_name'] = message['stream'].name
            if message['stream'].invite_only:
                event['invite_only'] = True
            if (message['stream'].first_message_id is None):
                message['stream'].first_message_id = message['message'].id
                message['stream'].save(update_fields=['first_message_id'])
        if (message['local_id'] is not None):
            event['local_id'] = message['local_id']
        if (message['sender_queue_id'] is not None):
            event['sender_queue_id'] = message['sender_queue_id']
        send_event(message['realm'], event, users)
        if links_for_embed:
            event_data = {'message_id': message['message'].id, 'message_content': message['message'].content, 'message_realm_id': message['realm'].id, 'urls': links_for_embed}
            queue_json_publish('embed_links', event_data)
        if (message['message'].recipient.type == Recipient.PERSONAL):
            welcome_bot_id = get_system_bot(settings.WELCOME_BOT).id
            if ((welcome_bot_id in message['active_user_ids']) and (welcome_bot_id != message['message'].sender_id)):
                send_welcome_bot_response(message)
        for (queue_name, events) in message['message'].service_queue_events.items():
            for event in events:
                queue_json_publish(queue_name, {'message': wide_message_dict, 'trigger': event['trigger'], 'user_profile_id': event['user_profile_id']})
    return (already_sent_ids + [message['message'].id for message in messages])
See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem.
def do_send_messages(messages_maybe_none: Sequence[Optional[MutableMapping[(str, Any)]]], email_gateway: bool=False, mark_as_read: Sequence[int]=[]) -> List[int]:
    'See\n    https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html\n    for high-level documentation on this subsystem.\n    '
    messages = [message for message in messages_maybe_none if (message is not None)]
    already_sent_ids: List[int] = []
    new_messages: List[MutableMapping[(str, Any)]] = []
    for message in messages:
        if isinstance(message['message'], int):
            already_sent_ids.append(message['message'])
        else:
            new_messages.append(message)
    messages = new_messages
    links_for_embed: Set[str] = set()
    for message in messages:
        message['rendered_content'] = message.get('rendered_content', None)
        message['stream'] = message.get('stream', None)
        message['local_id'] = message.get('local_id', None)
        message['sender_queue_id'] = message.get('sender_queue_id', None)
        message['realm'] = message.get('realm', message['message'].sender.realm)
        mention_data = MentionData(realm_id=message['realm'].id, content=message['message'].content)
        message['mention_data'] = mention_data
        if message['message'].is_stream_message():
            stream_id = message['message'].recipient.type_id
            stream_topic: Optional[StreamTopicTarget] = StreamTopicTarget(stream_id=stream_id, topic_name=message['message'].topic_name())
        else:
            stream_topic = None
        info = get_recipient_info(recipient=message['message'].recipient, sender_id=message['message'].sender_id, stream_topic=stream_topic, possibly_mentioned_user_ids=mention_data.get_user_ids(), possible_wildcard_mention=mention_data.message_has_wildcards())
        message['active_user_ids'] = info['active_user_ids']
        message['push_notify_user_ids'] = info['push_notify_user_ids']
        message['stream_push_user_ids'] = info['stream_push_user_ids']
        message['stream_email_user_ids'] = info['stream_email_user_ids']
        message['um_eligible_user_ids'] = info['um_eligible_user_ids']
        message['long_term_idle_user_ids'] = info['long_term_idle_user_ids']
        message['default_bot_user_ids'] = info['default_bot_user_ids']
        message['service_bot_tuples'] = info['service_bot_tuples']
        assert (message['message'].rendered_content is None)
        rendered_content = render_incoming_message(message['message'], message['message'].content, message['active_user_ids'], message['realm'], mention_data=message['mention_data'], email_gateway=email_gateway)
        message['message'].rendered_content = rendered_content
        message['message'].rendered_content_version = markdown_version
        links_for_embed |= message['message'].links_for_preview
        for group_id in message['message'].mentions_user_group_ids:
            members = message['mention_data'].get_group_members(group_id)
            message['message'].mentions_user_ids.update(members)
        if message['message'].mentions_wildcard:
            message['wildcard_mention_user_ids'] = info['wildcard_mention_user_ids']
        else:
            message['wildcard_mention_user_ids'] = []
        '\n        Once we have the actual list of mentioned ids from message\n        rendering, we can patch in "default bots" (aka normal bots)\n        who were directly mentioned in this message as eligible to\n        get UserMessage rows.\n        '
        mentioned_user_ids = message['message'].mentions_user_ids
        default_bot_user_ids = message['default_bot_user_ids']
        mentioned_bot_user_ids = (default_bot_user_ids & mentioned_user_ids)
        message['um_eligible_user_ids'] |= mentioned_bot_user_ids
    user_message_flags: Dict[(int, Dict[(int, List[str])])] = defaultdict(dict)
    with transaction.atomic():
        Message.objects.bulk_create([message['message'] for message in messages])
        for message in messages:
            if do_claim_attachments(message['message'], message['message'].potential_attachment_path_ids):
                message['message'].has_attachment = True
                message['message'].save(update_fields=['has_attachment'])
        ums: List[UserMessageLite] = []
        for message in messages:
            mentioned_user_ids = message['message'].mentions_user_ids
            user_messages = create_user_messages(message=message['message'], um_eligible_user_ids=message['um_eligible_user_ids'], long_term_idle_user_ids=message['long_term_idle_user_ids'], stream_push_user_ids=message['stream_push_user_ids'], stream_email_user_ids=message['stream_email_user_ids'], mentioned_user_ids=mentioned_user_ids, mark_as_read=mark_as_read)
            for um in user_messages:
                user_message_flags[message['message'].id][um.user_profile_id] = um.flags_list()
            ums.extend(user_messages)
            message['message'].service_queue_events = get_service_bot_events(sender=message['message'].sender, service_bot_tuples=message['service_bot_tuples'], mentioned_user_ids=mentioned_user_ids, active_user_ids=message['active_user_ids'], recipient_type=message['message'].recipient.type)
        bulk_insert_ums(ums)
        for message in messages:
            do_widget_post_save_actions(message)
    for message in messages:
        realm_id: Optional[int] = None
        if message['message'].is_stream_message():
            if (message['stream'] is None):
                stream_id = message['message'].recipient.type_id
                message['stream'] = Stream.objects.select_related().get(id=stream_id)
            assert (message['stream'] is not None)
            realm_id = message['stream'].realm_id
        wide_message_dict = MessageDict.wide_dict(message['message'], realm_id)
        user_flags = user_message_flags.get(message['message'].id, {})
        sender = message['message'].sender
        message_type = wide_message_dict['type']
        presence_idle_user_ids = get_active_presence_idle_user_ids(realm=sender.realm, sender_id=sender.id, message_type=message_type, active_user_ids=message['active_user_ids'], user_flags=user_flags)
        event = dict(type='message', message=message['message'].id, message_dict=wide_message_dict, presence_idle_user_ids=presence_idle_user_ids)
        "\n        TODO:  We may want to limit user_ids to only those users who have\n               UserMessage rows, if only for minor performance reasons.\n\n               For now we queue events for all subscribers/sendees of the\n               message, since downstream code may still do notifications\n               that don't require UserMessage rows.\n\n               Our automated tests have gotten better on this codepath,\n               but we may have coverage gaps, so we should be careful\n               about changing the next line.\n        "
        user_ids = (message['active_user_ids'] | set(user_flags.keys()))
        users = [dict(id=user_id, flags=user_flags.get(user_id, []), always_push_notify=(user_id in message['push_notify_user_ids']), stream_push_notify=(user_id in message['stream_push_user_ids']), stream_email_notify=(user_id in message['stream_email_user_ids']), wildcard_mention_notify=(user_id in message['wildcard_mention_user_ids'])) for user_id in user_ids]
        if message['message'].is_stream_message():
            assert (message['stream'] is not None)
            if message['stream'].is_public():
                event['realm_id'] = message['stream'].realm_id
                event['stream_name'] = message['stream'].name
            if message['stream'].invite_only:
                event['invite_only'] = True
            if (message['stream'].first_message_id is None):
                message['stream'].first_message_id = message['message'].id
                message['stream'].save(update_fields=['first_message_id'])
        if (message['local_id'] is not None):
            event['local_id'] = message['local_id']
        if (message['sender_queue_id'] is not None):
            event['sender_queue_id'] = message['sender_queue_id']
        send_event(message['realm'], event, users)
        if links_for_embed:
            event_data = {'message_id': message['message'].id, 'message_content': message['message'].content, 'message_realm_id': message['realm'].id, 'urls': links_for_embed}
            queue_json_publish('embed_links', event_data)
        if (message['message'].recipient.type == Recipient.PERSONAL):
            welcome_bot_id = get_system_bot(settings.WELCOME_BOT).id
            if ((welcome_bot_id in message['active_user_ids']) and (welcome_bot_id != message['message'].sender_id)):
                send_welcome_bot_response(message)
        for (queue_name, events) in message['message'].service_queue_events.items():
            for event in events:
                queue_json_publish(queue_name, {'message': wide_message_dict, 'trigger': event['trigger'], 'user_profile_id': event['user_profile_id']})
    return (already_sent_ids + [message['message'].id for message in messages])