### Install WcfAuto Client Source: https://github.com/lich0821/wechatferry/blob/master/clients/pyauto/README.MD The command to install or upgrade the WcfAuto Python package via pip. ```shell pip install --upgrade wcfauto ``` -------------------------------- ### Install vcpkg and Integrate with Visual Studio Source: https://github.com/lich0821/wechatferry/blob/master/README.MD Instructions for installing vcpkg, a C++ package manager, and integrating it with Visual Studio. This is a prerequisite for compiling WeChatFerry. ```shell cd C:\Tools git clone https://github.com/microsoft/vcpkg .\vcpkg\bootstrap-vcpkg.bat ``` ```shell setx VCPKG_ROOT "C:/Tools/vcpkg" /M ``` ```shell vcpkg integrate install ``` -------------------------------- ### Install WeChatFerry with Pip (Python) Source: https://github.com/lich0821/wechatferry/blob/master/README.MD Installs or upgrades the WeChatFerry Python package using pip. This is the primary method for Python users to get started. ```shell pip install --upgrade wcferry ``` -------------------------------- ### Install Python Dependencies for WeChatFerry Source: https://github.com/lich0821/wechatferry/blob/master/README.MD Installs the necessary Python dependencies for WeChatFerry development, specifically grpcio-tools with a version constraint. ```shell pip install grpcio-tools==1.48.2 ``` -------------------------------- ### Get Databases Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves a list of available databases. ```APIDOC ## GET /get_dbs ### Description Lists all the databases that are accessible or managed by the system. ### Method GET ### Endpoint /get_dbs ### Parameters None ### Response #### Success Response (200) - **databases** (List[str]) - A list of database names. #### Error Response (Non-200) - **message** (str) - An error message indicating failure. ### Response Example ```json { "databases": [ "database1", "database2" ] } ``` ``` -------------------------------- ### Implement WeChat Bot with WcfAuto Source: https://github.com/lich0821/wechatferry/blob/master/clients/pyauto/README.MD A complete example demonstrating how to register message handlers, send text, images, and files, and query WeChat databases using the WcfAuto library. ```python #! /usr/bin/env python3 # -*- coding: utf-8 -*- import logging from time import sleep from wcfauto import Register, Wcf, WxMsg logging.basicConfig(level='DEBUG', format="%(asctime)s %(message)s") LOG = logging.getLogger("Demo") def main(): receiver = Register() @receiver.message_register(isDivision=True, isGroup=True, isPyq=False) def process_msg(bot: Wcf, msg: WxMsg): LOG.info(f"收到消息: {msg}") sleep(5) LOG.info(f"已经登录: {True if bot.is_login() else False}") LOG.info(f"wxid: {bot.get_self_wxid()}") sleep(5) ret = bot.send_text("Hello world.", "filehelper") LOG.info(f"send_text: {ret}") sleep(5) ret = bot.send_image("https://raw.githubusercontent.com/lich0821/WeChatFerry/master/assets/QR.jpeg", "filehelper") LOG.info(f"send_image: {ret}") sleep(5) ret = bot.send_file("https://raw.githubusercontent.com/lich0821/WeChatFerry/master/README.MD", "filehelper") LOG.info(f"send_file: {ret}") sleep(5) LOG.info(f"Message types:\n{bot.get_msg_types()}") LOG.info(f"Contacts:\n{bot.get_contacts()}") sleep(5) LOG.info(f"DBs:\n{bot.get_dbs()}") LOG.info(f"Tables:\n{bot.get_tables('db')}") LOG.info(f"Results:\n{bot.query_sql('MicroMsg.db', 'SELECT * FROM Contact LIMIT 1;')}") sleep(5) bot.refresh_pyq(0) @receiver.async_message_register() async def async_process_msg(bot: Wcf, msg: WxMsg): print(msg) @receiver.group_changed_register(allow_other_receive=False) async def group_changed(bot: Wcf, msg: WxMsg): print(msg) @receiver.revoke_message_register(allow_other_receive=False) async def group_changed(bot: Wcf, msg: WxMsg): print(msg) print(msg.get_revoke_msg()) def judge(msg: WxMsg): return False @receiver.custom_message_register(register_name='custom', msg_judge_func=judge, allow_other_receive=False) async def group_changed(bot: Wcf, msg: WxMsg): print(msg) receiver.run() if __name__ == "__main__": main() ``` -------------------------------- ### Wcf Client Initialization Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Initializes the Wcf client for WeChatFerry. It can start a local RPC server or connect to a remote one. ```APIDOC ## Wcf Client Initialization ### Description Initializes the Wcf client for WeChatFerry. It can start a local RPC server or connect to a remote one. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from wcferry import Wcf # Initialize with default settings (starts a local server on port 10086) client = Wcf() # Initialize connecting to a remote server # client = Wcf(host='remote_host', port=10086) ``` ### Response #### Success Response (200) None (Initialization is synchronous) #### Response Example None ``` -------------------------------- ### Get Databases - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves a list of available database names. Returns a list of strings, where each string is a database name. ```python def get_dbs() -> list[str]: """Gets all available database names. Returns: A list of database names. """ pass ``` -------------------------------- ### Basic WeChat Client Operations in Go Source: https://context7.com/lich0821/wechatferry/llms.txt Demonstrates basic WeChat client operations using the Go SDK, including connecting to the RPC service, checking login status, getting the user's wxid, and sending a text message. ```Go package main import ( "fmt" "github.com/lich0821/WeChatFerry/clients/go/wcf" ) func main() { // 创建客户端,连接 RPC 服务 client, err := wcf.NewWCF("") if err != nil { panic(err) } defer client.Close() // 检查登录状态 if client.IsLogin() { fmt.Println("已登录") } // 获取自己的 wxid wxid := client.GetSelfWxid() fmt.Printf("wxid: %s\n", wxid) // 发送文本消息 err = client.SendText("Hello from Go!", "wxid_xxxxx", "") if err != nil { fmt.Printf("发送失败: %v\n", err) } } ``` -------------------------------- ### Get Database Tables Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves all tables from a specified database, along with their creation statements. ```python def get_tables(db: str) -> List[Dict]: """获取 db 中所有表""" pass ``` -------------------------------- ### Get User Info Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Fetches the personal information of the logged-in account. ```python def get_user_info() -> Dict: """获取登录账号个人信息""" pass ``` -------------------------------- ### Get Login QR Code Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Fetches the login QR code. Returns an empty string if already logged in. ```python def get_qrcode() -> str: """获取登录二维码,已经登录则返回空字符串""" pass ``` -------------------------------- ### Initialize Wcf Client Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Initializes the Wcf client for interacting with the WeChatFerry RPC server. It can connect to a remote server or start a local one. Options include setting the host, port, debug mode, and blocking behavior for login. ```python from wcferry import Wcf # Connect to a local server client = Wcf(port=10086, debug=True, block=True) # Connect to a remote server # client = Wcf(host='192.168.1.100', port=10086) ``` -------------------------------- ### Get Self WxID Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves the wxid of the logged-in account. ```python def get_self_wxid() -> str: """获取登录账户的 wxid""" pass ``` -------------------------------- ### Get Message Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves messages from the message queue. ```APIDOC ## GET /get_msg ### Description Fetches messages from the internal message queue. This is the primary way to receive incoming messages. ### Method GET ### Endpoint /get_msg ### Parameters #### Query Parameters - **block** (bool) - Optional - If true, the request will block until a message is available. Defaults to true. ### Response #### Success Response (200) - **message** (WxMsg) - An object representing the received WeChat message. #### Error Response (Non-200) - **message** (str) - An error message indicating failure or an empty queue if not blocking. ### Response Example ```json { "message": { "type": 1, "content": "Hello there!", "from_wxid": "sender_wxid", "to_wxid": "my_wxid", "msg_id": "msg_id_789" } } ``` ``` -------------------------------- ### Debugging Log Output (C++) Source: https://github.com/lich0821/wechatferry/blob/master/README.MD Provides examples of how to output debug messages using different methods in C++. This includes a custom utility function, OutputDebugString, and a MessageBox. ```c++ util::dbg_msg("ListenMessage"); // 封装的 OutputDebugString OutputDebugString(L"ListenMessage\n"); MessageBox(NULL, L"ListenMessage", L"ListenMessage", 0); ``` -------------------------------- ### Get Message Types Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves a dictionary of all supported message types. ```APIDOC ## GET /get_msg_types ### Description Provides a mapping of all known message types and their corresponding identifiers. ### Method GET ### Endpoint /get_msg_types ### Parameters None ### Response #### Success Response (200) - **msg_types** (Dict) - A dictionary where keys are message type names and values are their integer identifiers. #### Error Response (Non-200) - **message** (str) - An error message indicating failure. ### Response Example ```json { "msg_types": { "text": 1, "image": 3, "audio": 34 } } ``` ``` -------------------------------- ### Get Info by WXID - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves user information (like nickname, gender) based on their WXID. Requires the user's WXID as input. Returns a dictionary containing user details. ```python def get_info_by_wxid(wxid: str) -> dict: """Gets user information by WXID. Args: wxid: The WXID of the contact. Returns: A dictionary containing user info {wxid, code, name, gender}. """ pass ``` -------------------------------- ### HTTP API - Get Chatrooms Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves a list of all chatrooms the user is a member of. Returns a JSON array of chatroom objects. ```bash curl -X POST http://localhost:8080/wcf/chatrooms ``` -------------------------------- ### GET /loginStatus Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcf-bmc/CHANGELOG.md Checks the current login status of the WeChat client. ```APIDOC ## GET /loginStatus ### Description Returns the current login status of the WeChat client. ### Method GET ### Endpoint /loginStatus ### Response #### Success Response (200) - **status** (boolean) - True if logged in, false otherwise. #### Response Example { "status": true } ``` -------------------------------- ### GET /loginStatus Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcf-bmc/CHANGELOG.md Checks the current login status of the WeChat client. ```APIDOC ## GET /loginStatus ### Description Checks whether the WeChat client is currently logged in. ### Method GET ### Endpoint /loginStatus ### Response #### Success Response (200) - **status** (boolean) - Returns true if logged in, false otherwise. #### Response Example { "status": true } ``` -------------------------------- ### HTTP API - Get Self Info Source: https://context7.com/lich0821/wechatferry/llms.txt Fetches detailed information about the currently logged-in user, including nickname, wxid, and other profile details. Returns a JSON object with user information. ```bash curl -X POST http://localhost:8080/wcf/self_info ``` -------------------------------- ### Get Audio Message Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves an audio message and converts it to MP3 format. ```APIDOC ## POST /get_audio_msg ### Description Fetches an audio message by its ID and converts it into an MP3 file, saving it to a specified directory. ### Method POST ### Endpoint /get_audio_msg ### Parameters #### Query Parameters - **id** (int) - Required - The ID of the audio message. - **dir** (str) - Required - The directory where the converted MP3 file will be saved. This directory must exist. - **timeout** (int) - Optional - The timeout in seconds for the operation. Defaults to 3. ### Response #### Success Response (200) - **path** (str) - The file path of the saved MP3 audio. #### Error Response (Non-200) - **message** (str) - An error message indicating failure. ### Request Example ```json { "id": 98765, "dir": "/path/to/save/audio" } ``` ### Response Example ```json { "path": "/path/to/save/audio/audio.mp3" } ``` ``` -------------------------------- ### Get Info by WXID Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves user information using their WeChat ID (WXID). ```APIDOC ## GET /get_info_by_wxid ### Description Retrieves detailed information about a WeChat user, such as their nickname and gender, given their unique WeChat ID. ### Method GET ### Endpoint /get_info_by_wxid ### Parameters #### Query Parameters - **wxid** (str) - Required - The WeChat ID of the user. ### Response #### Success Response (200) - **user_info** (dict) - A dictionary containing user details like 'wxid', 'code', 'name', and 'gender'. #### Error Response (Non-200) - **message** (str) - An error message indicating failure. ### Request Example ```json { "wxid": "user_wxid_111" } ``` ### Response Example ```json { "user_info": { "wxid": "user_wxid_111", "code": "000001", "name": "Charlie", "gender": "male" } } ``` ``` -------------------------------- ### Get Chatroom Members - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves a list of members for a given chatroom ID. Returns a dictionary where keys are wxids and values are their nicknames within the chatroom. ```python def get_chatroom_members(roomid: str) -> dict: """Gets the members of a chatroom. Args: roomid: The ID of the chatroom. Returns: A dictionary of members {wxid: nickname}. """ pass ``` -------------------------------- ### Get Audio Message as MP3 - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves an audio message and converts it to an MP3 file. Requires the message ID, a directory to save the MP3, and an optional timeout. Returns the saved MP3 path on success or an empty string on failure. ```python def get_audio_msg(id: int, dir: str, timeout: int = 3) -> str: """Gets an audio message and converts it to MP3. Args: id: The ID of the audio message. dir: The directory to save the MP3 file. Will error if it doesn't exist. timeout: Timeout in seconds. Returns: The saved path on success, or an empty string on failure. """ pass ``` -------------------------------- ### Get Contacts - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves the entire contact list. Returns a list of dictionaries, where each dictionary contains information about a contact. ```python def get_contacts() -> list[dict]: """Gets the complete contact list. Returns: A list of contact dictionaries. """ pass ``` -------------------------------- ### Get Audio Message as MP3 Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves an audio message, converts it to MP3 format, and saves it to a specified directory. Requires message ID, save directory, and supports timeout. ```python from wcferry import Wcf wcf = Wcf() # 获取语音消息并转为 MP3 path = wcf.get_audio_msg( id=1234567890, # 语音消息 ID dir="C:/Downloads", # 保存目录 timeout=10 # 超时时间(秒) ) if path: print(f"语音已保存到: {path}") ``` -------------------------------- ### HTTP API - Get Contacts Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves a list of all contacts, including friends, groups, and official accounts. Returns a JSON array of contact objects. ```bash curl -X POST http://localhost:8080/wcf/contacts ``` -------------------------------- ### Build wechatFerry HTTP Server for Windows Source: https://github.com/lich0821/wechatferry/blob/master/clients/go_wcf_http/README.MD This command compiles the Go source code into a Windows executable. It uses ldflags to strip debug information and sets the target architecture to amd64. ```batch set GOOS=windows set GOARCH=amd64 go build -ldflags="-s -w" -o go_wcf_http3.9.10.27.exe .\main.go ``` -------------------------------- ### Get Friends Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves a list of all friends. ```APIDOC ## GET /get_friends ### Description Fetches a list of all contacts identified as friends. ### Method GET ### Endpoint /get_friends ### Parameters None ### Response #### Success Response (200) - **friends** (List[Dict]) - A list of dictionaries, where each dictionary represents a friend with their details. #### Error Response (Non-200) - **message** (str) - An error message indicating failure. ### Response Example ```json { "friends": [ { "wxid": "friend1_wxid", "name": "Alice", "remark": "Bestie" } ] } ``` ``` -------------------------------- ### Generate Protobuf Files Source: https://github.com/lich0821/wechatferry/blob/master/WeChatFerry/spy/CMakeLists.txt Configures a custom build command to generate C source and header files from a .proto definition using the nanopb compiler. ```cmake add_custom_command( OUTPUT ${CMAKE_SOURCE_DIR}/rpc/proto/wcf.pb.c ${CMAKE_SOURCE_DIR}/rpc/proto/wcf.pb.h COMMAND ${CMAKE_SOURCE_DIR}/rpc/tool/protoc --nanopb_out=${CMAKE_SOURCE_DIR}/rpc/proto wcf.proto WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/rpc/proto DEPENDS ${CMAKE_SOURCE_DIR}/rpc/proto/wcf.proto COMMENT "Generated protobuf files" ) add_custom_target(protobuf_generation DEPENDS ${CMAKE_SOURCE_DIR}/rpc/proto/wcf.pb.c ${CMAKE_SOURCE_DIR}/rpc/proto/wcf.pb.h ) add_dependencies(spy protobuf_generation) ``` -------------------------------- ### Initialize and Destroy WeChatFerry SDK (Python) Source: https://github.com/lich0821/wechatferry/blob/master/README.MD Demonstrates how to load the WeChatFerry SDK dynamic library and initialize/destroy the SDK using ctypes in Python. This is essential for interacting with the WeChat client. ```python import ctypes # 加载 sdk.dll (需要绝对路径) sdk = ctypes.cdll.LoadLibrary("C:/Projs/WeChatFerry/WeChatFerry/Out/sdk.dll") # 初始化 sdk.WxInitSDK(False, 10086) # 退出 SDK sdk.WxDestroySDK() # 注意关闭 Python 进程 ``` -------------------------------- ### Get Contacts Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves the entire contact list of the user. ```APIDOC ## GET /get_contacts ### Description Fetches a comprehensive list of all contacts associated with the logged-in WeChat account. ### Method GET ### Endpoint /get_contacts ### Parameters None ### Response #### Success Response (200) - **contacts** (List[Dict]) - A list of dictionaries, where each dictionary represents a contact with their details. #### Error Response (Non-200) - **message** (str) - An error message indicating failure. ### Response Example ```json { "contacts": [ { "wxid": "user1_wxid", "name": "Alice", "remark": "Friend" }, { "wxid": "group_id_1", "name": "My Group" } ] } ``` ``` -------------------------------- ### Initialize WeChatFerry Client Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Instantiates the Wcf client to connect to the WeChatFerry RPC server. It allows configuration of host, port, and connection behavior. ```python from wcferry import Wcf # Initialize client with default settings wcf = Wcf(host=None, port=10086, debug=True, block=True) ``` -------------------------------- ### Initialize Wcf Client (Python) Source: https://context7.com/lich0821/wechatferry/llms.txt Initializes the Wcf client for WeChatFerry. Supports both local mode (auto-injecting WeChat) and remote mode (connecting to an existing RPC server). It also demonstrates checking login status and retrieving QR codes for login. ```python from wcferry import Wcf # 本地模式:自动启动并注入微信进程 wcf = Wcf(port=10086, debug=True, block=True) # 远程模式:连接已启动的 RPC 服务 wcf = Wcf(host="192.168.1.100", port=10086, block=True) # 检查登录状态 if wcf.is_login(): print(f"已登录,wxid: {wcf.get_self_wxid()}") else: # 获取登录二维码(base64 编码) qrcode = wcf.get_qrcode() print(f"请扫码登录: {qrcode}") # 获取登录账号信息 user_info = wcf.get_user_info() print(f"昵称: {user_info.get('name')}") print(f"手机: {user_info.get('mobile')}") print(f"数据目录: {user_info.get('home')}") ``` -------------------------------- ### WxMsg Object and Message Handling in Python Source: https://context7.com/lich0821/wechatferry/llms.txt Demonstrates how to use the WxMsg object in Python to access message properties and use convenient methods for checking message types and origins. It also shows how to enable message receiving and retrieve messages. ```Python from wcferry import Wcf wcf = Wcf() wcf.enable_receiving_msg() msg = wcf.get_msg() # 消息属性 print(f"消息 ID: {msg.id}") # 消息唯一标识 print(f"消息类型: {msg.type}") # 消息类型编号 print(f"发送者: {msg.sender}") # 发送者 wxid print(f"群 ID: {msg.roomid}") # 群消息时为群 ID,否则为空 print(f"内容: {msg.content}") # 消息内容 print(f"XML: {msg.xml}") # 消息 XML 部分 print(f"缩略图: {msg.thumb}") # 图片/视频缩略图路径 print(f"附件: {msg.extra}") # 图片/视频/文件路径 print(f"时间戳: {msg.ts}") # 消息时间戳 # 便捷判断方法 if msg.from_group(): print("这是群消息") if msg.from_self(): print("这是自己发的消息") if msg.is_text(): print("这是文本消息") if msg.is_at(wcf.self_wxid): print("有人 @ 了我") ``` -------------------------------- ### Generate Java Protobuf Classes Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcferry/README.MD Use the protoc compiler to generate Java source files from the wcf.proto definition file. ```bash cd C:/Projs/WeChatFerry/java/wcferry/src/main/java protoc.exe --java_out=. --proto_path=C:\Projs\WeChatFerry\WeChatFerry\rpc\proto wcf.proto ``` -------------------------------- ### Get Chatroom Members Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves a list of members within a specified chatroom. ```APIDOC ## GET /get_chatroom_members ### Description Fetches all members of a given chatroom, returning their WeChat IDs and nicknames. ### Method GET ### Endpoint /get_chatroom_members ### Parameters #### Query Parameters - **roomid** (str) - Required - The ID of the chatroom. ### Response #### Success Response (200) - **members** (Dict) - A dictionary where keys are WeChat IDs (wxid) and values are the members' nicknames. #### Error Response (Non-200) - **message** (str) - An error message indicating failure. ### Request Example ```json { "roomid": "room_id_abc" } ``` ### Response Example ```json { "members": { "user1_wxid": "Alice", "user2_wxid": "Bob" } } ``` ``` -------------------------------- ### Configure Gradle Dependencies Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcferry/README.MD Add JNA and local library dependencies to your build.gradle file to support the WeChatFerry client. ```groovy implementation 'net.java.dev.jna:jna:5.6.0' implementation fileTree(dir: 'libs', include: ['*.jar']) ``` -------------------------------- ### Build a WeChat Auto-Reply Bot with Python Source: https://context7.com/lich0821/wechatferry/llms.txt This script demonstrates how to initialize the WeChatFerry client, enable message reception, and implement a basic keyword-based auto-reply system. It includes logic for handling text messages, group mentions, and time queries. ```python from wcferry import Wcf from queue import Empty import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("Bot") def main(): wcf = Wcf() if not wcf.is_login(): logger.info("请扫码登录...") qrcode = wcf.get_qrcode() while not wcf.is_login(): pass logger.info(f"登录成功: {wcf.get_self_wxid()}") wcf.enable_receiving_msg() try: while True: try: msg = wcf.get_msg(block=True) process_message(wcf, msg) except Empty: continue except KeyboardInterrupt: logger.info("机器人已停止") finally: wcf.cleanup() def process_message(wcf, msg): if msg.from_self(): return if msg.is_text(): content = msg.content.strip() sender = msg.roomid if msg.from_group() else msg.sender if "你好" in content: wcf.send_text("你好!有什么可以帮助你的吗?", sender) elif "帮助" in content: help_text = "可用命令:\n- 你好:打招呼\n- 时间:查询当前时间\n- 帮助:显示此帮助" wcf.send_text(help_text, sender) elif "时间" in content: from datetime import datetime now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") wcf.send_text(f"当前时间:{now}", sender) if msg.from_group() and msg.is_at(wcf.self_wxid): wcf.send_text("有什么需要帮忙的?", sender) if __name__ == "__main__": main() ``` -------------------------------- ### Get Alias in Chatroom Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves a user's alias (nickname) within a specific chatroom. ```APIDOC ## GET /get_alias_in_chatroom ### Description Fetches the specific alias or nickname a user has within a particular group chat. ### Method GET ### Endpoint /get_alias_in_chatroom ### Parameters #### Query Parameters - **wxid** (str) - Required - The WeChat ID of the user. - **roomid** (str) - Required - The ID of the chatroom. ### Response #### Success Response (200) - **alias** (str) - The user's alias in the chatroom. #### Error Response (Non-200) - **message** (str) - An error message indicating failure. ### Request Example ```json { "wxid": "user_wxid_789", "roomid": "room_id_xyz" } ``` ### Response Example ```json { "alias": "Group Nickname" } ``` ``` -------------------------------- ### Refresh Moments Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Refreshes WeChat Moments. An optional ID can be provided to start refreshing from a specific point. ```python def refresh_pyq(id: int = 0) -> int: """刷新朋友圈""" pass ``` -------------------------------- ### Compile NNG Library Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcferry/README.MD Configure the NNG library build with TLS support enabled using CMake. ```bash cmake -DBUILD_SHARED_LIBS=ON -DNNG_ENABLE_TLS=ON -DMBEDTLS_ROOT_DIR="C:\Program Files (x86)\mbed TLS" .. ``` -------------------------------- ### Get Friends List - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves the list of friends. Returns a list of dictionaries, where each dictionary represents a friend. ```python from typing import List, Dict def get_friends() -> List[Dict]: """获取好友列表""" pass ``` -------------------------------- ### Get Database Names via HTTP API Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves a list of available database names on the WeChat client. ```HTTP curl -X POST http://localhost:8080/wcf/db_names ``` -------------------------------- ### Enable Receiving Messages - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Enables the reception of messages. Can optionally be configured for 'pyq' (likely 'pyq' messages). Successful enabling allows messages to be read using get_msg. ```python def enable_receiving_msg(pyq=False) -> bool: """允许接收消息,成功后通过 get_msg 读取消息""" pass ``` -------------------------------- ### Get Friends - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves the list of friends. Returns a list of dictionaries, where each dictionary contains information about a friend. ```python def get_friends() -> list[dict]: """Gets the friend list. Returns: A list of friend dictionaries. """ pass ``` -------------------------------- ### POST /exec/dbQuerySql Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcf-bmc/CHANGELOG.md Executes a SQL query against the WeChat local database. ```APIDOC ## POST /exec/dbQuerySql ### Description Executes a custom SQL query on the specified WeChat database. ### Method POST ### Endpoint /exec/dbQuerySql ### Request Body - **db** (string) - Required - The database name. - **sql** (string) - Required - The SQL query string. ### Request Example { "db": "MicroMsg.db", "sql": "SELECT * FROM Contact" } ### Response #### Success Response (200) - **data** (array) - The result set of the query. #### Response Example { "data": [] } ``` -------------------------------- ### Compile Mbed TLS Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcferry/README.MD Commands to configure and build the Mbed TLS library using CMake on Windows. ```bash cd build cmake .. ``` -------------------------------- ### Enable and Receive Messages (Python) Source: https://context7.com/lich0821/wechatferry/llms.txt Enables message receiving functionality and retrieves messages from a queue. Using a queue is recommended to prevent message loss. Supports receiving normal messages and朋友圈 (Moments) messages. ```python from wcferry import Wcf from queue import Empty wcf = Wcf() # 启用消息接收,pyq=True 可同时接收朋友圈消息 wcf.enable_receiving_msg(pyq=False) # 循环读取消息 while wcf.is_receiving_msg(): try: msg = wcf.get_msg(block=True) # 阻塞等待消息 # 消息基本属性 print(f"消息ID: {msg.id}") print(f"消息类型: {msg.type}") print(f"发送者: {msg.sender}") print(f"内容: {msg.content}") # 判断消息来源 if msg.from_group(): print(f"来自群聊: {msg.roomid}") if msg.from_self(): print("这是自己发送的消息") # 判断是否被 @ if msg.is_at(wcf.self_wxid): print("有人 @ 了我") # 处理图片/视频消息 if msg.thumb: print(f"缩略图: {msg.thumb}") if msg.extra: print(f"附件路径: {msg.extra}") except Empty: continue # 超时,继续等待 except Exception as e: print(f"处理消息出错: {e}") ``` -------------------------------- ### Get Message Types - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves a dictionary of all available message types. This can be useful for understanding or processing different kinds of messages. ```python from typing import Dict def get_msg_types() -> Dict: """获取所有消息类型""" pass ``` -------------------------------- ### POST /query_sql Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Executes a SQL query against a specified database. ```APIDOC ## POST /query_sql ### Description Executes a SQL query on a specified database. Note: Use pagination for large datasets to avoid OOM. ### Method POST ### Endpoint /query_sql ### Parameters #### Request Body - **db** (string) - Required - The name of the database to query. - **sql** (string) - Required - The SQL statement to execute. ### Response #### Success Response (200) - **data** (List[Dict]) - The result set of the query. ``` -------------------------------- ### Get Database Tables via HTTP API Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves a list of tables within a specified database. Requires the database name. ```HTTP curl -X POST http://localhost:8080/wcf/db_tables \ -H "Content-Type: application/json" \ -d '{"db": "MicroMsg.db"}' ``` -------------------------------- ### Get Message Types - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves a dictionary of all available message types. This can be useful for understanding or filtering different kinds of messages. ```python def get_msg_types() -> dict: """Gets all message types. Returns: A dictionary of message types. """ pass ``` -------------------------------- ### POST /exec/dbQuerySql Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcf-bmc/CHANGELOG.md Executes a custom SQL query against the WeChat database. ```APIDOC ## POST /exec/dbQuerySql ### Description Allows execution of arbitrary SQL queries on the local WeChat database. ### Method POST ### Endpoint /exec/dbQuerySql ### Request Body - **db** (string) - Required - The database name. - **sql** (string) - Required - The SQL query string. ### Request Example { "db": "MicroMsg.db", "sql": "SELECT * FROM Contact" } ### Response #### Success Response (200) - **data** (array) - The result set of the query. #### Response Example { "data": [{"username": "wxid_1", "nickname": "test"}] } ``` -------------------------------- ### Get OCR Result Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Retrieves OCR results from an image. Note: This function may not work with images downloaded via the download interface. ```python def get_ocr_result(extra: str, timeout: int = 2) -> str: """获取 OCR 结果。鸡肋,需要图片能自动下载;通过下载接口下载的图片无法识别。""" pass ``` -------------------------------- ### Download Video - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Downloads a video from a message. Requires message ID, thumbnail data, a directory to save the video, and an optional timeout. Returns the saved file path on success or an empty string on failure. ```python def download_video(id: int, thumb: str, dir: str, timeout: int = 30) -> str: """下载视频""" pass ``` -------------------------------- ### Get Chatroom Members via HTTP API Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves a list of members belonging to a specified chatroom. Requires the chatroom's ID. ```HTTP curl -X POST http://localhost:8080/wcf/chatroom_members \ -H "Content-Type: application/json" \ -d '{"roomid": "xxxxx@chatroom"}' ``` -------------------------------- ### Download Video - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Downloads a video from a message. It requires the message ID, a thumbnail identifier, a directory to save the video, and an optional timeout. Returns the saved path on success or an empty string on failure. ```python def download_video(id: int, thumb: str, dir: str, timeout: int = 30) -> str: """Downloads a video. Args: id: The message ID. thumb: The video's thumbnail identifier. dir: The directory to save the video. Will error if it doesn't exist. timeout: Timeout in seconds. Returns: The saved path on success, or an empty string on failure. """ pass ``` -------------------------------- ### HTTP API - Get Friends Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves a list of only friend contacts, excluding groups and official accounts. Returns a JSON array of friend objects. ```bash curl -X POST http://localhost:8080/wcf/friends ``` -------------------------------- ### POST /wcf/db_query_sql Source: https://context7.com/lich0821/wechatferry/llms.txt Executes a custom SQL query against the local WeChat database files. ```APIDOC ## POST /wcf/db_query_sql ### Description Runs a SQL query on a specified database file. ### Method POST ### Endpoint http://localhost:8080/wcf/db_query_sql ### Request Body - **db** (string) - Required - The database filename (e.g., MicroMsg.db) - **sql** (string) - Required - The SQL query string ### Request Example { "db": "MicroMsg.db", "sql": "SELECT UserName, NickName FROM Contact LIMIT 10" } ``` -------------------------------- ### Get Message Types Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves a dictionary mapping all supported message type IDs to their corresponding names. Useful for identifying and processing different kinds of messages. ```python from wcferry import Wcf wcf = Wcf() # 获取消息类型字典 msg_types = wcf.get_msg_types() for type_id, type_name in msg_types.items(): print(f"{type_id}: {type_name}") # 常见消息类型: # 1: 文本 # 3: 图片 # 34: 语音 # 42: 名片 # 43: 视频 # 47: 表情 # 49: 链接/文件/小程序等 # 10000: 系统消息 ``` -------------------------------- ### Enable Receiving Messages with Callback - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Sets a callback for receiving messages. This method is not recommended for high message volumes as it may lead to message loss. It takes a callback function that processes incoming WxMsg objects. ```python from typing import Callable def enable_recv_msg(callback: Callable[[WxMsg], None] = None) -> bool: """Sets a callback for receiving messages (deprecated). Args: callback: A function to process incoming WxMsg objects. Returns: True if successful, False otherwise. """ pass ``` -------------------------------- ### Get Message - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves messages from the message queue. By default, it blocks until a message is available. Can be configured to not block. Raises an Empty exception on timeout if blocking. ```python def get_msg(block=True) -> WxMsg: """Gets a message from the message queue. Args: block: Whether to block until a message is available (default True). Returns: A WxMsg object. Raises: Empty: If blocking and a timeout occurs. """ pass ``` -------------------------------- ### Enable Receiving Messages - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Enables the reception of messages. After enabling, messages can be read using get_msg. An optional parameter `pyq` can be set to True for specific message types. ```python def enable_receiving_msg(pyq=False) -> bool: """Enables message reception. Args: pyq: Boolean flag for specific message types. Returns: True if successful, False otherwise. """ pass ``` -------------------------------- ### HTTP API - Get Self WxID Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves the WeChat ID (wxid) of the currently logged-in user. Returns a JSON response containing the user's wxid. ```bash curl -X POST http://localhost:8080/wcf/self_wxid ``` -------------------------------- ### wcferry.client API Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/index.md The client module provides the primary interface for interacting with the WeChat process. ```APIDOC ## GET /wcferry/client ### Description Initializes and manages the connection to the WeChat process for message interception and command execution. ### Method GET ### Endpoint /wcferry/client ### Parameters #### Query Parameters - **host** (string) - Optional - The host address of the WCF service. - **port** (int) - Optional - The port number of the WCF service. ### Request Example { "host": "127.0.0.1", "port": 10086 } ### Response #### Success Response (200) - **status** (string) - Connection status of the client. #### Response Example { "status": "connected" } ``` -------------------------------- ### Download Attach Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Downloads attachments like images, videos, or files. It's recommended to use `download_image` for images. ```APIDOC ## POST /download_attach ### Description Downloads attachments like images, videos, or files. It's recommended to use `download_image` for images. ### Method POST ### Endpoint /download_attach ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (integer) - Required - The message ID associated with the attachment. - **thumb** (string) - Required - The thumb information from the message. - **extra** (string) - Required - The extra information from the message. ### Request Example ```json { "id": 123456789, "thumb": "thumb_data_string", "extra": "extra_data_string" } ``` ### Response #### Success Response (200) - **result** (integer) - 0 for success, other values indicate failure. #### Response Example ```json { "result": 0 } ``` ``` -------------------------------- ### Add Protobuf Dependency Source: https://github.com/lich0821/wechatferry/blob/master/clients/java/wcferry/README.MD Include the Google Protobuf library in your Gradle project. Ensure the version matches your protoc compiler version. ```groovy implementation 'com.google.protobuf:protobuf-java:3.22.2' ``` -------------------------------- ### Execute SQL Query Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Executes a SQL query on a specified database. Be mindful of large datasets to avoid Out Of Memory errors. ```python def query_sql(db: str, sql: str) -> List[Dict]: """执行 SQL,如果数据量大注意分页,以免 OOM""" pass ``` -------------------------------- ### Get Chatroom Alias - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/index.md Retrieves the alias (nickname) of a member within a specific chatroom. Requires the member's wxid and the chatroom's ID. Returns the member's alias within the chatroom. ```python def get_alias_in_chatroom(wxid: str, roomid: str) -> str: """Gets the alias of a member in a chatroom. Args: wxid: The wxid of the member. roomid: The ID of the chatroom. Returns: The member's alias in the chatroom. """ pass ``` -------------------------------- ### Enable Message Callback - Python Source: https://github.com/lich0821/wechatferry/blob/master/docs/source/autoapi/wcferry/client/index.md Sets a callback for receiving messages. This method is not recommended for high message volumes as it may lead to message loss. It takes a callback function that accepts a WxMsg object. ```python from typing import Callable from wcferry.wxmsg import WxMsg def enable_recv_msg(callback: Callable[[WxMsg], None] = None) -> bool: """(不建议使用)设置接收消息回调,消息量大时可能会丢失消息""" pass ``` -------------------------------- ### Configure Spy Library Build Source: https://github.com/lich0821/wechatferry/blob/master/WeChatFerry/spy/CMakeLists.txt Defines the Spy shared library, including source files, external dependencies like spdlog and nng, and custom build steps for Protocol Buffers. ```cmake project(Spy LANGUAGES C CXX) find_package(spdlog REQUIRED) find_package(magic_enum REQUIRED) find_package(minhook CONFIG REQUIRED) find_package(nng REQUIRED) add_library(spy SHARED spy.cpp dllmain.cpp spy.def ) target_link_libraries(spy PRIVATE magic_enum::magic_enum nng::nng spdlog::spdlog minhook::minhook ) ``` -------------------------------- ### POST /wcf/send_img Source: https://context7.com/lich0821/wechatferry/llms.txt Sends an image file from the local filesystem to a specified receiver. ```APIDOC ## POST /wcf/send_img ### Description Sends an image file located on the local disk. ### Method POST ### Endpoint http://localhost:8080/wcf/send_img ### Request Body - **path** (string) - Required - Full path to the image file - **receiver** (string) - Required - The wxid of the user or group ### Request Example { "path": "C:/Pictures/photo.jpg", "receiver": "wxid_xxxxx" } ``` -------------------------------- ### Get Contacts and Friends List Source: https://context7.com/lich0821/wechatferry/llms.txt Retrieves either the complete contact list (including groups and official accounts) or a filtered list of only friends. Each contact entry includes details like wxid, name, remark, WeChat ID, gender, and city. ```python from wcferry import Wcf wcf = Wcf() # 获取完整通讯录(包括群聊、公众号等) contacts = wcf.get_contacts() for contact in contacts: print(f"wxid: {contact['wxid']}") print(f"昵称: {contact['name']}") print(f"备注: {contact['remark']}") print(f"微信号: {contact['code']}") print(f"性别: {contact['gender']}") print(f"城市: {contact['city']}") print("---") # 仅获取好友列表(排除群聊、公众号等) friends = wcf.get_friends() print(f"好友数量: {len(friends)}") ```