I’m trying to send automated responses via Instagram Messenger using the Meta API. Here’s a snippet of my code:
async function handleInstagramMessage(messagingItem) {
try {
if (messagingItem.message && messagingItem.message.text) {
// Ignore echo messages
// if (messagingItem.message.is_echo) {
// console.log("Skipping echo message.");
// return;
// }
const messageId = messagingItem.message.mid;
const message = messagingItem.message.text.trim();
const senderId = messagingItem.sender.id;
const recipientId = messagingItem.recipient.id;
const timestamp = messagingItem.timestamp;
const pageTokens = getPageTokens();
const currentPage = pageTokens.find(page => page.instagram_page_id === senderId);
// Check if sender ID exists in ownPageSenderIds
if (ownPageSenderIds[senderId]) {
const senderDetails = ownPageSenderIds[senderId];
// Respond to "send" by sending an image
if (message === "scanner") {
console.log('Message is "SEND" - Sending image');
await sendInstagramImage(recipientId, senderDetails.imageUrl, currentPage.access_token);
console.log('Sent image to recipient:', recipientId);
return;
}
// Respond to "email" by sending email details
if (message === "email") {
console.log('Message is "EMAIL" - Sending email details');
const responseText = `${senderDetails.email}`;
await sendInstagramMessage(recipientId, responseText, currentPage.access_token);
console.log('Sent email details to recipient:', recipientId);
return;
}
} else {
console.log(`Sender ID: ${senderId} not found in ownPageSenderIds.`);
}
// const pageTokens = getPageTokens();
const currentPageRESPONSE = pageTokens.find(page => page.instagram_page_id === recipientId);
if (!currentPageRESPONSE) {
console.error(`No access token found for Instagram page ID: ${senderId}`);
return;
}
if (processedMessageIds.has(messageId)) {
console.log(`Skipping already processed message ID: ${messageId}`);
return;
}
processedMessageIds.add(messageId);
// Get time-based greeting
const timeGreeting = getTimeBasedGreetingFromTimestamp(timestamp);
// Fetch username
const username = await getUsername(senderId, currentPageRESPONSE.access_token);
// Handle the question with both username and timeGreeting
const responseText = handleQuestion(message, username, timeGreeting);
if (responseText !== "I'm sorry, I didn't understand that. Could you please rephrase?") {
await sendInstagramMessage(senderId, responseText, currentPageRESPONSE.access_token);
} else {
console.log("Message did not match any question triggers.");
}
}
} catch (error) {
console.error("Error in handleInstagramMessage:", error);
}
}
async function sendInstagramMessage(recipientId, message, pageAccessToken) {
try {
console.log(`Sending message "${message}" to ${recipientId}`);
const response = await axios.post(`https://graph.facebook.com/v20.0/me/messages`, {
recipient: { id: recipientId },
message: { text: message },
messaging_type: "RESPONSE"
}, {
headers: { Authorization: `Bearer ${pageAccessToken}` }
});
console.log('Message sent successfully:', response.data);
} catch (error) {
console.error('Error sending message:', error.response ? error.response.data : error.message);
}
}
The problem: All messages are going to the General inbox instead of Primary. I’ve checked for:
Proper access tokens.
Valid user permissions.
Whether the user has interacted with the bot before.
Still, the issue persists. Is there a way to control the placement of messages (General vs. Primary)?
Environment:
Node.js
Instagram Graph API
Any insights or suggestions would be greatly appreciated!
bimal inc is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.