Microsoft Bot Framework Bot Builder core functionality for building conversational AI bots and chatbots in Python.
npx @tessl/cli install tessl/pypi-botbuilder-core@4.17.00
# BotBuilder Core
1
2
Microsoft Bot Framework core functionality for building conversational AI bots and chatbots in Python. This package provides the foundational components for activity handling, conversation state management, middleware support, bot adapters, and turn context management, enabling developers to build sophisticated enterprise-grade conversational experiences.
3
4
## Package Information
5
6
- **Package Name**: botbuilder-core
7
- **Language**: Python
8
- **Installation**: `pip install botbuilder-core`
9
10
## Core Imports
11
12
```python
13
from botbuilder.core import (
14
ActivityHandler, Bot, BotFrameworkAdapter, TurnContext,
15
MemoryStorage, ConversationState, UserState, MessageFactory, CardFactory
16
)
17
```
18
19
Common patterns:
20
21
```python
22
# Bot and activity handling
23
from botbuilder.core import Bot, ActivityHandler, TurnContext
24
25
# Adapters and settings
26
from botbuilder.core import BotFrameworkAdapter, BotFrameworkAdapterSettings
27
28
# State management
29
from botbuilder.core import ConversationState, UserState, MemoryStorage, BotState
30
31
# Message creation
32
from botbuilder.core import MessageFactory, CardFactory
33
34
# Middleware
35
from botbuilder.core import AutoSaveStateMiddleware, ShowTypingMiddleware
36
37
# OAuth and authentication
38
from botbuilder.core import ExtendedUserTokenProvider, UserTokenProvider
39
40
# Utilities
41
from botbuilder.core import BotAssert, ComponentRegistration
42
```
43
44
## Basic Usage
45
46
```python
47
from botbuilder.core import ActivityHandler, TurnContext, MessageFactory
48
49
class EchoBot(ActivityHandler):
50
async def on_message_activity(self, turn_context: TurnContext):
51
# Echo back what the user said
52
reply_text = f"You said: {turn_context.activity.text}"
53
await turn_context.send_activity(MessageFactory.text(reply_text))
54
55
async def on_members_added_activity(self, members_added, turn_context: TurnContext):
56
for member in members_added:
57
if member.id != turn_context.activity.recipient.id:
58
await turn_context.send_activity(MessageFactory.text("Welcome!"))
59
60
# Usage with adapter
61
from botbuilder.core import BotFrameworkAdapter, BotFrameworkAdapterSettings
62
63
# Create adapter
64
settings = BotFrameworkAdapterSettings(app_id="", app_password="")
65
adapter = BotFrameworkAdapter(settings)
66
67
# Create bot
68
bot = EchoBot()
69
70
# Process incoming activities (typically in web framework)
71
async def process_request(req):
72
auth_header = req.headers.get("Authorization", "")
73
response = await adapter.process_activity(req, auth_header, bot.on_turn)
74
return response
75
```
76
77
## Architecture
78
79
The Bot Framework SDK follows a layered architecture:
80
81
- **ActivityHandler**: High-level bot class that processes different activity types (messages, member additions, invokes)
82
- **BotAdapter**: Connects bot logic to communication channels, handles activity routing and response sending
83
- **TurnContext**: Encapsulates a single conversational turn with methods for sending/updating activities and managing turn state
84
- **BotState & Storage**: Persistent state management across conversation turns with support for user, conversation, and private conversation scopes
85
- **Middleware**: Pipeline components for cross-cutting concerns like logging, telemetry, typing indicators, and auto-save state
86
87
This design enables building scalable bots that handle complex conversation flows, integrate with various channels, and maintain context across multiple turns.
88
89
## Capabilities
90
91
### Bot Base Class
92
93
Abstract base class for all bots that defines the core contract for processing activities. All bot implementations must inherit from this class and implement the on_turn method.
94
95
```python { .api }
96
class Bot:
97
"""Abstract base class for bots."""
98
99
async def on_turn(self, context: TurnContext):
100
"""Handle an incoming activity."""
101
```
102
103
### Activity Handling
104
105
Core functionality for processing bot activities including messages, member additions, invokes, and other Bot Framework activity types. The ActivityHandler provides event-driven methods for handling different scenarios in conversational flows.
106
107
```python { .api }
108
class ActivityHandler(Bot):
109
async def on_turn(self, turn_context: TurnContext):
110
"""Main entry point for processing activities."""
111
112
async def on_message_activity(self, turn_context: TurnContext):
113
"""Handle message activities from users."""
114
115
async def on_members_added_activity(self, members_added, turn_context: TurnContext):
116
"""Handle when members are added to the conversation."""
117
118
async def on_members_removed_activity(self, members_removed, turn_context: TurnContext):
119
"""Handle when members are removed from the conversation."""
120
121
async def on_invoke_activity(self, turn_context: TurnContext):
122
"""Handle invoke activities (typically from cards or skills)."""
123
124
async def on_message_reaction_activity(self, turn_context: TurnContext):
125
"""Handle message reaction activities."""
126
127
async def on_event_activity(self, turn_context: TurnContext):
128
"""Handle event activities."""
129
```
130
131
[Activity Handling](./activity-handling.md)
132
133
### Bot Adapters
134
135
Adapter classes that connect bot logic to various communication channels and handle the low-level details of activity processing, authentication, and response management. Includes the main BotFrameworkAdapter and specialized adapters.
136
137
```python { .api }
138
class BotFrameworkAdapter:
139
def __init__(self, settings: BotFrameworkAdapterSettings):
140
"""Initialize adapter with Bot Framework settings."""
141
142
async def process_activity(self, req, auth_header: str, logic):
143
"""Process incoming activity from Bot Framework channels."""
144
145
async def send_activities(self, context: TurnContext, activities):
146
"""Send multiple activities to the channel."""
147
```
148
149
[Bot Adapters](./bot-adapters.md)
150
151
### Turn Context & Activities
152
153
Turn context management and activity manipulation utilities. TurnContext represents the context of a single conversational turn and provides methods for sending responses, managing turn state, and working with activities.
154
155
```python { .api }
156
class TurnContext:
157
activity: Activity
158
responded: bool
159
160
async def send_activity(self, activity_or_text, speak=None, input_hint=None):
161
"""Send a single activity response."""
162
163
async def send_activities(self, activities):
164
"""Send multiple activities in sequence."""
165
166
async def update_activity(self, activity):
167
"""Update an existing activity."""
168
```
169
170
[Turn Context & Activities](./turn-context.md)
171
172
### State Management
173
174
Persistent state management across conversation turns with support for different scopes (user, conversation, private conversation) and custom storage implementations. Includes state property accessors and automatic state persistence.
175
176
```python { .api }
177
class ConversationState(BotState):
178
"""Manages conversation-scoped state."""
179
180
class UserState(BotState):
181
"""Manages user-scoped state."""
182
183
class BotState:
184
def create_property(self, name: str):
185
"""Create a state property accessor."""
186
187
async def load(self, turn_context: TurnContext, force: bool = False):
188
"""Load state from storage."""
189
190
async def save_changes(self, turn_context: TurnContext, force: bool = False):
191
"""Save state changes to storage."""
192
```
193
194
[State Management](./state-management.md)
195
196
### Storage
197
198
Storage implementations for persisting bot state and data. Includes memory storage for development and testing, plus abstract base classes for implementing custom storage solutions.
199
200
```python { .api }
201
class MemoryStorage(Storage):
202
"""In-memory storage implementation for development and testing."""
203
204
class Storage:
205
async def read(self, keys):
206
"""Read items from storage."""
207
208
async def write(self, changes):
209
"""Write items to storage."""
210
211
async def delete(self, keys):
212
"""Delete items from storage."""
213
```
214
215
[Storage](./storage.md)
216
217
### Middleware
218
219
Middleware pipeline for implementing cross-cutting concerns like logging, telemetry, typing indicators, and automatic state saving. Middleware components can inspect and modify activities as they flow through the bot.
220
221
```python { .api }
222
class AutoSaveStateMiddleware(Middleware):
223
"""Automatically saves state after each turn."""
224
225
class ShowTypingMiddleware(Middleware):
226
"""Shows typing indicator during processing."""
227
228
class TelemetryLoggerMiddleware(Middleware):
229
"""Logs telemetry data for analytics."""
230
```
231
232
[Middleware](./middleware.md)
233
234
### Message & Card Factories
235
236
Factory classes for creating rich message activities and card attachments. Simplifies the creation of formatted responses, cards, and other rich content types supported by the Bot Framework.
237
238
```python { .api }
239
class MessageFactory:
240
@staticmethod
241
def text(text: str, speak: str = None, input_hint=None):
242
"""Create a text message activity."""
243
244
@staticmethod
245
def attachment(attachment):
246
"""Create a message with an attachment."""
247
248
class CardFactory:
249
@staticmethod
250
def adaptive_card(card):
251
"""Create an Adaptive Card attachment."""
252
253
@staticmethod
254
def hero_card(title: str, subtitle: str = None, text: str = None):
255
"""Create a Hero Card attachment."""
256
```
257
258
[Message & Card Factories](./message-factories.md)
259
260
261
### OAuth & Authentication
262
263
OAuth token management and user authentication functionality. Includes token providers, authentication utilities, and integration with Bot Framework authentication services.
264
265
```python { .api }
266
class ExtendedUserTokenProvider:
267
async def get_user_token(self, turn_context: TurnContext, connection_name: str):
268
"""Get OAuth token for user."""
269
270
async def sign_out_user(self, turn_context: TurnContext, connection_name: str):
271
"""Sign out user from OAuth provider."""
272
```
273
274
[OAuth & Authentication](./oauth-authentication.md)
275
276
### Telemetry & Logging
277
278
Telemetry and logging functionality for monitoring bot performance, usage analytics, and debugging. Includes telemetry clients, logging middleware, and transcript storage.
279
280
```python { .api }
281
class BotTelemetryClient:
282
def track_event(self, name: str, properties: dict = None):
283
"""Track custom telemetry events."""
284
285
def track_exception(self, exception, properties: dict = None):
286
"""Track exceptions for monitoring."""
287
288
class TranscriptLoggerMiddleware(Middleware):
289
"""Logs conversation transcripts."""
290
```
291
292
[Telemetry & Logging](./telemetry-logging.md)
293
294
### Testing Utilities
295
296
Testing utilities for unit testing bots including test adapters, test flows, and assertion helpers. Enables comprehensive testing of bot logic without requiring actual Bot Framework channels.
297
298
```python { .api }
299
class TestAdapter(BotAdapter):
300
"""Test adapter for unit testing bots."""
301
302
class TestFlow:
303
def test(self, user_says: str, expected: str):
304
"""Test a single turn of conversation."""
305
306
async def start_test(self):
307
"""Start a test conversation flow."""
308
```
309
310
[Testing Utilities](./testing-utilities.md)
311
312
### Cloud Adapters & Advanced Components
313
314
Cloud-based adapter implementations and advanced components for enterprise scenarios including cloud channel service handlers, component registration systems, and utility classes.
315
316
```python { .api }
317
class CloudAdapterBase(BotAdapter):
318
"""Base class for cloud-based bot adapters."""
319
320
class CloudChannelServiceHandler:
321
"""Handler for cloud channel service operations."""
322
323
class ComponentRegistration:
324
"""Component registration system for dependency injection."""
325
326
@staticmethod
327
def get_components():
328
"""Get all registered components."""
329
330
@staticmethod
331
def add(component_registration):
332
"""Add a component registration."""
333
334
class BotAssert:
335
"""Assertion utilities for validating bot objects."""
336
337
@staticmethod
338
def activity_not_none(activity: Activity):
339
"""Assert activity is not None."""
340
341
@staticmethod
342
def context_not_none(turn_context: TurnContext):
343
"""Assert turn context is not None."""
344
```
345
346
## Types
347
348
```python { .api }
349
class Activity:
350
"""Represents a Bot Framework activity."""
351
type: str
352
text: str
353
from_property: ChannelAccount
354
recipient: ChannelAccount
355
conversation: ConversationAccount
356
357
class ChannelAccount:
358
"""Represents a channel account (user or bot)."""
359
id: str
360
name: str
361
362
class ConversationAccount:
363
"""Represents a conversation."""
364
id: str
365
name: str
366
is_group: bool
367
368
class ResourceResponse:
369
"""Response from activity operations."""
370
id: str
371
372
class InvokeResponse:
373
"""Response for invoke activities."""
374
status: int
375
body: object
376
```