//TODO: allows me to add to output. Find a better way to do this. //rewriteFile: add the text to the json file. False during the initial read of the json file. public void AddTextToTexts(TextMessage text, bool rewriteFile) { if (rewriteFile) { JSONArray array = (JSONArray)savedTexts ["texts"]; for (int i = textsLength; i > 0; i --) //move all contacts up an index in the array { array[i]["sender"] = array[i-1]["sender"]; Debug.Log ("recipient: '" + array[i-1]["recipient"] + "'"); array[i]["recipient"] = array[i-1]["recipient"]; array[i]["message"] = array[i-1]["message"]; array[i]["timestamp"] = array[i-1]["timestamp"]; array[i]["isRead"] = array[i-1]["isRead"]; array[i]["isTraceable"] = array[i-1]["isTraceable"]; } array[0]["sender"] = text.GetSender(); //add the new text at the top array[0]["recipient"] = text.GetRecipient(); array[0]["message"] = text.GetMessage(); array[0]["timestamp"] = ""+text.GetTimestamp(); array[0]["isRead"] = ""+text.HasBeenRead(); array[0]["isTraceable"] = ""+text.IsTraceable(); savedTexts ["texts"] = array; SaveJson(); } texts.Insert (0, text); textsLength += 1; }
private MatchResult WithRegex(TextMessage msg) { MatchCollection matches = Regex.Matches(msg.Text, "testregex", RegexOptions.IgnoreCase); return matches.Cast<Match>().Any(m => m.Success) ? new MatchResult(true, matches) : new MatchResult(false); }
/// <summary> /// 发送支付宝服务窗消息 /// </summary> /// <param name="msg"></param> private string SendAlipay(TextMessage msg) { string url = ParamDic["url"]; string appid = string.Empty; try { appid = ParamDic[msg.AppCode + "_app_id"]; //获取appid,通过appcode_app_id找ParamList.config } catch (Exception ex) { throw new Exception("获取" + msg.AppCode + " appid失败" + ex.Message); } string content = msg.Text.Content; List<string> lists = new List<string>(); //支付宝服务窗异步文本消息不能超过4k,所以限制消息文本不得超过360个字符, while (content.Length > 360) { lists.Add(content.Substring(0,360)); content = content.Remove(0, 360); } lists.Add(content); string result = string.Empty; foreach (var s in lists) { string str = s; str = HttpUtility.HtmlEncode(str); //对发送文本中包含html转义字符做html转义 str = HttpUtility.JavaScriptStringEncode(str); //对发送字符做javascript转义 //生成发送数据 string sendData = StringHelper.GetSendStringContent(msg.Openid, str, appid, "alipay.mobile.public.message.custom.send", "utf-8");//生成要发送的数据 try { result = SendHelper.SendPOSTAndGetStr(url, sendData, "utf-8");//发送 } catch (Exception ex) { throw ex; } //返回其中一个发送异常 if (!result.Contains("\"code\":200")) { Logger.Write("SendData:"+sendData+"\n Response Data:"+result, "ReturnError"); return result; } } return result; }
private MatchResult NoOtherHandlers(TextMessage msg) { if (_robot.Listeners.OfType<TextListener>().Any(t => t.RegexPattern.IsMatch(msg.Text))) { return new MatchResult(false); } return new MatchResult(true); }
public TextMessage getModel() { var model = new TextMessage(); Mapper.CreateMap<TextMessageView, TextMessage>(); Mapper.Map<TextMessageView, TextMessage>(this, model); return model; }
void OnTriggerEnter() { Debug.Log("trigger"); ps.PhoneUpdateText (message); TextMessage txt = new TextMessage (sender, message); string str = txt.ToString(); ps.PhoneUpdateText (str); }
public void HandleIncomingMessage(TextMessage textMessage) { _sentTextMessage = null; IMBotMessage reply = HandleIncomingMessage(textMessage.Text); TextMessage message = reply.ToMsnMessage(); _contact.SendMessage(message); }
// returns a welcome message public TextMessage Welcome( string yourName ) { // add welcome message to field of TextMessage object TextMessage message = new TextMessage(); message.Message = string.Format( "Welcome to WCF Web Services with REST and JSON, {0}!", yourName ); return message; }
public void AddConsoleMessage(TextMessage message) { if(InvokeRequired) Invoke(new Action<TextMessage>(AddConsoleMessage), message); else { consoleView.AddMessage(message); } }
void IMessageLogger.SendMessage(TestMessageLevel testMessageLevel, string message) { TextMessage textMessage = new TextMessage() { Level = testMessageLevel, Text = message }; Events.Add(new Event() { EventType = EventType.SendMessage, Message = textMessage }); }
public async System.Threading.Tasks.Task <VoiceMessage> ProcessAsync(TextMessage message) { switch (message.Language) { case Core.Enums.Language.English: this._language = SynthesisLanguage.English; break; case Core.Enums.Language.Russian: this._language = SynthesisLanguage.Russian; break; default: throw new Exceptions.InvalidMessageException(message.Id, "Invalid Language: " + message.Language.ToString()); } var apiSetttings = new SpeechKitClientOptions($"{YandexCompmnentConfig.YandexSpeechApiKey}", "MashaWebApi", Guid.Empty, "server"); using (var client = new SpeechKitClient(apiSetttings)) { var options = new SynthesisOptions(message.Text, YandexCompmnentConfig.Speed) { AudioFormat = SynthesisAudioFormat.Wav, Language = _language, Emotion = Emotion.Good, Quality = SynthesisQuality.High, Speaker = Speaker.Omazh }; using (var textToSpechResult = await client.TextToSpeechAsync(options, cancellationToken).ConfigureAwait(false)) { if (textToSpechResult.TransportStatus != TransportStatus.Ok || textToSpechResult.ResponseCode != HttpStatusCode.OK) { throw new Exception("YandexSpeechKit error: " + textToSpechResult.ResponseCode.ToString()); } VoiceMessage result = new VoiceMessage { Id = message.Id, Language = message.Language, Vioce = textToSpechResult.Result.ToByteArray() }; return(result); } } }
private void OnMessageReceived(object sender, TextMessage textMessage) { if (textMessage?.Message == null) { Log.Warn("Invalid TextMessage: {@textMessage}", textMessage); return; } Log.Debug("TextMessage: {@textMessage}", textMessage); var langResult = LocalizationManager.LoadLanguage(config.Language, false); if (!langResult.Ok) { Log.Error("Failed to load language file ({0})", langResult.Error); } textMessage.Message = textMessage.Message.TrimStart(' '); if (!textMessage.Message.StartsWith("!", StringComparison.Ordinal)) { return; } Log.Info("User {0} requested: {1}", textMessage.InvokerName, textMessage.Message); clientConnection.InvalidateClientBuffer(); ulong?channelId = null, databaseId = null, channelGroup = null; ulong[] serverGroups = null; if (tsFullClient.Book.Clients.TryGetValue(textMessage.InvokerId, out var bookClient)) { channelId = bookClient.Channel; databaseId = bookClient.DatabaseId; serverGroups = bookClient.ServerGroups.ToArray(); channelGroup = bookClient.ChannelGroup; } else if (!clientConnection.GetClientInfoById(textMessage.InvokerId).GetOk(out var infoClient).GetError(out var infoClientError)) { channelId = infoClient.ChannelId; databaseId = infoClient.DatabaseId; serverGroups = infoClient.ServerGroups; channelGroup = infoClient.ChannelGroup; }
private void 添加新人物ToolStripMenuItem_Click(object sender, EventArgs e) { for (int i = 0x2328; i <= 0x270f; i++) { if (!this.Persons.HasGameObject(i)) { Person t = new Person(); t.Scenario = this.MainForm.Scenario; t.ID = i; t.SurName = "新"; t.GivenName = "人物"; t.PictureIndex = 0x7d1; t.Strain = t.ID; t.Alive = true; t.IdealTendency = this.MainForm.Scenario.GameCommonData.AllIdealTendencyKinds[0] as IdealTendencyKind; t.Character = this.MainForm.Scenario.GameCommonData.AllCharacterKinds[0]; this.Persons.Add(t); Biography biography = this.MainForm.Scenario.GameCommonData.AllBiographies.GetBiography(t.ID); if (biography == null) { biography = new Biography(); biography.ID = t.ID; biography.Scenario = t.Scenario; biography.FactionColor = 0; biography.MilitaryKinds.AddMilitaryKind(t.Scenario.GameCommonData.AllMilitaryKinds.GetMilitaryKind(0)); biography.MilitaryKinds.AddMilitaryKind(t.Scenario.GameCommonData.AllMilitaryKinds.GetMilitaryKind(1)); biography.MilitaryKinds.AddMilitaryKind(t.Scenario.GameCommonData.AllMilitaryKinds.GetMilitaryKind(2)); t.Scenario.GameCommonData.AllBiographies.AddBiography(biography); } t.PersonBiography = biography; TextMessage textMessage = this.MainForm.Scenario.GameCommonData.AllTextMessages.GetTextMessage(t.ID); if (textMessage == null) { textMessage = new TextMessage(); textMessage.ID = t.ID; textMessage.Scenario = t.Scenario; t.Scenario.GameCommonData.AllTextMessages.AddTextMessage(textMessage); } t.PersonTextMessage = textMessage; this.RebindDataSource(); break; } } }
public async Task <IActionResult> SendMessage(SendMessageDTO sendMessage) { #region TokenValidation try { token = HttpContext.Request.Headers["Authorization"]; token = token.Replace("Bearer ", ""); if (!_tokenHelper.IsValidateToken(token)) { error.Err = "Token wygasł"; error.Desc = "Zaloguj się od nowa"; return(StatusCode(405, error)); } } catch { error.Err = "Nieprawidlowy token"; error.Desc = "Wprowadz token jeszcze raz"; return(StatusCode(405, error)); } #endregion var id = _tokenHelper.GetIdByToken(token); var user = await _apiHelper.ReturnUserByID(id); var classObj = await _apiHelper.ReturnClassByID(sendMessage.classID); if (classObj == null || !classObj.members.Contains(id)) { error.Err = "Nie możesz wysłać wiadomości"; error.Desc = "Nie należysz do tej klasy"; return(StatusCode(405, error)); } TextMessage textMessage = new TextMessage { messageID = 0, msessage = sendMessage.message, senderName = user.name, senderSurname = user.surrname, sendTime = DateTime.Now }; var message = await _apiHelper.SendMessage(sendMessage.subjectID, textMessage); return(Ok(textMessage)); }
public void TestSetObjectProperty() { TextMessage msg = new TextMessage(); string name = "property"; try { msg.Properties[name] = "string"; msg.Properties[name] = (Char)1; msg.Properties[name] = (Int16)1; msg.Properties[name] = (Int32)1; msg.Properties[name] = (Int64)1; msg.Properties[name] = (Byte)1; msg.Properties[name] = (UInt16)1; msg.Properties[name] = (UInt32)1; msg.Properties[name] = (UInt64)1; msg.Properties[name] = (Single)1.1f; msg.Properties[name] = (Double)1.1; msg.Properties[name] = (Boolean)true; msg.Properties[name] = null; } catch (NMSException) { Assert.Fail("should accept object primitives and String"); } try { msg.Properties[name] = new Object(); Assert.Fail("should accept only object primitives and String"); } catch (NMSException) { } try { msg.Properties[name] = new StringBuilder(); Assert.Fail("should accept only object primitives and String"); } catch (NMSException) { } }
public async Task Post( [FromBody] GitHubPayload payload, [FromQuery] string lineId, [FromQuery] string jenkinsUrl) { var message = new TextMessage() { Text = $"專案[{payload.Repository.Name}],由使用者[{payload.Sender.Login}]觸發建置({payload.Ref})" }; await Bot.Push(lineId, message); HttpClient client = new HttpClient(); try { var response = await client.GetAsync(jenkinsUrl); if (response.IsSuccessStatusCode) { var success = new TextMessage() { Text = $"專案[{payload.Repository.Name}]({payload.Ref})引動Jenkins成功!正在建置..." }; await Bot.Push(lineId, success); } else { var error = new TextMessage() { Text = $"專案[{payload.Repository.Name}]({payload.Ref})引動Jenkins失敗!" }; await Bot.Push(lineId, error); } } catch (Exception e) { var error = new TextMessage() { Text = $"專案[{payload.Repository.Name}]({payload.Ref})引動Jenkins失敗!" }; var errorData = new TextMessage() { Text = $"錯誤訊息: {e.Message}" }; await Bot.Push(lineId, error, errorData); } }
static void TestSSL() { var connection = new ConnectionConfiguration(); connection.Port = 5673; connection.UserName = "******"; connection.Password = "******"; connection.Product = "SSLTest"; var host1 = new HostConfiguration(); host1.Host = "192.168.0.169"; host1.Port = 5673; host1.Ssl.Enabled = true; host1.Ssl.ServerName = "www.shiyx.top"; host1.Ssl.CertPath = @"E:\git\RabbitMqDemo\server.pfx"; host1.Ssl.CertPassphrase = "123123"; host1.Ssl.AcceptablePolicyErrors = SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateChainErrors; //var host2 = new HostConfiguration(); //host2.Host = "192.168.0.115"; //host2.Port = 5673; //host2.Ssl.Enabled = true; //host2.Ssl.ServerName = "www.shiyx.top"; //host2.Ssl.CertPath = @"E:\git\RabbitMqDemo\server.pfx"; //host2.Ssl.CertPassphrase = "123123"; connection.Hosts = new List <HostConfiguration> { host1 }; connection.Validate(); var bus = RabbitHutch.CreateBus(connection, services => services.Register <ILogProvider>(ConsoleLogProvider.Instance)); var message = new TextMessage { MessageRouter = "api.notice.zhangsan", MessageBody = "Hello Rabbit" }; bus.Publish(message, x => x.WithTopic(message.MessageRouter)); Console.WriteLine("发送成功"); }
/// <summary> /// Enviar un mensaje al chat group /// al ser publico puede ser invocado desde el cliente /// </summary> /// <param name="name"></param> /// <param name="message"></param> public void Send(string name, string message) { var msg = new TextMessage { Title = message, Text = message }; var conn = connList.Find(c => c.ConnectionID == Context.ConnectionId); if (conn == null) { return; } //atencion para enviar un mensaje a un grupo determinado se selecciona el grupo y se hace un broadcast a este //(todos los ejemplos con otros metodos no funcionan) //enviar un mensaje a todo el grupo //Clients.Group(name).broadcastMessage(name, msg); //enviar el mensaje para persistir HubContextHelper.SendClientMessage(conn, msg); }
public void SendMessageToAll(TextMessage message) { var listOfUsers = ConnectedUsers.Values.ToList(); foreach (var user in listOfUsers) { try { user.ReceiveMessage(message); } catch (Exception e) { Console.Error.WriteLine(e); var item = ConnectedUsers.First(pair => pair.Value == user); Unregister(item.Key); } } }
public void TestFiltersUserOrContent() { MobileStorage.Messages.Clear(); SMSProvider SMSProvider = new SMSProvider(formMessageFormating); TextMessage message1 = new TextMessage("User", "Hello1"); SMSProvider.SendMessage(message1); TextMessage message2 = new TextMessage("User", "Hello"); SMSProvider.SendMessage(message2); TextMessage message3 = new TextMessage("User1", "Hello"); SMSProvider.SendMessage(message3); ExpectationsList.Clear(); ExpectationsList.Add(message1); ExpectationsList.Add(message3); ResultList = formMessageFormating.Filters(Messages, "User1", "Hello1", DateTime.Now, DateTime.Now, true, false); CollectionAssert.AreEqual(ExpectationsList, ResultList); }
private static void PublishGeneric(string key) { using (var publisher = GetPublisher(key)) { for (int i = 1; i <= 1000000; i++) { var payload = new TextMessage { Text = $"{i}: Hello World..." }; var msg = GetGenericMessage(payload); publisher.Publish(msg); Console.WriteLine(" [x] Sent wrapped message {0}", msg.Message.Body); // Simulate real world Thread.Sleep(rnd.Next(0, 500)); } } }
private static async Task PassQuery(string phoneNumber, string messageBody, ILogger log) { var userAccount = await AccountsClient.GetAccount(phoneNumber); log.LogInformation( $"AdmissionFunc| Sending request to process query of '{userAccount.Name} / {userAccount.PhoneNumber}'"); var textMessage = new TextMessage { Account = userAccount, Body = messageBody }; await ExistingAccountsQueueClient.SendAsync(new Message { To = "incomingqueries", Body = textMessage.GetBytes() }); }
public void SendMessage_StyledMessage_TextMessage() { var message = "test styled sendMessage"; var expected = new TextMessage { Chat = _privateChat, Text = message, From = _botUser, Entities = new List <MessageEntity> { _italicTextEntity } }; var actual = _telegramMethods.SendMessage(_privateChat.Id.ToString(), "_" + message + "_", ParseMode.Markdown).Result; var compareLogic = new CompareLogic(_config); var comparationResult = compareLogic.Compare(expected, actual); Assert.IsTrue(comparationResult.AreEqual, comparationResult.DifferencesString); }
public ActionResult Composs(TextMessage textMessage) { var recipient = db.AppUsers.Where(e => e.UserId == textMessage.id).FirstOrDefault(); var number = recipient.phoneNumber; number = "+1" + number; const string accountSid = "AC3b1a400c4343537508f47488b4542f97"; const string authToken = "aa474c6417dfce7a1c98c64aba6f16e6"; TwilioClient.Init(accountSid, authToken); var message = MessageResource.Create( body: textMessage.BodyOfMessage, from: new Twilio.Types.PhoneNumber("+12622179385"), to: new Twilio.Types.PhoneNumber(number) ); Console.WriteLine(message.Sid); return(RedirectToAction("Index")); }
private void JoinGame(string playerName) { if (!tcpClient.Connected) { OnJoin?.Invoke(null); return; } try { //Отправка имени игрока: TextMessage textMessage = new TextMessage(playerName); tcpClient.Send(textMessage); joinGameListener.Start(); } catch (Exception) { OnJoin?.Invoke(null); } }
/// <summary> /// Received a text message from the server. /// </summary> /// <param name="textMessage"></param> public virtual void TextMessage(TextMessage textMessage) { User user; if (!textMessage.ShouldSerializeActor() || !UserDictionary.TryGetValue(textMessage.Actor, out user)) //If we don't know the user for this packet, just ignore it { return; } if (textMessage.ChannelIds == null || textMessage.ChannelIds.Length == 0) { if (textMessage.TreeIds == null || textMessage.TreeIds.Length == 0) { //personal message: no channel, no tree PersonalMessageReceived(new PersonalMessage(user, string.Join("", textMessage.Message))); } else { //recursive message: sent to multiple channels Channel channel; if (!ChannelDictionary.TryGetValue(textMessage.TreeIds[0], out channel)) //If we don't know the channel for this packet, just ignore it { return; } //TODO: This is a *tree* message - trace down the entire tree (using IDs in textMessage.TreeId as roots) and call ChannelMessageReceived for every channel ChannelMessageReceived(new ChannelMessage(user, string.Join("", textMessage.Message), channel, true)); } } else { foreach (uint channelId in textMessage.ChannelIds) { Channel channel; if (!ChannelDictionary.TryGetValue(channelId, out channel)) { continue; } ChannelMessageReceived(new ChannelMessage(user, string.Join("", textMessage.Message), channel)); } } }
/// <summary> /// event_MessageHandler /// </summary> /// <param name="sender"></param> /// <param name="args"></param> void event_MessageHandler(object sender, EMSMessageEventArgs args) { // Since args.Message is generic message we need to box into TextMessage // which allows us access to the message.Text content. TextMessage message = (TextMessage)args.Message; string msg = message.Text; Console.Write(DateTime.Now.ToLongTimeString() + "\t"); Console.WriteLine("Received message: " + msg); // Acknowledge we received the message. If the message did not get written to disk // we want to not acknowledge the message was received. if (ackMode == Session.CLIENT_ACKNOWLEDGE || ackMode == Session.EXPLICIT_CLIENT_ACKNOWLEDGE || ackMode == Session.EXPLICIT_CLIENT_DUPS_OK_ACKNOWLEDGE) { args.Message.Acknowledge(); } }
private void ListenSocket_OnRecieve(object sender, SocketEventArgs e) { TextMessage inMessage = (TextMessage)e.Message; Application.Current.Dispatcher.Invoke(() => { switch (e.Message.Type) { case MessageType.TextMessage: ChatListView.Items.Add(string.Format("{0}", (e.Message as TextMessage).Text)); break; default: break; } (sender as SNetServer).SendToAllClients(e.Message.Buffer); }); }
private void HostInfo_Run() { int counter = 0; Boolean end = false; while (end != true) { TextMessage msg = new TextMessage(); msg.Type = "dagent.presence"; counter += 1; counter = counter % 15; msg.value = "<dagent>"; msg.value += "<hostinfo>"; msg.value += "<uuid>" + this.Broker.UUID + "</uuid>"; msg.value += "<uptime>" + Util.getUptime() + "</uptime>"; msg.value += "</hostinfo>"; msg.value += "</dagent>"; this.HostInfo_Channel.Send(msg); msg.Type = "dagent.hostinfo"; if (counter == 1) { msg.value = "<dagent>"; msg.value += "<hostinfo>"; msg.value += "<uuid>" + this.Broker.UUID + "</uuid>"; msg.value += "<uptime>" + Util.getUptime() + "</uptime>"; msg.value += "<user>" + Util.getUserName() + "</user>"; msg.value += "<hostname>" + Util.getHostName() + "</hostname>"; msg.value += "<installeddate>" + Util.getInstalledDate() + "</installeddate>"; msg.value += "<ipaddress>" + Util.getIPAddress() + "</ipaddress>"; msg.value += "<macaddress>" + Util.getMacAddress() + "</macaddress>"; msg.value += "<os>" + Util.getOperatingSystem() + "</os>"; msg.value += "<kernel>" + Util.getOSKernel() + "</kernel>"; msg.value += "<architecture>" + Util.getArchitecture() + "</architecture>"; msg.value += "</hostinfo>"; msg.value += "</dagent>"; this.HostInfo_Channel.Send(msg); // MessageBox.Show(msg.value); } /* sleep for approximately 1 minute */ Thread.Sleep(50000 + this.random.Next(1, 30)); } }
public bool MatchMessage(TextMessage textMessage, RootModel rootModel) { ClearMatchingResults(); if (IsRegExp) { Match match; if (_compiledRegex != null) { match = _compiledRegex.Match(textMessage.InnerText); } else { var varReplace = rootModel.ReplaceVariables(MatchingPattern); if (!varReplace.IsAllVariables) { return(false); } Regex rExp = new Regex(varReplace.Value); match = rExp.Match(textMessage.InnerText); } if (!match.Success) { return(false); } for (int i = 0; i < 10; i++) { if (i + 1 < match.Groups.Count) { _matchingResults[i] = match.Groups[i + 1].ToString(); } } return(true); } var res = GetRootPatternToken(rootModel).Match(textMessage.InnerText, 0, _matchingResults); return(res.IsSuccess); }
public void SendMessage_InlineKeyboardMarkupMessage_TextMessage() { var message = "https://www.twitch.tv"; var expected = new TextMessage { Chat = _privateChat, Text = message, From = _botUser, Entities = new List <MessageEntity> { _urlEntity } }; var actual = _telegramMethods.SendMessage(_privateChat.Id.ToString(), message, null, false, false, null, _testInlineKeyboardMarkup).Result; var compareLogic = new CompareLogic(_config); var comparationResult = compareLogic.Compare(expected, actual); Assert.IsTrue(comparationResult.AreEqual, comparationResult.DifferencesString); }
public void CanHandleSomeEqualTextInMessageRegex() { var paramses = new HandlerParams(null, new Update() { Message = new Message() { Text = "Blah", Chat = new Chat() { Type = ChatType.Private } } }, null, "testbot"); var attribute = new TextMessage("foo|bar|Blah", true); Assert.True(attribute.CanHandleInternal(paramses)); attribute = new TextMessage("foo", true); Assert.False(attribute.CanHandleInternal(paramses)); }
public void Broadcast(string text, UserSession sender = null) { Console.WriteLine(sender == null ? $"\n[Chat] System: {text}" : $"\n[Chat] {sender.Name}: {text}"); var message = new TextMessage() { From = sender == null ? "System" : $"{sender.Name}", Text = text }; foreach (var user in usersOnline) { //if (user != sender) //{ // user.SendMessage(message); //} user.SendMessage(message); } }
public ReturnValue SendText(int agentID, string content, string toParty, string toTag, string toUser) { Text text = new Text { content = content }; TextMessage message = new TextMessage { agentid = agentID, text = text, msgtype = "text", safe = 0, toparty = toParty, totag = toTag, touser = toUser }; return(this.SendText(message)); }
public void CanHandleSomeEqualTextInMessage() { var paramses = new HandlerParams(null, new Update() { Message = new Message() { Text = "Blah" } }, null, "testbot"); var attribute = new TextMessage("Blah"); Assert.True(attribute.CanHandleInternal(paramses)); attribute = new TextMessage("Foo"); Assert.False(attribute.CanHandleInternal(paramses)); attribute = new TextMessage("/test"); Assert.False(attribute.CanHandleInternal(paramses)); }
public void SendReceiveForeignTextMessageTest( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using (IConnection connection = CreateConnection()) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { try { producer.DeliveryMode = deliveryMode; TextMessage request = new TextMessage(); request.Properties[propertyName] = propertyValue; request.Text = textBody; producer.Send(request); ITextMessage message = consumer.Receive(receiveTimeout) as ITextMessage; Assert.IsNotNull(message, "No message returned!"); Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties."); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); // Check the body Assert.AreEqual(textBody, message.Text, "TextMessage body was wrong."); // use generic API to access entries Assert.AreEqual(propertyValue, message.Properties[propertyName], "generic map entry: " + propertyName); // use type safe APIs Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName), "map entry: " + propertyName); } catch (NotSupportedException) { } } } } }
private void OnTextMsgReceived(object o, TextMessageRecivedEventArgs e) { if (MsgReceived != null) { var textMsg = new TextMessage() { text = e.text, ipToken = e.id }; //saving // //to ui MsgReceived(this, new TextMessageArgs() { msg = textMsg }); } }
public Response EditTextMessage(TextMessage message, long messageId) { string url = baseUrl + "editmessagetext"; string content = Utils.Serialize(message, new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("message_id", messageId.ToString()) }); HttpResponseMessage response = client.PostAsync(url, new StringContent(content, Encoding.UTF8, "application/json")).Result; if (response.StatusCode == System.Net.HttpStatusCode.OK) { string result = response.Content.ReadAsStringAsync().Result; Response res = Utils.Deserialize <Response>(result); return(res); } return(null); }
public void OnCompletion(Message msg) { try { System.Console.WriteLine("Successfully sent message {0}.", ((TextMessage)msg).Text); TextMessage m = (TextMessage)msg; String s = m.Text; s = s + "."; m.Text = s; } catch (EMSException e) { System.Console.WriteLine("Error retrieving message text."); System.Console.WriteLine("Message: " + e.Message); System.Console.WriteLine(e.StackTrace); } }
public void SendMessage(string[] message, bool recursive) { var msg = new TextMessage { actor = Owner.LocalUser.Id, message = string.Join(Environment.NewLine, message), }; if (recursive) { msg.tree_id.AddRange(new uint[] { Id }); } else { msg.channel_id.AddRange(new uint[] { Id }); } Owner.Connection.SendControl <TextMessage>(PacketType.TextMessage, msg); }
public static TextMessage Deserialize(string rawMessage) { TextMessage msg = new TextMessage(); // '3:' [message id ('+')] ':' [message endpoint] ':' [data] // 3:1::blabla msg.RawMessage = rawMessage; string[] args = rawMessage.Split(SPLITCHARS, 4); if (args.Length == 4) { int id; if (int.TryParse(args[1], out id)) msg.AckId = id; msg.Endpoint = args[2]; msg.MessageText = args[3]; } else msg.MessageText = rawMessage; return msg; }
public static void SendMessage(this IEnumerable<Channel> channels, string[] message, bool recursive) { // It's conceivable that this group could include channels from multiple different server connections // group by server foreach (var group in channels.GroupBy(a => a.Owner)) { var owner = group.First().Owner; var msg = new TextMessage { actor = owner.LocalUser.Id, message = string.Join(Environment.NewLine, message), }; if (recursive) msg.tree_id.AddRange(group.Select(c => c.Id)); else msg.channel_id.AddRange(group.Select(c => c.Id)); owner.Connection.SendControl<TextMessage>(PacketType.TextMessage, msg); } }
public void SendChatMessage(TextMessage txtmsg) { txtmsg.Sent = true; ChatMessage msg = new ChatMessage(null); msg.From = txtmsg.From; msg.To = txtmsg.To; msg.Type = "chat"; msg.Body = txtmsg.Message; //msg.InnerXML = string.Format(@"<body>{0}</body>", txtmsg.Message); /// Find the roster guy for this message and add it to their conversation /// RosterItem item = XMPPClient.FindRosterItem(txtmsg.To); if (item != null) { item.AddSendTextMessage(txtmsg); // Notify XMPPClient that a new conversation item has been added XMPPClient.FireNewConversationItem(item, false, txtmsg); } XMPPClient.SendXMPP(msg); }
public bool SendMessage(string text) { // if there is no switchboard available, request a new switchboard session if (conversation.SwitchboardProcessor.Connected == false) { return false; } else { // note: you can add some code here to catch the event where the remote contact lefts due to being idle too long // in that case Conversation.Switchboard.Contacts.Count equals 0. /* You can optionally change the message's font, charset, color here. * For example: * message.Color = Color.Red; * message.Decorations = TextDecorations.Bold; */ TextMessage message = new TextMessage(text); conversation.Switchboard.SendTextMessage(message); frm_main.AddFormLog(String.Format("[<< {0}] :\r\n{1}", Mail, text)); return true; } }
public override bool NewMessage(Message iq) { /// See if this is a standard text message /// if (iq is ChatMessage) { ChatMessage chatmsg = iq as ChatMessage; RosterItem item = XMPPClient.FindRosterItem(chatmsg.From); if (item != null) { if (chatmsg.Body != null) { TextMessage txtmsg = new TextMessage(); txtmsg.From = chatmsg.From; txtmsg.To = chatmsg.To; txtmsg.Received = DateTime.Now; if (chatmsg.Delivered.HasValue == true) txtmsg.Received = chatmsg.Delivered.Value; /// May have been a server stored message txtmsg.Message = chatmsg.Body; txtmsg.Sent = false; item.AddRecvTextMessage(txtmsg); item.HasNewMessages = true; // Notify XMPPClient that a new conversation item has been added XMPPClient.FireNewConversationItem(item, true, txtmsg); } if (chatmsg.ConversationState != ConversationState.none)// A conversation message { item.Conversation.ConversationState = chatmsg.ConversationState; XMPPClient.FireNewConversationState(item, item.Conversation.ConversationState); } } return true; } return false; }
public string SendQQMessage(TextMessage msg) { string nonce = RandomHelper.GetRandom(); string token = string.Empty; QqTextSendInfo sendInfo = new QqTextSendInfo(); sendInfo.msgtype = "text"; try { sendInfo.spid = ParamDic[msg.AppCode + "_spid"]; token = ParamDic[msg.AppCode + "_token"]; } catch (Exception ex) { throw new Exception("获取"+msg.AppCode+"spid或token失败"); } sendInfo.touser = msg.Openid; sendInfo.spsc = "00"; msg.Text.Content = HttpUtility.UrlDecode(msg.Text.Content); //url编码 sendInfo.text = msg.Text; string signature = SHA1.SHA1_Encrypt(sendInfo.spid + token + nonce); //签名 string url = ParamDic["SendMsgUrl"] + "?spid=" + sendInfo.spid + "&signature=" + signature + "&nonce=" + nonce + ""; string JsonData = JsonConvert.SerializeObject(sendInfo); string ruStr = WebRequserSender.SendPOST(JsonData, url, "text/json;charset=utf-8"); //JObject jsonObj = JObject.Parse(ruStr); //if (jsonObj["errcode"].ToString() != "0") //{ // ExceptionHelper.HandleException(new Exception("调用QQ接口,发送消息接口请求异常:" + ruStr),"Job"); //} return ruStr; }
private void LoadMessage(Dictionary<string, IConversation> conversationHashTable, TextMessage message, ILoadingProgressCallback progressCallback) { CheckForCancel(progressCallback); string conversationKey; PhoneNumber messagePhoneNumber = new PhoneNumber(message.Address, message.Country); string phoneNumberStripped = PhoneNumber.Strip(messagePhoneNumber); if (message.ChatId != null) { conversationKey = message.ChatId; } else { conversationKey = phoneNumberStripped; } if (string.IsNullOrEmpty(conversationKey)) { return; } Contact unknownContact = new Contact(Contact.UnknownContactId, null, null, null, messagePhoneNumber); message.Contact = GetContactByPhoneNumber(messagePhoneNumber); if (message.Contact == null) { message.Contact = unknownContact; } else { // // Update the contact's phone number to include country information. // foreach (PhoneNumber contactPhoneNumber in message.Contact.PhoneNumbers) { if (PhoneNumber.NumbersAreEquivalent(contactPhoneNumber, messagePhoneNumber)) { contactPhoneNumber.Country = message.Country; break; } } } IConversation conversation; if (conversationHashTable.ContainsKey(conversationKey)) { conversation = conversationHashTable[conversationKey]; // If The contact is not part of the conversation, add them here. This can happen with "orphaned" chat // messages. if (!message.Contact.Equals(unknownContact) && !conversation.AssociatedContacts.Contains(message.Contact)) { conversation.AssociatedContacts.Add(message.Contact); } } else if (message.ChatId != null) { // It's possible to have "orphaned" chat messages, where they appear in the message database with a chat ID // but the chat ID was not in the chat room database. Handle those here. List<IContact> chatContacts = new List<IContact>(); if (!message.Contact.Equals(unknownContact)) { chatContacts.Add(message.Contact); } conversation = new ChatConversation(chatContacts); conversationHashTable.Add(message.ChatId, conversation); } else { conversation = new SingleNumberConversation(unknownContact); conversationHashTable.Add(conversationKey, conversation); } _messageLookupTable.Add(message.MessageId, message); conversation.AddMessage(message); IncrementWorkProgress(progressCallback); }
protected internal virtual void SendTextMessage(Contact remoteContact, TextMessage textMessage) { textMessage.PrepareMessage(); string to = ((int)remoteContact.ClientType).ToString() + ":" + remoteContact.Account; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = NSMessageHandler.MachineGuid.ToString("B").ToLowerInvariant(); if (remoteContact.ClientType == IMAddressInfoType.Circle) { mmMessage.RoutingHeaders[MIMERoutingHeaders.To][MIMERoutingHeaders.Path] = "IM"; } else if (remoteContact.Online) { mmMessage.RoutingHeaders[MIMERoutingHeaders.ServiceChannel] = "IM/Online"; } else { mmMessage.RoutingHeaders[MIMERoutingHeaders.ServiceChannel] = "IM/Offline"; } if (remoteContact.Via != null) { mmMessage.RoutingHeaders[MIMERoutingHeaders.To]["via"] = ((int)remoteContact.Via.ClientType).ToString() + ":" + remoteContact.Via.Account; } mmMessage.ContentKeyVersion = "2.0"; mmMessage.ContentHeaders[MIMEContentHeaders.MessageType] = MessageTypes.Text; mmMessage.ContentHeaders[MIMEHeaderStrings.X_MMS_IM_Format] = textMessage.GetStyleString(); mmMessage.InnerBody = Encoding.UTF8.GetBytes(textMessage.Text); NSMessage sdgPayload = new NSMessage("SDG"); sdgPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(sdgPayload); }
protected internal virtual void SendOIMMessage(Contact remoteContact, TextMessage textMessage) { SendTextMessage(remoteContact, textMessage); }
/// <summary> /// Sends a mobile message to the specified remote contact. This only works when /// the remote contact has it's mobile device enabled and has MSN-direct enabled. /// </summary> /// <param name="receiver"></param> /// <param name="text"></param> protected internal virtual void SendMobileMessage(Contact receiver, string text) { TextMessage txtMsg = new TextMessage(text); string to = ((int)receiver.ClientType).ToString() + ":" + ((receiver.ClientType == IMAddressInfoType.Telephone) ? "tel:" + receiver.Account : receiver.Account); string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.RoutingHeaders[MIMERoutingHeaders.ServiceChannel] = "IM/Mobile"; mmMessage.ContentKeyVersion = "2.0"; mmMessage.ContentHeaders[MIMEContentHeaders.MessageType] = MessageTypes.Text; mmMessage.ContentHeaders[MIMEContentHeaders.MSIMFormat] = txtMsg.GetStyleString(); mmMessage.InnerBody = Encoding.UTF8.GetBytes(txtMsg.Text); NSMessage sdgPayload = new NSMessage("SDG"); sdgPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(sdgPayload); }
public void SetTextMessageContent(string content) { string str = ""; TextMessage txt = new TextMessage (content); str = "From: " + txt.GetSender () + "\n"; //senderText.text = senderStart + txt.GetSender(); DateTime dt = new DateTime (txt.GetTimestamp()); string date = dt.Day + "/" + dt.Month + "/" + dt.Year + " " + dt.Hour + ":" + dt.Minute + ":" + dt.Second; str += "Time: " + date + "\n"; str += txt.GetMessage (); //ResetAllLines(); SetScreenText (str); //timestampText.text = timeStart +date; //messageText.text = txt.GetMessage(); }
private void ExtendedTextMessage(object sender, TextMessage eventArgs) { if (connectionData.suppressLoopback && eventArgs.InvokerId == me.ClientId) return; OnMessageReceived?.Invoke(sender, eventArgs); }
private MatchResult WithoutRegex(TextMessage msg) { return new MatchResult(true); }
private bool HasInvokerAdminRights(TextMessage textMessage) { Log.Write(Log.Level.Debug, "AdminCheck called!"); ClientData client = QueryConnection.GetClientById(textMessage.InvokerId); if (client == null) return false; int[] clientSgIds = QueryConnection.GetClientServerGroups(client); return clientSgIds.Contains(mainBotData.adminGroupId); }
private void TextCallback(object sender, TextMessage textMessage) { Log.Write(Log.Level.Debug, "MB Got message from {0}: {1}", textMessage.InvokerName, textMessage.Message); textMessage.Message = textMessage.Message.TrimStart(new[] { ' ' }); if (!textMessage.Message.StartsWith("!")) return; BobController.HasUpdate(); QueryConnection.RefreshClientBuffer(true); // get the current session BotSession session = SessionManager.GetSession(textMessage.Target, textMessage.InvokerId); if (textMessage.Target == MessageTarget.Private && session == SessionManager.DefaultSession) { Log.Write(Log.Level.Debug, "MB User {0} created auto-private session with the bot", textMessage.InvokerName); try { session = SessionManager.CreateSession(this, textMessage.InvokerId); } catch (SessionManagerException smex) { Log.Write(Log.Level.Error, smex.ToString()); return; } } var isAdmin = new Lazy<bool>(() => HasInvokerAdminRights(textMessage)); var execInfo = new ExecutionInformation(session, textMessage, isAdmin); // check if the user has an open request if (session.ResponseProcessor != null) { if (session.ResponseProcessor(execInfo)) { session.ClearResponse(); return; } } // parse (and execute) the command ASTNode parsedAst = CommandParser.ParseCommandRequest(textMessage.Message); if (parsedAst.Type == ASTType.Error) { PrintAstError(session, (ASTError)parsedAst); } else { var command = CommandManager.CommandSystem.AstToCommandResult(parsedAst); try { var res = command.Execute(execInfo, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String, CommandResultType.Empty }); if (res.ResultType == CommandResultType.String) { var sRes = (StringCommandResult)res; // Write result to user if (!string.IsNullOrEmpty(sRes.Content)) session.Write(sRes.Content); } } catch (CommandException ex) { session.Write("Error: " + ex.Message); } catch (Exception ex) { session.Write("An unexpected error occured: " + ex.Message); Log.Write(Log.Level.Error, "MB Unexpected command error: ", ex); } } }
private void SendSms(TextMessage txtmessage) { var twilio = new TwilioRestClient(AccountSid, TwilioAuthToken); var message = twilio.SendMessage(TwilioNumber, "+1" + txtmessage.ToPerson.PhoneNumber, txtmessage.FromPerson.Name + ": " + txtmessage.Request.Body, @"http://benjaminjanderson.com/smslistener.ashx"); _uow.SmsLogs.Add(new SmsLog { Message = txtmessage.Request.Body, SmsDate = DateTime.UtcNow, MessageType = SmsMessageType.Sent, SmsPersonId = txtmessage.ToPerson.Id, MessageId = message.Sid, MessageStatus = "Sending", }); _uow.SaveChanges(); }
private void BeginSendMessage(TextMessage msg) { if (this.role is Member) { DataUtil.Client.BeginSendMesg(msg, new AsyncCallback((result) => { var status = DataUtil.Client.EndSendMesg(result); if (status == MessageStatus.Failed) { } else if (status == MessageStatus.Refuse) { MessageBox.Show("您不是对方的好友,不可以给对方发消息,你可以先删除该好友然后添加"); return; } }), this); } else if (this.role is Group) { Group group = role as Group; P2PClient.GetP2PClient(group.GroupId).SendP2PMessage(msg); } }
public void SendMesg(string mesg) { TextMessage msg = new TextMessage(); msg.from = DataUtil.Member; msg.to = role; msg.sendTime = DateTime.Now; msg.type = MessageType.TextMessage; msg.msg = mesg; BeginSendMessage(msg); if (role is Member) { Paragraph pa = new Paragraph(); string nickName = DataUtil.Member.nickName + " " + DateTime.Now.ToLongTimeString() + Environment.NewLine; pa.Inlines.Add(new Run(nickName) { FontSize = 15, Foreground=new SolidColorBrush(Colors.White), FontFamily = new FontFamily("Avenir Book") }); pa.Inlines.Add(new Run(mesg) { FontSize = 20,Foreground = new SolidColorBrush(Color.FromArgb(255, 172, 32, 9))}); rtxtBox.Document.Blocks.Add(pa); pa.LineStackingStrategy = LineStackingStrategy.MaxHeight; rtxtBox.ScrollToEnd(); } }
public void SendTextMessage(TextMessage textMessage) { _sentTextMessage = textMessage; _sentTextMessageTimeout = DateTime.Now.AddSeconds(90); _contact.SendMessage(textMessage); }
public static void SelectEnter() { savedText = new TextMessage("me", "", m_newTextMessageContent, "", true, true); if (m_collectionType == TextMessageCollection.CollectionType.Inbox) { if (selectOptionAtIndex == 0) //reply { Debug.Log ("reply"); } else if (selectOptionAtIndex == 1) //delete { DeleteTextViaOptions(); } } else if (m_collectionType == TextMessageCollection.CollectionType.Outbox) { if (selectOptionAtIndex == 0) //delete { DeleteTextViaOptions(); } } else if (m_collectionType == TextMessageCollection.CollectionType.Drafts) { if (selectOptionAtIndex == 0) //enter contact { Debug.Log ("Select from contacts"); ps.ShowAllContactsForPossibleTextRecipient(); } else if (selectOptionAtIndex == 1) //enter number { Debug.Log ("enter number"); //ps.EnterNumberAsTextRecipient(); } else if (selectOptionAtIndex == 2) { Debug.Log ("Save draft and quit"); //public TextMessage(string sender, string recipient, string message, string timestamp, bool isRead, bool isTraceable) //TODO: what if we are over-writing an old draft text? This will just add a new one ps.draftTexts.AddTextToTexts(savedText, true); ps.SetViewToTextMessageCollection(); } else if (selectOptionAtIndex == 3) { Debug.Log ("Back to drafts menu"); ps.SetViewToTextMessageCollection(); } else if (selectOptionAtIndex == 4) { Debug.Log ("delete draft"); DeleteTextViaOptions(); } } else if (m_collectionType == TextMessageCollection.CollectionType.Create) { if (selectOptionAtIndex == 0) { Debug.Log ("Select from contacts"); ps.ShowAllContactsForPossibleTextRecipient(); } else if (selectOptionAtIndex == 1) { Debug.Log ("enter number"); ps.EnterNumberAsTextRecipient(); } else if (selectOptionAtIndex == 2) //save and quit { Debug.Log ("save to drafts and quit"); //public TextMessage(string sender, string recipient, string message, string timestamp, bool isRead, bool isTraceable) //TODO: what if we are over-writing an old draft text? This will just add a new one ps.draftTexts.AddTextToTexts(savedText, true); ps.SetViewToSubMainMenu(); } else if (selectOptionAtIndex == 3) //Back to message { Debug.Log ("Quit to message menu"); ps.SetViewToSubMainMenu(); } } }