Python 发送企业微信消息

下方代码实现功能

1、联接Sqlserver数据库,取出发送消息清单

2、根据appid,secret获取企业微信token

3、根据消息清单类型决定发送客户消息还是内部员工消息

4、更新发送消标记

5、创建发送定时任务

python 复制代码
from datetime import datetime
import time
import threading
from queue import Queue
from queue import Empty
import pymssql
from http_utils import *

class UserMsgServer(object):


    def init(self):
        self.connect = pymssql.connect('xxxxxx:6229', 'user_name', 'pass', 'HD_Common')  #建立连接
        if self.connect:
            print("连接成功!")
        self.appid = None;
        self.secret_abs = None;
        self.secret_kh = None;
        self.agentid = None;
        self.token_abs = None;
        self.token_kh = None;


    def getToken(self):
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.appid}&corpsecret={self.secret_abs}"
        result = httpGet(url)
        self.token_abs = result["access_token"]
        print(self.token_abs)
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.appid}&corpsecret={self.secret_kh}"
        result = httpGet(url)
        self.token_kh = result["access_token"]
        print(self.token_kh)
        pass


    #发送给内部员工
    def send(self, userId, conent):

        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + self.token_abs
        print(url)
        data = {
            "touser" : userId,
            "toparty" : "",
            "totag" : "",
            "msgtype" : "text",
            "agentid" : self.agentid,
            "text" : {
                "content" : conent
            },
            "safe":0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
        }
        result = httpPost(url, data)
        print(result)
        return result["errcode"]
        pass

    #发送给客户
    def send1(self, userId, sender, conent):

        url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token=" + self.token_kh + "&debug=1"
        print(url)
        data = {
            "chat_type": "single",
            "external_userid": [
                userId
            ],
            "sender": sender,
            "text": {
                "content": conent
            }
        }
        result = httpPost(url, data)
        print(result)
        return result["errcode"]
        pass    

    def sendMsg(self):
        cursor = self.connect.cursor()   #创建一个游标对象,python里的sql语句都要通过cursor来执行
        sql = "select IndexId,UserId,Content,UserType from W_UserMessage where state = 0 and (ISNULL(PlanFlag,0)= 0 or (ISNULL(PlanFlag,0)= 1 and PlanTime <= GETDATE()))"
        cursor.execute(sql)   #执行sql语句
        row = cursor.fetchone()  #读取查询结果,            
        index = 1    
        while row:            #循环读取所有结果
            if index == 1:
                self.getToken();  #获取token

            id = row[0]
            userId = row[1]
            content = row[2]
            userType = row[3]
            
            print("发送消息给"+ userId +",content=" + content)
            if userType == "guest":
                users = userId.split('|');
                sender = "";
                if len(users) > 1:
                    userId = users[0];
                    sender =  users[1];
                    
                result = self.send1(userId, sender, content)
                self.updateMsg(id, result)

            else:    
                result = self.send(userId,content)
                self.updateMsg(id, result)
                
                           
            row = cursor.fetchone()
            index = index + 1
            time.sleep(1)
            
        
    def updateMsg(self,id, result):

        print("result")
        print(result);
        cursor = self.connect.cursor()
        if result == 0:
             cursor.execute(f"update W_UserMessage set state=1 where IndexId={id}")
        else:
             cursor.execute(f"update W_UserMessage set state=-1 where IndexId={id}")
             
        self.connect.commit()  #提交
        

    # 每n秒执行一次
    def job(self):
        while True:
            #print(datetime.now().strftime("%Y-%m-%d  %H:%M:%S"))
            try:
                self.sendMsg()
                time.sleep(3)      
            except Exception as reason:
                print(reason)
                

        
userMsgServer = UserMsgServer()
userMsgServer.init()
userMsgServer.appid = "wwe72868b229a****"
userMsgServer.secret_abs = "sGbP3HiG2e4ciZFuqyiHlAxnHvmY_Xlku8B7******"
userMsgServer.secret_kh = "Xw24GyBQCDj_IEJL7Sv1Sd1eSRGUJLo*******"
userMsgServer.agentid = 1000012
userMsgServer.job()
相关推荐
love530love16 小时前
LiveTalking 数字人项目 Windows 部署完全指南(EPGF 架构)
人工智能·windows·python·架构·livetalking·epgf
遇事不決洛必達16 小时前
【Python基础】GIL 锁是什么及其对爬虫的影响
爬虫·python·线程·进程·gil锁
CryptoPP17 小时前
快速对接东京证券交易所API数据:实战指南与代码示例
开发语言·人工智能·windows·python·信息可视化·区块链
探物 AI17 小时前
把 MambaOut 塞进 YOLOv11:会有什么样的反应
python·yolo·计算机视觉
如竟没有火炬18 小时前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
阳区欠18 小时前
【LangChain】LLM基础介绍
开发语言·python·langchain
Cosolar18 小时前
保姆级 CrewAI 教程:从零构建多智能体协作系统
人工智能·python·架构
GDAL18 小时前
使用 uv 管理 Python 版本
python·uv·版本
真实的菜18 小时前
Redis 从入门到精通(十二):典型业务场景实战 —— 排行榜、限流器、秒杀系统、Session 共享
数据库·redis·python
cup1119 小时前
[开源] Meta Assistant / 告别命令行,我为一堆 Python 脚本做了一个 Windows 任务栏的“家”
windows·python·工具·nuitka·脚本运行