### Example: Load Plugins and Get Command Names Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Demonstrates how to initialize the BOT, load plugins automatically, and then retrieve and print the list of all enabled command names. This example assumes SDK version 4.3.9 or higher. ```python from qg_botsdk import BOT bot = BOT(bot_id="xxx", bot_token="xxx") # 加载插件后获取所有指令名字 bot.load_plugins_auto() command_names = bot.get_command_names() print(f"已加载的指令:{command_names}") # 输出:已加载的指令:['help', 'ping', 'info', 'echo .*'] ``` -------------------------------- ### Plugin Directory Structure Example Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/Plugins插件开发.md An example illustrating a typical project structure for organizing plugins. Files starting with an underscore (e.g., `__init__.py`) are automatically skipped. ```text 你的项目/ ├── main.py # 机器人主程序 ├── plugins/ # 插件目录 │ ├── __init__.py # 会被自动跳过 │ ├── admin.py # 管理插件 │ ├── fun.py # 娱乐插件 │ └── welcome.py # 欢迎插件 └── ... ``` -------------------------------- ### Basic Bot Workflow with Event Handling Source: https://github.com/glgdly/qg_botsdk/blob/master/README.rst Demonstrates a simple bot setup. Import necessary classes, instantiate the BOT with your credentials, bind a message event handler, and start the bot. The handler can process incoming messages and reply. ```python from qg_botsdk import BOT, Model # 导入SDK核心类(BOT)、所有数据模型(Model) bot = BOT(bot_id='xxx', bot_token='xxx', is_private=True, is_sandbox=True) # 实例化SDK核心类 @bot.bind_msg() # 绑定接收消息事件的函数 def deliver(data: Model.MESSAGE): # 创建接收消息事件的函数 if '你好' in data.treated_msg: # 判断消息是否存在特定内容 data.reply('你好,世界') # 发送被动回复(带message_id直接reply回复) # 如需使用如 Embed 等消息模板,可传入相应结构体, 如: # data.reply(ApiModel.MessageEmbed(title="你好", content="世界")) if __name__ == '__main__': bot.start() # 开始运行机器人 ``` -------------------------------- ### Complete bot code example Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/快速入门.md A full example demonstrating importing necessary modules, defining a message handler, initializing the bot, binding the handler, and starting the bot. ```python # 导入SDK核心类(BOT)、所有数据模型(Model) from qg_botsdk import BOT, Model def deliver(data: Model.MESSAGE): # 创建接收消息事件的函数并绑定数据模型 if "你好" in data.treated_msg: # data.treated_msg 为消息内容 data.reply("你好世界") bot = BOT(bot_id="xxx", bot_token="xxx") # 实例化SDK核心类 bot.bind_msg(deliver) # 绑定接收消息事件的回调函数 bot.start() # 开始运行机器人 ``` -------------------------------- ### Install qg-botsdk Source: https://github.com/glgdly/qg_botsdk/blob/master/README.rst Install the SDK using pip. Ensure you use the correct package name with a hyphen. ```bash pip install qg-botsdk ``` -------------------------------- ### Simple qg_botsdk Bot Workflow Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/简介.md A basic example of a qg_botsdk bot that replies to messages. It requires importing BOT and Model, defining a message handler, and initializing and starting the bot with credentials. ```python # qg_botsdk的一个简单工作流 from qg_botsdk import BOT, Model @bot.bind_msg() def deliver(data: Model.MESSAGE): if "你好" in data.treated_msg: data.reply("你好,世界") if __name__ == "__main__": bot = BOT(bot_id="xxx", bot_token="xxx") bot.start() ``` -------------------------------- ### Register Initial Start Event Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Register a function to run once when the bot starts. This function should not contain infinite loops. Requires SDK version 2.5.0 or higher. ```python def start_event(): """ 这是一个在机器人开始运行后(成功连接后)马上执行的函数 """ all_guilds = bot.get_me_guilds() bot.logger.info('全部频道:' + str([items['name'] + '(' + items['id'] + ')' for items in all_guilds])) bot.logger.info('全部频道数量:' + str(len(all_guilds))) for items in all_guilds: gi = bot.get_guild_info(items["id"]) if 'code' in gi and str(gi['code']) == '11292': bot.logger.warning(items['name'] + '(' + items['id'] + ')[权限不足,无法查询此频道信息]') else: bot.logger.info(f'频道 {items["name"]}({items["id"]}) 的拥有者:' + str(items['owner_id'])) bot = BOT(bot_id='xxx', bot_token='xxx') bot.register_start_event(on_start_function=start_event) # 路径:qg_botsdk.qg_bot.BOT().register_start_event() ``` -------------------------------- ### Start Bot Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Starts the instantiated bot. Code after this function call will not execute if `is_blocking` is True. For non-blocking execution, set `is_blocking=False`. ```APIDOC ## Start Bot ### Description Starts the bot. If `is_blocking` is True, subsequent code will not run. For non-blocking execution, set `is_blocking=False` to run the bot as an asynchronous task. ### Method `bot.start()` ### Parameters - **is_blocking** (bool) - Optional - Default: True. If False, the bot runs asynchronously (SDK version >= 2.6.0). ``` -------------------------------- ### Import BOT class Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/快速入门.md Import the main BOT class from the qg_botsdk library to start building your bot. ```python from qg_botsdk import BOT ``` -------------------------------- ### Get Current Preprocessor List Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Get the list of preprocessors for the current bot. Requires SDK version >= 3.0.0. ```APIDOC ## Get Current Preprocessor List ### Description Get the list of preprocessors for the current bot. ### Method Function Call ### Endpoint bot.get_current_preprocessors() ### Parameters None ### Request Example ```python preprocessors = bot.get_current_preprocessors() ``` ``` -------------------------------- ### Start Bot Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Start the instantiated bot. Code after this call will not execute if the bot runs in blocking mode. For non-blocking execution, pass `is_blocking=False`. ```python bot.start() # 路径:qg_botsdk.BOT().start() ``` -------------------------------- ### Bind message handler and start bot Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/快速入门.md Register the message handler function with the BOT instance and start the bot to listen for events. ```python bot.bind_msg(deliver) bot.start() ``` -------------------------------- ### Import ApiModel Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/ApiModel.md Import the ApiModel class from the qg_botsdk library to start using API models. ```python from qg_botsdk import ApiModel ``` -------------------------------- ### Register Initial Run Event Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Registers a function to be executed once when the bot starts up and successfully connects. This function should not contain infinite loops. ```APIDOC ## Register Initial Run Event ### Description Registers a function to be executed once when the bot starts up and successfully connects. This function should not contain infinite loops. ### Method `bot.register_start_event(on_start_function)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### on_start_function - **on_start_function** (function) - Required - The function to execute on bot startup. This function should not accept any parameters. ### Request Example ```python def start_event(): all_guilds = bot.get_me_guilds() bot.logger.info('All guilds: ' + str([items['name'] + '(' + items['id'] + ')' for items in all_guilds])) bot = BOT(bot_id='xxx', bot_token='xxx') bot.register_start_event(on_start_function=start_event) ``` ### Response None (This is an event registration, not a direct request/response operation) ### Error Handling None explicitly documented for the registration itself. ``` -------------------------------- ### Flexible Data Handling with qg_botsdk Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/简介.md Demonstrates how qg_botsdk returns raw API data, allowing access to new fields even before type hints are updated. Use print() or str() to get JSON output and access fields directly, ignoring IDE warnings. ```python gi = bot.api.get_guild_info('某频道的guild_id') print(gi) # 借由上面的指令,你可以获取到以下资料: # {"data": {"id": "xxx", "name": "xxx", "icon": "xxx", "owner_id": "xxx", "owner": false, "joined_at": "xxx", "member_count": 11, "max_members": 1200, "description": "xxx"}, "trace_id": "xxx", "http_code": 200, "result": true} # 其中data是返回的数据实体,trace_id是腾讯的内部bug追踪id,http_code是请求api时返回的状态码,result是sdk帮忙判断的api请求是否成功 # 那么如果腾讯新增了一个名为abc的字段,sdk会怎么处理呢? # {"data": {"abc": "xxx", "id": "xxx", "name": "xxx", "icon": "xxx", "owner_id": "xxx", "owner": false, "joined_at": "xxx", "member_count": 11, "max_members": 1200, "description": "xxx"}, "trace_id": "xxx", "http_code": 200, "result": true} # SDK会如实给你反馈abc这个字段;唯一的问题是,如果要获取数据的时候,你的ide可能会提示无相关字段 # 因此,你要做的是无视ide的提示,直接获取 gi.data.abc 即可 ``` -------------------------------- ### Get Current Preprocessor List Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Retrieve the list of current preprocessors for the bot. Requires SDK version >= 3.0.0. ```python bot.get_current_preprocessors() ``` -------------------------------- ### Get Bot Information Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Fetches the detailed information for the current user (bot). ```python bot.api.get_bot_info() ``` -------------------------------- ### Get Bot Info Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Fetches the detailed information of the current user (bot). ```APIDOC ## get_bot_info ### Description Fetches the detailed information of the current user (bot). ### Method `bot.api.get_bot_info()` ### Parameters None ### Response #### Success Response (200) - **data** (object) - Parsed JSON data containing bot details. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official provided trace ID. - **result** (bool) - True if successful, False otherwise. ### Response Example ```json { "data": {}, "http_code": 200, "trace_id": "some_trace_id", "result": true } ``` ``` -------------------------------- ### Auto Load Plugins Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Automatically scan and load all Python files in a plugin directory. Requires SDK version >= 4.3.9. Files starting with '_' are skipped. ```python bot.load_plugins_auto(plugins_dir="plugins", recursive=False, pattern="*.py") ``` ```python from qg_botsdk import BOT bot = BOT(bot_id="xxx", bot_token="xxx") # 基础用法:加载默认目录下的所有插件 bot.load_plugins_auto() # 指定目录 bot.load_plugins_auto("my_plugins") # 递归扫描子目录 bot.load_plugins_auto("plugins", recursive=True) # 自定义匹配模式 bot.load_plugins_auto("plugins", pattern="*_plugin.py") ``` -------------------------------- ### Register Loop Run Event Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Registers a function to be executed repeatedly at a specified interval after the bot starts. The interval is defined in seconds. ```APIDOC ## Register Loop Run Event ### Description Registers a function to be executed repeatedly at a specified interval after the bot starts. The interval is defined in seconds. ### Method `bot.register_repeat_event(time_function, check_interval)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### time_function - **time_function** (function) - Required - The function to execute repeatedly. This function should not accept any parameters. #### check_interval - **check_interval** (int or float) - Optional - The interval in seconds between calls to `time_function`. Defaults to 10 seconds. ### Request Example ```python def loop_event(): print('This message is printed every minute.') bot = BOT(bot_id='xxx', bot_token='xxx') bot.register_repeat_event(time_function=loop_event, check_interval=60) ``` ### Response None (This is an event registration, not a direct request/response operation) ### Error Handling None explicitly documented for the registration itself. ``` -------------------------------- ### Register Loop Running Event Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Register a function to be called repeatedly at a specified interval after the bot starts. Requires SDK version 2.5.0 or higher. ```python def loop_event(): """ 这是一个在机器人开始运行后,不断重复运行的函数 """ print('由于check_interval的值是60,代表每一分钟会运行函数并输出一次此段文字') bot = BOT(bot_id='xxx', bot_token='xxx') bot.register_repeat_event(time_function=loop_event, check_interval=60) # 路径:qg_botsdk.qg_bot.BOT().register_repeat_event() ``` -------------------------------- ### Get Bot Guilds List Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves a list of all channels the current user (bot) has joined. This method handles pagination to fetch all data directly. ```python bot.api.get_bot_guilds() ``` -------------------------------- ### Initialize BOT instance Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/快速入门.md Instantiate the BOT class with your bot's ID and token. For public bots, set is_private to False. For sandbox testing, use is_sandbox=True. ```python bot = BOT(bot_id="xxx", bot_token="xxx") # 如为公域机器人,需传入is_private参数,如下: # bot = BOT(bot_id="xxx", bot_token="xxx", is_private=False) ``` ```python bot = BOT(bot_id="xxx", bot_token="xxx", is_sandbox=True) ``` ```python bot = BOT(bot_id="xxx", bot_token="xxx", is_sandbox=False) ``` -------------------------------- ### Directly Import Plugins Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/Plugins插件开发.md Plugins can be loaded by directly importing their modules. The BOT.start() method will automatically detect and load these imported plugins. ```python import my_plugins ``` -------------------------------- ### Get Guild Roles Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves a list of roles for a specified guild. ```APIDOC ## GET Guild Roles ### Description Used to obtain the list of roles for the specified `guild_id`. ### Method GET ### Endpoint `/guilds/{guild_id}/roles` ### Parameters #### Path Parameters - **guild_id** (string) - Required - The ID of the guild. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **data** (object) - Parsed JSON data. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official provided trace ID. - **result** (bool) - True if successful, False otherwise. #### Response Example ```json { "data": {}, "http_code": 200, "trace_id": "some_trace_id", "result": true } ``` ``` -------------------------------- ### Get Guild Channels Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves a list of sub-channels for a specified channel. ```APIDOC ## GET /guilds/{guild_id}/channels ### Description Retrieves a list of sub-channels for a specified channel. ### Method GET ### Endpoint /guilds/{guild_id}/channels ### Parameters #### Path Parameters - **guild_id** (string) - Required - The ID of the channel. ### Response #### Success Response (200) - **data** (list[object]) - A list containing all data, where each item is an object. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official error trace ID. - **result** (bool) - True for success, False otherwise. ``` -------------------------------- ### Command Matching Rules Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/Plugins插件开发.md Demonstrates recommended and strict ways to register commands. Registering without a leading slash (e.g., command="time") is recommended for broader compatibility with user inputs like 'time' and '/time'. ```python # 推荐:同时支持 time 和 /time @Plugins.on_command(command="time") async def time_cmd(data): await data.reply("当前时间:...") ``` ```python # 严格模式:只支持 /time @Plugins.on_command(command="/time") async def time_cmd(data): await data.reply("当前时间:...") ``` -------------------------------- ### Get Channels Info Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves the details of a specified sub-channel using its ID. ```APIDOC ## GET /channels/{channel_id} ### Description Retrieves the details of a specified sub-channel. ### Method GET ### Endpoint /channels/{channel_id} ### Parameters #### Path Parameters - **channel_id** (string) - Required - The ID of the sub-channel. ### Response #### Success Response (200) - **data** (object) - Parsed JSON data. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official error trace ID. - **result** (bool) - True for success, False otherwise. ``` -------------------------------- ### Get Guild Info Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves the details of a specified channel using its ID. ```APIDOC ## GET /guilds/{guild_id} ### Description Retrieves the details of a specified channel. ### Method GET ### Endpoint /guilds/{guild_id} ### Parameters #### Path Parameters - **guild_id** (string) - Required - The ID of the channel. ### Response #### Success Response (200) - **data** (object) - Parsed JSON data. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official error trace ID. - **result** (bool) - True for success, False otherwise. ``` -------------------------------- ### Bot with Command Decorator and Preprocessor Source: https://github.com/glgdly/qg_botsdk/blob/master/README.rst Illustrates using command decorators for specific command matching with regex and various conditions like requiring mentions or admin privileges. Includes a preprocessor to log incoming messages before command processing. ```python from qg_botsdk import BOT, Model bot = BOT(bot_id='xxx', bot_token='xxx', is_private=True, is_sandbox=True) # before_command代表预处理器,将在检查所有commands前执行(要求SDK版本>=2.5.2) @bot.before_command() def preprocessor(data: Model.MESSAGE): bot.logger.info(f"收到来自{data.author.username}的消息:{data.treated_msg}") @bot.on_command( regex=r"你好(?:机器人)?", # 正则表达式,匹配用户消息 is_short_circuit=True, # is_short_circuit代表短路机制,根据注册顺序,匹配到即停止匹配,但不影响bind_msg() is_require_at=True, # is_require_at代表是否要求检测到用户@了机器人才可触发指令 is_require_admin=True, # is_require_admin代表是否要求检测到用户是频道主或频道管理才可触发指令 admin_error_msg="抱歉,你的权限不足(非频道主或管理员),不能使用此指令", ) def command(data: Model.MESSAGE): data.reply("你好,世界") if __name__ == '__main__': bot.start() ``` -------------------------------- ### Load Plugins with BOT.load_plugins() Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/Plugins插件开发.md Use `load_plugins()` for unified plugin loading, supporting various modes like loading the default directory, single files, entire directories (recursively or not), multiple targets, or with custom file matching patterns. Requires SDK version >= 4.4.0. ```python from qg_botsdk import BOT bot = BOT(bot_id="xxx", bot_token="xxx") # 加载默认目录(初始化时设置的 plugins_dir) bot.load_plugins() # 加载单个文件 bot.load_plugins("plugins/hello.py") # 加载整个目录 bot.load_plugins("plugins") # 递归加载目录 bot.load_plugins("plugins", recursive=True) # 批量加载多个目标 bot.load_plugins(["plugins/hello.py", "plugins/tools.py", "extra_plugins"]) # 自定义文件匹配模式 bot.load_plugins("plugins", pattern="*_plugin.py") bot.start() ``` -------------------------------- ### Load Plugins Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Load plugins into the current bot instance. Requires SDK version >= 2.5.0. Specify the path to the plugin .py file. ```python bot.load_plugins(path_to_plugins="xxx") ``` -------------------------------- ### Get Message Information Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves the details of a specific message within a given sub-channel. ```APIDOC ## GET /channels/{channel_id}/messages/{message_id} ### Description Fetches the details of a specific message identified by `message_id` within the sub-channel specified by `channel_id`. ### Method GET ### Endpoint `/channels/{channel_id}/messages/{message_id}` ### Parameters #### Path Parameters - **channel_id** (string) - Required - The ID of the sub-channel. - **message_id** (string) - Required - The ID of the target message. ### Response #### Success Response (200) - **data** (object) - The parsed JSON data of the message. - **http_code** (int) - The HTTP status code. - **trace_id** (string) - A unique trace ID for error tracking. - **result** (bool) - True if the operation was successful, False otherwise. #### Response Example ```json { "data": { "message_id": "12345", "content": "Hello, world!", "timestamp": "2023-10-27T10:00:00Z" }, "http_code": 200, "trace_id": "some_trace_id", "result": true } ``` ``` -------------------------------- ### Load Plugins Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Load plugins into the current bot instance. Requires SDK version >= 2.5.0. ```APIDOC ## Load Plugins ### Description Load plugins into the current bot instance. ### Method Function Call ### Endpoint bot.load_plugins(path_to_plugins="xxx") ### Parameters #### Request Body - **path_to_plugins** (str) - Required - The relative or absolute path to the plugin .py file. ### Request Example ```python bot.load_plugins(path_to_plugins="path/to/your/plugin.py") ``` ``` -------------------------------- ### Get Guild Roles Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves a list of roles for a specified channel. Requires the guild_id of the channel. ```python bot.api.get_guild_roles() ``` -------------------------------- ### Get Bot Information Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Retrieves the bot's channel user ID, username, and avatar. ```APIDOC ## Get Bot Information ### Description Retrieves the bot's channel user ID, username, and avatar. ### Method `bot.robot.id`, `bot.username`, `bot.avatar` ### Parameters None. ``` -------------------------------- ### Auto-load Plugins on Startup Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/Plugins插件开发.md Enable `auto_load_plugins` when instantiating the BOT for automatic scanning and loading of plugins from a specified directory. The `plugins_dir` parameter specifies the directory, and `plugins_recursive` controls whether subdirectories are scanned. ```python from qg_botsdk import BOT bot = BOT( bot_id="你的BotAppID", bot_token="你的BotToken", auto_load_plugins=True, # 开启自动加载 plugins_dir="plugins", # 指定插件目录,默认为 "plugins" plugins_recursive=True, # 是否递归扫描子目录,默认 False ) bot.start() # 启动时会自动加载 plugins 目录下的所有插件 ``` -------------------------------- ### Instantiate a Bot Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Instantiate a robot for registration. Supports multiple processes registering multiple robots within the same program. ```python from qg_botsdk import BOT bot = BOT(bot_id='xxx', bot_token='xxx') bot.bind_msg(deliver) bot.start() ``` ```python from qg_botsdk import BOT BOT(bot_id='xxx', bot_token='xxx') ``` -------------------------------- ### Get Schedule Info API Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Fetches the details of a specific schedule within a channel. Requires both channel_id and schedule_id. ```python bot.api.get_schedule_info() ``` -------------------------------- ### Proto.websocket() Configuration Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Configure the WebSocket connection protocol for the robot. Parameters like shard_no and total_shard are for advanced configuration and should not be changed lightly. ```python Proto.websocket() ``` -------------------------------- ### Get Guild Message Frequency Setting Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves the message frequency settings for a bot within a specific guild. ```APIDOC ## GET /guilds/{guild_id}/settings/message-frequency ### Description Used to obtain the message frequency settings of the bot in the guild `guild_id`. ### Method GET ### Endpoint `/guilds/{guild_id}/settings/message-frequency` ### Parameters #### Path Parameters - **guild_id** (string) - Required - The ID of the guild. ### Response #### Success Response (200) - **data** (object) - Parsed JSON data. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official provided trace ID. - **result** (bool) - True if successful, False otherwise. #### Response Example ```json { "data": {}, "http_code": 200, "trace_id": "some_trace_id", "result": true } ``` ``` -------------------------------- ### Import Proto Class Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Import the Proto class, which is required for SDK version 4.2.0 and later. It defines the robot's connection protocol. ```python from qg_botsdk import Proto ``` -------------------------------- ### Get Specific Message Details Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves the details of a specific message within a sub-channel. Requires the sub-channel ID and the message ID. ```python bot.api.get_message_info() ``` -------------------------------- ### Get Bot Guilds Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves a list of all guilds (servers) the current user (bot) has joined. Handles pagination to fetch all data. ```APIDOC ## get_bot_guilds ### Description Retrieves a list of all guilds (servers) the current user (bot) has joined. This method has resolved pagination issues and directly fetches all data. ### Method `bot.api.get_bot_guilds()` ### Parameters None ### Response #### Success Response (200) - **data** (list[object]) - A list containing all guild data, where each item is an object. - **http_code** (int) - HTTP status code. - **trace_id** (list[string]) - Tencent official provided trace ID, aggregated into a list for each request. - **result** (list[bool]) - True if successful, False otherwise, aggregated into a list for each request. ### Response Example ```json { "data": [{}], "http_code": 200, "trace_id": ["some_trace_id"], "result": [true] } ``` ``` -------------------------------- ### Use Tencent Content Detection API (Async) Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Asynchronous method to check if text content is potentially violating. Requires `security_setup` to be called with mini program ID and secret. ```python # 异步async版调用方法 async def msg_function(data: MESSAGE): checking = await bot.api.security_check(data.content) if checking: print('检测通过,内容并无违规') else: print('检测不通过,内容有违规') bot = BOT(bot_id='xxx', bot_token='xxx', bot_secret='xxx') bot.security_setup(mini_id='xxx', mini_secret='xxx') bot.bind_msg(callback=msg_function) # 路径(v2.2.0后):qg_botsdk.qg_bot.BOT().api.security_check() # 路径(v2.2.0前):qg_botsdk.qg_bot.BOT().security_check() ``` -------------------------------- ### 创建日程 Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Creates a new schedule within a specified channel. Requires administrator privileges. Returns the created schedule object upon success. ```APIDOC ## 创建日程 ### Description Used to create a schedule in the `channel_id` specified schedule sub-channel. Requires the operator to have `Manage Channel` permission (set the bot as an administrator). After successful creation, returns the created schedule object. Creation operation frequency is limited: single administrator limited to 10 times per day; single channel limited to 100 times per day. ### Method POST (assumed, based on 'create' operation) ### Endpoint `/channels/{channel_id}/schedules` (inferred, common REST pattern) ### Parameters #### Path Parameters - **channel_id** (string) - Required - The ID of the schedule sub-channel. #### Request Body - **schedule_name** (string) - Required - The name of the schedule. - **start_timestamp** (string) - Required - The start timestamp of the schedule (in milliseconds). - **end_timestamp** (string) - Required - The end timestamp of the schedule (in milliseconds). - **jump_channel_id** (string) - Required - The sub-channel ID to jump to when the schedule starts. - **remind_type** (string) - Required - The type of schedule reminder. ### Response #### Success Response (200) - **data** (object) - Parsed JSON data of the created schedule. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official error tracking ID. - **result** (bool) - True if successful; otherwise False. ### Request Example ```python bot.api.create_schedule( channel_id='YOUR_CHANNEL_ID', schedule_name='Team Meeting', start_timestamp='1678886400000', end_timestamp='1678890000000', jump_channel_id='ANOTHER_CHANNEL_ID', remind_type='ALL_MEMBERS' ) ``` ### Response Example ```json { "data": { "schedule_id": "new_schedule_id", "schedule_name": "Team Meeting", "start_timestamp": "1678886400000", "end_timestamp": "1678890000000", "jump_channel_id": "ANOTHER_CHANNEL_ID", "remind_type": "ALL_MEMBERS" }, "http_code": 200, "trace_id": "some_trace_id", "result": true } ``` ``` -------------------------------- ### Use Tencent Content Detection API (Sync) Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Synchronous method to check if text content is potentially violating. Requires `security_setup` to be called with mini program ID and secret. ```python # 同步sync版调用方法 def msg_function(data: MESSAGE): if bot.api.security_check(data.content): print('检测通过,内容并无违规') else: print('检测不通过,内容有违规') bot = BOT(bot_id='xxx', bot_token='xxx', bot_secret='xxx') bot.security_setup(mini_id='xxx', mini_secret='xxx') bot.bind_msg(callback=msg_function) # 路径(v2.2.0后):qg_botsdk.qg_bot.BOT().api.security_check() # 路径(v2.2.0前):qg_botsdk.qg_bot.BOT().security_check() ``` -------------------------------- ### Get Reaction Users Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves a list of users who have reacted to a specific message with a given emoji. This API handles pagination to fetch all users. ```APIDOC ## Get Reaction Users ### Description Retrieves a list of users who reacted to a specified message with a specified emoji. This API handles pagination to fetch all data. ### Method `bot.api.get_reaction_users()` ### Parameters #### Path Parameters - **channel_id** (string) - Required - The ID of the sub-channel. - **message_id** (string) - Required - The ID of the target message. - **type_** (string) - Required - The type of the emoji. - **id_** (string) - Required - The ID of the emoji. ### Response #### Success Response - **data** (list[object]) - A list of parsed JSON data. - **http_code** (int) - The HTTP status code. - **trace_id** (list[string]) - A list of trace IDs provided by Tencent for each request. - **result** (list[bool]) - A list of booleans, True for success and False otherwise, for each request. ``` -------------------------------- ### 上传富媒体文件 Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Uploads rich media files for use in QQ single chats and group chats. Returns a file ID upon successful upload. ```APIDOC ## 上传富媒体文件 ### Description 用于上传富媒体文件的 v2 API,仅用于在 QQ 单聊和 QQ 群聊内。上传成功后,返回上传成功的文件 ID。 ### Method POST (assumed, as it's an upload operation) ### Endpoint /upload_media (assumed based on function name) ### Parameters #### Request Body - **file_type** (int) - Required - 文件类型 - **url** (string) - Required - 需要发送媒体资源的 url - **srv_send_msg** (bool) - Required - 设置 True 会直接发送消息到目标端,且会占用主动消息频次 - **file_data** (string) - Required - base64 二进制数据 - **user_openid** (string) - Required - 用户 id,此项有值时,group_openid 必须为 None - **group_openid** (string) - Required - 群 id,此项有值时,user_openid 必须为 None ### Response #### Success Response (200) - **data** (object) - 解析后的 json 数据 - **file_uuid** (string) - 文件 ID - **file_info** (string) - 文件信息 - **ttl** (int) - 文件有效时间(秒) - **http_code** (int) - HTTP 状态码 - **trace_id** (string) - 腾讯官方提供的错误追踪 ID - **result** (bool) - 成功为 True;否则为 False ``` -------------------------------- ### Get Sub-channel Role Permissions Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves the permissions for a specific role within a given sub-channel. Requires the operator to have sub-channel management permissions. ```APIDOC ## Get Sub-channel Role Permissions ### Description Used to obtain the permissions of role `role_id` in sub-channel `channel_id`. Requires the operator to have sub-channel management permissions (robot needs to be set as administrator). ### Method `bot.api.get_channel_role_permission()` ### Parameters #### Path Parameters - **channel_id** (string) - Required - Sub-channel ID - **role_id** (string) - Required - Target role ID ### Response #### Success Response (200) - **data** (object) - Parsed JSON data. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official error trace ID. - **result** (bool) - True if successful; otherwise False. ``` -------------------------------- ### Import SandBox Class Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Import the SandBox class from the SDK. This class is used to define the sandbox environment configuration for the bot. ```python from qg_botsdk import SandBox ``` -------------------------------- ### Get Sub-channel Member Permissions Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves the permissions for a specific user within a given sub-channel. Requires the operator to have sub-channel management permissions. ```APIDOC ## Get Sub-channel Member Permissions ### Description Used to obtain the permissions of user `user_id` in sub-channel `channel_id`. Requires the operator to have sub-channel management permissions (robot needs to be set as administrator). ### Method `bot.api.get_channel_member_permission()` ### Parameters #### Path Parameters - **channel_id** (string) - Required - Sub-channel ID - **user_id** (string) - Required - Target member's user ID ### Response #### Success Response (200) - **data** (object) - Parsed JSON data. - **http_code** (int) - HTTP status code. - **trace_id** (string) - Tencent official error trace ID. - **result** (bool) - True if successful; otherwise False. ``` -------------------------------- ### Get Sub-Channel Role Permissions Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Use this to retrieve the permissions for a specific role within a sub-channel. The operator must have channel management permissions. ```python bot.api.get_channel_role_permission() ``` -------------------------------- ### Get Sub-Channel Member Permissions Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Use this to retrieve the permissions for a specific user within a sub-channel. The operator must have channel management permissions. ```python bot.api.get_channel_member_permission() ``` -------------------------------- ### Clear Current Plugins, Commands, and Preprocessors Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Clear all current plugins, commands, and preprocessors for the bot instance. Requires SDK version >= 3.0.0. ```python bot.clear_current_plugins() ``` -------------------------------- ### Get Bot Admin Manager Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Retrieve the bot admin manager to manage global bot administrators. Requires SDK version >= 4.3.9. ```python bot.bot_admin_manager ``` ```python from qg_botsdk import BOT bot = BOT(bot_id="xxx", bot_token="xxx") # 添加机器人管理员 bot.bot_admin_manager.add_admin("user_id_1", "user_id_2") # 检查是否为机器人管理员 if bot.bot_admin_manager.is_admin("user_id_1"): print("是机器人管理员") # 移除机器人管理员 bot.bot_admin_manager.remove_admin("user_id_1") # 获取所有机器人管理员 all_admins = bot.bot_admin_manager.get_all_admins() print(f"所有管理员:{all_admins}") ``` -------------------------------- ### Proto.webhook() Configuration Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Configure the Webhook connection protocol. This method creates a reverse WebSocket for the `remote_webhook()` method. SSL certificate paths are required if not handled by a reverse proxy. ```python Proto.webhook() ``` -------------------------------- ### Import Plugins Module Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/Plugins插件开发.md Import the Plugins module to begin developing custom bot functionalities. ```python from qg_botsdk import Plugins ## 导入插件开发模块 ``` -------------------------------- ### Get Guild Message Frequency Setting Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Retrieves the message frequency settings for a bot within a specific guild. This function is part of the API module. ```python bot.api.get_guild_setting() # v2.2.0前路径:qg_botsdk.qg_bot.BOT().get_guild_setting() # v2.2.0后路径:qg_botsdk.qg_bot.BOT().api.get_guild_setting() ``` -------------------------------- ### Clear Current Plugins, Commands, and Preprocessors Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Clear all current plugins, commands, and preprocessors for the bot instance. Requires SDK version >= 3.0.0. ```APIDOC ## Clear Current Plugins, Commands, and Preprocessors ### Description Clear all current plugins, commands, and preprocessors for the bot instance. ### Method Function Call ### Endpoint bot.clear_current_plugins() ### Parameters None ### Request Example ```python bot.clear_current_plugins() ``` ``` -------------------------------- ### Get Bot Information Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Retrieve the bot's channel user ID, username, and avatar. This provides access to the bot's profile information. ```yaml bot.robot: - bot.robot.id - bot.username - bot.avatar # 路径:qg_botsdk.BOT().robot.id/username/avatar ``` -------------------------------- ### Construct AT Mention String Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/Model库.md Use the AT class to build strings that mention other users. Pass the user ID as a string argument. ```python from qg_botsdk import AT AT('123456789') ## 返回 "<@123456789>" ``` -------------------------------- ### Auto Load Plugins Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Automatically scan and load all Python files in a plugin directory. Requires SDK version >= 4.3.9. ```APIDOC ## Auto Load Plugins ### Description Automatically scan and load all Python files in a plugin directory. ### Method Function Call ### Endpoint bot.load_plugins_auto(plugins_dir="plugins", recursive=False, pattern="*.py") ### Parameters #### Request Body - **plugins_dir** (str) - Optional - The path to the plugin directory. Defaults to the `plugins_dir` provided during initialization. - **recursive** (bool) - Optional - Whether to recursively scan subdirectories. Defaults to `False`. - **pattern** (str) - Optional - The file matching pattern. Defaults to "*.py". ### Request Example ```python from qg_botsdk import BOT bot = BOT(bot_id="xxx", bot_token="xxx") # Basic usage: load all plugins in the default directory bot.load_plugins_auto() # Specify a directory bot.load_plugins_auto("my_plugins") # Recursively scan subdirectories bot.load_plugins_auto("plugins", recursive=True) # Custom matching pattern bot.load_plugins_auto("plugins", pattern="*_plugin.py") ``` > **Note**: Files starting with `_` (e.g., `__init__.py`) are automatically skipped. ``` -------------------------------- ### Instantiate BOT in Sandbox Mode Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/常见问题Q&A.md To enable a sandbox environment for testing, pass `is_sandbox=True` when instantiating the BOT class. This isolates bot execution without affecting the main application. ```python from qg_botsdk.qg_bot import BOT bot = BOT('BotAppID', 'BotToken', is_sandbox=True) ``` -------------------------------- ### Bind Audio Event Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/SDK组件.md Use this function to bind handlers for receiving audio events like AUDIO_START, AUDIO_FINISH, AUDIO_ON_MIC, and AUDIO_OFF_MIC. The callback function should accept a data object of type Model.AUDIO_ACTION. ```python def audio_function(data): # 可使用 def msg_function(data: Model.AUDIO_ACTION): 调用模型数据 """ 这是接收音频事件的函数,包含了一个data的参数以接收Object类型数据 :param data: 可从model取用模型数据,方法 —— data: Model.AUDIO_ACTION """ if data.t == 'AUDIO_ON_MIC ': bot.logger.info('频道ID:%s 子频道ID:%s 已上麦' % (data.guild_id, data.channel_id)) bot = BOT(bot_id='xxx', bot_token='xxx') bot.bind_audio(callback=audio_function) # 路径:qg_botsdk.qg_bot.BOT().bind_audio() ``` -------------------------------- ### Get Channel Details Source: https://github.com/glgdly/qg_botsdk/blob/master/docs/API.md Use this method to retrieve the details of a specified channel using its guild_id. Ensure you are using the correct path based on your SDK version. ```python bot.api.get_guild_info() ```