Python connection Webhook problem

Asked

Viewed 106 times

4

I have a doubt in my code.

I am using an example code and tried to apply to create a json template on the local machine. Follow what is working. It is located [at this link]( https://github.com/svet4/shipping-costs-sample):

#!/usr/bin/env python

import urllib
import json
import os

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():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def makeWebhookResult(req):
    if req.get("result").get("action") != "shipping.cost":
        return {}
    result = req.get("result")
    parameters = result.get("parameters")
    zone = parameters.get("shipping-zone")

    cost = {'Europe':100, 'North America':200, 'South America':300, 'Asia':400, 'Africa':500}

    speech = "The cost of shipping to " + zone + " is " + str(cost[zone]) + " euros."

    print("Response:")
    print(speech)

    return {
        "speech": speech,
        "displayText": speech,
        #"data": {},
        # "contextOut": [],
        "source": "apiai-onlinestore-shipping"
    }


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')

Code that doesn’t work

#!/usr/bin/env python

import urllib
import json
import os
import firebase
import urllib3

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():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def makeWebhookResult(req):

    action = req.get("result").get("action")


    if (action != "curso.valor") and (action != "translate.text") and (action !="planeta.temperatura" and (action != "pedido.gravar"):
        return {}
    result = req.get("result")
    parameters = result.get("parameters")

    # Curso

    if(action == "curso.valor"):
        curso = parameters.get("curso")

        #cost = {'R':100, 'Python':200, 'Machine Learning':300, 'Hadoop':400 }
        from firebase import firebase
        firebase = firebase.FirebaseApplication('https://dsa-bot-fabio.firebaseio.com', None)
        preco = firebase.get("/Cursos", Curso+"/Preco")

    if curso:
        speech = "O valor do curso " + curso + " e " + str(preco) + " reais."
    else:
        speech = "Qual Curso? Escolha entre: " + str(cost.keys())

     #tradução
    if(action =="translate.text"):
        text = parameters.get("text")
        language = parameters.get("to").get("lang")
        speech = text + " em " + language + " eh " + text[::-1]

    #Temperatura planeta
    if(action == "planeta.temperatura"):
        planeta = parameters.get("planeta")
        if(planeta != "Marte"):
            speech = "Ainda não medimos temperatura para " + planeta
        else:
            url="http://marsweather.ingenology.com/v1/latest/?format=json"
            http = urllib3.PoolManager()
            r=http.request('GET', url)
            data = json.loads(r.data.decode('utf-8'))
            temperatura_minima= str(data.get("Report").get("min_temp"))
            temperatura_maxima=str(data.get("Report").get("max_temp"))
            speech = "Previsao para {}: minima de {} e maxima de {}".format(planeta, temperatura_minima temperatura_maxima)

    #Gravação de pedido
    if(action =="pedido.gravar")
        from firebase import firebase
        from firebase.firebase import FirebaseApplication, FirebaseAuthentication


        authentication = FirebaseAuthentication('QuRhyzqXXn7s5pX2gEcdLnzC3o66mi2rmb92DcwO', True, True)
        firebase = firebase.FirebaseApplication('https://dsa-bot-fabio.firebaseio.com', authentication)

        parameters =  result.get("context")[0].get("parameters")
        nome = parameters.get("nome")
        tamanho_pao = parameters.get("tamanho_pao")
        tipo_pao = parameters.get("tipo_pao")
        recheio = parameters.get("recheio")
        queijo = "não"
        dobro_queijo = "não"
        if(parameters.get("dobro_queijo")):
            queijo = "sim"
            dobro_queijo = parameters.get("dobro_queijo")

        pedido = {"nome": nome, "tamanho_pao": tamanho_pao, "tipo_pao": tipo_pao, "queijo": queijo, "dobro_queijo": dobro_queijo, "recheio": recheio}
        result = firebase.post("/Pedidos", pedido)
        speech = "Anote seu pedido: {}. Volte sempre!".format(result['name'])







    print("Response:")
    print(speech)

    return {
        "speech": speech,
        "displayText": speech,
        #"data": {},
        # "contextOut": [],
        "source": "apiai-onlinestore-shipping"
    }


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')

The Mistake that comes to me is this:

File "C:\Users\fabio\dsa-bot-fabio\app.py", line 37
if (action != "curso.valor") and (action != "translate.text") and (action !="planeta.temperatura" and (action != "pedido.gravar"):

^
IndentationError: unindent does not match any outer indentation level
[Finished in 0.4s with exit code 1]

If anyone can help I’d appreciate it.

1 answer

3

The mistake is clear, caused by something treacherous:

IndentationError: unindent does not match any outer indentation level

In this line:

File "C:\Users\fabio\dsa-bot-fabio\app.py", line 37
if (action != "curso.valor") and (action != "translate.text") and (action !="planeta.temperatura" and (action != "pedido.gravar"):

possibly this if is indented with symbols different from the others. For example, the file indentation is done with 4 spaces, but you used tab on the line.

Some editors have the option to change all commands tab by spaces to avoid this error. It would be good to enable this option.

In any case, delete the indentation of the line and do it again. If you fail with tab, do only using spaces.


Correcting in Sublime Text:

  • View -> Indentation
  • Where does it say
    • Indent using Spaces [x]
    • Tab width: 2
  • Weaning Convert Indentation to Tabs
    • Tab width: 4
    • Convert Indentation to Spaces

Use Ctrl + I to reindentate the code.

  • But strange to give this problem, being that in the other code the spacing is the same no? I’m using the sublime to run the code.

  • It is. See my edition if it helps you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.