问题
What are the steps to create a push notification/proactive messaging bot using Python with microsoft bot framework? Since there's no official documentation yet, I don't really know where to start.
I have imported the following:
from botbuilder.schema import Activity, ActivityTypes, ConversationReference
How can it be used and what's a very simple example?
回答1:
I worked a sample demo which based on state management sample for you .
Pls follow the setps to make it work :
1.Adding code below into app.py
:
@APP.route("/api/notify", methods=["POST"])
def notify():
if request.headers["Content-Type"] == "application/json":
body = request.json
else:
return Response(status=415)
activity = Activity().deserialize(body)
auth_header = (
request.headers["Authorization"] if "Authorization" in request.headers else ""
)
async def aux_func(turn_context):
await BOT.on_turn(turn_context)
try:
task = LOOP.create_task(
ADAPTER.process_activity(activity, auth_header, aux_func)
)
LOOP.run_until_complete(task)
return Response(status=201)
except Exception as exception:
raise exception
2.Modify function on_message_activity
in state_management_bot.py
as code below
async def on_message_activity(self, turn_context: TurnContext):
# Get the state properties from the turn context.
if(turn_context.activity.channel_id != 'notify'):
await turn_context.send_activity("You asid:" + turn_context.activity.text);
else:
await turn_context.send_activity("You get a notify : "+ turn_context.activity.text);
- Run this sample locally on Azure bot emulator, click the message from bot and note the conversation id and serviceUrl :
Use postman or restclient to do a post call to trigger the notify endpoint with json content :
{
"text": "this is a notify sent from outside ",
"textFormat": "plain",
"type": "message",
"channelId": "notify",
"from": {
"id": "backend",
"name": "xxxxx",
"role": "xxxxxx"
},
"conversation": {
"id": "<conversation id>"
},
"recipient": {
"id": "",
"name": "bot",
"role": "bot"
},
"serviceUrl": "<service URL>"
}
Result :
来源:https://stackoverflow.com/questions/57961856/create-python-proactive-messaging-with-microsoft-bot-framework