├── .gitignore ├── LICENSE ├── README.md └── voidbot.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # VoidBot 2 | 支持 OneBot 标准的 能跑就行 Python SDK 3 | 4 | - 极致轻量:一个文件,200 行代码实现了 80% 常用开发功能 5 | - 部署简单:Python环境上,只需再安装一个 `websocket-client` 库 6 | - 代码简单:只需要 Python 入门即可读懂源码,参考[菜鸟教程](https://www.runoob.com/python3/python3-tutorial.html) 7 | - 入门快速:无需文档即可直接接触到 OneBot 标准 8 | 9 | 10 | ### How to use 11 | 12 | 1. 安装 [Python](https://www.python.org/downloads/) 3.7 或以上 环境 13 | 2. 命令行中执行 `pip install websocket-client` 14 | 3. 启动任意一个 [OneBot](https://github.com/botuniverse/onebot/blob/master/ecosystem.md#onebot-%E5%AE%9E%E7%8E%B0) 实现,如 `go-cqhttp` ,并打开 `正向WS` 15 | 4. 在 `voidbot.py` 文件中 注释位置编写你的插件 16 | 5. 使用 `Python` 直接运行 `voidbot.py` 文件 17 | 18 | 你的插件通过基类 **Plugin** 的一个子类来实现。你只需要写一个继承 **Plugin** 的子类并重写 **match** 和 **handle** 方法就能快速实现插件功能 19 | 20 | 21 | ### 说明 22 | 23 | 24 | ###### API 25 | 26 | | API | 功能 | 说明 | 27 | | ---------------- | ------------- | ---- | 28 | | send_msg | 发送消息 | | 29 | | send_group_msg | 发送群聊消息 | | 30 | | send_private_msg | 发送私聊消息 | | 31 | 32 | ###### 消息段 33 | 34 | | 消息段 | 功能 | 说明 | 35 | | ------ | ------ | ---- | 36 | | text | 纯文本 | | 37 | | image | 图片 | | 38 | | record | 语音 | | 39 | | at | 艾特 | | 40 | | xml | XML | | 41 | | json | JSON | | 42 | 43 | 44 | ###### 匹配 45 | 46 | | RULE | 功能 | 说明 | 47 | | ---------------- | ---------------- | ---- | 48 | | on_full_match | 完全匹配消息 | | 49 | | on_reg_match | 正则匹配消息 | | 50 | | only_to_me | 被艾特或者被喊名字 | | 51 | | super_user | 发送者为主人 | | 52 | | admin_user | 发送者为群管理 | | 53 | 54 | 55 | 以上提供常用的封装,可按例子自行仿照扩充。你可以在[这里](https://github.com/botuniverse/onebot)查看 `OneBot` 标准的文档 -------------------------------------------------------------------------------- /voidbot.py: -------------------------------------------------------------------------------- 1 | import re 2 | import time 3 | import queue 4 | import logging 5 | import threading 6 | import collections 7 | import json as json_ 8 | 9 | import websocket 10 | 11 | WS_URL = "ws://127.0.0.1:6700/ws" # WebSocket 地址 12 | NICKNAME = ["BOT", "ROBOT"] # 机器人昵称 13 | SUPER_USER = [12345678, 23456789] # 主人的 QQ 号 14 | # 日志设置 level=logging.DEBUG -> 日志级别为 DEBUG 15 | logging.basicConfig(level=logging.DEBUG, format="[void] %(asctime)s - %(levelname)s - %(message)s") 16 | logger = logging.getLogger(__name__) 17 | 18 | 19 | class Plugin: 20 | def __init__(self, context: dict): 21 | self.ws = WS_APP 22 | self.context = context 23 | 24 | def match(self) -> bool: 25 | return self.on_full_match("hello") 26 | 27 | def handle(self): 28 | self.send_msg(text("hello world!")) 29 | 30 | def on_message(self) -> bool: 31 | return self.context["post_type"] == "message" 32 | 33 | def on_full_match(self, keyword="") -> bool: 34 | return self.on_message() and self.context["message"] == keyword 35 | 36 | def on_reg_match(self, pattern="") -> bool: 37 | return self.on_message() and re.search(pattern, self.context["message"]) 38 | 39 | def only_to_me(self) -> bool: 40 | flag = False 41 | for nick in NICKNAME + [f"[CQ:at,qq={self.context['self_id']}] "]: 42 | if self.on_message() and nick in self.context["message"]: 43 | flag = True 44 | self.context["message"] = self.context["message"].replace(nick, "") 45 | return flag 46 | 47 | def super_user(self) -> bool: 48 | return self.context["user_id"] in SUPER_USER 49 | 50 | def admin_user(self) -> bool: 51 | return self.super_user() or self.context["sender"]["role"] in ("admin", "owner") 52 | 53 | def call_api(self, action: str, params: dict) -> dict: 54 | echo_num, q = echo.get() 55 | data = json_.dumps({"action": action, "params": params, "echo": echo_num}) 56 | logger.info("发送调用 <- " + data) 57 | self.ws.send(data) 58 | try: # 阻塞至响应或者等待30s超时 59 | return q.get(timeout=30) 60 | except queue.Empty: 61 | logger.error("API调用[{echo_num}] 超时......") 62 | 63 | def send_msg(self, *message) -> int: 64 | # https://github.com/botuniverse/onebot-11/blob/master/api/public.md#send_msg-%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF 65 | if "group_id" in self.context and self.context["group_id"]: 66 | return self.send_group_msg(*message) 67 | else: 68 | return self.send_private_msg(*message) 69 | 70 | def send_private_msg(self, *message) -> int: 71 | # https://github.com/botuniverse/onebot-11/blob/master/api/public.md#send_private_msg-%E5%8F%91%E9%80%81%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF 72 | params = {"user_id": self.context["user_id"], "message": message} 73 | ret = self.call_api("send_private_msg", params) 74 | return 0 if ret is None or ret["status"] == "failed" else ret["data"]["message_id"] 75 | 76 | def send_group_msg(self, *message) -> int: 77 | # https://github.com/botuniverse/onebot-11/blob/master/api/public.md#send_group_msg-%E5%8F%91%E9%80%81%E7%BE%A4%E6%B6%88%E6%81%AF 78 | params = {"group_id": self.context["group_id"], "message": message} 79 | ret = self.call_api("send_group_msg", params) 80 | return 0 if ret is None or ret["status"] == "failed" else ret["data"]["message_id"] 81 | 82 | 83 | def text(string: str) -> dict: 84 | # https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E7%BA%AF%E6%96%87%E6%9C%AC 85 | return {"type": "text", "data": {"text": string}} 86 | 87 | 88 | def image(file: str, cache=True) -> dict: 89 | # https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E5%9B%BE%E7%89%87 90 | return {"type": "image", "data": {"file": file, "cache": cache}} 91 | 92 | 93 | def record(file: str, cache=True) -> dict: 94 | # https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E8%AF%AD%E9%9F%B3 95 | return {"type": "record", "data": {"file": file, "cache": cache}} 96 | 97 | 98 | def at(qq: int) -> dict: 99 | # https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E6%9F%90%E4%BA%BA 100 | return {"type": "at", "data": {"qq": qq}} 101 | 102 | 103 | def xml(data: str) -> dict: 104 | # https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#xml-%E6%B6%88%E6%81%AF 105 | return {"type": "xml", "data": {"data": data}} 106 | 107 | 108 | def json(data: str) -> dict: 109 | # https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#json-%E6%B6%88%E6%81%AF 110 | return {"type": "json", "data": {"data": data}} 111 | 112 | 113 | def music(data: str) -> dict: 114 | # https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E9%9F%B3%E4%B9%90%E5%88%86%E4%BA%AB- 115 | return {"type": "music", "data": {"type": "qq", "id": data}} 116 | 117 | 118 | """ 119 | 在下面加入你自定义的插件,自动加载本文件所有的 Plugin 的子类 120 | 只需要写一个 Plugin 的子类,重写 match() 和 handle() 121 | match() 返回 True 则自动回调 handle() 122 | """ 123 | 124 | 125 | class TestPlugin(Plugin): 126 | def match(self): # 说 hello 则回复 127 | return self.on_full_match("hello") 128 | 129 | def handle(self): 130 | self.send_msg(at(self.context["user_id"]), text("hello world!")) 131 | 132 | 133 | class TestPlugin2(Plugin): 134 | def match(self): # 艾特机器人说菜单则回复 135 | return self.only_to_me() and self.on_full_match("菜单") 136 | 137 | def handle(self): 138 | self.send_msg(text("没有菜单")) 139 | 140 | 141 | class TestPlugin3(Plugin): 142 | def match(self): # 戳一戳机器人则回复 143 | return self.context["post_type"] == "notice" and self.context["sub_type"] == "poke"\ 144 | and self.context["target_id"] == self.context["self_id"] 145 | 146 | def handle(self): 147 | self.send_msg(text("请不要戳我 >_<")) 148 | 149 | 150 | """ 151 | 在上面自定义你的插件 152 | """ 153 | 154 | 155 | def plugin_pool(context: dict): 156 | # 遍历所有的 Plugin 的子类,执行匹配 157 | for P in Plugin.__subclasses__(): 158 | plugin = P(context) 159 | if plugin.match(): 160 | plugin.handle() 161 | 162 | 163 | class Echo: 164 | def __init__(self): 165 | self.echo_num = 0 166 | self.echo_list = collections.deque(maxlen=20) 167 | 168 | def get(self): 169 | self.echo_num += 1 170 | q = queue.Queue(maxsize=1) 171 | self.echo_list.append((self.echo_num, q)) 172 | return self.echo_num, q 173 | 174 | def match(self, context: dict): 175 | for obj in self.echo_list: 176 | if context["echo"] == obj[0]: 177 | obj[1].put(context) 178 | 179 | 180 | def on_message(_, message): 181 | # https://github.com/botuniverse/onebot-11/blob/master/event/README.md 182 | context = json_.loads(message) 183 | if "echo" in context: 184 | logger.debug("调用返回 -> " + message) 185 | # 响应报文通过队列传递给调用 API 的函数 186 | echo.match(context) 187 | elif "meta_event_type" in context: 188 | logger.debug("心跳事件 -> " + message) 189 | else: 190 | logger.info("收到事件 -> " + message) 191 | # 消息事件,开启线程 192 | t = threading.Thread(target=plugin_pool, args=(context, )) 193 | t.start() 194 | 195 | 196 | if __name__ == "__main__": 197 | echo = Echo() 198 | WS_APP = websocket.WebSocketApp( 199 | WS_URL, 200 | on_message=on_message, 201 | on_open=lambda _: logger.debug("连接成功......"), 202 | on_close=lambda _: logger.debug("重连中......"), 203 | ) 204 | while True: # 掉线重连 205 | WS_APP.run_forever() 206 | time.sleep(5) 207 | --------------------------------------------------------------------------------