个性化阅读
专注于IT技术分析

建立你的第一个电报机器人:分步指南

本文概述

聊天机器人通常被吹捧为用户与技术和企业交互方式的一场革命。与传统应用程序相比, 它们具有相当简单的界面, 因为它们仅要求用户聊天, 并且至少从理论上讲, 聊天机器人应理解并执行用户对其的要求。

许多行业正在将其客户服务转移到聊天机器人系统。这是因为与实际人类相比, 成本大幅下降, 而且还因为其坚固性和持续可用性。聊天机器人可提供一定程度的用户支持, 而无需支付大量额外费用。

如今, 聊天机器人已用于许多场景, 从诸如显示时间和天气数据之类的琐碎任务到诸如基本医疗诊断和客户沟通/支持之类的更复杂的操作。你可以设计一个聊天机器人, 以在客户询问有关你产品的某些问题时为你提供帮助, 也可以制作一个个人助理聊天机器人, 该机器人可以处理基本任务并提醒你何时去开会或去健身房。

部署聊天机器人的地方有很多选择, 最常见的用途之一是社交媒体平台, 因为大多数人会定期使用它们。即时消息应用程序也可以这样说, 但有一些警告。

Telegram是当今最受欢迎的IM平台之一, 因为它使你可以将消息存储在云中, 而不仅仅是设备上, 并且具有良好的多平台支持, 因为你可以在Android, iOS, Windows和其他平台上使用Telegram任何其他可以支持网络版本的平台。在Telegram上构建聊天机器人非常简单, 只需很少的步骤即可完成。聊天机器人可以集成到Telegram组和渠道中, 并且也可以独立工作。

在本教程中, 我们将创建一个Telegram机器人, 为你提供”可爱头像”的头像图像。我们的示例将涉及使用Flask构建机器人并将其部署在免费的Heroku服务器上。

要完成本教程, 你将需要在系统上安装Python 3以及Python编码技能。另外, 对应用程序的工作原理有一个很好的了解是很好的补充, 但不是必须的, 因为我们将详细介绍我们所介绍的大多数内容。你还需要在系统上安装Git。

当然, 本教程还需要一个电报帐户, 该帐户是免费的。你可以在这里注册。另外, 还需要一个Heroku帐户, 你可以在这里免费获得它。

使你的电报机器人栩栩如生

要在Telegram上创建聊天机器人, 你需要联系BotFather, BotFather本质上是一个用于创建其他机器人的机器人。

你需要的命令是/ newbot, 它会导致创建机器人的以下步骤:

电报机器人教程-屏幕截图示例

你的漫游器应具有两个属性:名称和用户名。该名称将显示给你的机器人, 而用户名将用于提及和共享。

选择你的漫游器名称和用户名(必须以” bot”结尾)后, 你将收到一条包含访问令牌的消息, 显然, 你需要保存访问令牌和用户名以备后用, 因为你将需要它们。

编写Chatbot逻辑

在本教程中, 我们将使用Ubuntu。对于Windows用户, 此处的大多数命令都可以正常使用, 但是如果你在虚拟环境设置方面遇到任何问题, 请查阅此链接。对于Mac用户, 本教程应该可以正常工作。

首先, 让我们创建一个虚拟环境。它有助于将项目的需求与全局Python环境隔离开。

$ python -m venv botenv/

现在, 我们将拥有一个botenv /目录, 其中包含我们将要使用的所有Python库。继续并使用以下命令激活virtualenv:

$ source botenv/bin/activate

我们的机器人需要的库是:

  • Flask:一个用Python构建的微型Web框架。
  • Python-telegram-bot:Python中的Telegram包装器。
  • 请求:流行的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

在certificate.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对象, 该对象将用于我们需要bot执行的任何操作。

# start the flask app
app = Flask(__name__)

我们还需要将功能绑定到特定的路由。换句话说, 我们需要告诉Flask在调用特定地址时该怎么做。有关Flask和路线的更多详细信息, 请点击此处。

在我们的示例中, route函数响应一个基本上为/ {token}的URL, 这是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, 它为我们提供了一种让bot在消息被调用时调用服务器的方式, 这样我们就无需让服务器陷入等待消息的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仪表板上, 创建一个新应用。完成后, 它将引导你进入Deploy页面。然后, 在新窗口中打开”设置”标签, 然后复制应用程序的域(类似于https://appname.herokuapp.com/), 然后将其粘贴到凭据.py中的URL变量中。

Heroku仪表板屏幕截图

现在, 返回到”部署”选项卡并继续执行以下步骤:

注意:Windows和macOS用户可以按照此处描述的步骤进行操作。

登录到Heroku:

$ heroku 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设置正常, 则意味着你已经准备好开始!

现在去和你的机器人说话

实时版Telegram聊天机器人

机器人的实时版本

画龙点睛, 技巧和窍门

现在, 无需任何干预, 你就可以24/7全天候启动和运行Telegram机器人。你可以向机器人添加所需的任何逻辑, 例如, 可以通过添加”键入”状态并发送照片状态来使机器人更逼真, 如下所示:

response()函数的下一个代码段:

   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机器人-你所需要做的就是将逻辑集成到response()函数中。例如, 你的逻辑可以在单独的模块中, 并且可以像这样在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!"

现在将其导入app.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 Telegram Bot文档
赞(0)
未经允许不得转载:srcmini » 建立你的第一个电报机器人:分步指南

评论 抢沙发

评论前必须登录!