Search code examples
c#smstwiliobotframeworkproactive

Send sms notify message to user when his/her account locked, how can i do that in C#


Bot Info SDK : C# Active Channels: SMS (Twilio) Bot version: v4.4.3

Issue Description: I'd like to be able to send proactive messages through SMS messages. When a user's account locked, i have that person's phone number, and i want to send a notify message like "your account is locked, please do something." Is this possible? i checked the documentation about proactive message, which is get the "ConversationReference" through "activity", i don't know with the phone number, can i create a "ConversationReference" object, and how to tell bot about the phone number through notify controller.

Thank you.


Solution

  • Fortunately, unlike most channels, you can construct a conversation reference without having to have the user message the bot first since you know the user's number and you have the bot's number. Take a look at the code snippet below. You can send a proactive message to a phone number by sending a get request to http://localhost:3978/api/notify/+1##########

    using Microsoft.Bot.Connector.Authentication;
    
    [HttpGet("{number}")]
    public async Task<IActionResult> Get(string number)
    {
        MicrosoftAppCredentials.TrustServiceUrl("https://sms.botframework.com/"); 
    
        var conversationReference = new ConversationReference {
            User = new ChannelAccount { Id = number },
            Bot = new ChannelAccount { Id = "<BOT_NUMBER>" },
            Conversation = new ConversationAccount { Id = number },
            ServiceUrl = "https://sms.botframework.com/"
        };
    
        await ((BotAdapter)_adapter).ContinueConversationAsync(_appId, conversationReference, BotCallback, default(CancellationToken));
    
        // Let the caller know proactive messages have been sent
        return new ContentResult()
        {
            Content = "<html><body><h1>Proactive messages have been sent.</h1></body></html>",
            ContentType = "text/html",
            StatusCode = (int)HttpStatusCode.OK,
        };
    }
    
    private async Task BotCallback(ITurnContext turnContext, CancellationToken cancellationToken)
    {
        await turnContext.SendActivityAsync("proactive hello");
    }
    

    For more details on sending proactive messages, take a look at the Proactive Message sample.

    Hope this helps.