Python

[Python]파이썬 텔레그램 봇과 연동하는 방법: Telegram API Key 발급 및 메세지를 보내봅시다.

파이썬에서 텔레그램 봇과 연동하기위해서는 텔레그램 API KEY(토큰)를 생성해야합니다. 텔레그램 봇을 만들면 Telegram API Key는 저절로 생성됩니다. 사전 작업으로 텔레그램 앱을 설치 후 로그인 계정을 생성해야합니다. 어렵지않아요. 

텔레그램 봇 만들기

1. 텔레그램 앱을 실행 후 오른쪽에 독보기 아이콘을 클릭한 후 “botfather”를 검색합니다.

2. 첫번째에 있는 BotFather를 클릭합니다.


 

3. 하단에 START버튼을 클릭합니다.

4. 새로운 봇을 만들기위해  /newbot – create a new bot를 클릭 하거나 또는 메세지 입력 창에 /newbot를 타이핑 후 보내기를 해도 동일하게 동작하게 됩니다.


5. 본인이 원하는 봇 이름을 입력합니다. 이미 존재하는 동일한 이름의 봇이 존재할 경우 다른 이름으로 입력해야합니다.

저는 봇의 이름으로 ddolcat.bot을 등록하였습니다.  언제든지 /setname 명령어를 통해 변경가능합니다.

 

6. 사용자 이름을 입력합니다. 반드시 “bot”로 끝나야합니다. 제가 등록한 것들이 이미 등록되어 있어서 여러번 실패했습니다. 저는 “ddolcatBot”으로 설정이 되었습니다. 정상적으로 마무리가 되면 생성완료 축하 메세지와 함께 텔레그램 HTTP API에 접근할 수 있는 KEY가 발급됩니다. 절대 다른 사람들에게 노출하지마세요. 만약 노출이 되면 누군가가 당신의 봇을 마음대로 컨트롤하게 됩니다.

Use this token to access the HTTP API: 뒤에 있는 문자열이 API KEY입니다.

 

7. t.me/ddolcatBot를 클릭하거나 텔레그램의 메인 화면에서 독보기 버튼을 사용하여 내가 만든 봇의 이름으로 검색하여 내가 만든 봇으로 메세지를 보내봅니다. 


봇 생성은 완료되었습니다.

 

파이썬에서 텔레그램 봇에게 메세지 보내기

파이썬에서 텔레그램 봇을 접근하기 위해 먼저 라이브러리 설치가 필요합니다.

명령프롬프트창(cmd)을 열고 pip install telegram 명령어를 실행합니다. 저는  pip install wheel명령어를 실행하여 wheel모듈을 설치했습니다.

C:Usersilike>pip install telegram
Collecting telegram
  Downloading telegram-0.0.1.tar.gz (879 bytes)
Using legacy 'setup.py install' for telegram, since package 'wheel' is not installed.
Installing collected packages: telegram
    Running setup.py install for telegram ... done
Successfully installed telegram-0.0.1

C:Usersilike>pip install wheel
Collecting wheel
  Using cached wheel-0.36.2-py2.py3-none-any.whl (35 kB)
Installing collected packages: wheel
Successfully installed wheel-0.36.2

다음으로 pip install python-telegram-bot 명령어를 실행하여 python-telegram-bot 모듈을 설치합니다.

C:Usersilike>pip install python-telegram-bot
Collecting python-telegram-bot
  Downloading python_telegram_bot-13.1-py3-none-any.whl (422 kB)
     |████████████████████████████████| 422 kB 3.3 MB/s
Requirement already satisfied: pytz>=2018.6 in c:usersilikeappdatalocalprogramspythonpython39libsite-packages (from python-telegram-bot) (2020.4)
Requirement already satisfied: cryptography in c:usersilikeappdatalocalprogramspythonpython39libsite-packages (from python-telegram-bot) (3.3.1)
Requirement already satisfied: certifi in c:usersilikeappdatalocalprogramspythonpython39libsite-packages (from python-telegram-bot) (2020.12.5)
Collecting APScheduler==3.6.3
  Downloading APScheduler-3.6.3-py2.py3-none-any.whl (58 kB)
     |████████████████████████████████| 58 kB 3.8 MB/s
Requirement already satisfied: six>=1.4.0 in c:usersilikeappdataroamingpythonpython39site-packages (from APScheduler==3.6.3->python-telegram-bot) (1.15.0)
Requirement already satisfied: setuptools>=0.7 in c:usersilikeappdatalocalprogramspythonpython39libsite-packages (from APScheduler==3.6.3->python-telegram-bot) (51.1.1)
Collecting decorator>=4.4.0
  Downloading decorator-4.4.2-py2.py3-none-any.whl (9.2 kB)
Collecting tornado>=5.1
  Downloading tornado-6.1-cp39-cp39-win_amd64.whl (422 kB)
     |████████████████████████████████| 422 kB ...
Collecting tzlocal>=1.2
  Downloading tzlocal-2.1-py2.py3-none-any.whl (16 kB)
Requirement already satisfied: cffi>=1.12 in c:usersilikeappdatalocalprogramspythonpython39libsite-packages (from cryptography->python-telegram-bot) (1.14.4)
Requirement already satisfied: pycparser in c:usersilikeappdatalocalprogramspythonpython39libsite-packages (from cffi>=1.12->cryptography->python-telegram-bot) (2.20)
Installing collected packages: tzlocal, tornado, decorator, APScheduler, python-telegram-bot
Successfully installed APScheduler-3.6.3 decorator-4.4.2 python-telegram-bot-13.1 tornado-6.1 tzlocal-2.1

C:Usersilike>

참고로 모듈 업데이트 방법은 pip install python-telegram-bot –upgrade 처럼 pip 명령어 뒤에  –upgrade 옵션을 추가하면 현재 설치된 라이브러리의 업데이트가 진행됩니다.

 

메세지를 보내기위한 스크립트 먼저 살펴 봅니다. telegram모듈을 import 하여 봇에 접근할 수 있습니다. getUpdate()메서드를 사용하여 봇의 채팅창 메시지를 가져옵니다.  앞에서 만들었던 API KEY가 필요합니다.

import telegram
api_key = '본인의 api key'
bot = telegram.Bot(token=api_key)

for item in bot.getUpdates():
    print(item)

[스크립트 실행결과] getUpdate()를 실행시 오류가 발생할 수 도 있습니다. 이는 첫 API키 생성시에는 텔레그램 API 서버와의 연동에 약간의 딜레이가 있을 수 있습니다.

{'update_id': 346558346
    , 'message': {'message_id': 3, 'date': 1609878571
    , 'chat': {'id': 1********, 'type': 'private', 'first_name': '길동', 'last_name': '홍'}
    , 'text': '야', 'entities': [], 'caption_entities': []
    , 'photo': [], 'new_chat_members': [], 'new_chat_photo': []
    , 'delete_chat_photo': False, 'group_chat_created': False
    , 'supergroup_chat_created': False, 'channel_chat_created': False
    , 'from': {'id': 1********, 'first_name': '길동', 'is_bot': False
        , 'last_name': '홍', 'language_code': 'ko'}}}

‘chat’:{‘id’:1********** } 로 시작하는 부분의 id가 chat_id입니다. 챗봇에게 메세지를 보내기위해 필요합니다. 아래와 같이 sendMessage()메서드를 사용하여 메세지를 보낼 수 있습니다.

bot.sendMessage(chat_id='1********', text='방갑다')
bot.sendMessage(chat_id='1********', text='방갑다')
bot.sendMessage(chat_id='1********', text='몇살이냐?')

 

전체 스크립트는 다음과 같습니다.

import telegram
api_key = '본인의 api key'
bot = telegram.Bot(token=api_key)

for item in bot.getUpdates():
    print(item)

bot.sendMessage(chat_id='1********', text='방갑다')
bot.sendMessage(chat_id='1********', text='방갑다')
bot.sendMessage(chat_id='1********', text='몇살이냐?')

 

텔레그램 앱의 내가 만든 봇 창을 확인해봅니다.


 

봇에게 보낼 수 있는 것들이 어떤 것들이 있는지 살펴볼까요? 오디오파일, 문서, 위치, 사진, 애니메이션 등 많은 것들을 보낼 수 있습니다.


 

텔레그램 봇에게 사진(이미지) 보내는 방법

사진을 하나 보내볼까요?

send_phto()메서드를 사용하여 아이유 사진을 하나 보내봅니다.

import telegram

api_key = '본인의 api key'
bot = telegram.Bot(token=api_key)

# for item in bot.getUpdates():
#     print(item)

# bot.sendMessage(chat_id='1********', text='방갑다')
# bot.sendMessage(chat_id='1********', text='방갑다')
# bot.sendMessage(chat_id='1********', text='몇살이냐?')


img = "C:/Users/ilike/Pictures/IU_400x400.jpg"
bot.send_photo(chat_id='1335443076', photo=open(img, 'rb'))


 

텔레그램 봇에게 오디오파일(mp3,wav)을 보내는 방법

노래파일을 send_audio()메서드를 사용하여 보내봅니다.

import telegram
 
api_key = '본인의 api key'
bot = telegram.Bot(token=api_key)


# for item in bot.getUpdates():
#     print(item)
#
# bot.sendMessage(chat_id='1********', text='방갑다')
# bot.sendMessage(chat_id='1********', text='방갑다')
# bot.sendMessage(chat_id='1********', text='몇살이냐?')

#아이유 사진 보냄
# img = "C:/Users/ilike/Pictures/IU_400x400.jpg"
# bot.send_photo(chat_id='1335443076', photo=open(img, 'rb'))

mp3 = 'C:/Users/ilike/Music/054 아이유 - 밤편지.mp3'
bot.send_audio(chat_id='1335443076', audio=open(mp3, 'rb'))


 

깃허브 : github.com/python-telegram-bot/python-telegram-bot

 

python-telegram-bot/python-telegram-bot

We have made you a wrapper you can’t refuse. Contribute to python-telegram-bot/python-telegram-bot development by creating an account on GitHub.

github.com

core.telegram.org/bots/api

 

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

 

Leave a Reply

error: Content is protected !!