├── .github └── workflows │ └── python-publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── WorkWeixinRobot ├── __init__.py └── work_weixin_robot.py ├── demo ├── articles.yaml ├── help.md └── picture.jpg ├── requirements.txt └── setup.py /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflows will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | deploy: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: '3.x' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install setuptools wheel twine 25 | - name: Build and publish 26 | env: 27 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 28 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 29 | run: | 30 | python setup.py sdist bdist_wheel 31 | twine upload dist/* 32 | 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # local 132 | .idea/ 133 | debug.py 134 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Will 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Work Weixin Robot 2 | > 企业微信群机器人 3 | 4 | [![Org](https://img.shields.io/static/v1?label=org&message=Truth%20%26%20Insurance%20Office&color=597ed9)](http://bx.baoxian-sz.com) 5 | ![Author](https://img.shields.io/static/v1?label=author&message=v.stone@163.com&color=blue) 6 | ![License](https://img.shields.io/github/license/seoktaehyeon/work-weixin-robot) 7 | [![python](https://img.shields.io/static/v1?label=Python&message=3.7&color=3776AB)](https://www.python.org) 8 | [![PyPI](https://img.shields.io/pypi/v/WorkWeixinRobot.svg)](https://pypi.org/project/WorkWeixinRobot/) 9 | [![Ref](https://img.shields.io/badge/ref-企业微信群机器人-informational)](https://work.weixin.qq.com/help?person_id=1&doc_id=13376) 10 | 11 | ## Installation 12 | ```bash 13 | pip install WorkWeixinRobot 14 | ``` 15 | 16 | ## Usage 17 | #### Command 18 | ```text 19 | Usage: wwx-robot -k -t -d -f 20 | Option: 21 | -k Robot key 22 | -t Message type 23 | text, markdown, image, news 24 | -d Message data 25 | -f Message file 26 | +--------------+--------------+ 27 | | Message Type | File Type | 28 | +--------------+--------------+ 29 | | text | text | 30 | +--------------+--------------+ 31 | | markdown | markdown | 32 | +--------------+--------------+ 33 | | image | jpg,png | 34 | +--------------+--------------+ 35 | | news | yaml | 36 | +--------------+--------------+ 37 | Example: 38 | wwx-robot -k xxxx -t text -d "Hello world" 39 | wwx-robot -k xxxx -t markdown -f demo/help.md 40 | wwx-robot -k xxxx -t image -f demo/picture.jpg 41 | wwx-robot -k xxxx -t news -f demo/articles.yaml 42 | 43 | Message File Template: 44 | help.md 45 | ## Weixin MSG 46 | How to use this tool 47 | articles.yaml 48 | - title: 'Article I' 49 | description: 'Article I Description' # Optional 50 | url: 'URL I' 51 | picurl: 'Article I Picture URL' # Optional 52 | - title: 'Article II' 53 | description: 'Article II Description' # Optional 54 | url: 'URL II' 55 | picurl: 'Article II Picture URL' # Optional 56 | ``` 57 | 58 | #### Python 59 | ##### Init a weixin robot 60 | ```python 61 | #!/usr/bin/env python 62 | # -*- coding: utf-8 -*- 63 | from WorkWeixinRobot.work_weixin_robot import WWXRobot 64 | wwxrbt = WWXRobot(key='Robot Key') 65 | ``` 66 | ##### Send Text Message 67 | ```python 68 | wwxrbt.send_text(content='Hello') 69 | ``` 70 | ##### Send Markdown Message 71 | ```python 72 | wwxrbt.send_markdown(content='Hello') 73 | ``` 74 | ##### Send Image Message 75 | ```python 76 | # Method I: Send local image 77 | wwxrbt.send_image(local_file='local_image.jpg') 78 | # Method II: Send remote URL image 79 | wwxrbt.send_image(remote_url='https://office.baoxian-sz.com/assets/img/logo_logo_zhenxinhuaxian_tiw_600_150.png') 80 | ``` 81 | ##### Send Articles Message [ Image + Text ] 82 | ```python 83 | articles = [ 84 | { 85 | 'title': 'Article I', 86 | 'description': 'Article I Description', # Optional 87 | 'url': 'URL I', 88 | 'picurl': 'Article I Picture URL', # Optional 89 | }, 90 | { 91 | 'title': 'Article II', 92 | 'description': 'Article II Description', # Optional 93 | 'url': 'URL II', 94 | 'picurl': 'Article II Picture URL', # Optional 95 | } 96 | ] 97 | wwxrbt.send_news(articles=articles) 98 | ``` 99 | -------------------------------------------------------------------------------- /WorkWeixinRobot/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seoktaehyeon/work-weixin-robot/dd9aaa70ab79acb5ff242baa5c8d3161a732eec5/WorkWeixinRobot/__init__.py -------------------------------------------------------------------------------- /WorkWeixinRobot/work_weixin_robot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Author: Will v.stone@163.com 4 | 5 | import requests 6 | import base64 7 | import hashlib 8 | import os 9 | import yaml 10 | import sys 11 | import getopt 12 | 13 | 14 | help_doc = """Usage: wwx-robot -k -t -d -f 15 | Option: 16 | -k Robot key 17 | -t Message type 18 | text, markdown, image, news 19 | -d Message data 20 | -f Message file 21 | +--------------+--------------+ 22 | | Message Type | File Type | 23 | +--------------+--------------+ 24 | | text | text | 25 | +--------------+--------------+ 26 | | markdown | markdown | 27 | +--------------+--------------+ 28 | | image | jpg,png | 29 | +--------------+--------------+ 30 | | news | yaml | 31 | +--------------+--------------+ 32 | Example: 33 | wwx-robot -k xxxx -t text -d "Hello world" 34 | wwx-robot -k xxxx -t markdown -f demo/help.md 35 | wwx-robot -k xxxx -t image -f demo/picture.jpg 36 | wwx-robot -k xxxx -t news -f demo/articles.yaml 37 | """ 38 | 39 | 40 | class WWXRobot(object): 41 | def __init__(self, key: str): 42 | self.url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=' + key 43 | self.headers = { 44 | 'Content-Type': 'application/json' 45 | } 46 | 47 | def _send(self, body: dict): 48 | rsp = requests.post(url=self.url, headers=self.headers, json=body) 49 | assert rsp.status_code == 200, rsp.content 50 | assert rsp.json().get('errmsg') == 'ok', rsp.content 51 | print('SUCCEED') 52 | return True 53 | 54 | def send_text(self, content: str): 55 | """ 56 | 文本类型 57 | :param content: 58 | :return: 59 | """ 60 | body = { 61 | 'msgtype': 'text', 62 | 'text': { 63 | 'content': content, 64 | # 'mentioned_list': ['@all'], # Optional 65 | # 'mentioned_mobile_list': ['@all'] # Optional 66 | } 67 | } 68 | self._send(body) 69 | 70 | def send_markdown(self, content: str): 71 | """ 72 | Markdown 类型 73 | :param content: 74 | :return: 75 | """ 76 | body = { 77 | 'msgtype': 'markdown', 78 | 'markdown': { 79 | 'content': content, 80 | } 81 | } 82 | self._send(body) 83 | 84 | def send_image(self, local_file=None, remote_url=None): 85 | """ 86 | 图片类型 87 | :param local_file: local file path 88 | :param remote_url: image url 89 | :return: 90 | """ 91 | if local_file: 92 | with open(local_file, 'rb') as f: 93 | image_content = f.read() 94 | elif remote_url: 95 | image_content = requests.get(remote_url).content 96 | else: 97 | raise Exception('Need provide local_file: str or remote_url: str') 98 | image_base64 = base64.b64encode(image_content).decode('utf-8') 99 | md5 = hashlib.md5() 100 | md5.update(image_content) 101 | image_md5 = md5.hexdigest() 102 | body = { 103 | 'msgtype': 'image', 104 | 'image': { 105 | 'base64': image_base64, 106 | 'md5': image_md5 107 | } 108 | } 109 | self._send(body) 110 | 111 | def send_news(self, articles: list): 112 | """ 113 | 图文类型 114 | :param articles: [ 115 | { 116 | 'title': '', 117 | 'description': '', # Optional 118 | 'url': '', 119 | 'picurl': '', # Optional 120 | } 121 | ] 122 | :return: 123 | """ 124 | assert len(articles) <= 8, 'Only support 1-8 articles' 125 | for article in articles: 126 | assert article.get('title'), 'Need provide article title' 127 | assert article.get('url'), 'Need provide article url' 128 | body = { 129 | 'msgtype': 'news', 130 | 'news': { 131 | 'articles': articles 132 | } 133 | } 134 | self._send(body) 135 | 136 | @staticmethod 137 | def read_file(file_path): 138 | if os.path.exists(file_path): 139 | with open(file_path, 'r', encoding='utf-8') as f: 140 | return f.read() 141 | else: 142 | return "" 143 | 144 | def sender(self, msg_type: str = "text", msg_data=None, msg_file_path=None): 145 | if msg_type == "text": 146 | self.send_text(msg_data or self.read_file(msg_file_path)) 147 | elif msg_type == "markdown": 148 | self.send_markdown(msg_data or self.read_file(msg_file_path)) 149 | elif msg_type == "image": 150 | if os.path.exists(msg_file_path): 151 | self.send_image(local_file=msg_file_path) 152 | else: 153 | self.send_image(remote_url=msg_file_path) 154 | elif msg_type == "news": 155 | self.send_news(yaml.full_load(self.read_file(msg_file_path))) 156 | 157 | 158 | def main(): 159 | if len(sys.argv[1:]) == 0: 160 | print(help_doc) 161 | exit(1) 162 | try: 163 | _args = dict() 164 | for opt, arg in getopt.getopt(sys.argv[1:], "k:t:d:f:")[0]: 165 | if opt == '-k': 166 | _args['key'] = arg 167 | elif opt == '-t': 168 | _args['type'] = arg 169 | elif opt == '-d': 170 | _args['data'] = arg 171 | elif opt == '-f': 172 | _args['file'] = arg 173 | if not _args.get('key') or not _args.get('type'): 174 | print('Robot key and message type is required') 175 | print(help_doc) 176 | exit(1) 177 | if not _args.get('data') and not _args.get('file'): 178 | print('Message data or message file is required') 179 | print(help_doc) 180 | exit(1) 181 | print('Welcome to use Work WeiXin Robot tool') 182 | rbt = WWXRobot(key=_args.get('key')) 183 | print('Try to send == %s == type message' % _args.get('type').upper()) 184 | if _args.get('data'): 185 | print('Message Content:\n%s' % _args.get('data')) 186 | else: 187 | if _args.get('type') == 'image': 188 | print('Message Content: \n%s' % _args.get('file')) 189 | else: 190 | with open(_args.get('file'), 'r', encoding='utf-8') as f: 191 | print('Message Content:\n%s' % f.read()) 192 | rbt.sender(msg_type=_args.get('type'), msg_data=_args.get('data'), msg_file_path=_args.get('file')) 193 | except getopt.GetoptError: 194 | print(help_doc) 195 | exit(1) 196 | print('Complete to send message') 197 | 198 | 199 | if __name__ == '__main__': 200 | print('This is the scripts of Work Weixin Robot sender') 201 | -------------------------------------------------------------------------------- /demo/articles.yaml: -------------------------------------------------------------------------------- 1 | - title: '企业微信群机器人使用手册' 2 | description: '如何配置群机器人?' 3 | url: 'https://work.weixin.qq.com/help?person_id=1&doc_id=13376' 4 | picurl: 'https://p.qpic.cn/pic_wework/3478722865/7b7dda774dab6fcebd7949815c85fb0f47681013914755be/0' 5 | - title: 'Python 操控企业微信机器人' 6 | description: '不但可以 Python 脚本,还可以直接命令行执行' 7 | url: 'https://pypi.org/project/WorkWeixinRobot' 8 | picurl: 'https://www.python.org/static/img/python-logo.png' -------------------------------------------------------------------------------- /demo/help.md: -------------------------------------------------------------------------------- 1 | # 企业微信群机器人 2 | 3 | #### WorkWeixinRobot 4 | [GitHub地址](https://github.com/seoktaehyeon/work-weixin-robot) 5 | 6 | #### 如何配置群机器人 7 | > [如何使用群机器人](https://work.weixin.qq.com/help?person_id=1&doc_id=13376#如何使用群机器人) 8 | > [文本类型](https://work.weixin.qq.com/help?person_id=1&doc_id=13376#文本类型) 9 | > [markdown类型](https://work.weixin.qq.com/help?person_id=1&doc_id=13376#markdown类型) 10 | > [图片类型](https://work.weixin.qq.com/help?person_id=1&doc_id=13376#图片类型) 11 | > [图文类型](https://work.weixin.qq.com/help?person_id=1&doc_id=13376#图文类型) 12 | > [消息发送频率限制](https://work.weixin.qq.com/help?person_id=1&doc_id=13376#消息发送频率限制) 13 | 14 | 15 | -------------------------------------------------------------------------------- /demo/picture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seoktaehyeon/work-weixin-robot/dd9aaa70ab79acb5ff242baa5c8d3161a732eec5/demo/picture.jpg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | PyYAML -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | from setuptools import find_packages, setup 5 | import os 6 | 7 | 8 | URL = 'https://github.com/seoktaehyeon/work-weixin-robot' 9 | NAME = 'WorkWeixinRobot' 10 | VERSION = '1.0.1' 11 | DESCRIPTION = '企业微信群机器人' 12 | if os.path.exists('README.md'): 13 | with open('README.md', encoding='utf-8') as f: 14 | LONG_DESCRIPTION = f.read() 15 | else: 16 | LONG_DESCRIPTION = DESCRIPTION 17 | AUTHOR = 'Will' 18 | AUTHOR_EMAIL = 'v.stone@163.com' 19 | LICENSE = 'MIT' 20 | PLATFORMS = [ 21 | 'any', 22 | ] 23 | REQUIRES = [ 24 | 'requests', 25 | 'PyYAML', 26 | ] 27 | CONSOLE_SCRIPTS = 'wwx-robot = WorkWeixinRobot.work_weixin_robot:main' 28 | 29 | setup( 30 | name=NAME, 31 | version=VERSION, 32 | description=( 33 | DESCRIPTION 34 | ), 35 | long_description=LONG_DESCRIPTION, 36 | long_description_content_type='text/markdown', 37 | author=AUTHOR, 38 | author_email=AUTHOR_EMAIL, 39 | maintainer=AUTHOR, 40 | maintainer_email=AUTHOR_EMAIL, 41 | license=LICENSE, 42 | packages=find_packages(), 43 | platforms=PLATFORMS, 44 | url=URL, 45 | install_requires=REQUIRES, 46 | entry_points={ 47 | 'console_scripts': [CONSOLE_SCRIPTS], 48 | } 49 | ) 50 | --------------------------------------------------------------------------------