基于Microsoft Bot Framework,如何实现管理员查看客席实时对话?
Hey there! Since you've already got the Tompanna handoff flow working in your Bot Framework app, building an admin portal for real-time conversation monitoring is totally achievable with a few key components. Let's walk through the steps:
1. Capture & Store Conversation Data First
First, you need a way to persist every message between customers and agents—whether it's coming through your bot or the Tompanna agent interface. Here are two reliable approaches:
Option 1: Intercept Messages in Your Bot
In your bot's OnTurnAsync method, add logic to log every incoming/outgoing message right as it's processed. This works for messages routed through the bot, and you can store the data in a real-time-friendly store like Azure Cosmos DB (with Change Feed support) or Redis.
Example C# snippet for logging:
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { // Handle the original conversation logic first await base.OnMessageActivityAsync(turnContext, cancellationToken); // Build a conversation log entry var logEntry = new ConversationLog { ConversationId = turnContext.Activity.Conversation.Id, SenderType = turnContext.Activity.From.Role == "user" ? "Customer" : "Agent", SenderId = turnContext.Activity.From.Id, MessageContent = turnContext.Activity.Text, Timestamp = DateTime.UtcNow, // Add Tompanna session ID if you passed it during handoff TompannaSessionId = turnContext.Activity.ChannelData?["TompannaSessionId"]?.ToString() }; // Save to your storage service (e.g., Cosmos DB) await _conversationLogService.SaveLogEntryAsync(logEntry); }
Option 2: Sync Directly from Tompanna
If Tompanna exposes webhooks or a real-time API for conversation events, use that to pull agent-side messages directly. This ensures you capture every interaction, even those initiated directly in the Tompanna agent console. Just subscribe to Tompanna's conversation update events and sync the data to your central store.
2. Add Real-Time Push with SignalR
To avoid forcing admins to refresh the portal, use Azure SignalR Service (integrates seamlessly with Microsoft's ecosystem) to push new messages to the portal in real-time.
Backend Setup (ASP.NET Core Example)
- Create a SignalR Hub in your portal backend:
public class ConversationHub : Hub { // Allow admins to join a group for a specific conversation public async Task JoinConversationGroup(string conversationId) { await Groups.AddToGroupAsync(Context.ConnectionId, conversationId); } }
- Trigger pushes when new logs are added:
- If using Cosmos DB, set up a Change Feed processor to listen for new log entries. When a new entry comes in, send it to all admins watching that conversation:
public async Task ProcessNewLogEntries(IReadOnlyCollection<Document> changes) { foreach (var change in changes) { var logEntry = change.ToObject<ConversationLog>(); await _hubContext.Clients.Group(logEntry.ConversationId) .SendAsync("ReceiveNewMessage", logEntry); } }
Frontend Setup
Use the SignalR JavaScript client to connect to the hub and render new messages instantly:
const connection = new signalR.HubConnectionBuilder() .withUrl("/conversationHub") .build(); // Listen for new messages connection.on("ReceiveNewMessage", (logEntry) => { const messageElement = document.createElement("div"); messageElement.className = logEntry.SenderType === "Customer" ? "customer-message" : "agent-message"; messageElement.innerHTML = `<strong>${logEntry.SenderType}:</strong> ${logEntry.MessageContent}<br><small>${new Date(logEntry.Timestamp).toLocaleString()}</small>`; document.getElementById(`conversation-${logEntry.ConversationId}`).appendChild(messageElement); }); // Start the connection connection.start().catch(err => console.error(err.toString())); // When an admin selects a conversation, join its group function selectConversation(conversationId) { connection.invoke("JoinConversationGroup", conversationId) .catch(err => console.error(err.toString())); // Load historical messages for the conversation via your API }
3. Build the Admin Portal Core Features
Key UI Components:
- Active Conversations List: Show all ongoing customer-agent chats with details like customer name/ID, agent name, conversation start time, and status.
- Real-Time Conversation Panel: When an admin clicks a conversation, load the full history (use pagination for older messages) and stream new messages as they come in.
- Access Control: Lock down the portal with Azure AD authentication, ensuring only users with an
Adminrole can access the monitoring features.
4. Integrate with Your Existing Tompanna Handoff
- Sync Conversation IDs: When you initiate a handoff to Tompanna, pass the Bot Framework conversation ID to Tompanna and store it in their session data. This lets you link bot logs to Tompanna logs seamlessly.
- Agent Status Sync: Use Tompanna's API to pull agent online/offline status and current load, then display that in your admin portal for full visibility.
- Data Consistency: Make sure logs from both the bot and Tompanna are synced to the same storage layer—use idempotent writes to avoid duplicate messages.
5. Optional Nice-to-Haves
- Search & Filter: Let admins search conversations by customer ID, agent ID, date range, or keyword.
- Conversation Export: Add a button to export full conversation history as CSV/PDF for compliance or auditing.
- Dashboard Metrics: Display real-time stats like active conversations, wait time, and agent utilization to help admins manage load.
内容的提问来源于stack exchange,提问作者tushar gupta

