8000 Added 23.facebook-events sample · snifhex/botbuilder-python@d5515ba · GitHub
[go: up one dir, main page]

Skip to content

Commit d5515ba

Browse files
author
Tracy Boehrer
committed
Added 23.facebook-events sample
1 parent d6d6213 commit d5515ba

File tree

7 files changed

+508
-0
lines changed

7 files changed

+508
-0
lines changed

samples/23.facebook-events/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Facebook events
2+
3+
Bot Framework v4 facebook events bot sample
4+
5+
This bot has been created using [Bot Framework](https://dev.botframework.com), is shows how to integrate and consume Facebook specific payloads, such as postbacks, quick replies and optin events. Since Bot Framework supports multiple Facebook pages for a single bot, we also show how to know the page to which the message was sent, so developers can have custom behavior per page.
6+
7+
More information about configuring a bot for Facebook Messenger can be found here: [Connect a bot to Facebook](https://docs.microsoft.com/en-us/azure/bot-service/bot-service-channel-connect-facebook)
8+
9+
## Running the sample
10+
- Clone the repository
11+
```bash
12+
git clone https://github.com/Microsoft/botbuilder-python.git
13+
```
14+
- Activate your desired virtual environment
15+
- Bring up a terminal, navigate to `botbuilder-python\samples\23.facebook-evbents` folder
16+
- In the terminal, type `pip install -r requirements.txt`
17+
- In the terminal, type `python app.py`
18+
19 8000 +
## Testing the bot using Bot Framework Emulator
20+
[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.
21+
22+
- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
23+
24+
### Connect to bot using Bot Framework Emulator
25+
- Launch Bot Framework Emulator
26+
- File -> Open Bot
27+
- Paste this URL in the emulator window - http://localhost:3978/api/messages
28+
29+
## Further reading
30+
31+
- [Bot Framework Documentation](https://docs.botframework.com)
32+
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
33+
- [Facebook Quick Replies](https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies/0)
34+
- [Facebook PostBack](https://developers.facebook.com/docs/messenger-platform/reference/webhook-events/messaging_postbacks/)
35+
- [Facebook Opt-in](https://developers.facebook.com/docs/messenger-platform/reference/webhook-events/messaging_optins/)
36+
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)

samples/23.facebook-events/app.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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 BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter
11+
from botbuilder.schema import Activity, ActivityTypes
12+
13+
from bots import FacebookBot
14+
15+
# Create the loop and Flask app
16+
LOOP = asyncio.get_event_loop()
17+
app = Flask(__name__, instance_relative_config=True)
18+
app.config.from_object("config.DefaultConfig")
19+
20+
# Create adapter.
21+
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
22+
SETTINGS = BotFrameworkAdapterSettings(app.config["APP_ID"], app.config["APP_PASSWORD"])
23+
ADAPTER = BotFrameworkAdapter(SETTINGS)
24+
25+
26+
# Catch-all for errors.
27+
async def on_error(self, context: TurnContext, error: Exception):
28+
# This check writes out errors to console log .vs. app insights.
29+
# NOTE: In production environment, you should consider logging this to Azure
30+
# application insights.
31+
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
32+
33+
# Send a message to the user
34+
await context.send_activity("The bot encountered an error or bug.")
35+
await context.send_activity("To continue to run this bot, please fix the bot source code.")
36+
# Send a trace activity if we're talking to the Bot Framework Emulator
37+
if context.activity.channel_id == 'emulator':
38+
# Create a trace activity that contains the error object
39+
trace_activity = Activity(
40+
label="TurnError",
41+
name="on_tur 1E80 n_error Trace",
42+
timestamp=datetime.utcnow(),
43+
type=ActivityTypes.trace,
44+
value=f"{error}",
45+
value_type="https://www.botframework.com/schemas/error"
46+
)
47+
# Send a trace activity, which will be displayed in Bot Framework Emulator
48+
await context.send_activity(trace_activity)
49+
50+
ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
51+
52+
# Create the Bot
53+
BOT = FacebookBot()
54+
55+
# Listen for incoming requests on /api/messages
56+
@app.route("/api/messages", methods=["POST"])
57+
def messages():
58+
# Main bot message handler.
59+
if "application/json" in request.headers["Content-Type"]:
60+
body = request.json
61+
else:
62+
return Response(status=415)
63+
64+
activity = Activity().deserialize(body)
65+
auth_header = (
66+
request.headers["Authorization"] if "Authorization" in request.headers else ""
67+
)
68+
69+
try:
70+
task = LOOP.create_task(
71+
ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
72+
)
73+
LOOP.run_until_complete(task)
74+
return Response(status=201)
75+
except Exception as exception:
76+
raise exception
77+
78+
79+
if __name__ == "__main__":
80+
try:
81+
app.run(debug=False, port=app.config["PORT"]) # nosec debug
82+
except Exception as exception:
83+
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 .facebook_bot import FacebookBot
5+
6+
__all__ = ["FacebookBot"]
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
from botbuilder.dialogs.choices import Choice, ChoiceFactory
5+
from botbuilder.core import ActivityHandler, MessageFactory, TurnContext, CardFactory
6+
from botbuilder.schema import ChannelAccount, CardAction, ActionTypes, HeroCard
7+
8+
FacebookPageIdOption = "Facebook Id"
9+
QuickRepliesOption = "Quick Replies"
10+
PostBackOption = "PostBack"
11+
12+
13+
class FacebookBot(ActivityHandler):
14+
async def on_members_added_activity(
15+
self, members_added: [ChannelAccount], turn_context: TurnContext
16+
):
17+
for member in members_added:
18+
if member.id != turn_context.activity.recipient.id:
19+
await turn_context.send_activity("Hello and welcome!")
20+
21+
async def on_message_activity(self, turn_context: TurnContext):
22+
if not await self._process_facebook_payload(turn_context, turn_context.activity.channel_data):
23+
await self._show_choices(turn_context)
24+
25+
async def on_event_activity(self, turn_context: TurnContext):
26+
await self._process_facebook_payload(turn_context, turn_context.activity.value)
27+
28+
async def _show_choices(self, turn_context: TurnContext):
29+
choices = [
30+
Choice(
31+
value=QuickRepliesOption,
32+
action=CardAction(
33+
title=QuickRepliesOption,
34+
type=ActionTypes.post_back,
35+
value=QuickRepliesOption
36+
)
37+
),
38+
Choice(
39+
value=FacebookPageIdOption,
40+
action=CardAction(
41+
title=FacebookPageIdOption,
42+
type=ActionTypes.post_back,
43+
value=FacebookPageIdOption
44+
)
45+
),
46+
Choice(
47+
value=PostBackOption,
48+
action=CardAction(
49+
title=PostBackOption,
50+
type=ActionTypes.post_back,
51+
value=PostBackOption
52+
)
53+
)
54+
]
55+
56+
message = ChoiceFactory.for_channel(
57+
turn_context.activity.channel_id,
58+
choices,
59+
"What Facebook feature would you like to try? Here are some quick replies to choose from!"
60+
)
61+
await turn_context.send_activity(message)
62+
63+
async def _process_facebook_payload(self, turn_context: TurnContext, data) -> bool:
64+
if "postback" in data:
65+
await self._on_facebook_postback(turn_context, data["postback"])
66+
return True
67+
elif "optin" in data:
68+
await self._on_facebook_optin(turn_context, data["optin"])
69+
return True
70+
elif "message" in data and "quick_reply" in data["message"]:
71+
await self._on_facebook_quick_reply(turn_context, data["message"]["quick_reply"])
72+
return True
73+
elif "message" in data and data["message"]["is_echo"]:
74+
await self._on_facebook_echo(turn_context, data["message"])
75+
return True
76+
77+
async def _on_facebook_postback(self, turn_context: TurnContext, facebook_postback: dict):
78+
# TODO: Your PostBack handling logic here...
79+
80+
reply = MessageFactory.text("Postback")
81+
await turn_context.send_activity(reply)
82+
await self._show_choices(turn_context)
83+
84+
async def _on_facebook_quick_reply(self, turn_context: TurnContext, facebook_quick_reply: dict):
85+
# TODO: Your quick reply event handling logic here...
86+
87+
if turn_context.activity.text == FacebookPageIdOption:
88+
reply = MessageFactory.text(
89+
f"This message comes from the following Facebook Page: {turn_context.activity.recipient.id}"
90+
)
91+
await turn_context.send_activity(reply)
92+
await self._show_choices(turn_context)
93+
elif turn_context.activity.text == PostBackOption:
94+
card = HeroCard(
95+
text="Is 42 the answer to the ultimate question of Life, the Universe, and Everything?",
96+
buttons=[
97+
CardAction(
98+
title="Yes",
99+
93C6 type=ActionTypes.post_back,
100+
value="Yes"
101+
),
102+
CardAction(
103+
title="No",
104+
type=ActionTypes.post_back,
105+
value="No"
106+
)
107+
]
108+
)
109+
reply = MessageFactory.attachment(CardFactory.hero_card(card))
110+
await turn_context.send_activity(reply)
111+
else:
112+
await turn_context.send_activity("Quick Reply")
113+
await self._show_choices(turn_context)
114+
115+
async def _on_facebook_optin(self, turn_context: TurnContext, facebook_optin: dict):
116+
# TODO: Your optin event handling logic here...
117+
await turn_context.send_activity("Opt In")
118+
pass
119+
120+
async def _on_facebook_echo(self, turn_context: TurnContext, facebook_message: dict):
121+
# TODO: Your echo event handling logic here...
122+
await turn_context.send_activity("Echo")
123+
pass

samples/23.facebook-events/config.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
""" Bot Configuration """
8+
9+
10+
class DefaultConfig:
11+
""" Bot Configuration """
12+
13+
PORT = 3978
14+
APP_ID = os.environ.get("MicrosoftAppId", "")
15+
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")

0 commit comments

Comments
 (0)
0