Пример #1
0
def parse_and_schedule(params):
    user_id = params['user_id'][0]
    team_id = params['team_id'][0]
    team_domain = params['team_domain'][0]
    channel_id = params['channel_id'][0]
    command_text = params['text'][0]
    response_url = params['response_url'][0]
    
    user = User(user_id)
    team = Team(team_id)
    
    try:
        token = user.get_auth_token()
    except UserAuthorizeError:
        post_and_print_info_and_confirm_success(
            response_url,
            "Sorry, your text cannot be sent because you haven't"
            " authorized DelaySay yet."
            "\n*Please grant DelaySay permission* to schedule your messages,"
            " then try again:"
            f"\n{api_domain}/add/?team=" + team_id +
            "\nIf you have any questions, please reach out at"
            f" {contact_page} or {support_email}")
        return
    
    if team.is_trialing():
        if team.get_time_payment_has_been_overdue() > PAYMENT_GRACE_PERIOD:
            payment_status = "red trial"
        elif team.get_time_till_payment_is_due() < TRIAL_WARNING_PERIOD:
            payment_status = "yellow trial"
        else:
            payment_status = "green"
    else:
        if team.get_time_payment_has_been_overdue() > PAYMENT_GRACE_PERIOD:
            payment_status = "red"
        elif (team.get_time_payment_has_been_overdue()
              > SUBSCRIPTION_WARNING_PERIOD):
            payment_status = "yellow"
        else:
            payment_status = "green"
    
    subscribe_url_with_team_id = f"{subscribe_url}/?team={team_id}"
    
    if payment_status.startswith("red"):
        text = ("\nWe hope you've enjoyed DelaySay! Your *message cannot be"
                " sent* because your workspace's")
        if payment_status == "red trial":
            text += (
                " free trial has ended."
                "\nTo continue using DelaySay, *please subscribe here:*"
                "\n" + subscribe_url_with_team_id +
                "\nIf you have any questions, please reach out at"
                f" {contact_page} or {support_email}"
            )
        else:
            text += " subscription has expired or the last payment failed."
            # TODO: As of 2021-02-06, if the team's subscription was
            # cancelled (not failed), the Stripe customer portal will
            # show payment information but no current plan.
            # And it will not have a way to add a plan.
            # So don't offer to send them to the billing portal.
            # Just have them make a new subscription or contact us.
            if user.can_manage_billing():
                url = generate_billing_url(user_id, team_id, team_domain)
                text += (
                    "\n\nTo see why, please *view your Stripe customer"
                    " portal*:"
                    f"\n{url}"
                )
            else:
                text += (
                    "\n\nTo see why, an admin in your Slack workspace can type"
                    " this to *view your Stripe customer portal*:"
                    f"\n        `{slash} billing`"
                )
            text += (
                "\nIn your billing portal, you can add credit cards, view past"
                " invoices, and manage your DelaySay subscription."
                "\n\nOr if you prefer, you can start a new subscription:"
                "\n" + subscribe_url_with_team_id +
                "\n\nIf you have any questions or concerns, we'd be happy to"
                f" chat with you at {contact_page} or {support_email}"
            )
        
        post_and_print_info_and_confirm_success(response_url, text)
        return
    # fi payment_status.startswith("red")
    
    request_unix_timestamp = params['request_timestamp']
    
    user_tz = user.get_timezone()
    try:
        parser = SlashCommandParser(
            command_text,
            datetime.fromtimestamp(request_unix_timestamp, tz=user_tz))
    except CommandParseError as err:
        post_and_print_info_and_confirm_success(
            response_url,
            "*Sorry, I don't understand. Please try again.*\n"
            + build_help_response(params, user_asked_for_help=False)['body'])
        return
    except TimeParseError as err:
        post_and_print_info_and_confirm_success(
            response_url,
            f'Sorry, I don\'t understand the time "{err.time_text}".'
            " *Please try again.*")
        return
    
    date = parser.get_date_string_for_slack()
    time = parser.get_time_string_for_slack()
    unix_timestamp = datetime.timestamp(parser.get_time())
    message = parser.get_message()
    
    slack_client = slack.WebClient(token=token)
    try:
        slack_client.chat_scheduleMessage(
            channel=channel_id,
            post_at=unix_timestamp,
            text=message
        )
    except slack.errors.SlackApiError as err:
        error_code = err.response['error']
        if error_code == "time_in_past":
            if unix_timestamp < request_unix_timestamp:
                error_text = "Sorry, I can't schedule a message in the past."
            else:
                error_text = (
                    "Sorry, I can't schedule in the extremely near future.")
        elif error_code == "time_too_far":
            error_text = (
                "Sorry, I can't schedule more than 120 days in the future.")
        elif error_code == "msg_too_long":
            error_text = (
                f"Sorry, your message is too long: {len(message)} characters.")
        else:
            raise
        post_and_print_info_and_confirm_success(response_url, error_text)
        return
    
    text = (
        f'At {time} on {date}, I will post on your behalf:'
        f'\n{message}'.replace("\n", "\n> "))
    if payment_status.startswith("yellow"):
        text += "\n\nWe hope you're enjoying DelaySay! Your workspace's"
        if payment_status == "yellow trial":
            text += " free trial is almost over."
        elif payment_status == "yellow":
            text += " subscription is expiring."
        text += ("\nTo continue using DelaySay, *please subscribe here:*"
                 "\n" + subscribe_url_with_team_id +
                 "\nIf you have any questions, please reach out at"
                 f" {contact_page} or {support_email}")
    post_and_print_info_and_confirm_success(response_url, text)
Пример #2
0
def respond_to_billing_request(params):
    user_id = params['user_id'][0]
    team_id = params['team_id'][0]
    team_domain = params['team_domain'][0]
    response_url = params['response_url'][0]
    command_text = params['text'][0]
    
    user = User(user_id)
    team = Team(team_id)
    
    try:
        token = user.get_auth_token()
    except UserAuthorizeError:
        post_and_print_info_and_confirm_success(
            response_url,
            "Sorry, you can't manage your DelaySay billing information"
            " because you haven't authorized DelaySay yet."
            "\n*Please grant DelaySay permission* to schedule your messages:"
            f"\n{api_domain}/add/?team=" + team_id)
        return
    
    billing_info = (
        "your workspace's DelaySay subscription and billing information")
    option, other_user_id, other_user = parse_option_and_user(command_text)
    if option:
        res = write_message_and_add_or_remove_billing_role(
            option, user, user_id, other_user, other_user_id, billing_info)
    elif team.is_trialing():
        if team.get_time_payment_has_been_overdue() > PAYMENT_GRACE_PERIOD:
            res = (
                "Your team's free trial has ended."
                "\nTo continue using DelaySay, *please subscribe here:*"
                f"\n{subscribe_url}/?team={team_id}"
                "\nIf you have any questions, please reach out at"
                f" {contact_page} or {support_email}"
            )
        else:
            res = (
                "Your team is currently on a *free trial* with full access"
                " to all DelaySay features."
                "\nIf you're interested in starting your DelaySay subscription"
                " early before your trial ends, please subscribe here:"
                f"\n{subscribe_url}/?team={team_id}"
                "\nAfter you subscribe, check back here to manage"
                f" {billing_info}."
                # TODO: Add the trial expiration date
            )
    elif team.never_expires():
        res = (
            "Congrats! Your team currently has free access to DelaySay."
            "\nIf you subscribe in the future, check back here to manage"
            f" {billing_info}."
        )
    elif not user.can_manage_billing():
        res = (
            f"You're not authorized to manage {billing_info}."
            "\nPlease ask a *workspace admin* to try instead."
            "\nAn admin can also decide to give you access by typing this:"
            f"\n        `{slash} billing authorize <@{user_id}>`"
        )
    elif False:
        # TODO: Implement a response for when I manually input a payment
        # expiration date, but the team has no Stripe subscription yet.
        pass
    else:
        res = write_billing_portal_message(
            user_id, team_id, team_domain, response_url)
    
    post_and_print_info_and_confirm_success(response_url, res)