"""
This bot listens to port 5002 for incoming connections from Facebook. It takes
in any messages that the bot receives and echos it back.
"""
from flask import Flask, request
import requests
import sys
import os
import logging

app = Flask(__name__)
TOKEN = os.environ['MESSENGER_TOKEN']
WEBHOOK_TOKEN = os.environ['WEBHOOK_TOKEN']

class Bot(object):
    def __init__(self, access_token):
        self.access_token = access_token
        self.base_url = "https://graph.facebook.com/v2.6/me/messages?access_token={0}".format(access_token)


    def send_text_message(self, recipient_id, message):
        return self.send_message(recipient_id, {'text': message})


    def send_message(self, recipient_id, message):
        payload ={'recipient': {'id': recipient_id},
                  'message': message
                 }
        print "Posting payload to facebook: %s" % payload
        return requests.post(self.base_url, json=payload).json()


    def send_generic_message(self, recipient_id, elements):
        payload = {'recipient': {'id': recipient_id},
                   'message': {
                                "attachment": {
                                    "type": "template",
                                    "payload": {
                                        "template_type": "generic",
                                        "elements": [{
                                            "title": "Here's your T-Shirt!",
                                            "subtitle": "Buy it now for only $20!",
                                            "image_url": "http://messengerdemo.parseapp.com/img/rift.png",
                                            "buttons": [{
                                                "type": "web_url",
                                                "url": "https://www.messenger.com/",
                                                "title": "Buy it now!"
                                            }]
                                        }]
                                    }
                                }
                            }
                   }
        return requests.post(self.base_url, json=payload).json()

bot = Bot(TOKEN)

def init_logging(logger):
    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)


@app.route("/webhook", methods=['GET', 'POST'])
def hello():
    if request.method == 'GET':
        if (request.args.get("hub.verify_token") == WEBHOOK_TOKEN):
            return request.args.get("hub.challenge")
        else:
            app.logger.info('missing token')
            return 'missing challenge token', 400
    if request.method == 'POST':
        output = request.json
        event = output['entry'][0]['messaging']
        for x in event:
            if (x.get('message') and x['message'].get('text')):
                message = x['message']['text']
                recipient_id = x['sender']['id']
                print bot.send_generic_message(recipient_id, message)
        return "success"

if __name__ == "__main__":
    init_logging(app.logger)
    app.run(port=5002, debug=True)

@@ -221,16 +221,86 @@
  logging
+%0Afrom urllib import quote%0Aimport urllib2%0Afrom bs4 import BeautifulSoup
 %0A%0Aapp = 
@@ -396,16 +396,194 @@
 _TOKEN'%5D
+%0ATEEMILL_API_KEY = os.environ%5B'TEEMILL_API_KEY'%5D%0A%0ATEEMILL_URL = 'https://rapanuiclothing.com/api-access-point/?api_key='+TEEMILL_API_KEY+'&item_code=RNA1&colour=White&image_url='
 %0A%0Aclass 
@@ -1242,24 +1242,38 @@
 ent_id, 
-elements
+product_url, image_url
 ):%0A     
@@ -1851,56 +1851,17 @@
 l%22: 
-%22http://messengerdemo.parseapp.com/img/rift.png%22
+image_url
 ,%0A  
@@ -2042,36 +2042,19 @@
 l%22: 
-%22https://www.messenger.com/%22
+product_url
 ,%0A  
@@ -2688,16 +2688,628 @@
 dler)%0A%0A%0A
+def get_product_url(image_url):%0A    encoded_image_url = quote(image_url)%0A    print encoded_image_url%0A    temp_teemill_url = TEEMILL_URL + encoded_image_url%0A    print temp_teemill_url%0A    product_url = urllib2.urlopen(temp_teemill_url).read()%0A    print product_url%0A    return product_url%0A%0A%0Adef get_tshirt_image_url(product_url):%0A    product_page = urllib2.urlopen(product_url).read()%0A    soup = BeautifulSoup(product_page, %22html.parser%22)%0A    meta_tag_data = soup.findAll(attrs=%7B%22property%22:%22og:image%22%7D)%0A    print meta_tag_data%0A    image_url = meta_tag_data%5B0%5D%5B'content'%5D%0A    print image_url%0A    return image_url%0A%0A%0A
 @app.rou
@@ -3918,16 +3918,223 @@
 %5D%5B'id'%5D%0A
+%0A                image_url = 'https://pbs.twimg.com/media/Cg6rupTWwAQCern.jpg'%0A%0A                product_url = get_product_url(image_url)%0A                tshirt_image_url = get_tshirt_image_url(product_url)%0A%0A
         
@@ -4186,23 +4186,45 @@
 ent_id, 
-message
+product_url, tshirt_image_url
 )%0A      

Add test image to tshirt