Python发送微信模板消息

1、根据appid,secret获取token

2、查找粉丝

3、指定模板及粉丝id发送模板消息

4、链接SqlServer数据库获取消息任务

5、创建定时任务监听消息

python 复制代码
from logging import exception
import time
import pymysql
import datetime;
from utils.http_utils import *;
from model.msg_wx_model import *;
from threading import Timer

appid = "wx*****";
appsecret = "****";   
template_id = '9uWUl0evW9o5Q5KPbZaa4WxpXOsHN9V28vWPG2T**'     #模板id
token = "";


#查找公众号所有的粉丝
def findUser():
    url = f"https://api.weixin.qq.com/cgi-bin/user/get?access_token={token}&next_openid=";
    result = httpGet(url,"");
    print(result);
    for row in result["data"]["openid"]:
        print(row);
        url =  "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + row;
        jsonText = httpGet(url,"");
        print(jsonText);
        pass;

#指定粉丝发送模板消息
def send(userId, content):

    list = content.split('|');
    first = list[0]
    k1=list[1];
    k2=list[2];
    k3=list[3];
    k4=list[4];
    k5=list[5];
    remark = list[6];

    jsonstr =  "{'first':{ "\
                f"    'value':'{first}',"\
                "    'color':'#173177'"\
                "},"\
                "'keyword1': {"\
                f"    'value':'{k1}',"\
                "    'color':'#173177'"\
                "},"\
                "'keyword2': {"\
                f"    'value':'{k2}',"\
                "    'color':'#173177'"\
                "},"\
                "'keyword3': {"\
                f"    'value':'{k3}',"\
                "    'color':'#173177'"\
                "},"\
                "'keyword4': {"\
                f"    'value':'{k4}',"\
                "    'color':'#173177'"\
                "},"\
                "'keyword5': {"\
                f"    'value':'{k5}',"\
                "    'color':'#173177'"\
                "},"\
                "'remark':{"\
                f"    'value':'{remark}',"\
                "    'color':'#173177'"\
                "}}";

    jsonstr = jsonstr.replace("'", "\"")
    body = "{" + f'"touser":"{userId}", "template_id": "{template_id}", "url":"#", "data":{jsonstr}' + "}";
    data = json.loads(body);

    url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
    result = httpPost(url, data , "");
    print(result);

def getToken():  
    print("获取token...")
    url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
    result = httpGet(url,"");
    print(result);
    global token;
    token = result["access_token"];
    #Timer(60*60, getToken).start()

def sendMsg():
    now = datetime.datetime.now()
    ts = now.strftime('%Y-%m-%d %H:%M:%S')
    conn1 = pymysql.connect(host="xx.xx.xx.xx",port=3306,user="root",passwd="xxx",db="sxty_data" )
    cursor1 = conn1.cursor()
    print(ts + " 获取消息任务")
    sql = "select to_user,content,id from msg_wx where state = 0 "
    #print(sql)
    cursor1.execute(sql)
    data1 = cursor1.fetchall()
    #print(data1);
    for row in data1:
        userId = row[0];
        content = row[1];
        msgId = row[2];
        send(userId,content);
        msg = MsgWxModel();
        msg.cursor = cursor1;
        msg.conn = conn1;
        msg.id = msgId;
        msg.state = 1;
        msg.send_date = ts;
        msg.update();
    cursor1.close();
    conn1.close();

#获取token
def job0():
    try:
        getToken();        
    except Exception as reason:
        print(reason)
        pass;

    Timer(60*60, job0).start();       

#发送消息
def job1():

    try:
        sendMsg();        
    except Exception as reason:
        getToken();
        print(reason)

    Timer(5, job1).start();



print("消息服务已启动...")
job0();
job1(); 
  
#findUser();








 
相关推荐
chao_78923 分钟前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
大霞上仙1 小时前
nonlocal 与global关键字
开发语言·python
Mark_Aussie2 小时前
Flask-SQLAlchemy使用小结
python·flask
程序员阿龙2 小时前
【精选】计算机毕业设计Python Flask海口天气数据分析可视化系统 气象数据采集处理 天气趋势图表展示 数据可视化平台源码+论文+PPT+讲解
python·flask·课程设计·数据可视化系统·天气数据分析·海口气象数据·pandas 数据处理
ZHOU_WUYI2 小时前
Flask与Celery 项目应用(shared_task使用)
后端·python·flask
且慢.5892 小时前
Python_day47
python·深度学习·计算机视觉
佩奇的技术笔记2 小时前
Python入门手册:异常处理
python
大写-凌祁2 小时前
论文阅读:HySCDG生成式数据处理流程
论文阅读·人工智能·笔记·python·机器学习
爱喝喜茶爱吃烤冷面的小黑黑3 小时前
小黑一层层削苹果皮式大模型应用探索:langchain中智能体思考和执行工具的demo
python·langchain·代理模式
Blossom.1184 小时前
使用Python和Flask构建简单的机器学习API
人工智能·python·深度学习·目标检测·机器学习·数据挖掘·flask