Profile picture

[Python] 텔레그램 봇 명령어 등록하기 (python-telegram-bot==13.13)

JaehyoJJAng2023년 08월 21일

▶︎ 사전 준비

Telegram Bot이 생성되어 있어야 한다.

봇이 생성되어 있지 않다면 아래 블로그 글을 참고하여 봇을 생성하도록 하자.
https://blog.naver.com/monkeychoi/223185247922


▶︎ 개요

텔레그램 'BotFather' 봇을 통해 @lotto_bot을 만들고 해당 봇에 Python을 활용하여 로또 관련 다양한 로직(최근 로또 당첨 번호 조회, 다음 회차 로또 예측 번호 조회,로또 번호 저장 및 당첨 알림 등)을 등록하고
등록한 명령어를 선택해 봇에게 메시지로 요청을 보냄년 명령어에 해당하는 이벤트를 실행하는 봇을 만들고자 한다.

먼저 @lotto_bot에 명령어를 등록하고 @lotto_bot Command line에 잘 나오는지 확인을 해줘야 한다.

예를 들어, '/help'와 같은 명령어를 직접 입력해도 상관은 없다. '/help' 명령어를 메시지로 받아 '/help'와 맞는 명령어 이벤트를 싫행해주면 된다.


▶︎ 봇 작업

BotFather을 통하여 Telegram Bot이 생성 되어있는 상태라면, BotFather 봇을 실행시키고 '/mybots' 라고 입력하여 현재 내 봇 리스트를 출력해보도록 하자.
image


1. lotto_bot 선택 후, Edit Bot 클릭
image


2. Edit Commands 클릭
image
'Edit Commands'는 우리가 특정 명령어를 등록 할 수 있는 등록 이벤트다. 'Edit Commands'를 클릭하면 위 이미지처럼 봇에 등록할 명령어 목록을 보내달라고 한다.
형식에 맞게 명령어를 입력하고 등록 요청을 해주자.


3. 특정 명령어와 설명 입력 후 요청.
image


4. @lotto_bot을 실행해 등록한 명령어 확인
image
BotFather 봇을 통해 내가 만든 @lotto_bot에 '/infos' 라는 명령어를 등록하였다.

이런식으로 내가 원하는 명령어들을 등록해주면 되고 해당 명령어들에 대한 이벤트 로직을 코드단에서 추가해주면 된다.


▶︎ 코드 작성

코드 작성에 들어가기 전에 먼저 필수 패키지를 설치해주도록 하자.

pip install python-telegram-bot==13.13

위에서 만든 /infos 명령어에 대한 이벤트 코드를 작성해보도록 하자.

handler.py

from telegram import Update
from telegram.ext import Updater,CommandHandler,CallbackContext
from utilities.token import get_token
import telegram

class Handler():
    def __init__(self,token: str) -> None:
        self.updater = Updater(token)
        self.dispatcher = self.updater.dispatcher
    
    def run(self) -> None:
        # 봇 시작
        self.updater.start_polling()
        self.updater.idle()

    def set_handler(self) -> None:        
        # /infos 명령어 핸들러 등록
        self.dispatcher.add_handler(CommandHandler('infos',self.infos))
    
    def infos(self,update: Update, context: CallbackContext) -> None:
        update.message.reply_text('로또 봇 입니다!')

# Token file
_TOKEN_FILE : str = '/Users/jaehyolee/tokens/telegram/token.ini'

# Get token
_TOKEN : str = get_token(token_file=_TOKEN_FILE)

handler : Handler = Handler(token=_TOKEN)
handler.set_handler()
handler.run()

‣ 마크다운 메시지 작성

update로 메시지를 보낼 때 마크다운 문법으로 메시지를 보내고 싶다면 아래와 같이 해보자.

...

class Handler():
    ...  
    def infos(self,update: Update, context: CallbackContext) -> None:
        reply_text: str = f"1116회차 로또 당첨 번호 조회```당첨번호\n15  16  17  25  30```"
        update.message.reply_text(
            text=reply_text,
            parse_mode=ParseMode.MARKDOWN_V2
        )

...

위 코드를 실행하고 텔레그램에서 /infos 명령을 실행하면 아래와 같은 응답 결과가 나올 것이다.
image


Loading script...