10000 Merge pull request #654 from microsoft/josh/cherrypickScenario · TheCompuGuru/botbuilder-python@3fa310d · GitHub
[go: up one dir, main page]

Skip to content

Commit 3fa310d

Browse files
authored
Merge pull request microsoft#654 from microsoft/josh/cherrypickScenario
Adding new scenario for updated TeamsInfo helper
2 parents 1780305 + 9830352 commit 3fa310d

File tree

9 files changed

+210
-0
lines changed

9 files changed

+210
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# EchoBot
2+
3+
Bot Framework v4 echo bot sample.
4+
5+
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
6+
7+
## Running the sample
8+
- Clone the repository
9+
```bash
10+
git clone https://github.com/Microsoft/botbuilder-python.git
11+
```
12+
- Activate your desired virtual environment
13+
- Bring up a terminal, navigate to `botbuilder-python\samples\02.echo-bot` folder
14+
- In the terminal, type `pip install -r requirements.txt`
15+
- In the terminal, type `python app.py`
16+
17+
## Testing the bot using Bot Framework Emulator
18+
[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
19+
20+
- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
21+
22+
### Connect to bot using Bot Framework Emulator
23+
- Launch Bot Framework Emulator
24+
- Paste this URL in the emulator window - http://localhost:3978/api/messages
25+
26+
## Further reading
27+
28+
- [Bot Framework Documentation](https://docs.botframework.com)
29+
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
30+
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
import asyncio
5+
import sys
6+
from datetime import datetime
7+
from types import MethodType
8+
9+
from flask import Flask, request, Response
10+
from botbuilder.core import (
11+
BotFrameworkAdapterSettings,
12+
TurnContext,
13+
BotFrameworkAdapter,
14+
)
15+
from botbuilder.schema import Activity, ActivityTypes
16+
17+
from bots import CreateThreadInTeamsBot
18+
19+
# Create the loop and Flask app
20+
LOOP = asyncio.get_event_loop()
21+
APP = Flask(__name__, instance_relative_config=True)
22+
APP.config.from_object("config.DefaultConfig")
23+
24+
# Create adapter.
25+
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
26+
SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
27+
ADAPTER = BotFrameworkAdapter(SETTINGS)
28+
29+
30+
# Catch-all for errors.
31+
async def on_error( # pylint: disable=unused-argument
32+
self, context: TurnContext, error: Exception
33+
):
34+
# This check writes out errors to console log .vs. app insights.
35+
# NOTE: In production environment, you should consider logging this to Azure
36+
# application insights.
37+
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
38+
39+
# Send a message to the user
40+
await context.send_activity("The bot encountered an error or bug.")
41+
await context.send_activity(
42+
"To continue to run this bot, please fix the bot source code."
43+
)
44+
# Send a trace activity if we're talking to the Bot Framework Emulator
45+
if context.activity.channel_id == "emulator":
46+
# Create a trace activity that contains the error object
47+
trace_activity = Activity(
48+
label="TurnError",
49+
name="on_turn_error Trace",
50+
timestamp=datetime.utcnow(),
51+
type=ActivityTypes.trace,
52+
value=f"{error}",
53+
value_type="https://www.botframework.com/schemas/error",
54+
)
55+
# Send a trace activity, which will be displayed in Bot Framework Emulator
56+
await context.send_activity(trace_activity)
57+
58+
59+
ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
60+
61+
# Create the Bot
62+
BOT = CreateThreadInTeamsBot(APP.config["APP_ID"])
63+
64+
# Listen for incoming requests on /api/messages.s
65+
@APP.route("/api/messages", methods=["POST"])
66+
def messages():
67+
# Main bot message handler.
68+
if "application/json" in request.headers["Content-Type"]:
69+
body = request.json
70+
else:
71+
return Response(status=415)
72+
73+
activity = Activity().deserialize(body)
74+
auth_header = (
75+
request.headers["Authorization"] if "Authorization" in request.headers else ""
76+
)
77+
78+
try:
79+
task = LOOP.create_task(
80+
ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
81+
)
82+
LOOP.run_until_complete(task)
83+
return Response(status=201)
84+
except Exception as exception:
85+
raise exception
86+
87+
88+
if __name__ == "__main__":
89+
try:
90+
APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
91+
except Exception as exception:
92+
raise exception
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
from .create_thread_in_teams_bot import CreateThreadInTeamsBot
5+
6+
__all__ = ["CreateThreadInTeamsBot"]
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
from botbuilder.core import MessageFactory, TurnContext
5+
from botbuilder.core.teams import (
6+
teams_get_channel_id,
7+
TeamsActivityHandler,
8+
TeamsInfo
9+
)
10+
11+
12+
class CreateThreadInTeamsBot(TeamsActivityHandler):
13+
def __init__(self, id):
14+
self.id = id
15+
16+
async def on_message_activity(self, turn_context: TurnContext):
17+
message = MessageFactory.text("first message")
18+
channel_id = teams_get_channel_id(turn_context.activity)
19+
result = await TeamsInfo.send_message_to_teams_channel(turn_context, message, channel_id)
20+
21+
await turn_context.adapter.continue_conversation(result[0], self._continue_conversation_callback, self.id)
22+
23+
async def _continue_conversation_callback(self, turn_context):
24+
await turn_context.send_activity(MessageFactory.text("second message"))
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License.
4+
5+
import os
6+
7+
8+
class DefaultConfig:
9+
""" Bot Configuration """
10+
11+
PORT = 3978
12+
APP_ID = os.environ.get("MicrosoftAppId", "")
13+
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
botbuilder-core>=4.4.0b1
2+
flask>=1.0.3
Loading
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
{
2+
"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
3+
"manifestVersion": "1.5",
4+
"version": "1.0.0",
5+
"id": "<<YOUR-MICROSOFT-BOT-ID>>",
6+
"packageName": "com.teams.sample.conversationUpdate",
7+
"developer": {
8+
"name": "MentionBot",
9+
"websiteUrl": "https://www.microsoft.com",
10+
"privacyUrl": "https://www.teams.com/privacy",
11+
"termsOfUseUrl": "https://www.teams.com/termsofuser"
12+
},
13+
"icons": {
14+
"color": "color.png",
15+
"outline": "outline.png"
16+
},
17+
"name": {
18+
"short": "MentionBot",
19+
"full": "MentionBot"
20+
},
21+
"description": {
22+
"short": "MentionBot",
23+
"full": "MentionBot"
24+
},
25+
"accentColor": "#FFFFFF",
26+
"bots": [
27+
{
28+
"botId": "<<YOUR-MICROSOFT-BOT-ID>>",
29+
"scopes": [
30+
"groupchat",
31+
"team",
32+
"personal"
33+
],
34+
"supportsFiles": false,
35+
"isNotificationOnly": false
36+
}
37+
],
38+
"permissions": [
39+
"identity",
40+
"messageTeamMembers"
41+
],
42+
"validDomains": []
43+
}
Loading

0 commit comments

Comments
 (0)
0