├── bot_echo_text ├── requirements.txt └── echo_text.py ├── ai_actions_stream ├── requirements.txt └── actions.py ├── bot_echo_markdown ├── requirements.txt └── echo_markdown.py ├── event_chat_update ├── requirements.txt └── event_handler.py ├── README.md ├── LICENSE └── .gitignore /bot_echo_text/requirements.txt: -------------------------------------------------------------------------------- 1 | dingtalk-stream==0.15.1 2 | -------------------------------------------------------------------------------- /ai_actions_stream/requirements.txt: -------------------------------------------------------------------------------- 1 | dingtalk-stream==0.22.0 2 | -------------------------------------------------------------------------------- /bot_echo_markdown/requirements.txt: -------------------------------------------------------------------------------- 1 | dingtalk-stream==0.15.1 2 | -------------------------------------------------------------------------------- /event_chat_update/requirements.txt: -------------------------------------------------------------------------------- 1 | dingtalk-stream==0.15.1 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dingtalk-tutorial-python 2 | Python tutorial for DingTalk Open Platform 钉钉开放平台的 Python 教程 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 钉钉开放平台团队 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 | -------------------------------------------------------------------------------- /bot_echo_text/echo_text.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python 2 | 3 | import argparse 4 | import logging 5 | from dingtalk_stream import AckMessage 6 | import dingtalk_stream 7 | 8 | def setup_logger(): 9 | logger = logging.getLogger() 10 | handler = logging.StreamHandler() 11 | handler.setFormatter( 12 | logging.Formatter('%(asctime)s %(name)-8s %(levelname)-8s %(message)s [%(filename)s:%(lineno)d]')) 13 | logger.addHandler(handler) 14 | logger.setLevel(logging.INFO) 15 | return logger 16 | 17 | 18 | def define_options(): 19 | parser = argparse.ArgumentParser() 20 | parser.add_argument( 21 | '--client_id', dest='client_id', required=True, 22 | help='app_key or suite_key from https://open-dev.digntalk.com' 23 | ) 24 | parser.add_argument( 25 | '--client_secret', dest='client_secret', required=True, 26 | help='app_secret or suite_secret from https://open-dev.digntalk.com' 27 | ) 28 | options = parser.parse_args() 29 | return options 30 | 31 | 32 | class EchoTextHandler(dingtalk_stream.ChatbotHandler): 33 | def __init__(self, logger: logging.Logger = None): 34 | super(dingtalk_stream.ChatbotHandler, self).__init__() 35 | if logger: 36 | self.logger = logger 37 | 38 | async def process(self, callback: dingtalk_stream.CallbackMessage): 39 | incoming_message = dingtalk_stream.ChatbotMessage.from_dict(callback.data) 40 | text = incoming_message.text.content.strip() 41 | self.reply_text(text, incoming_message) 42 | return AckMessage.STATUS_OK, 'OK' 43 | 44 | def main(): 45 | logger = setup_logger() 46 | options = define_options() 47 | 48 | credential = dingtalk_stream.Credential(options.client_id, options.client_secret) 49 | client = dingtalk_stream.DingTalkStreamClient(credential) 50 | client.register_callback_handler(dingtalk_stream.chatbot.ChatbotMessage.TOPIC, EchoTextHandler(logger)) 51 | client.start_forever() 52 | 53 | 54 | if __name__ == '__main__': 55 | main() 56 | -------------------------------------------------------------------------------- /event_chat_update/event_handler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import argparse 5 | import logging 6 | import time 7 | import dingtalk_stream 8 | 9 | 10 | def define_options(): 11 | parser = argparse.ArgumentParser() 12 | parser.add_argument( 13 | '--client_id', dest='client_id', required=True, 14 | help='app_key or suite_key from https://open-dev.digntalk.com' 15 | ) 16 | parser.add_argument( 17 | '--client_secret', dest='client_secret', required=True, 18 | help='app_secret or suite_secret from https://open-dev.digntalk.com' 19 | ) 20 | options = parser.parse_args() 21 | return options 22 | 23 | 24 | class MyEventHandler(dingtalk_stream.EventHandler): 25 | async def process(self, event: dingtalk_stream.EventMessage): 26 | if event.headers.event_type != 'chat_update_title': 27 | # ignore events not equals `chat_update_title`; 忽略`chat_update_title`之外的其他事件; 28 | # 该示例仅演示 chat_update_title 类型的事件订阅; 29 | return dingtalk_stream.AckMessage.STATUS_OK, 'OK' 30 | self.logger.info( 31 | 'received event, delay=%sms, eventType=%s, eventId=%s, eventBornTime=%d, eventCorpId=%s, ' 32 | 'eventUnifiedAppId=%s, data=%s', 33 | int(time.time() * 1000) - event.headers.event_born_time, 34 | event.headers.event_type, 35 | event.headers.event_id, 36 | event.headers.event_born_time, 37 | event.headers.event_corp_id, 38 | event.headers.event_unified_app_id, 39 | event.data) 40 | # put your code here; 可以在这里添加你的业务代码,处理事件订阅的业务逻辑; 41 | 42 | return dingtalk_stream.AckMessage.STATUS_OK, 'OK' 43 | 44 | 45 | def main(): 46 | options = define_options() 47 | credential = dingtalk_stream.Credential(options.client_id, options.client_secret) 48 | client = dingtalk_stream.DingTalkStreamClient(credential) 49 | client.register_all_event_handler(MyEventHandler()) 50 | client.start_forever() 51 | 52 | 53 | if __name__ == '__main__': 54 | main() 55 | -------------------------------------------------------------------------------- /bot_echo_markdown/echo_markdown.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python 2 | 3 | import argparse 4 | import logging 5 | from dingtalk_stream import AckMessage 6 | import dingtalk_stream 7 | 8 | def setup_logger(): 9 | logger = logging.getLogger() 10 | handler = logging.StreamHandler() 11 | handler.setFormatter( 12 | logging.Formatter('%(asctime)s %(name)-8s %(levelname)-8s %(message)s [%(filename)s:%(lineno)d]')) 13 | logger.addHandler(handler) 14 | logger.setLevel(logging.INFO) 15 | return logger 16 | 17 | 18 | def define_options(): 19 | parser = argparse.ArgumentParser() 20 | parser.add_argument( 21 | '--client_id', dest='client_id', required=True, 22 | help='app_key or suite_key from https://open-dev.digntalk.com' 23 | ) 24 | parser.add_argument( 25 | '--client_secret', dest='client_secret', required=True, 26 | help='app_secret or suite_secret from https://open-dev.digntalk.com' 27 | ) 28 | options = parser.parse_args() 29 | return options 30 | 31 | 32 | class EchoMarkdownHandler(dingtalk_stream.ChatbotHandler): 33 | def __init__(self, logger: logging.Logger = None): 34 | super(dingtalk_stream.ChatbotHandler, self).__init__() 35 | if logger: 36 | self.logger = logger 37 | 38 | async def process(self, callback: dingtalk_stream.CallbackMessage): 39 | incoming_message = dingtalk_stream.ChatbotMessage.from_dict(callback.data) 40 | text = 'echo received message:\n' 41 | text += '\n'.join(['> 1. %s'%i for i in incoming_message.text.content.strip().split('\n')]) 42 | self.reply_markdown('dingtalk-tutorial-python', text, incoming_message) 43 | return AckMessage.STATUS_OK, 'OK' 44 | 45 | def main(): 46 | logger = setup_logger() 47 | options = define_options() 48 | 49 | credential = dingtalk_stream.Credential(options.client_id, options.client_secret) 50 | client = dingtalk_stream.DingTalkStreamClient(credential) 51 | client.register_callback_handler(dingtalk_stream.chatbot.ChatbotMessage.TOPIC, EchoMarkdownHandler(logger)) 52 | client.start_forever() 53 | 54 | 55 | if __name__ == '__main__': 56 | main() 57 | -------------------------------------------------------------------------------- /ai_actions_stream/actions.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python 2 | 3 | import json 4 | import argparse 5 | import logging 6 | from dingtalk_stream import AckMessage 7 | import dingtalk_stream 8 | 9 | def setup_logger(): 10 | logger = logging.getLogger() 11 | handler = logging.StreamHandler() 12 | handler.setFormatter( 13 | logging.Formatter('%(asctime)s %(name)-8s %(levelname)-8s %(message)s [%(filename)s:%(lineno)d]')) 14 | logger.addHandler(handler) 15 | logger.setLevel(logging.INFO) 16 | return logger 17 | 18 | 19 | def define_options(): 20 | parser = argparse.ArgumentParser() 21 | parser.add_argument( 22 | '--client_id', dest='client_id', required=True, 23 | help='app_key or suite_key from https://open-dev.digntalk.com' 24 | ) 25 | parser.add_argument( 26 | '--client_secret', dest='client_secret', required=True, 27 | help='app_secret or suite_secret from https://open-dev.digntalk.com' 28 | ) 29 | options = parser.parse_args() 30 | return options 31 | 32 | 33 | class WeatherHandler(dingtalk_stream.GraphHandler): 34 | def __init__(self, logger: logging.Logger = None): 35 | super(dingtalk_stream.GraphHandler, self).__init__() 36 | if logger: 37 | self.logger = logger 38 | 39 | async def process(self, callback: dingtalk_stream.CallbackMessage): 40 | request = dingtalk_stream.GraphRequest.from_dict(callback.data) 41 | self.logger.info('incoming request, method=%s, uri=%s', request.request_line.method, request.request_line.uri) 42 | 43 | response = dingtalk_stream.GraphResponse() 44 | response.status_line.code = 200 45 | response.status_line.reason_phrase = 'OK' 46 | response.headers['Content-Type'] = 'application/json' 47 | response.body = json.dumps({ 48 | 'location': '杭州', 49 | 'dateStr': '2024-10-24', 50 | 'text': '晴天', 51 | 'temperature': 22, 52 | 'humidity': 65, 53 | 'wind_direction': '东南风' 54 | }, ensure_ascii=False) 55 | return AckMessage.STATUS_OK, response.to_dict() 56 | 57 | 58 | def main(): 59 | logger = setup_logger() 60 | options = define_options() 61 | 62 | credential = dingtalk_stream.Credential(options.client_id, options.client_secret) 63 | client = dingtalk_stream.DingTalkStreamClient(credential) 64 | client.register_callback_handler(dingtalk_stream.graph.GraphMessage.TOPIC, WeatherHandler(logger)) 65 | client.start_forever() 66 | 67 | 68 | if __name__ == '__main__': 69 | main() 70 | -------------------------------------------------------------------------------- /.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 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 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 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | .idea/ 161 | --------------------------------------------------------------------------------