Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用web应用程序通过bot主动发送消息 解决了的_C#_Botframework_Microsoft Teams - Fatal编程技术网

C# 使用web应用程序通过bot主动发送消息 解决了的

C# 使用web应用程序通过bot主动发送消息 解决了的,c#,botframework,microsoft-teams,C#,Botframework,Microsoft Teams,多亏了用户MarkMoose,我才意识到我的数据库表没有存储完整的ID。 未来的调试器:如果这不能帮助您解决问题,请查看我与MarkMoose的对话,他们指导我完成了非常有用的故障排除步骤 我正在尝试使用Microsoft bot SDK版本4.0创建托管在Azure上的Microsoft Team bot 流程如下 Web应用程序警报触发器。向bot发送POST请求,其中包含(从用户以前的消息中收集的所有数据) 收件人ID(收件人用户的) (收件人用户的)姓名 来自ID(我的机器人) 来自名

多亏了用户MarkMoose,我才意识到我的数据库表没有存储完整的ID。 未来的调试器:如果这不能帮助您解决问题,请查看我与MarkMoose的对话,他们指导我完成了非常有用的故障排除步骤

我正在尝试使用Microsoft bot SDK版本4.0创建托管在Azure上的Microsoft Team bot

流程如下

  • Web应用程序警报触发器。向bot发送POST请求,其中包含(从用户以前的消息中收集的所有数据)

    • 收件人ID(收件人用户的)
    • (收件人用户的)姓名
    • 来自ID(我的机器人)
    • 来自名称(我的机器人)
    • 通道ID
    • 会话ID
    • (收件人用户的)服务URL
  • Bot从JSON中提取信息,形成新的消息活动

  • Bot向用户发送活动
  • 问题:当bot试图使用上面列出的凭据创建一个
    ConversationAccount
    对象时,它会抛出以下错误:

    捕获到异常:Microsoft.Bot.Schema.ErrorResponseException:操作返回无效的状态代码“BadRequest”

    下面是代码的相关部分

    请特别注意以下几行:

    var account = new MicrosoftAppCredentials(botCreds["App ID"], botCreds["App Password"]);
    var jwtToken = await account.GetTokenAsync();
    ConnectorClient connector = new ConnectorClient(new System.Uri(serviceURL), account);
    
    当我找到其他人对我的问题的解决方案时,这两条线略有不同。在我当前使用的代码版本中。我也尝试过他创建的DelegatingHandler类,但它抛出了相同的错误

    /// <summary>
    /// Sends a message to a user or group chat.
    /// </summary>
    /// <param name="forwardContext">JSON object containing credentials for destination chat.</param>
    /// <param name="messageToSend">The message to forward.</param>
    /// <returns></returns>
    private async Task ForwardMessage(JToken forwardContext, string messageToSend)
    {
        // Collect data from JSON input
        var restCmd = forwardContext;
        var toId = (string) restCmd["toId"];
        var toName = (string) restCmd["toName"];
        var fromId = (string) restCmd["fromId"];
        var fromName = (string) restCmd["fromName"];
        var channelId = (string) restCmd["channel"];
        var serviceURL = (string) restCmd["serviceURL"];
        var conversationId = (string) restCmd["conversation"];
        var cred_str = $@"toId: {toId}
        toName: {toName}
        fromId: {fromId}
        fromName: {fromName}
        channelId: {channelId}
        serviceURL: {serviceURL}
        conversationId: {conversationId}";
        _logger.LogInformation(cred_str);
        _logger.LogInformation($"Forwarding the following message to {toName}: {messageToSend}");
    
        Dictionary<string, string> botCreds = GetBotCredentials();
    
        // Create relevant accounts
        ChannelAccount userAccount = new ChannelAccount(name: toName, id: toId);
        ChannelAccount botAccount = new ChannelAccount(name: fromName, id: fromId);
        if (!MicrosoftAppCredentials.IsTrustedServiceUrl(serviceURL))
        {
            _logger.LogInformation($"Adding to trusted service urls: {serviceURL}");
    
            // Register the service URL as trusted
            MicrosoftAppCredentials.TrustServiceUrl(serviceURL);
        }
        MicrosoftAppCredentials.TrustServiceUrl(serviceURL);
        var account = new MicrosoftAppCredentials(botCreds["App ID"], botCreds["App Password"]);
        var jwtToken = await account.GetTokenAsync();
        ConnectorClient connector = new ConnectorClient(new System.Uri(serviceURL), account);
    
        // Create a new message activity
        IMessageActivity message = Activity.CreateMessageActivity();
    
        conversationId = (
            await connector
            .Conversations
            .CreateDirectConversationAsync(botAccount, userAccount)).Id;
    
        // Set relevant message details
        message.From = botAccount;
        message.Recipient = userAccount;
        message.Text = messageToSend;
        message.Locale = "en-Us";
        message.ChannelId = channelId;
    
        // Create a new converstaion and add it to the message.
        message.Conversation = new ConversationAccount(id: conversationId);
        await connector.Conversations.SendToConversationAsync((Activity) message);
    }
    
    //
    ///向用户或群聊天室发送消息。
    /// 
    ///包含目标聊天的凭据的JSON对象。
    ///要转发的消息。
    /// 
    专用异步任务ForwardMessage(JToken forwardContext,string messageToSend)
    {
    //从JSON输入收集数据
    var restCmd=forwardContext;
    变量toId=(字符串)restCmd[“toId”];
    var toName=(string)restCmd[“toName”];
    var fromId=(string)restCmd[“fromId”];
    var fromName=(string)restCmd[“fromName”];
    var channelId=(字符串)restCmd[“channel”];
    var serviceURL=(字符串)restCmd[“serviceURL”];
    var conversationId=(字符串)restCmd[“conversation”];
    var cred_str=$@“toId:{toId}
    toName:{toName}
    fromId:{fromId}
    fromName:{fromName}
    channelId:{channelId}
    serviceURL:{serviceURL}
    会话ID:{conversationId}”;
    _登录信息(cred_str);
    _logger.LogInformation($“将以下消息转发到{toName}:{messageToSend}”);
    字典botCreds=GetBotCredentials();
    //创建相关帐户
    ChannelAccount userAccount=新的ChannelAccount(名称:toName,id:toId);
    ChannelAccount botAccount=新的ChannelAccount(名称:fromName,id:fromId);
    如果(!MicrosoftAppCredentials.IsTrustedServiceUrl(serviceURL))
    {
    _logger.LogInformation($“添加到受信任的服务URL:{serviceURL}”);
    //将服务URL注册为受信任的
    MicrosoftAppCredentials.TrustServiceUrl(serviceURL);
    }
    MicrosoftAppCredentials.TrustServiceUrl(serviceURL);
    var帐户=新的MicrosoftAppCredentials(botCreds[“应用程序ID”]、botCreds[“应用程序密码”]);
    var jwtToken=await account.GetTokenAsync();
    ConnectorClient连接器=新的ConnectorClient(新的System.Uri(serviceURL),帐户);
    //创建新的消息活动
    IMessageActivity message=Activity.CreateMessageActivity();
    会话ID=(
    等待连接器
    .对话
    .CreateDirectConversationAsync(botAccount,userAccount)).Id;
    //设置相关的消息详细信息
    message.From=botAccount;
    message.Recipient=userAccount;
    message.Text=messageToSend;
    message.Locale=“en-Us”;
    message.ChannelId=ChannelId;
    //创建一个新会话并将其添加到消息中。
    message.Conversation=新的ConversationAccount(id:conversationId);
    等待connector.Conversations.SendToConversationAsync((活动)消息);
    }
    
    这是我收集上述信息的代码。当用户第一次与bot交互时,将调用此函数

    /// <summary>
        /// Called only when the !setup command is sent to the bot.
        /// Updates the chats info in the DB.
        /// </summary>
        /// <param name="activity">Activity of the message the "!setup" command was sent in.</param>
        /// <returns>True if the update query executed fine.</returns>
        private bool SetupCommand(Activity activity)
        {
            // Connect to the database
            this.database = new DBConnection(serverIP, databaseName, userName, password, _logger);
            this.database.Connect();
            var tableName = "ms_teams_chats";
    
            // Data gathered from Activity for database.
    
            // User ID
            string toId = activity.From.Id;
    
            // User Name
            string toName = activity.From.Name;
    
            // Bot ID
            string fromId = activity.Recipient.Id;
    
            // Bot Name
            string fromName = activity.Recipient.Name;
    
            // Users service URL
            string serviceURL = activity.ServiceUrl;
    
            // The platform the message came from. Example: 'skype'
            string channelId = activity.ChannelId;
            string conversationID = activity.Conversation.Id;
    
            string conversationName = activity.Conversation.Name;
            bool isGroupChat = activity.Conversation.IsGroup ?? false;
    
            string upsertQuery = string.Empty;
            upsertQuery = $@"
                INSERT INTO {tableName} 
                    (user_id, user_name, assoc_bot_id, assoc_bot_name, service_url, channel_id, conversation_id, is_group_chat)
                VALUES (
                    '{toId}', '{toName}', '{fromId}', '{fromName}', '{serviceURL}', '{channelId}', '{conversationID}', {isGroupChat}
                )
                ON DUPLICATE KEY UPDATE
                user_id = '{toId}',
                user_name = '{toName}',
                assoc_bot_id = '{fromId}',
                assoc_bot_name = '{fromName}',
                service_url = '{serviceURL}',
                channel_id = '{channelId}',
                conversation_id = '{conversationID}',
                is_group_chat = {isGroupChat}
            ";
            try
            {
                this.database.ExecuteNonQuery(upsertQuery);
            }
            catch (System.Exception e)
            {
                _logger.LogError($"Could not update users information. \nError:{e.ToString()}");
                return false;
            }
    
            return true;
        }
    
    //
    ///只有当电话响的时候才打电话!安装命令被发送到bot。
    ///更新数据库中的聊天信息。
    /// 
    ///发送了“!setup”命令的消息的活动。
    ///如果更新查询执行良好,则为True。
    专用布尔设置命令(活动)
    {
    //连接到数据库
    this.database=新的数据库连接(serverIP、数据库名、用户名、密码、\u记录器);
    这是.database.Connect();
    var tableName=“ms\u teams\u chats”;
    //从数据库的活动中收集的数据。
    //用户ID
    字符串toId=activity.From.Id;
    //用户名
    字符串toName=activity.From.Name;
    //机器人ID
    string fromId=activity.Recipient.Id;
    //机器人名称
    string fromName=activity.Recipient.Name;
    //用户服务URL
    字符串serviceURL=activity.serviceURL;
    //消息来自的平台。例如:“skype”
    字符串channelId=activity.channelId;
    字符串conversationID=activity.Conversation.Id;
    字符串conversationName=activity.Conversation.Name;
    bool isGroupChat=activity.Conversation.IsGroup??false;
    string upsertQuery=string.Empty;
    upsertQuery=$@”
    插入到{tableName}
    (用户id、用户名称、助理机器人id、助理机器人名称、服务url、频道id、对话id、是群组聊天)
    价值观(
    {toId}、{toName}、{fromId}、{fromName}、{serviceURL}、{channelId}、{conversationID}、{isGroupChat}
    )
    关于重复密钥更新
    用户_id='{toId}',
    用户名=“{toName}”,
    assoc_bot_id='{fromId}',
    assoc_bot_name='{fromName}',
    服务url='{serviceURL}',
    
    private static async Task SendProActiveMessgae()private async Task ForwardMessage(JToken forwardContext, string messageToSend)
    {
        // Collect data from JSON input
        var restCmd = forwardContext;
        var toId = (string) restCmd["toId"];
        var toName = (string) restCmd["toName"];
        var fromId = (string) restCmd["fromId"];
        var fromName = (string) restCmd["fromName"];
        var serviceURL = (string) restCmd["serviceURL"]
        var conversationId = (string) restCmd["conversation"];
    
        var uri = new Uri(serviceURL);
        var appId = "APP ID";
        var appSecret = "APP PASSWORD";
        ConnectorClient connector = new ConnectorClient(uri, appId, appSecret);
    
        var activity = new Activity()
        {
            Type = ActivityTypes.Message,
            From = new ChannelAccount(fromId, fromName),
            Recipient = new ChannelAccount(toId, toName),
            Conversation = new ConversationAccount(false, "personal", conversationId),
            Text = messageToSend
        };
        try
        {
            MicrosoftAppCredentials.TrustServiceUrl(serviceURL);
            await connector.Conversations.SendToConversationAsync(conversationId, activity);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }