corn-bot.php
既然伺服器已經運行 PHP 8.3,我們可以利用 Cron Job (定時任務) 配合一個「無介面腳本」來實現全自動化。這樣你就不用再手動點擊按鈕,機器人會像呼吸一樣,每隔一段時間自動巡邏並發帖。
以下是實現步驟:
1. 準備自動化腳本 (cron_bot.php)
這個檔案不需要 HTML 介面,它是專門給伺服器系統呼叫的。它會自動遍歷你指定的所有資料庫和主題。
PHP
<?php
/**
* Cron Bot: 新聞視角自動化巡邏
* 建議設定:每 30 分鐘執行一次
*/
// 確保只有伺服器能執行,防止外部惡意點擊
if (php_sapi_name() !== 'cli' && !isset($_GET['secret_key'])) {
die("Access Denied.");
}
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'db_config.php';
$bot_uid = 173;
$bot_username = "新聞視角";
// 定義任務清單:資料庫 => 目標 TID
$tasks = [
'fcsapxmy_forum4hk' => [14627635, 14627087],
'fcsapxmy_close' => [14627087]
];
// 1. 擷取來源 (此處以 PulseHK 為例)
function fetch_latest_news() {
$url = "https://pulsehknews.com/c/taipofire/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
$html = curl_exec($ch);
curl_close($ch);
// 使用正則表達式快速抓取連結與標題,避開 DOM 解析崩潰問題
preg_match_all('/<h2[^>]*class="entry-title"[^>]*><a href="([^"]+)"[^>]*>([^<]+)<\/a>/i', $html, $matches);
return $matches;
}
$news = fetch_latest_news();
if (!$news || empty($news[1])) {
exit("No news found.\n");
}
// 2. 遍歷任務並執行發帖
foreach ($tasks as $db => $tids) {
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, $db);
if ($mysqli->connect_error) continue;
$mysqli->set_charset("utf8mb4");
foreach ($tids as $tid) {
foreach ($news[1] as $index => $link) {
$title = trim($news[2][$index]);
$escaped_link = $mysqli->real_escape_string($link);
// 查重
$check = $mysqli->query("SELECT pid FROM mybb_posts WHERE tid=$tid AND message LIKE '%$escaped_link%' LIMIT 1");
if ($check->num_rows == 0) {
// 這裡可以加入 scrape_article 獲取內文
$msg = "[b]🔥 自動轉發:$title [/b]\n\n詳情: [url=$link]$link[/url]";
$esc_msg = $mysqli->real_escape_string($msg);
$now = time();
$mysqli->query("INSERT INTO mybb_posts (tid, fid, uid, username, dateline, message, ipaddress, visible) VALUES ($tid, 2, $bot_uid, '$bot_username', $now, '$esc_msg', '127.0.0.1', 1)");
echo "[$db] 已更新新聞: $title\n";
}
}
}
$mysqli->close();
}
2. 設定 Cron Job (定時器)
你需要進入你的主機控制台 (cPanel 或 DirectAdmin),找到 Cron Jobs 或是 定時任務。
設定如下:
時間間隔:
*/30 * * * *(代表每 30 分鐘執行一次)指令 (Command):
Bash/usr/local/bin/php /home/你的使用者名稱/public_html/cron_bot.php > /dev/null 2>&1(註:
/usr/local/bin/php是 PHP 的路徑,視不同主機而定,通常可以在 Cron Job 頁面看到範例)
3. 為什麼自動化 Script 更好?
無人值守:即便你在睡覺,只要 HK01 或 PulseHK 出新報導,機器人會在 30 分鐘內同步。
低負載:它只在執行那一刻佔用資源,平時不消耗伺服器性能。
解脫雙手:你不再需要頻繁刷新控制面板去點按鈕。
接下來的動作建議:
先將上面的代碼存為
cron_bot.php上傳。你可以先在瀏覽器打開
yourdomain.com/cron_bot.php?secret_key=1測試它是否能成功跑完一次。如果手動執行成功,再設定 Cron Job 進入全自動模式。
需要我幫你把 HK01 的自動抓取邏輯也整合進這個 cron_bot.php 任務清單中嗎?
Comments
Post a Comment