構建您的第一個 Telegram 機器人:分步指南

已發表: 2022-03-11

聊天機器人經常被吹捧為用戶與技術和業務交互方式的一場革命。 與傳統應用程序相比,它們的界面相當簡單,因為它們只需要用戶聊天,而且聊天機器人應該理解並執行用戶對它們的任何要求,至少在理論上是這樣。

許多行業正在將他們的客戶服務轉移到聊天機器人系統。 這是因為與實際人類相比成本大幅下降,還因為穩健性和持續可用性。 聊天機器人無需大量額外成本即可提供一定程度的用戶支持。

今天,聊天機器人被用於許多場景,從顯示時間和天氣數據等瑣碎任務到基本醫療診斷和客戶溝通/支持等更複雜的操作。 您可以設計一個聊天機器人來幫助您的客戶詢問有關您的產品的某些問題,或者您可以製作一個可以處理基本任務並提醒您何時去會議或健身房的個人助理聊天機器人。

在部署聊天機器人的地方有很多選擇,最常見的用途之一是社交媒體平台,因為大多數人都會定期使用它們。 即時通訊應用程序也是如此,但有一些警告。

Telegram 是當今最受歡迎的 IM 平台之一,因為它允許您將消息存儲在雲上而不僅僅是您的設備上,並且它擁有良好的多平台支持,因為您可以在 Android、iOS、Windows 等平台上使用 Telegram任何其他可以支持網絡版本的平台。 在 Telegram 上構建聊天機器人非常簡單,只需幾個步驟,只需很少的時間即可完成。 聊天機器人可以集成到 Telegram 群組和頻道中,也可以獨立運行。

在本教程中,我們將創建一個 Telegram 機器人,為您提供來自 Adorable Avatars 的頭像圖像。 我們的示例將涉及使用 Flask 構建一個機器人並將其部署在免費的 Heroku 服務器上。

要完成本教程,您需要在系統上安裝 Python 3 以及 Python 編碼技能。 此外,對應用程序如何工作的良好理解將是一個很好的補充,但不是必須的,因為我們將詳細介紹大部分內容。 您還需要在系統上安裝 Git。

當然,教程還需要一個免費的 Telegram 賬號。 你可以在這裡註冊。 Heroku 帳戶也是必需的,您可以在這裡免費獲得。

讓您的 Telegram 機器人栩栩如生

要在 Telegram 上創建聊天機器人,您需要聯繫 BotFather,它本質上是一個用於創建其他機器人的機器人。

您需要的命令是/newbot ,它會導致以下步驟來創建您的機器人:

電報機器人教程 - 截圖示例

您的機器人應該有兩個屬性:名稱和用戶名。 該名稱將顯示在您的機器人中,而用戶名將用於提及和分享。

選擇您的機器人名稱和用戶名(必須以“bot”結尾)後,您將收到一條包含您的訪問令牌的消息,您顯然需要保存您的訪問令牌和用戶名以備後用,因為您將需要它們。

編碼聊天機器人邏輯

我們將在本教程中使用 Ubuntu。 對於 Windows 用戶,這裡的大多數命令都可以正常運行,但如果您在虛擬環境設置方面遇到任何問題,請查閱此鏈接。 對於 Mac 用戶,本教程應該可以正常工作。

首先,讓我們創建一個虛擬環境。 它有助於將您的項目需求與您的全球 Python 環境隔離開來。

 $ python -m venv botenv/

現在我們將有一個botenv/目錄,其中包含我們將使用的所有 Python 庫。 繼續並使用以下命令激活virtualenv

 $ source botenv/bin/activate

我們的機器人需要的庫是:

  • Flask:一個用 Python 構建的微型 Web 框架。
  • Python-telegram-bot:Python 中的 Telegram 包裝器。
  • Requests:一個流行的 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)

現在我們有了 bot 對象,它將用於我們需要機器人執行的任何操作。

 # start the flask app app = Flask(__name__)

我們還需要將函數綁定到特定的路由。 換句話說,我們需要告訴 Flask 在調用特定地址時要做什麼。 更多關於 Flask 和路由的詳細信息可以在這裡找到。

在我們的示例中,路由函數響應一個基本上是/{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,它為我們提供了一種讓機器人在調用消息時調用我們的服務器的方法,這樣我們就不需要讓我們的服務器在等待消息的 while 循環中受苦。

因此,我們將製作一個我們自己需要調用的函數來激活 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

現在你已經準備好你的需求文件了。

現在你需要Procfile告訴 Heroku 我們的應用程序從哪裡開始,所以創建一個Procfile文件並添加以下內容:

 web: gunicorn app:app

退回步驟:您可以將.gitignore文件添加到項目中,這樣不使用的文件就不會上傳到存儲庫。

在您的 Heroku 儀表板中,創建一個新應用程序。 完成後,它會將您定向到“部署”頁面。 然後,在新窗口中打開“設置”選項卡並複制應用程序的域,類似於https://appname.herokuapp.com/並將其粘貼到credentials.py內的 URL 變量中。

Heroku 儀表板屏幕截圖

現在,返回Deploy選項卡並繼續執行以下步驟:

注意: 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.

現在轉到應用程序頁面(您之前複製的域的鏈接)並添加到鏈接的末尾/setwebhook以便地址類似於https://appname.herokuapp.com/setwebhook 。 如果您看到webhook setup ok ,則表示您已準備就緒!

現在去和你的機器人說話

Telegram 聊天機器人的實時版本
機器人的實時版本

最後的潤色、提示和技巧

現在,您可以 24/7 全天候啟動並運行 Telegram 機器人,無需您的干預。 您可以向機器人添加任何您想要的邏輯,例如,您可以通過添加“打字”狀態並發送照片狀態來使您的機器人更加逼真,如下所示:

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 頁面上找到更多簡單的電報機器人示例。

您可以在我們的機器人的基礎上構建並使其成為下一個超級人工智能機器人——您需要做的就是將您的邏輯集成到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 機器人時玩得開心。

其他資源

  • 使用 Telegram 和 Python 構建聊天機器人
  • 輕鬆設置 Telegram Bot WebHook
  • Python-telegram-bot 存儲庫
  • 在 Heroku 上使用 Git 進行部署
  • Python 電報機器人文檔
相關:創建一個 WhatsApp 聊天機器人,而不是一個應用程序