Python 自动化微信机器人:实现天气推送 + 查看热搜 + 生成图片功能

部署运行你感兴趣的模型镜像

Python 自动化微信机器人:实现天气推送 + 查看热搜 + 生成图片功能

一、项目简介

这是一个基于 Python 的微信机器人项目,采用 wxauto 库接入 Windows 版微信应用,实现对指定联系人或群的监听和自动处理,包括以下功能:

  • 自动推送当前天气
  • 触发关键词答复:微博热搜抖音热搜百度热搜,历史上的今天舔狗日记,摸鱼
  • 下载图片或自动生成图片并发送

项目调用多个 API 成功实现信息推送和内容生成。


二、环境依赖

pip install wxauto requests
  • wxauto :进行 Windows 微信端接入和操控
  • requests :网络 API 请求

三、功能概览

1. 微信初始化

指定监听的联系人/群:

LISTEN_TARGETS = ["测试群1", "测试群2"]

2. 气象 API 接入

通过 HeWeather 提供的 API 获取当前天气:

def get_current_weather():
    url = f"https://你的API/v7/weather/now?location={LOCATION_ID}&key={API_KEY}"

3. 图片下载/生成

  • 接口:揭示最新潮图
  • 自动下载图片并发送
def download_moyu_image(path=IMG_PATH):
    resp = requests.get(MOYU_API, timeout=10)

4. 历史今日

获取历史上的重要事件

def today_of_history():
    url = "https://api.oick.cn/lishi/api.php"

5. 热搜榜单

支持抓取投音、微博、百度等热搜

def hot_search(Type):
    url = f"https://api.oick.cn/api/hot?type={Type}"

6. 生成图片

自定义文本发送到 API ,回返一张图片

def pictures(msg, msg2):
    resp = requests.get(PIC_API, params=params, timeout=20)

7. 注意事项

  • 系统需要安装 WeChat PC 版
  • wxauto 监听需要显示窗口

四、流程结构

1. 初始化监听
2. 检测到关键词
3. 分析内容
4. 调用 API 或 下载图片
5. 通过 wxauto 发送图文给对应群聊

五、主循环部分

while True:
    now = datetime.now()
    # 时间推送
    # 触发关键词处理
    msgs = wx.GetListenMessage()
    for chat, one_msgs in msgs.items():
        for msg in one_msgs:
            if TRIGGER_WORD in msg.content:
                download_moyu_image()
                wx.SendFiles(IMG_PATH, chat)
    time.sleep(5)

六、结论

这个项目基于 Python + wxauto 实现了非常实用的微信人工机器人。适合自己本地搭建搞着玩。

谢谢阅读,如有帮助请点赞 + 收藏 + 评论指教~


七、代码实现

import time
import requests
import os
from datetime import datetime
from wxauto import WeChat

# -------------------- 配置 --------------------

API_KEY = "天气key,用的和风天气"
LOCATION_ID = "101120101"  # 济南
LISTEN_TARGETS = ["测试群1", "测试群2"]  # 群或联系人名
MOYU_API = "https://api.vvhan.com/api/moyu"
TUI_API = "https://api.317ak.com/API/tp/hstp.php"
PIC_API = "https://api.suyanw.cn/api/hsjp/"
IMG_PATH = "moyu.jpg"
TUI_PATH = "tui.jpg"
PIC_PATH = "pic.jpg"

SEND_HOURS = [8, 12]
SEND_MINUTE = 0
TRIGGER_WORD = "摸鱼"
TRIGGER_WORD2 = "历史上的今天"
TRIGGER_WORD3 = "毒鸡汤"
TRIGGER_WORD4 = "舔狗日记"
TRIGGER_WORD5 = "抖音热搜"
TRIGGER_WORD6 = "微博热搜"
TRIGGER_WORD7 = "百度热搜"
TRIGGER_WORD9 = "看看腿"
TRIGGER_WORD10 = "生成图片"

# -------------------- 微信初始化 --------------------

wx = WeChat()
print("微信登录账号:", wx.nickname)

for who in LISTEN_TARGETS:
    wx.AddListenChat(who=who, savepic=False)
    print(f"正在监听:{who}")

# -------------------- 天气工具函数 --------------------

def format_time(qweather_time):
    try:
        dt = datetime.strptime(qweather_time[:16], "%Y-%m-%dT%H:%M")
        return dt.strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        return qweather_time

def get_current_weather():
    url = f"https://自己申请的地址/v7/weather/now?location={LOCATION_ID}&key={API_KEY}"
    try:
        resp = requests.get(url, timeout=10)
        data = resp.json()
    except Exception as e:
        return f"请求天气接口失败:{e}"

    if data.get("code") != "200":
        return f"获取天气失败,错误代码:{data.get('code')}"

    now = data["now"]
    formatted_time = format_time(data.get("updateTime", ""))
    return (
        f"【济南当前天气预报】\n"
        f"天气:{now['text']}\n"
        f"温度:{now['temp']}℃(体感 {now['feelsLike']}℃)\n"
        f"风向:{now['windDir']},风速:{now['windSpeed']} km/h\n"
        f"湿度:{now['humidity']}%\n"
        f"观测时间:{formatted_time}\n"
    )

# -------------------- 摸鱼图函数 --------------------

def download_moyu_image(path=IMG_PATH):
    try:
        resp = requests.get(MOYU_API, timeout=10)
        with open(path, "wb") as f:
            f.write(resp.content)
        print("摸鱼图下载成功")
        return True
    except Exception as e:
        print(f"下载失败:{e}")
        return False


# -------------------- 看看腿 --------------------

def download_tui_image(path=TUI_PATH):
    try:
        resp = requests.get(TUI_API, timeout=20)
        with open(path, "wb") as f:
            f.write(resp.content)
        print("摸鱼图下载成功")
        return True
    except Exception as e:
        print(f"下载失败:{e}")
        return False


# -------------------- 历史上的今天 --------------------

def today_of_history():
    url = "https://api.oick.cn/lishi/api.php"
    try:
        resp = requests.get(url, timeout=10)
        data = resp.json()
    except Exception as e:
        return f"请求接口出错:{e}"

    if data.get("code") != 200 or "result" not in data:
        return "无法获取历史内容,请稍后再试"

    day = data.get("day", "今日")
    events = data.get("result", [])

    # 构建历史事件文本
    message = [f"📜 历史的今天({day}):" ]
    for event in events[:10]:  # 最多展示前10条
        date = event.get("date", "")[:4]  # 截取年份
        title = event.get("title", "")
        message.append(f"- {date}年:{title}")

    return "\n".join(message)

# -------------------- 毒鸡汤 --------------------

def chicken_soup():
    url = "https://api.oick.cn/api/dutang"
    try:
        resp = requests.get(url, timeout=10)
        data = resp.json()
    except Exception as e:
        return f"请求接口出错:{e}"

    return data

# -------------------- 舔狗日记 --------------------

def doy_diary():
    url = "https://api.oick.cn/api/dog"
    try:
        resp = requests.get(url, timeout=10)
        data = resp.json()
    except Exception as e:
        return f"请求接口出错:{e}"

    return data

# -------------------- 热搜 --------------------

def hot_search(Type):
    url = f"https://api.oick.cn/api/hot?type={Type}"
    try:
        resp = requests.get(url, timeout=10)
        data = resp.json()
    except Exception as e:
        return f"请求热搜接口失败:{e}"

    if data.get("code") != 200:
        return f"获取热搜失败,错误代码:{data.get('code')}"



    title = data.get("title")
    events = data.get("data", [])

    # 构建历史事件文本
    message = [f"📜 热搜榜来源({title}):" ]
    for event in events[:15]:  # 最多展示前10条
        index = event.get("index", "")
        title1 = event.get("title", "")
        hot = event.get("hot", "")
        message.append(f"{index}{title1}(热度:{hot})")

    return "\n".join(message)

# -------------------- 生成图片 --------------------

def pictures(msg, msg2):
    try:
        params = {
            "rgb1": "52",
            "rgb2": "38",
            "rgb3": "39",
            "msg": msg,
            "msg1": msg2
        }

        resp = requests.get(PIC_API, params=params, timeout=20)

        if resp.status_code == 200 and resp.content:
            with open(PIC_PATH, "wb") as f:
                f.write(resp.content)
            return True
        else:
            print(f"请求失败,状态码:{resp.status_code}")
            return False

    except Exception as e:
        print(f"请求接口出错:{e}")
        return False




# -------------------- 主循环 --------------------

print("机器人已启动")

already_sent_flags = {hour: False for hour in SEND_HOURS}
wait_interval = 5

while True:
    now = datetime.now()
    current_hour = now.hour
    current_minute = now.minute

    # ===== 自动天气推送 =====
    for target_hour in SEND_HOURS:
        if current_hour == target_hour and current_minute == SEND_MINUTE:
            if not already_sent_flags[target_hour]:
                print(f"到达 {target_hour}:00,开始获取天气...")
                weather_msg = get_current_weather()
                for target in LISTEN_TARGETS:
                    wx.SendMsg(weather_msg, target)
                    print(f"已发送天气到 {target}")
                already_sent_flags[target_hour] = True
        if current_hour != target_hour:
            already_sent_flags[target_hour] = False

    # ===== 监听关键词消息 =====
    msgs = wx.GetListenMessage()
    for chat, one_msgs in msgs.items():
        for msg in one_msgs:
            print(f"收到消息:{msg.sender} - {msg.content}")

            if TRIGGER_WORD in msg.content:
                print("关键词“摸鱼”触发,准备发送摸鱼图...")
                if download_moyu_image():
                    target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                    wx.SendFiles(IMG_PATH, target)
                    print(f"已发送摸鱼图到 {target}")
                else:
                    print("图片下载失败")

            elif TRIGGER_WORD2 in msg.content:
                print("关键词“历史上的今天”触发,准备发送事件列表...")
                history_msg = today_of_history()
                target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                wx.SendMsg(history_msg, target)
                print(f"已发送历史事件到 {target}")

            elif TRIGGER_WORD3 in msg.content:
                print("关键词“毒鸡汤”触发,准备发送事件列表...")
                history_msg = chicken_soup()
                target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                wx.SendMsg(history_msg, target)
                print(f"已发送毒鸡汤到 {target}")

            elif TRIGGER_WORD4 in msg.content:
                print("关键词“舔狗日记”触发,准备发送事件列表...")
                history_msg = chicken_soup()
                target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                wx.SendMsg(history_msg, target)
                print(f"已发送舔狗日记到 {target}")


            elif TRIGGER_WORD5 in msg.content:
                print("关键词“热搜”触发,准备发送事件列表...")
                type = "douyin"
                history_msg = hot_search(type)
                target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                wx.SendMsg(history_msg, target)
                print(f"已发送舔狗日记到 {target}")

            elif TRIGGER_WORD6 in msg.content:
                print("关键词“热搜”触发,准备发送事件列表...")
                type = "weibo"
                history_msg = hot_search(type)
                target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                wx.SendMsg(history_msg, target)
                print(f"已发送舔狗日记到 {target}")

            elif TRIGGER_WORD7 in msg.content:
                print("关键词“热搜”触发,准备发送事件列表...")
                type = "baidu"
                history_msg = hot_search(type)
                target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                wx.SendMsg(history_msg, target)
                print(f"已发送舔狗日记到 {target}")

            elif TRIGGER_WORD9 in msg.content:
                print("关键词“看看退”触发,准备发送摸鱼图...")
                if download_tui_image():
                    target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                    wx.SendFiles(TUI_PATH, target)
                    print(f"已发送摸鱼图到 {target}")
                else:
                    print("图片下载失败")



            elif TRIGGER_WORD10 in msg.content:
                print("关键词“生成图片”触发,准备发送生成图...")
                try:
                    # 去掉触发关键词,提取后面的参数部分
                    content = msg.content.replace(TRIGGER_WORD10, '', 1).strip()
                    if "," in content:
                        param1, param2 = content.split(",", 1)
                        param1 = param1.strip()
                        param2 = param2.strip()
                        print(f"提取参数成功:param1 = '{param1}', param2 = '{param2}'")
                        if pictures(param1, param2):
                            target = next((g for g in LISTEN_TARGETS if g in str(chat)), '文件传输助手')
                            wx.SendFiles(PIC_PATH, target)
                            print(f"已发送生成图到 {target}")
                        else:
                            print("图片生成失败")
                    else:
                        print("无法提取两个参数,请确保使用中文逗号“,”分隔")
                except Exception as e:
                    print(f"提取参数或生成图片时出错: {e}")

    time.sleep(wait_interval)

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值