internal static async Task ProcessWSMessageAsync(this ApiPostListener listener, JObject eventObject) { var response = await Task.Run(() => listener.ProcessPost(eventObject)).ConfigureAwait(false); var apiClient = listener.ApiClient; if (response is RequestResponse && !(apiClient is null)) { JObject data = eventObject; data.Merge(JObject.FromObject(response)); switch (response) { case FriendRequestResponse friend: await apiClient.HandleFriendRequestInternalAsync(data).ConfigureAwait(false); break; case GroupRequestResponse group: await apiClient.HandleGroupRequestInternalAsync(data).ConfigureAwait(false); break; default: break; } } }
private static void ListeningTest(HttpApiClient httpApi) { Console.WriteLine("input listening port"); string port = Console.ReadLine(); ApiPostListener listener = new ApiPostListener(); listener.ApiClient = httpApi; listener.PostAddress = $"http://127.0.0.1:{port}/"; listener.ForwardTo = "http://[::1]:10202"; listener.StartListen(); listener.FriendRequestEvent += Friend; listener.FriendRequestEvent += ApiPostListener.ApproveAllFriendRequests; listener.GroupInviteEvent += Group; listener.GroupInviteEvent += ApiPostListener.ApproveAllGroupRequests; listener.GroupRequestEvent += Group; listener.GroupRequestEvent += ApiPostListener.ApproveAllGroupRequests; //listener.MessageEvent += ApiPostListener.RepeatAsync; listener.MessageEvent += PrintRaw; listener.GroupNoticeEvent += ApiPostListener.RepeatAsync; listener.AnonymousMessageEvent += ApiPostListener.RepeatAsync; listener.AnonymousMessageEvent += PrintRaw; //listener.MessageEvent += ApiPostListener.Say("good"); var listener2 = new ApiPostListener(); listener2.PostAddress = "http://[::1]:10202"; listener2.StartListen(); listener2.MessageEvent += (api, message) => { Console.WriteLine(message.Time); Console.WriteLine(message.Content.Raw); }; }
private static void ConfigListener(ApiPostListener cqWebSocketEvent) { _ = Task.Run(async() => { while (true) { await Task.Delay(1000); Console.WriteLine("Available: {0}, Listening {1}", (cqWebSocketEvent as dynamic).IsAvailable, (cqWebSocketEvent as dynamic).IsListening); } }); cqWebSocketEvent.MessageEvent += async(api, e) => { Console.WriteLine(e.Content.Raw); Console.WriteLine(api is null); await api.SendMessageAsync(e.Endpoint, "Response 1" + SendingMessage.LocalImage(@"C:\Users\yinmi\Pictures\bad(Y)(auto_scale)(Level3)(width 2000).jpg")); if (e is GroupMessage groupMessage) { await api.GetGroupMemberInfoAsync(groupMessage.GroupId, e.UserId); } await api.SendMessageAsync(e.Endpoint, "Response 2" + SendingMessage.LocalImage(@"C:\Users\yinmi\Pictures\karen.jpg")); }; cqWebSocketEvent.FriendRequestEvent += (api, e) => true; cqWebSocketEvent.GroupInviteEvent += (api, e) => true; cqWebSocketEvent.AnonymousMessageEvent += (api, e) => { Console.WriteLine("id|name|flag:{0}|{1}|{2}", e.Anonymous.Id, e.Anonymous.Name, e.Anonymous.Flag); api.BanMessageSource(e.GroupId, e.Source, 1); }; }
public void Request_MultiFriendRequest() { string json = @"{""comment"":""hmmmmmm"",""flag"":""747576"",""post_type"":""request"",""request_type"":""friend"",""self_id"":12345678,""time"":1541601678,""user_id"":87654321}"; var listener = new ApiPostListener(); bool invo1 = false, invo2 = false, invo3 = false; listener.FriendRequestEvent += (api, e) => { invo1 = true; return(null); }; listener.FriendRequestEvent += (api, e) => { invo2 = true; return(new FriendRequestResponse { Approve = false }); }; listener.FriendRequestEvent += (api, e) => { invo3 = true; return(null); }; listener.ProcessPost(json); Assert.True(invo1); Assert.True(invo2); Assert.False(invo3); }
public void TextPostTypeSectionsUnescape() { string json = @"{""anonymous"":null,""font"":336542616,""group_id"":514661057,""message"":""绑定[CQ:at,qq=962549599] [ Morion ]:测试"",""message_id"":745339,""message_type"":""group"",""post_type"":""message"",""raw_message"":""绑定[CQ:at,qq=962549599] [ Morion ]:测试"",""self_id"":122866607,""sender"":{""age"":21,""card"":""钻石 | 动漫站建不成了"",""nickname"":""ymy😂/pch"",""sex"":""male"",""user_id"":962549599},""sub_type"":""normal"",""time"":1541558577,""user_id"":962549599}"; var listener = new ApiPostListener(); IReadOnlyList <Section> sections = null; listener.MessageEvent += (api, e) => { var content = e.Content; sections = content.Sections; }; listener.ProcessPost(json); // Assert.NotNull(sections); Assert.Equal(3, sections.Count); // Section 1 // Section 2 Assert.Equal <KeyValuePair <string, string> >(new SortedDictionary <string, string> { ["qq"] = "962549599" }, sections[1].Data); Assert.Equal("at", sections[1].Type); // Section 3 // 应该正确转义 " [ Morion ]:测试" 为下面的内容。 Assert.Equal(" [ Morion ]:测试", sections[2].ToString()); }
public void ArrayMessage_Normal() { string json = "{\"anonymous\":null,\"font\":236846192,\"group_id\":123456789,\"message\":[{\"data\":{\"text\":\"去2\"},\"type\":\"text\"}],\"message_id\":282,\"message_type\":\"group\",\"post_type\":\"message\",\"raw_message\":\"去2\",\"self_id\":1131545658,\"sender\":{\"age\":21,\"area\":\"青岛\",\"card\":\"\",\"level\":\"冒泡\",\"nickname\":\"ymy😂/pch\",\"role\":\"owner\",\"sex\":\"female\",\"title\":\"\",\"user_id\":962549599},\"sub_type\":\"normal\",\"time\":1547742375,\"user_id\":962549599}"; var listener = new ApiPostListener(); Posts.Message context = null; listener.MessageEvent += (api, e) => { context = e; }; listener.ProcessPost(json); Assert.IsType <GroupMessage>(context); Assert.Equal(1, context.Content.Sections.Count); }
private static void Main(string[] args) { var culture = CultureInfo.GetCultureInfo("zh-CN"); CultureInfo.DefaultThreadCurrentCulture = culture; CultureInfo.DefaultThreadCurrentUICulture = culture; CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; var httpApiClient = new HttpApiClient(); var friendList = httpApiClient.GetFriendListAsync().ConfigureAwait(false).GetAwaiter().GetResult(); // test for get_friend_list ha kokomade. var groupMemberInfo = httpApiClient.GetGroupMemberInfoAsync(661021255, 962549599).GetAwaiter().GetResult(); //var groupMemberInfos = httpApiClient.GetGroupMemberListAsync(641236878).GetAwaiter().GetResult(); var banResult = httpApiClient.BanAnonymousMember(72318078, "AAAAAAAPQl8ADMfHwK2hpMSqtvvDyQAoAHXUxZeiC+YKi480g3ERUrpzM+o20KsUJ0mm1xxoobOEtwYU+3KqiA==", 60).GetAwaiter().GetResult(); banResult = httpApiClient.BanWholeGroup(72318078, true).GetAwaiter().GetResult(); Task.Delay(TimeSpan.FromSeconds(10)).Wait(); banResult = httpApiClient.BanWholeGroup(72318078, false).GetAwaiter().GetResult(); var postListener = new ApiPostListener(8876); PrintNoticeAndRequests(postListener); postListener.StartListen(); Console.ReadKey(true); Environment.Exit(0); var httpApi = new HttpApiClient(); httpApi.ApiAddress = "http://127.0.0.1:5700/"; //var privateResponse = httpApi.SendPrivateMessageAsync(962549599, "hello").Result; //Console.WriteLine(privateResponse.MessageId); //var groupResponse = httpApi.SendGroupMessageAsync(72318078, "hello").Result; //Console.WriteLine(groupResponse.MessageId); //605617685 #region kick test //var success1 = httpApi.KickGroupMember(605617685, 962549599); //var success2 = httpApi.KickGroupMember(72318078, 962549599); //Console.WriteLine(success1); //Console.WriteLine(success2); #endregion Console.WriteLine("--------------"); #region recall test //var delete1 = httpApi.RecallMessageAsync(privateResponse).Result; //var delete2 = httpApi.RecallMessageAsync(groupResponse).Result; //Console.WriteLine(delete1); //Console.WriteLine(delete2); #endregion #region group member info test //Console.Write("group num:"); //long group = long.Parse(Console.ReadLine().Trim()); //Console.Write("qq id:"); //long qqid = long.Parse(Console.ReadLine().Trim()); //var member = httpApi.GetGroupMemberInfoAsync(group, qqid).Result; //Console.WriteLine(member.Age); //Console.WriteLine(member.Area); //Console.WriteLine(member.Authority.ToString()); //Console.WriteLine(member.GroupId); //Console.WriteLine(member.InGroupName); //Console.WriteLine(member.IsCardChangeable); //Console.WriteLine(member.JoinTime); //Console.WriteLine(member.LastSendTime); //Console.WriteLine(member.Nickname); //Console.WriteLine(member.Title); //Console.WriteLine(member.UserId); //var memberList = httpApi.GetGroupMemberListAsync(605617685).Result; //var query = from m in memberList // where m.Age > 19 // select new { m.InGroupName, m.Nickname, m.Area }; //foreach (var item in query) //{ // Console.WriteLine(item.InGroupName); // Console.WriteLine(item.Nickname); // Console.WriteLine(item.Area); //} #endregion #region Message Class Test //var message = new Message("this is at test,: "); //message += Message.At(962549599); //httpApi.SendGroupMessageAsync(72318078, message).Wait(); #endregion #region Image Test //var imgMessage = Message.LocalImage(@"C:\Users\Administrator\Desktop\Rinima.jpg"); //var netMessage = Message.NetImage(@"https://files.yande.re/image/ca815083c96a99a44ff72e70c6957c14/yande.re%20437737%20dennou_shoujo_youtuber_shiro%20heels%20pantyhose%20shiro_%28dennou_shoujo_youtuber_shiro%29%20shouju_ling.jpg"); //httpApi.SendGroupMessageAsync(72318078, imgMessage).Wait(); //httpApi.SendGroupMessageAsync(72318078, netMessage).Wait(); //httpApi.SendGroupMessageAsync(72318078, imgMessage + netMessage).Wait(); //message += netMessage; //httpApi.SendGroupMessageAsync(72318078, message).Wait(); #endregion RecordTestAsync(httpApi); //ListeningTest(httpApi); Console.WriteLine("end"); Console.ReadKey(); }
private static void PrintNoticeAndRequests(ApiPostListener apiPostListener) { void PrintPost(Post post) { Console.WriteLine(post.Time); Console.WriteLine("user: "******"self: " + post.SelfId); } void PrintRequest(Request request) { PrintPost(request); Console.WriteLine(request.Comment); Console.WriteLine(request.Flag); } apiPostListener.GroupFileUploadedEvent += (api, notice) => { Console.WriteLine("file uploaded"); PrintPost(notice); Console.WriteLine("group: " + notice.GroupId); Console.WriteLine($"file: {notice.File.Id} | name: {notice.File.Name} | size: {notice.File.Length} | busid: {notice.File.BusId}"); }; apiPostListener.GroupAdminSetEvent += (api, notice) => { Console.WriteLine($"admin set ({notice.SubType})"); PrintPost(notice); Console.WriteLine($"group: {notice.GroupId}"); }; apiPostListener.GroupAdminUnsetEvent += (api, notice) => { Console.WriteLine($"admin unset ({notice.SubType})"); PrintPost(notice); Console.WriteLine($"group: {notice.GroupId}"); }; apiPostListener.GroupMemberDecreasedEvent += (api, notice) => { Console.WriteLine($"group member decreased ({notice.SubType})"); PrintPost(notice); Console.WriteLine($"group: {notice.GroupId}"); Console.WriteLine($"operator: {notice.OperatorId}"); }; apiPostListener.KickedEvent += (api, notice) => { Console.WriteLine($"kicked ({notice.SubType})"); PrintPost(notice); Console.WriteLine($"group: {notice.GroupId}"); Console.WriteLine($"operator: {notice.OperatorId}"); }; apiPostListener.GroupMemberIncreasedEvent += (api, notice) => { Console.WriteLine($"group member increased ({notice.SubType})"); PrintPost(notice); Console.WriteLine($"group: {notice.GroupId}"); Console.WriteLine($"operator: {notice.OperatorId}"); }; apiPostListener.GroupAddedEvent += (api, notice) => { Console.WriteLine($"group join ({notice.SubType})"); PrintPost(notice); Console.WriteLine($"group: {notice.GroupId}"); Console.WriteLine($"operator: {notice.OperatorId}"); }; apiPostListener.FriendAddedEvent += (api, notice) => { Console.WriteLine("friend added"); PrintPost(notice); }; apiPostListener.FriendRequestEvent += (api, request) => { Console.WriteLine("friend request"); PrintRequest(request); return(new FriendRequestResponse { Approve = false }); }; apiPostListener.GroupInviteEvent += (api, request) => { Console.WriteLine($"group invite"); PrintRequest(request); Console.WriteLine($"group: {request.GroupId}"); if (request.UserId != 962549599) { return(new GroupRequestResponse { Approve = false }); } else { return(new GroupRequestResponse { Approve = true }); } }; apiPostListener.GroupRequestEvent += (api, request) => { Console.WriteLine($"group request"); PrintRequest(request); Console.WriteLine($"group: {request.GroupId}"); return(new GroupRequestResponse { Approve = false }); }; }
/// <exception cref="ArgumentException">Some of elements in <c>assemblies</c> was <c>null</c>.</exception> public Hydrant(HttpApiClient httpApiClient, ApiPostListener listener, params Assembly[] assemblies) { if (assemblies == null) { throw new ArgumentNullException(nameof(assemblies)); } _assemblies = (Assembly[])assemblies.Clone(); if (_assemblies.Any(a => a is null)) { throw new ArgumentException("Each of elements in assemblies must not be null.", nameof(assemblies)); } _qq = httpApiClient; _listener = listener; // 配置日志 //_logger = FileLogger.Default; listener.OnException += e => LogException(nameof(ApiPostListener), "Listener 的异常", e); // 配置定期任务 _plan = new Task(() => { async void Run(ScheduleInfo info) { info.Next(); await Task.Run(async() => { try { await info.Action.RunAsync(_qq); } catch (Exception e) { //_logger.LogException(e); LogException(GetServiceName(info.Action), "定期任务的异常", e); } }); } var limit = new TimeSpan(0, 1, 0); var minus = new TimeSpan(0, 0, 10); var delay = new TimeSpan(0, 0, 1); TimeSpan Clear() { //TimeSpan min = TimeSpan.MaxValue; //foreach (var info in _regularTasks) //{ // if (info.ShouldRun()) // { // Run(info); // } // TimeSpan wait = info.WaitTime; // if (wait < min) min = wait; //} _regularTasks.Where(info => info.ShouldRun()).ForEach(Run); var min = _regularTasks.Min(info => info.WaitTime); min = min > limit ? min - minus : min + delay; return(min); } while (!_disposeCancellationTokenSource.IsCancellationRequested) { var interval = Clear(); Task.Delay(interval, _disposeCancellationTokenSource.Token).Wait(); } }, TaskCreationOptions.LongRunning); }
public Dispatcher(HttpApiClient onebotApi, ApiPostListener onebotPost, ILogger <Dispatcher>?logger = null) { _logger = logger ?? NullLogger <Dispatcher> .Instance; _onebotApi = onebotApi; _onebotPost = onebotPost; }
static void Main(string[] args) { Database = new MongoClient(Config.DefaultConfig.DatabaseConnectionString).GetDatabase("vtuber-bot-data"); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); if (!string.IsNullOrEmpty(Config.DefaultConfig.ProxyUrl)) { WebRequest.DefaultWebProxy = new WebProxy(Config.DefaultConfig.ProxyUrl); } LogHelper.Info("载入中.."); if (!Config.DefaultConfig.UseLocalClient) { LogHelper.Info("使用CoolQ HTTP接口启动机器人"); Client = new HttpApiClient() { ApiAddress = Config.DefaultConfig.CoolQApi, AccessToken = Config.DefaultConfig.CoolQAccessToken }; Listener = new ApiPostListener() { ApiClient = Client, PostAddress = Config.DefaultConfig.CoolQListenUrl, }; Listener.StartListen(); var service = new CoolService(); SendService = service; Bot = new LocalVtuberBot(SendService, service, null); } else { LogHelper.Info("使用本地QQ框架启动机器人"); User = new QQUser(Config.DefaultConfig.Id, Config.DefaultConfig.Password); var socketServer = new SocketServiceImpl(User); var transponder = new Transponder(); SendService = new SendMessageServiceImpl(socketServer, User); var manage = new MessageManage(socketServer, User, transponder); manage.Init(); QQGlobal.DebugLog = false; while (string.IsNullOrEmpty(User.NickName)) { Thread.Sleep(100); } Bot = new LocalVtuberBot(SendService, transponder, User); } LogHelper.Info("载入完成"); LogHelper.Info("载入缓存中"); CacheManager.Manager.Init(); Thread.Sleep(10000); LogHelper.Info("载入完成"); Bot.Commands.Add(new MenuCommand()); Bot.Commands.Add(new TimeLineCommand()); Bot.Commands.Add(new OfficeInfoCommand()); Bot.Commands.Add(new YoutubeSearchCommand()); Bot.Commands.Add(new VtuberInfoCommand(SendService)); Bot.Commands.Add(new SubscribeCommand()); Bot.Commands.Add(new LiveCommand(SendService)); Bot.Commands.Add(new PluginManagerCommand(SendService)); LogHelper.Info("载入插件中..."); PluginManager.Manager.LoadPlugins(); LogHelper.Info("载入完成."); Console.ReadLine(); }