Teams Bot 在尝试发回消息时抛出未经授权的错误
Teams Bot throws Unauthorized error when attempting to send message back
我正在尝试使用 Python 机器人框架 SDK 构建一个简单的 MS Teams 机器人。使用模拟器在本地测试我的机器人时,一切正常。我在此处 https://dev.botframework.com/bots 使用旧版门户注册了机器人,因为我不想创建 Azure 订阅。
我将应用程序 ID 和应用程序密码添加到机器人,并使用 API 网关(具有 HTTP 代理集成)将其部署在 EC2 机器上,以获取消息传递端点的 HTTPS url。
部署后,代码能够从开发框架页面上的测试功能和 Teams 上实际部署的应用程序接收和解析消息。但是,在尝试回复消息时,我收到了未经授权的错误消息。
这是堆栈跟踪:
[on_turn_error] unhandled error: Operation returned an invalid status code 'Unauthorized'
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_adapter.py", line 103, in run_pipeline
context, callback
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/middleware_set.py", line 69, in receive_activity_with_status
return await self.receive_activity_internal(context, callback)
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/middleware_set.py", line 79, in receive_activity_internal
return await callback(context)
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/activity_handler.py", line 28, in on_turn
await self.on_message_activity(turn_context)
File "/home/ec2-user/bot/bot.py", line 24, in on_message_activity
return await turn_context.send_activity(response)
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 165, in send_activity
result = await self.send_activities([activity_or_text])
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 198, in send_activities
return await self._emit(self._on_send_activities, output, logic())
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 276, in _emit
return await logic
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 193, in logic
responses = await self.adapter.send_activities(self, output)
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_framework_adapter.py", line 444, in send_activities
raise error
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_framework_adapter.py", line 431, in send_activities
activity.conversation.id, activity.reply_to_id, activity
File "/usr/local/lib/python3.7/site-packages/botframework/connector/aio/operations_async/_conversations_operations_async.py", line 533, in reply_to_activity
raise models.ErrorResponseException(self._deserialize, response)
botbuilder.schema._models_py3.ErrorResponseException: Operation returned an invalid status code 'Unauthorized'
我的应用代码是:
CONFIG = DefaultConfig()
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD,
CONFIG.APP_AUTH_TENANT, CONFIG.APP_OAUTH_ENDPOINT)
ADAPTER = BotFrameworkAdapter(SETTINGS)
# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
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
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)
ADAPTER.on_turn_error = on_error
APP_ID = SETTINGS.app_id
dynamodb = boto3.resource("dynamodb")
CONVERSATION_REFERENCES = dynamodb.Table("ConversationReferences")
# Create the Bot
BOT = MyBot(CONVERSATION_REFERENCES)
# Listen for incoming requests on /api/messages
async def messages(req):
print(f"Message Received - {str(datetime.now())}")
json_request = await req.json()
print(f"Request Body: {json_request}")
activity = Activity().deserialize(json_request)
print("Request successfully deserialized")
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
try:
print("Sending activity to adapter")
response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
if response:
return Response(status=response.status, text=response.body)
return Response(status=201)
except Exception as exception:
raise exception
async def health(req):
return Response(status=200, text="Working")
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
APP.router.add_get("/health", health)
if __name__ == "__main__":
web.run_app(APP)
我的机器人代码是:
class MyBot(ActivityHandler):
def __init__(self, conversation_references):
self.conversation_references = conversation_references
async def on_message_activity(self, turn_context: TurnContext):
print("Message received by bot adapter")
# The next two lines also cause an unauthorized error. I commented them out to try and simplify
# team_details = await teams.TeamsInfo.get_members(turn_context)
# user = team_details[1].email
user = "test@test.com"
conversation = self.conversation_references.get_item(Key={"user": user})
if "Item" in conversation:
response = "You are already registered"
else:
conversation = TurnContext.get_conversation_reference(turn_context.activity)
item = {"user": user, "conversation": conversation.as_dict()}
self.conversation_references.put_item(Item=item)
response = "You have been successfully registered!"
return await turn_context.send_activity(response)
更新:在本地测试时,我没有将app id和密码添加到模拟器中。当我这样做时,在调试模式下我收到以下错误消息:"An error occurred while POSTing "/INSPECT open" command to conversation xxxxxx|livechat: 400: The bot's Microsoft App ID or Microsoft App Password is incorrect."
不过,我 100% 确定 ID 和密码是正确的,因为我已经手动使用注册页面中的令牌端点来获取具有这些凭据的访问令牌。这可能与以下事实有关:在代码中和手动使用端点我可以指定目录(租户)ID,而我不能使用模拟器这样做。
另一个奇怪的地方是,当模拟器 returns 响应时,它实际上似乎并没有向我的本地端点发出请求,所以我什至不确定 400 响应来自哪里.
以下是您将从团队中获得的内容。
它具有关键的 serviceURL,它将用于连接回您的机器人,该机器人使用下面 json 中提供的其他参数部署在您的团队中,我已将其替换为 << 和 >> 之间的逻辑名称.
{ text: 'help',
textFormat: 'plain',
type: 'message',
timestamp: 2020-03-05T12:29:26.830Z,
localTimestamp: 2020-03-05T12:29:26.830Z,
id: '1583411366810',
channelId: 'msteams',
serviceUrl: 'https://smba.trafficmanager.net/emea/',
from:
{ id:
'<<Use ID>>',
name: '<<Display Name>>',
aadObjectId: '<<objectID>>' },
conversation:
{ conversationType: 'personal',
tenantId: '<<Microsoft Tenant ID>>',
id:
'<<Unique Conversation ID>>' },
recipient:
{ id: '<<BotID>>', name: 'Sybot' },
entities:
[ { locale: 'en-US',
country: 'US',
platform: 'Windows',
type: 'clientInfo' } ],
channelData: { tenant: { id: '<<Microsoft Tenant ID>>' } },
locale: 'en-US' }
收到此消息后,您必须使用以下代码使服务 url 成为受信任的 url,这样当您将消息发回给用户时,您就不会收到未经授权的错误.
const { MicrosoftAppCredentials } = require('botbuilder/node_modules/botframework-connector');
const { BotFrameworkAdapter } = require('botbuilder');
const { TurnContext } = require('botbuilder');
const adapter = new BotFrameworkAdapter({
appId: <<Your App ID>>,
appPassword: <<Your App Password>>,
});
turnContext = new TurnContext(adapter, contextActivity);
if (!MicrosoftAppCredentials.isTrustedServiceUrl(serviceUrl)) {
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
}
await context.sendActivity(`Hello World`);
您需要确保使用多租户 AAD 应用凭据,如 here 所述。
我正在尝试使用 Python 机器人框架 SDK 构建一个简单的 MS Teams 机器人。使用模拟器在本地测试我的机器人时,一切正常。我在此处 https://dev.botframework.com/bots 使用旧版门户注册了机器人,因为我不想创建 Azure 订阅。
我将应用程序 ID 和应用程序密码添加到机器人,并使用 API 网关(具有 HTTP 代理集成)将其部署在 EC2 机器上,以获取消息传递端点的 HTTPS url。
部署后,代码能够从开发框架页面上的测试功能和 Teams 上实际部署的应用程序接收和解析消息。但是,在尝试回复消息时,我收到了未经授权的错误消息。
这是堆栈跟踪:
[on_turn_error] unhandled error: Operation returned an invalid status code 'Unauthorized'
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_adapter.py", line 103, in run_pipeline
context, callback
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/middleware_set.py", line 69, in receive_activity_with_status
return await self.receive_activity_internal(context, callback)
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/middleware_set.py", line 79, in receive_activity_internal
return await callback(context)
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/activity_handler.py", line 28, in on_turn
await self.on_message_activity(turn_context)
File "/home/ec2-user/bot/bot.py", line 24, in on_message_activity
return await turn_context.send_activity(response)
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 165, in send_activity
result = await self.send_activities([activity_or_text])
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 198, in send_activities
return await self._emit(self._on_send_activities, output, logic())
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 276, in _emit
return await logic
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 193, in logic
responses = await self.adapter.send_activities(self, output)
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_framework_adapter.py", line 444, in send_activities
raise error
File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_framework_adapter.py", line 431, in send_activities
activity.conversation.id, activity.reply_to_id, activity
File "/usr/local/lib/python3.7/site-packages/botframework/connector/aio/operations_async/_conversations_operations_async.py", line 533, in reply_to_activity
raise models.ErrorResponseException(self._deserialize, response)
botbuilder.schema._models_py3.ErrorResponseException: Operation returned an invalid status code 'Unauthorized'
我的应用代码是:
CONFIG = DefaultConfig()
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD,
CONFIG.APP_AUTH_TENANT, CONFIG.APP_OAUTH_ENDPOINT)
ADAPTER = BotFrameworkAdapter(SETTINGS)
# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
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
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)
ADAPTER.on_turn_error = on_error
APP_ID = SETTINGS.app_id
dynamodb = boto3.resource("dynamodb")
CONVERSATION_REFERENCES = dynamodb.Table("ConversationReferences")
# Create the Bot
BOT = MyBot(CONVERSATION_REFERENCES)
# Listen for incoming requests on /api/messages
async def messages(req):
print(f"Message Received - {str(datetime.now())}")
json_request = await req.json()
print(f"Request Body: {json_request}")
activity = Activity().deserialize(json_request)
print("Request successfully deserialized")
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
try:
print("Sending activity to adapter")
response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
if response:
return Response(status=response.status, text=response.body)
return Response(status=201)
except Exception as exception:
raise exception
async def health(req):
return Response(status=200, text="Working")
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
APP.router.add_get("/health", health)
if __name__ == "__main__":
web.run_app(APP)
我的机器人代码是:
class MyBot(ActivityHandler):
def __init__(self, conversation_references):
self.conversation_references = conversation_references
async def on_message_activity(self, turn_context: TurnContext):
print("Message received by bot adapter")
# The next two lines also cause an unauthorized error. I commented them out to try and simplify
# team_details = await teams.TeamsInfo.get_members(turn_context)
# user = team_details[1].email
user = "test@test.com"
conversation = self.conversation_references.get_item(Key={"user": user})
if "Item" in conversation:
response = "You are already registered"
else:
conversation = TurnContext.get_conversation_reference(turn_context.activity)
item = {"user": user, "conversation": conversation.as_dict()}
self.conversation_references.put_item(Item=item)
response = "You have been successfully registered!"
return await turn_context.send_activity(response)
更新:在本地测试时,我没有将app id和密码添加到模拟器中。当我这样做时,在调试模式下我收到以下错误消息:"An error occurred while POSTing "/INSPECT open" command to conversation xxxxxx|livechat: 400: The bot's Microsoft App ID or Microsoft App Password is incorrect."
不过,我 100% 确定 ID 和密码是正确的,因为我已经手动使用注册页面中的令牌端点来获取具有这些凭据的访问令牌。这可能与以下事实有关:在代码中和手动使用端点我可以指定目录(租户)ID,而我不能使用模拟器这样做。
另一个奇怪的地方是,当模拟器 returns 响应时,它实际上似乎并没有向我的本地端点发出请求,所以我什至不确定 400 响应来自哪里.
以下是您将从团队中获得的内容。 它具有关键的 serviceURL,它将用于连接回您的机器人,该机器人使用下面 json 中提供的其他参数部署在您的团队中,我已将其替换为 << 和 >> 之间的逻辑名称.
{ text: 'help',
textFormat: 'plain',
type: 'message',
timestamp: 2020-03-05T12:29:26.830Z,
localTimestamp: 2020-03-05T12:29:26.830Z,
id: '1583411366810',
channelId: 'msteams',
serviceUrl: 'https://smba.trafficmanager.net/emea/',
from:
{ id:
'<<Use ID>>',
name: '<<Display Name>>',
aadObjectId: '<<objectID>>' },
conversation:
{ conversationType: 'personal',
tenantId: '<<Microsoft Tenant ID>>',
id:
'<<Unique Conversation ID>>' },
recipient:
{ id: '<<BotID>>', name: 'Sybot' },
entities:
[ { locale: 'en-US',
country: 'US',
platform: 'Windows',
type: 'clientInfo' } ],
channelData: { tenant: { id: '<<Microsoft Tenant ID>>' } },
locale: 'en-US' }
收到此消息后,您必须使用以下代码使服务 url 成为受信任的 url,这样当您将消息发回给用户时,您就不会收到未经授权的错误.
const { MicrosoftAppCredentials } = require('botbuilder/node_modules/botframework-connector');
const { BotFrameworkAdapter } = require('botbuilder');
const { TurnContext } = require('botbuilder');
const adapter = new BotFrameworkAdapter({
appId: <<Your App ID>>,
appPassword: <<Your App Password>>,
});
turnContext = new TurnContext(adapter, contextActivity);
if (!MicrosoftAppCredentials.isTrustedServiceUrl(serviceUrl)) {
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
}
await context.sendActivity(`Hello World`);
您需要确保使用多租户 AAD 应用凭据,如 here 所述。