Search code examples
python-3.xbotframeworkmicrosoft-teamsmicrosoft-graph-teams

How to proactively send a message to a teams channel


I can't seem to figure out how to proactively message a MS teams channel using a Python Bot (botframework).

  1. An user installs my third-party MS teams bot, adding it to one of their Teams channels.
  2. My Bot needs to send ad-hoc messages as part of an event from an unrelated back-end system.

The botframework does not let you message channels at will, it needs a conversation reference. You can get a conversation reference in various ways, such as someone messaging the bot, or fetching the list of channels and constructing a conversationId from that.

Reading the documentation

The documentation will have you believe that it is in fact possible to send message at will, using the following steps:

  1. Get the user ID or team/channel ID (if needed).
  2. Create the conversation or conversation thread (if needed).
  3. Get the conversation ID.
  4. Send the message.

For step 1, how/when do I get the channel ID if there are no events that my Bot has been added to a channel?

For step 2, how do I create a conversation if I don't know what team channels there are?

Conclusion

Does someone know how to send a message to a MS Teams channel using a Python app/bot? It should not require user interaction. The app/bot gets added to a Teams channel, and it should immediately post a message inside this channel.


Solution

  • Turns out the issue was that my on_teams_members_added() was not getting called because I kept deleting the app within Teams instead of uninstalling.

    Make sure to:

    1. Click on the ... overflow menu next to the team name
    2. Pick Manage Team
    3. Select the "Apps" tab
    4. Click the trash icon to remove the app from that team
    5. Then try to install the app again

    With this code you can send a channel message when the Bot enters the channel:

    async def on_teams_members_added(  # pylint: disable=unused-argument
        self,
        teams_members_added: [TeamsChannelAccount],
        team_info: TeamInfo,
        turn_context: TurnContext,
    ):
        for member in teams_members_added:
            if member.id == turn_context.activity.recipient.id and team_info is not None:
                # bot entered a Teams channel
                await turn_context.send_activity("Hello channel! I have just been added.")
    

    Your handler needs to inherit from TeamsActivityHandler.