如何在 C# 机器人框架中使用 javascript disable/enable 聊天框内的附件按钮

how to disable/enable attachment button inside chatbox using javascript in C# bot framework

我已经根据机器人消息使用此 tutorial. I created a chatbot using this javascript. I need to Enable/Disable the attachment button 创建了一个 Microsoft 机器人框架。我的条件是当机器人向用户发送消息以提交附件时启用附件按钮。

Html:

<div id="webchat" role="main"></div>

脚本:

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

<script>
  // style properties
    var styleOptions = {
        botAvatarInitials: 'Bot',
        bubbleBackground: 'rgba(0, 0, 255, .1)',
        bubbleFromUserBackground: 'rgba(0, 255, 0, .1)',
        userAvatarInitials: 'User',
        hideUploadButton: true,  //To hide attachment button
        backgroundColor: "Grey"
    };

   // chatbot 
     window.WebChat.renderWebChat(
     {
        directLine: window.WebChat.createDirectLine({
        token: 'access token'
        }),
        userID: 'YOUR_USER_ID',
        username: 'Web Chat User',
        locale: 'en-US',
        styleOptions
      },
       document.getElementById('webchat'),
    );
    
</script>

您可以通过过滤通过网络聊天商店的活动来完成此操作。正如您在下面看到的,我首先查询附件按钮的元素 - 有两个,一个隐藏的输入字段和按钮。

接下来,我检查 activity 是否有附件,以及该附件的 contentType 是否匹配“application/vnd.microsoft.card.adaptive”。如果是,则启用附件输入和按钮。否则,所有其他活动都禁用附件输入和按钮。

整个 if 语句被超时包裹。这是必要的,因为对附件 contentType 的检查将在商店完成渲染 activity 之前完成,从而导致按钮永久禁用。将超时设置为 ~300 毫秒允许商店完成其呈现操作。您可以调整超时,但少于 ~50 毫秒,上述情况将开始发生。超过 ~500 毫秒,用户就会开始注意到它。

请注意,隔离输入和按钮元素依赖于 Web Chat 定义的属性和 类。虽然这不太可能成为问题,但这些定义可能会在未来的版本中发生变化,从而导致重大更改并需要更新您的代码。

const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => action => {
  if ( action.type === 'DIRECT_LINE/INCOMING_ACTIVITY' ) {
    const activity = action.payload?.activity;

    const attachmentBtn = document.querySelector( '[title="Upload file"]' );
    const attachmentInput = document.querySelector( '.webchat__upload-button--file-input' );
    setTimeout(() => {
      if ( activity && activity.attachments) {
        if (activity.attachments[0].contentType === 'application/vnd.microsoft.card.adaptive' ) {
          attachmentBtn.disabled = false;
          attachmentBtn.disabled = false;
        }
      } else {
        attachmentBtn.disabled = true;
        attachmentInput.disabled = true;
      }
    }, 300);
  };
  next( action );
} );

[...]

window.WebChat.renderWebChat(
  {
    directLine: directLine,
    store: store,
  },
  document.getElementById( 'webchat' )
);
document.querySelector( '#webchat > *' ).focus();

希望得到帮助!