Ejemplo n.º 1
0
        public void TestAppealToTheEmptySticker()
        {
            SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToTheEmptySticker()");

            StickerInfo sticker = sendMessage.Result.Sticker;

            ConsoleUtlis.PrintResult(sticker);
            ConsoleUtlis.PrintResult(sticker.Thumb);

            Assert.Multiple(() =>
            {
                Assert.True(sendMessage.Ok);

                Assert.IsInstanceOf(typeof(StickerInfo), sticker);
                Assert.IsNull(sticker.FileId);
                Assert.AreEqual(sticker.Width, 0);
                Assert.AreEqual(sticker.Height, 0);
                Assert.IsNull(sticker.Emoji);
                Assert.AreEqual(sticker.FileSize, 0);

                Assert.IsInstanceOf(typeof(PhotoSizeInfo), sticker.Thumb);
                Assert.AreEqual(sticker.Thumb.Width, 0);
                Assert.AreEqual(sticker.Thumb.Height, 0);
                Assert.IsNull(sticker.Thumb.FileId);
                Assert.AreEqual(sticker.Thumb.FileSize, 0);
            });
        }
        private async Task <List <SendMessageResult> > SendMessage(CancellationToken token, List <SignalServiceAddress> recipients,
                                                                   List <UnidentifiedAccess?> unidentifiedAccess, long timestamp, byte[] content)
        {
            List <SendMessageResult> results = new List <SendMessageResult>();

            for (int i = 0; i < recipients.Count; i++)
            {
                var recipient = recipients[i];
                try
                {
                    var result = await SendMessage(token, recipient, unidentifiedAccess[i], timestamp, content);

                    results.Add(result);
                }
                catch (UntrustedIdentityException e)
                {
                    results.Add(SendMessageResult.NewIdentityFailure(recipient, e.IdentityKey));
                }
                catch (UnregisteredUserException e)
                {
                    results.Add(SendMessageResult.NewUnregisteredFailure(recipient));
                }
                catch (PushNetworkException e)
                {
                    results.Add(SendMessageResult.NewNetworkFailure(recipient));
                }
            }
            return(results);
        }
Ejemplo n.º 3
0
        private static void test_notify_url()
        {
            var configuration = new Configuration("ENVOTIONS", "Envo6183");

            var smsClient = new SMSClient(configuration);

            {
                var smsRequest = new SMSRequest("ABC", "InfobipDeliveryReport" + DateTime.Now.ToShortDateString(), new string[] { "+886921859698" });
                smsRequest.NotifyURL    = "http://zutech-sms.azurewebsites.net/api/InfobipDeliveryReport";
                smsRequest.CallbackData = "InfobipDeliveryReport";
                SendMessageResult sendMessageResult = smsClient.SmsMessagingClient.SendSMS(smsRequest);

                // requestId = messageId;

                string requestId = sendMessageResult.ClientCorrelator; // you can use this to get deliveryReportList later.

                Console.WriteLine(requestId);
            }

            {
                var smsRequest = new SMSRequest("ABC", "InfobipDeliveryReportRawBody" + DateTime.Now.ToShortDateString(), new string[] { "+886921859698" });
                smsRequest.NotifyURL    = "http://zutech-sms.azurewebsites.net/api/InfobipDeliveryReportRawBody";
                smsRequest.CallbackData = "InfobipDeliveryReportRawBody";
                SendMessageResult sendMessageResult = smsClient.SmsMessagingClient.SendSMS(smsRequest);

                // requestId = messageId;

                string requestId = sendMessageResult.ClientCorrelator; // you can use this to get deliveryReportList later.

                Console.WriteLine(requestId);
            }
        }
Ejemplo n.º 4
0
        public void TestAppealToTheEmptyVideoNote()
        {
            SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToTheEmptyVideoNote");

            VideoNoteInfo videoNote = sendMessage.Result.VideoNote;

            ConsoleUtlis.PrintResult(videoNote);

            Assert.Multiple(() =>
            {
                Assert.True(sendMessage.Ok);

                Assert.IsInstanceOf(typeof(VideoNoteInfo), videoNote);
                Assert.IsNull(videoNote.FileId);
                Assert.AreEqual(videoNote.Length, 0);
                Assert.AreEqual(videoNote.Duration, 0);
                Assert.AreEqual(videoNote.FileSize, 0);

                Assert.IsInstanceOf(typeof(PhotoSizeInfo), videoNote.Thumb);
                Assert.AreEqual(videoNote.Thumb.Width, 0);
                Assert.AreEqual(videoNote.Thumb.Height, 0);
                Assert.IsNull(videoNote.Thumb.FileId);
                Assert.AreEqual(videoNote.Thumb.FileSize, 0);
            });
        }
Ejemplo n.º 5
0
        static void Main()
        {
            IMail email = Mail
                          .Html(@"<img src=""cid:lemon@id"" align=""left"" /> This is simple 
                        <strong>HTML email</strong> with an image and attachment")
                          .Subject("Subject")
                          .AddVisual("Lemon.jpg").SetContentId("lemon@id")
                          .AddAttachment("Attachment.txt").SetFileName("Invoice.txt")
                          .From(new MailBox("*****@*****.**", "Lemon Ltd"))
                          .To(new MailBox("*****@*****.**", "John Smith"))
                          .Create();

            email.Save(@"SampleEmail.eml");             // You can save the email for preview.

            using (Smtp smtp = new Smtp())              // Now connect to SMTP server and send it
            {
                smtp.Connect(_server);                  // Use overloads or ConnectSSL if you need to specify different port or SSL.
                smtp.UseBestLogin(_user, _password);    // You can also use: Login, LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                        // or use UseBestLogin method if you want Mail.dll to choose for you.

                SendMessageResult result = smtp.SendMessage(email);
                Console.WriteLine(result.Status);

                smtp.Close();
            }

            // For sure you'll need to send complex emails,
            // take a look at our templates support in SmtpTemplates sample.
        }
        public SendMessageResult SendMessage([FromBody] MessageModel messageRequest)
        {
            SendMessageResult result = null;

            try
            {
                var message = messageRequest.GetKubeMQMessage();
                var queue   = CreatreQueue(message.Queue, message.ClientID);
                if (queue != null)
                {
                    result = queue.SendQueueMessage(message);
                    if (result.IsError)
                    {
                        Console.WriteLine($"[Sender]Sent:{message.Body} error, error:{result.Error}");
                    }
                    else
                    {
                        Console.WriteLine($"[Sender]Sent:{message.Body}");
                    }
                }
            }
            catch (RpcException rpcex)
            {
                Console.WriteLine($"rpc error: {rpcex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception has accrued: {ex.Message}");
            }

            return(result);
        }
        public static void Execute()
        {
            // Configure in the 'app.config' which Logger levels are enabled(all levels are enabled in the example)
            // Check http://logging.apache.org/log4net/release/manual/configuration.html for more informations about the log4net configuration
            XmlConfigurator.Configure(new FileInfo("OneApiExamples.exe.config"));


            // example:initialize-sms-client
            Configuration configuration = new Configuration(System.Configuration.ConfigurationManager.AppSettings.Get("Username"),
                                                            System.Configuration.ConfigurationManager.AppSettings.Get("Password"));
            SMSClient smsClient = new SMSClient(configuration);
            // ----------------------------------------------------------------------------------------------------

            // example:prepare-message-without-notify-url
            SMSRequest smsRequest = new SMSRequest(senderAddress, message, recipientAddress);
            // ----------------------------------------------------------------------------------------------------

            // example:send-message
            // Store request id because we can later query for the delivery status with it:
            SendMessageResult sendMessageResult = smsClient.SmsMessagingClient.SendSMS(smsRequest);

            // ----------------------------------------------------------------------------------------------------

            // Few seconds later we can check for the sending status
            System.Threading.Thread.Sleep(10000);

            // example:query-for-delivery-status
            DeliveryInfoList deliveryInfoList = smsClient.SmsMessagingClient.QueryDeliveryStatus(senderAddress, sendMessageResult.ClientCorrelator);
            string           deliveryStatus   = deliveryInfoList.DeliveryInfos[0].DeliveryStatus;

            // ----------------------------------------------------------------------------------------------------
            Console.WriteLine(deliveryStatus);
        }
Ejemplo n.º 8
0
        public void TestAppealToTheEmptyDocument()
        {
            SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToTheEmptyDocument()");

            DocumentInfo document = sendMessage.Result.Document;

            ConsoleUtlis.PrintResult(document);
            ConsoleUtlis.PrintResult(document.Thumb);

            Assert.Multiple(() =>
            {
                Assert.True(sendMessage.Ok);

                Assert.IsInstanceOf(typeof(DocumentInfo), document);
                Assert.IsNull(document.FileId);
                Assert.IsNull(document.FileName);
                Assert.IsNull(document.MimeType);
                Assert.AreEqual(document.FileSize, 0);

                Assert.IsInstanceOf(typeof(PhotoSizeInfo), document.Thumb);
                Assert.AreEqual(document.Thumb.Width, 0);
                Assert.AreEqual(document.Thumb.Height, 0);
                Assert.IsNull(document.Thumb.FileId);
                Assert.AreEqual(document.Thumb.FileSize, 0);
            });
        }
Ejemplo n.º 9
0
        public void TestAppealToTheEmptyGame()
        {
            SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToTheEmptyGame()");

            GameInfo gameInfo = sendMessage.Result.Game;

            ConsoleUtlis.PrintResult(gameInfo);

            Assert.Multiple(() =>
            {
                //Game
                Assert.IsInstanceOf(typeof(GameInfo), gameInfo);
                Assert.IsNull(gameInfo.Title);
                Assert.IsNull(gameInfo.Description);
                Assert.IsNull(gameInfo.Text);

                //Game.Photo
                Assert.IsInstanceOf(typeof(PhotoSizeInfo[]), gameInfo.Photo);

                //Game.Entities
                Assert.IsInstanceOf(typeof(MessageEntityInfo[]), gameInfo.Entities);

                //Game.Animation
                Assert.IsNull(gameInfo.Animation.FileId);
                Assert.IsNull(gameInfo.Animation.FileName);
                Assert.IsNull(gameInfo.Animation.MimeType);
                Assert.AreEqual(0, gameInfo.Animation.FileSize);

                //Game.Animation.Thumb
                Assert.IsNull(gameInfo.Animation.Thumb.FileId);
                Assert.AreEqual(0, gameInfo.Animation.Thumb.Height);
                Assert.AreEqual(0, gameInfo.Animation.Thumb.Width);
                Assert.AreEqual(0, gameInfo.Animation.Thumb.FileSize);
            });
        }
Ejemplo n.º 10
0
        public void TestAppealToTheEmptyForwardFromChat()
        {
            SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToTheEmptyForwardFrom()");

            ChatInfo forwardFromChat = sendMessage.Result.ForwardFromChat;

            ConsoleUtlis.PrintResult(forwardFromChat);
            ConsoleUtlis.PrintResult(forwardFromChat.Photo);

            Assert.Multiple(() =>
            {
                Assert.True(sendMessage.Ok);

                Assert.IsInstanceOf(typeof(ChatInfo), forwardFromChat);
                Assert.AreEqual(forwardFromChat.Id, 0);
                Assert.IsNull(forwardFromChat.Type);
                Assert.IsNull(forwardFromChat.Title);
                Assert.IsNull(forwardFromChat.Username);
                Assert.IsNull(forwardFromChat.FirstName);
                Assert.IsNull(forwardFromChat.LastName);
                Assert.IsFalse(forwardFromChat.AllMembersAreAdministrators);
                Assert.IsNull(forwardFromChat.Description);
                Assert.IsNull(forwardFromChat.InviteLink);

                Assert.IsNull(forwardFromChat.Photo.BigFileId);
                Assert.IsNull(forwardFromChat.Photo.SmallFileId);
            });
        }
Ejemplo n.º 11
0
    //Public Method SendSMS
    public string SendSMS(string mobileno, string message)
    {
        if (CheckConnection())
        {
            try
            {
                SmsClient.ServerAddress       = ServerAddress;
                SmsClient.Port                = Convert.ToInt32(ServerPort);
                SmsClient.HttpProxy.ProxyMode = HttpProxyMode.AutoDetect;
                //SmsClient.HttpProxy.Host = ProxyAddress;
                //SmsClient.HttpProxy.Port = Convert.ToInt32(ProxyPort);

                SmsClient sms = new SmsClient(Username, Password);
                try
                {
                    SendMessageResult result = sms.SendMessage(mobileno, message);
                    return(result.TaskId + "|" + result.MessageId);
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        else
        {
            return("Error");
        }
    }
Ejemplo n.º 12
0
        public void TestSendComplexTextMessageAsFactoryMethod()
        {
            SendMessageResult result = _messageClient.SendSingleMessage(ComplexMessageContent.InstanceAsTextMessageContent("复杂文本消息概要", "这里是复杂文本消息的内容"),
                                                                        new PersonMessageReceiver("zhongt", "钟涛"));

            Assert.AreEqual(true, result.Success);
        }
Ejemplo n.º 13
0
        private SendMessageResult SendReminderEmail(Guid assessmentSystemEmailGuid, int PersonAliasId)
        {
            var person = new PersonAliasService(new RockContext()).GetPerson(PersonAliasId);
            var result = new SendMessageResult();

            if (!person.IsEmailActive)
            {
                result.Warnings.Add($"{person.FullName.ToPossessive()} email address is inactive.");
                return(result);
            }

            var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            mergeObjects.Add("Person", person);

            var recipients = new List <RockEmailMessageRecipient>();

            recipients.Add(new RockEmailMessageRecipient(person, mergeObjects));

            var emailMessage = new RockEmailMessage(assessmentSystemEmailGuid);

            emailMessage.SetRecipients(recipients);

            if (emailMessage.Send(out var errors))
            {
                result.MessagesSent = 1;
            }
            else
            {
                result.Errors.AddRange(errors);
            }
            return(result);
        }
        /// <summary>
        /// Send a message to a single recipient.
        /// </summary>
        /// <param name="token">The cancellation token</param>
        /// <param name="recipient">The message's destination.</param>
        /// <param name="unidentifiedAccess"></param>
        /// <param name="message">The message.</param>
        public async Task <SendMessageResult> SendMessage(CancellationToken token, SignalServiceAddress recipient,
                                                          UnidentifiedAccessPair?unidentifiedAccess, SignalServiceDataMessage message)
        {
            byte[] content = await CreateMessageContent(token, message);

            long timestamp           = message.Timestamp;
            SendMessageResult result = await SendMessage(token, recipient, unidentifiedAccess?.TargetUnidentifiedAccess, timestamp, content);

            if ((result.Success != null && result.Success.NeedsSync) || (unidentifiedAccess != null && IsMultiDevice))
            {
                byte[] syncMessage = CreateMultiDeviceSentTranscriptContent(content, recipient, (ulong)timestamp, new List <SendMessageResult>()
                {
                    result
                });
                await SendMessage(token, LocalAddress, unidentifiedAccess?.SelfUnidentifiedAccess, timestamp, syncMessage);
            }

            if (message.EndSession)
            {
                Store.DeleteAllSessions(recipient.E164number);

                if (EventListener != null)
                {
                    EventListener.OnSecurityEvent(recipient);
                }
            }
            return(result);
        }
        private async Task SendMessage(CancellationToken token, VerifiedMessage message, UnidentifiedAccessPair?unidentifiedAccessPair)
        {
            byte[] nullMessageBody = new DataMessage()
            {
                Body = Base64.EncodeBytes(Util.GetRandomLengthBytes(140))
            }.ToByteArray();

            NullMessage nullMessage = new NullMessage()
            {
                Padding = ByteString.CopyFrom(nullMessageBody)
            };

            byte[] content = new Content()
            {
                NullMessage = nullMessage
            }.ToByteArray();

            SendMessageResult result = await SendMessage(token, new SignalServiceAddress(message.Destination), unidentifiedAccessPair?.TargetUnidentifiedAccess, message.Timestamp, content);

            if (result.Success.NeedsSync)
            {
                byte[] syncMessage = CreateMultiDeviceVerifiedContent(message, nullMessage.ToByteArray());
                await SendMessage(token, LocalAddress, unidentifiedAccessPair?.SelfUnidentifiedAccess, message.Timestamp, syncMessage);
            }
        }
Ejemplo n.º 16
0
        public void TestAppealToSuccessfulPayment()
        {
            SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToTheEmptySuccessfulPayment()");

            SuccessfulPaymentInfo successfulPaymentInfo = sendMessage.Result.SuccessfulPayment;

            ConsoleUtlis.PrintResult(successfulPaymentInfo);

            Assert.Multiple(() =>
            {
                //SuccessfulPaymentInfo field
                Assert.IsInstanceOf(typeof(SuccessfulPaymentInfo), successfulPaymentInfo);
                Assert.IsNull(successfulPaymentInfo.Currency);
                Assert.AreEqual(0, successfulPaymentInfo.TotalAmmount);
                Assert.IsNull(successfulPaymentInfo.InvoicePayload);
                Assert.IsNull(successfulPaymentInfo.ShippingOptionId);
                Assert.IsNull(successfulPaymentInfo.TelegramPaymentChargeId);
                Assert.IsNull(successfulPaymentInfo.ProviderPaymentChargeId);

                //OrderInfo fields
                Assert.IsInstanceOf(typeof(OrderInfo), successfulPaymentInfo.OrderInfo);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.Name);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.PnoneNumber);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.Email);

                //ShippingAddressInfo fields
                Assert.IsInstanceOf(typeof(ShippingAddressInfo), successfulPaymentInfo.OrderInfo.ShippingAddress);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.ShippingAddress.CountryCode);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.ShippingAddress.State);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.ShippingAddress.City);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.ShippingAddress.StreetLineOne);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.ShippingAddress.StreetLineTwo);
                Assert.IsNull(successfulPaymentInfo.OrderInfo.ShippingAddress.PostCode);
            });
        }
Ejemplo n.º 17
0
        public void TestAppealToTheEmptyNewChatMember()
        {
            SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToTheEmptyNewChatMember()");

            UserInfo newChatMember = sendMessage.Result.NewChatMember;
            var      id            = sendMessage.Result.NewChatMember.Id;
            var      firstName     = sendMessage.Result.NewChatMember.FirstName;
            var      lastName      = sendMessage.Result.NewChatMember.LastName;
            var      userName      = sendMessage.Result.NewChatMember.UserName;
            var      languageCode  = sendMessage.Result.NewChatMember.LanguageCode;

            ConsoleUtlis.PrintResult(newChatMember);

            Assert.Multiple(() =>
            {
                Assert.True(sendMessage.Ok);

                Assert.IsInstanceOf(typeof(UserInfo), newChatMember);
                Assert.AreEqual(id, 0);
                Assert.IsNull(firstName);
                Assert.IsNull(lastName);
                Assert.IsNull(userName);
                Assert.IsNull(languageCode);
            });
        }
Ejemplo n.º 18
0
        public void TestSendComplexTextMessageWithActionAsFactoryMethod()
        {
            SendMessageResult result = _messageClient.SendSingleMessage(ComplexMessageContent.InstanceAsTextMessageContent("简单文本消息概要", "这里是简单问题消息的内容",
                                                                                                                           Action.InstanceAsOpenUrl("http://www.mi.com")),
                                                                        new PersonMessageReceiver("zhongt", "钟涛"));

            Assert.AreEqual(true, result.Success);
        }
Ejemplo n.º 19
0
        public void SendSendLocationTest()
        {
            const float latitude  = 1.00000095f;
            const float longitude = 1.00000203f;

            SendMessageResult sendLocation = mTelegramBot.SendLocation(mChatGroupId, latitude, longitude);

            Assert.AreEqual(sendLocation.Result.Location.Latitude, latitude);
            Assert.AreEqual(sendLocation.Result.Location.Longitude, longitude);
        }
Ejemplo n.º 20
0
        public void TestAppealToMigrateFromPinnedMessage()
        {
            SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToMigrateFromPinnedMessage()");

            MessageInfo pinnedMessage = sendMessage.Result.PinnedMessage;

            ConsoleUtlis.PrintResult(pinnedMessage);

            CommonAsserts(pinnedMessage);
        }
Ejemplo n.º 21
0
        public async Task <SendMessageResult> SendMessageAsync(Uri queueUrl, SendMessageRequest request)
        {
            var httpRequest = new HttpRequestMessage(HttpMethod.Post, queueUrl)
            {
                Content = GetPostContent(request.ToParams())
            };

            var responseText = await SendAsync(httpRequest).ConfigureAwait(false);

            return(SendMessageResult.Parse(responseText));
        }
Ejemplo n.º 22
0
        public void TestSendComplexTextMessage()
        {
            ComplexMessageContent     complexMessageContent = new ComplexMessageContent("复杂文本消息概要", ComplexMessageType.Text);
            ComplexMessageContentItem contentItem           = new ComplexMessageContentItem("这里是复杂文本消息的内容");

            complexMessageContent.AddMessageContentItem(contentItem);

            SendMessageResult result = _messageClient.SendSingleMessage(complexMessageContent, new PersonMessageReceiver("zhongt", "钟涛"));

            Assert.AreEqual(true, result.Success);
        }
Ejemplo n.º 23
0
        static SendMessageResult SendCommand(InsteonBridgeStream stream, CommandMessage msg, int timeout, out byte[] data)
        {
            SendMessageResult r = WriteMessage(stream, msg.GetBytes, timeout);

            if (r != OK)
            {
                data = null;
                return(r);
            }
            return(ReadResponse(stream, msg.GetResponseHeaderBytes, timeout, CommandResponse.Length, out data));
        }
Ejemplo n.º 24
0
        public void Initialize(SendMessageResult result, byte[] data = null)
        {
            if (Initialized)
            {
                throw new InvalidOperationException("Already initialized; Initialize() cannot be called more than once.");
            }

            Result        = result;
            ResponseBytes = result == OK ? data : null;
            Initialized   = true;
        }
Ejemplo n.º 25
0
        public void SendPhotoAsUrlTest()
        {
            ExistingFile existing = new ExistingFile
            {
                Url = "https://proglib.io/wp-content/uploads/2017/07/telegram-bot-na-Python-s-ispolzovaniem-tolko-requests.jpg"
            };

            SendMessageResult sendMessage = mTelegramBot.SendPhoto("@telebotTestChannel", existing);

            Assert.AreEqual("AgADBAADEsg4GwoeZAcwyq9C0fVhKANXvRkABDMpTvt2GGzZ-2UEAAEC", sendMessage.Result.Photo[0].FileId);
        }
Ejemplo n.º 26
0
        public void TestSendOpenUrlMessage()
        {
            ComplexMessageContent     complexTextMessage = new ComplexMessageContent("演示打开一个远程URL的Action消息", ComplexMessageType.Text);
            ComplexMessageContentItem contentItem        = new ComplexMessageContentItem("点击可以打开远程URL页面",
                                                                                         Action.InstanceAsOpenUrl("http://www.xiaomi.com"));

            complexTextMessage.AddMessageContentItem(contentItem);

            SendMessageResult result = _messageClient.SendSingleMessage(complexTextMessage, new PersonMessageReceiver("zhongt", "钟涛"));

            Assert.AreEqual(true, result.Success);
        }
Ejemplo n.º 27
0
        public void TestSendOpenHtmlMessage()
        {
            ComplexMessageContent     complexTextMessage = new ComplexMessageContent("演示打开一个HTML的Action消息", ComplexMessageType.Text);
            ComplexMessageContentItem contentItem        = new ComplexMessageContentItem("点击可以打开HTML页面",
                                                                                         Action.InstanceAsOpenHtml("<div><b>这里是HTML的详细内容</b></div>"));

            complexTextMessage.AddMessageContentItem(contentItem);

            SendMessageResult result = _messageClient.SendSingleMessage(complexTextMessage, new PersonMessageReceiver("zhongt", "钟涛"));

            Assert.AreEqual(true, result.Success);
        }
Ejemplo n.º 28
0
        public void TestSendMultiTextMessage()
        {
            List <PersonMessageReceiver> personMessageReceivers = new List <PersonMessageReceiver>
            {
                new PersonMessageReceiver("zhongt", "钟涛"),
                new PersonMessageReceiver("wuyang", "武扬")
            };
            MultiMessageReceiver multiMessageReceiver = new MultiMessageReceiver(personMessageReceivers, PersonMessageReceiverIdType.LoginId);
            SendMessageResult    result = _messageClient.SendMultiMessage(new TextMessageContent("简单文本消息"), multiMessageReceiver);

            Assert.AreEqual(true, result.Success);
        }
Ejemplo n.º 29
0
        public void TestSendOpenNativeFunctionMessageAsOpenBingoTouchRemotePage()
        {
            ComplexMessageContent     complexTextMessage = new ComplexMessageContent("演示打开一个Bingotouch远程页面的Action消息", ComplexMessageType.Text);
            ComplexMessageContentItem contentItem        = new ComplexMessageContentItem("点击可以打开BingoTouch远程应用页面",
                                                                                         Action.InstanceAsOpenNative(NativeCommandAndParamsBuilder.BuildAsOpenBingoTouchRemoteAppPage("http://www.mi.com")));

            complexTextMessage.AddMessageContentItem(contentItem);

            SendMessageResult result = _messageClient.SendSingleMessage(complexTextMessage, new PersonMessageReceiver("zhongt", "钟涛"));

            Assert.AreEqual(true, result.Success);
        }
Ejemplo n.º 30
0
        public static string Send(string queue_url, string msg)
        {
            AmazonSQS          sqs    = AWSClientFactory.CreateAmazonSQSClient();
            SendMessageRequest msgreq = new SendMessageRequest();

            msgreq.QueueUrl    = queue_url;
            msgreq.MessageBody = msg;
            SendMessageResponse msgres = sqs.SendMessage(msgreq);
            SendMessageResult   msgrst = msgres.SendMessageResult;

            return(msgrst.ToString());
        }
Ejemplo n.º 31
0
        public SendMessageResult SendCommand(string chatRoomId, string token, string targetUserId, string command)
        {
            var result = new SendMessageResult();
            string userId = chatRoomStorage.GetUserIdByToken(token);
            if (userId == null)
            {
                result.Error = "Chat disconnected!";
                return result;
            }

            if (!chatRoomStorage.IsUserInRoom(chatRoomId, userId))
            {
                result.Error = "Chat disconnected!";
                return result;
            }

            var user = chatUserProvider.GetUser(userId);
            var targetUser = chatUserProvider.GetUser(targetUserId);

            if (command == "ignore")
            {
                chatUserProvider.IgnoreUser(userId, targetUserId);
            }
            else if (command == "kick")
            {
                if (chatUserProvider.IsChatAdmin(userId, chatRoomId) && chatRoomStorage.IsUserInRoom(chatRoomId, targetUserId))
                {
                    chatRoomStorage.RemoveUserFromRoom(chatRoomId, targetUserId);

                    chatRoomStorage.AddMessage(chatRoomId, new Message
                    {
                        Content =
                            string.Format("User {0} has been kicked off the room by {1}.",
                                          targetUser.DisplayName, user.DisplayName),
                        FromUserId = targetUserId,
                        MessageType = MessageTypeEnum.Kicked,
                        Timestamp = Miscellaneous.GetTimestamp()
                    });
                }
            }
            else if (command == "ban")
            {
                if (chatUserProvider.IsChatAdmin(userId, chatRoomId) && chatRoomStorage.IsUserInRoom(chatRoomId, targetUserId))
                {
                    chatRoomStorage.RemoveUserFromRoom(chatRoomId, targetUserId);

                    chatRoomStorage.AddMessage(chatRoomId, new Message
                    {
                        Content =
                            string.Format("User {0} has been kicked off the room by {1} (Banned).",
                                          targetUser.DisplayName, user.DisplayName),
                        FromUserId = targetUserId,
                        MessageType = MessageTypeEnum.Kicked,
                        Timestamp = Miscellaneous.GetTimestamp()
                    });

                    chatRoomProvider.BanUser(chatRoomId, userId, targetUserId);
                }
            }
            else if (command == "slap")
            {
                chatRoomStorage.AddMessage(chatRoomId, new Message
                {
                    Content =
                        string.Format("{0} slaps {1} around with a large trout.",
                                      user.DisplayName, targetUser.DisplayName),
                    FromUserId = userId,
                    MessageType = MessageTypeEnum.System,
                    Timestamp = Miscellaneous.GetTimestamp()
                });
            }

            return result;
        }
Ejemplo n.º 32
0
        public SendMessageResult SendMessage(string chatRoomId, string token, string toUserId, string message, 
            bool bold = false, bool italic = false, bool underline = false, string fontName = null, int? fontSize = null,
            string color = null)
        {
            var result = new SendMessageResult();
            string userId = chatRoomStorage.GetUserIdByToken(token);
            if (userId == null)
            {
                result.Error = "Chat disconnected!";
                return result;
            }

            if (!chatRoomStorage.IsUserInRoom(chatRoomId, userId))
            {
                result.Error = "Chat disconnected!";
                return result;
            }

            // TODO: Process message (trim, filter)
            if (!string.IsNullOrEmpty(color))
                color = Regex.Replace(color, @"[^\w\#]", String.Empty); // Strip dangerous input
            var formatOptions = new MessageFormatOptions
                                           {
                                               Bold = bold,
                                               Italic = italic,
                                               Underline = underline,
                                               Color = color,
                                               FontName = fontName,
                                           };
            if (fontSize.HasValue) formatOptions.FontSize = fontSize.Value;
            chatRoomStorage.AddMessage(chatRoomId, new Message
                                                       {
                                                           Content = WebUtility.HtmlEncode(message),
                                                           FromUserId = userId,
                                                           ToUserId = toUserId,
                                                           MessageType = MessageTypeEnum.User,
                                                           Timestamp = Miscellaneous.GetTimestamp(),
                                                           FormatOptions = formatOptions
                                                       });

            return result;
        }