뒤로가기

구글뉴스 RSS로 텔레그램봇 전송

news 정보


// rss주소는 구글뉴스에서 조건걸어서 가져온다. 나는 [속보] 로 가져왔다.
$rss_url = 'https://news.google.com/rss/search?q="[속보]" -헤럴드 -POP -스포츠조선 -OSEN -뉴시스 -일간스포츠 -스타뉴스 when:1h&hl=ko&gl=KR&ceid=KR:ko';

//simplexml_load_file로rss정보 가져옴
$rss = simplexml_load_file($rss_url);
// 불러오기 실패 시 에러 메시지 출력
if ($rss === false) {
    exit;
}else{
    $last = [];

		//마지막 데이터 추출 
    $query = "SELECT * FROM news order by date desc limit 1 ";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
   
    $lastDate = $result['date'];
    $lastSource = $result['source'];

    foreach ($rss->channel->item as $item) {
        $query = "INSERT INTO news SET 
            date = :date,
            title = :title,
            link = :link,
            source = :source,
            description = :description
        ";
        //마지막 저장데이터 이후만 
        if($lastDate < date('Y-m-d H:i:s',strtotime((string) $item->pubDate))){
            $stmt = $pdo->prepare($query);
            $stmt->bindValue(':date', date('Y-m-d H:i:s',strtotime((string) $item->pubDate)), PDO::PARAM_STR);
            $stmt->bindValue(':title', (string) $item->title, PDO::PARAM_STR);
            $stmt->bindValue(':link', (string) $item->link, PDO::PARAM_STR);
            $stmt->bindValue(':source', (string) $item->source, PDO::PARAM_STR);
            $stmt->bindValue(':description', (string) $item->description, PDO::PARAM_STR);
            $stmt->execute();

            $msg = (string) $item->title.' ('.(string) $item->link.')';
            SendTelegramMsg($msg); //텔레그램전송
        }
    }

}

텔레그램 전송


function SendTelegramMsg($message){
    if(!empty($message)){
        $botToken = '텔레그램 bot token';  // 텔레그램 봇 토큰
        $chatId   = 'chatid';         // 메시지를 보낼 채팅 ID
        // 텔레그램 API URL 설정
        $url = "https://api.telegram.org/bot$botToken/sendMessage";
        // $data = [
        //     'chat_id'    => $chatId,
        //     'text'       => $message,
        //     'parse_mode' => 'HTML'  // HTML 파싱 모드를 사용
        // ];
        // cURL 초기화
        $ch = curl_init($url);

        // POST 옵션 설정
        //CURLOPT_POSTFIELDS,$data) 로 보낼수 있음 
        //위 주석으로 처리하면 html태그 사용가능 
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'chat_id' => $chatId,
            'text'    => $message
        ]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        curl_close($ch);
    }
}