【Python定时发送消息到微信】
前言
哔咘:“你看下明天天气呢?我好准备明天穿的衣服鞋子。”
叭卟没做回应,心想怎么又问啊,自己不知道看吗。
哔咘一个温柔的眼神,叭卟立刻回答道:“要得,天气预报马上看。”
......
于是乎,叭卟产生了一个大胆的想法——
整个自动发送天气预报的东东。哔咘一高兴,然后就可以...嘻嘻嘻嘻嘻嘻......
不用帮看天气预报了
故事讲完了,来,我们搞起!
1. 准备道具
1.1 天气预报和笑话key的获取
聚合数据注册免费的API:https://www.juhe.cn/docs/api/id/73
注册申请成功后,在【个人中心】查看自己的key(key_joke、key_weather)
1.2 天气灾害预警城市id和key的获取
https://id.qweather.com/和风天气注册免费账号:https://id.qweather.com/
登录后进入【应用管理】,新建应用 -添加Key(key_alarm)
预警城市id获取:https://dev.qweather.com/docs/api/geo/city-lookup/
1.3 企业微信相关id、Secret获取及设置
注册企业微信:https://work.weixin.qq.com/
进入【我的企业】,查看企业id(corpid)
【应用管理】新建应用,查看应用AgentId和Secret(agentid、appsecret)
查看应用Secret需要下载企业微信app,被邀请人不需要下载
【通讯录】中邀请微信好友,也可以通过企业微信app邀请
查看成员的账号(userid_list)
企业微信app【新消息通知】中关闭“仅在企业微信中接收消息”
不关闭的话微信端收不到消息哦
2. 搞起搞起
2.1 Python代码示例
2.1.1 配置文件(Config.py)
# -*- coding:utf-8 -*-# 天气预报及笑话参数
city = '重庆' # 要查询的城市——重庆
key_weather = '*************************' # 聚合数据的天气预报key
url_weather = 'http://apis.juhe.cn/simpleWeather/query' # 聚合数据的天气预报URL
key_joke = '*************************' # 聚合数据的笑话key
url_joke = 'http://v.juhe.cn/joke/randJoke.php' # 聚合数据的笑话URL
url_oneword = 'http://open.iciba.com/dsapi?' # 金山词霸每日一句URL# 天气灾害预警参数
cityid_CQ = 101040100 # 要查询的城市id,和风天气城市列表API文档:https://dev.qweather.com/docs/api/warning/weather-warning-city-list/
key_alarm = '*************************' # 和风天气的Key
url_alarm = 'https://devapi.qweather.com/v7/warning/now' # 和风天气灾害预警URL
url_alarm_text = 'https://weather.cma.cn/web/channel-380.html' # 中国气象局每日天气提示URL# 企业微信参数
corpid = '***************' # 企业的id
agentid = ******** # 应用的id
appsecret = '*************************' # 应用的Secret
userid_list = ['********', '********'] # 企业成员的账号,即要发送给的好友列表
userid_str = '|'.join(userid_list) # 企业微信格式要求
url_token = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken' # 企业微信token获取URL
url_send = 'https://qyapi.weixin.qq.com/cgi-bin/message/send' # 企业微信发送消息URL
2.1.2 获取现在的时间和明天是星期几(GetTime.py)
# -*- coding:utf-8 -*-import datetime# 获取现在的时间和明天是星期几
def get_time():time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')time_tomorrow = (datetime.timedelta(days=1) + datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')week_num = datetime.datetime.strptime(time_tomorrow, '%Y-%m-%d %H:%M:%S').weekday()week_list = ['一', '二', '三', '四', '五', '六', '日']week_tomorrow = '星期' + week_list[week_num]return time_now, week_tomorrow
2.1.3 从企业微信获取token(GetToken.py)
# -*- coding:utf-8 -*-import requests, json, Config# 参数-从Config文件引入
corpid = Config.corpid
appsecret = Config.appsecret
url_token = Config.url_token# 获取企业微信的token,API文档:https://open.work.weixin.qq.com/api/doc/90000/90135/91039
def get_token():response = requests.get(f'{url_token}?corpid={corpid}&corpsecret={appsecret}')data = json.loads(response.text)token = data['access_token']return token
2.1.4 获取天气预报并发送(SendWeather.py)
# -*- coding:utf-8 -*-import requests, json, traceback, Config
from GetToken import get_token
from GetTime import get_time# 参数-从Config文件引入
url_weather = Config.url_weather
key = Config.key_weather
city = Config.city
url_oneword = Config.url_oneword
corpid = Config.corpid
appsecret = Config.appsecret
userid = Config.userid_str
agentid = Config.agentid
url_send = Config.url_send# 聚合数据获取天气数据,API文档:https://www.juhe.cn/docs/api/id/73
def get_weather():params_weather = {'key': key, 'city': city} # 天气参数体response_weather = requests.get(url_weather,params=params_weather)r_weather = json.loads(response_weather.text) # 将返回的数据构造为json格式city_r = r_weather['result']['city'] # 城市date = r_weather['result']['future'][1]['date'] # 明天的日期tem = r_weather['result']['future'][1]['temperature'] # 明天的温度wea = r_weather['result']['future'][1]['weather'] # 明天的天气# 构造要发送消息的内容和格式title = '☀天气预报' + '\n'weather = title + ('%s %s\n%s: %s %s' % (date, get_time()[1], city_r, tem, wea)) \+ get_one_word() # 添加了金山词霸每日一句return weather# 金山词霸获取每日一句英文和中文内容,金山词霸开放平台API文档:http://open.iciba.com/index.php?c=wiki
def get_one_word():r_oneword = requests.get(url_oneword).json()content = r_oneword.get('content') + '\n' # 英文内容,这里添加了换行符note = r_oneword.get('note') # 中文内容oneword = '\n' + content + note # 每日一句的内容,添加了换行符return oneword# 通过企业微信发送天气预报,发送应用消息API文档:https://open.work.weixin.qq.com/api/doc/90000/90135/90236
def send_weather():msg_content = get_weather()json_data = {'touser': userid,'msgtype': 'text', # 消息类型:文本消息'agentid': agentid,'text': {'content': msg_content}} # 构造请求参数str_f = '发送天气预报失败!!'str_s = '发送天气预报成功!!'try:response_send = requests.post(f'{url_send}?access_token={get_token()}', json=json_data)r_wea = json.loads(response_send.text)if r_wea['errmsg'] == 'ok': # 判断消息是否发送成功print('%s %s' % (str_s, get_time()[0]))print('=' * 56)else:print('%s %s' % (str_f, get_time()[0]))print(r_wea)except Exception as err:print('%s %s' % (str_f, get_time()[0]))print(err.args)print('-' * 56)print(traceback.format_exc())if __name__ == '__main__':send_weather()
2.1.5 获取笑话并发送(SendJoke.py)
# -*- coding:utf-8 -*-import requests, json, traceback, Config
from GetToken import get_token
from GetTime import get_time# 参数-从Config文件引入
key = Config.key_joke
url = Config.url_joke
userid = Config.userid_str
agentid = Config.agentid
url_send = Config.url_send# 聚合数据获取笑话数据,API文档:https://www.juhe.cn/docs/api/id/95
def get_joke():params_joke = {'key': key}response_joke = requests.get(url, params=params_joke)r_joke = json.loads(response_joke.text)title_one = '\U0001F604一份开心:' + '\n'title_two = '\U0001F604两份快乐:' + '\n'# \U0001F604表情unicode编码详见:https://apps.timwhitlock.info/emoji/tables/unicode#block-6c-other-additional-symbolsjoke_one = r_joke['result'][0]['content'] + '\n\n' # 第一条笑话内容joke_two = r_joke['result'][1]['content'] # 第二条笑话内容# 要发送的笑话内容jokes = title_one + joke_one + title_two + joke_tworeturn jokes# 通过企业微信发送笑话,企业微信发送应用消息API文档:https://open.work.weixin.qq.com/api/doc/90000/90135/90236
def send_joke():msg_content = get_joke()json_data = {'touser': userid,'msgtype': "text", # 消息类型:文本消息'agentid': agentid,'text': {'content': msg_content}} # 构造请求参数str_f = '发送笑话失败!!'str_s = '发送笑话成功!!'try:response_joke = requests.post(f"{url_send}?access_token={get_token()}", json=json_data)r_joke = json.loads(response_joke.text)if r_joke['errmsg'] == 'ok': # 判断消息是否发送成功print('%s %s' % (str_s, get_time()[0]))print('=' * 56)else:print('%s %s' % (str_f, get_time()[0]))print(r_joke)except Exception as err:print('%s %s' % (str_f, get_time()[0]))print(err.args)print('-' * 56)print(traceback.format_exc())if __name__ == '__main__':send_joke()
2.1.6 获取天气灾害预警并发送(SendAlarm.py)
# -*- coding:utf-8 -*-import requests, json, traceback, Config
from GetToken import get_token
from GetTime import get_time# 参数-从Config文件引入
cityid = Config.cityid_CQ
url = Config.url_alarm
key = Config.key_alarm
url_alarm_text = Config.url_alarm_text
userid = Config.userid_str
agentid = Config.agentid
url_send = Config.url_send# 和风天气获取天气灾害预警数据,API文档:https://dev.qweather.com/docs/api/warning/weather-warning/
def get_alarm():try:alarm_content = 0 # 预警内容初始值:0response_alarm = requests.get(f'{url}?location={cityid}&key={key}') # 获取对应城市(cityid)的灾害预警r_alarm = json.loads(response_alarm.text)if r_alarm['warning'] != []: # 判断是否有天气灾害预警内容alarm_title = r_alarm['warning'][0]['title'] # 天气灾害预警的标题list = alarm_title.split('[') # 这里对返回的标题做了拆分处理title_head = list[0] # 灾害预警的名称title_tail = list[1].split(']')[0] # 灾害预警的等级alarm_type = r_alarm['warning'][0]['typeName'] # 灾害类型alarm_level = r_alarm['warning'][0]['level'] # 灾害颜色级别alarm_text = r_alarm['warning'][0]['text'] # 灾害详情内容# 构造要发送的天气灾害预警的内容和格式alarm_content = {'content': f'★{title_head}\n★ {title_tail}\n类型:{alarm_type}\n'f'级别:{alarm_level}\n详情:{alarm_text}\n更多:{url_alarm_text}'} # 添加了中国气象局每日天气提示的URLelse:print(f'目前没有天气灾害预警消息!! {get_time()[0]}')return alarm_contentexcept Exception as err:print(err.args)print('-' * 56)print(traceback.format_exc())# 通过企业微信发送天气灾害预警,发送应用消息API文档:https://open.work.weixin.qq.com/api/doc/90000/90135/90236
def send_alarm():content = get_alarm()json_data = {'touser': userid,'msgtype': 'text', # 消息类型:文本消息'agentid': agentid,'text': content} # 构造请求参数str_f = '发送天气灾害预警失败!!'str_s = '发送天气灾害预警成功!!'try:if content != 0: # 判断是否有天气灾害预警response = requests.post(f'{url_send}?access_token={get_token()}', json=json_data)r_alarm = json.loads(response.text)if r_alarm['errmsg'] == 'ok': # 判断消息是否发送成功print('%s %s' % (str_s, get_time()[0]))print('=' * 56)else:print('%s %s' % (str_f, get_time()[0]))print(r_alarm)except Exception as err:print('%s %s' % (str_f, get_time()[0]))print(err.args)print('-' * 56)print(traceback.format_exc())if __name__ == '__main__':send_alarm()
2.2 部署代码到Linux服务器
2.2.1 WinSCP工具将以上6个Python文件拷贝到Linux服务器中的同一个文件夹下
2.2.2 Linux 定时任务配置
crontab -e命令写入以下定时任务
crontab命令详解见参考资料2
Linux命令详解见参考资料3
# 每天6:26后台执行SendJoke.py并输出日志保存到SendJoke.log中
26 6 * * * nohup python3 -u /usr/local/pythonfiles/JokeWeather/SendJoke.py >> /usr/local/pythonfiles/JokeWeather/SendJoke.log 2>&1 &# 每天18:18后台执行SendAlarm.py并输出日志保存到SendAlarm.log中
18 18 * * * nohup python3 -u /usr/local/pythonfiles/JokeWeather/SendAlarm.py >> /usr/local/pythonfiles/JokeWeather/SendAlarm.log 2>&1 &# 每天21:18后台执行SendWeather.py并输出日志保存到SendWeather.log中
18 21 * * * nohup python3 -u /usr/local/pythonfiles/JokeWeather/SendWeather.py >> /usr/local/pythonfiles/JokeWeather/SendWeather.log 2>&1 &
3. 搞完收工
效果如下
参考资料
1. 利用Python实现企业微信发送文件消息_Lin_Xiao_Dai的博客-CSDN博客_python 企业微信发送文件
2. Linux定时运行Python脚本_孤影惆怅的博客-CSDN博客_linux定时运行python脚本
3. 如何让你的 Python 代码在腾讯云 Linux 中一直运行着_mukes的博客-CSDN博客
【Python定时发送消息到微信】相关推荐
- python 定时发送消息给微信好友
1.爬取爱情的文艺句子 import requests from lxml import etree import redef save_file(love_sentences):with open( ...
- chatgpt赋能python:Python如何发送消息到微信群?一步步教你实现
Python如何发送消息到微信群?一步步教你实现 在生活和工作中,我们用微信的频率越来越高,微信群也成了我们工作和社交中不可或缺的一部分.那么如何用Python来实现消息的自动发送到微信群呢?本文就为 ...
- 写一个python定时发送消息的脚本——每天跟你女盆友说晚安
首先 你要有个女朋友 效果 需要安装几个包 pip install wxpy pip install wechat_sender pip install requests 代码如下 from __fu ...
- python微信定时发消息_python实现给微信指定好友定时发送消息
微信如何在设定时间自动发送信息给指定好友 微信没有定时发送信息的功能,但是可以借助小程序. 世界上最遥远的距离,不是生与死,而是小编就站在你面前,你却不知道小编爱你. 打开微信之后在搜索小程序中输入蜗 ...
- Python微信操控itchat定时发送消息
前言 itchat是一个开源的个人微信接口,利用itchat可以实现例如微信自动回复,定时发送信息.详细可查看itchat项目文档,这里我只介绍一些简单的操作,并用10行代码完成定时发送消息. 安装 ...
- python 给QQ好友定时发送消息
python 给QQ好友定时发送消息 前言 初衷 代码 效果 后记 前言 在小编的上一篇python文章中提到了关于微信或者QQ的消息"轰炸"(其实我是想你也去看看,23333 [ ...
- 微信小程序订阅消息定时发送消息
微信小程序订阅消息定时发送消息 本人专注使用云开发,实现一个前端可以做后端以及整个项目的部署与上线. 如果觉得我讲的好就可以给我点个赞.也可以加我微信了解详情. 1.我们先要了解什么是订阅消息 而现在 ...
- 企业微信如何定时发送消息?
为了增进与客户之间的往来,提高客户活跃度,我们要与客户时刻保持接触.那么为了有计划的与客户保持联系,可不可以在企业微信中设置消息的定时发送呢? 实际上,企业微信无法定时发送消息,但我们可以通过使用第三 ...
- 使用python 定时发送微信信息给喜欢的人
原创 使用python 定时发送微信信息给喜欢的人 2019-11-08 16:34:18 冒牌技术小哥 阅读数 171 文章标签: python 更多 分类专栏: python 版权声明:本文为博主 ...
最新文章
- JAVA性能诊断与调优
- STM32(Cortex-M3)启动过程+IAR中xcl及icf文件详解
- 三十七、下篇 | tkinter实现一个翻译软件
- android 居右属性,使用layoutDirection属性设置布局靠左或靠右
- mariadb备份与恢复工具
- python3 xlrd包的用法
- JDK自带的int值的sun.text.IntHashtable
- 怎样网上赚钱最快方法有哪些?IP打造是关键
- 【JS逆向系列】某服务器平台sm系列算法分析
- 2019年世界500强完整榜单,出炉!
- 使用scapy 构造一个 特定Ether dmac 的报文
- android2.2 模拟器,网易MuMu模拟器2.2.29官方版
- Excel VBA语句集300
- 数据产品-数据化产品应用
- Mysql 民族数据库
- zookeeper为什么是CP原则
- connected components algorithm连通组件算法
- 计算机盘有百度云盘怎么删除文件,百度网盘的群内分享文件可以删除吗
- Neo4j 之 Cypher 语法(1)
- 【免杀】————1、PHP一句话过狗、卫士、D盾等免杀思路