开启左侧

Python企业微信集成教程

[复制链接]
在线会员 6KjHg7gd 发表于 2025-1-22 12:45:29 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
各人佳!尔是您们的Python西席。来日诰日咱们要进修怎样完毕Python取企业微疑的散成。便像一名熟练的通信员,咱们要教会怎样收收消息、办理通信录、处置工作等妙技。颠末那些本领,咱们能够完毕更智能的办公主动化。让咱们开端此次企业微疑散成之旅吧!
1、根底设置模块


起首,咱们去完毕根底设置的功用:
import requests
import json
import logging
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta
import time
import hashlib

class WeChatConfig:
    def __init__(self,
                 corp_id: str,
                 corp_secret: str):
        self.corp_id = corp_id
        self.corp_secret = corp_secret
        self.access_token = None
        self.token_expires = datetime.now()
        self.setup_logging()
   
    def setup_logging(self):
        """设置日记记载"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s'
        )
   
    def get_access_token(self) -> str:
        """获得会见令牌"""
        try:
            #反省 令牌可否过时
            if (self.access_token and
                datetime.now() < self.token_expires):
                return self.access_token
           
            # 恳求新的令牌
            url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
            params = {
                "corpid": self.corp_id,
                "corpsecret": self.corp_secret
            }
           
            response = requests.get(url, params=params)
            result = response.json()
           
            if result.get("errcode") == 0:
                self.access_token = result["access_token"]
                self.token_expires = (
                    datetime.now() +
                    timedelta(seconds=7000)  # 保障起睹,比2小时少些
                )
                return self.access_token
            else:
                raise Exception(
                    f"获得令牌失利: {result}"
                )
               
        except Exception as e:
            logging.error(f"令牌获得失利: {str(e)}")
            raise

class WeChatAPI:
    def __init__(self, config: WeChatConfig):
        self.config = config
   
    def _request(self,
                 method: str,
                 url: str,
                 **kwargs) -> Dict:
        """收收恳求"""
        try:
            # 增加会见令牌
            params = kwargs.get('params', {})
            params['access_token'] = self.config.get_access_token()
            kwargs['params'] = params
           
            # 收收恳求
            response = requests.request(
                method,
                url,
                **kwargs
            )
            result = response.json()
           
            #反省 照应
            if result.get("errcode", 0) != 0:
                raise Exception(
                    f"恳求失利: {result}"
                )
           
            return result
           
        except Exception as e:
            logging.error(f"恳求失利: {str(e)}")
            raise

# 使用示例
config = WeChatConfig(
    "your_corp_id",
    "your_corp_secret"
)
api = WeChatAPI(config)

小揭士:忘患上按期革新会见令牌,制止过时!
2、消息收收模块


让咱们完毕消息收收功用:
class MessageSender:
    def __init__(self, api: WeChatAPI):
        self.api = api
   
    def send_text(self,
                  agentid: int,
                  content: str,
                  touser: Optional[str] = "@all",
                  toparty: Optional[str] = None,
                  totag: Optional[str] = None
                  ) -> bool:
        """收收文原消息"""
        try:
            url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
           
            data = {
                "msgtype": "text",
                "agentid": agentid,
                "text": {"content": content},
                "touser": touser
            }
           
            if toparty:
                data["toparty"] = toparty
            if totag:
                data["totag"] = totag
           
            result = self.api._request(
                "POST",
                url,
                json=data
            )
           
            return True
           
        except Exception as e:
            logging.error(f"消息收收失利: {str(e)}")
            return False
   
    def send_markdown(self,
                     agentid: int,
                     content: str,
                     touser: Optional[str] = "@all"
                     ) -> bool:
        """收收Markdown消息"""
        try:
            url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
           
            data = {
                "msgtype": "markdown",
                "agentid": agentid,
                "markdown": {"content": content},
                "touser": touser
            }
           
            result = self.api._request(
                "POST",
                url,
                json=data
            )
           
            return True
           
        except Exception as e:
            logging.error(f"Markdown收收失利: {str(e)}")
            return False

# 使用示例
sender = MessageSender(api)

# 收收文原消息
sender.send_text(
    1000002,  # 使用ID
    "您佳,那是一条尝试消息",
    "@all"
)

# 收收Markdown消息
sender.send_markdown(
    1000002,
    "**主要报告**\n> 请于来日诰日上班条件接周报"
)
3、通信录办理模块


现在咱们完毕通信录办理功用:
class ContactManager:
    def __init__(self, api: WeChatAPI):
        self.api = api
   
    def get_department_list(self,
                          id: Optional[int] = None
                          ) -> List[Dict]:
        """获得部分列表"""
        try:
            url = "https://qyapi.weixin.qq.com/cgi-bin/department/list"
           
            params = {}
            if id is not None:
                params['id'] = id
           
            result = self.api._request(
                "GET",
                url,
                params=params
            )
           
            return result['department']
           
        except Exception as e:
            logging.error(f"获得部分列表失利: {str(e)}")
            return []
   
    def get_user_list(self,
                     department_id: int,
                     fetch_child: bool = False
                     ) -> List[Dict]:
        """获得部分成员列表"""
        try:
            url = "https://qyapi.weixin.qq.com/cgi-bin/user/list"
           
            params = {
                'department_id': department_id,
                'fetch_child': 1 if fetch_child else 0
            }
           
            result = self.api._request(
                "GET",
                url,
                params=params
            )
           
            return result['userlist']
           
        except Exception as e:
            logging.error(f"获得成员列表失利: {str(e)}")
            return []
   
    def create_user(self,
                    user_data: Dict[str, Any]
                    ) -> bool:
        """创立成员"""
        try:
            url = "https://qyapi.weixin.qq.com/cgi-bin/user/create"
           
            result = self.api._request(
                "POST",
                url,
                json=user_data
            )
           
            return True
           
        except Exception as e:
            logging.error(f"创立成员失利: {str(e)}")
            return False

# 使用示例
contact = ContactManager(api)

# 获得部分列表
departments = contact.get_department_list()

# 获得成员列表
users = contact.get_user_list(1)  # 获得部分ID为1的成员

#创立 新成员
new_user = {
    "userid": "zhangsan",
    "name": "弛三",
    "mobile": "13800000000",
    "department": [1],
    "email": "zhangsan@example.com"
}
contact.create_user(new_user)

留神事变:
    庇护敏感疑息处置API限流记载操纵日记按期共步数据
操练题

    增加图片消息收收功用完毕部分成员导出功用开辟主动挨卡提醒
合用本领

    消息模板:
def generate_message_template(
    template_type: str,
    **kwargs
) -> str:
    """天生消息模板"""
    templates = {
        'notice': (
            "📢通知 :{title}\n"
            "━━━━━━━━━━\n"
            "{content}\n"
            "公布时间:{time}"
        ),
        'report': (
            "📊 {report_type}陈述\n"
            "━━━━━━━━━━\n"
            "部分:{department}\n"
            "时间:{time}\n"
            "概略:{content}"
        )
    }
    return templates[template_type].format(**kwargs)
    批质操纵:
def batch_send_message(
    sender: MessageSender,
    messages: List[Dict]
) -> Dict[str, int]:
    """批质收收消息"""
    results = {
        'success': 0,
        'failed': 0
    }
    for msg in messages:
        success = sender.send_text(**msg)
        if success:
            results['success'] += 1
        else:
            results['failed'] += 1
    return results
    共步查抄:
def check_sync_status(
    local_data: List[Dict],
    remote_data: List[Dict],
    key: str = 'userid'
) -> Dict[str, List]:
    """查抄共步形状"""
    local_ids = {item[key] for item in local_data}
    remote_ids = {item[key] for item in remote_data}
   
    return {
        'to_add': list(remote_ids - local_ids),
        'to_delete': list(local_ids - remote_ids),
        'to_check': list(local_ids & remote_ids)
    }

小同伴们,来日诰日的Python进修之旅便到那里啦!忘患上入手敲代码,有成就随时正在批评区问尔哦。祝各人进修高兴,Python进修节节下!
您需要登录后才可以回帖 登录 | 立即注册 qq_login

本版积分规则

发布主题
阅读排行更多+
用专业创造成效
400-778-7781
周一至周五 9:00-18:00
意见反馈:server@mailiao.group
紧急联系:181-67184787
ftqrcode

扫一扫关注我们

Powered by 职贝云数A新零售门户 X3.5© 2004-2025 职贝云数 Inc.( 蜀ICP备2024104722号 )