|
1 | 1 | import { ScrapeGraphAI } from "scrapegraph-js"; |
2 | 2 |
|
3 | | -// reads SGAI_API_KEY from env, or pass explicitly: ScrapeGraphAI({ apiKey: "..." }) |
4 | 3 | const sgai = ScrapeGraphAI(); |
5 | 4 |
|
6 | 5 | const res = await sgai.monitor.create({ |
7 | | - url: "https://example.com/prices", |
8 | | - name: "Price Monitor", |
9 | | - interval: "0 */6 * * *", |
| 6 | + url: "https://time.is/", |
| 7 | + name: "Time Monitor with Webhook", |
| 8 | + interval: "*/10 * * * *", |
10 | 9 | formats: [ |
11 | 10 | { type: "markdown" }, |
12 | | - { type: "json", prompt: "Extract all product prices" }, |
| 11 | + { |
| 12 | + type: "json", |
| 13 | + prompt: "Extract the current time and timezone", |
| 14 | + schema: { |
| 15 | + type: "object", |
| 16 | + properties: { |
| 17 | + time: { type: "string" }, |
| 18 | + timezone: { type: "string" }, |
| 19 | + }, |
| 20 | + required: ["time"], |
| 21 | + }, |
| 22 | + }, |
13 | 23 | ], |
14 | 24 | webhookUrl: "https://your-server.com/webhook", |
15 | 25 | }); |
16 | 26 |
|
17 | | -if (res.status === "success") { |
18 | | - console.log("Monitor created:", res.data?.cronId); |
19 | | - console.log("Will notify:", res.data?.config.webhookUrl); |
20 | | -} else { |
21 | | - console.error("Failed:", res.error); |
| 27 | +if (res.status !== "success" || !res.data) { |
| 28 | + throw new Error(`Failed to create monitor: ${res.error}`); |
| 29 | +} |
| 30 | + |
| 31 | +const { cronId: monitorId, interval, config } = res.data; |
| 32 | +console.log(`Monitor created: ${monitorId}`); |
| 33 | +console.log(`Interval: ${interval}`); |
| 34 | +console.log(`Webhook: ${config.webhookUrl}`); |
| 35 | +console.log("\nPolling for activity (Ctrl+C to stop)...\n"); |
| 36 | + |
| 37 | +function cleanup() { |
| 38 | + console.log("\nStopping monitor..."); |
| 39 | + sgai.monitor.delete(monitorId).then(() => { |
| 40 | + console.log("Monitor deleted"); |
| 41 | + process.exit(0); |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +process.on("SIGINT", cleanup); |
| 46 | + |
| 47 | +const seenIds = new Set<string>(); |
| 48 | + |
| 49 | +while (true) { |
| 50 | + const activity = await sgai.monitor.activity(monitorId); |
| 51 | + if (activity.status === "success" && activity.data) { |
| 52 | + for (const tick of activity.data.ticks) { |
| 53 | + if (seenIds.has(tick.id)) continue; |
| 54 | + seenIds.add(tick.id); |
| 55 | + |
| 56 | + const changes = tick.changed ? "CHANGED" : "no change"; |
| 57 | + console.log(`[${tick.createdAt}] ${tick.status} - ${changes} (${tick.elapsedMs}ms)`); |
| 58 | + if (tick.diffs && Object.keys(tick.diffs).length > 0) { |
| 59 | + console.log(" Diffs:", JSON.stringify(tick.diffs, null, 2)); |
| 60 | + } else if (tick.changed) { |
| 61 | + console.log(" (no diffs data - first tick establishes baseline)"); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + await new Promise((r) => setTimeout(r, 30000)); |
22 | 66 | } |
0 commit comments