能用Python编写自动回复WhatsApp文本的程序吗?

能用Python编写自动回复WhatsApp文本的程序吗?

阅读更多:Python 教程

引言

WhatsApp 是全球最流行的即时通讯应用程序。使用 WhatsApp,我们可以在不同平台和操作系统之间发送消息,进行语音电话和视频通话等。在使用 WhatsApp 过程中,我们有时会遇到需要回复相同消息的情况,如问候语、感谢、问询及道歉等。继续手动回复显然是让人厌烦的过程,因此,我们可能想使用自动化机制来回复消息。本文将介绍如何使用Python编写自动回复WhatsApp文本的程序。

方案概述

下面是我将要使用的方案概述:

  • 使用 yowsup构建一个 WhatsApp 客户端,以便我们对其进行自动化操作。
  • 使用 Python 编写一个程序,该程序可以在运行时监视 WhatsApp 客户端,并对接收到的消息进行自动回复。

虽然这种方式需要对消息进行监视,但它对用户是不可见的,因此在用户界面上无感知。

yowsup

yowsup 是一个 Python 库,用于构建 WhatsApp 客户端。它提供了一个可以用来登录和配置 WhatsApp 帐户的 API。我们可以使用它来注册账户、发送文本和媒体消息,以及更多其他的 WhatsApp 功能。

要安装 yowsup,需要先安装 Python 3 和 pip 依赖管理器。安装完依赖后,可以通过以下命令安装 yowsup:

$ pip install yowsup2

手动登录到 WhatsApp

使用 yowsup 前,我们需要手动在 WhatsApp 上登录。由于 WhatsApp 实施了二次验证,我们需要通过向 WhatsApp 发送短信来获取验证码。此处有一些注意事项:

  • 需要给自己发送验证码。如果你把自己封锁了或自己已经阻止了你,则不会接收到验证码。
  • yowsup 自动化程序必须将 WhatsApp 的验证码发送回服务器以进行身份验证。确保您的 WhatsApp 安全且不受恶意攻击方面的威胁。

阅读 yowsup2 README 文件中的“安装 & 登录”部分,了解使用 yowsup 手动登录 WhatsApp 的指示。

一旦你已经登录 yowsup,就可以使用它的API进行 WhatsApp 的自动化操作。

编写 Python 脚本

在我们写 Python 脚本之前,需要先为想要收到自动回复的联系人、组或群聊创建一个数据库,每个数据库都应包含需要自动回复的消息。此处我们将使用 SQLite 数据库。

首先,我们创建了一个名为
“`whatsauto.db“` 的 SQLite 数据库文件,该文件将存储所有需要自动回复的消息。对于每个联系人、组或群聊,我们将创建一个表,其中包含不同的消息和示例代码。

代码示例:

import sqlite3

#打开数据库连接,如果不存在则会自动创建
conn = sqlite3.connect('whatsauto.db')

def create_table_chat(chat_id):
  conn.execute('''CREATE TABLE IF NOT EXISTS PS_''' + chat_id + '_messages
                 (ID INTEGER PRIMARY KEY AUTOINCREMENT,
                 MESSAGE_TEXT    TEXT);''')

def save_message(chat_id, message):
  conn.execute("INSERT INTO PS_" + chat_id + "_messages (MESSAGE_TEXT) VALUES ('" + message + "')")
  conn.commit()

def get_messages(chat_id):
  messages = []
  cursor = conn.execute("SELECT MESSAGE_TEXT FROM PS_" + chat_id + "_messages")
  for row in cursor:
       messages.append(row[0])
  return messages

在上面的代码示例中,我们定义了一个 create_table_chat() 函数,用于在创建新聊天时创建新表。然后,我们定义了一个 save_message() 函数,用于将消息存储到相应的表中。最后,我们定义了一个 get_messages() 函数,用于从表中获取消息列表。

接下来,我们创建一个新脚本文件 whatsapp_auto.py,并将以下代码添加到其中:

import yowsup
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.protocol_messages import YowMessagesProtocolLayer
from yowsup.layers import YowLayerEvent
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback

class WhatsAppAutoClient:

    def __init__(self, username, password):
        layers = (
            YowAuthenticationProtocolLayer,
            YowMessagesProtocolLayer
        )
        self.whatsapp = yowsup.Yowsup(username, password, layers)
        self.whatsappEventLoop = self.whatsapp.getLoop()
        self.add_event_handler(YowLayerEvent.EVENT_STATE_CONNECTING, self.onConnecting)
        self.add_event_handler(YowLayerEvent.EVENT_STATE_CONNECTED, self.onConnected)
        self.add_event_handler(YowLayerEvent.EVENT_STATE_DISCONNECTED, self.onDisconnected)
        self.add_event_handler(YowLayerEvent.EVENT_CONTACT_PROFILE_PICTURE_UPDATED, self.onProfilePictureUpdated)
        self.add_event_handler(YowLayerEvent.EVENT_CONTACT_PROFILE_UPDATED, self.onProfileUpdated)
        self.add_event_handler(YowLayerEvent.EVENT_GROUP_SUBJECT_UPDATED, self.onGroupSubjectUpdated)
        self.add_event_handler(YowLayerEvent.EVENT_MESSAGE, self.onMessage)

    def connect(self):
        self.whatsappEventLoop.run()

    def add_event_handler(self, event, callback):
        self.whatsapp.getLayerInterface().addEventHander(YowLayerEvent(event, callback))

    def onConnecting(self, layerEvent):
        print("Connecting to WhatsApp ...")

    def onConnected(self, layerEvent):
        print("Connected to WhatsApp ...")

    def onDisconnected(self, layerEvent):
        print("Disconnected to WhatsApp ...")

    def onProfilePictureUpdated(self, layerEvent):
        print("Profile Picture Updated")

    def onProfileUpdated(self, layerEvent):
        print("Profile Updated")

    def onGroupSubjectUpdated(self, layerEvent):
        print("Group Subject Updated")

    def onMessage(self, layerEvent):
        print(f"New Message:\n{layerEvent.getMessage()}")

        # 检查消息是否已经有自动回复
        chat_id = layerEvent.getFrom()
        message = layerEvent.getMessage().getBody()
        messages = get_messages(chat_id)
        if message in messages:
          # 发送自动回复
          self.whatsapp.send_message(chat_id, "自动回复:" + message)
        else:
          # 如果没有自动回复,保存此消息
          save_message(chat_id, message)

在上面的示例中,我们首先导入 yowsup 库,并引入 YowLayerEvent、YowAuthenticationProtocolLayer、YowNetworkLayer 和 YowMessagesProtocolLayer。然后,我们定义了一个名为 WhatsAppAutoClient 的类,该类包含连接、事件处理和自动回复消息等方法。最后,我们实例化 WhatsAppAutoClient 对象并执行 yowsup 事件循环。

接下来,我们需要添加以下代码,以初始化客户端并启动自动回复 WhatsApp 消息的功能:

if __name__ == '__main__':
    # 初始化客户端
    WA_USERNAME = "你的WhatsApp帐户手机号"
    WA_PASSWORD = "通过yowsup手动登录后获取的密钥"
    WA_AUTO_REPLY_MESSAGES = {"你的联系人手机号": ["你好", "谢谢"]}
    client = WhatsAppAutoClient(WA_USERNAME, WA_PASSWORD)

    # 启动自动回复功能
    for chat_id, messages in WA_AUTO_REPLY_MESSAGES.items():
        create_table_chat(chat_id)
        for message in messages:
            save_message(chat_id, message)

    # 连接到 WhatsApp
    client.connect()

在上面的示例中,我们首先定义了两个常量,即我们的 WhatsApp 帐户手机号和手动登录后获取的密钥。然后,我们定义了一个字典常量 WA_AUTO_REPLY_MESSAGES,其中包含需要自动回复的联系人手机号及其对应的消息列表。接着,我们通过循环将每个联系人的消息列表添加到数据库中,并创建与相应联系人的表格。最后,我们连接到 WhatsApp 并开始自动回复消息。

总结

在本文中,我们介绍了如何使用 Python 和 yowsup 构建 WhatsApp 客户端,并使用 SQLite 数据库存储需要自动回复的消息。通过将这些技术结合起来,我们可以编写一个自动回复 WhatsApp 消息的程序,帮助我们更高效地与朋友和家人交流。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程