#!/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 = processRequest(req)

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


def processRequest(req):
    if req.get("result").get("action") != "yahooWeatherForecast":
        return {}
    baseurl = "https://query.yahooapis.com/v1/public/yql?"
    yql_query = makeYqlQuery(req)
    if yql_query is None:
        return {}
    yql_url = baseurl + urllib.urlencode({'q': yql_query}) + "&format=json"
    result = urllib.urlopen(yql_url).read()
    data = json.loads(result)
    res = makeWebhookResult(data)
    return res


def makeYqlQuery(req):
    result = req.get("result")
    parameters = result.get("parameters")
    city = parameters.get("geo-city")
    if city is None:
        return None

    return "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='" + city + "')"


def makeWebhookResult(data):
    query = data.get('query')
    if query is None:
        return {}

    result = query.get('results')
    if result is None:
        return {}

    channel = result.get('channel')
    if channel is None:
        return {}

    item = channel.get('item')
    location = channel.get('location')
    units = channel.get('units')
    if (location is None) or (item is None) or (units is None):
        return {}

    condition = item.get('condition')
    if condition is None:
        return {}

    # print(json.dumps(item, indent=4))

    speech = "Today in " + location.get('city') + ": " + condition.get('text') + \
             ", the temperature is " + condition.get('temp') + " " + units.get('temperature')

    print("Response:")
    print(speech)
    
       kik_message = [
        {
            "type": "text",
            "body": "Here's the picture of item " + item
        },
        {
            "type": "picture",
            "picUrl": "https://raw.githubusercontent.com/svet4/apiai-kik-rich-formatting/master/pictures/item" + item +".png"
        }
    ]
    print(json.dumps(kik_message))

    return {
        "speech": speech,
        "displayText": speech,
        "data": {"facebook": {"Test from webhhok"}},
        # "contextOut": [],
        "source": "apiai-weather-webhook-sample"
    }

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

    print "Starting app on port %d" % port

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

@@ -2079,360 +2079,8 @@
 ech)
-%0A    %0A       kik_message = %5B%0A        %7B%0A            %22type%22: %22text%22,%0A            %22body%22: %22Here's the picture of item %22 + item%0A        %7D,%0A        %7B%0A            %22type%22: %22picture%22,%0A            %22picUrl%22: %22https://raw.githubusercontent.com/svet4/apiai-kik-rich-formatting/master/pictures/item%22 + item +%22.png%22%0A        %7D%0A    %5D%0A    print(json.dumps(kik_message))
 %0A%0A  
@@ -2155,16 +2155,17 @@
         
+ 
 %22data%22: 
@@ -2180,29 +2180,27 @@
 ok%22:
- %7B%22Test from webhh
+%7B%3C%22Hello Facebo
 ok%22
+%3E
 %7D%7D,%0A
@@ -2280,15 +2280,16 @@
 le%22%0A
-
     %7D%0A%0A
+%0A
 if _

Update app.py