You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取组织内MS Teams用户列表并存储、推送通知?现有代码仅获取会话成员

获取组织内所有MS Teams用户并推送通知的解决方案

Hey there! I see you've got code that fetches members from a specific Teams conversation, but you need to scale this up to get all users in your organization and send them notifications. Let's walk through how to make this happen.

首先:现有代码的局限

Your current snippet uses connector.fetchMembers, which only pulls members from a single conversation (like a team channel or one-on-one chat). It doesn't access the full list of users in your organization—for that, we'll need to use the Microsoft Graph API.


步骤1:通过Microsoft Graph获取组织内所有用户

To get every user in your Teams tenant, you'll call Graph's GET /users endpoint. You'll need to authenticate your app with the right permissions first:

  • Use Application Permissions (not delegated) like User.Read.All so your bot can access user data without a signed-in user.
  • Make sure you've registered your app in Azure AD and granted these permissions (don't forget to grant admin consent!).

Here's a Node.js example using the Microsoft Graph SDK:

const { Client } = require('@microsoft/microsoft-graph-client');
const { ClientCredentialAuthenticationProvider } = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials');
const { ClientSecretCredential } = require('@azure/msal-node');

// Configure your Azure AD app credentials
const credential = new ClientSecretCredential(
  'YOUR_TENANT_ID',
  'YOUR_CLIENT_ID',
  'YOUR_CLIENT_SECRET'
);

const authProvider = new ClientCredentialAuthenticationProvider(credential, {
  scopes: ['https://graph.microsoft.com/.default']
});

const graphClient = Client.initWithMiddleware({ authProvider });

// Fetch all users in the organization
async function getAllOrgUsers() {
  try {
    const users = await graphClient.api('/users').get();
    return users.value; // Array of user objects with id, displayName, userPrincipalName, etc.
  } catch (err) {
    console.error('Error fetching users:', err);
    throw err;
  }
}

步骤2:向所有用户推送通知

Once you have the user list, you'll need to initiate a one-on-one conversation with each user to send your notification. The Bot Framework's connector.createConversation method lets you do this.

Important Notes:

  • Your bot must be published and available in your tenant.
  • Users don't need to have chatted with the bot before, but you'll need the right permissions (like TeamsActivity.Send as an application permission).

Here's how to send a notification to a single user—you can loop this over your user list:

const { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector');

// Initialize connector client
MicrosoftAppCredentials.trustServiceUrl('https://smba.trafficmanager.net/amer/'); // Adjust region if needed
const connector = new ConnectorClient(
  new MicrosoftAppCredentials('YOUR_BOT_APP_ID', 'YOUR_BOT_APP_PASSWORD'),
  { baseUri: 'https://smba.trafficmanager.net/amer/' }
);

async function sendNotificationToUser(user) {
  try {
    // Create a one-on-one conversation with the user
    const conversationParameters = {
      members: [
        {
          id: user.id // Use the user's ID from Graph
        }
      ],
      channelData: {
        tenant: {
          id: 'YOUR_TENANT_ID'
        }
      }
    };

    const conversationResponse = await connector.conversations.createConversation(conversationParameters);
    
    // Send the notification message
    const message = {
      type: 'message',
      text: 'Hello! This is a notification from your organization\'s bot.'
    };

    await connector.conversations.sendToConversation(conversationResponse.id, message);
    console.log(`Notification sent to ${user.displayName}`);
  } catch (err) {
    console.error(`Failed to send to ${user.displayName}:`, err);
  }
}

步骤3:整合流程

Put it all together to fetch users and send notifications in one go:

async function runNotificationWorkflow() {
  const orgUsers = await getAllOrgUsers();
  
  // Loop through each user and send notification
  for (const user of orgUsers) {
    await sendNotificationToUser(user);
    // Add a small delay to avoid hitting rate limits
    await new Promise(resolve => setTimeout(resolve, 100));
  }
}

// Run the workflow
runNotificationWorkflow();

Key Considerations

  • Rate Limits: Graph and Bot Framework have rate limits—add delays between requests or use batch operations to avoid being throttled.
  • Error Handling: Some users might have disabled bot notifications, or your bot might lack permissions for certain accounts. Always catch and log errors.
  • Permissions Double-Check: Make sure your bot's Azure AD app has all required permissions (both Graph and Bot Framework permissions) and admin consent is granted.

内容的提问来源于stack exchange,提问作者nguyendn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:07:23