clienttarget-python / src /slack /slack-agent.ts
iDevBuddy
feat: Add Slack Events integration, Dockerfiles, and Hugging Face deployment config
5f138d4
import { callLLM, MODELS } from "../shared/llm/nvidia-client";
import { getSupabaseClient } from "../shared/supabase/client";
import { manualDiscoveryTask } from "../discovery/trigger-tasks/manual-discovery";
import { logger } from "../shared/utils/logger";
import axios from "axios";
import { getEnv } from "../shared/config/env";
const env = getEnv();
// Helper to post messages back to Slack
async function replyToSlack(channelId: string, text: string, threadTs?: string): Promise<void> {
try {
await axios.post(
"https://slack.com/api/chat.postMessage",
{
channel: channelId,
text,
thread_ts: threadTs,
},
{
headers: { Authorization: `Bearer ${env.SLACK_BOT_TOKEN}` },
timeout: 5000,
}
);
} catch (err) {
logger.error({ err }, "Failed to reply to Slack");
}
}
// ─── Intent System Prompt ──────────────────────────────────────
const AGENT_SYSTEM_PROMPT = `You are "Lead Finder AI", an intelligent Slack Chatbot assistant.
Your job is to parse the user's natural language request (in English, Urdu, or Roman Urdu) and map it to a structured action.
You must respond ONLY with a valid JSON object matching this schema:
{
"intent": "discover" | "leads" | "lead_detail" | "status" | "pause" | "resume" | "quota" | "chat",
"params": {
"region": "US" | "UK" | "AU" | "UAE" | "SA" | "SG" (optional),
"industry": string (optional),
"maxCompanies": number (optional),
"companyName": string (optional),
"quotaAmount": number (optional),
"quotaPermanent": boolean (optional)
},
"explanation": "A very brief, friendly sentence in Roman Urdu explaining what you understood and what you are doing (e.g. 'Ji bilkul! Main abhi US ke dental leads dhoondta hoon.' or 'Bilkul, ye rahi aaj ki leads summary:')"
}
Intents mapping rules:
1. "discover": Manual trigger of search/enrichment/scoring.
- Example: "aj US me SaaS leads dhoondo", "manual run UK dental", "dental leads US", "UK clinical leads nikal do", "discover dental UAE"
- Default region to US if not specified. Default maxCompanies to 10 if not specified.
2. "leads": Today's qualified leads list.
- Example: "aj ki leads dikhao", "show today's leads", "aj kya mila?", "today leads summary", "leads"
3. "lead_detail": Profile/score details about a specific company.
- Example: "clickup ki details do", "show lead clickup", "clickup ka batao", "lead detail of Google"
- Extract company name into companyName.
4. "status": System config status (quota, pause/run mode, coordinates).
- Example: "status batao", "system kaisa chal raha?", "running status", "check status"
5. "pause": Pauses automatic CRON daily runs.
- Example: "pause system", "automatic run rok do", "pause auto mode", "stop runs"
6. "resume": Resumes automatic CRON daily runs.
- Example: "resume system", "auto runs start kar do", "resume run"
7. "quota": Changes daily lead quota.
- Example: "quota 15 kar do", "set today's quota to 20", "set permanent quota to 50"
- Extract quotaAmount and quotaPermanent.
8. "chat": General greetings, small talk, questions about how you work, or how to use you.
- Example: "hello", "hi", "tum kon ho?", "how do you work?", "help me"
Respond ONLY with raw JSON. Do not include markdown code block syntax or explanation outside JSON.`;
// ─── Main Chatbot handler ──────────────────────────────────────
export async function handleSlackChat(
userText: string,
userId: string,
channelId: string,
threadTs?: string
): Promise<void> {
const cleanText = userText.trim();
logger.info({ userId, cleanText }, "🤖 AI Chatbot processing message");
// Call the LLM to parse the intent
const llmRes = await callLLM({
operation: "slack_intent_classification",
modelIndex: MODELS.LLAMA_70B, // Use LLaMA 70B for highly accurate intent mapping
systemPrompt: AGENT_SYSTEM_PROMPT,
userPrompt: cleanText,
jsonMode: true,
traceId: `slack-chat-${Date.now()}`,
});
if (!llmRes.parsed) {
await replyToSlack(
channelId,
"Maaf kijiye ga, mujhe aap ki baat samajh nahi aayi. Kya aap dobara keh sakte hain? (Greetings, /discover, /leads waghaira ke liye pooch sakte hain)",
threadTs
);
return;
}
const { intent, params, explanation } = llmRes.parsed as {
intent: string;
params: any;
explanation: string;
};
logger.info({ intent, params }, "🎯 Decoded intent");
// Respond with explanation first so user knows we are on it
if (explanation && intent !== "chat") {
await replyToSlack(channelId, `💬 *Lead Finder AI:* ${explanation}`, threadTs);
}
const db = getSupabaseClient();
try {
switch (intent) {
case "discover": {
const region = params?.region || "US";
const industry = params?.industry || "SaaS";
const maxCompanies = params?.maxCompanies || 10;
await manualDiscoveryTask.trigger({
region: region.toUpperCase(),
industry,
maxCompanies,
triggeredBy: `slack-chat:${userId}`,
});
await replyToSlack(
channelId,
`🚀 **Manual Discovery Triggered!**\n• *Region:* ${region.toUpperCase()}\n• *Industry:* ${industry}\n• *Max Leads:* ${maxCompanies}\n\nJaise hi leads ready honge, main isi channel me card deliver kar dunga!`,
threadTs
);
break;
}
case "leads": {
const today = new Date();
today.setHours(0, 0, 0, 0);
const { data: leads } = await db
.from("lead_scores")
.select(`
total_score, tier,
companies (name, domain, industry, city, service_match),
contacts (full_name, email, email_verified, linkedin_personal_url)
`)
.gte("created_at", today.toISOString())
.order("total_score", { ascending: false });
if (!leads?.length) {
await replyToSlack(channelId, "📋 Aaj ke din abhi tak koi leads qualified nahi huin.", threadTs);
break;
}
const lines = leads.map((l: any, i: number) => {
const emoji = l.tier === "hot" ? "🔥" : l.tier === "warm" ? "✅" : "📋";
const email = l.contacts?.email_verified ? "📧✓" : l.contacts?.email ? "📧" : "—";
const li = l.contacts?.linkedin_personal_url ? "💼" : "—";
return `${emoji} *${l.total_score}* | *${l.companies?.name ?? "?"}* | ${l.companies?.industry ?? "?"} | ${l.companies?.city ?? "?"} | ${email} ${li}`;
});
const reply = `*Today's Leads Summary (${leads.length}):*\n\n` +
`Score | Company | Industry | City | Channels\n` +
`─`.repeat(40) + `\n` +
lines.join("\n") +
`\n\nAap kisi bhi company ki details pooch sakte hain (e.g. "ClickUp ki details do").`;
await replyToSlack(channelId, reply, threadTs);
break;
}
case "lead_detail": {
const companySearch = params?.companyName || "";
if (!companySearch) {
await replyToSlack(channelId, "Mujhe company ka naam batayein taake main detail nikal sakoon.", threadTs);
break;
}
const { data: companies } = await db
.from("companies")
.select("*")
.ilike("name", `%${companySearch.trim()}%`)
.limit(1);
if (!companies?.length) {
await replyToSlack(channelId, `❌ Mujhe "${companySearch}" naam ki koi company database me nahi mili.`, threadTs);
break;
}
const company = companies[0];
const { data: contacts } = await db.from("contacts").select("*").eq("company_id", company.id);
const { data: scores } = await db.from("lead_scores").select("*").eq("company_id", company.id).limit(1);
const { data: profiles } = await db.from("lead_profiles").select("*").eq("company_id", company.id).limit(1);
const score = scores?.[0];
const profile = profiles?.[0];
const contact = contacts?.[0];
const channels: string[] = [];
if (contact?.email) channels.push(`📧 ${contact.email} ${contact.email_verified ? "✓" : "(unverified)"}`);
if (contact?.linkedin_personal_url) channels.push(`💼 <${contact.linkedin_personal_url}|LinkedIn>`);
const responseText = `*🏢 ${company.name}* (Domain: ${company.domain})\n` +
`• *Location:* ${company.city ?? "?"}, ${company.country ?? "?"}\n` +
`• *Industry:* ${company.industry ?? "?"} · *Employees:* ${company.employee_count ?? "?"}\n` +
`• *Service Match:* ${company.service_match ?? "—"}\n\n` +
`*📊 AI Scoring: ${score?.total_score ?? "?"}/100 — ${score?.tier?.toUpperCase() ?? "?"}*\n` +
` - Fit: ${score?.company_fit ?? "?"}/25 · AI Readiness: ${score?.ai_readiness ?? "?"}/20\n` +
` - Service Fit: ${score?.service_match_score ?? "?"}/20 · Contact: ${score?.decision_maker ?? "?"}/20\n\n` +
`*🧠 Profile Summary:*\n_${profile?.profile_summary ?? "No profile summary available."}_\n\n` +
`*🎯 Personalized Outreach Angle:*\n_"${profile?.outreach_angle ?? "—"}"_\n\n` +
`*👤 Decision Maker:* ${contact?.full_name ?? "?"} (${contact?.title ?? "?"})\n` +
` - Channels: ${channels.join(" | ") || "None found"}`;
await replyToSlack(channelId, responseText, threadTs);
break;
}
case "status": {
const { data: autoConfig } = await db.from("system_config").select("value").eq("key", "auto_mode").single();
const paused = autoConfig?.value?.paused ?? false;
const { data: quotaConfig } = await db.from("system_config").select("value").eq("key", "daily_quota").single();
const quota = quotaConfig?.value;
const { data: territory } = await db.from("system_config").select("value").eq("key", "current_territory").single();
const pos = territory?.value;
const { data: todayRuns } = await db
.from("discovery_runs")
.select("status, leads_qualified")
.gte("ran_at", new Date(new Date().setHours(0, 0, 0, 0)).toISOString());
const todayLeads = todayRuns?.reduce((sum: number, r: any) => sum + (r.leads_qualified ?? 0), 0) ?? 0;
const reply = `⚙️ **System Status Report**\n` +
`• *Auto Runs Status:* ${paused ? "⏸️ PAUSED" : "▶️ RUNNING"}\n` +
`• *Daily Quota:* ${(quota as any)?.today_override ?? (quota as any)?.default ?? 10} leads/day\n` +
`• *Qualified Today:* ${todayLeads} leads\n` +
`• *Active Territory:* ${(pos as any)?.countryCode ?? "?"} city#${(pos as any)?.cityIndex ?? 0}\n` +
`• *Runs Executed Today:* ${todayRuns?.length ?? 0}`;
await replyToSlack(channelId, reply, threadTs);
break;
}
case "pause": {
await db.from("system_config").update({
value: { enabled: true, paused: true, paused_by: "slack-chat" },
updated_at: new Date().toISOString(),
}).eq("key", "auto_mode");
await replyToSlack(channelId, "⏸️ **System Paused!** Daily automatic runs ko rok diya gaya hai. Jab tak aap resume nahi karenge, automatic process nahi chale ga.", threadTs);
break;
}
case "resume": {
await db.from("system_config").update({
value: { enabled: true, paused: false, paused_by: null },
updated_at: new Date().toISOString(),
}).eq("key", "auto_mode");
await replyToSlack(channelId, "▶️ **System Resumed!** Automatic runs dubara schedule par start ho gayi hain.", threadTs);
break;
}
case "quota": {
const num = params?.quotaAmount;
if (!num || isNaN(num) || num < 1 || num > 100) {
await replyToSlack(channelId, "Usage: 'quota 15 kar do' (max 100)", threadTs);
break;
}
const permanent = !!params?.quotaPermanent;
const key = "daily_quota";
const { data: config } = await db.from("system_config").select("value").eq("key", key).single();
const val = config?.value || { default: 10, today_override: null };
if (permanent) {
val.default = num;
val.today_override = null;
} else {
val.today_override = num;
}
await db.from("system_config").update({
value: val,
updated_at: new Date().toISOString()
}).eq("key", key);
await replyToSlack(
channelId,
permanent
? `✅ **Daily Quota permanently set to ${num} leads/day!**`
: `✅ **Today's Quota set to ${num} leads!** Kal automatic default par wapas chala jaye ga.`,
threadTs
);
break;
}
case "chat": {
// Chatbot replies using LLM in Roman Urdu directly
await replyToSlack(channelId, `💬 ${explanation}`, threadTs);
break;
}
default: {
await replyToSlack(channelId, "Mujhe aap ka naya command samajh nahi aaya. Kya aap explain kar sakte hain?", threadTs);
}
}
logger.info({ intent }, "🤖 Chatbot action completed successfully");
} catch (err: any) {
logger.error({ err, intent }, "Error executing Slack AI Chatbot action");
await replyToSlack(channelId, `❌ Action fail ho gaya: ${err.message || err}`, threadTs);
}
}