-
Notifications
You must be signed in to change notification settings - Fork 724
/
teams_conversation_bot.py
227 lines (191 loc) · 8.46 KB
/
teams_conversation_bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import json
from typing import List
from botbuilder.core import CardFactory, TurnContext, MessageFactory
from botbuilder.core.teams import TeamsActivityHandler, TeamsInfo
from botbuilder.schema import CardAction, HeroCard, Mention, ConversationParameters, Attachment, Activity
from botbuilder.schema.teams import TeamInfo, TeamsChannelAccount
from botbuilder.schema._connector_client_enums import ActionTypes
ADAPTIVECARDTEMPLATE = "resources/UserMentionCardTemplate.json"
class TeamsConversationBot(TeamsActivityHandler):
def __init__(self, app_id: str, app_password: str):
self._app_id = app_id
self._app_password = app_password
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:
await turn_context.send_activity(
f"Welcome to the team { member.given_name } { member.surname }. "
)
async def on_message_activity(self, turn_context: TurnContext):
TurnContext.remove_recipient_mention(turn_context.activity)
text = turn_context.activity.text.strip().lower()
if "mention me" in text:
await self._mention_adaptive_card_activity(turn_context)
return
if "mention" in text:
await self._mention_activity(turn_context)
return
if "update" in text:
await self._send_card(turn_context, True)
return
if "message" in text:
await self._message_all_members(turn_context)
return
if "who" in text:
await self._get_member(turn_context)
return
if "delete" in text:
await self._delete_card_activity(turn_context)
return
await self._send_card(turn_context, False)
return
async def _mention_adaptive_card_activity(self, turn_context: TurnContext):
TeamsChannelAccount: member = None
try:
member = await TeamsInfo.get_member(
turn_context, turn_context.activity.from_property.id
)
except Exception as e:
if "MemberNotFoundInConversation" in e.args[0]:
await turn_context.send_activity("Member not found.")
return
else:
raise
card_path = os.path.join(os.getcwd(), ADAPTIVECARDTEMPLATE)
with open(card_path, "rb") as in_file:
template_json = json.load(in_file)
for t in template_json["body"]:
t["text"] = t["text"].replace("${userName}", member.name)
for e in template_json["msteams"]["entities"]:
e["text"] = e["text"].replace("${userName}", member.name)
e["mentioned"]["id"] = e["mentioned"]["id"].replace("${userUPN}", member.user_principal_name)
e["mentioned"]["id"] = e["mentioned"]["id"].replace("${userAAD}", member.additional_properties["aadObjectId"])
e["mentioned"]["name"] = e["mentioned"]["name"].replace("${userName}", member.name)
adaptive_card_attachment = Activity(
attachments=[CardFactory.adaptive_card(template_json)]
)
await turn_context.send_activity(adaptive_card_attachment)
async def _mention_activity(self, turn_context: TurnContext):
mention = Mention(
mentioned=turn_context.activity.from_property,
text=f"<at>{turn_context.activity.from_property.name}</at>",
type="mention",
)
reply_activity = MessageFactory.text(f"Hello {mention.text}")
reply_activity.entities = [Mention().deserialize(mention.serialize())]
await turn_context.send_activity(reply_activity)
async def _send_card(self, turn_context: TurnContext, isUpdate):
buttons = [
CardAction(
type=ActionTypes.message_back,
title="Message all members",
text="messageallmembers",
),
CardAction(type=ActionTypes.message_back, title="Who am I?", text="whoami"),
CardAction(type=ActionTypes.message_back, title="Find me in Adaptive Card", text="mention me"),
CardAction(
type=ActionTypes.message_back, title="Delete card", text="deletecard"
),
]
if isUpdate:
await self._send_update_card(turn_context, buttons)
else:
await self._send_welcome_card(turn_context, buttons)
async def _send_welcome_card(self, turn_context: TurnContext, buttons):
buttons.append(
CardAction(
type=ActionTypes.message_back,
title="Update Card",
text="updatecardaction",
value={"count": 0},
)
)
card = HeroCard(
title="Welcome Card", text="Click the buttons.", buttons=buttons
)
await turn_context.send_activity(
MessageFactory.attachment(CardFactory.hero_card(card))
)
async def _send_update_card(self, turn_context: TurnContext, buttons):
data = turn_context.activity.value
data["count"] += 1
buttons.append(
CardAction(
type=ActionTypes.message_back,
title="Update Card",
text="updatecardaction",
value=data,
)
)
card = HeroCard(
title="Updated card", text=f"Update count {data['count']}", buttons=buttons
)
updated_activity = MessageFactory.attachment(CardFactory.hero_card(card))
updated_activity.id = turn_context.activity.reply_to_id
await turn_context.update_activity(updated_activity)
async def _get_member(self, turn_context: TurnContext):
TeamsChannelAccount: member = None
try:
member = await TeamsInfo.get_member(
turn_context, turn_context.activity.from_property.id
)
except Exception as e:
if "MemberNotFoundInConversation" in e.args[0]:
await turn_context.send_activity("Member not found.")
else:
raise
else:
await turn_context.send_activity(f"You are: {member.name}")
async def _message_all_members(self, turn_context: TurnContext):
team_members = await self._get_paged_members(turn_context)
for member in team_members:
conversation_reference = TurnContext.get_conversation_reference(
turn_context.activity
)
conversation_parameters = ConversationParameters(
is_group=False,
bot=turn_context.activity.recipient,
members=[member],
tenant_id=turn_context.activity.conversation.tenant_id,
)
async def get_ref(tc1):
conversation_reference_inner = TurnContext.get_conversation_reference(
tc1.activity
)
return await tc1.adapter.continue_conversation(
conversation_reference_inner, send_message, self._app_id
)
async def send_message(tc2: TurnContext):
return await tc2.send_activity(
f"Hello {member.name}. I'm a Teams conversation bot."
) # pylint: disable=cell-var-from-loop
await turn_context.adapter.create_conversation(
conversation_reference, get_ref, conversation_parameters
)
await turn_context.send_activity(
MessageFactory.text("All messages have been sent")
)
async def _get_paged_members(
self, turn_context: TurnContext
) -> List[TeamsChannelAccount]:
paged_members = []
continuation_token = None
while True:
current_page = await TeamsInfo.get_paged_members(
turn_context, continuation_token, 100
)
continuation_token = current_page.continuation_token
paged_members.extend(current_page.members)
if continuation_token is None:
break
return paged_members
async def _delete_card_activity(self, turn_context: TurnContext):
await turn_context.delete_activity(turn_context.activity.reply_to_id)