Sending SMS to Caller



This example demonstrates how to send SMS messages with OzML through an installed API Extension.
Please write the following code into the right file on your web server:


This example demonstrates how to send SMS messages with Ozeki Phone System and OPS SDK. First of all, please login and connect to the API Extension. Wait for an Incoming call, and when it is occured you can use the SendMessage with the caller's number as the Recipient.


Example code coming soon...
[HttpPost]
public ActionResult SendSMSViaOzML(string notificationName, string callLegID, string caller, string apiExtension)
{
	return Content(
	"<Response>" +
		"<Speak>Hello " + caller + "!, I sent you an SMS</Speak>" +
		"<SendSms Recipient=\"" + caller + "\">"
			"Hello, I got your call!  Thank you!" +
		"</SendSms>" +
		"<HangUp></HangUp>" +
	"</Response>", "text/xml");
}
class SendingSmsViaOzmlController < ApplicationController
  
  protect_from_forgery except: :index

  # In routes.rb you need to set the following routing rule
  # post '/send_sms_via_ozml' => 'sending_sms_via_ozml#index'
  
  def index
    render :xml => '<?xml version="1.0" encoding="UTF-8"?>
    <Response>
      <Speak>Hello ' + params['Caller'] + '!, I sent you an SMS</Speak>
      <SendSms Recipient="' + params['Caller'] + '">
      	 Hello, I got your call! Thank you!
      </SendSms>
      <HangUp></HangUp>
    </Response>'
  end
  
end
<?php	
	print "<Response>";
		print "<Speak>Hello ".$_REQUEST['Caller']."!, I sent you an SMS</Speak>";
		print "<SendSms Recipient="".$_REQUEST['Caller']."">";
			print "Hello, I got your call! Thank you!";
		print "</SendSms>";
		print "<HangUp></HangUp>";
	print "</Response>";
?>
#!c:/Perl64/bin/perl.exe   
print "Content-Type: text/plain\n\n";
#You have to add the directory route of perl.exe, and print the content type

use CGI qw(:cgi-lib :standard);  # Use CGI that let read data passed
&ReadParse(%in); #Read in from HTTPPost parameters

#Send response
print 
'<?xml version="1.0" encoding="UTF-8"?>
<Response>
	<Speak>Hello '.$in{'Caller'}.'!, I sent you an SMS</Speak>
	<SendSms Recipient="'.$in{'Caller'}.'">Hello, I got your call! Thank you!</SendSms>
	<HangUp></HangUp>
</Response>'
Imports OPSSDKCommon.Model.Message
Imports OPSSDK
Imports Ozeki.Media.MediaHandlers
Imports OPSSDKCommon.Model.Call
Imports Ozeki.VoIP

Module Module1
    Private apiExtension As IAPIExtension
    Public Sub Main(args As String())
        Dim client = New OpsClient()
        AddHandler client.ErrorOccurred, Sub(sender, info)
                                             Console.WriteLine(info.Message)
                                         End Sub

        If Not client.Login("ozekixepbx.ip", "admin", "12345") Then
            Return
        End If

        apiExtension = client.GetAPIExtension("9000")
        AddHandler apiExtension.IncomingCall, AddressOf IncomingCall
        Console.ReadLine()
    End Sub

    Private Sub IncomingCall(sender As Object, e As VoIPEventArgs(Of ICall))
        Dim [call] = e.Item
        Dim tts = New TextToSpeech()
        AddHandler tts.Stopped,
            Sub(s, ev)
                Dim caller = [call].OtherParty
                [call].HangUp()
                Dim sms As New SMSMessage(caller, "Hello, I got your call! Thank you!")
                apiExtension.SendMessage(sms)
            End Sub
        [call].ConnectAudioSender(tts)

        AddHandler [call].CallStateChanged,
            Sub(s, ev)
                If ev.Item = CallState.Answered Then
                    tts.AddAndStartText("Hello, I sent you an SMS")
                ElseIf ev.Item.IsCallEnded() Then
                    tts.Dispose()
                End If
            End Sub

        [call].Accept()
    End Sub
End Module
import urllib.parse
import datetime
from cgi import escape

def application(environ, start_response):
    result = receiveCall(environ)

    response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(result)))]
    start_response('200 OK', response_headers)

    return [result]

def receiveCall(environ):
    today = datetime.datetime.now();

    try:
        length= int(environ.get('CONTENT_LENGTH', '0'))

        if(length != 0):
            body = environ['wsgi.input'].read(length)
            receivedData = urllib.parse.parse_qs(body.decode("utf-8"))
            caller = escape(receivedData['Caller'][0])

            return """<?xml version="1.0" encoding="UTF-8"?>
            <Response>
                <Delay>1</Delay>
                <Speak>Hello {1}!, I sent you an SMS</Speak>
                <SendSms Recipient="{1}">
                	Hello, I got your call at {0}! Thank you!
                </SendSms>
                <HangUp></HangUp>
            </Response>""".format(today.strftime("%Y-%m-%d %H:%M"), caller)
            
    except IOError:
        return ""
using System;
using OPSSDKCommon.Model.Message;
using OPSSDK;
using Ozeki.Media.MediaHandlers;
using OPSSDKCommon.Model.Call;
using Ozeki.VoIP;

static class Module1
{
	private static IAPIExtension apiExtension;
	public static void Main(string[] args)
	{
		var client = new OpsClient();
		client.ErrorOccurred += (sender, info) => { Console.WriteLine(info.Message); };

		if (!client.Login("ozekixepbx.ip", "admin", "12345")) {
			return;
		}

		apiExtension = client.GetAPIExtension("9000");
		apiExtension.IncomingCall += IncomingCall;
		Console.ReadLine();
	}

	private static void IncomingCall(object sender, VoIPEventArgs e)
	{
		var call = e.Item;
		var tts = new TextToSpeech();
		tts.Stopped += (s, a) =>
            {
                var caller = call.OtherParty;
                call.HangUp();
                var sms = new SMSMessage(caller, "Hello, I got your call! Thank you!");
                apiExtension.SendMessage(sms);
            };
		call.ConnectAudioSender(tts);

		call.CallStateChanged += (s, ev) =>
            {
                if (ev.Item == CallState.Answered) {
                    tts.AddAndStartText("Hello, I sent you an SMS");
                } else if (ev.Item.IsCallEnded()) {
                    tts.Dispose();
                }
            };

		call.Accept();
	}
}
package pbxsampleapp;

import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class SendingSmstoCaller 
{
 public static void main(String[] args)
    {
        try
        {
            System.out.println("Starting http server...");
            HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getByAddress(new byte[]{ 0, 0, 0, 0 }), 12345), 0);
            server.createContext("/sendsmstocaller", new PbxSampleApp.PBXRequestHandler());
            server.start();
            System.out.println("http server running on " + server.getAddress().toString());
        }
        catch (IOException ex){ System.out.println("Error" + ex.toString());
        }
    }

    static class PBXRequestHandler implements HttpHandler
    {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException
        {
            InputStream inputStream = httpExchange.getRequestBody();
            byte[] body = new byte[inputStream.available()];
            inputStream.read(body);
            Map parameters = parseBody(body);
            String caller = parameters.get("Caller").toString();
            httpExchange.getResponseHeaders().add("Content-type", "text/xml");
            String response = "<?xml version=\"1.0\"?>"
                    + "<Response>"
                    + "<Speak>Hello "+ caller +", I sent you an SMS.</Speak>"
                    + "<SendSms Recipient=\"" + caller + "\">"+
                        + "Hello, I got your call! Thank you!"
                    + "</SendSms>"
                    + "</Response>";
            httpExchange.sendResponseHeaders(200, response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }

       private Map<String, String> parseBody(byte[] params) throws UnsupportedEncodingException
        {
            Map<String, String> query_pairs = new LinkedHashMap<String, String>();
            String[] pairs = URLDecoder.decode(new String(params), "UTF-8").split("&");
            String paramname;
            String value;
            for (String pair : pairs)
            {
                int idx = pair.indexOf("=");
                paramname = pair.substring(0, idx);
                value = pair.substring(idx + 1);
                query_pairs.put(paramname, value);
                System.out.println(String.format("%s: %s", paramname, value));
            }
            return query_pairs;
        }
    }
}

Code example 1 - Reply to incoming call by sending SMS

When the API Extension is called, it sends a HTTP Request to the configured Incoming Call URL. In the example, get the Request and handle it. After that, send back a Response OzML. In the Response you can use the SendSMS OzML Command, and the Recipient of the SMS can be read out from the Caller parameter of the incoming Request. You can add the content of the SMS between the <SendSms> and the </SendSms> tags. The API Extension gets this Response and sends the given Message to the given Recipient.
IN MORE DETAILS

Get the OPSSDK.dll

First you need to add the OPSSDK.dll reference to your project
(You can find OPSSDK.dll at C:\Program Files\Ozeki\Ozeki Phone System\Examples.NET API\OPSSDK.dll).

Login and connect

Create a new instance of OpsClient, and subscribe to the ErrorOccurred event. Your program will communicate with the Ozeki Phone System through this client. Try to login with the client into the running Ozeki Phone System, with the address of the server(ozekixepbx.ip) and a valid username, password combination.
If you are ready, try to get an existing API Extension, with the GetApiExtension method of the OpsClient. Read more about installation of API Extension.

Further steps

When you are ready with the initial steps above, subscribe the IncomingCall event of the apiExtension. This event will be triggered every time when the selected API Extension is called. In the mentioned event handler you will see the e.Item parameter, this parameter will be the call object. This call object has a CallState property, when the CallState is Ringing subscribe the CallStateChanged event of the call object and Accept the call.

The CallStateChanged event will be triggered when the call is going to another state. When the CallState is Answered, you can connect the devices to the call. When the call has ended, please do not forget to disconnect all devices from the call.

When the CallState is Answered, start and connect to the call a TextToSpeech object, what will read to the caller the "Hello caller, I sent you an SMS" text. When the TextToSpeech is finished with the reading, it starts to send the SMS. Please instantiate a new SMSMessage. The original caller will be the first parameter of the constructor (Recipient), the content of the SMS will be the second. After you finished the initialization of the SMSMessage you can add it as the parameter of the apiExtension's SendSMS method.

With these steps, you learned how to receive an incoming call, and send a reply SMS to the caller.

MORE DOCS FOR DEVELOPERS

This was the quick start guide for developers to make it easy to create your own first VoIP and/or SMS application. Check the Developers Guide and build more advanced projects using .NET API, SQL API, HTTP API or JavaScript API.

More information