본문 바로가기
SW programming/Telegram bot 프로젝트

[Python 텔레그램 봇] - I say '관심 기업', you say '기사 5개' 툭!

by 고뭉나무 2021. 5. 16.

 

프로그램 컨셉

I say '관심 기업'

 

원하는 기업을 말하면,

 

you say '기사 5개'

텔레그램 봇이 네이버에 검색해서 그 기업 최신 뉴스 5개를 뙇 내 앞에!

 

프로젝트 결과

 

이 프로젝트는 지난 포스팅에서 했던 날씨 알림 코드를 응용하여 제작하였다.

2021.05.02 - [SW programming/Python] - [Python] 텔레그램 봇 - 원하는 지역의 날씨 정보 알림

 

[Python] 텔레그램 봇 - 원하는 지역의 날씨 정보 알림

프로그램 컨셉 - Weather bot 채팅 창에 '/날씨 부산'를 치면 원하는 결과를 알려준다. - 그 결과는 네이버 검색에서 마치 '부산 날씨'를 검색해서 해당 날씨 정보이다. - 날씨 정보로 현재 온도, 미세

rubber-tree.tistory.com

 

HTML 정보 읽어오기

Tip!
PC버전보다 '모바일 버전'이 HTML 문서 구조가 더 간결하게 되어 있다. 그러므로 모바일 버전(m.naver.com)으로 보는 것을 추천한다.

m.naver.com에서 '삼성전자'를 검색하여 뉴스 탭에 가면 아래와 같은 HTML 정보를 얻을 수 있다.

Block 단위로 구분된 뉴스 리스트는 news_result_list (파란선) 에 담겨 있으며, 

해당 뉴스의 링크는 bx 아래 news_wrap 아래 a의 href에 담겨 있다. (빨간선)

 

설치 라이브러리

총 3개를 설치해야 한다.

1) pip install telepot

2) pip install requests

3) pip install BeautifulSoup

 

 

소스 코드

import requests
from bs4 import BeautifulSoup
import telepot

#텔레그램 봇 생성
token = '본인의 Token 정보'
bot = telepot.Bot(token=token)

#링크 추출 함수
#원하는 기업의 이름을 넘김
#해당 url의 html문서를 soup 객체로 저장
def get_news(where):
    url = "https://m.search.naver.com/search.naver?where=m_news&sm=mtb_jum&query={}".format(where)
    req = requests.get(url)
    html = req.text
    soup = BeautifulSoup(html, 'html.parser')

    search_result = soup.select_one('#news_result_list')
    news_list = search_result.select('.bx > .news_wrap > a')
 
    #기사 5개를 출력한다.
    links = []
    for news in news_list[:5]:
        #해당 기사의 링크 추출
        link = news['href']
        links.append(link)

    return links


def handler(msg):
    content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance(msg, long=True)

    print(msg)

    if content_type == "text":
        str_message = msg["text"]
        if str_message[0:1] == "/":
            args = str_message.split(" ")
            command = args[0]
            del args[0]
            
            #'/뉴스 <원하는 기업>'으로 텔레그램 봇에 입력하면 get_news 함수가 실행된다.
            #추후에 한 코드 안에 다른 기능도 넣을 예정이라 이렇게 구분 지었다.
            if command == "/뉴스":
                n = " ".join(args)
                new_links = get_news(n)
                for link in new_links:
                    bot.sendMessage(chat_id, text = link)
 
bot.message_loop(handler, run_forever=True)

 

Telegram 결과

 

반응형

댓글