이전 글에서는 Python으로 코드를 짜서 텔레그램 봇으로 메시지를 보내는 기능을 구현하였다. 이번에는 텔레그램 봇으로 메시지를 보내는 것은 동일하되 정해진 시간마다 메시지를 보내는 기능을 추가하고자 한다.
Index
1. Python 코드
필자는 텔레그램 봇으로 각 시간마다 'plz'와 'test'라는 메시지가 보내지도록 코드를 짜서 Visual Studio Code로 실행해보았다.
import telegram, time
import aioschedule as sch
import asyncio as asy
bot = telegram.Bot(token='유저토큰')
chat_id = 채팅방ID
async def msg1():
await bot.send_message(chat_id, "PLZ")
asy.sleep(1)
async def msg2():
await bot.send_message(chat_id, "test")
asy.sleep(1)
sch.every(13).seconds.do(msg1)
sch.every(1).minutes.do(msg2)
loop = asy.get_event_loop()
while True:
loop.run_until_complete(sch.run_pending())
time.sleep(1)
그 결과, "DeprecationWarning: There is no current event loop loop = asy.get_event_loop()", "RuntimeWarning: coroutine 'sleep' was never awaited asy.sleep(1)" 등의 에러 메시지가 나오긴 했지만 제멋대로 메시지를 보내긴 했다... 비동기 함수에 대한 이해가 부족하여 어디서 손을 대야될지 막막해서 요즘에 핫한 ChatGPT의 손(?)을 빌리기로 하였다.
2. ChatGPT로 코드 수정
OpenAI사에서 개발한 ChatGPT는 다음과 같은 피드백을 주었다.
There are a few issues with your code. First, it looks like you're trying to use the asyncio and aioschedule libraries, but you're also using the time module to sleep, which is not compatible with asyncio.
Here's an updated version of your code that uses asyncio.sleep instead of time.sleep, and awaits the asyncio.sleep call to make sure it doesn't block other tasks:
<요약>
time 모듈과 asyncio는 호환되지 않고, sleep 앞에 asyncio를 넣어야 함.
ChatGPT의 코드는 아래를 참고하길 바란다. 놀라웠던 건 개인 토큰도 알아서 your_token으로 바꿔주었다는 것이다... 어떻게 알았냐??
import telegram
import aioschedule as sch
import asyncio as asy
bot = telegram.Bot(token='YOUR_TOKEN')
chat_id = 개인 chat_id
async def msg1():
await bot.send_message(chat_id, "PLZ")
await asy.sleep(1)
async def msg2():
await bot.send_message(chat_id, "test")
await asy.sleep(1)
sch.every(13).seconds.do(msg1)
sch.every(1).minutes.do(msg2)
loop = asy.get_event_loop()
while True:
loop.run_until_complete(sch.run_pending())
await asy.sleep(1)
코드 실행 결과, "SyntaxError: 'await' outside function"라는 메시지와 함께 에러가 발생하였다. 아직 ChatGPT가 완벽하진 않은 듯하다. 마지막줄의 await가 문제라 그걸 지우고 다시 시도해봐도 필자가 처음 작성한 코드의 결과와 딱히 차이점을 발견하지 못했다. 여전히 뭔가 충돌하며 문제를 일으킨다는 것을 확인했다. 그래도 소기의 성과는 텔레그램 봇으로 시간을 정해서 메시지를 보내는 것을 직접 실행해봤다는 점이다. 혹시 개선점을 발견한 고수분들께서는 댓글로 한마디 남겨주시면 후학에게 큰 도움이 될 테니 많은 관심 부탁드린다. 마지막으로 시도한 코드는 아래와 같다.
import telegram
import aioschedule as sch
import asyncio as asy
bot = telegram.Bot(token='???')
chat_id = ???
async def msg1():
await bot.send_message(chat_id, "test")
await asy.sleep(1)
# async def msg2():
# await bot.send_message(chat_id, "test")
# await asy.sleep(1)
# 현재 시간 기준 매 3시간 마다 매시 20분 00초에 메시지를 보냄.
sch.every(3).hours.at("20:00").do(msg1)
# sch.every(30).seconds.do(msg1)
# sch.every(1).minutes.do(msg2)
# 이벤트 루프 획득
loop = asy.get_event_loop()
while True:
loop.run_until_complete(sch.run_pending())
asy.sleep(1)
그리고 24시간 메시지를 보내는 봇을 작동시키기 위해서는 항시 운영되는 서버에 올려놓는 과정이 필요하다. AWS나 Azure, 구름IDE 등이 이러한 유형의 서비스를 제공하는 것으로 알고 있는데 대체로 유료 혹은 조건부 무료인데다 절차도 쉽지 않아서 필자는 다루지 않았음을 양해 바란다.
3. 참고
'Python > SNS BOT' 카테고리의 다른 글
[Python] 텔레그램 봇 생성 및 메시지 송신 (0) | 2023.02.19 |
---|