Пример #1
0
def _check_and_send_paused_warning(megatron_channel: MegatronChannel,
                                   user_id: str):
    if megatron_channel.is_paused:
        return

    last_warning = cache.get(PAUSE_WARNING_PREFIX + str(megatron_channel.id))
    if last_warning:
        last_warning = datetime.strptime(last_warning, '%d-%m-%Y:%H:%M:%S')
        minutes_elapsed = (datetime.now() - last_warning).total_seconds() / 60
        if minutes_elapsed < TIME_TIL_NEXT_WARNING:
            return

    workspace_id = megatron_channel.workspace.platform_id
    platform_user_id = megatron_channel.platform_user_id
    msg = formatting.get_unpaused_warning(workspace_id, platform_user_id)

    channel_id = megatron_channel.platform_channel_id
    integration_connection = IntegrationService(
        megatron_channel.megatron_integration).get_connection(as_user=False)
    message_action = Action(ActionType.POST_MESSAGE, {
        'channel': channel_id,
        'message': msg
    })
    integration_connection.take_action(message_action)

    last_warning = datetime.now().strftime('%d-%m-%Y:%H:%M:%S')
    cache.set(PAUSE_WARNING_PREFIX + str(megatron_channel.id), last_warning)
Пример #2
0
def _change_pause_state(
    megatron_user: MegatronUser,
    platform_user: User,
    request_data: RequestData,
    pause=False,
) -> dict:
    workspace = platform_user.workspace
    if not getattr(megatron_user, "command_url", None):
        return {"ok": False, "error": "No command url provided for workspace."}

    customer_connection = WorkspaceService(workspace).get_connection(as_user=False)
    response = customer_connection.open_im(platform_user.platform_id)
    if not response["ok"]:
        return {
            "ok": False,
            "error": "Failed to open get im channel from "
            f"slack: {response['error']}",
        }
    channel_id = response["channel"]["id"]

    data = {
        "megatron_verification_token": settings.MEGATRON_VERIFICATION_TOKEN,
        "command": "pause",
        "channel_id": channel_id,
        "platform_user_id": platform_user.platform_id,
        "team_id": workspace.platform_id,
        "paused": pause,
    }
    response = requests.post(megatron_user.command_url, json=data)
    # TODO: This response is 200 even on failure to find user
    if not response.status_code == 200:
        return {"ok": False, "error": "Failed to pause bot for user."}

    megatron_channel = MegatronChannel.objects.get(
        workspace=workspace, platform_user_id=platform_user.platform_id
    )
    megatron_channel.is_paused = pause
    megatron_channel.save()

    # TODO: This is probably better suited to being part of the integration itself
    integration = megatron_user.megatronintegration_set.first()
    integration_connection = IntegrationService(integration).get_connection(
        as_user=False
    )
    paused_word = "paused" if pause else "unpaused"
    msg = {"text": f"Bot *{paused_word}* for user: {platform_user}."}
    channel = request_data.channel_id
    message_action = Action(
        ActionType.POST_MESSAGE, {"channel": channel, "message": msg}
    )
    integration_connection.take_action(message_action)
    return {"ok": True}
Пример #3
0
def _change_pause_state(megatron_user: MegatronUser, platform_user: User,
                        request_data: RequestData, pause=False
                        ) -> dict:
    workspace = platform_user.workspace
    if not getattr(megatron_user, 'command_url', None):
        return {'ok': False, 'error': 'No command url provided for workspace.'}

    customer_connection = WorkspaceService(
        workspace).get_connection(as_user=False)
    response = customer_connection.open_im(platform_user.platform_id)
    if not response['ok']:
        return {
            'ok': False,
            'error': 'Failed to open get im channel from '
            f"slack: {response['error']}"
        }
    channel_id = response['channel']['id']

    data = {
        'megatron_verification_token': settings.MEGATRON_VERIFICATION_TOKEN,
        'command': 'pause',
        'channel_id': channel_id,
        'platform_user_id': platform_user.platform_id,
        'team_id': workspace.platform_id,
        'paused': pause,
    }
    response = requests.post(megatron_user.command_url, json=data)
    # TODO: This response is 200 even on failure to find user
    if not response.status_code == 200:
        return {'ok': False, 'error': 'Failed to pause bot for user.'}

    megatron_channel = MegatronChannel.objects.get(
        workspace=workspace, platform_user_id=platform_user.platform_id)
    megatron_channel.is_paused = pause
    megatron_channel.save()

    # TODO: This is probably better suited to being part of the integration itself
    integration = megatron_user.megatronintegration_set.first()
    integration_connection = IntegrationService(
        integration).get_connection(as_user=False)
    paused_word = 'paused' if pause else 'unpaused'
    msg = {
        "text": f"Bot *{paused_word}* for user: {platform_user}."
    }
    channel = request_data.channel_id
    message_action = Action(ActionType.POST_MESSAGE, {'channel': channel, 'message': msg})
    integration_connection.take_action(message_action)
    return {'ok': True}
Пример #4
0
def _get_slack_user_data(channel_id, slack_id):
    # TODO: Verify responses/that user exists
    incoming_channel = MegatronChannel.objects.get(
        platform_channel_id=channel_id)
    integration_connection = IntegrationService(
        incoming_channel.megatron_integration).get_connection()
    action = Action(ActionType.GET_USER_INFO, {'user_id': slack_id})
    response = integration_connection.take_action(action)
    user_data = response['user']
    from_user = {
        'user_name': user_data['profile']['real_name'],
        'user_icon_url': user_data['profile']['image_24']
    }
    return from_user
Пример #5
0
def _get_slack_user_data(channel_id, slack_id):
    # TODO: Verify responses/that user exists
    incoming_channel = MegatronChannel.objects.get(
        platform_channel_id=channel_id)
    integration_connection = IntegrationService(
        incoming_channel.megatron_integration).get_connection()
    action = Action(ActionType.GET_USER_INFO, {"user_id": slack_id})
    response = integration_connection.take_action(action)
    user_data = response["user"]
    from_user = {
        "user_name": user_data["profile"]["real_name"],
        "user_icon_url": user_data["profile"]["image_24"],
    }
    return from_user
Пример #6
0
def edit(request):
    message = json.loads(request.body)
    # Warning! Currently the only way to identify msgs sent by Megatron
    try:
        footer_text = message["message"]["attachments"][-1]["footer"]
        if footer_text.startswith("sent by"):
            return OK_RESPONSE
    except KeyError:
        pass

    if message.get("user"):
        megatron_channel = MegatronChannel.objects.filter(
            platform_user_id=message["message"]["user"]).first()
    elif message.get("channel"):
        megatron_channel = MegatronChannel.objects.filter(
            platform_channel_id=message["channel"]).first()
    else:
        return OK_RESPONSE
    if not megatron_channel:
        return OK_RESPONSE
    team_connection = IntegrationService(
        megatron_channel.megatron_integration).get_connection(as_user=False)

    existing_message = MegatronMessage.objects.filter(
        customer_msg_id=message["previous_message"]["ts"],
        megatron_channel=megatron_channel,
    ).first()

    if not megatron_channel or not existing_message:
        return OK_RESPONSE

    new_message = {
        "text": message["message"].get("text", ""),
        "attachments": message["message"].get("attachments"),
    }
    old_message = {
        "channel_id": megatron_channel.platform_channel_id,
        "ts": existing_message.integration_msg_id,
    }
    params = {"new_message": new_message, "old_message": old_message}
    update_action = Action(ActionType.UPDATE_MESSAGE, params)
    response = team_connection.take_action(update_action)

    existing_message.customer_msg_id = message["message"]["ts"]
    existing_message.integration_msg_id = response["ts"]
    existing_message.save()

    return OK_RESPONSE
Пример #7
0
def edit(request):
    message = json.loads(request.body)
    # Warning! Currently the only way to identify msgs sent by Megatron
    try:
        footer_text = message['message']['attachments'][-1]['footer']
        if footer_text.startswith('sent by'):
            return OK_RESPONSE
    except KeyError:
        pass

    if message.get('user'):
        megatron_channel = MegatronChannel.objects.filter(
            platform_user_id=message['message']['user']).first()
    elif message.get('channel'):
        megatron_channel = MegatronChannel.objects.filter(
            platform_channel_id=message['channel']).first()
    else:
        return OK_RESPONSE
    if not megatron_channel:
        return OK_RESPONSE
    team_connection = IntegrationService(
        megatron_channel.megatron_integration).get_connection(as_user=False)

    existing_message = MegatronMessage.objects.filter(
        customer_msg_id=message['previous_message']['ts'],
        megatron_channel=megatron_channel).first()

    if not megatron_channel or not existing_message:
        return OK_RESPONSE

    new_message = {
        'text': message['message'].get('text', ''),
        'attachments': message['message'].get('attachments')
    }
    old_message = {
        'channel_id': megatron_channel.platform_channel_id,
        'ts': existing_message.integration_msg_id
    }
    params = {'new_message': new_message, 'old_message': old_message}
    update_action = Action(ActionType.UPDATE_MESSAGE, params)
    response = team_connection.take_action(update_action)

    existing_message.customer_msg_id = message['message']['ts']
    existing_message.integration_msg_id = response['ts']
    existing_message.save()

    return OK_RESPONSE
Пример #8
0
def get_a_human(request):
    payload = json.loads(request.body)
    requesting_user = payload['requesting_user']
    workspace_id = payload['workspace_id']
    integration = MegatronIntegration.objects.get(
        megatron_user__id=request.user.id)
    team_connection = IntegrationService(integration).get_connection(
        as_user=False)

    # TODO: This should all be integration dependent
    channel = settings.NOTIFICATIONS_CHANNELS[
        NotificationChannels.customer_service]

    slack_name = requesting_user['with_team_domain']
    attach = {
        "color":
        '1f355e',
        "text":
        f"🆘 *{slack_name}* requested some help!",
        "callback_id":
        f"open",
        "actions": [{
            "name": "categorize",
            "text": "Open engagement channel",
            "type": "button",
            "value": f'{workspace_id}-{requesting_user["slack_id"]}'
        }],
        "mrkdwn_in": ["text"]
    }
    msg = ({'text': ' ', 'attachments': [attach]})

    msg_action = Action(ActionType.POST_MESSAGE, {
        'channel': channel,
        'message': msg
    })
    response = team_connection.take_action(msg_action)
    if response.get('ok'):
        return OK_RESPONSE
    return MegatronResponse(response.get('error'), response.get('status'))