[파이썬/RPA] 텔레그램

seulzzang·2022년 9월 16일
0

파이썬/RPA

목록 보기
4/6
post-thumbnail

📍텔레그램 연동

  • python-telegram-bot 라이브러리 설치
  • pip install python-telegram-bot
  • @BotFather를 검색해서 가장 최상단에 인증마크가 달린 @BotFather로 시작한다.
    • /newbot을 입력하고 전송
    • 봇 이름 입력 ex) MyFirstAuto
    • bot으로 끝나는 이름 입력 ex) MyFirstAutoBot
    • HTTP API에 접근할 수 있는 토큰을 별도로 관리

💬텔레그램 채팅 ID 조회

  • 텔레그램에서 채팅을 하게되면 고유한 채팅 ID가 생기게 된다. 이를 통해서 그 채팅방으로 메시를 전송할 수 있게 한다.
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_configtoken=***********이런식으로 구성을 해둔다. 그래서 따로 분리하는 과정이 위의 반복문에 나타나있음.

  • updates[-1].message.text로 가장 최근에 보낸 메세지를 확인할 수 있다. 인덱스가 [-1]인 이유는 updates에 메세지 객체가 계속 쌓이는데, 가장 최근거를 확인해야하니까!

💬텔레그램 메시지 발송 함수

1. 문자메시지 보내기

import telegram

bot = telegram.Bot(token)
bot.send_message(chat_id, msg)

2. 이미지 보내기

import telegram

image_file = open(‘image_path’, ‘rb’)
bot.send_photo(chat_id, image_file)

3. 오디오 보내기

import telegram

audio_file = open(‘audio_path’, ‘rb’)
bot.send_audio(chat_id, audio_file)

📍실습6

  • 크롤링 프로그램을 활용해 텔레그램에 메시지를 발송하는 프로그램 개발
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배우고 나면 내 스팀홈페이지 크롤링 서브프로젝트도 완성이 될 듯 하다!

profile
중요한 것은 꺾이지 않는 마음

0개의 댓글