科技 economic
您现在的位置:首页 > 科技 > 有关构建第一个Telegram机器人的分步指南

新闻

化工事故年损百亿?谷东科技AR黑科技如何化险为夷? 化工事故年损百亿?谷东科技AR黑科技如何化险为夷?

化工行业年产值3.6万亿美元,背后却藏着触目惊心的安全隐患。数据显示,我国每年化工灾害事故高达百起,直...

  • 全国农技中心到广东调研智慧农业,丰农控股获高度认可

    3月19日至22日,全国农业技术推广中心组织浙江、山东、广西、四川、陕西、广东等省农技推广部门领导专家,调研广东智慧农业。调研组以现场查看、座谈交流等方式,聚焦智慧果园,深入走访广州、韶关、河源、惠州、...

  • 天自照明微孔交叉出光射灯照明行业新趋势

    天自照明首次在国内推广小孔出光射灯,凭借其在照明技术上的独特优势,一举推出6种结构,20款家族式矩阵小孔出光产品,全系列独立开模制造,利用交叉出光技术,通过特定的结构设计、光学设计、LED光源设计,充分...

  • 微软智能办公工具OfficePLUS让创作更轻松!PPT/Wor...

      近日,微软发布智能办公工具OfficePLUS V3.0版本。 全新升级的OfficePLUS V3.0新增了Excel插件,继已发布的PPT/Word插件之后, 完成了对Office核心使用场景的全方位覆盖,让用户拥有更加轻松的创作体验。 ...

科技

勇闯前人未至之境,Pimax Frontier 2022破界而来 勇闯前人未至之境,Pimax Frontier 2022破界而来

北京时间11月10日上午10点,小派科技将携又一款VR3.0力作在PimaxFrontier2022海外发布会正式亮相。去年...

  • G客 4力释放!耕升 GeForce RTX® 40系列GPU评测解...

    2022年9月20日,NVIDIAGTC 2022主题演讲在美国加利福尼亚州圣克拉拉举办。在本次主题演讲中,无数玩家和创作者们期待的GeForceRTX®40系列GPU和NVIDIA®DLSS 3正式发布,为玩家和创作者带来巨大的性能提升。 &n...

  • “破圈”的协作机器人|看越疆如何赋能新商业!

    协作机器人以革新的人机交互技术,打破了传统机器人应用场景的边界,由于安全易用,灵活智能等先天优势,协作机器人在越来越多的场景下释放出巨大潜能,从工业到商业应用快速延伸,势如破竹,触发了前所未有的机遇。 ...

  • 用高科技替代除草剂 保障粮产与食品“双安全”

    “新冠肺炎疫情迅速蔓延全球,一些国家和地区正在加强贸易管控。对于我国粮食安全同样带来严峻考验。”近日,在江苏扬州江都区宜陵镇北斗导航数字化精准化物理除草新技术现场会上,扬州大学机械工程学院张瑞宏教授...

有关构建第一个Telegram机器人的分步指南

发布时间:2020/05/28 科技 浏览:457

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

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

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

[阅读: 构建WhatsApp聊天机器人的开发人员指南 ]

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

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

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

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

要在Telegram上创建聊天机器人,您需要联系BotFather,它实际上是一个用于创建其他机器人的机器人。

您需要的命令将导致以下步骤来创建您的机器人: /newbot

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

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

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

编写聊天机器人逻辑

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

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

$ python -m venv botenv/

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

$ source botenv/bin/activate

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

Flask:一个用Python构建的微型Web框架。

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)

现在,我们有了bot对象,该对象将用于我们需要bot执行的任何操作。

# start the flask app

app = Flask(__name__)

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

在我们的示例中,route函数响应的URL基本上是,这是URL电报将调用以获取对发送到机器人的消息的响应。 /{token}

@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不知道您的项目使用什么库,因此我们必须使用文件来告诉它(一个常见的问题是您拼错了需求,所以要小心),要使用pip生成需求文件: requirements.txt

pip freeze > requirements.txt

现在,您的需求文件已准备就绪。

现在,您需要使用告诉Heroku我们的应用程序从哪里启动,因此创建一个文件并添加以下内容: Procfile Procfile

web: gunicorn app:app

退回步骤:您可以将文件添加到项目中,以便不要将没有使用的文件上载到资源库。 .gitignore

在Heroku 仪表板上,创建一个新应用。完成后,它将引导您进入Deploy页面。然后,在新窗口中打开“ 设置”标签,然后复制应用程序的域(将类似域)并将其粘贴到内的URL变量中。 https://appname.herokuapp.com/ credentials.py

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.

现在转到应用程序页面(您之前复制的域的链接),然后将其添加到链接的末尾,以 /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页面上找到许多更简单的电报机器人示例。

您可以在我们的机器人上构建基础,并使其成为下一个超级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)

现在,您可以按照自己想要的方式来运行您的机器人-继续前进,创造下一个大事!

姓 名:
邮箱
留 言: