첫 텔레그램 봇 구축: 단계별 가이드

게시 됨: 2022-03-11

챗봇은 종종 사용자가 기술 및 비즈니스와 상호 작용하는 방식의 혁명으로 선전됩니다. 사용자가 채팅하기만 하면 되며 챗봇은 최소한 이론상 사용자가 요구하는 것은 무엇이든 이해하고 수행해야 하기 때문에 기존 앱에 비해 인터페이스가 상당히 단순합니다.

많은 산업에서 고객 서비스를 챗봇 시스템으로 전환하고 있습니다. 이는 실제 사람에 비해 비용이 크게 감소하고 견고성과 지속적인 가용성 때문이기도 합니다. 챗봇은 상당한 추가 비용 없이 사용자 지원을 제공합니다.

오늘날 챗봇은 시간 및 날씨 데이터 표시와 같은 사소한 작업부터 기초적인 의료 진단 및 고객 커뮤니케이션/지원과 같은 보다 복잡한 작업에 이르기까지 다양한 시나리오에서 사용됩니다. 고객이 제품에 대해 특정 질문을 할 때 도움이 되는 챗봇을 고안하거나, 기본적인 작업을 처리하고 회의나 체육관에 가야 할 시간을 알려줄 수 있는 개인 비서 챗봇을 만들 수 있습니다.

챗봇을 배포할 수 있는 위치와 관련하여 많은 옵션이 있으며 대부분의 사람들이 정기적으로 사용하기 때문에 가장 일반적인 용도 중 하나는 소셜 미디어 플랫폼입니다. 몇 가지 주의 사항이 있지만 인스턴트 메시징 앱도 마찬가지입니다.

Telegram은 오늘날 가장 인기 있는 IM 플랫폼 중 하나입니다. 이 플랫폼을 사용하면 장치 대신 클라우드에 메시지를 저장할 수 있고 Android, iOS, Windows 등에서 Telegram을 사용할 수 있기 때문에 우수한 다중 플랫폼 지원을 자랑합니다. 웹 버전을 지원할 수 있는 다른 플랫폼. Telegram에서 챗봇을 구축하는 것은 매우 간단하며 완료하는 데 시간이 거의 걸리지 않는 몇 가지 단계가 필요합니다. 챗봇은 텔레그램 그룹 및 채널에 통합될 수 있으며 자체적으로도 작동합니다.

이 튜토리얼에서는 Adorable Avatars의 아바타 이미지를 제공하는 Telegram 봇을 만들 것입니다. 우리의 예는 Flask를 사용하여 봇을 구축하고 무료 Heroku 서버에 배포하는 것을 포함합니다.

이 튜토리얼을 완료하려면 시스템에 설치된 Python 3과 Python 코딩 기술이 필요합니다. 또한 앱이 어떻게 작동하는지 잘 이해하는 것이 도움이 될 수 있지만 우리가 제시하는 대부분의 내용을 자세히 다룰 것이기 때문에 필수는 아닙니다. 또한 시스템에 Git이 설치되어 있어야 합니다.

물론 튜토리얼에는 무료인 텔레그램 계정도 필요합니다. 여기에서 가입할 수 있습니다. Heroku 계정도 필요하며 여기에서 무료로 얻을 수 있습니다.

Telegram 봇에 생명 불어넣기

Telegram에서 챗봇을 만들려면 BotFather에 연락해야 합니다. BotFather는 본질적으로 다른 봇을 만드는 데 사용되는 봇입니다.

필요한 명령은 /newbot 으로 봇을 생성하기 위한 다음 단계로 이어집니다.

텔레그램 봇 튜토리얼 - 스크린샷 예시

봇에는 이름과 사용자 이름의 두 가지 속성이 있어야 합니다. 이름은 봇에 표시되고 사용자 이름은 멘션 및 공유에 사용됩니다.

봇 이름과 사용자 이름("bot"으로 끝나야 함)을 선택한 후 액세스 토큰이 포함된 메시지를 받게 되며 나중에 필요하므로 액세스 토큰과 사용자 이름을 저장해야 합니다.

챗봇 로직 코딩

이 튜토리얼에서는 Ubuntu를 사용할 것입니다. Windows 사용자의 경우 여기에 있는 대부분의 명령이 문제 없이 작동하지만 가상 환경 설정에 문제가 있는 경우 이 링크를 참조하십시오. Mac 사용자의 경우 이 튜토리얼은 잘 작동합니다.

먼저 가상 환경을 만들어 보겠습니다. 글로벌 Python 환경에서 프로젝트 요구 사항을 격리하는 데 도움이 됩니다.

 $ python -m venv botenv/

이제 우리는 우리가 사용할 모든 Python 라이브러리를 포함할 botenv/ 디렉토리를 갖게 될 것입니다. 다음 명령을 사용하여 virtualenv 를 활성화하십시오.

 $ source botenv/bin/activate

봇에 필요한 라이브러리는 다음과 같습니다.

  • Flask: Python으로 구축된 마이크로 웹 프레임워크.
  • Python-telegram-bot: Python의 텔레그램 래퍼.
  • 요청: 인기 있는 Python http 라이브러리.

다음과 같이 pip 명령을 사용하여 가상 환경에 설치할 수 있습니다.

 (telebot) $ pip install flask (telebot) $ pip install python-telegram-bot (telebot) $ pip install requests

이제 프로젝트 디렉토리를 찾아봅시다.

 . ├── app.py ├── telebot │ ├── credentials.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv

credentials.py 파일에는 세 가지 변수가 필요합니다.

 bot_token = "here goes your access token from BotFather" bot_user_name = "the username you entered" URL = "the heroku app link that we will create later"

이제 app.py로 돌아가서 코드를 단계별로 살펴보겠습니다.

 # import everything from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL
 global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN)

이제 봇이 수행해야 하는 모든 작업에 사용할 봇 개체가 있습니다.

 # start the flask app app = Flask(__name__)

또한 함수를 특정 경로에 바인딩해야 합니다. 즉, 특정 주소가 호출될 때 Flask에 무엇을 해야 하는지 알려야 합니다. Flask 및 경로에 대한 자세한 정보는 여기에서 찾을 수 있습니다.

이 예에서 route 함수는 기본적으로 /{token} 인 URL에 응답하며 이것은 Telegram이 봇에 보낸 메시지에 대한 응답을 얻기 위해 호출할 URL입니다.

 @app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok'

이 기능이 작동하도록 하는 직관적인 방법은 매초 호출하여 새 메시지가 도착했는지 여부를 확인하지만 그렇게 하지는 않을 것입니다. 대신에 메시지가 호출될 때마다 봇이 서버를 호출하도록 하는 방법을 제공하는 Webhook을 사용하여 메시지가 올 때까지 기다리는 동안 루프에 서버를 만들 필요가 없습니다.

따라서 Telegram의 Webhook을 활성화하기 위해 호출해야 하는 함수를 만들 것입니다. 기본적으로 Telegram에 새 메시지가 도착하면 특정 링크를 호출하도록 지시합니다. 봇을 처음 생성할 때 이 함수를 한 번만 호출합니다. 앱 링크를 변경하면 새로운 링크로 이 기능을 다시 실행해야 합니다.

여기의 경로는 무엇이든 될 수 있습니다. 당신은 그것을 부를 사람입니다 :

 @app.route('/setwebhook', methods=['GET', 'POST']) def set_webhook(): # we use the bot object to link the bot to our app which live # in the link provided by URL s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) # something to let us know things work if s: return "webhook setup ok" else: return "webhook setup failed"

이제 모든 것이 설정되었으므로 엔진이 작동 중임을 알 수 있도록 멋진 홈페이지를 만들어 보겠습니다.

 @app.route('/') def index(): return '.' if __name__ == '__main__': # note the threaded arg which allow # your app to have more than one thread app.run(threaded=True)

app.py의 전체 버전을 살펴보겠습니다.

 import re from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN) app = Flask(__name__) @app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok' @app.route('/set_webhook', methods=['GET', 'POST']) def set_webhook(): s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) if s: return "webhook setup ok" else: return "webhook setup failed" @app.route('/') def index(): return '.' if __name__ == '__main__': app.run(threaded=True)

이것이 튜토리얼에서 작성할 마지막 코드입니다. 이제 Heroku에서 앱을 시작하는 마지막 단계로 진행할 수 있습니다.

Heroku에서 앱 시작

앱을 만들기 전에 몇 가지가 필요합니다.

Heroku는 프로젝트에서 어떤 라이브러리를 사용하는지 알 수 없습니다. 따라서 우리는 requirements.txt 파일을 사용하여 알려야 합니다. 일반적인 문제는 요구사항의 철자를 틀리는 것이므로 주의해야 합니다. pip를 사용하여 요구사항 파일을 생성하려면 다음과 같이 하십시오.

 pip freeze > requirements.txt

이제 요구 사항 파일을 사용할 준비가 되었습니다.

이제 앱이 시작되는 위치를 Heroku에 알려주는 Procfile 이 필요하므로 Procfile 파일을 만들고 다음을 추가합니다.

 web: gunicorn app:app

반송 단계: .gitignore 파일을 프로젝트에 추가하여 사용하지 않는 파일이 저장소에 업로드되지 않도록 할 수 있습니다.

Heroku 대시보드에서 새 앱을 만듭니다. 그렇게 하면 배포 페이지로 이동합니다. 그런 다음 새 창에서 설정 탭을 열고 https://appname.herokuapp.com/ 과 같은 앱의 도메인을 복사하고 credentials.py 안의 URL 변수에 붙여넣습니다.

Heroku 대시보드 스크린샷

이제 배포 탭으로 돌아가 다음 단계를 진행합니다.

참고: Windows 및 macOS 사용자는 여기에 설명된 단계를 따를 수 있습니다.

Heroku에 로그인:

 $ heroku login

이 방법은 때때로 waiting for login 가 멈추는 경우가 있습니다. 이런 일이 발생하면 다음을 사용하여 로그인을 시도하십시오.

 $ heroku login -i

디렉토리에서 Git 리포지토리를 초기화합니다.

 $ git init $ heroku git:remote -a {heroku-project-name}

앱 배포:

 $ git add . $ git commit -m "first commit" $ git push heroku master

이 시점에서 터미널에서 건물 진행 상황을 볼 수 있습니다. 모든 것이 정상적으로 진행되면 다음과 같이 표시됩니다.

 remote: -----> Launching... remote: Released v6 remote: https://project-name.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done.

이제 앱 페이지(이전에 복사한 도메인의 링크)로 이동하여 링크의 끝에 추가하여 주소가 https://appname.herokuapp.com/setwebhook/setwebhook 도록 합니다. webhook setup ok 가 표시되면 준비가 된 것입니다!

이제 봇과 대화하세요.

텔레그램 챗봇의 라이브 버전
봇의 라이브 버전

마무리 손질, 팁 및 요령

이제 귀하의 개입 없이 Telegram 봇을 연중무휴 24시간 가동할 수 있습니다. 봇에 원하는 로직을 추가할 수 있습니다. 예를 들어 다음과 같이 "입력" 상태를 추가하고 사진 상태를 전송하여 봇을 보다 사실적으로 만들 수 있습니다.

respond() 함수의 다음 코드 스니펫:

 if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendChatAction(chat_id=chat_id, action="typing") sleep(1.5) bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendChatAction(chat_id=chat_id, action="upload_photo") sleep(2) bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

스 니펫에서 볼 수 있듯이 봇에 대한 정보를 텍스트 형식으로 보내려고 할 때 입력 작업을 추가하고 사진을 보내려고 할 때 사진 업로드 작업을 추가하여 봇을 보다 사실적으로 만들었습니다. . 더 많은 작업은 여기에서 찾을 수 있습니다.

BotFather 채널에서 봇 이미지와 설명을 변경하여 더 친근하게 만들 수도 있습니다.

전보 봇의 더 많은 간단한 예는 GitHub의 python-telegram-bot 페이지에서 찾을 수 있습니다.

우리의 봇을 기반으로 차세대 슈퍼 AI 봇으로 만들 수 있습니다. 당신이 해야 할 일은 당신의 로직을 respond() 함수에 통합하는 것입니다. 예를 들어 로직은 별도의 모듈에 있을 수 있으며 다음과 같이 respond() 함수 내부에서 호출할 수 있습니다.

 . ├── app.py ├── telebot │ ├── credentials.py │ ├──ai.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv

그리고 ai .py 내부:

 def generate_smart_reply(text): # here we can do all our work return "this is a smart reply from the ai!"

지금 .py에서 가져옵니다.

 import re from time import sleep from flask import Flask, request import telegram From telebot.ai import generate_smart_reply from telebot.credentials import bot_token, bot_user_name,URL

그런 다음 respond() 코드 내에서 호출하면 됩니다.

 def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # here call your smart reply message reply = generate_smart_reply(text) bot.sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)

이제 봇이 원하는 방식으로 작동하도록 할 수 있습니다. 다음으로 큰 일을 만들어 보세요!

첫 텔레그램 봇을 만드는 데 재미를 느끼셨기를 바랍니다.

추가 리소스

  • Telegram과 Python을 사용하여 챗봇 구축
  • Telegram Bot WebHook을 쉬운 방법으로 설정
  • Python-telegram-bot 저장소
  • Heroku에서 Git으로 배포하기
  • 파이썬 텔레그램 봇 문서
관련: 앱이 아닌 WhatsApp 챗봇 만들기