Начиная диалог с проактивного сообщения - PullRequest
0 голосов
/ 30 мая 2019

Я новичок в Bot Framework, поэтому прошу прощения, если это просто, но я пытаюсь отправить Проактивное сообщение пользователю, чтобы начать разговор. Я использую приведенный ниже пример:

https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/16.proactive-messages

Это прекрасно работает, но я хотел бы начать с этого момента диалог, а не просто отослать назад некоторый текст пользователю. Это возможно? Вот код из образца

[Route("api/notify")]
[ApiController]
public class NotifyController : ControllerBase
{
    private readonly IBotFrameworkHttpAdapter _adapter;
    private readonly string _appId;
    private readonly ConcurrentDictionary<string, ConversationReference> _conversationReferences;

    private readonly BotState _userState;
    private readonly BotState _conversationState;

    public NotifyController(IBotFrameworkHttpAdapter adapter,
        ICredentialProvider credentials,
        ConcurrentDictionary<string, ConversationReference> conversationReferences,
        ConversationState conversationState,
        UserState userState
        )
    {
        _adapter = adapter;
        _conversationReferences = conversationReferences;
        _appId = ((SimpleCredentialProvider)credentials).AppId;

        // If the channel is the Emulator, and authentication is not in use,
        // the AppId will be null.  We generate a random AppId for this case only.
        // This is not required for production, since the AppId will have a value.
        if (string.IsNullOrEmpty(_appId))
        {
            _appId = Guid.NewGuid().ToString(); //if no AppId, use a random Guid
        }


        _conversationState = conversationState;
        _userState = userState;
    }

    [HttpGet("{number}")]
    public async Task<IActionResult> Get(string number)
    {
        foreach (var conversationReference in _conversationReferences.Values)
        {
            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)
    {
        //This works from the sample:
        await turnContext.SendActivityAsync("Starting proactive message bot call back");

        //However I would like to do something like this (pseudo code):
        //var MyDialog = new ConfirmAppointmentDialog();
        //await turnContext.StartDialog(MyDialog);
    }
}

1 Ответ

1 голос
/ 04 июня 2019

В итоге я понял это - вот что я сделал:

В моем NotifyController я начинаю разговор следующим образом

  [HttpGet("{number}")]
        public async Task<IActionResult> Get(string number)
        {

            //For Twillio Channel
            MicrosoftAppCredentials.TrustServiceUrl("https://sms.botframework.com/");

            var NewConversation = new ConversationReference
            {
                User = new ChannelAccount { Id = $"+1{number}" },
                Bot = new ChannelAccount { Id = "+1YOURPHONENUMBERHERE" },
                Conversation = new ConversationAccount { Id = $"+1{number}" },
                ChannelId = "sms",
                ServiceUrl = "https://sms.botframework.com/"
            };

            try
            {
                BotAdapter ba = (BotAdapter)_HttpAdapter;
                await ((BotAdapter)_HttpAdapter).ContinueConversationAsync(_AppId, NewConversation, BotCallback, default(CancellationToken));
            }
            catch (Exception ex)
            {
                this._Logger.LogError(ex.Message);
            }


            // 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,
            };
        }

Затем в BotCallback я запускаю диалог:

private async Task BotCallback(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            try
            {
                var conversationStateAccessors = _ConversationState.CreateProperty<DialogState>(nameof(DialogState));

                var dialogSet = new DialogSet(conversationStateAccessors);
                dialogSet.Add(this._Dialog);

                var dialogContext = await dialogSet.CreateContextAsync(turnContext, cancellationToken);
                var results = await dialogContext.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dialogContext.BeginDialogAsync(_Dialog.Id, null, cancellationToken);
                    await _ConversationState.SaveChangesAsync(dialogContext.Context, false, cancellationToken);
                }
                else
                    await turnContext.SendActivityAsync("Starting proactive message bot call back");
            }
            catch (Exception ex)
            {
                this._Logger.LogError(ex.Message);
            }
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...