# -*- coding: utf-8 -*- import logging from flask import Flask, request, json import markovify app = Flask(__name__) def load_model(fname): # Get raw text as string. with open(fname) as f: text = f.read() # Build the model. return markovify.Text(text) models = { "peejay": load_model("peejay.txt"), "nithin": load_model("nithin.txt"), "vss": load_model("vss.txt"), "kunal": load_model("kunal.txt") } @app.route('/peejay', methods=['POST', 'GET']) def peejay(): """Handles an event from Hangouts Chat.""" if request.method == 'GET': return json.jsonify({'message': 'Hello there!'}) event = request.get_json() if event['type'] == 'ADDED_TO_SPACE' and event['space']['type'] == 'ROOM': text = 'Thanks for adding me to "%s"!' % event['space']['displayName'] return json.jsonify({'text': text}) elif event['type'] == 'MESSAGE': text = models["peejay"].make_short_sentence(280) return json.jsonify({ 'cards': [{ 'sections': [{ 'widgets': [{ 'textParagraph': { 'text': text } }] }] }] }) else: return @app.route('/vss', methods=['POST', 'GET']) def vss(): """Handles an event from Hangouts Chat.""" if request.method == 'GET': return json.jsonify({'message': 'Hello there!'}) event = request.get_json() if event['type'] == 'ADDED_TO_SPACE' and event['space']['type'] == 'ROOM': text = 'Thanks for adding me to "%s"!' % event['space']['displayName'] return json.jsonify({'text': text}) elif event['type'] == 'MESSAGE': text = models["vss"].make_short_sentence(280) return json.jsonify({ 'cards': [{ 'sections': [{ 'widgets': [{ 'textParagraph': { 'text': text } }] }] }] }) else: return @app.route('/kunal', methods=['POST', 'GET']) def kunal(): """Handles an event from Hangouts Chat.""" if request.method == 'GET': return json.jsonify({'message': 'Hello there!'}) event = request.get_json() if event['type'] == 'ADDED_TO_SPACE' and event['space']['type'] == 'ROOM': text = 'Thanks for adding me to "%s"!' % event['space']['displayName'] return json.jsonify({'text': text}) elif event['type'] == 'MESSAGE': text = models["kunal"].make_short_sentence(280) return json.jsonify({ 'cards': [{ 'sections': [{ 'widgets': [{ 'textParagraph': { 'text': text } }] }] }] }) else: return @app.route('/nithin', methods=['POST', 'GET']) def nithin(): """Handles an event from Hangouts Chat.""" if request.method == 'GET': return json.jsonify({'message': 'Hello there!'}) event = request.get_json() if event['type'] == 'ADDED_TO_SPACE' and event['space']['type'] == 'ROOM': text = 'Thanks for adding me to "%s"!' % event['space']['displayName'] return json.jsonify({'text': text}) elif event['type'] == 'MESSAGE': text = models["nithin"].make_short_sentence(280) return json.jsonify({ 'cards': [{ 'sections': [{ 'widgets': [{ 'textParagraph': { 'text': text } }] }] }] }) else: return @app.errorhandler(500) def server_error(e): # Log the error and stacktrace. logging.exception('An error occurred during a request.') return 'An internal error occurred.', 500