messages
Send and receive direct messages on Facebook, Instagram, and X/Twitter
The Messaging Add-On is required to access the messages endpoints. Only available for Business Plans.
The Messaging Add-On allow you to manage direct messages (DM) to correspondents who contact your User Profiles. A correspondent is the person with whom your user (User Profile) is communicating with. A conversation is a series of messages between your user (User Profile) and their correspondent.
Messaging is available for Facebook Messenger, Instagram Direct Messenger, and X Direct Messages. Learn more about using the DM API.
Key Messaging Features
Sending text, image, video, and emoji messages.
Retrieving complete conversation histories.
Setting up automated message responses.
Receiving real-time updates via webhooks for messages received, message reactions, read receipts.
Enable Messaging for Your Account and User Profiles
You must first enable messaging for your overall Ayrshare account to manage DMs. In the Ayrshare dashboard go to the Account page and click to "Learn More" button and then "Enable". At this point you have enabled messaging for your overall account, but have not activate messaging for individual User Profiles.
You can activate messaging for individual User Profiles either in the User Profiles page by clicking "Messaging Active" for each profile or via the profiles endpoint (create or update).
Important Information on Messaging
A conversation must be initiated by the correspondent. Once a conversation is established, you may then freely send messages, receive messages, get reactions (e.g. thumbs ups), or get read receipts on behalf of your users.
Your user must respond to an Instagram conversation within 7 days of the last message the correspondent sent. If the correspondent has not sent a message in 7 days the conversation is considered inactive and cannot be responded to.
Monthly Conversation Limit
Each Ayrshare User Profile can have up to 100 active conversations each month. A conversation is considered active for the month if a user or the correspondent has sent as a message. If 100 monthly conversations has been reached you can still receive messages, but will not be able to respond until the start of the month. If you need to increase the monthly conversation limit, please contact your Ayrshare account representative.
You may see the current converation count with the user endpoint.
Message WebHooks
See Messages Webhooks to automatically receive messages, read receipts, or reactions.
POST Message
POST
https://app.ayrshare.com/api/messages/:platform
Send a new direct message to a recipient.
Send an emoji as part of the
message
text.Facebook and Instagram
mediaUrls
must end in a know extension. Having query parameters will cause the media url to fail.
Headers
Path Parameters
Body
Response
{ // single text message
"status": "success",
"recipientId": "72706337063589124",
"messageId": "aWdfZAG1faXRlbToxOkl",
"message": "What is up?"
}
{ // single text message
"action": "messages",
"status": "error",
"code": 363,
"message": "The recipient ID was not found. Please confirm the recipient ID is correct."
}
{ // single image
"status": "success",
"recipientId": "761943",
"messageId": "m_EgvfBrgjaM",
"type": "image",
"mediaUrl": "https://img.ayrshare.com/012/gb.jpg"
}
{ // text and image message
"action": "send",
"status": "error",
"code": 337,
"message": "Error sending message.",
"messages": [
{
"recipientId": "727063370635",
"messageId": "aWdfZAG1faXRlbT",
"message": "What a great day"
},
{
"action": "messages",
"status": "error",
"code": 365,
"message": "An error occurred sending the message attachment. Please verify the attachment is still available and try again."
}
]
}
Request Examples
curl \
-H "Authorization: Bearer API_KEY" \
-H 'Content-Type: application/json' \
-d '{"message": "What's up!", "recipientId": "283j839222"' \
-X POST https://app.ayrshare.com/api/messages/instagram
const apiKey = 'API_KEY';
const url = 'https://app.ayrshare.com/api/messages/instagram';
const data = {
message: "What's up!",
recipientId: '283j839222',
};
const headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
};
fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Response:', data);
})
.catch(error => {
console.error('Error:', error);
});
import requests
api_key = 'API_KEY'
url = 'https://app.ayrshare.com/api/messages/instagram'
data = {
'message': "What's up!",
'recipientId': '283j839222',
}
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json',
}
response = requests.post(url, json=data, headers=headers)
print('Response:', response.json())
<?php
$apiKey = 'API_KEY';
$url = 'https://app.ayrshare.com/api/messages/instagram';
$data = [
'message' => "What's up!",
'recipientId' => '283j839222',
];
$headers = [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
echo 'Error: ' . $error;
} else {
$responseData = json_decode($response, true);
print_r($responseData);
}
curl_close($ch);
?>
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string apiKey = "API_KEY";
string url = "https://app.ayrshare.com/api/messages/instagram";
var data = new
{
message = "What's up!",
recipientId = "283j839222"
};
var jsonData = JsonSerializer.Serialize(data);
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
try
{
var response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
var responseData = JsonSerializer.Deserialize<dynamic>(responseBody);
Console.WriteLine("Response:");
Console.WriteLine(responseData);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) {
String apiKey = "API_KEY";
String url = "https://app.ayrshare.com/api/messages/instagram";
String data = "{\"message\": \"What's up!\", \"recipientId\": \"283j839222\"}";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(data))
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
String responseBody = response.body();
System.out.println("Response:");
System.out.println(responseBody);
} else {
System.out.println("Request failed. Status code: " + response.statusCode());
}
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
GET Messages
GET
https://app.ayrshare.com/api/messages/:platform
Get messages or conversations for a messaging platform.
Retrieval times differ on each social network. On Facebook and Instagram, messages are available via Ayrshare in real time. On X/Twitter, there is a delay of up to 3 minutes to see the messages. Please contact us to learn more about Enterprise Plans if you need real-time X/Twitter message access.
Headers
Path Parameters
Query
Response
{
"status": "success",
"messages": [
{
"senderId": "106638148652444",
"senderDetails": {
"name": "Ayrshare"
},
"conversationId": "t_10161117434308444",
"created": "2024-06-06T00:54:32.455Z",
"action": "sent",
"recipientId": "7101149746568444",
"id": "m_JH6o-yS83JoxWmQaLrmgSaHwGtfTgQ",
"message": "Howdy!",
"platform": "facebook",
"reactions": {
"7101149746568522": "😆". // Reaction by the customer on the Howdy! message
}
},
{
"senderId": "7101149746568444",
"senderDetails": {
"name": "John Smith",
"profileImage": "https://platform-lookaside.fbsbx.com/platform/profilepic/"
},
"conversationId": "t_10161117434308444",
"created": "2024-06-06T00:54:28.102Z",
"action": "received",
"recipientId": "106638148652329",
"id": "m_HGbotYJUmf4AzyPlJ-2uZqHwGtfTgQihX",
"message": "Look up!",
"platform": "facebook"
},
{
"senderId": "7101149746568444",
"senderDetails": {
"name": "John Smith",
"profileImage": "https://platform-lookaside.fbsbx.com/platform/profilepic/"
},
"conversationId": "t_10161117434308444",
"created": "2024-06-06T00:49:11.679Z",
"action": "received",
"recipientId": "106638148652444",
"id": "m_jXoYQIwTXaq2u06PG6Z8vaHwGtfTgQ",
"message": "How is the weather?",
"platform": "facebook"
}
],
"lastUpdated": "2024-06-09T21:46:04.233Z",
"nextUpdate": "2024-06-09T21:47:04.233Z"
}
{
"status": "success",
"conversationIds": [
"t_10161117434308444",
"t_356759043857444"
],
"converstationsDetails": [
{
"id": "t_10161117434308444",
"participant": {
"name": "John Smith",
"id": "7101149746568444",
"picture": "https://platform-lookaside.fbsbx.com/platform/profilepic/"
},
"status": "active",
"watermark": 1717889607444
},
{
"id": "t_356759043857444",
"participant": {
"name": "Sara Johnson",
"id": "7365320280173444",
"picture": "https://platform-lookaside.fbsbx.com/platform/profilepic/"
},
"status": "active"
}
],
"lastUpdated": "2024-06-09T21:46:04.233Z",
"nextUpdate": "2024-06-09T21:47:04.233Z"
}
{
"action": "messages",
"status": "error",
"code": 361,
"message": "Messaging is not enabled for this User Profile. Please subscribe to Messaging and activate Messaging for this User Profile."
}
Request Examples
curl \
-H "Authorization: Bearer API_KEY" \
-X GET https://app.ayrshare.com/api/messages/facebook
const apiKey = 'API_KEY';
const url = 'https://app.ayrshare.com/api/messages/facebook';
const headers = {
'Authorization': `Bearer ${apiKey}`,
};
fetch(url, {
method: 'GET',
headers: headers,
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error(`Request failed. Status code: ${response.status}`);
}
})
.then(data => {
console.log('Response:', data);
})
.catch(error => {
console.error('Error:', error.message);
});
import requests
api_key = 'API_KEY'
url = 'https://app.ayrshare.com/api/messages/facebook'
headers = {
'Authorization': f'Bearer {api_key}',
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
print('Response:', data)
else:
print(f'Request failed. Status code: {response.status_code}')
<?php
$apiKey = 'API_KEY';
$url = 'https://app.ayrshare.com/api/messages/facebook';
$headers = [
'Authorization: Bearer ' . $apiKey,
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
echo 'Error: ' . $error;
} else {
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($statusCode === 200) {
$responseData = json_decode($response, true);
print_r($responseData);
} else {
echo 'Request failed. Status code: ' . $statusCode;
}
}
curl_close($ch);
?>
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Text.Json;
class Program
{
static async Task Main()
{
string apiKey = "API_KEY";
string url = "https://app.ayrshare.com/api/messages/facebook";
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
try
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
var responseData = JsonSerializer.Deserialize<dynamic>(responseBody);
Console.WriteLine("Response:");
Console.WriteLine(responseData);
}
else
{
Console.WriteLine($"Request failed. Status code: {response.StatusCode}");
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) {
String apiKey = "API_KEY";
String url = "https://app.ayrshare.com/api/messages/facebook";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + apiKey)
.GET()
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
String responseBody = response.body();
System.out.println("Response:");
System.out.println(responseBody);
} else {
System.out.println("Request failed. Status code: " + response.statusCode());
}
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
PUT Update Messages
PUT
https://app.ayrshare.com/api/messages/:platform/:conversationId
Update the status of a conversation to active or archived. You may want to archive conversations if they are no longer active or relevant.
Headers
Path Parameters
Body
Response
{
"status": "success"
}
{
"action": "request",
"status": "error",
"code": 101,
"message": "Missing or incorrect parameters. Please verify with the docs. https://docs.ayrshare.com/rest-api/endpoints"
}
Request Examples
curl \
-H "Authorization: Bearer API_KEY" \
-H 'Content-Type: application/json' \
-d '{"status": "archived"' \
-X PUT https://app.ayrshare.com/api/messages/instagram/aWdfZMTpIyzQw
const url = 'https://app.ayrshare.com/api/messages/instagram/aWdfZMTpIyzQw';
const options = {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer API_KEY'
},
body: JSON.stringify({
'status': 'archived'
})
};
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
import json
import requests
url = 'https://app.ayrshare.com/api/messages/instagram/aWdfZMTpIyzQw'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer API_KEY'
}
data = {
'status': 'archived'
}
response = requests.put(url, headers=headers, data=json.dumps(data))
try:
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print('Error:', e)
<?php
$url = 'https://app.ayrshare.com/api/messages/instagram/aWdfZMTpIyzQw';
$headers = [
'Content-Type: application/json',
'Authorization: Bearer API_KEY'
];
$data = [
'status' => 'archived'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >=
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string url = "https://app.ayrshare.com/api/messages/instagram/aWdfZMTpIyzQw";
var headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"Authorization", "Bearer API_KEY"}
};
var data = new Dictionary<string, string>
{
{"status", "archived"}
};
using (var client = new HttpClient())
{
var jsonData = JsonSerializer.Serialize(data);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
var response = await client.PutAsync(url, content);
try
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var responseData = JsonSerializer.Deserialize<Dictionary<string, object>>(responseBody);
Console.WriteLine(JsonSerializer.Serialize(responseData, new JsonSerializerOptions { WriteIndented = true }));
}
catch (HttpRequestException e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String url = "https://app.ayrshare.com/api/messages/instagram/aWdfZMTpIyzQw";
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer API_KEY");
Map<String, String> data = new HashMap<>();
data.put("status", "archived");
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.headers(headers.entrySet().stream()
.map(entry -> entry.getKey() + ": " + entry.getValue())
.toArray(String[]::new))
.PUT(HttpRequest.BodyPublishers.ofString(getJsonString(data)))
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) {
System.out.println("Error: HTTP " + response.statusCode());
} else {
System.out.println(response.body());
}
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
private static String getJsonString(Map<String, String> data) {
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{");
for (Map.Entry<String, String> entry : data.entrySet()) {
jsonBuilder.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\",");
}
if (jsonBuilder.length() > 1) {
jsonBuilder.setLength(jsonBuilder.length() - 1);
}
jsonBuilder.append("}");
return jsonBuilder.toString();
}
}
POST Set Auto Response
POST
https://app.ayrshare.com/api/messages/autoresponse
Automatically send message auto responses to the correspondent. This is useful if your customer service support desk is not currently available.
If active, the auto response is used for all social networks for a given User Profile.
Headers
Body
Response
{
"status": "success",
"updated": {
"autoResponseActive": true,
"autoResponseMessage": "Howdy!",
"autoResponseWaitSeconds": 30
}
}
{
"action": "request",
"status": "error",
"code": 101,
"message": "Missing or incorrect parameters. Please verify with the docs. https://docs.ayrshare.com/rest-api/endpoints"
}
Request Examples
curl \
-H "Authorization: Bearer API_KEY" \
-H 'Content-Type: application/json' \
-d '{"autoResponseActive": true, "autoResponseWaitSeconds": 30, "autoResponseMessage": "Howdy!"' \
-X POST https://app.ayrshare.com/api/messages/autoresponse
const fetch = require('node-fetch');
const url = 'https://app.ayrshare.com/api/messages/autoresponse';
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer API_KEY'
},
body: JSON.stringify({
'autoResponseActive': true,
'autoResponseWaitSeconds': 30,
'autoResponseMessage': 'Howdy!'
})
};
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
import json
import requests
url = 'https://app.ayrshare.com/api/messages/autoresponse'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer API_KEY'
}
data = {
'autoResponseActive': True,
'autoResponseWaitSeconds': 30,
'autoResponseMessage': 'Howdy!'
}
response = requests.post(url, headers=headers, data=json.dumps(data))
try:
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print('Error:', e)
<?php
$url = 'https://app.ayrshare.com/api/messages/autoresponse';
$headers = [
'Content-Type: application/json',
'Authorization: Bearer API_KEY'
];
$data = [
'autoResponseActive' => true,
'autoResponseWaitSeconds' => 30,
'autoResponseMessage' => 'Howdy!'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 400) {
echo 'Error: HTTP ' . $httpCode;
} else {
$data = json_decode($response, true);
print_r($data);
}
}
curl_close($ch);
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string url = "https://app.ayrshare.com/api/messages/autoresponse";
var headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"Authorization", "Bearer API_KEY"}
};
var data = new Dictionary<string, object>
{
{"autoResponseActive", true},
{"autoResponseWaitSeconds", 30},
{"autoResponseMessage", "Howdy!"}
};
using (var client = new HttpClient())
{
var jsonData = JsonSerializer.Serialize(data);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
var response = await client.PostAsync(url, content);
try
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var responseData = JsonSerializer.Deserialize<Dictionary<string, object>>(responseBody);
Console.WriteLine(JsonSerializer.Serialize(responseData, new JsonSerializerOptions { WriteIndented = true }));
}
catch (HttpRequestException e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String url = "https://app.ayrshare.com/api/messages/autoresponse";
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer API_KEY");
Map<String, Object> data = new HashMap<>();
data.put("autoResponseActive", true);
data.put("autoResponseWaitSeconds", 30);
data.put("autoResponseMessage", "Howdy!");
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.headers(headers.entrySet().stream()
.map(entry -> entry.getKey() + ": " + entry.getValue())
.toArray(String[]::new))
.POST(HttpRequest.BodyPublishers.ofString(getJsonString(data)))
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) {
System.out.println("Error: HTTP " + response.statusCode());
} else {
System.out.println(response.body());
}
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}