#!/usr/bin/env python

from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()

from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError

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") != "news.search":
        return {}
    baseurl = "https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=latest&apiKey=dda1592b3267447193fb1756b5746b0e"
    
    result = urlopen(baseurl).read()
    data = json.loads(result)
    res = makeWebhookResult(data)
    return res
    print(res)
    print(data)

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


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

@@ -662,17 +662,16 @@
 =4)%0A    
-#
  print(r
@@ -951,14 +951,11 @@
 tBy=
-latest
+top
 &api
@@ -996,16 +996,89 @@
 0e%22%0A    
+yql_query = makeYqlQuery(req)%0A    if yql_query is None:%0A        return %7B%7D
 %0A    res
@@ -1190,37 +1190,608 @@
 res%0A
-    print(res)%0A    print(data
+%0A%0A%0A%0A%0Adef makeWebhookResult(data):%0A    query = data.get('query')%0A    if query is None:%0A        return %7B%7D%0A%0A    result = query.get('articles')%0A    if result is None:%0A        return %7B%7D%0A%0A    channel = result.get('author')%0A    if channel is None:%0A        return %7B%7D%0A%0A    item = channel.get('title')%0A    location = channel.get('description')%0A    units = channel.get('url')%0A    if (location is None) or (item is None) or (units is None):%0A        return %7B%7D%0A%0A%0A    # print(json.dumps(item, indent=4))%0A%0A   %0A    speech = %22 latest news%22+channel+%22item%22+%22%22+location+%22%22+%22units%22%0A%0A    print(%22Response:%22)%0A    print(speech
 )%0A%0A 
@@ -1940,16 +1940,30 @@
 iai-
-news-api
+weather-webhook-sample
 %22%0A  

Create app.py