Spaces:
Runtime error
Runtime error
File size: 7,283 Bytes
c7fbc2e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | import { prisma } from "@/lib/prisma";
// Define strict types for the webhook payload
interface WebhookEvent {
entry: Array<{
id: string; // Instagram Business Account ID
time: number;
changes: Array<{
field: string;
value: {
from: {
id: string; // User ID who commented
username: string; // Username of commenter
};
media: {
id: string; // Media ID (Post ID)
product_type?: string;
};
id: string; // Comment ID
text: string; // Comment text
created_time: number;
parent_id?: string; // If it's a reply to a comment
};
}>;
}>;
}
export async function processCommentEvent(body: WebhookEvent) {
if (!body.entry || body.entry.length === 0) return;
for (const entry of body.entry) {
for (const change of entry.changes) {
if (change.field === "comments") {
const value = change.value;
const mediaId = value.media.id;
const commentText = value.text;
const commentId = value.id;
const userId = value.from.id;
// 1. Find the local Post relating to this Instagram Media ID
// Note: We need to store instagramMediaId in our Post model to map this back.
// Assuming we have it. If not, we might fail to match.
console.log(`[Automation] Processing comment ${commentId} on media ${mediaId} from user ${userId}`);
// 1. Find the local Post relating to this Instagram Media ID
const post = await prisma.post.findFirst({
where: { instagramMediaId: mediaId },
include: {
automations: {
where: { isActive: true },
include: { keywords: true, replies: true }
},
instagramAccount: true
}
});
if (!post) {
console.log(`[Automation] No local post found for IG Media ID: ${mediaId}`);
continue;
}
if (post.automations.length === 0) {
console.log(`[Automation] Post found (ID: ${post.id}), but no active automations.`);
continue;
}
const automation = post.automations[0];
const keywords = automation.keywords.map(k => k.keyword.toLowerCase().trim());
// 2. Check for Keyword Match
const lowerText = commentText.toLowerCase();
console.log(`[Automation] Checking text: "${lowerText}" against keywords: [${keywords.join(", ")}]`);
const matched = keywords.some(k => lowerText.includes(k));
if (matched) {
console.log(`[Automation] Keyword matched! Executing actions...`);
const accessToken = post.instagramAccount?.accessToken;
if (!accessToken) {
console.error("[Automation] No access token found for account.");
continue;
}
// 3. Send Public Reply
if (automation.replies.length > 0) {
const randomReply = automation.replies[Math.floor(Math.random() * automation.replies.length)];
await sendInstagramReply(commentId, randomReply.replyText, accessToken);
}
// 4. Send DM
if (automation.dmMessage) {
await sendInstagramDM(userId, automation.dmMessage, automation.dmLinkText, automation.dmLinkUrl, accessToken);
}
}
}
}
}
}
async function sendInstagramReply(commentId: string, text: string, accessToken: string) {
try {
const url = `https://graph.facebook.com/v21.0/${commentId}/replies`;
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: text,
access_token: accessToken
})
});
const data = await res.json();
if (!data.id) {
console.error("Failed to send reply:", data);
} else {
console.log("Reply sent:", data.id);
}
} catch (e) {
console.error("Error sending reply:", e);
}
}
async function sendInstagramDM(userId: string, text: string, linkText: string | null | undefined, linkUrl: string | null | undefined, accessToken: string) {
try {
// NOTE: Sending DMs via API typically requires 'messages' scope and often uses 'IG Send API'.
// However, generic "messages" endpoint on Graph API usually works for Business accounts communicating with users who interacted.
// Structure for a generic message
const body: any = {
recipient: { id: userId },
message: { text: text },
access_token: accessToken
};
// If a button is required, it might need "Generic Template" structure,
// but for simplicity/reliability safely, we append the link to text if button not supported easily in basic tier.
// Let's try to append link if present as text for higher success rate unless we are sure about "Generic Template".
// The user request showed a "Button".
// IG Send API with Generic Template for button:
if (linkText && linkUrl) {
body.message = {
attachment: {
type: "template",
payload: {
template_type: "button",
text: text,
buttons: [
{
type: "web_url",
url: linkUrl,
title: linkText
}
]
}
}
};
}
const url = `https://graph.facebook.com/v21.0/me/messages`; // 'me' refers to the Page/account linked to token
// Actually for Instagram Graph API, it's typically POST /{ig-user-id}/messages
// Use the token to inspect 'me' or just assume flow relative to token owner.
// Better: POST https://graph.facebook.com/v21.0/me/messages with access_token of the IG Business User.
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
const data = await res.json();
if (!data.message_id) {
console.error("Failed to send DM:", data);
// Fallback: try sending just text if template failed?
} else {
console.log("DM sent:", data.message_id);
}
} catch (e) {
console.error("Error sending DM:", e);
}
}
|