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()
def do_POST(self): body = self.rfile.read(int(self.headers['Content-Length'])) data = json.loads(str(body, 'utf-8')) activity = Activity.deserialize(data) self._adapter = BotFrameworkAdapter(APP_ID, APP_PASSWORD) self._adapter.on_receive = self.on_receive self._adapter.receive(self.headers.get("Authorization"), activity)
class BotRequestHandler(http.server.BaseHTTPRequestHandler): @staticmethod def __create_reply_activity(request_activity, text): return Activity(type=ActivityTypes.message, channel_id=request_activity.channel_id, conversation=request_activity.conversation, recipient=request_activity.from_property, from_property=request_activity.recipient, text=text, service_url=request_activity.service_url) def __handle_conversation_update_activity(self, activity: Activity): self.send_response(202) self.end_headers() if activity.members_added[0].id != activity.recipient.id: self._adapter.send([ BotRequestHandler.__create_reply_activity( activity, 'Hello and welcome to the Git bot! I will answer all your questions about GIT' ) ]) def __handle_message_activity(self, activity: Activity): self.send_response(200) self.end_headers() response = qna_response(activity.text) self._adapter.send([ BotRequestHandler.__create_reply_activity(activity, '> %s' % response) ]) def __unhandled_activity(self): self.send_response(404) self.end_headers() def on_receive(self, activity: Activity): if activity.type == ActivityTypes.conversation_update.value: self.__handle_conversation_update_activity(activity) elif activity.type == ActivityTypes.message.value: self.__handle_message_activity(activity) else: self.__unhandled_activity() def do_POST(self): body = self.rfile.read(int(self.headers['Content-Length'])) data = json.loads(str(body, 'utf-8')) activity = Activity.deserialize(data) self._adapter = BotFrameworkAdapter(APP_ID, APP_PASSWORD) self._adapter.on_receive = self.on_receive self._adapter.receive(self.headers.get("Authorization"), activity)
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, )
async def process_activity( channel_id: str, channel_data_tenant_id: str, conversation_tenant_id: str ): activity = None mock_claims = unittest.mock.create_autospec(ClaimsIdentity) mock_credential_provider = unittest.mock.create_autospec( BotFrameworkAdapterSettings ) sut = BotFrameworkAdapter(mock_credential_provider) async def aux_func(context): nonlocal activity activity = context.Activity await sut.process_activity( Activity( channel_id=channel_id, service_url="https://smba.trafficmanager.net/amer/", channel_data={"tenant": {"id": channel_data_tenant_id}}, conversation=ConversationAccount(tenant_id=conversation_tenant_id), ), mock_claims, aux_func, ) return activity
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
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
class BotRequestHandler(http.server.BaseHTTPRequestHandler): @staticmethod def __create_hero_cart(request_activity, title, url): return HeroCard(title="Test hero card image", subtitle="Testing subtitle", text="Here is some text", images=[CardImage()]) def __handle_conversation_update_activity(self, activity: Activity): self.send_response(202) self.end_headers() if activity.members_added[0].id != activity.recipient.id: self._adapter.send([ BotRequestHandler.__create_reply_activity( activity, 'Hello and welcome to the echo bot!') ]) def __handle_message_activity(self, activity: Activity): self.send_response(200) self.end_headers() self._adapter.send([ BotRequestHandler.__create_reply_activity( activity, 'You said: %s' % activity.text) ]) self._adapter.send() def __unhandled_activity(self): self.send_response(404) self.end_headers() def on_receive(self, activity: Activity): if activity.type == ActivityTypes.conversation_update.value: self.__handle_conversation_update_activity(activity) elif activity.type == ActivityTypes.message.value: self.__handle_message_activity(activity) else: self.__unhandled_activity() def do_POST(self): body = self.rfile.read(int(self.headers['Content-Length'])) data = json.loads(str(body, 'utf-8')) activity = Activity.deserialize(data) self._adapter = BotFrameworkAdapter(APP_ID, APP_PASSWORD) self._adapter.on_receive = self.on_receive self._adapter.receive(self.headers.get("Authorization"), activity)
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()
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
def get_creds_and_assert_values( turn_context: TurnContext, expected_app_id: str, expected_scope: str, creds_count: int = None, ): # pylint: disable=protected-access credential_cache = turn_context.adapter._app_credential_map cache_key = BotFrameworkAdapter.key_for_app_credentials( expected_app_id, expected_scope) credentials = credential_cache.get(cache_key) assert credentials TestBotFrameworkAdapter.assert_credentials_values( credentials, expected_app_id, expected_scope) if creds_count: assert creds_count == len(credential_cache)
def get_client_and_assert_values( turn_context: TurnContext, expected_app_id: str, expected_scope: str, expected_url: str, client_count: int, ): # pylint: disable=protected-access client_cache = turn_context.adapter._connector_client_cache cache_key = BotFrameworkAdapter.key_for_connector_client( expected_url, expected_app_id, expected_scope) client = client_cache.get(cache_key) assert client TestBotFrameworkAdapter.assert_connectorclient_vaules( client, expected_app_id, expected_url, expected_scope) assert client_count == len(client_cache)
async def callback(context: TurnContext): TestBotFrameworkAdapter.get_creds_and_assert_values( context, skill_1_app_id, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, 1, ) TestBotFrameworkAdapter.get_client_and_assert_values( context, skill_1_app_id, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, channel_service_url, 1, ) # pylint: disable=protected-access client_cache = context.adapter._connector_client_cache client = client_cache.get( BotFrameworkAdapter.key_for_connector_client( channel_service_url, skill_1_app_id, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, ) ) 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 ( AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE == 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 AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE == scope # Ensure the serviceUrl was added to the trusted hosts assert AppCredentials.is_trusted_service(channel_service_url)
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, )
BotFrameworkAdapterSettings, TurnContext, ) from botbuilder.schema import Activity, ActivityTypes from bot import MyBot # Create the loop and Flask app LOOP = asyncio.get_event_loop() APP = Flask(__name__, instance_relative_config=True) APP.config.from_object("config.DefaultConfig") # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"]) ADAPTER = BotFrameworkAdapter(SETTINGS) # Catch-all for errors. # pylint: disable=unused-argument async def on_error(self, 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) # Send a message to the user await context.send_activity("The bot encounted an error or bug.") await context.send_activity( "To continue to run this bot, please fix the bot source code.") # Send a trace activity if we're talking to the Bot Framework Emulator
from botbuilder.core import (BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter, ConversationState, MemoryStorage) from fastapi import FastAPI, Request, HTTPException from botbuilder.schema import Activity, ActivityTypes from bots import FAQBot from config import DefaultConfig import taiwan_bot_sheet CONFIG = DefaultConfig() # 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.") # Send a trace activity if we're talking to the Bot Framework Emulator
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("", "") 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='TSRsession', 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 aiohttp.web import Request, Response, json_response from botbuilder.core import (BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter, ShowTypingMiddleware) from botbuilder.core.integration import aiohttp_error_middleware from botbuilder.schema import Activity, ActivityTypes from bot import MyBot from config import DefaultConfig CONFIG = DefaultConfig() # 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.") # Send a trace activity if we're talking to the Bot Framework Emulator
import asyncio import sys from flask import Flask, request, Response from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, ConversationState, MemoryStorage, UserState, TurnContext) from botbuilder.schema import Activity from qna_bot import QnaBot 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"]) ADAPTER = BotFrameworkAdapter(SETTINGS) async def on_error(context: TurnContext, error: Exception): """Top level exception handler 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!') BOT = QnaBot(APP.config['KB_ID'], APP.config['ENDPOINT_KEY'], APP.config['HOST'])
from aiohttp.web import Request, Response, json_response from botbuilder.core import BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter, ConversationState, MemoryStorage, UserState from botbuilder.core.integration import aiohttp_error_middleware from botbuilder.schema import Activity, ActivityTypes from src.dialogs import MainDialog # from src.nlu import NLU from src import Bot from config import Config # Load the config and create the bot config = Config() # Init a Bot adapter https://aka.ms/about-bot-adapter settings = BotFrameworkAdapterSettings(config.APP_ID, config.APP_PASSWORD) ADAPTER = BotFrameworkAdapter(settings) # Catch-all for errors async def on_error(context: TurnContext, error_: Exception): """ Catch-all functions to write out errors on console log. NOTE: In production environment, logging should be done to Azure application insights. """ # Print the error into the logs print(f"\n [on_turn_error] unhandled error: {error_}", file=sys.stderr) traceback.print_exc() # Send a message to the user
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
TurnContext, BotFrameworkAdapterSettings, BotFrameworkAdapter, MemoryStorage, UserState, ConversationState ) from botbuilder.schema import Activity, ActivityTypes from config import AppConfig from translation import TranslatorMiddleware, TranslatorM from bots import TeamsQABot CONFIG = AppConfig() 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) # 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.") # Send a trace activity if we're talking to the Bot Framework Emulator if context.activity.channel_id == 'emulator': # Create a trace activity that contains the error object trace_activity = Activity(
async def test_continue_conversation_without_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, ) channel_service_url = "https://smba.trafficmanager.net/amer/" async def callback(context: TurnContext): TestBotFrameworkAdapter.get_creds_and_assert_values( context, skill_1_app_id, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, 1, ) TestBotFrameworkAdapter.get_client_and_assert_values( context, skill_1_app_id, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, channel_service_url, 1, ) # pylint: disable=protected-access client_cache = context.adapter._connector_client_cache client = client_cache.get( BotFrameworkAdapter.key_for_connector_client( channel_service_url, skill_1_app_id, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, ) ) 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 ( AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE == 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 AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE == scope # Ensure the serviceUrl was added to the trusted hosts assert AppCredentials.is_trusted_service(channel_service_url) refs = ConversationReference(service_url=channel_service_url) # Ensure the serviceUrl is NOT in the trusted hosts assert not AppCredentials.is_trusted_service(channel_service_url) await adapter.continue_conversation( refs, callback, claims_identity=skills_identity )
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
TurnContext, UserState, ) from botbuilder.core.inspection import InspectionMiddleware, InspectionState from botbuilder.schema import Activity, ActivityTypes from botframework.connector.auth import MicrosoftAppCredentials 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(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.") # Send a trace activity if we're talking to the Bot Framework Emulator
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) ADAPTER.on_turn_error = on_error
class BotApp: """A Flask echo bot.""" 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() def messages(self) -> Response: """Main bot message handler that listens for incoming requests.""" if "application/json" in request.headers["Content-Type"]: body = request.json else: return Response(status=415) activity = Activity().deserialize(body) auth_header = (request.headers["Authorization"] if "Authorization" in request.headers else "") async def aux_func(turn_context): await self.bot.on_turn(turn_context) try: task = self.loop.create_task( self.adapter.process_activity(activity, auth_header, aux_func)) self.loop.run_until_complete(task) return Response(status=201) except Exception as exception: raise exception @staticmethod def test() -> Response: """ For test only - verify if the flask app works locally - e.g. with: ```bash curl http://127.0.0.1:3978/api/test ``` You shall get: ``` test ``` """ return Response(status=200, response="test\n") def run(self, host=None) -> None: try: self.flask.run(host=host, debug=False, port=self.flask.config["PORT"]) # nosec debug except Exception as exception: raise exception