使用Python Flask和Slack API处理交互消息中的按钮点击事件。

huangapple go评论101阅读模式
英文:

Handle button click events in Interactive messages using Slack API with Python Flask

问题

我正在尝试构建一个Slack应用程序,在发送带有命令的消息时,会显示一个带有两个按钮"确认"和"取消"的临时消息。如果用户点击"确认",则应发送该消息;如果点击"取消",则应删除该消息。

我已经编写了处理事件的端点,并将其添加到了"Interactivity"中。我在端点中接收到了有效载荷,但是我在这里遇到了两个问题:

  1. 由于这是一条临时消息,有效载荷中没有原始消息,我不知道在点击"确认"按钮时如何发送原始消息。我想要发送原始消息,而不是"confirm worked"。以下是示例代码:
payload = request.form["payload"]
payload = json.loads(payload)
if payload['type'] == 'interactive_message':
  action = payload['actions'][0]['name']

  if action == 'confirm':
    client.chat_postMessage(channel="#channelname", text="原始消息")
  1. 在事件处理程序中,当我使用chat_postMessage方法发送消息时,出现错误"哦,糟糕,出了些问题。请再试一次。"我了解到,我应该使用OAuth2.0获取访问令牌,以便通过调用oauth.access来发送此消息。我编写了这个端点,但是我不确定如何使用它。我应该在上面的client.chat_postMessage之前调用它吗?如果是的话,作为请求的一部分,我应该发送什么代码?
@app.route('/slack/authorize/', methods=['POST'])
def get_auth_token():
    payload = request.form["payload"]
    payload = json.loads(payload)
    code = payload["code"]
    result = client.oauth_v2_access(CLIENT_ID, SIGNING_SECRET, code, "URL/slack/authorize/")
    return jsonify(result), 200

我还在文档中阅读到,我需要在3秒内发送一个确认响应。你能帮我把所有这些部分连接起来吗?非常感谢。

英文:

I am trying to build a Slack app where when a message is sent with a command, an ephemeral message with two buttons Confirm and Cancel is shown. If the user clicks on Confirm, the message should be sent and if they click on Cancel, it should be deleted.

I have written endpoint to handle the events and I have added it under Interactivity. I receive the payload in my endpoint but I have two issues here:

  1. Since this is an ephemeral message, the payload does not have the original message and do not know how to send it when the Confirm button is clicked. In place of "confirm worked", I want to send the original message.
 payload = request.form["payload"]
 payload = json.loads(payload)
 if payload['type'] == 'interactive_message':
   action = payload['actions'][0]['name']

   if action == 'confirm':
      client.chat_postMessage(channel="#channelname", text="confirm worked")
  1. In the event handler, when I send the message using the method chat_postMessage I see the error "Oh no, something went wrong. Please try that again." I understand I should get the access token using OAuth2.0 for sending this message by calling the oauth.access. I wrote this endpoint but I am confused on how to use it? Should I call this before the client.chat_postMessage above? If yes, what is the code I should send as a part of the request?
@app.route('/slack/authorize/', methods=['POST'])
def get_auth_token():
    payload = request.form["payload"]
    payload = json.loads(payload)
    code = payload["code"]
    result = client.oauth_v2_access(CLIENT_ID, SIGNING_SECRET, code, "URL/slack/authorize/")
    return jsonify(result), 200

I have also read in the documentation that I need to send an acknowledgement response within 3 seconds. Could you please help me connect all these pieces? Thank you in advance.

答案1

得分: 1

访问原始消息:对于每条交互式消息,您必须包含一个独特的标识符(例如时间戳或消息ID),以便在处理按钮点击时能够访问原始消息。当您发送交互式消息时,此标识符需要包含在有效载荷中。稍后,当用户按下按钮时,Slack将在有效载荷中添加此标识符。如果需要,您可以使用此标识来获取原始消息。

发送消息:您需要一个访问令牌才能从您的Slack应用程序发送消息。获取此令牌的正确方法是OAuth2.0。您可能不需要使用oauth.access函数来发送消息,因为您提供的代码中的client.chat_postMessage方法似乎已经在执行此操作。在client实例中,请确认您使用的令牌具有发布消息所需的范围。

确认响应:在从Slack接收到交互事件后的3秒内,您必须发送一个确认响应。此响应需要一个200状态代码和一个空的响应体。这是向Slack确认您已收到事件并正在处理它的方式。这在用户面向的操作(如按钮点击)可能触发的情况下尤为重要。

from flask import Flask, request, jsonify
from slack_sdk import WebClient
import json

app = Flask(__name__)

# 使用您的机器人令牌初始化Slack客户端
client = WebClient(token="your_token")

@app.route('/slack/events', methods=['POST'])
def get_auth_token():
    payload = json.loads(request.form.get('payload'))
    if payload['type'] == 'interactive_message':
        action = payload['actions'][0]['name']
        response_url = payload['response_url']  # 使用此URL发送附加消息
        
        if action == 'confirm':
            original_message = payload['original_message']['text']
            # 使用response_url发送原始消息
            client.chat_postMessage(channel=payload['channel']['id'], text=original_message)
        elif action == 'cancel':
            # 使用response_url删除原始消息
            delete_response = {"text": "Message deleted.", "replace_original": True}
            client.chat_postMessage(channel=payload['channel']['id'], text=delete_response)
    
    # 发送确认响应
    return '', 200

if __name__ == '__main__':
    app.run()

请确保您在代码中检查按钮的action_id值与您正在检查的值匹配。

英文:

Accessing the Original Message: For each interactive message, you must include a distinctive identifier (such as a timestamp or message ID) in order to be able to access the original message when processing a button click. When you send the interactive message, this identifier needs to be included in the payload. Later, Slack will add this identifier in the payload when the user presses the buttons. If necessary, you may then use this identification to get the original message back.

Sending Messages: You require an access token in order to send messages from your Slack application. The proper method for obtaining this token is OAuth2.0. You might not need to utilize the oauth.access function for delivering messages as the client.chat_postMessage method in the code you provided appears to be doing it currently. In the client instance, confirm that the token you're using has the required scopes for posting messages.

Acknowledgment Response: You must send an acknowledgment response in 3 seconds after receiving an interactive event from Slack. A 200 status code and an empty body are required for this response. This is a confirmation to Slack that you have received the event and are handling it. This is especially crucial for situations where user-facing actions, like button clicks, may be triggered.

from flask import Flask, request, jsonify
from slack_sdk import WebClient
import json

app = Flask(__name__)

# Initialize Slack client with your bot token
client = WebClient(token="your_token")

@app.route('/slack/events', methods=['POST'])
def get_auth_token():
    payload = json.loads(request.form.get('payload'))
    if payload['type'] == 'interactive_message':
        action = payload['actions'][0]['name']
        response_url = payload['response_url']  # Use this URL to send additional messages
        
        if action == 'confirm':
            original_message = payload['original_message']['text']
            # Send the original message using response_url
            client.chat_postMessage(channel=payload['channel']['id'], text=original_message)
        elif action == 'cancel':
            # Delete the original message using response_url
            delete_response = {"text": "Message deleted.", "replace_original": True}
            client.chat_postMessage(channel=payload['channel']['id'], text=delete_response)
    
    # Send acknowledgment response
    return '', 200

if __name__ == '__main__':
    app.run()

Ensure that your action_id values for the buttons match the ones you're checking in your code.

huangapple
  • 本文由 发表于 2023年8月9日 01:05:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定