728x90
파이썬으로 간단한 텔레그램 봇을 만들어보자.
먼저 텔레그램 앱을 실행시켜 대화방에서 BotFather 검색한다.
대화창에 /newbot 을 통해 봇을 생성하고, 봇의 이름을 정한다.
봇의 계정명을 정한다. 계정명은 bot 으로 끝나야 한다.
성공적으로 계정 생성이 되었다.
이제 봇에게 본인의 아이디를 알려줘 나에게 메시지를 보낼 수 있게 한다.
방금 만들었던 봇을 검색한다.
파이썬 텔레그램 패키지를 설치한다.
(tfKeras) founder@hilbert:~$ pip install python-telegram-bot --upgrade
Collecting python-telegram-bot
Downloading https://files.pythonhosted.org/packages/84/6c/47932a4041ee76650ad1f45a80e1422077e1e99c08a4d7a61cfbe5393d41/python_telegram_bot-11.1.0-py2.py3-none-any.whl (326kB)
100% |████████████████████████████████| 327kB 21.7MB/s
Requirement already satisfied, skipping upgrade: cryptography in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from python-telegram-bot) (2.3.1)
Requirement already satisfied, skipping upgrade: certifi in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from python-telegram-bot) (2018.11.29)
Collecting future>=0.16.0 (from python-telegram-bot)
Downloading https://files.pythonhosted.org/packages/90/52/e20466b85000a181e1e144fd8305caf2cf475e2f9674e797b222f8105f5f/future-0.17.1.tar.gz (829kB)
100% |████████████████████████████████| 829kB 15.7MB/s
Requirement already satisfied, skipping upgrade: idna>=2.1 in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from cryptography->python-telegram-bot) (2.8)
Requirement already satisfied, skipping upgrade: asn1crypto>=0.21.0 in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from cryptography->python-telegram-bot) (0.24.0)
Requirement already satisfied, skipping upgrade: six>=1.4.1 in ./.local/lib/python3.6/site-packages (from cryptography->python-telegram-bot) (1.12.0)
Requirement already satisfied, skipping upgrade: cffi!=1.11.3,>=1.7 in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from cryptography->python-telegram-bot) (1.11.5)
Requirement already satisfied, skipping upgrade: pycparser in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from cffi!=1.11.3,>=1.7->cryptography->python-telegram-bot) (2.19)
Building wheels for collected packages: future
Running setup.py bdist_wheel for future ... done
Stored in directory: /home/founder/.cache/pip/wheels/0c/61/d2/d6b7317325828fbb39ee6ad559dbe4664d0896da4721bf379e
Successfully built future
주피터 노트북에서 다음과 같이 코드를 작성하고 실행한다.
import telegram
zoe_token = '123456748:ADHKJDIKD0D15GF50D5G05G'
zoe = telegram.Bot(token = zoe_token)
updates = zoe .getUpdates()
for u in updates:
print(u.message)
{'message_id': 1, 'date': 1550205116, 'chat': {'id': 123454657, 'type': .....................................
출력된 결과에서 id : 123454657 가 나의 ID 이다.
생성, 초기화, 메시지 종료 기능을 담고 있는 cutezoe_bot_model.py 을 다음과 같이 작성한다.
여기서 self.id 는 앞서본 id : 123454657 이다.
import telegram
from telegram.ext import Updater, CommandHandler
class TelegramBot:
def __init__(self, name, token):
self.core = telegram.Bot(token)
self.updater = Updater(token)
self.id = 141135473
self.name = name
def sendMessage(self, text):
self.core.sendMessage(chat_id = self.id, text=text)
def stop(self):
self.updater.start_polling()
self.updater.dispatcher.stop()
self.updater.job_queue.stop()
self.updater.stop()
class BotZoe(TelegramBot):
def __init__(self):
self.token = '1234154564:DHIDJIJID5D46D7D84D584DD45Dx0Y'
TelegramBot.__init__(self, '조', self.token)
self.updater.stop()
def add_handler(self, cmd, func):
self.updater.dispatcher.add_handler(CommandHandler(cmd, func))
def start(self):
self.sendMessage('봇이 잠에서 깨어납니다.')
self.updater.start_polling()
self.updater.idle()
다시 앞서 작성하던 노트북 셀로 돌아와 하단에 다음 코드를 추가한다.
import sys
import cutezoe_bot_model
def proc_rolling(bot, update):
zoe.sendMessage('데구르르..')
sound = firecracker()
zoe.sendMessage(sound)
zoe.sendMessage('르르..')
def proc_stop(bot, update):
zoe.sendMessage('봇이 잠듭니다.')
zoe.stop()
def firecracker():
return '팡팡!'
zoe = cutezoe_bot_model.BotZoe()
zoe.add_handler('rolling', proc_rolling)
zoe.add_handler('stop', proc_stop)
zoe.start()
이제 zoe 와 대화를 해보자.
참고
https://github.com/python-telegram-bot/python-telegram-bot/wiki/Extensions-%E2%80%93-Your-first-Bot
https://steemit.com/kr-dev/@maanya/30
728x90