コード例 #1
0
def test_format_help_remove_superfluous():
    with force_settings(PUBLIC_BY_DEFAULT=True,
                        PROGRESS_BY_DEFAULT=True,
                        BARS_BY_DEFAULT=True):
        hlp = frmts.format_help('/poll')
        assert '`--public`' not in hlp
        assert '`--anonym`' in hlp
        assert '`--progress`' not in hlp
        assert '`--noprogress`' in hlp
        assert '`--bars`' not in hlp
        assert '`--nobars`' in hlp

    with force_settings(PUBLIC_BY_DEFAULT=False,
                        PROGRESS_BY_DEFAULT=False,
                        BARS_BY_DEFAULT=False):
        hlp = frmts.format_help('/poll')
        assert '`--public`' in hlp
        assert '`--anonym`' not in hlp
        assert '`--progress`' in hlp
        assert '`--noprogress`' not in hlp
        assert '`--bars`' in hlp
        assert '`--nobars`' not in hlp
コード例 #2
0
def poll():
    """Creates a new poll.
    Directly called by Mattermost.
    Example response data:
    ```
    {
        "response_type": "in_channel",
        "attachments": [{
            "text": "<Poll message>",
            "actions": [
            {
                "name": "<First Option> (0)",
                "integration": {
                    "context": {
                        "poll_id": "<unique_id>",
                        "vote": 0
                    },
                    "url": "http://<hostname:port>/vote"
                }
            },
            ... additional entries for all poll options ...
            {
                "name": "End Poll",
                "integration": {
                    "url": "http://<hostname:port>/end",
                    "context": {
                        "poll_id": "<unique_id>"
                    }
                }
            }],
            "fields": [
            {
                "short": false,
                "title": "",
                "value": "Number of Votes: 1"
            }]
        }]
    }
    ```
    """
    if hasattr(settings, 'MATTERMOST_TOKEN'):
        warnings.warn("MATTERMOST_TOKEN is deprecated, use MATTERMOST_TOKENS \
                      instead",
                      category=DeprecationWarning)
        settings.MATTERMOST_TOKENS = [settings.MATTERMOST_TOKEN]
        settings.MATTERMOST_TOKEN = None

    if settings.MATTERMOST_TOKENS:
        token = request.form['token']
        if token not in settings.MATTERMOST_TOKENS:
            return jsonify({
                'response_type':
                'ephemeral',
                'text':
                tr("The integration is not correctly set up: "
                   "Invalid token.")
            })

    if 'user_id' not in request.form:
        abort(400)
    if 'text' not in request.form:
        abort(400)
    user_id = request.form['user_id']
    request.user_id = user_id

    app.logger.debug('Received command: %s', request.form['text'])

    # the poll should have a fixed locale, otherwise it
    # changes for everyone every time someone votes
    locale = flask_babel.get_locale().language

    if request.form['text'].strip() == 'help':
        return jsonify({
            'response_type': 'ephemeral',
            'text': format_help(request.form['command'], locale)
        })

    args = parse_slash_command(request.form['text'])
    if not args.message:
        text = tr("**Please provide a message.**\n\n"
                  "**Usage:**\n{help}").format(
                      help=format_help(request.form['command'], locale))
        return jsonify({'response_type': 'ephemeral', 'text': text})
    if args.public:
        if not settings.MATTERMOST_URL or not settings.MATTERMOST_PA_TOKEN:
            return jsonify({
                'response_type':
                'ephemeral',
                'text':
                tr("Public polls are not available with the "
                   "current setup. Please check with you "
                   "system administrator.")
            })

    if args.locale:
        locale = args.locale

    poll = Poll.create(user_id,
                       message=args.message,
                       locale=locale,
                       vote_options=args.vote_options,
                       secret=not args.progress,
                       public=args.public,
                       max_votes=args.max_votes,
                       bars=args.bars)

    app.logger.info('Creating Poll: %s', poll.id)

    return jsonify(format_poll(poll))
コード例 #3
0
def test_format_help(locale, start):
    help_text = frmts.format_help('/schwifty', locale)
    assert '/schwifty' in help_text
    assert '{command}' not in help_text
    assert help_text.startswith(start)
コード例 #4
0
ファイル: app.py プロジェクト: niccw/mattermost-poll-lunch
def poll():
    """Creates a new poll.
    Directly called by Mattermost.
    Example response data:
    ```
    {
        "response_type": "in_channel",
        "attachments": [{
            "text": "<Poll message>",
            "actions": [
            {
                "name": "<First Option> (0)",
                "integration": {
                    "context": {
                        "poll_id": "<unique_id>",
                        "vote": 0
                    },
                    "url": "http://<hostname:port>/vote"
                }
            },
            ... additional entries for all poll options ...
            {
                "name": "End Poll",
                "integration": {
                    "url": "http://<hostname:port>/end",
                    "context": {
                        "poll_id": "<unique_id>"
                    }
                }
            }],
            "fields": [
            {
                "short": false,
                "title": "",
                "value": "Number of Votes: 1"
            }]
        }]
    }
    ```
    """
    if hasattr(settings, 'MATTERMOST_TOKEN'):
        warnings.warn("MATTERMOST_TOKEN is deprecated, use MATTERMOST_TOKENS \
                      instead",
                      category=DeprecationWarning)
        settings.MATTERMOST_TOKENS = [settings.MATTERMOST_TOKEN]
        settings.MATTERMOST_TOKEN = None

    if settings.MATTERMOST_TOKENS:
        token = request.form['token']
        if token not in settings.MATTERMOST_TOKENS:
            return jsonify({
                'response_type':
                'ephemeral',
                'text':
                tr("The integration is not correctly set up: "
                   "Invalid token.")
            })

    if 'user_id' not in request.form:
        abort(400)
    if 'text' not in request.form:
        abort(400)
    user_id = request.form['user_id']
    request.user_id = user_id

    app.logger.debug('Received command: %s', request.form['text'])

    # the poll should have a fixed locale, otherwise it
    # changes for everyone every time someone votes
    locale = flask_babel.get_locale().language

    if request.form['text'].strip() == 'help':
        return jsonify({
            'response_type': 'ephemeral',
            'text': format_help(request.form['command'], locale)
        })

    args = parse_slash_command(request.form['text'])

    #debug
    #return jsonify({'response_type': 'ephemeral', 'text': str(args.progress)+str(args.lunch)+str(args.message)})

    # lunch
    # built new message and vote_options
    if args.lunch:
        lunch = Lunch()
        restaurants = lunch.read_restaurant()
        try:
            num_restaurant = int(args.message)
        except:
            num_restaurant = len(
                restaurants
            )  # if no number is provider as a message, just list all restautrant in the db
            #return jsonify({'ephemeral_text':tr("Please provide a number.")})
        restaurants_subset = random.sample(restaurants, num_restaurant)
        new_vote_options = restaurants_subset

        args_dict = args._asdict()
        args_dict['message'] = "Let's vote for lunch!"
        args_dict['vote_options'] = new_vote_options

        # copy from parse_slash_command
        Arguments = namedtuple('Arguments', [
            'message', 'vote_options', 'progress', 'public', 'max_votes',
            'bars', 'locale', 'lunch', 'lunchadd', 'lunchrm', 'lunchls'
        ])

        args = Arguments(**args_dict)

    if args.lunchadd:
        lunch = Lunch()
        flag = lunch.add_restaurant(author_id=user_id, restaurant=args.message)
        if flag:
            return jsonify({
                'response_type': 'ephemeral',
                'text': tr("Successfully added restaurant.")
            })
        else:
            return jsonify({
                'response_type': 'ephemeral',
                'text': tr("Error in adding restaurant.")
            })
    if args.lunchrm:
        lunch = Lunch()
        flag = lunch.rm_restaurant(args.message)
        if flag:
            return jsonify({
                'response_type': 'ephemeral',
                'text': tr("Successfully removed restaurant.")
            })
        else:
            return jsonify({
                'response_type': 'ephemeral',
                'text': tr("Error in removing restaurant.")
            })
    if args.lunchls:
        lunch = Lunch()
        restaurants = lunch.read_restaurant()
        restaurants_str = ",".join(restaurants)
        return jsonify({'response_type': 'ephemeral', 'text': restaurants_str})

    if not args.message:
        text = tr("**Please provide a message.**\n\n"
                  "**Usage:**\n{help}").format(
                      help=format_help(request.form['command'], locale))
        return jsonify({'response_type': 'ephemeral', 'text': text})
    if args.public:
        if not settings.MATTERMOST_URL or not settings.MATTERMOST_PA_TOKEN:
            return jsonify({
                'response_type':
                'ephemeral',
                'text':
                tr("Public polls are not available with the "
                   "current setup. Please check with you "
                   "system administrator.")
            })

    if args.locale:
        locale = args.locale

    poll = Poll.create(user_id,
                       message=args.message,
                       locale=locale,
                       vote_options=args.vote_options,
                       secret=not args.progress,
                       public=args.public,
                       max_votes=args.max_votes,
                       bars=args.bars)

    app.logger.info('Creating Poll: %s', poll.id)

    return jsonify(format_poll(poll))