После того, как пользователь устанавливает мое приложение и бот Teams, я фиксирую исходное событие разговора и отправляю уведомление на основной канал пользователей, используя эту ссылку.
Однако, если я перезагружаю свой сервер и запускаю тот же код, Я получаю сообщение об ошибке, что бот не авторизован.
Я звоню MicrosoftAppCredentials.trustedServiceUrl()
прямо перед вызовом turnContext.sendActivity()
, как указано в документации https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/javascript_nodejs/16.proactive-messages#avoiding -permission-related-errors . И вызов MicrosoftAppCredentials.isTrustedServiceUrl
возвращает true
прямо перед вызовом turnContext.sendActivity
.
Я в основном скопировал код из этого проекта для своей реализации.
{ Error: Authorization has been denied for this request.
at new RestError (...../node_modules/@azure/ms-rest-js/lib/restError.ts:18:5)
at ..../node_modules/@azure/ms-rest-js/lib/policies/deserializationPolicy.ts:117:27
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
code: undefined,
statusCode: 401,
request:
WebResource {
streamResponseBody: false,
url: 'https://smba.trafficmanager.net/amer/v3/conversations/{convo ID}%40thread.skype/activities/{activiyID}',
method: 'POST',
headers: HttpHeaders { _headersMap: [Object] },
body: '{"type":"message","serviceUrl":"https://smba.trafficmanager.net/amer/","channelId":"msteams","from":{"id":"{ID}","name":"CrossLead Dev Local"},"conversation":{"isGroup":true,"conversationType":"channel","id":"{ID}","tenantId":"{ID}"},"recipient":{"id":"{ID}","aadObjectId":"{ID}"},"text":"The bot encountered an error or bug.","inputHint":"acceptingInput","replyToId":"{ID}"}',
query: undefined,
formData: undefined,
withCredentials: false,
abortSignal: undefined,
timeout: 0,
onUploadProgress: undefined,
onDownloadProgress: undefined,
operationSpec:
{ httpMethod: 'POST',
path: 'v3/conversations/{conversationId}/activities/{activityId}',
urlParameters: [Array],
requestBody: [Object],
responses: [Object],
serializer: [Object] } },
response:
{ body: '{"message":"Authorization has been denied for this request."}',
headers: HttpHeaders { _headersMap: [Object] },
status: 401 },
body: { message: 'Authorization has been denied for this request.' } }
Это все еще мое доказательство реализации концепции, поэтому все значения жестко заданы, чтобы упростить ее.
const msBotAdapter = new BotFrameworkAdapter({
appId: {ID as string}
appPassword: {ID as string},
});
//Some people also said to do this, but never used it anywhere. It doesn't seem to help
const msCreditials = new MicrosoftAppCredentials(
{ID as string},
{ID as string}
);
//Save Conversation Reference from when the app was installed into teams
const conversationReference: {
[key: string]: Partial<ConversationReference>;
} = {
activityId: '{activity ID}',
//@ts-ignore
user: {
id:
'{ID}',
aadObjectId: '{ID}',
},
bot: {
id: '{Bot Id}',
name: '{Bot Name}',
},
//@ts-ignore
conversation: {
isGroup: true,
conversationType: 'channel',
tenantId: '{tenant ID}',
id: '19:{ID}@thread.skype',
},
channelId: 'msteams',
serviceUrl: 'https://smba.trafficmanager.net/amer/',
};
const postMessage = async () => {
MicrosoftAppCredentials.trustServiceUrl(conversationReference.serviceUrl);
await msBotAdapter.continueConversation(
conversationReference as any,
async turnContext => {
// If you encounter permission-related errors when sending this message, see
// https://aka.ms/BotTrustServiceUrl
await turnContext.sendActivity('test message');
}
);
}