Integrating Python with WeCom to Push Messages to Internal Groups
Preface A previous article mentioned using the wechatpy library to implement WeCom app login: Implementing WeCom Login in a Django + Taro Separated Frontend-Backend Project In fact, this library can do a great deal; basically all features involved in WeChat development can be implemented. This article introduces a very common scenario: pushing messages to WeCom groups in real time. Installation First install the wechatpy library pip install wechatpy If you get prompted to install other libraries at runtime (such as those related to encryption/decryption), just follow the prompts and install them,
目录15 个章节
Preface
A previous article mentioned using the wechatpy library to implement WeCom app login: Implementing WeCom Login in a Django + Taro Separated Frontend-Backend Project
In fact, this library can do a great deal; basically all features involved in WeChat development can be implemented.
This article introduces a very common scenario: pushing messages to WeCom groups in real time.
Installation
First install the wechatpy library
pip install wechatpy
If you get prompted to install other libraries at runtime (such as those related to encryption/decryption), just follow the prompts and install them. I won't belabor that here.
Create a WeCom App
First, go to the WeCom admin console and create an app, then note down the app ID (app_id)
While you're there, also note down the corp ID (corp_id) and secret from the admin console
Let's Get to the Code
Nothing else to it—let's start writing code
Create the App Object
Straight to the code
from wechatpy.work import WeChatClient
from wechatpy.work.client.api import WeChatAgent
client = WeChatClient('corp_id', 'secret')
agent: WeChatAgent = client.agent.get('app_id')
The IDs you need to fill in here are the ones mentioned above
With this agent object you can operate this WeCom app~
Create the Chat Object
To send messages, you first need a chat object. Well then, let's create one
from wechatpy.work.client.api import WeChatAppChat
chat = WeChatAppChat(client=client)
Create a Group Chat
As mentioned earlier, to send messages to a group, we still need to create a group
CHAT_ID = 'test'
result = chat.create(chat_id=CHAT_ID, name='群里名称', owner='群主ID',
user_list=['群主ID', '群员ID1', '群员ID2', '群员ID3'])
That's it—simple and easy to understand. When creating the group, specify the member IDs to invite in the user_list parameter
(Please look up these owner IDs and member IDs yourself in the WeCom admin console—they're the member IDs)
Wrap Up Some Common Operations
Send Text Messages
def send_text(content):
print(chat.send_text(CHAT_ID, content))
It's just simply sending a text message. The result looks like this:

Send Text Cards
def send_text_card(title, description, url, btn_text):
print(chat.send(CHAT_ID, 'textcard',
title=title,
description=description,
url=url,
btntxt=btn_text))
Here I used the official example
send_text_card('中秋节礼品领取',
'<div class=\"gray\">2016年9月26日</div> <div class=\"normal\"> 恭喜你抽中iPhone 7一台,领奖码:520258</div><div class=\"highlight\">请于2016年10月10日前联系行 政同事领取</div>',
'https://work.weixin.qq.com/', '谨防上当')
The result looks like this:

Send Images
def send_image(image_file):
media = WeChatMedia(client)
with open(image_file, 'rb') as f:
result = media.upload('image', f)
print(result)
if 'media_id' in result:
print(chat.send(CHAT_ID, 'image', media_id=result['media_id']))
Very simple—just pass the image path as the argument
The result looks like this

Send Markdown-Formatted Content
I tested this and found that the supported markdown format is quite limited, so don't get your hopes up too much
def send_markdown(md_file):
with open(md_file, 'r', encoding='utf-8') as f:
print(chat.send(CHAT_ID, 'markdown', content=f.read()))
I grabbed a random snippet to send. The result looks like this

As you can see, even markdown tables aren't supported……
Rename the Group Chat
Not much to say here
def rename_chat(new_name):
print(chat.update(CHAT_ID, name=new_name))
send_text(f'群聊名称已修改为:{new_name}')
Invite Users
def invite(user_id):
print(chat.update(CHAT_ID, add_user_list=[user_id]))
send_text(f'邀请用户:{user_id}')
OK
OK, that's it—all written. Pretty simple
There are quite a few scenarios for using WeCom push notifications. For example, add a webhook in Sentry monitoring so that when a project error is detected, the error info gets pushed to the group, making it easy to stay on top of project errors at any time~
Another use case we currently have is pushing some reports to the group. As you can see, these tables are all in image format (can't be helped—WeCom doesn't support full markdown……)
The result looks like this

Oh right, as for generating table images with Python, I'll write (fluff) another post next time. I'm out~
_EOF_
Integrating Python with WeCom to Push Messages to Internal Groups
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
Python创建压缩文件
代码实现 # 创建一个目录来保存这些东西 temp_path = os.path.join(settings.MEDIA_ROOT, 'temp', str(uuid.uuid4())) os.makedirs(temp_path) # 创建压缩文件 archive_path = os.path.join(temp_path, 'archive.zip') with zipfile.ZipFile
2022-09-30 · Python · 约 1 分钟
Python网络请求库,从 requests 到 httpx
Requests早该退休了,httpx这老古董才配活在异步时代?HTTP/2和超时?这些基本配置requests早该有。异步支持原生?别逗了,这年头谁还用同步。
2026-03-27 · Python · 约 1 分钟
手写核心价值观编码工具-Python实现
前言 今天是五一劳动节,祝各位无产阶级劳动者节日快乐! 然后来整活分享一些有趣的东西~ 这个小工具是我大学时做着玩的,对于各位接班人来说,12个词的核心价值观这东西,大家都非常熟悉了,这工具可以实现将一段话编码为核心价值观实现加密,同时也能将密文解密出来。 为啥要做这个呢,隔太久不太记得了,~~好像是因为游戏里喷队友老是被屏蔽,灵机一动,要是换成和谐的文字不就不会被屏蔽了吗(误~~ 实现原理 简单
2022-05-01 · Python · 约 1 分钟
Python数据展示 - 生成表格图片
前言 前一篇文章介绍了推送信息到企业微信群里,其中一个项目推送的信息是使用Python自动生成的表格,本文来讲讲如何用Python生成表格图片。 选一个合适库 Python最大的优点就是第三方库丰富,基本你要什么功能,都能找到别人实现好的库,几行代码一调用就完事了。 Pytable 项目地址:https://github.com/HiroshiARAKI/pytable 最先找到的是日本人开发的p
2022-04-09 · Python · 约 1 分钟
讨论
共 0 条加载评论中…