How to store & retrieve Bot Data in Azure Table storage with directLine channel?

前端 未结 3 1783
醉梦人生
醉梦人生 2020-12-18 14:24

I\'m using Microsoft Bot Framework with directLine channel. My Bot is a part of company\'s customer portal from where I fetch some user information

3条回答
  •  难免孤独
    2020-12-18 14:52

    One option is to use the Microsoft Azure Storage Client Library for .NET, as explained in the answer here: How to retrieve Saved Conversation Data in Azure (Tablelogger) Just make sure to follow the exact same PartitionKey strategy as is followed by the TableBotDataStore class, and serialize the data field correctly.

    -- Edit: I tested this out, and it does in fact work as expected.

     public class WebChatController : Controller
    {
        public ActionResult Index()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString;
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
    
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
    
            CloudTable table = tableClient.GetTableReference("BotStore");
            string userId = Guid.NewGuid().ToString();
            TableQuery query = new TableQuery().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, userId));
    
            var dataRow = table.ExecuteQuery(query).FirstOrDefault();
            if(dataRow != null)
            {
                dataRow.Data = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    UserName = "This user's name",
                    Email = "whatever@email.com",
                    GraphAccessToken = "token",
                    TokenExpiryTime = DateTime.Now.AddHours(1)
                });
                dataRow.Timestamp = DateTimeOffset.UtcNow;
                table.Execute(TableOperation.Replace(dataRow));
            }
            else
            {
                var row = new BotDataRow(userId, "userData");
                row.Data = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    UserName = "This user's name",
                    Email = "whatever@email.com",
                    GraphAccessToken = "token",
                    TokenExpiryTime = DateTime.Now.AddHours(1)
                });
                row.Timestamp = DateTimeOffset.UtcNow;
                table.Execute(TableOperation.Insert(row));
            }
    
            var vm = new WebChatModel();
            vm.UserId = userId;
            return View(vm);
        }
    
        public class BotDataRow : TableEntity
        {
            public BotDataRow(string partitionKey, string rowKey)
            {
                this.PartitionKey = partitionKey;
                this.RowKey = rowKey;
            }
    
            public BotDataRow() { }
    
            public bool IsCompressed { get; set; }
            public string Data { get; set; }
        }
    }
    

    In the node bot:

    'use strict';
    
    const builder = require('botbuilder');
    const restify = require('restify');
    var azure = require('botbuilder-azure');
    
    var tableName = 'BotStore';
    var azureTableClient = new azure.AzureTableClient(tableName,'accountname','accountkey');
    var tableStorage = new azure.AzureBotStorage({ gzipData: false }, azureTableClient);
    
    
    const connector = new builder.ChatConnector({
        appId: process.env.MicrosoftAppId,
        appPassword: process.env.MicrosoftAppPassword
        });
    
    const server = restify.createServer();
    server.listen(process.env.port || process.env.PORT || 3979, () => {
        console.log(`${server.name} listening to ${server.url}`);
    });
    
    server.post('/api/messages', connector.listen());
    
    var bot = new builder.UniversalBot(connector)
        .set('storage', tableStorage);;
    
    bot.dialog('/',
    [
        function (session){
            var data = session.userData;
        }
    ]);
    

提交回复
热议问题