PYTHON/ETC

Telegram / 텔레그램 봇으로 웹 상 변화감지 알람 만들기 (Python)

24_bean 2022. 8. 8. 11:47

Theme

Python telegram 모듈을 사용해 웹 상 변화 감지 알람을 만들어 보겠습니다.

 

Telegram logo

 


pre-requirement

 

#telegram
#pip
$pip install python-telegram-bot
#conda
$conda install -c conda-forge python-telegram-bot

#bs4
#pip
$pip install beautifulsoup4
#conda
$conda install -c anaconda beautifulsoup4

#requests
#pip
$pip install requests
#conda
$conda install -c anaconda requests

Component

  • telebot
    • logs : 변화 기록
    • scrapper : 해당 페이지 클래스 모듈
    • telebot : django
    • user : user table
    • db.sqlite3 : user information
    • main.py : 봇에게 메세지를 보냄
    • manage.py : django manage.py
    • token_ID.json : telegram token 저장소
  • venv
  • .gitignore : token id 숨김
  • README.md
  • LICENSE

main.py

from pydoc import doc
import telegram
import json
import time

import scrapper


TOKEN = None
chat_id = []


with open("token_ID.json", "r") as ti:
    ti = json.load(ti)
    TOKEN = ti["TOKEN"]
    chat_id.append(ti["CHAT_ID"])
    

bot = telegram.Bot(token=TOKEN)


def main():
    Seoultech = scrapper.Seoultech()
    
    while(Seoultech.check_title_of_announcement()):
        parse_data = Seoultech.get_title()
        bot.sendMessage(chat_id=chat_id[0], text=parse_data)
        time.wait(60)
        

if __name__ == "__main__":
    main()
  • 숨겨진 토큰을 불러와 telegram.Bot에게 parsing합니다.
  • 미리 만들어놓은 scrapper 모듈에서 원하는 페이지의 클래스를 불러와 변화가 감지될 때까지 반복을 돌립니다.
  • 서버의 부하를 막기 위해 time.wait(60)을 지정해줍니다.

Scrapper/seoultech.py

import requests as req
import bs4 as bs


class SeoulTech():
    def __init__(self):
        self.url = 'https://www.seoultech.ac.kr/service/info/matters/'
        self.res = req.get(self.url)
        self.soup = bs.BeautifulSoup(self.res.text, 'html.parser')

    def get_title(self):
        title = self.soup.select('#hcms_content > div.wrap_list > table > tbody > tr:nth-child(1) > td.tit.dn2 > a')
        return (title[0].text).strip()
        
    def save_title_of_announcement(self):
        title = self.get_title()
        with open('./logs/seoultech_info_matters.log', 'w') as f:
            f.writelines(title)
                
    def check_title_of_announcement(self):
        with open('./logs/seoultech_info_matters.log', 'r') as f:
            saved_title = f.read()
        if saved_title == self.get_title():
            print('No new announcement')
            return False
        else:
            self.save_title_of_announcement()
            print(f'New announcement : {self.get_title()}')
            return True
  • 제가 변화를 감지하고 싶은 웹 페이지는 self.url 입니다.
  • css selector를 통해 원하는 태그를 불러오고 bs4로 파싱합니다.
  • .log 파일에 저장된 정보를 가지고 최상단의 제목이 변했는지를 확인하는 로직입니다.

.gitignore

# token and id
.token_ID.json
token_ID.json
  • 개인정보 보호를 위해 위와 같은 코드를 추가해줍니다

Full code

https://github.com/sabin5105/telegram-bot

 

GitHub - sabin5105/telegram-bot: Notice some changes or somethings with telegram

Notice some changes or somethings with telegram. Contribute to sabin5105/telegram-bot development by creating an account on GitHub.

github.com


 

'PYTHON > ETC' 카테고리의 다른 글

PYTHON - pickle 기본 사용법  (0) 2022.08.05