### Install WeChatAuto SDK Dependencies Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/quick-start.html Before running the examples, install the necessary NuGet packages for WeChat automation and host building. ```bash dotnet add package WeChatAuto.SDK dotnet add package Microsoft.Extensions.Hosting ``` -------------------------------- ### Install WeChatAuto.SDK via NuGet Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/README.md Install the WeChatAuto.SDK package using the .NET CLI. ```bash dotnet add package WeChatAuto.SDK ``` -------------------------------- ### Basic WeChat Message Sending Example Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/README.md Demonstrates how to initialize the automation service, get a WeChat client instance, and send a message to a contact or group. Ensure your project's TargetFramework is set to a Windows-specific version (e.g., net10.0-windows). ```csharp using Microsoft.Extensions.DependencyInjection; using WeChatAuto.Components; using WeChatAuto.Services; // Initialize WeAutomation service var serviceProvider = WeAutomation.Initialize(options => { options.DebugMode = true; // Enable debug mode for visual feedback, recommended to disable in production //options.EnableRecordVideo = true; // Enable video recording feature, videos are saved in the Videos folder }); using var clientFactory = serviceProvider.GetRequiredService(); Console.WriteLine($"Currently open WeChat clients: {string.Join(",", clientFactory.GetWeChatClientNames())}, total: {clientFactory.GetWeChatClientNames().Count}."); // Get the list of currently open WeChat client names var clentNames = clientFactory.GetWeChatClientNames(); // Get the first WeChat client instance var wxClient = clientFactory.GetWeChatClient(clentNames.First()); // Send a message to the 'AI.Net' friend (or group nickname), please change to your own friend nickname await wxClient.SendWho("AI.Net","Hello, welcome to WeChatAuto.SDK WeChat automation framework!"); ``` -------------------------------- ### Install Additional Dependencies Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/README.md Add the WeChatAuto.SDK and Microsoft.Extensions.DependencyInjection packages to your project. ```bash dotnet add package WeChatAuto.SdK dotnet add package Microsoft.Extensions.DependencyInjection ``` -------------------------------- ### Install WeChat Auto SDK Dependencies Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/README.md Install the necessary NuGet packages for WeChat Auto SDK and Microsoft.Extensions.Hosting. ```bash dotnet add package WeChatAuto.SdK dotnet add package Microsoft.Extensions.Hosting ``` -------------------------------- ### MCP Server Configuration for VSCode Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/normal.html Configures the MCP server within VSCode's .vscode/mcp.json file to enable communication with the WeChatAuto.MCP project. This setup allows for starting the MCP server and interacting with it via GitHub Copilot Chat. ```json { "servers": { "wechat_mcp_server": { "type": "stdio", "command": "dotnet", "args": [ "run", "--project", "改成你的WeChatAuto.MCP.csproj的路径" ] } } } ``` -------------------------------- ### Initialize and Configure MCP Server in C# Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Programmatic setup for the MCP Server in `Program.cs`. It initializes the automation services, enables MCP server transport, registers tools, and configures the standard IO server. ```csharp // WeChatAuto.MCP/Program.cs 启动配置 WeAutomation.Initialize(builder.Services, options => { options.DebugMode = true; options.EnableMouseKeyboardSimulator = false; options.EnableRecordVideo = true; }) .AddMcpServer() .WithStdioServerTransport() // 标准 IO 传输(AI 工具通用接口) .WithToolsFromAssembly() // 自动注册所有 [McpServerTool] .WithPromptsFromAssembly(); builder.Services.AddSingleton(); await builder.Build().RunAsync(); ``` -------------------------------- ### Creating and Starting an STA Subthread for UI Operations Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/WeChatAutoWebSupport/Tests/test_resource/2.md Demonstrates how to create a subthread and explicitly set its apartment state to STA to handle UI operations or COM interactions. ```csharp // 主线程(通常是STA) [STAThread] static void Main() { // 主线程处理UI Application.Run(new MainForm()); } // 子线程(可以设置为STA) var uiThread = new Thread(() => { // 这个子线程也可以处理UI操作 var form = new DialogForm(); form.ShowDialog(); }); uiThread.SetApartmentState(ApartmentState.STA); // 设置为STA uiThread.Start(); ``` -------------------------------- ### Get All Messages Method Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Calls a method to retrieve all messages within the context. Each message is a MessageBubble object. ```csharp messageContext.GetAllMessages() ``` -------------------------------- ### Initialize WeAutomation Service and Get WeChatClientFactory Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/glossary.html Initializes the WeAutomation service with optional configurations like debug mode. It then retrieves the WeChatClientFactory, which is essential for managing WeChat client instances. ```csharp var serviceProvider = WeAutomation.Initialize(options => { options.DebugMode = true; //开启调试模式,调试模式会在获得焦点时边框高亮,生产环境建议关闭 //options.EnableRecordVideo = true; //开启录制视频功能,录制的视频会保存在项目的运行目录下的Videos文件夹中 }); //获取到WeChatClientFactory using var clientFactory = serviceProvider.GetRequiredService(); ``` -------------------------------- ### Get Owner Information Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Asynchronously retrieves the current user's (owner's) information. Returns a FriendInfo object. ```csharp public async Task GetOwnerInfo() ``` -------------------------------- ### Open WeChat Moments Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/friend-circle-operation.html Call this method to open the WeChat Moments window. No specific setup is required beyond having the SDK initialized. ```csharp public void OpenMoments() ``` -------------------------------- ### Get New Messages Method Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Calls a method to retrieve a list of new messages from the context. Each message is a MessageBubble object. ```csharp messageContext.GetNewMessages() ``` -------------------------------- ### Initializing a Dedicated STA Thread for FlaUI Operations Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/WeChatAutoWebSupport/Tests/test_resource/2.md This constructor initializes a new thread, sets its apartment state to STA, and starts it. This is often necessary for libraries like FlaUI that rely on UI Automation, which requires an STA thread. ```csharp public UIThreadInvoker() { _uiThread = new Thread(ThreadMain); _uiThread.SetApartmentState(ApartmentState.STA); // 设置为STA _uiThread.Start(); } ``` -------------------------------- ### Get Moment Content Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/listen-message.html Extract the text content of a moments post. This can be used as context for large language models. ```csharp public string GetMomentContent() ``` -------------------------------- ### Get LLM Context Messages (Overload) Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves a list of messages as tuples (sender, message) for constructing LLM historical context. ```csharp messageContext.GetLLMContextMessagesTuple ``` -------------------------------- ### Multiple STA Threads Handling UI Elements Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/WeChatAutoWebSupport/Tests/test_resource/2.md This example demonstrates that multiple STA threads can coexist and operate on different UI elements without conflict, as each STA thread has its own message loop and 'apartment'. ```csharp // 主线程(STA) [STAThread] static void Main() { // 主线程创建主窗口 var mainForm = new MainForm(); mainForm.Show(); // 主线程继续运行消息循环 Application.Run(); } // 子线程(也是STA) var dialogThread = new Thread(() => { // 子线程创建对话框 var dialog = new DialogForm(); dialog.ShowDialog(); // 这不会与主线程冲突! }); dialogThread.SetApartmentState(ApartmentState.STA); dialogThread.Start(); ``` -------------------------------- ### WeChatClient.AddFriendRequestAutoAcceptAndOpenChatListener Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Automatically accepts new friend requests, opens the chat window immediately after approval, and starts message listening. Optionally sends a welcome message upon first contact. This is a core API for building fully automated recruitment bots. ```APIDOC ## WeChatClient.AddFriendRequestAutoAcceptAndOpenChatListener ### Description Automatically accepts new friend requests, opens the chat window immediately after approval, and starts message listening. Optionally sends a welcome message upon first contact. This is a core API for building fully automated recruitment bots. ### Method `AddFriendRequestAutoAcceptAndOpenChatListener` ### Parameters - **callBack** (`Action`): A callback function to process incoming messages from new friends. It receives a `MessageContext` object. - **firstMessageAction** (`Func`): An asynchronous action to perform immediately after a friend request is approved. It receives a `Sender` object to send messages. - **keyWord** (`string`, optional): Only approves requests where the remark contains this keyword. - **suffix** (`string`, optional): A suffix to append to the friend's nickname after approval. - **label** (`string`, optional): A WeChat label to assign to the newly approved friend. - **isDelet** (`bool`, optional): If true, deletes the friend request record after approval. ### Example Usage ```csharp var semaphore = new SemaphoreSlim(1, 1); // Prevent concurrency client.AddFriendRequestAutoAcceptAndOpenChatListener( callBack: (MessageContext ctx) => { // Processing logic for messages from new friends (can integrate with LLM) var lastMsg = ctx.GetAllMessages().LastOrDefault()?.MessageContent ?? ""; var llm = ctx.ServiceProvider.GetRequiredService(); string reply = llm.Answer(lastMsg); ctx.SendMessage(reply); }, firstMessageAction: async (Sender sender) => { await semaphore.WaitAsync(); try { // Send welcome package immediately after friend approval sender.SendMessage("Welcome! I am an automated assistant, nice to meet you!"); await Task.Delay(2000); sender.SendFile(new string[] { @"C:\Welcome\guide.pdf" }); await Task.Delay(3000); sender.SendEmoji(3); // Send the 3rd emoji } finally { semaphore.Release(); } }, keyWord: "wechatauto", // Only approve requests with this keyword in the remark suffix: "_2025", // Automatically append suffix to nickname label: "New User", // Add WeChat label isDelet: true // Delete request record after approval ); // Stop the listener client.StopNewUserListener(); ``` ``` -------------------------------- ### UI Thread Invoker for External Application Automation Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/WeChatAutoWebSupport/Tests/test_resource/2.md This example shows a practical application of the UIThreadInvoker, where a dedicated STA thread is used to automate operations on an external application's UI using FlaUI. ```csharp // 场景:自动化测试 var invoker = new UIThreadInvoker(); // 主线程:显示测试界面 var testForm = new TestForm(); testForm.Show(); // 子线程:操作被测试的应用程序 await invoker.Run(automation => { // 操作外部应用程序的UI var button = automation.GetDesktop().FindFirstChild("Button"); button.Click(); }); ``` -------------------------------- ### Get Moment Item Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/listen-message.html Obtain the specific item details for a moments post. This object contains information like the author, content, and like status. ```csharp public MomentItem GetMomentItem() ``` -------------------------------- ### Auto-Accept Friend Requests and Listen for Messages Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Automatically accepts new friend requests, opens the chat window immediately after approval, and starts message listening. Supports sending a welcome message upon first contact. This is a core API for building fully automated recruitment bots. ```csharp var semaphore = new SemaphoreSlim(1, 1); // 防并发 client.AddFriendRequestAutoAcceptAndOpenChatListener( callBack: (MessageContext ctx) => { // 收到新好友消息后的处理逻辑(可接入 LLM) var lastMsg = ctx.GetAllMessages().LastOrDefault()?.MessageContent ?? ""; var llm = ctx.ServiceProvider.GetRequiredService(); string reply = llm.Answer(lastMsg); ctx.SendMessage(reply); }, firstMessageAction: async (Sender sender) => { await semaphore.WaitAsync(); try { // 好友通过后立即发送欢迎套餐 sender.SendMessage("欢迎!我是自动化助手,很高兴认识你!"); await Task.Delay(2000); sender.SendFile(new string[] { @"C:\Welcome\guide.pdf" }); await Task.Delay(3000); sender.SendEmoji(3); // 发送第 3 个表情 } finally { semaphore.Release(); } }, keyWord: "wechatauto", // 仅通过备注含此关键字的申请 suffix: "_2025", // 自动在昵称后追加后缀 label: "新用户", // 添加微信标签 isDelet: true // 通过后删除申请记录 ); // 停止监听 client.StopNewUserListener(); ``` -------------------------------- ### Add Conversation Change Listener Example Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/listen-message.html Register a callback function to be executed when the conversation list selection changes. The callback receives a ChatContext and CancellationToken for accessing conversation details and managing task cancellation. ```csharp var window = client.WxMainWindow; window.AddConversationChangeListener((context, token) => { Console.WriteLine(context.ToString()); //这里调用自己的方法,通过context可以获取自己需要的信息,如:好友/群聊/企业微信的名字等. //如果这里运行的是长任务,可能任务没有运行完,用户又点击了其他的列表项,通过token可以收到外部终止执行的信息,可以运行```token.ThrowIfCancellationRequested();```终止任务 }); ``` -------------------------------- ### Send Image Message via REST API (curl) Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Example using `curl` to send an image file via the REST API. Requires specifying the image path in the payload. ```bash # 发送图片消息 curl -X POST http://localhost:5000/api/send \ -H "Content-Type: application/json" \ -d '{ "actionType": "SendImage", "from": "Alex", "to": "项目群", "payload": "C:\\Images\\chart.png", "messageId": "img_002" }' ``` -------------------------------- ### Configure MCP Server in VS Code Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/quick-start.html Configure the MCP server settings in VS Code's `.vscode/mcp.json` file to enable communication with the WeChat automation backend. This setup is typically used for integrating with tools like GitHub Copilot Chat. ```json { "servers": { "wechat_mcp_server": { "type": "stdio", "command": "dotnet", "args": [ "run", "--project", "改成你的WeChatAuto.MCP.csproj的路径" ] } } } ``` -------------------------------- ### Correct: Main and Dialog Threads Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/WeChatAutoWebSupport/Tests/test_resource/2.md Shows the correct pattern for managing UI operations across threads. The main thread runs its message loop with Application.Run(), while a separate STA thread can show its own dialogs using ShowDialog(), which starts its own message loop. ```csharp // 主线程(STA) [STAThread] static void Main() { // 主线程创建主窗口 var mainForm = new MainForm(); mainForm.Show(); // 主线程继续运行消息循环 Application.Run(); } // 子线程(也是STA) var dialogThread = new Thread(() => { // 子线程创建对话框 var dialog = new DialogForm(); dialog.ShowDialog(); // 这不会与主线程冲突! }); dialogThread.SetApartmentState(ApartmentState.STA); dialogThread.Start(); ``` ```csharp // 主线程 Application.Run(); // 主线程的消息循环 // 子线程 var dialog = new DialogForm(); dialog.ShowDialog(); // 子线程启动自己的消息循环 ``` -------------------------------- ### Initialize WechatAuto.SDK with Debug and Video Recording Enabled Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/MD/faq.md Configure WechatAuto.SDK initialization to enable debug mode for visual feedback and to record video of automation processes. Ensure ffmpeg is accessible for video recording. ```csharp WeAutomation.Initialize(builder.Services, options => { //开启调试模式,调试模式会在获得焦点时边框高亮,生产环境建议关闭 options.DebugMode = true; //开启录制视频功能,录制的视频会保存在项目的运行目录下的Videos文件夹中 options.EnableRecordVideo = true; }); ``` -------------------------------- ### Get My Referencing Messages Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves a list of messages that I have referenced. ```APIDOC ## Get My Referencing Messages ### Description Retrieves a list of messages that I have referenced. ### Method ``` messageContext.MessageBubbleIsReferencing() ``` ### Response Returns a `List`. Refer to [MessageBubble](../api/WeChatAuto.Components.MessageBubble.html) for message details. ``` -------------------------------- ### WeAutomation.Initialize Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Initializes the WeChatAuto SDK. Supports integration with host DI frameworks or using an internal DI container. Configuration options include debug mode, mouse/keyboard simulator settings, and paths for capturing UI elements and recording videos. ```APIDOC ## WeAutomation.Initialize — SDK 初始化入口 SDK 的统一初始化方法,支持两种模式:与宿主 DI 框架集成(`IServiceCollection` 重载),或使用内置 DI 容器(无参/选项重载)。初始化时可配置调试模式、键鼠模拟器、截图路径、视频录制等全局选项。两种模式不可混用。 ```csharp // 模式一:使用内置 DI 容器(控制台 / 简单场景) var serviceProvider = WeAutomation.Initialize(options => { options.DebugMode = true; // 调试模式:点击时高亮边框 options.EnableMouseKeyboardSimulator = true; // 启用硬件键鼠模拟器(防风控) options.KMDevicePID = 0x1701; options.KMDeviceVID = 0x2612; options.KMVerifyUserData = "4F6A21981BE675822DEE7B9BC39F3791"; options.EnableRecordVideo = true; // 录制操作视频 options.CaptureUIPath = @"C:\Logs\Captures"; // 出错截图保存路径 }); // 模式二:与 .NET Generic Host / ASP.NET Core 集成 var builder = Host.CreateApplicationBuilder(args); WeAutomation.Initialize(builder.Services, options => { options.DebugMode = false; options.ListenInterval = 3; // 消息监听轮询间隔(秒) options.MomentsListenInterval = 15; // 朋友圈监听间隔(秒) }); builder.Services.AddSingleton(); // 注入自定义服务 var app = builder.Build(); await app.RunAsync(); ``` ``` -------------------------------- ### Get My Referenced Messages Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves a list of messages that have been referenced by others. ```APIDOC ## Get My Referenced Messages ### Description Retrieves a list of messages that have been referenced by others. ### Method ``` messageContext.MessageBubbleIsReferenced() ``` ### Response Returns a `List`. Refer to [MessageBubble](../api/WeChatAuto.Components.MessageBubble.html) for message details. ``` -------------------------------- ### MomentsContext - Get Moment Key Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/listen-message.html Retrieves a unique identifier for the moment. ```APIDOC ## GetMomentKey ### Description Retrieves a unique identifier for the moment. This can be used as context for large language models, such as a unique identifier for the moment record. ### Method `GetMomentKey() -> string` ### Parameters None ### Response #### Success Response (200) * **string** - The unique key of the moment. ``` -------------------------------- ### Initialize WeChatAuto.SDK with Dependency Injection Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/quick-start.html Integrate WeChatAuto.SDK into an existing dependency injection container. This method requires the application's services as the first parameter. ```csharp using Microsoft.Extensions.Hosting; using WeChatAuto.Services; using WeChatAuto.Components; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; var builder = Host.CreateApplicationBuilder(args); WeAutomation.Initialize(builder.Services, options => { // Enable debug mode, recommended to disable in production options.DebugMode = true; // Enable video recording feature //options.EnableRecordVideo = true; }); // Inject your own services (or objects), such as LLM services, etc. builder.Services.AddSingleton(); var serviceProvider = builder.Services.BuildServiceProvider(); var clientFactory = serviceProvider.GetRequiredService(); ...more code await builder.Build().RunAsync(); ... ``` -------------------------------- ### MomentsContext - Get Moment Content Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/listen-message.html Retrieves the textual content of a moment. ```APIDOC ## GetMomentContent ### Description Retrieves the textual content of the moment. This can be used as context for large language models. ### Method `GetMomentContent() -> string` ### Parameters None ### Response #### Success Response (200) * **string** - The content of the moment. ``` -------------------------------- ### Initialize WeChatAuto SDK Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Initialize the SDK using either the built-in DI container or by integrating with an existing .NET DI framework. Configure global options like debug mode, simulator usage, and logging paths. ```csharp var serviceProvider = WeAutomation.Initialize(options => { options.DebugMode = true; // 调试模式:点击时高亮边框 options.EnableMouseKeyboardSimulator = true; // 启用硬件键鼠模拟器(防风控) options.KMDevicePID = 0x1701; options.KMDeviceVID = 0x2612; options.KMVerifyUserData = "4F6A21981BE675822DEE7B9BC39F3791"; options.EnableRecordVideo = true; // 录制操作视频 options.CaptureUIPath = @"C:\Logs\Captures"; // 出错截图保存路径 }); ``` ```csharp var builder = Host.CreateApplicationBuilder(args); WeAutomation.Initialize(builder.Services, options => { options.DebugMode = false; options.ListenInterval = 3; // 消息监听轮询间隔(秒) options.MomentsListenInterval = 15; // 朋友圈监听间隔(秒) }); builder.Services.AddSingleton(); // 注入自定义服务 var app = builder.Build(); await app.RunAsync(); ``` -------------------------------- ### Get Owner Info Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves the current user's profile information. ```APIDOC ## Get Owner Info ### Description Retrieves the current user's profile information. ### Method ``` public async Task GetOwnerInfo() ``` ### Response Returns a `FriendInfo` object containing the owner's details. ``` -------------------------------- ### Listen to Friend/Group Messages and Reply Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/docs/index.html Demonstrates how to listen for new messages from friends or group chats, access message context, and reply. It also shows how to use dependency injection to retrieve custom services like an LLM service for business logic. ```csharp using Microsoft.Extensions.Hosting; using WeChatAuto.Services; using WeChatAuto.Components; using Microsoft.Extensions.DependencyInjection; using FlaUI.Core.Logging; using System.Diagnostics; using Microsoft.Extensions.Logging; var builder = Host.CreateApplicationBuilder(args); WeAutomation.Initialize(builder.Services, options => { //开启调试模式,调试模式会在获得焦点时边框高亮,生产环境建议关闭 options.DebugMode = true; //开启录制视频功能,录制的视频会保存在项目的运行目录下的Videos文件夹中 //options.EnableRecordVideo = true; }); //这里注入自已的服务(或者对象),如LLM服务等 builder.Services.AddSingleton(); var serviceProvider = builder.Services.BuildServiceProvider(); var clientFactory = serviceProvider.GetRequiredService(); // 得到名称为"Alex"的微信客户端实例,测试时请将AI.net替换为你自己的微信昵称 var client = clientFactory.GetWeChatClient("Alex"); await client.AddMessageListener("测试11", (messageContext) => { var index = 0; //显示收到的消息 foreach (var message in messageContext.NewMessages) { index++; Console.WriteLine($ ``` ```csharp 收到消息:{index}:{message.ToString()}'); Console.WriteLine($ ``` ```csharp 收到消息:{index}:{message.Who}:{message.MessageContent}'); } var allMessages = messageContext.AllMessages.Skip(messageContext.AllMessages.Count - 10).ToList(); index = 0; //显示所有消息的后十条 foreach (var message in allMessages) { index++; Console.WriteLine($"...收到所有消息的前10条之第{index}条:{message.Who}:{message.MessageContent}"); Console.WriteLine($".................详细之第{index}条:{message.ToString()}"); } //是否有人@我 if (messageContext.IsBeAt()) { var messageBubble = messageContext.MessageBubbleIsBeAt().FirstOrDefault(); if (messageBubble != null) { messageContext.SendMessage("我被@了!!!!我马上就回复你!!!!", new List { messageBubble.Who }); } else { messageContext.SendMessage("我被@了!!!!我马上就回复你!!!!"); } } //是否有人引用了我的消息 if (messageContext.IsBeReferenced()) { messageContext.SendMessage("我被引用了!!!!"); } //是否有人拍了拍我 if (messageContext.IsBeTap()) { messageContext.SendMessage("我被拍一拍了[微笑]!!!!"); } if (!messageContext.IsBeAt() && !messageContext.IsBeReferenced() && !messageContext.IsBeTap()) { //回复消息,这里可以引入大模型自动回复 messageContext.SendMessage($"我收到了{messageContext.NewMessages.FirstOrDefault()?.Who}的消息:{messageContext.NewMessages.FirstOrDefault()?.MessageContent}"); } //可以通过注入的服务容器获取你注入的服务实例,然后调用你的业务逻辑,一般都是LLM的自动回复逻辑 var llmService = messageContext.ServiceProvider.GetRequiredService(); llmService.DoSomething(); }); var app = builder.Build(); await app.RunAsync(); /// /// 一个包含LLM服务的Service类,用于注入到依赖注入容器. /// public class LLMService { private ILogger _logger; public LLMService(ILogger logger) { _logger = logger; } public void DoSomething() { _logger.LogInformation("这里是你注入的服务实例,可以在这里编写你的业务逻辑 "); } } ``` ```bash dotnet add package WeChatAuto.SdK dotnet add package Microsoft.Extensions.Hosting ``` -------------------------------- ### Get All Chat History Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves the message history for a specific chat, with pagination. ```APIDOC ## GetChatAllHistory ### Description Retrieves the message history for a specific chat, with pagination. Specifying -1 for pageCount retrieves all messages, which may cause performance issues. ### Method public List GetChatAllHistory(string who, int pageCount = 10) ### Parameters #### Path Parameters - **who** (string) - Required - The nickname of the friend or the name of the group chat. - **pageCount** (int) - Optional - Defaults to 10. The number of message pages to retrieve. Use -1 to get all messages. ``` -------------------------------- ### Listen to Messages and Reply with Context Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/README.md Demonstrates listening for messages from a specific contact, processing new and historical messages, and replying based on message context like mentions, references, or taps. It also shows how to access injected services like LLMService. ```csharp using Microsoft.Extensions.Hosting; using WeChatAuto.Services; using WeChatAuto.Components; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; var builder = Host.CreateApplicationBuilder(args); WeAutomation.Initialize(builder.Services, options => { //开启调试模式,调试模式会在获得焦点时边框高亮,生产环境建议关闭 options.DebugMode = true; //开启录制视频功能,录制的视频会保存在项目的运行目录下的Videos文件夹中 //options.EnableRecordVideo = true; }); //这里注入自已的服务(或者对象),如LLM服务等 builder.Services.AddSingleton(); var serviceProvider = builder.Services.BuildServiceProvider(); var clientFactory = serviceProvider.GetRequiredService(); // 得到名称为"Alex"的微信客户端实例,测试时请将AI.net替换为你自己的微信昵称 var client = clientFactory.GetWeChatClient("Alex"); await client.AddMessageListener("测试11", (messageContext) => { var index = 0; //打印收到最新消息 foreach (var message in messageContext.NewMessages) { index++; Console.WriteLine($ ``` ```csharp //发送文本消息 sender.SendMessage("你好啊!我是AI.Net,很高兴认识你!"); //发送表情 //sender.SendEmoji(1); //发送文件,改成你的文件路径 //sender.SendFile(new string[] { @"C:\Users\Administrator\Desktop\me\avatar.png" }); }); var app = builder.Build(); await app.RunAsync(); /// /// 一个包含LLM服务的Service类,用于注入到MessageContext中 /// public class LLMService { private ILogger _logger; public LLMService(ILogger logger) { _logger = logger; } public void DoSomething() { _logger.LogInformation("这里是你注入的服务实例,可以在这里编写你的业务逻辑 "); } } ``` -------------------------------- ### Get Current Chat Title Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves the title of the current chat window. ```APIDOC ## GetCurrentChatTitle ### Description Retrieves the title of the current chat window. ### Method public string GetCurrentChatTitle() ``` -------------------------------- ### Initialize WeChatAuto.SDK without Dependency Injection Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/quick-start.html Initialize the SDK and obtain a WeChatClientFactory when not using a dependency injection framework. Ensure proper disposal of the factory. ```csharp // Initialize WeAutomation service var serviceProvider = WeAutomation.Initialize(options => { options.DebugMode = true; // Enable debug mode, recommended to disable in production //options.EnableRecordVideo = true; // Enable video recording feature }); using var clientFactory = serviceProvider.GetRequiredService(); ... ``` -------------------------------- ### MomentsContext - Get Moment Item Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/listen-message.html Retrieves the detailed item object for a moment. ```APIDOC ## GetMomentItem ### Description Retrieves the detailed item object for a specific moment, containing information about the author, content, and interactions. ### Method `GetMomentItem() -> MomentItem` ### Parameters None ### Response #### Success Response (200) * **MomentItem** - The moment item object. ``` -------------------------------- ### Get My Referencing Messages Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves a list of messages that I have referenced. Requires the MessageContext object. ```csharp messageContext.MessageBubbleIsReferencing() ``` -------------------------------- ### Initialize Wechatauto.sdk and Add Message Listener Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Sets up the Wechatauto.sdk and registers a message listener for a specific chat. The listener receives a MessageContext object for performing operations on incoming messages. ```csharp var builder = Host.CreateApplicationBuilder(args); WeAutomation.Initialize(builder.Services, options => { }); var serviceProvider = builder.Services.BuildServiceProvider(); var clientFactory = serviceProvider.GetRequiredService(); var client = clientFactory.GetWeChatClient("Alex"); //监听群 "测试11" 聊天,并做自动回复. await client.AddMessageListener("测试11", (messageContext) => { //在这里messageContext使用回复、转发消息 }); var app = builder.Build(); await app.RunAsync(); ``` -------------------------------- ### Get Current Chat Title Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves the title of the currently active chat window. ```csharp public string GetCurrentChatTitle() ``` -------------------------------- ### 配置MCP Server的mcp.json Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/mcp-server-client.html 在VSCode的.vscode目录下创建或修改mcp.json文件,用于配置MCP Server的启动命令和参数。请确保替换"你的WeChatAuto.MCP.csproj路径"为实际的项目路径。 ```json { "servers": { "wechat_mcp_server": { "type": "stdio", "command": "dotnet", "args": [ "run", "--project", "你的WeChatAuto.MCP.csproj路径,如:D:\\repo\\wxauto.net\\WeChatAuto.SDK\\src\\WeChatAuto.MCP\\WeChatAuto.MCP.csproj" ] } } } ``` -------------------------------- ### Initialize WeChat Automation and Listen for Messages Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/vip888.html Initializes the WeChat automation client and sets up a listener for incoming messages. It demonstrates how to access message context, check for mentions, references, and taps, and send replies. Dependency injection is used to access custom services like LLMService. ```csharp using Microsoft.Extensions.Hosting; using WeChatAuto.Services; using WeChatAuto.Components; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; var builder = Host.CreateApplicationBuilder(args); WeAutomation.Initialize(builder.Services, options => { //开启调试模式,调试模式会在获得焦点时边框高亮,生产环境建议关闭 options.DebugMode = true; //开启录制视频功能,录制的视频会保存在项目的运行目录下的Videos文件夹中 //options.EnableRecordVideo = true; }); //这里注入自已的服务(或者对象),如LLM服务等 builder.Services.AddSingleton(); var serviceProvider = builder.Services.BuildServiceProvider(); var clientFactory = serviceProvider.GetRequiredService(); // 得到名称为"Alex"的微信客户端实例,测试时请将AI.net替换为你自己的微信昵称 var client = clientFactory.GetWeChatClient("Alex"); await client.AddMessageListener("测试11", (messageContext) => { var index = 0; //打印收到最新消息 foreach (var message in messageContext.NewMessages) { index++; Console.WriteLine($ ``` ```csharp //发送文本消息 sender.SendMessage("你好啊!我是AI.Net,很高兴认识你!"); //发送表情 //sender.SendEmoji(1); //发送文件,改成你的文件路径 //sender.SendFile(new string[] { @"C:\Users\Administrator\Desktop\me\avatar.png" }); ``` -------------------------------- ### Get My Referenced Messages Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves a list of messages that have been referenced by others. Requires the MessageContext object. ```csharp messageContext.MessageBubbleIsReferenced() ``` -------------------------------- ### Get All Conversation Titles in C# Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Fetches a list of all conversation titles for efficiency. Use this when only the names are needed. ```csharp // 获取全部会话标题(仅名称,效率更高) List allTitles = client.GetAllConversations(); ``` -------------------------------- ### Configure Project Target Framework Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/WeChatAuto3_9_12_xx/README.md Modify the .csproj file to set the TargetFramework to a Windows-specific version, such as net10.0-windows, to avoid compilation warnings. ```xml Exe net10.0-windows enable enable ``` -------------------------------- ### Configure WeChatAuto SDK Options Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Set various parameters to control the behavior of the WeChatAuto SDK, such as debug mode, listener intervals, and file paths. Ensure the specified paths exist for features like automatic screenshots. ```csharp WeAutomation.Initialize(options => { // 调试模式:UI 元素点击时高亮显示边框 options.DebugMode = true; // 消息监听轮询间隔(秒),默认 5 options.ListenInterval = 3; // 朋友圈监听间隔(秒),默认 10 options.MomentsListenInterval = 15; // 新好友申请监听间隔(秒),默认 5 options.NewUserListenerInterval = 3; // 截图保存目录(出错时自动截图) options.CaptureUIPath = @"C:\Logs\WxCaptures"; // 启用操作录像 options.EnableRecordVideo = true; options.TargetVideoPath = @"C:\Videos\WxRecords"; // 下载文件默认保存路径 options.DefaultSavePath = @"C:\Downloads\WeChat"; // 启用硬件键鼠模拟器(更真实,防风控) options.EnableMouseKeyboardSimulator = true; options.KMDeviceVID = 0x2612; options.KMDevicePID = 0x1701; options.KMVerifyUserData = "4F6A21981BE675822DEE7B9BC39F3791"; // 输出字符串方式: 4=剪贴板粘贴(推荐,速度快且不受输入法影响) options.KMOutputStringType = 4; // DPI 感知模式: 1=系统级(默认), 2=每显示器级别 options.ProcessDpiAwareness = 1; }); ``` -------------------------------- ### MomentsContext - Get History Reply Items Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/listen-message.html Retrieves a list of past reply items associated with a moment. ```APIDOC ## GetHistoryReplyItems ### Description Retrieves a list of past reply items for a given moment. ### Method `GetHistoryReplyItems() -> List` ### Parameters None ### Response #### Success Response (200) * **List** - A list of reply items. ``` -------------------------------- ### 通过Copilot Chat自动化微信 Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/mcp-server-client.html 在GitHub Copilot Chat对话框中输入自然语言指令,即可调用MCP Server来自动化微信操作。例如,发送消息给指定好友。 ```natural_language 请帮我给微信好友:AI.net发送消息: Hello world!! ``` -------------------------------- ### Get Last Messages Method Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves a specified number of the most recent messages from the context. Each message is a MessageBubble object. ```csharp messageContext.GetLastMessages(int count) ``` -------------------------------- ### Get Sender Object from Context Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves the Sender object associated with the message context, which can be used to send messages. ```csharp messageContext.Sender ``` -------------------------------- ### Access Swagger Documentation for REST API Source: https://context7.com/scottfly189/wechatauto.sdk/llms.txt Opens the Swagger UI for the REST API service, typically hosted at `http://localhost:5000`. This allows exploration of available API endpoints. ```bash # 查看 Swagger 文档 open http://localhost:5000/swagger ``` -------------------------------- ### Initialize WeAutomation Service and Send Message Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/normal.html This C# code initializes the WeAutomation service, retrieves a WeChat client, and sends a message to a specified contact. Ensure the contact name is updated to your actual friend's nickname. The WeChatClientFactory should be disposed of when no longer needed, or managed by a dependency injection container. ```csharp using Microsoft.Extensions.DependencyInjection; using WeChatAuto.Components; using WeChatAuto.Services; // Initialize WeAutomation service var serviceProvider = WeAutomation.Initialize(options => { options.DebugMode = true; // Enable debug mode for visual feedback, recommended to disable in production //options.EnableRecordVideo = true; // Enable video recording, saved in the Videos folder }); using var clientFactory = serviceProvider.GetRequiredService(); Console.WriteLine($"Currently open WeChat clients: {string.Join(",", clientFactory.GetWeChatClientNames())}, total: {clientFactory.GetWeChatClientNames().Count}."); // Get the list of currently open WeChat client names var clentNames = clientFactory.GetWeChatClientNames(); // Get the first WeChat client var wxClient = clientFactory.GetWeChatClient(clentNames.First()); // Send a message to a friend (or group nickname) named "AI.Net". Please change "AI.Net" to your actual friend's nickname for testing. wxClient?.SendWho("AI.Net","Hello, welcome to the AI.Net WeChat automation framework!"); ``` -------------------------------- ### Configure Target Framework for Windows Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/vip888.html Modify your .csproj file to target a Windows-specific .NET framework version. This is required for WeChat automation on Windows. ```xml Exe net10.0-windows enable enable ``` -------------------------------- ### Get All Messages from Context Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves a list of all messages within the current chat context. Each message is represented by a MessageBubble object. ```csharp messageContext.AllMessages ``` -------------------------------- ### MomentsContext - Do Like Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/listen-message.html Executes a like action on the moment. ```APIDOC ## DoLike ### Description Executes a like action on the moment. If the moment has already been liked, this action will not perform any operation. ### Method `DoLike()` ### Parameters None ``` -------------------------------- ### Get New Messages from Context Source: https://github.com/scottfly189/wechatauto.sdk/blob/master/docs/content/message-operation.html Retrieves a list of newly arrived messages from the MessageContext. Each message is represented by a MessageBubble object. ```csharp messageContext.NewMessages ```