我对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
编码良好)。