构建您的第一个 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 聊天机器人,而不是一个应用程序