AWS之基于Lambda和企业微信的消息推送功能实现
功能需求如下:
企业微信于每日下午5点自动发送学校教师本人次日课表安排。
架构
前提:Lambda可访问外网,且Lambda能访问RDS,为了同时满足以上两点,操作挺复杂的,踩了很多坑,大概就是RDS终端节点加进VPC,Lambda绑定VPC并添加为Lambda添加网关、子网、路由、安全组。
步骤说明
1.Lambda连接RDS,查询获取课表数据
import pymysql,datetime
import requests, json, os
db = pymysql.connect(host="",user="",password="",database="")
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute('select * from xxxxxx')
a = cursor.fetchall()
print(a)
2.Lambda代码请求https://qyapi.weixin.qq.com/cgi-bin/gettoken获取发消息的应用的token
def get_access_token():
params = {
'corpid': 见企业微信后台, #CORPID,CORPSECRET为企业微信应用识别参数,用这两个参数获取指定接口token。
'corpsecret': 见企业微信后台
}
resp = requests.get('https://qyapi.weixin.qq.com/cgi-bin/gettoken',params=params)
tk = json.loads(resp.text)['access_token']
return tk
3.Lambda代码发送正文至https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=‘步骤2的token’
msg = {
"touser": 接收人,
"toparty": "",
"totag": "",
"msgtype": "text",
"agentid": 见企业微信后台,
"text": {"content": 正文},
"safe": 0,
"enable_id_trans": 0,
"enable_duplicate_check": 0
}
tk = get_access_token()
msg_api = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + tk
resp = requests.post(url=msg_api, data=json.dumps(msg))
4.新建CloudWatch Events,每日定时触发该Lambda
5.CloudWatch查看Lambda日志,CloudWatch/日志组/aws/lambda/kcjktx