You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Microsoft Bot Framework的用户数据采集与Azure存储方案问询

Hey there! Let's break down exactly how to build your bot using Microsoft Bot Framework that collects user name, email, and phone number, then stores that data in an Azure database. I'll share code examples and key implementation steps below.

Prerequisites

First, make sure you have these set up:

  • Microsoft Bot Framework SDK v4 (I'll use C# here, but the logic translates to Python too)
  • An Azure Database (I'll use Azure SQL Database for this example; Cosmos DB works similarly with minor adjustments)
  • Basic understanding of bot dialogs (Waterfall dialogs are perfect for sequential data collection)

Step 1: Set Up the Bot & Data Collection Dialogs

We'll use a Waterfall dialog to guide the user through each question one by one. Here's the core code for the dialog:

using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using System.Threading;
using System.Threading.Tasks;

public class UserDataDialog : ComponentDialog
{
    private const string NamePrompt = "NamePrompt";
    private const string EmailPrompt = "EmailPrompt";
    private const string PhonePrompt = "PhonePrompt";

    public UserDataDialog(string dialogId) : base(dialogId)
    {
        // Add prompts for each field
        AddDialog(new TextPrompt(NamePrompt));
        AddDialog(new TextPrompt(EmailPrompt, ValidateEmailAsync));
        AddDialog(new TextPrompt(PhonePrompt, ValidatePhoneAsync));

        // Define the waterfall steps
        AddDialog(new WaterfallDialog("WaterfallDialog", new WaterfallStep[]
        {
            AskForNameAsync,
            AskForEmailAsync,
            AskForPhoneAsync,
            ConfirmAndStoreDataAsync
        }));

        // Set the initial dialog
        InitialDialogId = "WaterfallDialog";
    }

    private async Task<DialogTurnResult> AskForNameAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        return await stepContext.PromptAsync(NamePrompt, new PromptOptions { Prompt = MessageFactory.Text("Could you please tell me your name?") }, cancellationToken);
    }

    private async Task<DialogTurnResult> AskForEmailAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        // Store the name in dialog state
        stepContext.Values["Name"] = stepContext.Result;
        return await stepContext.PromptAsync(EmailPrompt, new PromptOptions { Prompt = MessageFactory.Text("Great! Now could you share your email address?") }, cancellationToken);
    }

    private async Task<DialogTurnResult> AskForPhoneAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        stepContext.Values["Email"] = stepContext.Result;
        return await stepContext.PromptAsync(PhonePrompt, new PromptOptions { Prompt = MessageFactory.Text("Perfect! Finally, could you provide your phone number?") }, cancellationToken);
    }

    private async Task<DialogTurnResult> ConfirmAndStoreDataAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        stepContext.Values["PhoneNumber"] = stepContext.Result;

        // Collect all data into a model
        var userData = new UserData
        {
            Name = (string)stepContext.Values["Name"],
            Email = (string)stepContext.Values["Email"],
            PhoneNumber = (string)stepContext.Values["PhoneNumber"]
        };

        // Store data in Azure Database (implementation below)
        await UserDataRepository.StoreUserDataAsync(userData);

        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Thanks {userData.Name}! We've saved your information successfully."), cancellationToken);
        return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
    }

    // Basic email validation helper
    private async Task<bool> ValidateEmailAsync(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
    {
        if (promptContext.Recognized.Succeeded)
        {
            var email = promptContext.Recognized.Value;
            // You can replace this with a more robust regex for stricter validation
            return email.Contains("@") && email.Contains(".");
        }
        await promptContext.Context.SendActivityAsync(MessageFactory.Text("That doesn't look like a valid email. Could you try again?"), cancellationToken);
        return false;
    }

    // Basic phone number validation helper
    private async Task<bool> ValidatePhoneAsync(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
    {
        if (promptContext.Recognized.Succeeded)
        {
            var phone = promptContext.Recognized.Value;
            // Strip non-digit characters and check length (adjust based on your region's format)
            var cleanedPhone = phone.Replace("-", "").Replace("(", "").Replace(")", "").Replace(" ", "");
            return cleanedPhone.Length >= 10;
        }
        await promptContext.Context.SendActivityAsync(MessageFactory.Text("That doesn't look like a valid phone number. Could you try again?"), cancellationToken);
        return false;
    }
}

// Model class to represent user data
public class UserData
{
    public int Id { get; set; } // Auto-incrementing primary key for Azure SQL
    public string Name { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
}

Step 2: Integrate with Azure SQL Database

We'll use Entity Framework Core to handle database interactions. First, install these NuGet packages:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools

Database Context Class

This class manages the connection to your Azure SQL database:

using Microsoft.EntityFrameworkCore;

public class UserDataContext : DbContext
{
    public UserDataContext(DbContextOptions<UserDataContext> options) : base(options) { }

    public DbSet<UserData> UserDatas { get; set; }
}

Repository Class for Database Operations

This class encapsulates the logic to save user data to the database:

using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

public static class UserDataRepository
{
    public static async Task StoreUserDataAsync(UserData userData)
    {
        // Important: Store your connection string in Azure App Service Configuration or Azure Key Vault, NOT hard-coded!
        var connectionString = "Server=tcp:<your-server-name>.database.windows.net,1433;Initial Catalog=<your-db-name>;Persist Security Info=False;User ID=<your-db-username>;Password=<your-db-password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
        
        var options = new DbContextOptionsBuilder<UserDataContext>()
            .UseSqlServer(connectionString)
            .Options;

        using (var context = new UserDataContext(options))
        {
            // Ensure the database exists (run this once, then remove or comment out)
            await context.Database.EnsureCreatedAsync();
            
            context.UserDatas.Add(userData);
            await context.SaveChangesAsync();
        }
    }
}

Step 3: Register the Dialog in Your Bot

Update your main bot class to trigger the data collection dialog when the user interacts with the bot:

using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using System.Threading;
using System.Threading.Tasks;

public class DataCollectionBot : ActivityHandler
{
    private readonly DialogSet _dialogs;
    private const string MainDialogId = "UserDataDialog";

    public DataCollectionBot()
    {
        _dialogs = new DialogSet();
        _dialogs.Add(new UserDataDialog(MainDialogId));
    }

    protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
    {
        var dc = await _dialogs.CreateContextAsync(turnContext, cancellationToken);
        
        if (dc.ActiveDialog == null)
        {
            // Start the data collection dialog if no dialog is running
            await dc.BeginDialogAsync(MainDialogId, cancellationToken: cancellationToken);
        }
        else
        {
            // Continue the active dialog if the user is already in the flow
            await dc.ContinueDialogAsync(cancellationToken);
        }
    }
}

Key Best Practices

  • Security: Never hard-code connection strings. Use Azure App Service's Application Settings or Azure Key Vault to store sensitive credentials. Enable encryption for sensitive data (like phone numbers) in your Azure SQL database.
  • Error Handling: Add try-catch blocks around database operations to handle connection failures or data validation errors, and notify the user if data storage fails.
  • Validation: Enhance the email/phone validation with region-specific regex patterns to ensure data quality.

内容的提问来源于stack exchange,提问作者Bhashitha Hemantha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:57:09