본문 바로가기

Bot 기술노트

웹페이지 게시물 업데이트 알람 봇 만들기(1)

 

텔레그램 웹페이지 게시물 업데이트 알람 봇 만들기(1)


  • 이번 블로깅 주제는 텔레그램 API를 활용하여 알람 받고자 하는 특정 웹 페이지 게시판에 새 게시물이 올라면 텔레그램 App으로 알람을 주는 알람 봇 만들기로, 1편과 2탄으로 나누어 방법을 소개한다.
  • 1편 - pytthon 환경 구성 및 알람 봇 소스코드
  • 2편 - python 소스코드를 Heroku에 배포하여 가상 서버에서 실시간으로 서비스 할 수 있는 방법
  • Anaconda와 python 3.6의 설치는 각각 환경이 다를 수 있기 때문에 이번 글에서는 언급하지 않음

설치환경


  • Windows 10 Pro 64bit
  • python 3.6, Anaconda 4.4.0 for Windows
  • heroku

python 3.6.x 환경 생성


  • Anaconda는 버전에 맞는 환경변수 그룹을 만들어 이름을 부여하고, 그룹마다 패키지를 설치하고 관리할 수 있는 툴을 제공한다.(가상환경 관리자, virtualenv, conda)
  • Anaconda Prompt 실행 후 아래 가상 환경 생성 명령어 입력
    (반드시 관리자 권한으로 Prompt 실행)

C:> conda create -n python36 python=3.6
  • python36라는 이름으로 환경을 구성 결과화면

python 3.6 환경 활성화

  • 환경 설정이 완료되면 activate 명령어로 3.6.x 환경을 활성화 할 수 있다.

생성한 python36 환경 활성화

C:> activate python36

텔레그램 python 패키지 설치



(python36) C:> pip install python-telegram-bot

텔레그램 봇 API 토큰 얻기


  • 텔레그램 봇을 사용하기 위해 봇 생성을 먼저 해야한다.
  • 텔레그램 App 검색에서 BotFather 검색 후 대화 시작
  • BotFather와 대화 형식으로 봇 생성 가능한 안내문이 보인다.
I can help you create and manage Telegram bots. 

If you're new to the Bot API, please see the manual.

You can control me by sending these commands:

/newbot - create a new bot

/mybots - edit your bots [beta]

Edit Bots

/setname - change a bot's name

/setdescription - change bot description

/setabouttext - change bot about info

/setuserpic - change bot profile photo

/setcommands - change the list of commands

/deletebot - delete a bot

Bot Settings

/token - generate authorization token

/revoke - revoke bot access token

/setinline - toggle inline mode

/setinlinegeo - toggle inline location requests

/setinlinefeedback - change inline feedback settings

/setjoingroups - can your bot be added to groups?

/setprivacy - toggle privacy mode in groups

Games

/mygames - edit your games [beta]

/newgame - create a new game

/listgames - get a list of your games

/editgame - edit a game

/deletegame - delete an existing game
  • /newbot 메시지 입력 후 생성할 봇 계정명 my_parsing_bot 전송
  • 봇 계정명 중복이 있는지 체크 후 봇 생성 완료되면 성공 메시지를 보내준다.

  • 메시지 중간 생성한 봇 계정으로 접근할 수 있는 HTTP API 키가 발급 된 것을 확인할 수 있다.

텔레그램 봇 - 사용자에게 메시지 보내기


#!/usr/bin/env python

# encoding=utf-8

import telegram

bot = telegram.Bot(token='YourTokenKey')

#생성한 텔레그램 봇 정보

me = bot.getMe()

print(me)

#생성한 텔레그램 봇 /start 시작 후 사용자 id 받아 오기

chat_id = bot.getUpdates()[-1].message.chat.id

print('user id :', chat_id)

#사용자 id로 메시지 보내기

bot.sendMessage(chat_id, u'bot이 보낸 메시지')
  • 봇에서 사용자로 메시지 보낸 것을 확인 할 수 있다.

텔레그램 봇 - 채널로 메시지 보내기(채널 생성)


  • 텔레그램 App에서 새로운 메시지 > New Channel

)

  • 생성할 Channel 이름 입력

  • 채널 정보에 텔레그램 봇을 관리자로 추가하기
  • 메시지 보내기 권한 등 관리자 권한 부여 후 완료

텔레그램 봇 - 채널로 메시지 보내기


  • 사용자 ID 처럼 메시지를 보낼 채널 ID를 알아야 한다.
  • [https://api.telegram.org/bot[YourTokenKey]/getUpdates](https://api.telegram.org/bot%5C%5BYourTokenKey%5C%5D/getUpdates%5C%60)
  • 위 url에 [YourTokenKey] 부분에 BotFather에게 받은 API 토큰을 넣은 후 브라우저에 주소 입력 후 Enter
  • JSON 출력 결과 중 chat_id가 사용자 ID와 다르게 음수 값인걸 확인할 수 있다.

..."channel_post":{"message_id":2,"chat":{"id":-123456789,"title":"my_parsing_bot","type":"channel"},"date":1562389614,"text":"dd"}...
#!/usr/bin/env python

# encoding=utf-8

import telegram

bot = telegram.Bot(token='YourTokenKey') 

#생성한 텔레그램 봇 정보

me = bot.getMe()

print(me)

#사용자 id로 메시지 보내기

bot.sendMessage(-123456789, u'bot이 채널로 보낸 메시지')
  • 봇에서 채널로 메시지 보낸 것을 확인 할 수 있다.

웹 페이지 게시물 업데이트 알람 봇(크롤러) 만들기(python)


1. 크롤러 관련 python 패키지 설치


(python36) C:> pip install requests

(python36) C:> pip install beautifulsoup4

2. 크롤링 할 웹 페이지의 HTML 태그 분석

  • 크롬 개발자 도구 활용하여 뽐뿌 게시판 HTML 태그 분석

3. python 크롤러 구현

#!/usr/bin/env python

# encoding=utf-8

import requests

import time

from bs4 import BeautifulSoup

import telegram

bot = telegram.Bot(token='YourTokenKey')

if __name__ == '__main__':

# 제일 최신 게시글의 번호 저장

latest_num = 0

while True:

req = requests.get('http://www.ppomppu.co.kr/zboard/zboard.php?id=ppomppu')

html = req.text

soup = BeautifulSoup(html, 'html.parser')

posts = soup.find("tr", {"class" : "list1"})

post_num = posts.find("td", {"class" : "eng list_vspace"}).text

# 제일 최신 게시글 번호와 30초 마다 크롤링한 첫번째 게시글의 번호 비교

# 비교 후 같지 않으면 최신 게시글 업데이트 된 것으로 텔레그램 봇으로 업데이트 메시지 전송

if latest_num != post_num :

latest_num = post_num

link = 'http://www.ppomppu.co.kr/zboard/'+posts.find("td", { "valign" : "middle"}).find("a").attrs['href']

title = posts.find("font", {"class" : "list_title"}).text

text = '<뽐뿌 게시글 업데이트>'+'n'+title+'n'+link  

bot.sendMessage(-123456789, text)

# 프롬프트 로그

print(post_num)

print(title)

print(link)

time.sleep(30) # 30초 간격으로 크롤링

print('bot 동작 중 현재 게시글 번호' + latest_num)
  • 크롤러 python 코드 동작 결과 30초 간격으로 게시판의 게시물 업데이트를 확인하며, 새 게시물이 등록되면 아래 처럼 알람을 준다.