Как создать простой скайп бот с python и каркасом бота - PullRequest
0 голосов
/ 22 ноября 2018

Я пытаюсь создать очень простого бота в скайпе с помощью botframework с использованием python.Вот шаги, которые я сделал.

  • Создан бот каналов в ресурсах.

enter image description here

  • Создан простой веб-сервис на Python, использующий колбу для получения сообщения от бота.Выставил его через ngrok и добавил то же самое в конечную точку обмена сообщениями.

enter image description here

  • Я тестировал бота из веб-чатаи я получаю json в моем веб-сервисе python

    {
    "recipient": {
    "id": "txBot@b0X6R31x6uQ", 
    "name": "txBot"
     }, 
    "from": {
    "id": "1xFUIEqdQfv", 
    "name": "You"
     }, 
     "entities": [
        {
        "supportsTts": true, 
        "supportsListening": true, 
        "type": "ClientCapabilities", 
        "requiresBotState": true
        }
     ], 
    "locale": "en", 
    "timestamp": "2018-11-22T13:00:42.9086958Z", 
    "channelId": "webchat", 
    "channelData": {
    "clientActivityId": "1542891640077.5912976099256072.0"
    }, 
    "conversation": {
        "id": "b5b52b9e464b4e958b1219dadedfffce"
    }, 
    "serviceUrl": "https://webchat.botframework.com/", 
    "text": "hello from test", 
    "textFormat": "plain", 
    "type": "message", 
    "id": "b5b52b9e464b4e958b1219dadedfffce|0000002"
    }
    
  • Я могу обработать этот json и получить пользовательский ввод "hello from test" в этом примере на мой веб-сервис.

То, что я хочу сделать, это вернуть то же самое моему боту в веб-чате из python.

Я также ссылался на приведенный ниже учебник.Я могу отправить ответ обратно, но я не получаю его в боте.

Python-код серверной части, как показано ниже

import urllib
import json

import requests
import urllib2, json
from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)


@app.route('/webhook', methods=['POST'])
def webhook():
    print "came inside"
    req = request.get_json(silent=True, force=True)
    print("Request:")
    print(json.dumps(req, indent=4))
    service_url=""
    if req['type']=='conversationUpdate':
            return ''

    else:
            print "got input as : ",str(req['text'])
            payload = build_text_message_payload(req, req['text'])
            print "---- calling service url ----"
            #service_url = build_service_url2(req['serviceUrl'],req['conversation']['id'],req['id'])
            service_url = build_service_url2(req['serviceUrl'],req['conversation']['id'])


    print "---- Payload ----"
    print payload
    # where we are going to send our request
    print "---- Service url ----"
    print service_url
    # let's send the message
    response = send_to_conversation(service_url, payload)

    print "****************"
    print response
    # always return a response

    #print get_auth_token()

    return "success"



def build_text_message_payload(data, text):
    """Creates a text only message dict"""
    payload = {
    'type': 'message/text',
    'from': {
        'id': data['recipient']['id'],
        'name': data['recipient']['name'],
    },
    'recipient': {
        'id': data['from']['id'],

        'name': data['from']['name'],
    },
    'text': text,
}
    return payload






def build_service_url2(service_url, cid):
    """build the service url"""
    service_url = '{0}v3/conversations/{1}/activities'.format(
    service_url,
    cid
)
    return service_url

def send_to_conversation(service_url, payload):

  url="https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token"
  headers1={'Content-Type':'application/x-www-form-urlencoded'}

  data=urllib.urlencode({'grant_type':'client_credentials','client_id':'jhxzxk1b2-1jjk-44b4-88bd-566d09crs4sg','client_secret':'lpfgrpDBPxjsLLFC41}@','scope':'https://api.botframework.com/.default'}
  req = urllib2.Request(url, headers=headers1, data=data)
  resp=urllib2.urlopen(req)
  ans=resp.read()
  ans=json.loads(ans)
  token=ans['access_token']
  full_token="Bearer "+token
  headers = {
    "Content-Type": "application/json",
    "Authorization": full_token
}
  payload = json.dumps(payload)
  response = requests.post(
    service_url,
    data=payload,
    headers=headers
)
  print response.text
  return response



if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    print "Starting app on port %d" % port

    app.run(debug=True, port=port, host='0.0.0.0')

Я получаю ответ как 200, как только я отправляю ответ, но не получаю ответ в чате.Это ответ, который я получаю в коде Python

{
  "id":"b5b52b9e464b4e958b1219dadedfffce|0000003"
}

Что здесь не так?Нет ответа вообще

enter image description here

Получил эту ссылку для этой реализации.https://chatbotslife.com/microsoft-bot-framework-on-a-bottle-13fdcc3e04e

...