Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'botframework-webchat' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
constructor(props) {
super(props);
this.state = {
webChatStore: createStore(
{},
({ dispatch }) => next => action => {
// console.log(action);
try {
const { payload, type } = action;
if (type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
const { activity } = payload;
if (
activity.type === 'event'
&& activity.name === 'ActiveRoute.Directions'
) {
console.log(activity);
let store;
window.addEventListener('keydown', event => {
const { ctrlKey, keyCode } = event;
if (ctrlKey && keyCode === 82) {
// CTRL-R
sessionStorage.removeItem(REDUX_STORE_KEY);
} else if (ctrlKey && keyCode === 83) {
// CTRL-S
event.preventDefault();
store && console.log(store.getState());
}
});
store = createStore(
onErrorResumeNext(() => JSON.parse(window.sessionStorage.getItem(REDUX_STORE_KEY))),
({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: { name: 'webchat/join', value: { language: window.navigator.language } }
});
}
return next(action);
}
);
store.subscribe(() => {
sessionStorage.setItem(REDUX_STORE_KEY, JSON.stringify(store.getState()));
});
initConversation(props: EmulatorProps, options: any): void {
const encodedOptions = encode(JSON.stringify(options));
// TODO: We need to use encoded token because we need to pass both endpoint ID and conversation ID
// We should think about a better model to pass conversation ID from Web Chat to emulator core
const directLine = createDirectLine({
secret: encodedOptions,
domain: `${this.props.url}/v3/directline`,
webSocket: false,
});
this.props.newConversation(props.documentId, {
conversationId: options.conversationId,
// webChatStore,
directLine,
userId: options.userId,
mode: options.mode,
});
}
const {
botId,
currentUser,
conversationId,
directLine,
locale,
mode,
webchatStore,
webSpeechPonyfillFactory,
} = this.props;
const isDisabled = mode === 'transcript' || mode === 'debug';
// Due to needing to make idiosyncratic style changes, Emulator is using `createStyleSet` instead of `createStyleOptions`. The object below: {...webChatStyleOptions, hideSendBox...} was formerly passed into the `styleOptions` parameter of React Web Chat. If further styling modifications are desired using styleOptions, simply pass it into the same object in createStyleSet below.
const styleSet = createStyleSet({ ...webChatStyleOptions, hideSendBox: isDisabled });
styleSet.uploadButton = {
...styleSet.uploadButton,
padding: '1px',
};
if (this.props.pendingSpeechTokenRetrieval) {
return <div>Connecting...</div>;
}
if (directLine) {
const bot = {
id: botId || 'bot',
name: 'Bot',
};
runRpcCommand(rpcCommand);
// stop webchat redux action propagation
return;
}
}
}
return next(action);
});
this.state = {
minimized: true,
newMessage: false,
side: 'right',
store,
styleSet: createStyleSet({
backgroundColor: 'Transparent',
}),
token: props.token,
};
}
.subscribe((connectionStatus) => {
switch (connectionStatus) {
// Successfully connected to the converstaion.
case ConnectionStatus.Online :
if (!conversationId) {
// Store the current conversation id in the browser session storage
// with 15 minutes expiration
this._storage.local.put(
this.CONVERSATION_ID_KEY, this._botConnection["conversationId"],
Util.dateAdd(new Date(), "minute", 15)
);
}
break;
}
});
private async _login() {
this.setState({
isBotInitializing :true,
showPanel: true,
});
// Get the conversation id if there is one. Otherwise, a new one will be created
const conversationId = this._storage.local.get(this.CONVERSATION_ID_KEY);
// Initialize the bot connection direct line
this._botConnection = new DirectLine({
secret: this._directLineSecret,
webSocket: false, // Needed to be able to retrieve history
conversationId: conversationId ? conversationId : null,
});
this._botConnection.connectionStatus$
.subscribe((connectionStatus) => {
switch (connectionStatus) {
// Successfully connected to the converstaion.
case ConnectionStatus.Online :
if (!conversationId) {
// Store the current conversation id in the browser session storage
// with 15 minutes expiration
this._storage.local.put(
this.CONVERSATION_ID_KEY, this._botConnection["conversationId"],
Util.dateAdd(new Date(), "minute", 15)
}
let botChanged = false;
if (this.botId !== settings.serverSettings.activeBot) {
this.botId = settings.serverSettings.activeBot || '';
botChanged = true;
}
if (conversationChanged || userChanged || botChanged) {
if (this.directline) {
this.directline.end();
this.directline = undefined;
// log.debug(`ended conversation`);
}
if (this.conversationId.length && this.userId.length && this.botId.length) {
this.directline = new BotChat.DirectLine({
secret: settings.conversation.conversationId,
token: settings.conversation.conversationId,
domain: `${Emulator.serviceUrl}/v3/directline`,
webSocket: false
});
// log.debug(`started new conversation`);
}
this.reuseKey++;
this.forceUpdate();
}
} catch(e) {
//log.error(e.message);
}
this.setState({
showUpdateDialog: settings.update.showing,
updateVersion: settings.update.version
// containerName: ''
// });
// To use Azure Cosmos DB Storage to store memory, you can the CosmosDbStorage class from `botbuilder-azure`
// const memory = new CosmosDbStorage({
// serviceEndpoint: '',
// authKey: '',
// databaseId: '',
// collectionId: ''
// });
// Create the custom WebChatAdapter and add the ConversationState middleware
const webChatAdapter = new WebChatAdapter()
// Connect our BotFramework-WebChat App instance with the DOM
App({
user: { id: "Me!" },
bot: { id: "bot" },
botConnection: webChatAdapter.botConnection,
}, document.getElementById('bot'));
// Add the instatiated storage into state middleware
const convoState = new ConversationState(memory);
const userState = new UserState(memory);
webChatAdapter.use(new BotStateSet(convoState, userState));
// Register the business logic of the bot through the WebChatAdapter's processActivity implementation.
webChatAdapter.processActivity(async (context) => {
const state = convoState.get(context);
state.bump = state.bump ? state.bump + 1 : 1;
await context.sendActivity(`${state.bump}: You said, "${context.activity.text}"`);
});
import {Bot, BotStateManager, MemoryStorage} from "botbuilder";
import 'botframework-webchat/botchat.css';
import {App} from 'botframework-webchat/built/App';
import {WebChatAdapter} from './webChatAdapter';
import {AlarmRenderer} from "./alarmRenderer";
import {routes} from './routes';
import {AlarmsListComponent} from "./alarmsListComponent";
const webChatAdapter = new WebChatAdapter();
const bot = new Bot(webChatAdapter)
.use(new MemoryStorage(),
new BotStateManager(),
new AlarmRenderer());
App({
user: {id: "Me!"},
bot: {id: "bot"},
botConnection: webChatAdapter.botConnection,
}, document.getElementById('bot'));
AlarmsListComponent.bootstrap(webChatAdapter.botConnection.activity$, document.querySelector('.alarms-container'));
// handle activities
bot.onReceive((context) => routes(context));
// FOUC
document.addEventListener('DOMContentLoaded', function () {
requestAnimationFrame(() => document.body.style.visibility = 'visible');
});