cluic / wxauto

Windows版本微信客户端(非网页版)自动化,可实现简单的发送、接收微信消息,简单微信机器人
MIT License
2.88k stars 465 forks source link

配合Bark实现实时消息推送(ios多开推送) #253

Open hubumulity opened 3 months ago

hubumulity commented 3 months ago

自己瞎写的

hubumulity commented 3 months ago

# -*- coding: utf-8 -*-

from wxauto import WeChat
import time
import requests
import json

# 初始化 WeChat 实例
wx = WeChat()

# 发送通知的函数
def send_notification(title, content):
    data = {
        "body": content,
        "title": title,
        "device_key": "123456789",
        "url": "weixinpro://",
        "icon": "https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_appwx_logo.png"
    }
    headers = {'Content-Type': 'application/json'}
    try:
        response = requests.post('https://api.day.app/push', data=json.dumps(data), headers=headers)
        response.raise_for_status()  # 检查请求是否成功
    except requests.exceptions.RequestException as e:
        print(f"Error sending notification: {e}")

# 设置检查新消息的时间间隔
wait_time = 1

# 无限循环检查新消息
while True:
    try:
        messages = wx.GetAllNewMessage()
        for sender, msgs in messages.items():
            for msg in msgs:
                send_notification(f"{sender}", f"{msg}")
    except Exception as e:
        print(f"An error occurred in the main loop: {e}")
    time.sleep(wait_time)

### 说明

- **编码声明**:指定文件使用 UTF-8 编码。
- **导入模块**:导入必要的模块,包括 `WeChat`, `time`, `requests` 和 `json`。
- **`send` 函数**:发送通知的函数,使用 `requests` 库发送 POST 请求,并使用 `json.dumps` 来序列化数据。增加了异常处理以捕获并打印请求中的错误。
- **主循环**:每隔 1 秒获取新的消息并发送通知。