引言

在日常生活中,我们经常使用微信进行沟通、工作协作以及信息分享。然而,手动操作微信有时会显得效率低下,尤其是在需要处理大量信息或进行自动化任务时。幸运的是,Python的wxpy库为我们提供了一个强大的工具,能够实现微信的自动化操作,如发送消息、接收通知、管理联系人等。

编写代码

接下来,我们将编写一段简单的代码来实现使用wxpy向微信好友发送消息的功能。

import wxpy

# 初始化机器人
bot = wxpy.Bot()

# 搜索并选择好友(这里以“filehelper”为例)
my_friend = bot.friends().search('filehelper')[0]

# 发送消息
my_friend.send('Hello, wxpy!')

# 运行wxpy的嵌入式GUI,以便进行交互式操作
wxpy.embed()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
运行与调试

运行上述代码之前,请确保你的微信账户已经在电脑上登录过,并且微信网页版可以正常访问。首次运行wxpy时,它将打开一个浏览器窗口,要求你扫描二维码进行登录。登录后,你可以看到代码中发送的消息。

与智能AI结合

直接看代码:

import itchat
from zhipuai import ZhipuAI
from itchat.content import TEXT, PICTURE

# 智谱AI开放平台:https://open.bigmodel.cn/overview
client = ZhipuAI(api_key="wwwwwwwwwwwwwwwwwwwwwwwwwww")  # 请填写您自己的APIKey


def get_reply(context):
    try:
        response = client.chat.completions.create(
            model="charglm-3",  # 填写需要调用的模型名称
            meta={
                "user_info": "30岁的男性软件工程师,兴趣包括阅读、徒步和编程",
                "bot_info": "Emohaa是一款基于Hill助人理论的情感支持AI,拥有专业的心理咨询话术能力",
                "bot_name": "charglm",
                "user_name": "老铁"
            },
            messages=[
                {
                    "role": "assistant",
                    "content": "你好,我是老铁,很高兴见到你。请问有什么我可以帮忙的吗?"
                },
                {
                    "role": "user",
                    "content": context
                }
            ]
        )
        print(response.choices[0].message)
        return response.choices[0].message.content
    except:
        return "opps, 我还很笨,不造你在说啥"


@itchat.msg_register(TEXT, isFriendChat=True)
def auto_reply(msg):
    reply = "execuse me?"
    try:
        # 查找发送者信息
        sender = itchat.search_friends(userName=msg['FromUserName'])

        # 如果找到了发送者
        if sender is not None:
            sender_name = sender['NickName']
        else:
            sender_name = '未知用户'

        print(sender_name)
        if sender_name != '清天':
            return ""
        reply = get_reply(msg.text)
        reply = reply.replace('\n', "")
        return reply
    except Exception as e:
        print(e)


itchat.auto_login(hotReload=True)
itchat.run()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
安装wxpy

首先,确保你的Python环境已经搭建好。接下来,我们需要安装必要的库。由于wxpy依赖于itchat,我们需要按特定顺序安装它们,以确保兼容性。以下是安装步骤:

pip install itchat==1.3.10   先安装
pip install itchat-uos==1.5.0.dev0   后安装
pip install wxpy==0.3.9.8
  • 1.
  • 2.
  • 3.

注意:在itchat/components/login.py文件的第59行添加time.sleep(15),这是为了避免扫码登录时出现失效的情况。