돔저지 알림이(크롤링 + 슬랙 알림)

정현섭·2021년 4월 13일
0

상황

수업에서 교수님이 매주 problem solving문제를 내주시고
며칠 뒤에 dom judge 웹사이트에 code를 제출할 수 있는 란을 열어주셨다.

근데 항상 다 풀었는데 아직 코드 제출란을 안 열어주셔서 계속 dom judge 홈페이지를 들락날락하며 업로드 됐는지 확인했었다.

그래서 더이상 dom judge를 들락날락거리느라 시간낭비하지 않기 위해 코드 제출란 업로드를 확인해서 슬랙으로 알람을 주는 크롤러를 만들기로 결심했다!

(개발자라면 반복되는 불편한 작업을 자동화 해야하니까.?)

어떻게?

  • 파이썬의 request와 bs4 라이브러리로 크롤링
  • 슬랙 채널을 하나 파서 사용자 지정 통합 앱 (수신 웹 후크)를 이용하여 메시지를 보냈다.

0. 사용한 라이브러리(모듈)

1. 크롤링 후 변화가 있는지 체크

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

while True:
    time.sleep(5)
    req = requests.get('https://problemsolving.cafe24.com/public')
    req.encoding = 'utf-8'

    html = req.text
    soup = BeautifulSoup(html, 'html.parser')
    contests = soup.select('a.dropdown-item')

    latest = ""
    before = ""
    for contest in contests :
        latest += contest.text + '\n'

    with open(os.path.join(BASE_DIR, 'latest.txt'), 'r') as f_read :
        before = f_read.read()
        f_read.close()

    if before != latest :
        with open(os.path.join(BASE_DIR, 'latest.txt'), 'w') as f_write :
            f_write.write(latest)
            print("새로운 contest가 열렸습니다!")
            print(latest)
            f_write.close()
        notification(latest)

2. 슬랙으로 메시지 전송

def notification(message) :
    url = 'https://hooks.slack.com/services/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'
    
    payload = {
        "text": message
    }
    requests.post(url, json=payload)

incoming webhooks 라는 slack api 사용법은 "슬랙용 수신 웹후크" 여기를 참고하자!


incoming webhooks는 그냥 채널에 메시지를 보내는 기능만 있는 slack api다.

결과

만들어서 채널에 친구들을 초대해서 같이 알림을 받았다 ㅎㅎ

0개의 댓글