from lead_alerts import app
from flask import flash, redirect, render_template, request
from twilio.base.exceptions import TwilioRestException
from .services.twilio_service import TwilioService
@app.route('/')
def index():
house = {
'title': '555 Sunnybrook Lane',
'price': '$349,999',
'description':
'You and your family will love this charming home. ' +
'Featuring granite appliances, stainless steel windows, and ' +
'high efficiency dual mud rooms, this joint is loaded to the max. ' +
'Motivated sellers have priced for a quick sale, act now!'
}
return render_template('index.html', house=house)
@app.route('/notifications', methods=['POST'])
def create():
house_title = request.form["house_title"]
name = request.form["name"]
phone = request.form["phone"]
message = request.form["message"]
twilio_service = TwilioService()
formatted_message = build_message(house_title, name, phone, message)
try:
twilio_service.send_message(formatted_message)
flash('Thanks! An agent will be contacting you shortly', 'success')
except TwilioRestException as e:
print(e)
flash('Oops! There was an error. Please try again.', 'danger')
return redirect('/')
def build_message(house_title, name, phone, message):
template = 'New lead received for {}. Call {} at {}. Message {}'
return template.format(house_title, name, phone, message)
using System.Web.Mvc;
using LeadAlerts.Web.Domain;
using LeadAlerts.Web.ViewModels;
using Vereyon.Web;
using System.Threading.Tasks;
namespace LeadAlerts.Web.Controllers
{
public class NotificationsController : Controller
{
private readonly INotificationService _notificationService;
public NotificationsController() : this(new NotificationService()) { }
public NotificationsController(INotificationService notificationService)
{
_notificationService = notificationService;
}
// POST: Notifications/Create
[HttpPost]
public async Task<ActionResult> Create(Lead lead)
{
var message = await _notificationService.SendAsync(FormatMessage(lead));
if (message.ErrorCode.HasValue)
{
FlashMessage.Danger("Oops! There was an error. Please try again.");
}
else
{
FlashMessage.Confirmation("Thanks! An agent will be contacting you shortly.");
}
return RedirectToAction("Index", "Home");
}
private static string FormatMessage(Lead lead)
{
return $"New lead received for {lead.HouseTitle}. Call {lead.Name} at {lead.Phone}. Message: {lead.Message}";
}
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Twilio\Rest\Client;
class NotificationsController extends Controller
{
protected $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function create(Request $request)
{
$houseTitle = $request->input('houseTitle');
$name = $request->input('name');
$phone = $request->input('phone');
$message = $request->input('message');
$formattedMessage = $this->formatMessage($houseTitle, $name, $phone, $message);
try {
$this->sendMessage($formattedMessage);
$request
->session()
->flash('success', 'Thanks! An agent will be contacting you shortly.');
} catch (Exception $e) {
echo $e->getMessage();
$request
->session()
->flash('error', 'Oops! There was an error. Please try again.');
}
return redirect()->route('home');
}
private function sendMessage($message)
{
$twilioPhoneNumber = config('services.twilio')['twilioPhoneNumber'];
$agentPhoneNumber = config('services.twilio')['agentPhoneNumber'];
$this->client->messages->create(
$agentPhoneNumber,
array(
'from' => $twilioPhoneNumber,
'body' => $message
)
);
}
private function formatMessage($houseTitle, $name, $phone, $message)
{
return
"New lead received for $houseTitle. " .
"Call $name at $phone. " .
"Message: $message";
}
}
# frozen_string_literal: true
require 'message_sender'
class NotificationsController < ApplicationController
def create
MessageSender.send_message(message)
redirect_to root_url,
success: 'Thanks! An agent will be contacting you shortly.'
rescue Twilio::REST::TwilioError => error
p error.message
redirect_to root_url,
error: 'Oops! There was an error. Please try again.'
end
private
def message
"New lead received for #{params[:house_title]}. " \
"Call #{params[:name]} at #{params[:phone]}. " \
"Message: #{params[:message]}"
end
end
package com.twilio.leadalerts;
import com.twilio.leadalerts.lib.MessageSender;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class NotificationsServlet extends HttpServlet {
private final MessageSender messageSender;
@SuppressWarnings("unused")
public NotificationsServlet() {
this(new MessageSender());
}
public NotificationsServlet(MessageSender messageSender) {
this.messageSender = messageSender;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String houseTitle = request.getParameter("houseTitle");
String name = request.getParameter("name");
String phone = request.getParameter("phone");
String message = request.getParameter("message");
String formattedMessage = formatMessage(houseTitle, name, phone, message);
try {
messageSender.send(formattedMessage);
request.setAttribute("success", "Thanks! An agent will be contacting you shortly.");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error", "Oops! There was an error. Please try again.");
}
request.getRequestDispatcher("home.jsp").forward(request, response);
}
private String formatMessage(String houseTitle, String name, String phone, String message) {
return String.format("New lead received for %s. Call %s at %s. Message: %s",
houseTitle, name, phone, message);
}
}
const Twilio = require('twilio');
const config = require('../config');
const Express = require('express');
// Some hard-coded information about a house
var house = {
title: '555 Sunnybrook Lane',
price: '$349,999',
description: 'You and your family will love this charming home. '
+ 'Featuring granite appliances, stainless steel windows, and '
+ 'high efficiency dual mud rooms, this joint is loaded to the max. '
+ 'Motivated sellers have priced for a quick sale, act now!'
};
// Map routes to controller functions
module.exports = function () {
// Create an authenticated Twilio API client
var client = new Twilio(config.accountSid, config.authToken);
const router = Express.Router();
// Render landing page
router.get('/', function(request, response) {
response.render('index', house);
});
// Send lead notification
router.post('/leads', function(request, response) {
// Assemble a text message body
var message = 'New lead received for ' + house.title + '. Call '
+ request.body.name + ' at ' + request.body.phone + '. Message: "'
+ request.body.message + '"';
// Send lead notification to agent
client.messages.create({
to: config.agentNumber,
from: config.twilioNumber,
body: message
})
.then(() => {
// Otherwise, respond with 200 OK
response.status(200).send('Lead notification was successfully sent.');
})
.catch((err) => {
console.error(err);
response.status(500).send();
})
});
return router;
};