楔子:如果开发变成一件简单有趣也很有意义的事,你会不会也变得想去做呢?Python 可能不会感觉我在无中生有暗度陈仓凭空想象。
你可能想每天定时发送一条消息到企业微信工作群,来提醒同志们当天的任务和工作
你可能想创建一个企业微信机器人,解放人力,让它来替你做一些事情
你可能想定时发送一句心灵鸡汤、悄悄话、一句名言名句给TA
你可能如果有需要无中生有暗度陈仓凭空想象......
1. 自由极简
在指定时间后自动发送消息。
Timer(定时器)是 Thread 的派生类,用于在指定时间后调用一个方法。即可以控制指定函数在特定时间内执行一次。
import threading
def hello():
print("hello python")
# 指定2秒后执行hello函数
t = threading.Timer(2, hello)
t.start()
上面程序使用 Timer 延迟2秒后执行指定的 hello 函数。输出:hello python
但是,需求强调的是 Timer 只在指定时间(延时)后执行一次,如果要使用 Timer 控制函数多次重复执行,则需要多次再执行 Timer 调度:
from threading import Timer
import time
# 定义一个计数器,统计定时器需要执行的次数
count = 0
def print_time() :
global t, count
print("第 %s 次自动发消息,当前时间:%s" %(count, time.ctime()))
count += 1
# 制定一个只执行N次的定时调度
if count < 5 :
t = Timer(1, print_time)
t.start()
# 延迟1秒后自动执行指定函数
t = Timer(1, print_time)
t.start()
输出结果:
第 0 次自动发消息,当前时间:Mon Sep 2 14:54:42 2019
第 1 次自动发消息,当前时间:Mon Sep 2 14:54:43 2019
第 2 次自动发消息,当前时间:Mon Sep 2 14:54:44 2019
第 3 次自动发消息,当前时间:Mon Sep 2 14:54:45 2019
第 4 次自动发消息,当前时间:Mon Sep 2 14:54:46 2019
[Finished in 5.5s]
2. 自由进阶
利用 Timer 实现通过企业微信机器人每天给工作群定时发送消息。如下:
from threading import Timer
import requests
import random
import time
# 获取金山词霸每日一句英文和翻译
def get_news():
url = "http://open.iciba.com/dsapi/"
res = requests.get(url)
content = res.json()['content']
note = res.json()['note']
translation = res.json()['translation'].replace('小编的话', '美味书签')
return content, note, translation
# 文本类型消息
def send_msg_txt(content) :
headers = {"Content-Type" : "text/plain"}
send_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=69e3bed5-a20e-45be-9999-e30c0398c16c"
send_data = {
"msgtype": "text", # 消息类型,此时固定为text
"text": {
"content": content # 文本内容,最长不超过2048个字节,必须是utf8编码
}
}
requests.post(url = send_url, headers = headers, json = send_data)
# 自定义消息发送机制:每天自动推送消息
def send_msg_timer() :
global timer, count
contents = get_news()
for text in contents:
rand_sec = random.randint(1, 5) # 利用随机数让前后消息发送的时间间隔
time.sleep(rand_sec)
print("当前时间:%s,消息内容:%s" %(time.ctime(), text))
send_msg_txt(text)
# 定时发送消息:延迟一天(86400秒)发送消息到企业微信群
timer = Timer(86400, send_msg_timer)
timer.start()
当然,上面的代码只会执行一次,因为 Timer 只在指定时间(延时)后执行一次。
3. 自由进击
利用 schedule 实现通过企业微信机器人每天自动给工作群/员工群定时发送消息。如下:
from threading import Timer
import requests
import random
import time
import schedule
# 获取金山词霸每日一句英文和翻译
def get_news():
url = "http://open.iciba.com/dsapi/"
res = requests.get(url)
content = res.json()['content']
note = res.json()['note']
translation = res.json()['translation']
translation = translation.replace('小编的话', '进击物语')
return content, note, translation
# 文本类型消息
def send_msg_txt(content):
headers = {"Content-Type" : "text/plain"}
send_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3ac6a62e-443d-487e-9999-cbdaf4e1082b"
send_data = {
"msgtype": "text", # 消息类型,此时固定为text
"text": {
"content": content # 文本内容,最长不超过2048个字节,必须是utf8编码
}
}
requests.post(url = send_url, headers = headers, json = send_data)
def send_job():
contents = get_news()
for text in contents:
rand_sec = random.randint(1, 5) # 利用随机数让前后消息发送的时间产生延时
time.sleep(rand_sec)
# 打印下发送内容
print("当前时间:%s,消息内容:%s" %(time.ctime(), text))
send_msg_txt(text)
# 定时每天某个时刻执行一次job函数
schedule.every().day.at("17:30").do(send_job)
while True:
schedule.run_pending() # 确保schedule一直运行
time.sleep(2)
当然,再加工一下,自我发挥,就可以用来给女朋友、老婆、小哥哥小妹妹小朋友每天定时发消息,实现每日一句自动发送消息给喜欢的人,有木有暖暖的~
异常助手:
schedule 模块安装问题:ModuleNotFoundError: No module named 'schedule'
TAB 与空格问题:IndentationError: unindent does not match any outer indentation level