You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

零基础求助:如何用Python适配Facebook Messenger API按钮模板代码

Convert Facebook Messenger Button Template from cURL/PHP to Python

Hey there! Since you’ve already got a basic Python chatbot up and running for Facebook Messenger, let’s walk through how to adapt that button template example into Python code that fits your existing setup. It’s simpler than it looks—we just need to translate the JSON structure from the official docs into a Python dictionary, then send it via an HTTP request.

First, make sure you have the requests library installed

If you haven’t already, install it with pip (it’s the standard tool for sending HTTP requests in Python):

pip install requests

Step-by-step conversion of the button template

Here’s a direct translation of the button template example into Python. I’ll break down each part so you understand how it maps to the cURL/PHP examples you saw:

import requests

# Replace these with your actual values
PAGE_ACCESS_TOKEN = "YOUR_FACEBOOK_PAGE_ACCESS_TOKEN"
TARGET_USER_ID = "THE_ID_OF_THE_USER_YOU_WANT_TO_MESSAGE"

# This is the button template structure, exactly matching the JSON from Facebook's docs
button_message = {
    "recipient": {"id": TARGET_USER_ID},
    "message": {
        "attachment": {
            "type": "template",
            "payload": {
                "template_type": "button",
                "text": "What do you want to do next?",
                "buttons": [
                    {
                        "type": "web_url",
                        "url": "https://example.com",
                        "title": "Visit Website"
                    },
                    {
                        "type": "postback",
                        "title": "Start Chatting",
                        "payload": "USER_REQUEST_CHAT"
                    }
                ]
            }
        }
    }
}

# Send the template to Facebook's API
response = requests.post(
    f"https://graph.facebook.com/v18.0/me/messages?access_token={PAGE_ACCESS_TOKEN}",
    json=button_message,
    headers={"Content-Type": "application/json"}
)

# Check if the message sent successfully
if response.status_code == 200:
    print("Button template sent without issues!")
else:
    # Print the error details if something went wrong
    print(f"Oops, something failed: {response.json()}")

Key things to note:

  • PAGE_ACCESS_TOKEN: You get this from your Facebook Developer Dashboard (it’s tied to your Messenger app and page).
  • TARGET_USER_ID: This is the sender.id value you receive in the webhook payload when a user sends your bot a message.
  • API Version: I used v18.0 here—make sure it matches the version you’re using in your existing code (Facebook updates their API versions regularly).
  • Button Types: The example includes a web_url button (links to a website) and a postback button (sends a payload back to your webhook when clicked). You can add more buttons or change their types based on your needs.

Integrate this with your existing chatbot

If your bot uses a framework like Flask to handle webhooks, you can wrap the template-sending code into a function and call it when a specific trigger happens. For example:

from flask import Flask, request, jsonify
import requests

app = Flask(__name__)
PAGE_ACCESS_TOKEN = "YOUR_FACEBOOK_PAGE_ACCESS_TOKEN"

def send_button_template(user_id):
    button_message = {
        "recipient": {"id": user_id},
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "button",
                    "text": "What do you want to do next?",
                    "buttons": [
                        {"type": "web_url", "url": "https://example.com", "title": "Visit Website"},
                        {"type": "postback", "title": "Start Chatting", "payload": "USER_REQUEST_CHAT"}
                    ]
                }
            }
        }
    }
    response = requests.post(
        f"https://graph.facebook.com/v18.0/me/messages?access_token={PAGE_ACCESS_TOKEN}",
        json=button_message,
        headers={"Content-Type": "application/json"}
    )
    if response.status_code != 200:
        print(f"Error sending template: {response.json()}")

@app.route("/webhook", methods=["POST"])
def handle_webhook():
    data = request.get_json()
    # Extract the user's ID and message from the webhook payload
    sender_id = data["entry"][0]["messaging"][0]["sender"]["id"]
    user_message = data["entry"][0]["messaging"][0]["message"]["text"]
    
    # Trigger the button template when the user types "options"
    if user_message.lower() == "options":
        send_button_template(sender_id)
    
    return jsonify({"status": "ok"})

if __name__ == "__main__":
    app.run(port=5000, debug=True)

In this example, when a user sends the message "options", the bot will respond with the button template. You can adjust the trigger condition to fit your bot’s logic.

内容的提问来源于stack exchange,提问作者Khaled Awad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:40:39