index.ts 3.53 KB
Newer Older
duanjinfei's avatar
duanjinfei committed
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
import { createClient } from "jsr:@supabase/supabase-js@2";
import { Bot } from 'https://deno.land/x/grammy@v1.34.0/mod.ts'

// 初始化 Supabase 客户端
const supabaseUrl = Deno.env.get("SUPABASE_URL");
const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
const supabase = createClient(supabaseUrl, supabaseKey);


const sendTimeToleranceMs = 5 * 60 * 1000; // 5分钟的时间窗口

async function processBotChat() {
  try {
    const currentTime = new Date();
    const startTime = new Date(currentTime.getTime() - sendTimeToleranceMs).toISOString();
    const endTime = new Date(currentTime.getTime() + sendTimeToleranceMs).toISOString();

    console.log(`Processing bot_chat records between ${startTime} and ${endTime}`);

    // 查询符合条件的 bot_chat 记录
    const { data: botChats, error: fetchError } = await supabase
      .from("bot_chat")
      .select("id, content, bot_id, agent_id, send_time")
      .gte("send_time", startTime)
      .lte("send_time", endTime)
      .eq("status", "0");

    if (fetchError) {
      console.error("Error fetching bot_chat records:", fetchError);
      return;
    }

    if (!botChats || botChats.length === 0) {
      console.log("No bot_chat records found in the time window.");
      return;
    }

    console.log(`Fetched ${botChats.length} bot_chat records.`);

    // 处理每条 bot_chat 记录
    for (const chat of botChats) {
      const { id, content, bot_id, agent_id } = chat;

      try {
        // 查询 agent_tg 表获取 tg_chat_id
        const { data: agentData, error: agentError } = await supabase
          .from("agent_tg")
          .select("tg_chat_id")
          .eq("agent_id", agent_id)

        if (agentError || !agentData || agentData.length === 0) {
          console.error(`Failed to fetch tg_chat_id for agent_id ${agent_id}:`, agentError);
          continue;
        }

        // 查询 agent_tg 表获取 tg_chat_id
        const { data: botData, error: botError } = await supabase
          .from("bot")
          .select("id,tg_token")
          .eq("id", bot_id)
          .single();

        if (botError || !botData) {
          console.error(`Failed to fetch bot token for bot_id ${bot_id}:`, botError);
          continue;
        }

        const { tg_chat_id } = agentData[0];

        // 使用 bot_id 初始化 Telegram Bot
        const bot = new Bot(botData.tg_token);
        await bot.api.sendMessage(tg_chat_id, content);

        console.log(`Message sent to chat_id ${tg_chat_id} for bot_chat ID ${id}`);

        // 更新 bot_chat 状态为已发送
        const { error: updateError } = await supabase
          .from("bot_chat")
          .update({ status: "1", finished_at: new Date().toISOString() })
          .eq("id", id);

        if (updateError) {
          console.error(`Failed to update bot_chat status for ID ${id}:`, updateError);
        }
      } catch (err) {
        console.error(`Error processing bot_chat ID ${id}:`, err);
      }
    }
  } catch (err) {
    console.error("Unexpected error in processBotChat:", err);
  }
}

// 主流程:每次请求调用事件处理函数
Deno.serve(async () => {
  try {
    EdgeRuntime.waitUntil(processBotChat())
    return new Response(JSON.stringify({ message: "Bot chat processed successfully" }), {
      status: 200,
      headers: { "Content-Type": "application/json" },
    });
  } catch (err) {
    console.error("Unexpected error:", err);
    return new Response(JSON.stringify({ error: "Internal server error" }), {
      headers: { "Content-Type": "application/json" },
      status: 500,
    });
  }
});