class BotConfig(AppConfig): """ Bot initialization """ name = 'bots' appConfig = config.DefaultConfig SETTINGS = BotFrameworkAdapterSettings(appConfig.APP_ID, appConfig.APP_PASSWORD) ADAPTER = BotFrameworkAdapter(SETTINGS) LOOP = asyncio.get_event_loop() # Create MemoryStorage, UserState and ConversationState memory = MemoryStorage() user_state = UserState(memory) conversation_state = ConversationState(memory) dialog = MainDialog(appConfig) bot = DialogAndWelcomeBot(conversation_state, user_state, dialog) async def on_error(self, context: TurnContext, error: Exception): """ Catch-all for errors. This check writes out errors to console log NOTE: In production environment, you should consider logging this to Azure application insights. """ print(f'\n [on_turn_error]: { error }', file=sys.stderr) # Send a message to the user await context.send_activity('Oops. Something went wrong!') # Clear out state await self.conversation_state.delete(context) def ready(self): self.ADAPTER.on_turn_error = self.on_error
def main(): parse_command_line() # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. settings = BotFrameworkAdapterSettings(options.app_id, options.app_password) # Create MemoryStorage, UserState and ConversationState memory = MemoryStorage() user_state = UserState(memory) conversation_state = ConversationState(memory) # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. adapter = AdapterWithErrorHandler(settings, conversation_state) # Create dialogs and Bot recognizer = FlightBookingRecognizer(options) booking_dialog = BookingDialog() dialog = MainDialog(recognizer, booking_dialog) bot = DialogAndWelcomeBot(conversation_state, user_state, dialog) app = tornado.web.Application( [ (r"/api/messages", MessageHandler, dict(adapter=adapter, bot=bot)), ], debug=options.debug, ) app.listen(options.port) tornado.ioloop.IOLoop.current().start()
async def test_process_activity_for_forwarded_activity(self): bot_app_id = "00000000-0000-0000-0000-000000000001" skill_1_app_id = "00000000-0000-0000-0000-000000skill1" identity = ClaimsIdentity( claims={ AuthenticationConstants.AUDIENCE_CLAIM: skill_1_app_id, AuthenticationConstants.APP_ID_CLAIM: bot_app_id, AuthenticationConstants.VERSION_CLAIM: "1.0", }, is_authenticated=True, ) service_url = "https://root-bot.test.azurewebsites.net/" async def callback(context: TurnContext): TestBotFrameworkAdapter.get_creds_and_assert_values( context, skill_1_app_id, bot_app_id, 1, ) TestBotFrameworkAdapter.get_client_and_assert_values( context, skill_1_app_id, bot_app_id, service_url, 1, ) scope = context.turn_state[BotFrameworkAdapter.BOT_OAUTH_SCOPE_KEY] assert bot_app_id == scope settings = BotFrameworkAdapterSettings(bot_app_id) sut = BotFrameworkAdapter(settings) await sut.process_activity_with_identity( Activity(channel_id="emulator", service_url=service_url, text="test",), identity, callback, )
def __init__(self): # Create the loop and Flask app self.loop = asyncio.get_event_loop() self.flask = Flask(__name__, instance_relative_config=True) self.flask.config.from_object(DefaultConfig) # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. self.settings = BotFrameworkAdapterSettings( self.flask.config["APP_ID"], self.flask.config["APP_PASSWORD"]) self.adapter = BotFrameworkAdapter(self.settings) # Catch-all for errors. async def on_error(adapter, context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error]: {error}", file=sys.stderr) # Send a message to the user error_message_text = "Sorry, it looks like something went wrong." error_message = MessageFactory.text(error_message_text, error_message_text, InputHints.expecting_input) await context.send_activity(error_message) # pylint: disable=protected-access if adapter._conversation_state: # If state was defined, clear it. await adapter._conversation_state.delete(context) self.adapter.on_turn_error = MethodType(on_error, self.adapter) # Create the main dialog self.bot = MyBot()
async def test_process_activity_with_identity_token_exchange_invoke_response( self): mock_credential_provider = unittest.mock.create_autospec( CredentialProvider) settings = BotFrameworkAdapterSettings( app_id="bot_id", credential_provider=mock_credential_provider, ) adapter = AdapterUnderTest(settings) identity = ClaimsIdentity( claims={ AuthenticationConstants.AUDIENCE_CLAIM: "bot_id", AuthenticationConstants.APP_ID_CLAIM: "bot_id", AuthenticationConstants.VERSION_CLAIM: "1.0", }, is_authenticated=True, ) inbound_activity = Activity( type=ActivityTypes.invoke, name=SignInConstants.token_exchange_operation_name, service_url="http://tempuri.org/whatever", delivery_mode=DeliveryModes.normal, conversation=ConversationAccount(id="conversationId"), value=TokenExchangeInvokeRequest( id="token_exchange_id", token="token", connection_name="connection_name", ), ) async def callback(context: TurnContext): activity = Activity( type=ActivityTypes.invoke_response, value=InvokeResponse( status=200, body=TokenExchangeInvokeResponse( id=context.activity.value.id, connection_name=context.activity.value.connection_name, ), ), ) await context.send_activity(activity) invoke_response = await adapter.process_activity_with_identity( inbound_activity, identity, callback, ) assert invoke_response assert invoke_response.status == 200 assert invoke_response.body["id"] == inbound_activity.value.id assert (invoke_response.body["connectionName"] == inbound_activity.value.connection_name)
async def test_continue_conversation_with_audience(self): mock_credential_provider = unittest.mock.create_autospec(CredentialProvider) settings = BotFrameworkAdapterSettings( app_id="bot_id", credential_provider=mock_credential_provider ) adapter = BotFrameworkAdapter(settings) skill_1_app_id = "00000000-0000-0000-0000-000000skill1" skill_2_app_id = "00000000-0000-0000-0000-000000skill2" skills_identity = ClaimsIdentity( claims={ AuthenticationConstants.AUDIENCE_CLAIM: skill_1_app_id, AuthenticationConstants.APP_ID_CLAIM: skill_2_app_id, AuthenticationConstants.VERSION_CLAIM: "1.0", }, is_authenticated=True, ) skill_2_service_url = "https://skill2.com/api/skills/" async def callback(context: TurnContext): TestBotFrameworkAdapter.get_creds_and_assert_values( context, skill_1_app_id, skill_2_app_id, 1, ) TestBotFrameworkAdapter.get_client_and_assert_values( context, skill_1_app_id, skill_2_app_id, skill_2_service_url, 1, ) # pylint: disable=protected-access client_cache = context.adapter._connector_client_cache client = client_cache.get( BotFrameworkAdapter.key_for_connector_client( skill_2_service_url, skill_1_app_id, skill_2_app_id, ) ) assert client turn_state_client = context.turn_state.get( BotFrameworkAdapter.BOT_CONNECTOR_CLIENT_KEY ) assert turn_state_client client_creds = turn_state_client.config.credentials assert skill_1_app_id == client_creds.microsoft_app_id assert skill_2_app_id == client_creds.oauth_scope assert client.config.base_url == turn_state_client.config.base_url scope = context.turn_state[BotFrameworkAdapter.BOT_OAUTH_SCOPE_KEY] assert skill_2_app_id == scope refs = ConversationReference(service_url=skill_2_service_url) await adapter.continue_conversation( refs, callback, claims_identity=skills_identity, audience=skill_2_app_id )
def __init__(self, config, opsdroid=None): """Create the connector.""" self.name = config.get("name", "teams") self.config = config self.default_target = None # Teams has no default room self.opsdroid = opsdroid self.app_id = self.config.get("app-id", "abc123") self.app_password = self.config.get("password", "") self.adapter = BotFrameworkAdapter( BotFrameworkAdapterSettings(self.app_id, self.app_password)) self.conversation_references = {} self.service_endpoints = {}
async def __process_activity_creates_correct_creds_and_client( self, bot_app_id: str, expected_caller_id: str, channel_service: str, expected_scope: str, expected_app_credentials_count: int, expected_client_credentials_count: int, ): identity = ClaimsIdentity({}, True) if bot_app_id: identity.claims = { AuthenticationConstants.AUDIENCE_CLAIM: bot_app_id, AuthenticationConstants.APP_ID_CLAIM: bot_app_id, AuthenticationConstants.VERSION_CLAIM: "1.0", } credential_provider = SimpleCredentialProvider(bot_app_id, None) service_url = "https://smba.trafficmanager.net/amer/" async def callback(context: TurnContext): TestBotFrameworkAdapter.get_creds_and_assert_values( context, bot_app_id, expected_scope, expected_app_credentials_count, ) TestBotFrameworkAdapter.get_client_and_assert_values( context, bot_app_id, expected_scope, service_url, expected_client_credentials_count, ) assert context.activity.caller_id == expected_caller_id settings = BotFrameworkAdapterSettings( bot_app_id, credential_provider=credential_provider, channel_provider=SimpleChannelProvider(channel_service), ) sut = BotFrameworkAdapter(settings) await sut.process_activity_with_identity( Activity( channel_id="emulator", service_url=service_url, text="test", ), identity, callback, )
def init(): global LOOP global ADAPTER global BOT app_id = "XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" app_password = "******" settings = BotFrameworkAdapterSettings(app_id=app_id, app_password=app_password) ADAPTER = BotFrameworkAdapter(settings) LOOP = asyncio.get_event_loop() BOT = EchoBot()
async def test_delivery_mode_expect_replies(self): mock_credential_provider = unittest.mock.create_autospec(CredentialProvider) settings = BotFrameworkAdapterSettings( app_id="bot_id", credential_provider=mock_credential_provider ) adapter = AdapterUnderTest(settings) async def callback(context: TurnContext): await context.send_activity("activity 1") await context.send_activity("activity 2") await context.send_activity("activity 3") inbound_activity = Activity( type=ActivityTypes.message, channel_id="emulator", service_url="http://tempuri.org/whatever", delivery_mode=DeliveryModes.expect_replies, text="hello world", ) identity = ClaimsIdentity( claims={ AuthenticationConstants.AUDIENCE_CLAIM: "bot_id", AuthenticationConstants.APP_ID_CLAIM: "bot_id", AuthenticationConstants.VERSION_CLAIM: "1.0", }, is_authenticated=True, ) invoke_response = await adapter.process_activity_with_identity( inbound_activity, identity, callback ) assert invoke_response assert invoke_response.status == 200 activities = ExpectedReplies().deserialize(invoke_response.body).activities assert len(activities) == 3 assert activities[0].text == "activity 1" assert activities[1].text == "activity 2" assert activities[2].text == "activity 3" assert ( adapter.connector_client_mock.conversations.send_to_conversation.call_count == 0 )
async def test_process_activity_creates_correct_creds_and_client(self): bot_app_id = "00000000-0000-0000-0000-000000000001" identity = ClaimsIdentity( claims={ AuthenticationConstants.AUDIENCE_CLAIM: bot_app_id, AuthenticationConstants.APP_ID_CLAIM: bot_app_id, AuthenticationConstants.VERSION_CLAIM: "1.0", }, is_authenticated=True, ) service_url = "https://smba.trafficmanager.net/amer/" async def callback(context: TurnContext): TestBotFrameworkAdapter.get_creds_and_assert_values( context, bot_app_id, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, 1, ) TestBotFrameworkAdapter.get_client_and_assert_values( context, bot_app_id, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, service_url, 1, ) scope = context.turn_state[BotFrameworkAdapter.BOT_OAUTH_SCOPE_KEY] assert AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE == scope settings = BotFrameworkAdapterSettings(bot_app_id) sut = BotFrameworkAdapter(settings) await sut.process_activity_with_identity( Activity( channel_id="emulator", service_url=service_url, text="test", ), identity, callback, )
async def test_delivery_mode_normal(self): mock_credential_provider = unittest.mock.create_autospec(CredentialProvider) settings = BotFrameworkAdapterSettings( app_id="bot_id", credential_provider=mock_credential_provider ) adapter = AdapterUnderTest(settings) async def callback(context: TurnContext): await context.send_activity("activity 1") await context.send_activity("activity 2") await context.send_activity("activity 3") inbound_activity = Activity( type=ActivityTypes.message, channel_id="emulator", service_url="http://tempuri.org/whatever", delivery_mode=DeliveryModes.normal, text="hello world", conversation=ConversationAccount(id="conversationId"), ) identity = ClaimsIdentity( claims={ AuthenticationConstants.AUDIENCE_CLAIM: "bot_id", AuthenticationConstants.APP_ID_CLAIM: "bot_id", AuthenticationConstants.VERSION_CLAIM: "1.0", }, is_authenticated=True, ) invoke_response = await adapter.process_activity_with_identity( inbound_activity, identity, callback ) assert not invoke_response assert ( adapter.connector_client_mock.conversations.send_to_conversation.call_count == 3 )
def __init__(self, bot, name, app_id=None, app_password=None): """Create a receiver behavior object which acts on bot :param bot: Bot instance for this receiver to control :type bot: :class:`sparkbot.SparkBot` :param name: The MS Teams name of the bot in Microsoft Teams, which will be removed from incoming messages before dispatch :param app_id: The Microsoft App ID to authenticate as :param app_password: The Microsoft App Password to authenticate with If ``app_id`` and ``app_password`` are not passed, ``MICROSOFT_APP_ID`` and ``MICROSOFT_APP_PASSWORD`` from the environment will be used, respectively. """ if not app_id: try: app_id = environ["MICROSOFT_APP_ID"] except KeyError: raise KeyError( "MICROSOFT_APP_ID not found in environment and not passed in msteams.create() call" ) if not app_password: try: app_password = environ["MICROSOFT_APP_PASSWORD"] except KeyError: raise KeyError( "MICROSOFT_APP_PASSWORD not found in environment and not passed in msteams.create() call" ) settings = BotFrameworkAdapterSettings(app_id, app_password) self.adapter = BotFrameworkAdapter(settings) self.name = name self.bot = bot
from bots import RootBot from config import DefaultConfig, SkillConfiguration CONFIG = DefaultConfig() SKILL_CONFIG = SkillConfiguration() # Whitelist skills from SKILL_CONFIG ALLOWED_CALLER_IDS = {s.app_id for s in [*SKILL_CONFIG.SKILLS.values()]} CLAIMS_VALIDATOR = AllowedSkillsClaimsValidator(ALLOWED_CALLER_IDS) AUTH_CONFIG = AuthenticationConfiguration( claims_validator=CLAIMS_VALIDATOR.validate_claims) # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. SETTINGS = BotFrameworkAdapterSettings( app_id=CONFIG.APP_ID, app_password=CONFIG.APP_PASSWORD, auth_configuration=AUTH_CONFIG, ) ADAPTER = BotFrameworkAdapter(SETTINGS) STORAGE = MemoryStorage() CONVERSATION_STATE = ConversationState(STORAGE) ID_FACTORY = SkillConversationIdFactory(STORAGE) CREDENTIAL_PROVIDER = SimpleCredentialProvider(CONFIG.APP_ID, CONFIG.APP_PASSWORD) CLIENT = SkillHttpClient(CREDENTIAL_PROVIDER, ID_FACTORY) # Catch-all for errors. async def on_error(context: TurnContext, error: Exception):
from botbuilder.core.integration import aiohttp_error_middleware from botbuilder.schema import Activity from config import DefaultConfig from welcome import WelcomeBot from dialog import SmartBot from adapter_with_error_handler import AdapterWithErrorHandler CONFIG = DefaultConfig() MEMORY = MemoryStorage() USER_STATE = UserState(MEMORY) CONVERSATION_STATE = ConversationState(MEMORY) # Create adapter botadaptersettings = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD) botadapter = AdapterWithErrorHandler(botadaptersettings, CONVERSATION_STATE) # Create dialogs and Bot WELCOME = WelcomeBot() BOT = SmartBot() # Listen for incoming requests on /api/messages. async def messages(req: Request) -> Response: # Main bot message handler. if "application/json" in req.headers["Content-Type"]: body = await req.json() else: return Response(status=415) activity = Activity().deserialize(body)
BotFrameworkAdapter, MemoryStorage, TurnContext, UserState, ) from botbuilder.core.integration import aiohttp_error_middleware from botbuilder.schema import Activity, ActivityTypes import os from bots import EchoBot from config import DefaultConfig CONFIG = DefaultConfig() # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. SETTINGS = BotFrameworkAdapterSettings("3b6b88c3-b5e7-4202-9c65-e69d65e91220", "i4zTeVCDBKAPJGO6d.-_.B-6Vi05BR5mKk") ADAPTER = BotFrameworkAdapter(SETTINGS) # Catch-all for errors. async def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity( "To continue to run this bot, please fix the bot source code."
from flask import Flask, request, Response from botbuilder.core import BotFrameworkAdapter, BotFrameworkAdapterSettings, ConversationState,MemoryStorage from botbuilder.schema import Activity import asyncio from luis.luisApp import LuisConnect import os from logger.logger import Log app = Flask(__name__) loop = asyncio.get_event_loop() bot_settings = BotFrameworkAdapterSettings("985e09f6-a0d9-4db1-af68-fe3fd2e2b98a", "~P_k5KLvAWeNs_VI.GFbJi1-.0KBK1528C") bot_adapter = BotFrameworkAdapter(bot_settings) #CON_MEMORY = ConversationState(MemoryStorage()) luis_bot_dialog = LuisConnect() @app.route("/api/messages", methods=["POST"]) def messages(): if "application/json" in request.headers["content-type"]: log=Log() request_body = request.json user_says = Activity().deserialize(request_body) log.write_log(sessionID='session1',log_message="user says: "+str(user_says)) authorization_header = (request.headers["Authorization"] if "Authorization" in request.headers else "") async def call_user_fun(turncontext): await luis_bot_dialog.on_turn(turncontext)
from aiohttp import web from botbuilder.schema import Activity, ActivityTypes from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext, ConversationState, MemoryStorage, UserState, CardFactory) from bots import StateManagementBot relative_path = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(relative_path, "config.yaml") with open(path, 'r') as ymlfile: cfg = yaml.safe_load(ymlfile) PORT = cfg['Settings']['Port'] SETTINGS = BotFrameworkAdapterSettings(cfg['Settings']['AppId'], cfg['Settings']['AppPassword']) ADAPTER = BotFrameworkAdapter(SETTINGS) # Catch-all for errors. async def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f'\n [on_turn_error]: { error }', file=sys.stderr) # Send a message to the user await context.send_activity('Oops. Something went wrong!') # Clear out state await conversation_state.delete(context)
from flask import Flask, render_template, request, url_for, Response from models.counter import addVisitorRoot, viewVisitorRoot from http import HTTPStatus from twilio.twiml.messaging_response import MessagingResponse import asyncio import os from directLineAPI import DirectLineAPI from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext) from botbuilder.schema import Activity from bot import EchoBot bot = EchoBot() SETTINGS = BotFrameworkAdapterSettings(os.getenv("MicrosoftAppId", ""), os.getenv("MicrosoftAppPassword", "")) ADAPTER = BotFrameworkAdapter(SETTINGS) LOOP = asyncio.get_event_loop() botDirectLine = DirectLineAPI(os.getenv("MicrosoftDirectLineToken", "")) app = Flask(__name__) secretBot = os.getenv("BotSecretID", "Secret") @app.route("/") def hello(): addVisitorRoot() views = viewVisitorRoot() return "<h1 style='color:blue'>Hello There! Views: {0}</h1> <iframe src='https://webchat.botframework.com/embed/flask-sample-mongo-bot?s={1}' style='min-width: 400px; width: 100%; min-height: 500px;'></iframe>".format( views, secretBot)
MemoryStorage, TurnContext, BotFrameworkAdapter, ) from botbuilder.core.integration import aiohttp_error_middleware from botbuilder.schema import Activity, ActivityTypes from bots.bot import RestaurantBot from dialogs.main_dialog import MainDialog from dialogs.restaurant_finder_dialog import RestaurantFinderDialog from services.restaurant_recognizer import RestaurantRecognizer # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. SETTINGS = BotFrameworkAdapterSettings("", "") ADAPTER = BotFrameworkAdapter(SETTINGS) # Catch-all for errors. async def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity( "To continue to run this bot, please fix the bot source code."
from botbuilder.core import ( BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter, ) from botbuilder.schema import Activity from bots import ChildBot from config import DefaultConfig CONFIG = DefaultConfig() # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. SETTINGS = BotFrameworkAdapterSettings( app_id=CONFIG.APP_ID, app_password=CONFIG.APP_PASSWORD, ) ADAPTER = BotFrameworkAdapter(SETTINGS) # Catch-all for errors. async def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity(
from dialogs import ActivityRouterDialog, DialogSkillBotRecognizer from skill_adapter_with_error_handler import AdapterWithErrorHandler CONFIG = DefaultConfig() # Create MemoryStorage, UserState and ConversationState MEMORY = MemoryStorage() USER_STATE = UserState(MEMORY) CONVERSATION_STATE = ConversationState(MEMORY) # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. VALIDATOR = AllowedCallersClaimsValidator(CONFIG).claims_validator SETTINGS = BotFrameworkAdapterSettings( CONFIG.APP_ID, CONFIG.APP_PASSWORD, auth_configuration=AuthenticationConfiguration(claims_validator=VALIDATOR), ) ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE) # Create the Bot RECOGNIZER = DialogSkillBotRecognizer(CONFIG) ROUTER = ActivityRouterDialog(RECOGNIZER) BOT = SkillBot(CONVERSATION_STATE, ROUTER) # Listen for incoming requests on /api/messages async def messages(req: Request) -> Response: # Main bot message handler. if "application/json" in req.headers["Content-Type"]: body = await req.json()
MemoryStorage, TurnContext, UserState, ) from botbuilder.core.integration import aiohttp_error_middleware from botbuilder.schema import Activity, ActivityTypes from config import DefaultConfig from dialogs import UserProfileDialog from bots import DialogBot CONFIG = DefaultConfig() # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. SETTINGS = BotFrameworkAdapterSettings("37ce05ea-ce11-424d-9f56-8a90fc928a9c", "e~q8uMr_Tqpppc3.J1l2WwG-0.Qy14TWSA") ADAPTER = BotFrameworkAdapter(SETTINGS) # Catch-all for errors. async def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error]: { error }", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity( "To continue to run this bot, please fix the bot source code.")
from botbuilder.core import BotFrameworkAdapterSettings, BotFrameworkAdapter from botbuilder.core import TurnContext from botbuilder.schema import Activity, ActivityTypes from botbuilder.core.integration import aiohttp_error_middleware from aiohttp import web from aiohttp.web import Request, Response, json_response from report_bot import ReportBot PORT = 3978 APP_ID = os.getenv('AZURE_APP_ID') SECRET = os.getenv('AZURE_SECRET') SETTINGS = BotFrameworkAdapterSettings(APP_ID, SECRET) ADAPTER = BotFrameworkAdapter(SETTINGS) # https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/python/57.teams-conversation-bot/app.py # Catch-all for errors. async def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity(
from flask import Flask, request, Response from botbuilder.schema import Activity from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, ConversationState, UserState, MemoryStorage) import asyncio from bot import StateBot from botbuilder.azure import CosmosDbConfig, CosmosDbStorage app = Flask(__name__) loop = asyncio.get_event_loop() botadaptersettings = BotFrameworkAdapterSettings("", "") botadapter = BotFrameworkAdapter(botadaptersettings) memstore = MemoryStorage() constate = ConversationState(memstore) #userstate = UserState(memstore) key = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==" cosconfig = CosmosDbConfig("https://*****:*****@app.route("/api/messages", methods=["POST"]) def messages(): if "application/json" in request.headers["content-type"]: jsonmessage = request.json
from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, ConversationState, MemoryStorage, UserState, TurnContext) from botbuilder.schema import (Activity) from botbuilder.applicationinsights import ApplicationInsightsTelemetryClient from botbuilder.applicationinsights.flask import BotTelemetryMiddleware from dialogs import MainDialog from bots import DialogAndWelcomeBot LOOP = asyncio.get_event_loop() APP = Flask(__name__, instance_relative_config=True) APP.config.from_object('config.DefaultConfig') APP.wsgi_app = BotTelemetryMiddleware(APP.wsgi_app) SETTINGS = BotFrameworkAdapterSettings(APP.config['APP_ID'], APP.config['APP_PASSWORD']) ADAPTER = BotFrameworkAdapter(SETTINGS) # pylint:disable=unused-argument async def on_error(context: TurnContext, error: Exception): """ Catch-all for errors.""" # Send a message to the user await context.send_activity('Oops. Something went wrong!') # Clear out state await CONVERSATION_STATE.delete(context) ADAPTER.on_turn_error = on_error # Create MemoryStorage, UserState and ConversationState
from botbuilder.schema import Activity, ActivityTypes, ConversationReference from botbuilder.core import MemoryStorage, UserState from bot import MyBot from welcome import WelcomeUserBot from config import DefaultConfig """import asyncio from botdialog import BotDialog #dialog""" CONFIG = DefaultConfig() """CONMEMORY = ConversationState(MemoryStorage()) #dialog botdialog = BotDialog(CONMEMORY) #dialog""" # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD) ADAPTER = BotFrameworkAdapter(SETTINGS) # Catch-all for errors. async def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") await context.send_activity( "To continue to run this bot, please fix the bot source code.")
from flask import Flask, request, Response from botbuilder.schema import Activity from botbuilder.core import BotFrameworkAdapter, BotFrameworkAdapterSettings import asyncio from echobot import EchoBot app = Flask(__name__) loop = asyncio.get_event_loop() botadaptersettings = BotFrameworkAdapterSettings( "8d054fa1-23ec-43d1-bb8a-4dd80cdccc12", "2O-XN-Bybx6-DF_Xh805N.moi0.SPZ5b8c") botadapter = BotFrameworkAdapter(botadaptersettings) ebot = EchoBot() print("working#########################") @app.route("api/messages", methods=["POST"]) def messages(): if "application/json" in request.headers["content-type"]: jsonmessage = request.json else: return Response(status=415) activity = Activity().deserialize(jsonmessage) async def turn_call(turn_context): await ebot.on_turn(turn_context)
MemoryStorage, UserState, ) from botbuilder.schema import Activity from dialogs import MainDialog, BookingDialog from bots import DialogAndWelcomeBot from adapter_with_error_handler import AdapterWithErrorHandler from flight_booking_recognizer import FlightBookingRecognizer # Create the loop and Flask app LOOP = asyncio.get_event_loop() APP = Flask(__name__, instance_relative_config=True) APP.config.from_object("config.DefaultConfig") SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"]) # Create MemoryStorage, UserState and ConversationState MEMORY = MemoryStorage() USER_STATE = UserState(MEMORY) CONVERSATION_STATE = ConversationState(MEMORY) # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE) # Create dialogs and Bot RECOGNIZER = FlightBookingRecognizer(APP.config) BOOKING_DIALOG = BookingDialog() DIALOG = MainDialog(RECOGNIZER, BOOKING_DIALOG) BOT = DialogAndWelcomeBot(CONVERSATION_STATE, USER_STATE, DIALOG)
import copy import json from aiohttp import web from botbuilder.schema import (Activity, ActivityTypes, Attachment, ActionTypes, CardAction, CardImage, MediaUrl, ThumbnailUrl, Fact) from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext, ConversationState, MemoryStorage, UserState, CardFactory) """Import AdaptiveCard content from adjacent file""" APP_ID = '' APP_PASSWORD = '' PORT = 9000 SETTINGS = BotFrameworkAdapterSettings(APP_ID, APP_PASSWORD) ADAPTER = BotFrameworkAdapter(SETTINGS) # Create MemoryStorage, UserState and ConversationState memory = MemoryStorage() # Commented out user_state because it's not being used. # user_state = UserState(memory) conversation_state = ConversationState(memory) # Register both State middleware on the adapter. # Commented out user_state because it's not being used. # ADAPTER.use(user_state) ADAPTER.use(conversation_state) # Methods to generate cards