📜  在Python上构建 WhatsApp 机器人

📅  最后修改于: 2022-05-13 01:55:05.766000             🧑  作者: Mango

在Python上构建 WhatsApp 机器人

WhatsApp 机器人是一种应用软件,能够以口头或书面方式与人类进行交流。今天我们将学习如何使用Python创建一个 WhatsApp 机器人。首先,让我们看看使用Python语言构建 WhatsApp 机器人的要求。

系统要求:

  • 一个 Twilio 帐户和一部安装了有效电话号码和 WhatsApp 的智能手机。
  • 必须在系统中安装Python 3.9 或更新版本。
  • Flask:我们将使用Flask创建一个 Web 应用程序,用它来响应传入的 WhatsApp 消息。
  • ngrok: Ngrok 将帮助我们将您系统上运行Flask 应用程序连接到 Twilio 可以连接到的公共 URL 。这对于聊天机器人的开发版本来说是必要的,因为您的计算机可能位于路由器或防火墙之后,因此无法在 Internet 上直接访问。

入门

步骤 1:使用Twilio WhatsApp API设置 Twilio 帐户

转到此链接并单击注册并开始构建按钮并填写您的详细信息并验证您的电子邮件 ID 和手机号码。

注册

登录后,从左侧菜单中选择开发选项,然后进一步选择消息主题,然后选择试用选项,最后单击发送 WhatsApp 消息。这将打开一个用于设置 WhatsApp 沙盒的新网页。

设置 Whatsapp 消息

第 2 步:配置 Twilio WhatsApp 沙盒,向此 WhatsApp 号码发送消息,其中包含秘密的唯一安全代码,如下图所示:



将以下格式的代码发送到以下号码:+14155238886

设置沙盒

现在,将密码发送到上面的 WhatsApp 消息,您将收到如下确认消息:

确认讯息

步骤3:开了终端,运行下面的命令来创建一个可怕Ç托利为机器人,以创建Python虚拟环境中,以安装所有必要的包。

  • 要创建目录并导航到该目录
mkdir geeks-bot && cd geeks-bot
  • 创建和激活Python虚拟环境:
python3 -m venv geek-bot-env && source geek-bot-env/bin/activate
  • 要安装 Twilio、flask 和 requests:
pip3 install twilio flask requests

以下是仅一行的上述命令:

输出:

设置文件夹结构

创建 Flask 聊天机器人服务以在本地运行机器人:

第 1 步:导入运行此 Flask 应用程序所需的必要文件。



Python3
from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse


Python3
from flask import request
  
incoming_msg = request.values.get('Body', '').lower()


Python3
from twilio.twiml.messaging_response import MessagingResponse
  
response = MessagingResponse()
msg = response.message()
msg.body('this is the response/reply  from the bot.)


Python3
# chatbot logic
def bot():
  
    # user input
    user_msg = request.values.get('Body', '').lower()
  
    # creating object of MessagingResponse
    response = MessagingResponse()
  
    # User Query
    q = user_msg + "geeksforgeeks.org"
  
    # list to store urls
    result = []
  
    # searching and storing urls
    for i in search(q, tld='co.in', num=6, stop=6, pause=2):
        result.append(i)
  
    # displaying result
    msg = response.message(f"--- Result for '{user_msg}' are  ---")
  
    msg = response.message(result[0])
    msg = response.message(result[1])
    msg = response.message(result[2])
    msg = response.message(result[3])
    msg = response.message(result[4])
  
    return str(response)


Python3
from flask import Flask
from googlesearch import search
import requests
from twilio.twiml.messaging_response import MessagingResponse
  
  
app = Flask(__name__)
  
@app.route("/", methods=["POST"])
  
# chatbot logic
def bot():
  
    # user input
    user_msg = request.values.get('Body', '').lower()
  
    # creating object of MessagingResponse
    response = MessagingResponse()
  
    # User Query
    q = user_msg + "geeksforgeeks.org"
  
    # list to store urls
    result = []
  
    # searching and storing urls
    for i in search(q, tld='co.in', num=6, stop=6, pause=2):
        result.append(i)
  
    # displaying result
    msg = response.message(f"--- Result for '{user_msg}' are  ---")
  
    msg = response.message(result[0])
    msg = response.message(result[1])
    msg = response.message(result[2])
    msg = response.message(result[3])
    msg = response.message(result[4])
  
    return str(response)
  
  
if __name__ == "__main__":
    app.run()


第二步:接收用户输入的消息并发送响应。我们可以使用“ Body ”键访问来自 POST 请求的有效负载中的用户响应。

蟒蛇3

from flask import request
  
incoming_msg = request.values.get('Body', '').lower()

为了向用户发送消息/响应,我们将使用 Twilio 的MessagingResponse()函数。

蟒蛇3

from twilio.twiml.messaging_response import MessagingResponse
  
response = MessagingResponse()
msg = response.message()
msg.body('this is the response/reply  from the bot.)

第 3 步:现在我们将构建聊天机器人逻辑,我们将要求用户输入他/她想学习的主题,然后我们将消息发送给机器人,机器人将搜索查询并回复geeksfogeeks与用户最相关的文章。

蟒蛇3

# chatbot logic
def bot():
  
    # user input
    user_msg = request.values.get('Body', '').lower()
  
    # creating object of MessagingResponse
    response = MessagingResponse()
  
    # User Query
    q = user_msg + "geeksforgeeks.org"
  
    # list to store urls
    result = []
  
    # searching and storing urls
    for i in search(q, tld='co.in', num=6, stop=6, pause=2):
        result.append(i)
  
    # displaying result
    msg = response.message(f"--- Result for '{user_msg}' are  ---")
  
    msg = response.message(result[0])
    msg = response.message(result[1])
    msg = response.message(result[2])
    msg = response.message(result[3])
    msg = response.message(result[4])
  
    return str(response)

在这里,在这个函数,使用user_msg将接收用户响应/查询。然后我们使用谷歌搜索谷歌搜索中获取用户查询的前 5 个链接,并将它们存储到一个名为result的列表中。之后,只需使用 Twilio 消息服务向用户发送前 5 个链接。

要运行机器人将遵循以下步骤:

首先,使用以下命令运行上述脚本:



python3 main2.py

输出

运行机器人脚本

其次,打开另一个终端窗口并运行以下命令启动 ngrok 服务器。

ngrok http 5000

输出:

我们必须做的第三步也是最后一步是在WhatsApp 沙盒设置中设置转发 URL 导航到以下链接并将转发 URL 粘贴到所选位置,然后单击保存。

链接: https : //www.twilio.com/console/sms/whatsapp/sandbox

在 Twilio 中设置 URL

下面是完整的实现:

在这里,我们已经导入了将在聊天机器人执行期间使用的所有必要库,然后我们将创建一个称为机器人的函数,我们将在其中实现我们的聊天机器人逻辑。在 bot函数,首先,我们获取用户使用 WhatsApp 做出的响应并将其保存到名为 user_msg 的变量中。之后我们创建了一个 MessagingResponse() 对象,我们需要它来使用 WhatsApp 向用户发送回复。我们在用户查询后附加“geeksforgeeks.org”这个词,因为我们已经针对可能有研究相关查询的用户制作了这个机器人,他/她可以提出与研究相关的任何疑问。之后,我们创建了一个名为 result 的列表,我们将在其中保存必须发送给用户的 URL。我们使用谷歌搜索库进行谷歌搜索。使用 for 循环,我们获取前 5 个文章链接并将它们保存到结果中。使用 response.message()函数,我们只是通过 WhatsApp 将结果发送回用户。

蟒蛇3

from flask import Flask
from googlesearch import search
import requests
from twilio.twiml.messaging_response import MessagingResponse
  
  
app = Flask(__name__)
  
@app.route("/", methods=["POST"])
  
# chatbot logic
def bot():
  
    # user input
    user_msg = request.values.get('Body', '').lower()
  
    # creating object of MessagingResponse
    response = MessagingResponse()
  
    # User Query
    q = user_msg + "geeksforgeeks.org"
  
    # list to store urls
    result = []
  
    # searching and storing urls
    for i in search(q, tld='co.in', num=6, stop=6, pause=2):
        result.append(i)
  
    # displaying result
    msg = response.message(f"--- Result for '{user_msg}' are  ---")
  
    msg = response.message(result[0])
    msg = response.message(result[1])
    msg = response.message(result[2])
    msg = response.message(result[3])
    msg = response.message(result[4])
  
    return str(response)
  
  
if __name__ == "__main__":
    app.run()

输出: