Skip to Content

How do I send a message using Facebook API?

How do I send a message using Facebook API?

The Facebook API allows developers to integrate Facebook functionality into their own applications. One of the most common uses of the Facebook API is to send messages programmatically. There are a few different ways to send messages via the Facebook API, depending on your specific needs. In this comprehensive guide, we’ll walk through the various options for sending messages with the Facebook API and provide code samples to help you get started.

Prerequisites

Before you can start sending messages with the Facebook API, you’ll need a few things:

  • A Facebook app set up on the Facebook for Developers site. This will provide you with an app ID and app secret needed to authenticate.
  • The Facebook SDK for your platform installed in your project.
  • The required permissions from the user to send messages on their behalf. At minimum, you’ll need the email and manage_pages permissions.

With those basics covered, you’re ready start working with the Facebook API to send messages.

Sending Messages to Individuals

The most straightforward way to send a message is by sending it directly to an individual Facebook user. Here are the steps to follow:

  1. Get the user’s Facebook ID (this will be a numeric ID). You can get this once the user has logged into your app.
  2. Make a POST request to /user-id/messages endpoint.
  3. In the request body, include the following parameters:
    • message – The message text
    • access_token – The user access token

Here is an example request in Python:

import facebook

user_id = 12345
message_text = "Hello this is a test message from the API" 

facebook_access_token = "EAA..." # User access token 

url = f"{user_id}/messages"
params = {
  "message": message_text,
  "access_token": facebook_access_token  
}

response = facebook.post(url, params)

This will send the message directly to the user’s Facebook inbox from your app.

Sending Messages as a Page

In many cases, you’ll want to send messages not just as the app user, but on behalf of a Facebook Page. This is useful for things like Facebook chatbots, support bots, notifications from a Page, etc.

Here is how to send a message as a Page:

  1. Get the Page access token for the page you want to send the message from. This token will need to be generated with the manage_pages and publish_pages permissions.
  2. Get the PSID of the user you want to message. The PSID is the Page-scoped ID that identifies a user’s thread with a specific Page.
  3. Make a POST request to /me/messages endpoint with Page access token.
  4. In the request body, include the following parameters:
    • recipient – The PSID
    • message – The message text
    • access_token – The Page access token

Here is an example in Python:

page_access_token = "EAA..." # Page Access Token 

psid = 54321 # PSID for user 

url = "me/messages"
params = {
  "recipient": {"id": psid},
  "message": {"text": "Test message"},
  "access_token": page_access_token
}

response = facebook.post(url, params) 

This allows you to send the message as the Page, instead of just the individual user.

Sending Message Templates

For more structured messages, the Facebook API supports sending templates. Some common templates include:

  • Button template – Message with call-to-action buttons
  • Generic template – Carousel of items with image/text
  • Receipt template – For order receipts
  • Airline templates – Boarding passes, itineraries, etc.

To send a template, you follow a similar process as sending a regular message. The difference is that you’ll pass a template_type and template_payload in the request body instead of just message.

Here’s an example button template:

template_type = "button"
template_payload = {
  "text": "This is a button template",
  "buttons":[
    {
      "type":"web_url",
      "url":"https://www.example.com",
      "title":"View Website"
    },
    {
       "type":"postback",
       "title":"Start Chatting",
       "payload":"DEVELOPER_DEFINED_PAYLOAD"
    }      
  ]    
}

params = {
  "recipient": {"id": psid},
  "message": {
    "attachment": {
      "type": template_type, 
      "payload": template_payload
    }
  },
  "access_token": page_access_token  
} 

facebook.post(url, params)

You can find documentation on the structure of the available templates in Facebook’s developer docs.

Sending Message Attachments

In addition to text, you can include file attachments in messages via the API. The supported attachment types include:

  • Images
  • Video
  • Audio
  • File

To send an attachment, you simply include an attachments field in your request body instead of message.

Here is an example sending an image attachment:

attachment_url = "http://www.example.com/image.jpg" 

params = {
  "recipient": {"id": psid},
  "message": {
    "attachment": {
      "type":"image", 
      "payload": {
        "url": attachment_url,
        "is_reusable": True
      }  
    }
  },
  "access_token": page_access_token
}

facebook.post(url, params)

You can find details on formatting attachments for each file type in Facebook’s documentation.

Tagging Users in Messages

When sending messages as a Page, you can tag specific users using the tagging field. This allows you to notify users or bring their attention to a message.

To tag someone, you need their PSID. Then format the request like this:

tagged_psid = 67890 

params = {
  "recipient": {"id": psid},
  "message": {
    "text": "Hey @John check this out!", 
    "tagging": {
      "tags": [{"id": tagged_psid}]
    }
  },
  "access_token": page_access_token 
}

facebook.post(url, params)

You can include multiple tags in the tags array to tag multiple users.

Sending Messages with Quick Replies

To make your conversations more interactive, you can attach quick reply buttons to your messages. This allows the user to respond instantly with a tap.

Quick replies are formatted as part of the message payload like this:

quick_replies = [
  {
    "content_type":"text",
    "title":"Red",
    "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED",
  },
  {
    "content_type":"text",
    "title":"Blue",
    "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_BLUE",
  }
]

params = {
  "recipient": {"id": psid},
  "message": {
    "text": "Pick a color:",
    "quick_replies": quick_replies
  }
} 

When the user taps a quick reply, you’ll receive the payload back in the webhook event.

Sending Messages with Metadata

You can attach additional metadata to messages by including it in the messaging_type field.

For example:

metadata = "DEVELOPER_DEFINED_METADATA"

params = {
  "recipient": {"id": psid},
  "message": {
    "text": "This message has metadata",
    "messaging_type": "UPDATE",
    "metadata": metadata
  }
}

The metadata must be a string. This can be useful for tracking, analytics, and more.

Sending Messages to Queue

By default, messages are sent immediately when making the API request. However, you can also queue up messages to be sent later by passing messaging_type of RESPONSE.

params = {
  "recipient": {"id": psid},
  "message": {
    "text": "This message will be queued",
    "messaging_type": "RESPONSE" 
  }
} 

The message will then be sent to the user the next time they interact with your app.

Sending Messages with Personas

Pages that have been granted the pages_messaging_phone_number and pages_messaging_subscriptions permissions can assume different “personas” when messaging users.

To send a message with a persona, include the persona_id in your request:

persona_id = "100120000900059" # Numerical persona ID

params = {
  "recipient": {"id": psid},
  "persona_id": persona_id,
  "message": {
    "text": "This message will be sent with the persona"
  }
} 

Personas allow you tailor messaging tone and style for different types of conversations.

Broadcasting Messages

In addition to sending messages to individual PSIDs, you can also broadcast messages in bulk to multiple users. This can be useful for things like promotional announcements.

To broadcast, you make a single API call with the list of PSIDs included in the recipient field:

recipients = [12345, 67890, 13579] # List of PSIDs 

params = {
  "recipient": {"id_list": recipients},
  "message": {
    "text": "This is a broadcast message"
  },
  "access_token": page_access_token
}

facebook.post(url, params)

The same message will be sent to all the specified recipients.

Scheduling Message Broadcasts

You can also schedule message broadcasts for a later date/time. This is done using the scheudled_time parameter:

import time
scheduled_time = int(time.time()) + 60 * 60 * 24 # 24 hours from now

params = {
  "recipient": {"id_list": recipients},
  "message": {
    "text": "This message will broadcast tomorrow" 
  },
  "access_token": page_access_token,
  "scheduled_time": scheduled_time
}

facebook.post(url, params)

The message will be queued up and delivered at the specified time to all recipients.

Sending Message Notification

When sending broadcast messages, it’s considered best practice to also send a notification to your Page informing users that a broadcast was sent.

This helps avoid spam detection algorithms. To send the notification, make an additional API call:

num_recipients = len(recipients)

notification_params = {
  "recipient": {"id": page_id},
  "message": {
    "text": f"You sent a message to {num_recipients} people." 
  },
  "access_token": page_access_token
}

facebook.post(url, notification_params)  

This will send a message to your Page with details on the broadcast.

Handling Message Delivery Failures

When broadcasting messages, some messages may fail to deliver if the user has messaging disabled or has blocked your app.

In your broadcast API response, Facebook will include a message_delivery_statuses field with delivery details for each recipient.

You should check this field to handle failures appropriately in your app. For example:

response = facebook.post(url, broadcast_params)

delivery_statuses = response["message_delivery_statuses"]

for status in delivery_statuses:
  if status["error"]:
    # handle error case
    print(f"Error sending to {status['psid']}: {status['error']}")

This allows you to properly monitor for and respond to any message delivery issues.

Testing Messages

While developing your messaging functionality, you’ll likely want to test it out. However, you obviously can’t send test messages to real users.

For testing purposes, Facebook allows you to send messages to your own PSID. To get your app-scoped PSID, call:

params = {
  "access_token": access_token  
}

response = facebook.get("/me", params=params) 

app_scoped_psid = response["id"] 

You can then use this PSID to send test messages to yourself:

test_params = {
  "recipient": {"id": app_scoped_psid},
  "message": {
    "text": "This is a test message"
  } 
}

facebook.post(url, test_params)

This is extremely useful for testing and iterating quickly during development.

Troubleshooting

Here are some common issues and how to resolve them when sending messages via the API:

Permission Errors

Double check you have granted the necessary permissions, in particular pages_messaging and any related read permissions.

Invalid PSIDs

Verify you are using a valid PSID for the user/page. Make sure it is numeric.

Incorrect Access Tokens

Check the access token being used has the appropriate scopes, and that it belongs to a developer/page with permission to message users.

Spam Detection

If you are sending a lot of messages, Facebook may throttle your app if it gets flagged as spam. Follow Facebook’s guidelines to avoid issues.

Webhooks Not Getting Calls

Make sure you have properly set up your webhook subscription and are verifying the signature.

Conclusion

The Facebook APIs provide a powerful platform for building messaging functionality into your app or service. Whether you want to send one-off messages, build a chatbot, or broadcast promotions, the messaging API has you covered. Just remember to follow Facebook’s guidelines and best practices to deliver timely, relevant, and non-spammy messages to your users. With the code samples and tips in this guide, you should have everything you need to start integrating Facebook messaging into your platform.