public static Message GetMusicMessage(OsuApiClient osuApi, BloodcatBeatmapSet set) { int setId = set.Id; string info = string.Empty; info += set.Beatmaps.Max(b => b.TotalLength) + "s, "; if (set.Beatmaps.Length > 1) { info += $"{set.Beatmaps.Min(b => b.Stars):0.##}* - {set.Beatmaps.Max(b => b.Stars):0.##}*"; } else { info += $"{set.Beatmaps.Single()?.Stars:0.##}*"; } // Creator and BPM info += "\r\n" + $"by {set.Creator}"; var bpms = set.Beatmaps.Select(b => b.Bpm).Distinct().ToList(); if (bpms.Count == 1) { info += $" ♩{bpms.First():#.##}"; } if (!string.IsNullOrEmpty(set.Source)) { info += "\r\n" + $"From {set.Source}"; } Message message = SendingMessage.MusicCustom(osuApi.PageOfSetOld(setId), osuApi.PreviewAudioOf(setId), $"{set.Title}/{set.Artist}", info, osuApi.ThumbOf(setId)); return(message); }
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 CreateAndEqualTest() { var atAll = SendingMessage.AtAll(); Assert.Equal("[CQ:at,qq=all]", atAll.Raw); //var section = new Section(Section.MusicType, ("type", "cus"), ("source", "test")); var section = new Section(Section.MusicType, new Dictionary <string, string> { { "type", "cus" }, { "source", "test" }, }); var section2 = new Section(Section.MusicType, ("source", "test"), ("type", "cus")); var json = JsonConvert.SerializeObject(section); var jObj = JsonConvert.DeserializeObject <JObject>(json); Assert.Equal(Section.MusicType, jObj["type"].ToObject <string>()); var desSection = jObj.ToObject <Section>(); Assert.Equal(section, desSection); Assert.Equal(section, section2); Assert.Equal(desSection, section2); Assert.Equal(section.GetHashCode(), desSection.GetHashCode()); Assert.Equal(section.GetHashCode(), section2.GetHashCode()); Assert.Equal(desSection.GetHashCode(), section2.GetHashCode()); Assert.NotEqual(section.Raw, section2.Raw); }
/// <summary> /// Sends given message to host asynchronously using TcpClient with given cancellation token. /// </summary> /// <remarks> /// Sunricher device does not accept messages with interval less than ~100ms, so this method will not run in parallel. /// Internally uses queue to send one message at time. /// </remarks> /// <exception cref="OperationCanceledException">Operation was cancelled during connection to device.</exception> public async Task SendMessageAsync(Byte[] message, CancellationToken cancellationToken) { void SendMessageAction() { if (cancellationToken.IsCancellationRequested) { return; //Return if already cancelled } var eventArgs = new LedMessageEventArgs(message); SendingMessage?.Invoke(this, eventArgs); if (_tcpClient == null) { _tcpClient = new TcpClient(); _tcpClient.ConnectAsync(_host, _port).Wait(cancellationToken); //Will throw if cancelled during connection } var writeTask = _tcpClient .GetStream() .WriteAsync(message, 0, message.Length, cancellationToken); // ReSharper disable MethodSupportsCancellation writeTask.Wait(); MessageSent?.Invoke(this, eventArgs); if (writeTask.Status == TaskStatus.RanToCompletion) { Task.Delay(DelayAfterMessage).Wait(); } // ReSharper restore MethodSupportsCancellation } await _serialQueue.Enqueue(SendMessageAction); }
public static void ProcessQueueMessage([QueueTrigger("line-bot-workitems")] string message, TextWriter log) { log.WriteLine(message); var data = JsonConvert.DeserializeObject <LineMessageObject>(message); if (data?.Results != null) { Task.WhenAll(data.Results.Select(lineMessage => { if (lineMessage.Content != null) { log.WriteLine("Content: " + string.Join(Environment.NewLine, lineMessage.Content.Select(x => $"{x.Key}={x.Value}"))); } log.WriteLine("ContentType: " + lineMessage.ContentType); switch (lineMessage.ContentType) { case ContentType.Text: if (lineMessage.TextContent != null) { log.WriteLine("text: " + lineMessage.TextContent.Text); var sendingMessage = new SendingMessage(); sendingMessage.AddTo(lineMessage.TextContent.From); //TODO: Use Sending multiple messages, LINE response is {"statusCode":"422","statusMessage":"contentType is not valid : 0"} var sendingMessageApi = new SendMessageApi(log); var result = new GitHubSearchApi(log).Search(lineMessage.TextContent.Text).Result; if (result == null || !result.Any()) { sendingMessage.SetSingleContent(new SendingTextContent("There is no content.")); return(Task.WhenAll(sendingMessageApi.Post(sendingMessage))); } return(Task.WhenAll(result.Where(x => !string.IsNullOrEmpty(x)) .Select(s => { if (s.Length > 1024) { s = s.Substring(0, 1024); } sendingMessage.SetSingleContent(new SendingTextContent(s)); return sendingMessageApi.Post(sendingMessage); }))); } break; default: log.WriteLine("Not implemented contentType: " + lineMessage.ContentType); break; } return(Task.FromResult((SendingMessageResponse[])null)); })).Wait(); } }
public void Concat() { var msg1 = new SendingMessage("1"); var msg2 = msg1 + "2"; var msg3 = "3" + msg2; Assert.IsType <SendingMessage>(msg2); Assert.IsType <SendingMessage>(msg3); }
public void Interpolated(SendingMessage expected, SendingMessage actual) { Assert.Equal(expected.Raw, actual.Raw); Assert.Equal(expected.Sections.Count, actual.Sections.Count); for (int i = 0; i < expected.Sections.Count; i++) { Assert.Equal(expected.Sections[i], actual.Sections[i]); } }
public async Task <bool> SendPrivateMessageAsync(long friendId, SendingMessage message) { await SendMessageAsync("sendMessage", new { type = LightMessageType.Friend, qq = friendId.ToString(), content = message.ToString() }); return(true); }
public void ConcatNull() { SendingMessage message1 = null, message2 = null; Assert.NotNull(message1 + message2); Assert.False((message1 + message2)?.Sections.Count > 0); SendingMessage text = "hello"; Assert.Equal(text.Sections, (message1 + text).Sections); Assert.Equal(text.Sections, (text + message1).Sections); }
public async Task <SendingMessageResponse> Post(SendingMessage message) { if (message?.Content == null || !message.Content.Any()) { return(null); } var uri = new Uri(EndpointUrl); var body = JsonConvert.SerializeObject(message); return(await SendAsync <SendingMessageResponse>(uri, HttpMethod.Post, body)); }
/// <summary> /// Only support one image sending. /// </summary> /// <param name="groupNumber"></param> /// <param name="content"></param> public void SendToGroup(long groupNumber, Richtext content) { if (content.Snippets.Any(v => v.Type == MessageType.Picture)) { var image = content.Snippets.First(v => v.Type == MessageType.Picture); var bytes = image.Get <byte[]>("data"); Program.Client.SendGroupMessageAsync(groupNumber, SendingMessage.ByteArrayImage(bytes)).GetAwaiter().GetResult(); return; } Program.Client.SendGroupMessageLimitedAsync(groupNumber, content).GetAwaiter().GetResult(); }
public void SendCommand(Message message) { try { SendingMessage?.Invoke(message); } catch (Exception ex) { LogOutput.Instance.Write(ex); } _server.SendCommand(message.Command + ":" + message.Content); }
public static void ProcessQueueMessage([QueueTrigger("line-bot-workitems")] string message, TextWriter log) { log.WriteLine(message); var data = JsonConvert.DeserializeObject <LineMessageObject>(message); if (data?.Results != null) { Task.WhenAll(data.Results.Select(lineMessage => { if (lineMessage.Content != null) { log.WriteLine("Content: " + string.Join(Environment.NewLine, lineMessage.Content.Select(x => $"{x.Key}={x.Value}"))); } log.WriteLine("ContentType: " + lineMessage.ContentType); switch (lineMessage.ContentType) { case ContentType.Text: if (lineMessage.TextContent != null) { log.WriteLine("text: " + lineMessage.TextContent.Text); var sendingMessage = new SendingMessage(); sendingMessage.AddTo(lineMessage.TextContent.From); var translateApi = new TranslateApi(); var translated = translateApi.Translate(lineMessage.TextContent.Text); if (string.IsNullOrEmpty(translated)) { throw new ApplicationException("reply message is empty"); } sendingMessage.SetSingleContent(new SendingTextContent(translated)); return(new SendMessageApi(log).Post(sendingMessage)); } break; default: log.WriteLine("Not implemented contentType: " + lineMessage.ContentType); break; } return(Task.FromResult((SendingMessageResponse)null)); })).Wait(); } }
public void Ctor() { string message = "123["; string raw = "123["; var msg1 = new SendingMessage(message); Assert.Equal(raw, msg1.Raw); //Assert.Equal(message, msg1.ToString()); var atSection = new Section("at", ("qq", "all")); var atMsg = SendingMessage.AtAll(); Section atMsgSingleSection = atMsg.Sections.Single(); Assert.Equal(atSection, atMsgSingleSection); }
public async Task <bool> SendGroupMessageAsync(long groupId, SendingMessage message) { using (var client = HttpClientExtensions.CreateClient()) { await client.PostJsonAsync(ListenUrl + "Api_SendMsg", new { 响应QQ = QQ.ToString(), 信息类型 = MahuaMessageType.Group, 收信对象群_讨论组 = groupId.ToString(), 收信QQ = groupId.ToString(), 内容 = message.ToString(), 气泡ID = 0 }); } return(true); }
public async Task ProcessAsync(Message message, HttpApiClient api) { var k = new Api("https://konachan.net"); var recent = await k.PopularRecentAsync(); if (recent == null) { return; } recent = recent.Where(p => !p.tags.Split().Intersect(DissTags).Any()).Take(1); foreach (var post in recent) { await api.SendMessageAsync(message.Endpoint, SendingMessage.NetImage(post.JpegUrl)); } }
public void _PostSendingMessage(int IdGenerado, string confirmation_code) { Utils utils = new Utils(); var URL_RECEPCION = utils.GetConfigFromXML("URL_RECEPCION2"); var _cliente = new RestClient(URL_RECEPCION + "?MessageId=" + IdGenerado.ToString() + "&Sent_Date=" + DateTime.Now.ToString() + "&Confirmation_Code=" + confirmation_code); _cliente.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", "{\"query\":\"\",\"variables\":{}}", ParameterType.RequestBody); IRestResponse _response = _cliente.Execute(request); Response2 = JsonConvert.DeserializeObject <SendingMessage>(_response.Content); }
public async Task <bool> SendGroupMessageAsync(long groupId, SendingMessage message) { using (var client = HttpClientExtensions.CreateClient()) { //NMD为啥MPQ变成了 ‘响应的QQ’了,太不上心了吧 await client.PostJsonAsync(ListenUrl + "Api_SendMsg", new { 响应的QQ = QQ.ToString(), 信息类型 = MahuaMessageType.Group, 参考子类型 = 0, 收信对象群_讨论组 = groupId.ToString(), 收信对象 = groupId.ToString(), 内容 = message.ToString(), }); return(true); } }
public static IEnumerable <object[]> Interpolated_TestData() { var cqCodeMessage = SendingMessage.At(123456789); var textMessage = "hello"; var imageMessage = SendingMessage.LocalImage("/a.jpg"); var multipleSegmentMessage = SendingMessage.At(123456789) + "hello" + SendingMessage.LocalImage("/a.jpg"); { yield return(new object[] { SendingMessage.FromInterpolated($"{1}"), "1" }); yield return(new object[] { SendingMessage.FromInterpolated($"{cqCodeMessage},你好"), cqCodeMessage + ",你好" }); yield return(new object[] { SendingMessage.FromInterpolated($"{multipleSegmentMessage},你好"), multipleSegmentMessage + ",你好" }); yield return(new object[] { SendingMessage.FromInterpolated($"{cqCodeMessage}{textMessage}"), cqCodeMessage + textMessage }); yield return(new object[] { SendingMessage.FromInterpolated($"{textMessage}{cqCodeMessage},[]& {23}"), textMessage + cqCodeMessage + ",[]& " + 23.ToString() }); } }
public Response SendMessage([FromBody] SendingMessage message) { //Sends a message try { Response response = new Response(); SqlCommand commandObj = new SqlCommand(); commandObj.CommandType = CommandType.StoredProcedure; commandObj.CommandText = "TP_SendMessage"; commandObj.Parameters.AddWithValue("@SenderID", message.senderid); commandObj.Parameters.AddWithValue("@RecipientID", message.recipientid); commandObj.Parameters.AddWithValue("@MessageBody", message.message); commandObj.Parameters.Add("@SenderName", SqlDbType.VarChar, -1).Direction = ParameterDirection.Output; commandObj.Parameters.Add("@SenderEmail", SqlDbType.VarChar, -1).Direction = ParameterDirection.Output; if (objDB.DoUpdateUsingCmdObj(commandObj, out string exception) == -2) { response.result = "fail"; response.message = exception; } else { List <int> memberBlocks = GetBlocks(message.recipientid.ToString()); if (!(memberBlocks.Contains(Int32.Parse(message.recipientid)))) { //Check if the user is blocked //Creates a notification in the database for the notifier to use when that user is logged in notifier.NotifyMessage(Int32.Parse(message.recipientid), "You have a new message from " + commandObj.Parameters["@SenderName"].Value + "!"); } response.result = "success"; response.message = "Successfully sent Message!"; } return(response); } catch { return(null); } }
public async Task <IActionResult> SendMessage(SendingMessage message) { await chatService.SendMessage(message.ChatId, message.UserId, message.Message); return(Ok()); }
/// <summary> /// Отправка сообщения /// </summary> /// <param name="text">Текст сообщения</param> /// <param name="isSystem">Системное ли</param> /// <param name="receiver">Получатель</param> /// <param name="isPrivate">Приватное ли</param> public void SendMessage(string text, bool isSystem = true, string receiver = Constants.Everybody, bool isPrivate = false) { SendingMessage?.Invoke(this, new Message(text, Name, receiver, isSystem, isPrivate)); }
public Task <bool> SendPrivateMessageAsync(long friendId, SendingMessage message) { throw new NotImplementedException(); }
public Task <bool> SendGroupMessageAsync(long groupId, SendingMessage message) { message.TargetGroupId = groupId; SendingMessageQueue.Enqueue(message); return(Task.FromResult(true)); }
public static void AddMessage(SendingMessage msg) { msg.MyNode=Instance.MessagesToSend.AddLast(msg); }
public void LocalImageTests(string path, string expected) { var image = SendingMessage.LocalImage(path); Assert.Equal(new KeyValuePair <string, string>("file", expected), image.Sections.Single().Data.Single()); }
private static async void RecordTestAsync(HttpApiClient httpApi) { var record = SendingMessage.NetRecord("https://b.ppy.sh/preview/758101.mp3"); await httpApi.SendPrivateMessageAsync(962549599, record); }
public async Task ProcessAsync(Sisters.WudiLib.Posts.Message message, HttpApiClient api) { var osuApi = OsuApi; // 获取操作者信息。 var operatorBind = await Database.GetBindingIdAsync(_operator); if (!operatorBind.Success) { await api.SendMessageAsync(message.Endpoint, "查询数据库失败,无法记录日志。"); return; } string operatorName = (await osuApi.GetUserInfoAsync(operatorBind.Result.Value, OsuMixedApi.Mode.Standard)).Item2?.Name ?? "未知"; // 获取此用户名的相关信息。 var(networkSuccess, newUser) = await osuApi.GetUserInfoAsync(_username, OsuMixedApi.Mode.Standard); if (!networkSuccess) { await api.SendMessageAsync(message.Endpoint, "网络访问失败。"); return; } ExecutingException.Cannot(newUser == null, "没有这个用户。"); // 绑定。 var oldBind = (await Database.ResetBindingAsync( qq: _qq, osuId: newUser.Id, osuName: newUser.Name, source: "由管理员修改", operatorId: _operator, operatorName: operatorName, reason: _reason )).EnsureSuccess("绑定失败,数据库访问出错。"); ExecutingException.Cannot(oldBind.Result == newUser.Id, "未更改绑定,因为已经绑定了该账号。"); SendingMessage message1 = new SendingMessage("将") + SendingMessage.At(_qq) + new SendingMessage($"绑定为{newUser.Name}。"); if (oldBind.Result == null) { await api.SendMessageAsync(message.Endpoint, message1); return; } // 获取旧的用户信息。 OsuMixedApi.UserInfo oldUser; (networkSuccess, oldUser) = await osuApi.GetUserInfoAsync(oldBind.Result.Value, OsuMixedApi.Mode.Standard); if (!networkSuccess) { message1 += new SendingMessage($"因网络问题,无法获取旧的用户名(id: {oldBind.Result.Value})。"); } else if (oldUser == null) { message1 += new SendingMessage($"以前绑定的用户已经被 Ban(id: {oldBind.Result.Value})。"); } else { message1 += new SendingMessage($"取代{oldUser.Name}({oldUser.Id})。"); } await api.SendMessageAsync(message.Endpoint, message1); }