| 510 | |
| 511 | |
| 512 | class WeCom: |
| 513 | def __init__(self, corpid, corpsecret, agentid): |
| 514 | self.CORPID = corpid |
| 515 | self.CORPSECRET = corpsecret |
| 516 | self.AGENTID = agentid |
| 517 | self.ORIGIN = "https://qyapi.weixin.qq.com" |
| 518 | if push_config.get("QYWX_ORIGIN"): |
| 519 | self.ORIGIN = push_config.get("QYWX_ORIGIN") |
| 520 | |
| 521 | def get_access_token(self): |
| 522 | url = f"{self.ORIGIN}/cgi-bin/gettoken" |
| 523 | values = { |
| 524 | "corpid": self.CORPID, |
| 525 | "corpsecret": self.CORPSECRET, |
| 526 | } |
| 527 | req = requests.post(url, params=values) |
| 528 | data = json.loads(req.text) |
| 529 | return data["access_token"] |
| 530 | |
| 531 | def send_text(self, message, touser="@all"): |
| 532 | send_url = ( |
| 533 | f"{self.ORIGIN}/cgi-bin/message/send?access_token={self.get_access_token()}" |
| 534 | ) |
| 535 | send_values = { |
| 536 | "touser": touser, |
| 537 | "msgtype": "text", |
| 538 | "agentid": self.AGENTID, |
| 539 | "text": {"content": message}, |
| 540 | "safe": "0", |
| 541 | } |
| 542 | send_msges = bytes(json.dumps(send_values), "utf-8") |
| 543 | respone = requests.post(send_url, send_msges) |
| 544 | respone = respone.json() |
| 545 | return respone["errmsg"] |
| 546 | |
| 547 | def send_mpnews(self, title, message, media_id, touser="@all"): |
| 548 | send_url = ( |
| 549 | f"{self.ORIGIN}/cgi-bin/message/send?access_token={self.get_access_token()}" |
| 550 | ) |
| 551 | send_values = { |
| 552 | "touser": touser, |
| 553 | "msgtype": "mpnews", |
| 554 | "agentid": self.AGENTID, |
| 555 | "mpnews": { |
| 556 | "articles": [ |
| 557 | { |
| 558 | "title": title, |
| 559 | "thumb_media_id": media_id, |
| 560 | "author": "Author", |
| 561 | "content_source_url": "", |
| 562 | "content": message.replace("\n", "<br/>"), |
| 563 | "digest": message, |
| 564 | } |
| 565 | ] |
| 566 | }, |
| 567 | } |
| 568 | send_msges = bytes(json.dumps(send_values), "utf-8") |
| 569 | respone = requests.post(send_url, send_msges) |