现在, 已知你有一个love.txt文件, 如下如所示:
通过利用 itchat 库,实现给你的微信好友自动发送消息。在这个函数中利用 datetime 来计算相识相恋的时间。并在登录的时候添加了一个「hotReload=True」,这样你就可以不用每次运行程序的时候都要登录。关于 itchat 更多的操作,大家可以去网上查找相应的资料。代码如下:
import datetime
import os
import itchat
def send_news(name):
# 计算相恋天数
# 相恋日期
inLoveDate = datetime.datetime(2019, 5, 20) # 相恋的时间
# 当前日期
todayDate = datetime.datetime.today()
# (当前日期-相恋日期)-并获取天数
inLoveDays = (todayDate - inLoveDate).days
# 获取情话
file_path = os.getcwd() + '/' + love_word_path
with open(file_path) as file:
love_word = file.readlines()[inLoveDays]
itchat.auto_login(hotReload=True) # 热启动,不需要多次扫码登录
my_friend = itchat.search_friends(name=name)
girlfriend = my_friend[0]["UserName"]
print(girlfriend)
message = """
亲爱的{}:
早上好,今天是和你相恋的第 {} 天~
今天想对你说的话是:
{}
最后也是最重要的 I LOVE U!
""".format(name, str(inLoveDays), love_word)
itchat.send(message, toUserName=girlfriend)
name = "小白"
love_word_path = 'love.txt'
send_news(name)
每天定时发送主要是用 while True 死循环简单的实现,通过判断当前的时间是否是你所需要发送的时间,来达到每天定时发送。
if __name__ == '__main__':
while True:
curr_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
love_time = curr_time.split(" ")[1]
if love_time == "05:20:00":
main()
time.sleep(60)
else:
print("爱你的每一天都是如此美妙,现在时间:" + love_time)
最终效果如下:
此次的程序还有很多可以继续添加的地方。比如对于发送的消息字段,我们还可以继续添加天气信息、星座信息、娱乐新闻、最近的趣事、最近好看的电影等等。只要你能想到的内容,都可以添加上去。发送图片也可以以同样的思路, 先通过爬虫下载到本地, 依次通过微信发送给好友.Bingo
这些信息在网上都可以获取的到,我们只要通过同样的思路,先抓取到本地,然后进行读取。当然如果你觉得存储本地会有被删的风险,那么你也可以保存到云端,在云端上进行存储。