python-telegram-bot
라이브러리 설치pip install python-telegram-bot
@BotFather
를 검색해서 가장 최상단에 인증마크가 달린 @BotFather
로 시작한다./newbot
을 입력하고 전송MyFirstAuto
bot
으로 끝나는 이름 입력 ex) MyFirstAutoBot
HTTP API
에 접근할 수 있는 토큰을 별도로 관리import telegram
bot = telegram.Bot(token) # Bot클래스에 bot 객체가 생성됨
updates = bot.get_updates() # 신규 메세지들을 업데이트
여기서 token
은 아까 발급받은 HTTP API
에 접근할 수 있는 토큰이다.
보통 이런건 코드에 직접 적는거 보다 telegram_config
같이 별도 파일로 관리하는 것이 좋다.
telegram_config = {}
with open('./telegram_config', 'r') as f:
configs = f.readlines()
for config in configs:
key, value = config.rstrip().split('=')
telegram_config[key] = value
token = telegram_config['token']
이런식으로 읽어오기. telegram_config
는 token=***********
이런식으로 구성을 해둔다. 그래서 따로 분리하는 과정이 위의 반복문에 나타나있음.
updates[-1].message.text
로 가장 최근에 보낸 메세지를 확인할 수 있다. 인덱스가 [-1]
인 이유는 updates
에 메세지 객체가 계속 쌓이는데, 가장 최근거를 확인해야하니까!import telegram
bot = telegram.Bot(token)
bot.send_message(chat_id, msg)
import telegram
image_file = open(‘image_path’, ‘rb’)
bot.send_photo(chat_id, image_file)
import telegram
audio_file = open(‘audio_path’, ‘rb’)
bot.send_audio(chat_id, audio_file)
from SaveID import collect_new_ids, update_id_list
from SteamCrwaling import new_games_crawling
import telegram
from datetime import datetime
now = datetime.now()
telegram_config = {}
with open('telegram_config', 'r') as f:
configs = f.readlines()
for config in configs:
key, value = config.rstrip().split('=')
telegram_config[key] = value
token = telegram_config['token']
new_id = collect_new_ids('id_list.txt')
new_games = new_games_crawling(new_id)
bot = telegram.Bot(token)
if new_id == []:
bot.send_message(telegram_config['my_chat_id'], '신제품이 없습니다.')
else:
msg = str(now.year) + '년 ' + str(now.month) + '월 '+ str(now.day) +'일 신제품 입니다.\n'
for tt, req in new_games.items():
reqst = ''
for r in req:
reqst += r + '\n'
msg += tt + '\n' + reqst + '\n'
bot.send_message(telegram_config['my_chat_id'], msg)
update_id_list(new_id)
SaveID
, SteamCrawling
모듈은 스팀홈페이지 크롤링 파트에서 코딩한 모듈들이다.
이런식으로 코드를 작성하면
이쁘게 잘 온다.
잡 스케줄러를 사용하지 않았기 때문에 내가 저 코드를 실행해서 수동으로 전송한 것.
내 계획은 매일 n시에 이 코드를 실행시키고(잡 스케줄러를 통해) 메시지를 전송하고 나면 id_list
를 갱신하는 방식이다.
이로써 RPA실습은 모두 끝났다.
아마 다음주에 cron
배우고 나면 내 스팀홈페이지 크롤링 서브프로젝트도 완성이 될 듯 하다!