private async Task <SendNotificationResult> SendNotificationAsync(Notification notification)
        {
            ValidateParameters(notification);

            var result = new SendNotificationResult();

            TwilioClient.Init(_options.AccountId, _options.AccountPassword);

            try
            {
                var message = await MessageResource.CreateAsync(
                    body : notification.Body,
                    from : new Twilio.Types.PhoneNumber(_options.Sender),
                    to : notification.Recipient
                    );

                result.IsSuccess = message.Status != MessageResource.StatusEnum.Failed;
                if (!result.IsSuccess)
                {
                    result.ErrorMessage = $"Twilio sending failed. Error code: {message.ErrorCode}. Error message: {message.ErrorMessage}.";
                }
            }
            catch (ApiException e)
            {
                result.ErrorMessage = $"Twilio Error {e.Code} - {e.MoreInfo}. Exception: {e.Message}";
            }
            catch (Exception e)
            {
                result.ErrorMessage = $"Twilio sending failed. Exception: {e.Message}";
            }

            return(result);
        }
Exemplo n.º 2
0
        public async Task SendSMSMessageAsync(string bodyText, string fromPhoneNumber, string toPhoneNumber)
        {
            var twilioRestClient = GetTwilioRestClient();
            await MessageResource.CreateAsync(body : bodyText, from : new PhoneNumber(fromPhoneNumber), to : new PhoneNumber(toPhoneNumber), client : twilioRestClient).ConfigureAwait(false);

            _logger.LogInformation("Sent Text Message {Body} From:{From} To: {To}", bodyText, fromPhoneNumber, toPhoneNumber);
        }
Exemplo n.º 3
0
        public async Task <MessageResource> SendSMSAsync(string toPhoneNumber, string fromPhoneNumber, string message)
        {
            MessageResource messageResource = null;

            try
            {
                TwilioClient.Init(AccountSID, AuthToken);

                messageResource = await MessageResource.CreateAsync(body : message,
                                                                    from : new PhoneNumber(fromPhoneNumber),
                                                                    to : new PhoneNumber(toPhoneNumber));
            }
            catch (AuthenticationException e)
            {
                //Debug.WriteLine(e.Message);
                throw e;
            }
            catch (ApiException e)
            {
                //Debug.WriteLine(e.Message);
                //Debug.WriteLine($"Twilio Error {e.Code} - {e.MoreInfo}");
                throw e;
            }

            return(messageResource);
        }
Exemplo n.º 4
0
 public Task SendAsync(string number, string message)
 {
     if (string.IsNullOrWhiteSpace(SMSAccountFrom))
     {
         throw new ArgumentNullException();
     }
     if (string.IsNullOrWhiteSpace(SMSAccountIdentification))
     {
         throw new ArgumentNullException();
     }
     if (string.IsNullOrWhiteSpace(SMSAccountPassword))
     {
         throw new ArgumentNullException();
     }
     try
     {
         TwilioClient.Init(SMSAccountIdentification, SMSAccountPassword);
         return(MessageResource.CreateAsync(
                    to: new PhoneNumber(number),
                    from: new PhoneNumber(SMSAccountFrom),
                    body: message));
     }
     catch (Exception e)
     {
         _logger.LogCritical(e, e.Message);
         return(Task.CompletedTask);
     }
 }
 public async Task SendMessageAsync(string message, string phoneNumber)
 {
     var messageResource = await MessageResource.CreateAsync(
         to : new PhoneNumber(phoneNumber),
         from : new PhoneNumber(_fromPhonenumber),
         body : message, client : _client);
 }
        public async Task <string> SendSms(string messageContent, string phoneNumberTo)
        {
            try
            {
                // Find your Account Sid and Token at twilio.com/console
                const string accountSid      = AppConstants.TwilioAccountSid;
                const string authToken       = AppConstants.TwilioAuthToken;
                const string phoneNumberFrom = AppConstants.TwilioFromPhoneNumber;

                TwilioClient.Init(accountSid, authToken);

                var message = await MessageResource.CreateAsync(
                    body : messageContent,
                    from : new Twilio.Types.PhoneNumber(phoneNumberFrom),
                    to : new Twilio.Types.PhoneNumber(phoneNumberTo)
                    );

                Console.WriteLine(message.Sid);
                return(messageContent);
            }
            catch (ApiException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine($"Twilio Error {e.Code} - {e.MoreInfo}");
                return($"Twilio Error {e.Message} - {e.Code}");
            }
        }
Exemplo n.º 7
0
        private async static Task <MessageResource> SendTwilioMessageAsync(string fromPhone, string callbackUrl, List <Uri> attachmentMediaUrls, string twilioNumber, string messageText)
        {
            MessageResource      response;
            CreateMessageOptions createMessageOptions = new CreateMessageOptions(new TwilioTypes.PhoneNumber(twilioNumber))
            {
                From = new TwilioTypes.PhoneNumber(fromPhone),
                Body = messageText
            };

            if (callbackUrl.IsNotNullOrWhiteSpace())
            {
                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment &&
                    !callbackUrl.Contains(".ngrok.io"))
                {
                    createMessageOptions.StatusCallback = null;
                }
                else
                {
                    createMessageOptions.StatusCallback = new Uri(callbackUrl);
                }
            }

            if (attachmentMediaUrls != null && attachmentMediaUrls.Any())
            {
                createMessageOptions.MediaUrl = attachmentMediaUrls;
            }

            response = await MessageResource.CreateAsync(createMessageOptions).ConfigureAwait(false);

            return(response);
        }
Exemplo n.º 8
0
        public static async Task Main(string[] args)
        {
            // pull our account sid, auth token and the phone numbers from the usersecrets.json file
            // in a production app we'd obviously want to store these in a secure spot like our appSettings
            // or environmental variables.
            // see https://www.twilio.com/blog/2018/05/user-secrets-in-a-net-core-console-app.html
            // for more info on user secrets

            var builder = new ConfigurationBuilder();

            builder.AddUserSecrets <Program>();
            var config = builder.Build();

            var accountSid = config["twilio:accountSid"];
            var authToken  = config["twilio:authToken"];
            var fromPhone  = config["app:fromPhone"];
            var toPhone    = config["app:toPhone"];

            TwilioClient.SetRestClient(new ChaosTwilioRestClient(new TwilioRestClient(accountSid, authToken), TimeSpan.FromSeconds(10)));

            var policy = PollyPolicies.TwilioCircuitBreakerWrappedInRetryPolicy;

            var message = await policy.ExecuteAsync(async() => await MessageResource.CreateAsync(
                                                        body: "Coming to you live from a very chaotic world!",
                                                        from: new Twilio.Types.PhoneNumber(fromPhone),
                                                        to: new Twilio.Types.PhoneNumber(toPhone)
                                                        ));

            Console.WriteLine($"Message sent! Sid: {message.Sid}");
            Console.ReadLine();
        }
Exemplo n.º 9
0
        public async Task <SmsResult> SendAsync(App app, string to, string body, string reference,
                                                CancellationToken ct = default)
        {
            try
            {
                var callbackUrl = smsUrl.SmsWebhookUrl(app.Id, integrationId, new Dictionary <string, string>
                {
                    ["reference"]        = reference,
                    ["reference_number"] = to
                });

                var result = await MessageResource.CreateAsync(
                    ConvertPhoneNumber(to), null,
                    ConvertPhoneNumber(phoneNumber), null,
                    body,
                    statusCallback : new Uri(callbackUrl), client : twilioClient);

                if (!string.IsNullOrWhiteSpace(result.ErrorMessage))
                {
                    var errorMessage = string.Format(CultureInfo.CurrentCulture, Texts.Twilio_Error, to, result.ErrorMessage);

                    throw new DomainException(errorMessage);
                }

                return(SmsResult.Sent);
            }
            catch (Exception ex)
            {
                var errorMessage = string.Format(CultureInfo.CurrentCulture, Texts.Twilio_ErrorUnknown, to);

                throw new DomainException(errorMessage, ex);
            }
        }
Exemplo n.º 10
0
 public async Task <MessageResource> SendMessageAsync(string to, string from, string body)
 {
     return(await MessageResource.CreateAsync(
                to : new PhoneNumber(to),
                from : new PhoneNumber(from),
                body : body));
 }
Exemplo n.º 11
0
        public async Task <Response> SendAsync(string receiver, string subject, string message, object data = null)
        {
            var response = new Response()
            {
                Successful = false
            };

            try
            {
                TwilioClient.Init(_option.AccountSID, _option.Token);
                var res = await MessageResource.CreateAsync(
                    to : new PhoneNumber(receiver),
                    from : new PhoneNumber(_option.SendNumber),
                    body : message);

                response = new Response()
                {
                    Successful = true, Message = res.Sid
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.Error   = ex;
            }

            return(response);
        }
Exemplo n.º 12
0
        public Task SendAsync(IdentityMessage message)
        {
            //var accountSid = ConfigurationManager.AppSettings["SMSAccountIdentification"];
            //var authToken = ConfigurationManager.AppSettings["SMSAccountPassword"];
            //var fromNumber = ConfigurationManager.AppSettings["SMSAccountFrom"];

            //TwilioClient.Init(accountSid, authToken);

            //MessageResource result = MessageResource.Create(
            //    new PhoneNumber(message.Destination),
            //    from: new PhoneNumber(fromNumber),
            //    body: message.Body
            //);

            ////Status is one of Queued, Sending, Sent, Failed or null if the number is not valid
            //Trace.TraceInformation(result.Status.ToString());
            ////Twilio doesn't currently have an async API, so return success.
            ///

            TwilioClient.Init(_accountSid, _authToken);
            var result = MessageResource.CreateAsync(
                body: message.Body,
                from: new PhoneNumber(_fromNumber),
                to: new PhoneNumber(message.Destination)
                );

            return(Task.FromResult(result));
        }
Exemplo n.º 13
0
        public async Task SendMemory(string memoryToSend, string fromPhoneNumber, IEnumerable <string> phoneNumbers)
        {
            if (string.IsNullOrEmpty(memoryToSend) ||
                string.IsNullOrEmpty(fromPhoneNumber))
            {
                return;
            }

            var parameterDictionary = await _parameterManagementService.RetrieveParameters(new List <string>
            {
                Constants.TwilioAccountSidKey,
                Constants.TwilioAuthTokenKey,
                Constants.TwilioPhoneNumberKey
            });

            // initialize client
            TwilioClient.Init(parameterDictionary[Constants.TwilioAccountSidKey], parameterDictionary[Constants.TwilioAuthTokenKey]);

            var textTaskList = new List <Task <MessageResource> >();

            // send text(s)
            foreach (var phoneNumber in phoneNumbers)
            {
                var textTask = MessageResource.CreateAsync(
                    body: memoryToSend,
                    from: new Twilio.Types.PhoneNumber(parameterDictionary[Constants.TwilioPhoneNumberKey]),
                    to: new Twilio.Types.PhoneNumber(phoneNumber)
                    );

                textTaskList.Add(textTask);
            }

            // wait until done sending to all numbers
            await Task.WhenAll(textTaskList);
        }
Exemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pendingNotifications"></param>
        /// <param name="log"></param>
        public static void SendNotifications(List <NotificationModel> pendingNotifications, TraceWriter log)
        {
            TwilioClient.Init(ConfigurationManager.TwilioAccountId, ConfigurationManager.TwilioAccountSecret);

            var messageIds = new List <string>();

            foreach (var pendingNotification in pendingNotifications)
            {
                var responseUri         = string.Format(ConfigurationManager.NotificationResponseRoute, pendingNotification.NotificationId, 2);
                var shortenRequestModel = new ShortenRequestModel
                {
                    LongUrl = responseUri,
                    GroupId = ConfigurationManager.BitlyGroupId
                };
                log.Info($"Response Uri : {responseUri}");
                var shortenResponse = RestClient.PostAsync <ShortenResponseModel>(Constants.Common.BitlyHostName,
                                                                                  "/v4/shorten",
                                                                                  ConfigurationManager.BitlyKey,
                                                                                  JsonConvert.SerializeObject(shortenRequestModel)).GetAwaiter().GetResult();

                log.Info($"Shorten Uri : {shortenResponse?.Link}");
                var messageBody = $"{pendingNotification.Message} \n\n Please click : {(shortenResponse != null ? shortenResponse.Link : responseUri)} to optout.";

                var messageId = MessageResource.CreateAsync(body: messageBody,
                                                            from: new Twilio.Types.PhoneNumber(ConfigurationManager.TwilioPhoneNumber),
                                                            to: new Twilio.Types.PhoneNumber(pendingNotification.PhoneNumber)).GetAwaiter().GetResult();
            }
        }
Exemplo n.º 15
0
        public static async Task SendSms(string msg, string to)
        {
            try
            {
                if (to == Number)
                {
                    return;
                }
                // Find your Account Sid and Token at twilio.com/console
                TwilioClient.Init(accountSid, authToken);

                var message = await MessageResource.CreateAsync(
                    body : "SYSTEM:" + msg,
                    @from : new PhoneNumber(Number),
                    to : new PhoneNumber(to)
                    );

                Console.WriteLine(message.Sid);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error sending sms...");
                Console.WriteLine(e);
            }
        }
Exemplo n.º 16
0
        public async Task <bool> SendSms(string toPhoneNumber, string message, string fromPhoneNumber = null)
        {
            var success = false;

            try
            {
                var text = await MessageResource.CreateAsync(
                    body : message,
                    from : new Twilio.Types.PhoneNumber(fromPhoneNumber ?? _TwilioSettings.Value.PhoneNumber),
                    to : new Twilio.Types.PhoneNumber(toPhoneNumber)
                    );

                if (text.Status != MessageResource.StatusEnum.Failed &&
                    text.Status != MessageResource.StatusEnum.Undelivered)
                {
                    success = true;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            return(success);
        }
        public async Task SendMessageAsync(string to, string body)
        {
            string sender = _configuration["Twilio:Sender"];

            SMSLog log = new SMSLog
            {
                Sender    = sender,
                Recipient = to,
                Text      = body,
                CreatedAt = DateTime.UtcNow
            };

            try
            {
                var message = await MessageResource.CreateAsync(
                    to : new PhoneNumber(to),
                    from : sender,
                    body : body);

                log.Status = SendingStatus.Success;
            }
            catch (ApiException e)
            {
                log.Status = SendingStatus.Failed;

                _logger.LogError($"Twilio Error {e.Code}({e.Message}) - {e.MoreInfo}");
                throw new SystemException(e.Message);
            }
            finally
            {
                _unitOfWork.Repository <SMSLog>().Insert(log);
                _unitOfWork.SaveChanges();
            }
        }
Exemplo n.º 18
0
        public async Task <bool> EnviarMensagemNotificacaoAsync(NotificacaoMensagemModel mensagem)
        {
            try
            {
                TwilioClient.Init(_twilioConfig.TwilioAccountSID,
                                  _twilioConfig.TwilioAuthToken);

                var msgResource = await MessageResource.CreateAsync(
                    from : new PhoneNumber($"whatsapp:{_twilioConfig.TwilioWhatsappNumber}"),
                    to : new PhoneNumber($"whatsapp:{TwilioHelper.FormatarNumeroNoPadraoDoTwilio(mensagem.Para)}"),
                    body : mensagem.Conteudo);

                if (msgResource.Status == MessageResource.StatusEnum.Failed)
                {
                    throw new Exception($"{msgResource.ErrorCode} - {msgResource.ErrorMessage}");
                }

                _logger.LogInformation($"Mensagem enviada para {msgResource.To} em {DateTime.Now}");
                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(false);
            }
        }
Exemplo n.º 19
0
        private async Task <string> NotifyRaffleWinner(RaffleEntry entry)
        {
            var msg = await MessageResource.FetchAsync(
                entry.MessageSid,
                _accountSid);

            var response = await MessageResource.CreateAsync(
                msg.From,
                from : msg.To,
                body : @"You've won the latest raffle. Visit the Twilio booth to pick up your prize. If you can't email [email protected]");

            _notificationSid = response.Sid;

            using (var httpClient = new HttpClient())
            {
                var data = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("winner", msg.From.ToString()),
                    new KeyValuePair <string, string>("raffleSid", LatestRaffle.Sid),
                    new KeyValuePair <string, string>("prize", LatestRaffle.Prize.Name)
                });

                var httpResponse = await httpClient.PostAsync("https://hooks.zapier.com/hooks/catch/3191324/o3o1bt1/", data);

                httpResponse.EnsureSuccessStatusCode();
            }

            return(_notificationSid);
        }
Exemplo n.º 20
0
        /// <summary> Send SMS(Twilio API) to mobile number with verification code,  and verification link to verify the phone number directly from mobile</summary>
        /// <returns>
        /// true if sent successfully, else return false </returns>
        public async Task <bool> SmsSender(string phoneNumber, string UserName, string token, string link)
        {
            try
            {
                // Convert the Number to be valid in Twilio API
                var ToPhoneNumber = ConvertNumberToTwilioFormat(phoneNumber);

                // if phone number is valid
                if (!string.IsNullOrEmpty(ToPhoneNumber))
                {
                    // Initialize the Twilio client
                    TwilioClient.Init(_SendSmsAccountSID, _SendSmsAuthToken);

                    // Send a new outgoing SMS by POSTing to the Messages resource
                    await MessageResource.CreateAsync(
                        // the phone number SMS API Twilio has a special format, it must not contain 00, for that change it to
                        // From number, must be an SMS-enabled Twilio number
                        from : new PhoneNumber(_SendSmsNumber),
                        to : new PhoneNumber(ToPhoneNumber),
                        // Message content
                        body : $"Hey {UserName} the tolken: {token} or click on this link: \n {link}"
                        );

                    return(true);
                }
                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 21
0
        public async Task <MessageResource> SendMessage(string from, string to, string body)
        {
            var             toPhoneNumber   = new PhoneNumber(to);
            MessageResource messageResource = await MessageResource.CreateAsync(toPhoneNumber, from : new PhoneNumber(from), body : body, client : this._client);

            return(messageResource);
        }
Exemplo n.º 22
0
        public async Task <bool> SendSmsAsync(SMSTextModel model)
        {
            if (string.IsNullOrWhiteSpace(model.From))
            {
                model.From = _config["Twilio:DefaultFrom"];
            }
            TwilioClient.Init(_accountSid, _authToken);
            try
            {
                await MessageResource.CreateAsync
                (
                    body :
                    model.Message,
                    from :
                    new Twilio.Types.PhoneNumber(model.From),
                    to :
                    new Twilio.Types.PhoneNumber(model.To)
                );

                _logger.LogInformation($"Sent an SMS message to {model.To} from {model.From}.");
            }
            catch (System.Exception)
            {
                _logger.LogError($"Failed to send an SMS message to {model.To} using phone number {model.From}.");
                return(false);
            }
            return(true);
        }
        public override async Task SendAsync(string to, string body)
        {
            TwilioClient.Init(SmsProviderInfo.Sid, SmsProviderInfo.Token);

            var destination = new PhoneNumber(to);
            await MessageResource.CreateAsync(to, from : new PhoneNumber(SmsProviderInfo.From), body : body);
        }
Exemplo n.º 24
0
        }                                    // set only via Secret Manager

        public async Task SendSmsAsync(string number, string message)
        {
            await MessageResource.CreateAsync(
                to : new PhoneNumber(number),
                from : new PhoneNumber(this.Options.From),
                body : message);
        }
Exemplo n.º 25
0
        public async Task <SmsServiceResponseDTO> SendVerificationCode(string phoneNumber, string code)
        {
            if (phoneNumber != null && code != null)
            {
                TwilioClient.Init(accountSid, authToken);
                await MessageResource.CreateAsync(
                    body : code,
                    from : new Twilio.Types.PhoneNumber("+15017122661"),
                    to : new Twilio.Types.PhoneNumber($"{phoneNumber}"));

                return(await Task.FromResult(new SmsServiceResponseDTO
                {
                    StatusCode = 200,
                    Message = "Сообщения успешно отправлено"
                }));
            }
            else
            {
                return(await Task.FromResult(new SmsServiceResponseDTO
                {
                    StatusCode = 400,
                    Message = "Сообщение не было отправлено"
                }));
            }
        }
Exemplo n.º 26
0
 private Task <MessageResource> SendInternalAsync(string phone, string message)
 {
     return(MessageResource.CreateAsync(
                to: new PhoneNumber(phone),
                from: new PhoneNumber(_configuration["TwilioPhoneNumber"]),
                body: message));
 }
        public Task SendSmsAsync(string number, string message)
        {
            // Plug in your SMS service here to send a text message.
            // Your Account SID from twilio.com/console
            //var accountSid = Options.SMSAccountIdentification;
            // Your Auth Token from twilio.com/console
            //var authToken = Options.SMSAccountPassword;

            //TwilioClient.SetUsername(accountSid);
            //TwilioClient.SetPassword(authToken);
            //TwilioClient.Init(accountSid, authToken);

            TwilioClient.Init(_accountSid, _authToken);

            return(MessageResource.CreateAsync(
                       to: new PhoneNumber("+84" + number),
                       from: new PhoneNumber(_sMSAccountFrom),
                       body: message));

            /*
             * return MessageResource.CreateAsync(
             * to: new PhoneNumber("+84" + number),
             * from: new PhoneNumber(Options.SMSAccountFrom),
             * body: message);
             */
        }
Exemplo n.º 28
0
        private async Task SendSms(string description, List <EmergencySkillset> requiredEmergencySkillsets)
        {
            const string accountSid      = "21342135215321351"; // these are just random numbers
            const string authToken       = "1251809581058105";  // these are just random numbers
            const string fromPhoneNumber = "208510538210";      // these are just random numbers
            var          skillsets       = new List <Skillset>();

            foreach (var requiredEmergencySkillset in requiredEmergencySkillsets)
            {
                skillsets.Add(requiredEmergencySkillset.Skillset);
            }
            var users = this.databaseContext.UserSkillsets
                        .Where(s => skillsets.Contains(s.Skillset))
                        .Select(s => s.User)
                        .ToList();

            foreach (var user in users)
            {
                TwilioClient.Init(accountSid, authToken);
                var message = await MessageResource.CreateAsync(
                    body : description,
                    from : new Twilio.Types.PhoneNumber(fromPhoneNumber),
                    to : new Twilio.Types.PhoneNumber(user.MobilPhone)
                    );
            }
            return;
        }
        public async void SendAsync <T>(Func <string, T> options) where T : class
        {
            try
            {
                if (options == null)
                {
                    throw new ArgumentException(nameof(options));
                }
                TwilioClient.Init(_configuration.AccountSid, _configuration.AuthToken);
                var code  = _verificationCode.Generate(out var result);
                var param = options.Invoke(code);
                if (!(param is CreateMessageOptions))
                {
                    return;
                }
                var msgOption = param as CreateMessageOptions;
                var message   = await MessageResource.CreateAsync(msgOption);

                MessageSentHandler?.Invoke(result, message);
            }
            catch (Exception ex)
            {
                VerificationCodoeExceptionHandler?.Invoke(ex);
            }
        }
Exemplo n.º 30
0
        public async Task <bool> SendSms(MessageViewModel vm)
        {
            var accountSid = _twilioOptions.AccountSid;
            var authToken  = _twilioOptions.AuthToken;

            TwilioClient.Init(accountSid, authToken);
            var phoneNumber = new PhoneNumber(vm.To);
            var message     = "Want some Chuck Norris?  Please respond with one of the following categories: Random, " + string.Join(", ", Enum.GetNames(typeof(JokeCategory)));


            try
            {
                await MessageResource.CreateAsync(
                    to : phoneNumber,
                    from : new PhoneNumber(_twilioOptions.PhoneNumber),
                    body : message);

                return(true);
            }
            catch (Exception exception)
            {
                LogHelper.Error($"MessageController:Post - CreateAsync Exceptioned with {exception.Message}");
            }

            return(false);
        }