본문 바로가기
SW programming/Telegram bot 프로젝트

[Python 텔레그램 봇] python-telegram-bot 모듈이란?

by 고뭉나무 2021. 6. 17.

텔레그램 봇 Python 모듈

텔레그램 봇을 위한 Python 모듈이 여러 개 존재한다. 그 중 가장 많이 사용되는 모듈은 2가지 이며, telepot은 개발이 중단되어 지금은 python-telegram-bot을 쓰는 것이 좋다.

 

모듈 이름 웹 페이지 상태
telepot https://telepot.readthedocs.io/en/latest/ 개발 중단
python-telegram-bot https://python-telegram-bot.org/ 운영중

 

 

python-telegram-bot 설치

pip3 install python-telegram-bot

 

기본 코딩 - 봇에 메세지 보내기

import telegram

token = "token number"  #token 번호 - telegram 채팅창당 1개
bot = telegram.Bot(token)
bot.sendMessage(chat_id= 사용자 id, text="원하는 문구") #chat id - telegram 계정당 1개

 

#token 번호

BotFather에서 '/newbot'을 하여 새로운 채팅창을 만들면 HTTP API 정보를 알려준다.

그 뒤에 나오는 숫자와 영문 알파벳 조합들이 token 번호이다.

 

#chat id

아래의 코드로 텔레그램으로 봇에게 메세지를 전송하면 chat id를 출력해준다.

import telegram

token = "token number"
bot = telegram.Bot(token)
updates = bot.getUpdates()
print(updates[0].message.chat_id)

 

 

확장 구조 란?

만약 본인이 만든 프로그램이 User에게 메시지를 보낸다면 앞서 배운 내용으로도 충분하다.

예를 들면, 아래 포스팅의 내용들은 일방적으로 텔레그램에 메세지를 보내기만 한 것이다.

2021.06.06 - [SW programming/Python] - [Python 텔레그램 봇] 커뮤니티의 특정 '키워드'가 들어간 게시글 알림 받기

2021.06.15 - [SW programming/Python] - [Python 텔레그램 봇] '매일' '1시간 주기'로 단독 뉴스 전해주는 봇 만들기

 

하지만 사용자의 요청에 따라 어떤 동작을 하는 프로그램(예: 챗봇)을 만드려면 조금 더 복잡한 구조를 생각해야한다. python-telegram-bot 모듈에서는 이를 위해 Updater와 Dispatcher 객체를 사용한다.

이것 또한 과거에 포스팅한 적이 있다. 예시를 보면 더 이해가 빠를 테니 참고하면 좋다.

2021.05.02 - [SW programming/Python] - [Python 텔레그램 봇] - 원하는 지역의 날씨 정보 알림

2021.05.16 - [SW programming/Python] - [Python 텔레그램 봇] - I say '관심 기업', you say '기사 5개' 툭!

 

python-telegram-bot의 확장 구조, Updater와 Dispatcher

Updater는 사용자로부터 새로운 메시지가 왔는지를 주기적으로 확인한다. 이러한 방식으로 폴링(polling) 방식이라고 한다. 사용자로부터 어떤 명령어나 메시지가 왔다면 이를 Queue에 저장한다. Dispatcher는 Updater가 Queue에 넣어둔 사용자의 명령이나 메시지를 가져가서 처리하는 역할을 한다. 이때 각 요청에 대한 처리를 담당할 핸들러(Handler) 객체를 미리 지정해두고 요청이 들어오면 지정된 핸들러를 통해 처리한다.

 

 

일방적 구조의 코드

만약 아래와 같이 제작 프로그램이 일방적으로 User에게 메세지를 보내는 방식이라면,

python-telegram-bot의 일방적 구조

python-telegram-bot 모듈에서 'sendMessage' 함수만 이용하면 된다.

import telegram

token = "token number" 
bot = telegram.Bot(token)
bot.sendMessage(chat_id= 사용자 id, text="이렇게 하면 돼요. 쉽죠?")

 

확장 구조의 코드

그러나, 만약 위에서 설명한 확장 구조 방식이라면 아래의 코드를 따라야 한다.

from telegram.ext import Updater
from telegram.ext import CommandHandler

with open("./token.txt") as f:
    lines = f.readlines()
    token = lines[0].strip()

# updater 
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher


# command hander
def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")

start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

# polling
updater.start_polling()

위 코드에서 start_polling 함수가 호출되면 코드가 종료되지 않고 계속 수행된다. 프로그램은 계속해서 주기적으로 사용자의 메시지나 명령어가 있는지를 확인하는데 이러한 방식으로 폴링 방식이라고 했죠. 다음과 같이 /start command 명령어를 입력해봅니다. 앞서 지정한 CommandHandler에서 지정한 callback 함수인 start가 처리되면서 여러분에게 메시지를 보내는 것을 확인할 수 있다.

 

 

 

 

 

 

 

 

 

여기까지 python-telegram-bot 모듈의 일방적 구조와 확장 구조에 관해 알아보았습니다. 두 방식 모두 '메세지'라는 타입을 텔레그램에 전송하였습니다. 하지만 우리가 카카오톡으로 '사진', '동영상', '투표', '위치 정보' 등등을 전송하듯 '메세지' 뿐만 아니라 다른 형태의 타입을 전송할 수도 있습니다.

이들 또한 각자의 함수와 해당 인자가 따로 부여됩니다. 이에 대한 자세한 내용은 python-telegram-bot 공식 API 사이트에서 얻을 수 있습니다.

 

Telegram Bot API

https://core.telegram.org/bots/api#available-types

 

Telegram Bot API

The Bot API is an HTTP-based interface created for developers keen on building bots for Telegram. To learn how to create…

core.telegram.org

 

필요 인자에 대한 정보는 목차의 'Available types'에서, 함수 정보는 'Available methods'를 참고하시면 됩니다.

 

 

그리고 추가적으로 아래는 Telegram bot의 공식 사이트입니다. 이것 또한 참고하면 좋습니다 :)

https://core.telegram.org/bots

 

Bots: An introduction for developers

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands…

core.telegram.org

 

 

위 글이 도움이 되셨나면, 아래 하트를 눌러주세요↓

감사합니다 \( ˆoˆ )/​

반응형

댓글