All the my new Message Requests are going to General instead of Primary when responded by my Bots.
here is my test code.
// List of questions (triggers) const questions = [ "hi", "hello", "hey", "hlw", "Hii!", 'hlo', "hii", "helo", "is anyone available to chat?", "i'm interested. can you tell me more?", "can i learn more about your business?" ];
// List of possible answers (responses) const answers = [ "[timeGreeting] [username]! How can I assist you today?", "[timeGreeting] [username]! Glad to meet you. How may I help?", "[timeGreeting] [username]! Welcome! Let me know how I can assist you.", "[timeGreeting] [username]! How can I make your day better?", "[timeGreeting] [username]! It's a pleasure to assist you.", "Hello [username]! How can I assist you today?", "Hi [username]! Glad to meet you. How may I help?", "Hey [username]! Welcome! Let me know how I can assist you.", "Greetings [username]! How can I make your day better?", "Welcome, [username]! It's a pleasure to assist you.", "Hi [username]! I'm here to help. What do you need assistance with?", "Hello [username]! Let me know what you're looking for, and I'll do my best to help.", "Hi there, [username]! Please let me know how I can assist you.", "Welcome [username]! Let me know if there's anything specific you need help with.", "Hey [username]! How can I help you make the most of your day?", "Hi [username]! Feel free to ask me anything. I'm here to help.", "Hello [username]! It's great to connect with you. What can I do for you?", "Hi [username]! Let me know what you're interested in, and I'll guide you.", "Hello [username]! I'm here to assist you with any questions you have.", "Welcome [username]! How can I be of service today?" ];
function getTimeBasedGreetingFromTimestamp(timestamp) { const messageDate = new Date(timestamp); const hour = messageDate.getHours();
if (hour >= 5 && hour < 12) { return "Good Morning"; } else if (hour >= 12 && hour < 17) { return "Good Afternoon"; } else if (hour >= 17 && hour < 21) { return "Good Evening"; } else { return "LateNight"; } }
function getRandomAnswer(username, timeGreeting) { const randomAnswer = answers[Math.floor(Math.random() * answers.length)];
// If the response has [timeGreeting] placeholder, replace it if (randomAnswer.includes("[timeGreeting]")) { return randomAnswer .replace("[timeGreeting]", timeGreeting || "Hello") .replace("[username]", username || "there"); }
// If no [timeGreeting] placeholder, just replace username return randomAnswer.replace("[username]", username || "there"); }
function handleQuestion(message, username, timeGreeting) { const normalizedMessage = message.toLowerCase(); if (questions.includes(normalizedMessage)) { return getRandomAnswer(username, timeGreeting); } return "I'm sorry, I didn't understand that. Could you please rephrase?"; } async function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
// Handle Instagram message const processedMessageIds = new Set();
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);
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, timeGreeting);
await delay(5000);
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); } }
// Modified sendInstagramMessage for better logging 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); } }