Python实现微信每日定时发送晚安与每日一句
本文介绍如何使用Python编写微信机器人,通过wxpy库登录微信,结合金山词霸每日一句API获取英文及翻译内容。利用多线程Timer模块设定86400秒(1天)的定时任务,并加入随机延迟避免发送时间过于固定,实现每天自动向指定好友发送晚安及每日一句的功能。
项目背景与实现思路
当面对重复性任务时,利用程序进行自动化处理往往能提高效率。本文分享一个具体案例:通过Python脚本实现每天定时给女友发送微信“晚安”消息。考虑到单纯发送“晚安”可能略显单调,程序额外集成了金山词霸每日一句的爬取功能,获取对应的英文原文及中文翻译,从而丰富发送内容。整个过程通过设定定时器自动执行。
在开始编写代码之前,需要确保开发环境已安装必要的依赖库。
环境依赖安装
pip install wxpy
pip install requests
以下是实现该功能的核心代码逻辑。
核心代码实现
from __future__ import unicode_literals
from threading import Timer
from wxpy import *
import requests
import random
bot = Bot()
# linux执行登陆请调用下面的这句
#bot = Bot(console_qr=2,cache_path="botoo.pkl")
def get_news():
"""获取金山词霸每日一句,英文和翻译"""
url = "http://open.iciba.com/dsapi/"
r = requests.get(url)
content = r.json()['content']
note = r.json()['note']
return content, note
def send_news():
try:
contents = get_news()
# 你朋友的微信名称,不是备注,也不是微信帐号。
my_friend = bot.friends().search('fairy')[0]
my_friend.send(contents[0])
my_friend.send(contents[1])
my_friend.send(u"晚安")
# 每86400秒(1天),发送1次
t = Timer(86400, send_news)
# 为了防止时间太固定,于是决定对其加上随机数
ran_int = random.randint(0,100)
t = Timer(86400+ran_int,send_news)
t.start()
except:
# 你的微信名称,不是微信帐号。
my_friend = bot.friends().search('威风大侠')[0]
my_friend.send(u"今天消息发送失败了")
if __name__ == "__main__":
send_news()
运行效果展示
程序运行后的实际效果如下图所示。

以上内容即为本文的全部介绍,希望能为读者的学习提供有益参考。如果读者觉得内容有帮助,欢迎继续支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













