将查询字符串参数传递给直线通道Bot Framework

时间:2018-09-04 06:53:45

标签: c# botframework

我使用Bot Builder SDK 4.x创建了一个漫游器。我可以使用仿真器和消息终点public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.logout_confirmation, container, false); mLogout = view.findViewById(R.id.heading); mPleaseWait = view.findViewById(R.id.tvPleaseWait); mProgressBar = view.findViewById(R.id.progressBar); btnLogout = view.findViewById(R.id.btnLogout); mPleaseWait.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE); mAuth = FirebaseAuth.getInstance(); signOut(); setupFirebaseAuth(); return view; } /* //This is the button to sign out. Then system will read next the `setupFirebaseAuth`. So if mAuthListener knows there is no user signed it so it will navigate to the LoginFragment */ public void signOut(){ btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mAuth.signOut(); //Progress Bar and TextView mPleaseWait.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.VISIBLE); Log.d(TAG, "onClick: attempting to log out."); } }); } /* --------------------------------------Firebase------------------------------------------- */ private void setupFirebaseAuth(){ Log.d(TAG, "setupFirebaseAuth: setting up firebase auth."); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); //checking if the user is logged in or not if (user != null){ //User is signed in Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid()); }else { // User is signed out Log.d(TAG, "onAuthStateChanged: signed_out"); //After logging out, it will navigate to LoginFragment FragmentTransaction fr = getFragmentManager().beginTransaction(); fr.replace(R.id.container2, new LoginFragment()); fr.commit(); } } }; } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override public void onStop() { super.onStop(); if (mAuthListener != null){ mAuth.removeAuthStateListener(mAuthListener); } } 访问该机器人。我还将一些查询字符串参数传递给消息传递终结点,例如http://localhost:3978/api/messages,我可以在我的机器人启动过程中访问它。

http://localhost:3978/api/messages?botid=HRbot

将漫游器部署到Azure之后,我希望我的客户端使用消息终结点并传递自己的查询字符串参数。由于该机器人需要嵌入到网页中,因此我可以使用Web聊天频道和脚本,也可以使用Direct line频道。他们两个都使用秘密密钥,没有端点。因此,我看不到任何将查询字符串参数传递给消息端点的选项。

我看到我们可以使用网络聊天JavaScript SDK将一些public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles() .UseStaticFiles() .Use(async (context, next) => { _config["BotId"] = context.Request.Query["botid"]; await next.Invoke(); }) .UseBotFramework(); } 作为一些参数传递给Direct line通道,如下所示。

token

我不确定如何为要使用不同查询字符串参数使用该API的每个客户端使用bot服务消息API。

对此有任何帮助吗?请让我知道是否可以澄清更多信息。

2 个答案:

答案 0 :(得分:3)

  

对于每个希望使用不同查询字符串参数使用该API的客户端,我如何使用我的bot服务消息API。

Embeddable web chat control不会直接向bot应用程序终结点发出请求,而是使用DirectLine API。

要从Web聊天客户端向机器人应用程序传递其他信息,可以在启动BotChat时在user: { id: user_id, param: '{value_here}' }属性中指定其他参数。

var userinfo = { id: 'You', userparam: 'val11' };

BotChat.App({
    botConnection: botConnection,
    user: userinfo,
    bot: { id: 'xxxbot' },
    resize: 'detect'
}, document.getElementById("bot"));

然后您可以获取在机器人应用程序中通过Activity.From.Properties传递的值。

if (context.Activity.Type == ActivityTypes.Message)
{
    var uparam = context.Activity.From.Properties["userparam"].ToString();

    // Your code logic here   


    // Echo back to the user whatever they typed.
    await context.SendActivity($"Turn {state.TurnCount}: You sent '{context.Activity.Text}; Parameter you passed is {uparam}'");
}

测试结果:

enter image description here

更新:

  

我希望参数在用户发送任何数据之前可用。

您可以使用the backchannel mechanism发送event活动,并指定from属性以传递附加参数,如下所示:

botConnection.postActivity({
    type: 'event',
    from: userinfo,
}).subscribe(function (id) { console.log('you send an event activity'); });

在bot应用程序中:

else if (context.Activity.Type == ActivityTypes.Event)
{
    var uparam = context.Activity.From.Properties["userparam"].ToString();
    await context.SendActivity($"Parameter that you sent is '{uparam}'");
}

测试结果:

enter image description here

答案 1 :(得分:0)

我对Fei Han给出的两个选项都遇到了问题,但它们对我没有用。经过一段时间的研究,对我有用的是他提供的后端解决方案的组合,而对于客户端,我不得不使用此处给出的示例-https://github.com/Microsoft/BotFramework-WebChat/tree/master/samples/15.d.backchannel-send-welcome-event

所以最后,我有了这两段代码:

C#:

else if (turnContext.Activity.Type == ActivityTypes.Event)
{
      await turnContext.SendActivityAsync($"Received event");
      await turnContext.SendActivityAsync($"{turnContext.Activity.Name} - {turnContext.Activity.Value?.ToString()}");
}

和客户端:

<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>

<script>

    token = "your-token-here";

    (async function () {
        const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
            if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
                dispatch({
                    type: 'WEB_CHAT/SEND_EVENT',
                    payload: {
                    name: 'start-chat',
                        value: {
                            "example_id": "12345",
                            "example_array": ["123", "456"]
                        }
                      }
            });
        }
        return next(action);
    });

    window.WebChat.renderWebChat({
        directLine: window.WebChat.createDirectLine({ token }),
        store
    }, document.getElementById('webchat'));

    document.querySelector('#webchat > *').focus();
      }) ().catch(err => console.error(err));

</script>