Взаимодействие пользователей с Python's Flask - PullRequest
0 голосов
/ 27 апреля 2018

У меня есть вопрос о Python: во Flask я знаю, как создавать кнопки с параметрами yes и no, но я не знаю, как пользователь может взаимодействовать с ними с помощью Slack, и как при нажатии Эти кнопки, в зависимости от ответа, на который нажал пользователь, могут отображать ответ или другой ответ на канале Slack. У меня есть этот код:

'''
    It creates an app using slack_bot.py
'''

import os
import json
from flask import Flask, current_app, request, make_response, Response, render_template
from slackclient import SlackClient, process
import slack_bot as sb

# Your app's Slack bot user token
SLACK_BOT_TOKEN = sb.get_token()
SLACK_VERIFICATION_TOKEN = os.environ.get("SLACK_VERIFICATION_TOKEN")

# Slack client for Web API requests
SLACK_CLIENT = SlackClient(SLACK_BOT_TOKEN)

# Flask webserver for incoming traffic from Slack
APP = Flask(__name__)


def verify_slack_token(request_token):
    '''Verify token to not get it stealed from others'''
    if SLACK_VERIFICATION_TOKEN != request_token:
        print("Error: invalid verification token!!!")
        print("Received {} but was expecting {}".format(request_token, SLACK_VERIFICATION_TOKEN))
    return make_response("Request contains invalid Slack verification token", 403)


OPTIONS = [
    {
        "text": "Sí",
        "value": "si"
    },
    {
        "text": "No",
        "value": "no"
    }
]


MESSAGE_ATTACHMENTS = [
    {
        "fallback": "Upgrade your Slack client to use messages like these.",
        "callback_id": "Confirm_button",
        "actions": [
            {
                "name": "Sí",
                "text": "Sí",
                "value": "si",
                "type": "button"
            },
            {
                "name": "No",
                "text": "No",
                "value": "no",
                "type": "button"
            }
        ]
    }
]


@APP.route("/slack/message_options", methods=["POST"])
def message_options():
    ''' Parse the request payload'''
    form_json = json.loads(request.form["payload"])
    verify_slack_token(form_json["token"])

    # Dictionary of menu options which will be sent as JSON
    menu_options = {
        "options": [
            {
                "text": "Sí",
                "value": "si"
            },
            {
                "text": "No",
                "value": "no"
            }
        ]
    }

    # Load options dict as JSON and respond to Slack
    return Response(json.dumps(menu_options), mimetype='application/json')


@APP.route("/slack/message_actions", methods=["POST"])
def message_actions():

    '''
        Sends the report question
    '''

    form_json = json.loads(request.form["payload"])
    verify_slack_token(form_json["token"])
    message_text = "Voleu enviar l\'informe??"

    selection = form_json["actions"][0]["selected_options"][0]["value"]
    if selection == "Sí":
        message_text = "Operació acceptada."
    else:
        message_text = "Operació cancel·lada."
    response = SLACK_CLIENT.api_call(
        "chat.update",
        channel=form_json["channel"]["id"],
        ts=form_json["message_ts"],
        text=message_text,
        response_type="in_channel",
        options=OPTIONS
    )

    return make_response(response, 200)


with APP.app_context():
    # within this block, current_app points to app.
    print(current_app.name)


SLACK_CLIENT.api_call(
    "chat.postMessage",
    channel="#lufranxucybots",
    text="Voleu enviar l\'informe??",
    attachments=MESSAGE_ATTACHMENTS,
    response_type="in_channel"
)


@APP.route('/')
@APP.route('/index', methods=['GET', 'POST'])
def index():
    '''Index'''
    if request.method == "GET":
        return render_template("index.html")

    if request.form["submit"] == "submit":
        yes = request.form["Sí"]
        no = request.form["No"]
        success = process(yes, no)

        return render_template("index.html", fooResponse="Successful" if success else "Failed")



if __name__ == '__main__':
    APP.run(debug=True)

, где slack_bot.py:

'''
    Log bot: to send by Slack the error logs which are usually
    sent by command prompt.
'''

from slackclient import SlackClient

import constants as c
import utilities as u

log = u.ulog.set_logger(__file__)


def get_token():
    """ Retrives slack token """

    try:
        with open(c.SLACK_TOKEN, "r") as file:
            return file.read()

    except IOError as e:
        log.error("Token not found", error=e)
        return None


def send_message(text, channel="#test"):
    """
        Send message to Slack

        Args:
            text:       what will be sent
            channel:    where it will be posted
    """

    token = get_token()
    slack_client = SlackClient(token)

    slack_client.api_call(
        "chat.postMessage",
        channel=channel,
        text=text
    )



if __name__ == '__main__':
    TEXT = input("Write your text: ")
    send_message(TEXT)

У меня есть этот шаблон, это правильно ??:

<html>
<body>
<form action="/" method="post">
    CHIPS:<br />
    <input type="text" name="Sí"><br />
    SNACKS:<br />
    <input type="text" name="No"><br />
    <input type="submit" value="submit">
</form>

{% if fooResponse is not none %}
    {{ fooResponse }}
{% endif %}

</body>
</html>

P.D .: Pylint не распознает process ни в одном модуле, из какого он модуля ??

Ну ... Главный вопрос, который я хочу задать обо всем этом: как, черт возьми, я делаю код, чтобы не просто отправлять неработающие кнопки yes и no, но и заставить их работать благодаря взаимодействию и пользователь, да еще печатать слабые сообщения, когда пользователь взаимодействует ?? Любая строка первого кода или шаблона плохо закодирована? (поверьте мне, slack_bot.py хорошо закодировано).

1 Ответ

0 голосов
/ 27 апреля 2018

Похоже, вам нужно отправить вопрос в slack в желаемом формате его API: https://api.slack.com/docs/message-buttons

...