-
[Python-Telegram-Bot v20.0] 메시지 전송 에러 해결Memo/Python 2023. 1. 13. 16:52
- 23.02.13
파이썬에서 텔레그램 메시지를 보내려면 json을 이용해 api로 전송하는 것을 추천드립니다.
공식 문서를 지원할 뿐만 아니라, 더욱 간결하고 에러 문제가 없습니다.
https://l22hs.tistory.com/31파이썬을 이용해 텔레그램 메시지를 전송하고 싶어, 여느때와 같이 구글링을 시작하였다.
블로그에 친절하게 잘 정리된 글을 보고 'Python-Telegram-Bot' 패키지를 설치하였다.
그러나 블로그에서 알려준 코드대로 작성해보았지만 계속해서 오류가 발생하였다.
# Error RuntimeWarning: coroutine 'Bot.send_message' was never awaited
여러 국내 블로그 자료를 뒤져보고, 계속 수정도 해봤지만 끝내 오류가 해결되지 않았다.
결국 해외 자료를 검색해보기 시작하였다.
검색 결과 정확히는 아니지만 'Python-Telegram-Bot' 20.0 버전 부터는 'asyncio' 즉 비동기 처리를 사용해야 한다는 것을 알 수 있었다.
Since v20.0, python-telegram-bot is built on top of Pythons asyncio module. Because asyncio is in general single-threaded, python-telegram-bot does currently not aim to be thread-safe.
- https://docs.python-telegram-bot.org/en/stable/index.html'비동기' 라는 것에 대해 전혀 모르고 있었던 나는 굉장히 당황스러웠다.
이후 asyncio와 관련된 소스코드를 찾다, 우리의 stackoverflow에서 정보를 얻을 수 있었다.
Python-Telegram-Bot 20.0버전 부터는 다음과 같이 작성하면 정상적으로 메시지를 전송할 수 있었다.
import telegram import asyncio token = "<token>" chat_id = "<id>" bot = telegram.Bot(token=token) async def send_message(message): await bot.send_message(chat_id=chat_id, text=f'{message}') msg = "Hello!" asyncio.run(send_message(msg))
나의 경우 위 소스코드로 메시지 전송에는 성공했지만, 메시지 전송 이후 'RuntimeError: Event loop is closed' 이라는 오류가 계속 발생하여 검색해보니 코드 한 줄을 추가해 해결할 수 있었다.
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) asyncio.run(send_message(msg))
우선 어찌저찌 메시지 전송에 성공은 했지만, 사실 이 방법이 올바른 방법인지는 모르겠다.
내가 못 찾은건지는 모르겠지만, 국내 자료에서 asyncio를 이용해 텔레그램 메시지를 전송하는 정보가 없는 것 같아 작성해보았다.
차후 비동기가 무엇인지와, 공식 문서에서 정확한 방법을 찾아봐야겠다.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback - Not using async
I have a piece of code to test that my implementation of the telegram bot is working in python. It works completely fine on my Windows 11 laptop, but when I run it on a Windows 2019 server, I get ...
stackoverflow.com
"Asyncio Event Loop is Closed" when getting loop
When trying to run the asyncio hello world code example given in the docs: import asyncio async def hello_world(): print("Hello World!") loop = asyncio.get_event_loop() # Blocking call which
stackoverflow.com
'Memo > Python' 카테고리의 다른 글
[Selenium] 요소 위치로 스크롤 이동하기 (0) 2023.01.25 [Selenium] 결과 값 텍스트가 빈칸(공백)으로 리턴될 때 (0) 2023.01.18 [Selenium] 코드 실행 후 브라우저가 자동으로 종료될 때 (0) 2023.01.17 [Selenium] 클릭 시 element not interactable 에러 (0) 2023.01.17 [Django] allauth form field label 지우기 (0) 2022.08.05