Files
Siro/backend/marketing_engine/telegram_scraper.php
T

137 lines
4.5 KiB
PHP

<?php
// telegram_scraper.php
if (php_sapi_name() !== 'cli') {
die("This script must be run from the command line (Terminal).\n");
}
// Load .env for CLI
$envPath = __DIR__ . '/../.env';
if (file_exists($envPath)) {
$lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) continue;
$parts = explode('=', $line, 2);
if (count($parts) === 2) {
putenv(trim($parts[0]) . '=' . trim($parts[1]));
}
}
}
require_once __DIR__ . '/../core/Services/SiroGeminiService.php';
require_once __DIR__ . '/../core/Database/Database.php';
if (!file_exists(__DIR__ . '/madeline.php')) {
die("Error: madeline.php not found. Please run telegram_setup.php first.\n");
}
require_once __DIR__ . '/madeline.php';
if (!file_exists(__DIR__ . '/telegram_session.madeline')) {
die("Error: No session found. Please run telegram_setup.php to authenticate.\n");
}
echo "[*] Starting Telegram Scraper...\n";
$settings = new \danog\MadelineProto\Settings();
$settings->getAppInfo()->setApiId(2040);
$settings->getAppInfo()->setApiHash('b18441a1ff607e10a989891a5462e627');
$MadelineProto = new \danog\MadelineProto\API('telegram_session.madeline', $settings);
// Start MadelineProto (will resume session silently since it's already authenticated)
$MadelineProto->start();
// Define targets (Usernames, Group IDs, or Links)
// NOTE: You must be a member of the group/channel if it is private.
$targets = [
// 'https://t.me/example_group',
// '@example_channel',
'@YallaGo_Captains',
'@TaxiFJOR','@zakinntaxi','@zakinncaptains','@zakinaleppo','https://t.me/+rsfxbXEyDCczY2Nk'
];
if (empty($targets)) {
echo "[-] No targets defined. Please edit telegram_scraper.php and add your target groups/channels.\n";
exit;
}
$allMessages = [];
foreach ($targets as $target) {
echo "[*] Fetching latest messages from: $target\n";
try {
// Fetch history (last 50 messages per target)
$messages_Messages = $MadelineProto->messages->getHistory([
'peer' => $target,
'offset_id' => 0,
'offset_date' => 0,
'add_offset' => 0,
'limit' => 50,
'max_id' => 0,
'min_id' => 0,
'hash' => 0,
]);
if (isset($messages_Messages['messages'])) {
foreach ($messages_Messages['messages'] as $msg) {
if (isset($msg['message']) && !empty(trim($msg['message']))) {
// Prefix with [TELEGRAM] to inform Gemini
$allMessages[] = "[TELEGRAM]: " . trim($msg['message']);
}
}
}
} catch (\Exception $e) {
echo "[-] Error fetching $target: " . $e->getMessage() . "\n";
}
}
if (empty($allMessages)) {
echo "[-] No text messages found.\n";
exit;
}
echo "[+] Collected " . count($allMessages) . " messages.\n";
echo "--- Sample (First 3 messages) ---\n";
for($i=0; $i<min(3, count($allMessages)); $i++) {
echo $allMessages[$i] . "\n";
}
echo "---------------------------------\n";
echo "[*] Sending to Gemini AI for analysis...\n";
$gemini = new SiroGeminiService();
$reportHtml = $gemini->evaluateTelegramForReporting($allMessages);
if ($reportHtml && strpos($reportHtml, 'لا توجد بيانات مفيدة') === false) {
echo "[+] AI generated a useful report. Saving to DB...\n";
$db = new Database();
$con = $db->connect();
$stmt = $con->prepare("INSERT INTO marketing_reports (platform, report_html) VALUES (?, ?)");
$stmt->execute(['telegram', $reportHtml]);
$reportId = $con->lastInsertId();
echo "[+] Report saved with ID: $reportId\n";
// Attempt FCM Alert
try {
require_once __DIR__ . '/../core/Services/FcmService.php';
$fcm = new FcmService();
$fcm->send(
token: '/topics/admin_alerts',
title: 'New Telegram Intelligence Report 📊',
body: "A new autonomous analysis report for Telegram has been generated.",
data: ['type' => 'marketing_report', 'report_id' => (string)$reportId]
);
echo "[+] Sent FCM alert to admins.\n";
} catch (\Exception $e) {
echo "[-] Error sending FCM: " . $e->getMessage() . "\n";
}
} else {
echo "[-] AI Report: No useful data or API Error.\n";
echo "--- Gemini Raw Output ---\n";
echo var_export($reportHtml, true) . "\n";
echo "-------------------------\n";
}
echo "[*] Done.\n";