Microsoft Teams Python Botbuilder主动消息传递

时间:2020-06-24 04:24:30

标签: python azure botframework microsoft-graph-api microsoft-teams

在Webex中,简单的事情现在在Microsoft世界中似乎相当复杂。 我特别希望做的是:

  1. 在Azure Bot框架中创建一个机器人(完成)
  2. 使用收件人电子邮件使用botbuilder sdk识别收件人ID
  3. 使用Botframework-Connector分别识别这些收件人,创建新对话并主动向他们发送消息

这是我到目前为止一直在使用的 https://pypi.org/project/botframework-connector/

from botbuilder.schema import *
from botframework.connector import ConnectorClient
from botframework.connector.auth import MicrosoftAppCredentials

APP_ID = 'azure_bot_app_id'
APP_PASSWORD = 'azure_bot_app_password'
SERVICE_URL = 'azure_bot_messaging_endpoint'
CHANNEL_ID = 'msteams'
BOT_ID = 'azure_bot_subscription_id'
RECIPIENT_ID = 'msteams_individual_user_id'

credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
connector = ConnectorClient(credentials, base_url=SERVICE_URL)

conversation = connector.conversations.create_conversation(ConversationParameters(
            bot=ChannelAccount(id=BOT_ID),
            members=[ChannelAccount(id=RECIPIENT_ID)]))

connector.conversations.send_to_conversation(conversation.id, Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text='Hello Person!'))

这是否接近正确的方法?

2 个答案:

答案 0 :(得分:1)

粗略地看一下就可以了(我在Python中不工作,因此无法实际运行该示例)。在TrustServiceUrl调用中,确实看起来缺少一件事。有关详细信息,请参见here

答案 1 :(得分:0)

这是我发现使其工作最简单的方法。

from config import DefaultConfig

from botframework.connector.connector_client import ConnectorClient
from botframework.connector.models import ConversationParameters
from botframework.connector.auth.microsoft_app_credentials import MicrosoftAppCredentials
from botbuilder.core import  MessageFactory
from botbuilder.schema import ChannelAccount

CONFIG = DefaultConfig()

recipient_id = <<RECIPIENT_ID>>

to = ChannelAccount(id=recipient_id)
bot_channel = ChannelAccount(id='msteams')

MicrosoftAppCredentials.trust_service_url(CONFIG.SERVICE_URL)
credentials = MicrosoftAppCredentials(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
conn_client = ConnectorClient(credentials, CONFIG.SERVICE_URL)

message_activity = MessageFactory.text(f"Personal message from the Bot!");
 
conversation_params = ConversationParameters(members=[to], channel_data={ 'tenant': { 'id': CONFIG.TENANT_ID } })

conversation = conn_client.conversations.create_conversation(conversation_params)

conn_client.conversations.send_to_conversation(conversation.id, message_activity)

很容易推断所有大写变量。

<<RECIPIENT_ID>>是您要发送消息的用户的MS Teams ID。

希望这会有所帮助。

MSFT在Python中没有提供好的示例。