有的工作性质就是给指定客户发送一些内容,每次都要手动选择,很是繁琐,所以今天写了一个自动发送消息的脚本,运行脚本后扫码登录,登录进去即可定时发送。脚本内容如下:
import time
from wxpy import *
import schedule
import html # 添加 html 模块
# 初始化微信机器人
bot = Bot(cache_path=True, console_qr=True) # 添加 console_qr 参数方便扫码
# 定义要发送消息的好友列表
friends_to_message = ['好友1','好友2','好友n']
# 定义要发送的消息内容
message_to_send = "早上好哦~"
def send_messages():
"""发送消息给选定的好友"""
sent_count = 0
failed_count = 0
for friend_name in friends_to_message:
try:
# 查找好友
friend = bot.friends().search(friend_name)
if friend:
# 发送消息
friend[0].send(message_to_send)
print(f"已发送消息给: {friend_name}")
sent_count += 1
time.sleep(3) # 添加延迟避免发送过快
else:
print(f"未找到好友: {friend_name}")
failed_count += 1
except Exception as e:
print(f"发送给 {friend_name} 时出错: {str(e)}")
failed_count += 1
print(f"\n发送完成: 成功 {sent_count} 条, 失败 {failed_count} 条")
def job():
"""定时任务"""
print("\n开始执行定时发送任务...")
print(time.strftime("%Y-%m-%d %H:%M:%S"))
send_messages()
def main():
# 设置定时任务(这里设置为每天上午9点发送)
schedule.every().day.at("09:00").do(job)
#如果要立即发送
#job()
print("微信自动发送消息脚本已启动...")
print(f"将每天定时发送消息给以下好友: {', '.join(friends_to_message)}")
print("按 Ctrl+C 退出")
# 保持脚本运行
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n脚本已停止")
except Exception as e:
print(f"发生错误: {str(e)}")
finally:
bot.logout() # 退出登录
一、修改的内容有:
1、修改好友和发送内容
修改第10、13行,修改成你要发送的好友名字和需要发送的内容。
2、修改第50行,修改成你需要发送的那个时间点,图中写的是早上9点,可以修改为自己的发送时间。
二、环境
python使用的是python3.8.0,版本过高或者过低都会报错,requirements.txt里面的内容如下:
certifi==2025.1.31
charset-normalizer==3.4.1
future==1.0.0
idna==3.10
itchat==1.2.32
pypng==0.20220715.0
PyQRCode==1.2.1
requests==2.32.3
schedule==1.2.2
urllib3==2.2.3
wxpy==0.3.9.8
请详细按照此文件来安装第三方库,否则无法运行,感谢大家的围观,如果运行好了别忘了点赞,谢谢!