@@ -15,7 +15,7 @@ def __init__(self, webhook_url=None):
1515 self .default_webhook_url = webhook_url or os .environ .get ('WECOM_WEBHOOK_URL' , '' )
1616 self .enabled = os .environ .get ('WECOM_ENABLED' , '0' ) == '1'
1717
18- def _get_webhook_url (self , project_name = None ):
18+ def _get_webhook_url (self , project_name = None , url_base = None ):
1919 """
2020 获取项目对应的 Webhook URL
2121 :param project_name: 项目名称
@@ -31,8 +31,16 @@ def _get_webhook_url(self, project_name=None):
3131
3232 # 遍历所有环境变量(忽略大小写),找到项目对应的 Webhook URL
3333 target_key = f"WECOM_WEBHOOK_URL_{ project_name .upper ()} "
34+
35+ # 仓库名称优先级高,先匹配
36+ for env_key , env_value in os .environ .items ():
37+ if env_key .upper () == target_key :
38+ return env_value # 找到匹配项,直接返回
39+
40+ # url_base 优先级次之
41+ target_key_url_base = f"WECOM_WEBHOOK_URL_{ url_base .upper ()} "
3442 for env_key , env_value in os .environ .items ():
35- if env_key .upper () == target_key :
43+ if target_key_url_base != None and env_key .upper () == target_key_url_base :
3644 return env_value # 找到匹配项,直接返回
3745
3846 # 如果未找到匹配的环境变量,降级使用全局的 Webhook URL
@@ -61,7 +69,7 @@ def format_markdown_content(self, content, title=None):
6169 formatted_content += content
6270 return formatted_content
6371
64- def send_message (self , content , msg_type = 'text' , title = None , is_at_all = False , project_name = None ):
72+ def send_message (self , content , msg_type = 'text' , title = None , is_at_all = False , project_name = None , url_base = None ):
6573 """
6674 发送企业微信消息
6775 :param content: 消息内容
@@ -74,7 +82,7 @@ def send_message(self, content, msg_type='text', title=None, is_at_all=False, pr
7482 return
7583
7684 try :
77- post_url = self ._get_webhook_url (project_name = project_name )
85+ post_url = self ._get_webhook_url (project_name = project_name , url_base = url_base )
7886 if msg_type == 'markdown' :
7987 formatted_content = self .format_markdown_content (content , title )
8088 data = {
@@ -100,6 +108,30 @@ def send_message(self, content, msg_type='text', title=None, is_at_all=False, pr
100108
101109 if response .status_code != 200 :
102110 logger .error (_ ("企业微信消息发送失败! webhook_url:{}, error_msg:{}" ).format (post_url , response .text ))
111+
112+ try :
113+ data = json .loads (response .text )
114+ errmsg = data .get ("errmsg" )
115+ if errmsg and "markdown.content exceed max length" in errmsg :
116+ # markdown渲染过长了,尝试text发送
117+ data = {
118+ "msgtype" : "text" ,
119+ "text" : {
120+ "content" : content ,
121+ "mentioned_list" : ["@all" ] if is_at_all else []
122+ }
123+ }
124+
125+ response = requests .post (
126+ url = post_url ,
127+ json = data ,
128+ headers = {'Content-Type' : 'application/json' }
129+ )
130+
131+ except json .JSONDecodeError as e :
132+ print (f"JSON 解析失败: { e } " )
133+ except Exception as e :
134+ logger .error (_ ("企业微信消息发送失败! {}" ).format (e ))
103135 return
104136
105137 result = response .json ()
0 commit comments