Replying to an Incoming SMS message



Study how to receive and reply to the incoming SMS messages. Please install an API Extension. When this API Extension gets a message, it will forward the message to the configured Incoming message URL . This URL can be an application that looks like this:


Study how to receive and reply to the incoming SMS messages through Ozeki Phone System XE and OPS SDK. First of all, please login and connect to the API Extension. Wait for an Incoming SMS, and when it is occured you can use the SendMessage with the sender's number as the Recipient.


Example code coming soon...
<?php
	$receiveTime = date("c");
	$outString = "Date: " . $receiveTime . "\r\n";
	$outString .= "Sender: " . $_REQUEST['Sender'] . "\r\n";
	$outString .= "Message: " . $_REQUEST['Message'] . "\r\n\r\n";
	file_put_contents('sms.txt', $outString, FILE_APPEND);
	print "<SendSms Recipient="".$_REQUEST['Sender']."">";
	print "Hello, I got your message! Thank you!";
	print "</SendSms>";
?>
[HttpPost]
public ActionResult ReplyIncomingSMS(string notificationName, string sender, string recipient, string iD, string apiExtension, string message)
{
	using (var fs = new FileStream("c:\\sms.txt", FileMode.Append, FileAccess.Write, FileShare.Read))
	{
		using (var writer = new StreamWriter(fs))
		{
			writer.Write(
				"NotificationName=" + notificationName + ";" +
				"Sender=" + sender + ";" +
				"Recipient=" + recipient + ";" +
				"ID=" + iD + ";" +
				"ApiExtension=" + apiExtension + ";" +
				"Message=" + message + "\n");

			writer.Flush();
			writer.Close();
		}
		fs.Close();
	}

	return Content(
	"<Response>" +
		"<SendSms Recipient=\"" + sender + "\">"+
			"Hello, I got your message! Thank you!"+
		"</SendSms>" +
	"</Response>", "text/xml");
}
class ReplyIncomingSmsController < ApplicationController

  require 'time'
  protect_from_forgery except: :index

  # In routes.rb you need to set the following routing rule
  # post '/reply_to_sms' => 'reply_incoming_sms#index'
  
  def index
    
    receive_time = Time.now.utc.iso8601
    out_string = "Date: " + receive_time + "\r\n"
    out_string += "Sender: " + params['Sender'] + "\r\n"
    out_string += "Message: " + params['Message'] + "\r\n\r\n"

    begin
        file = File.new("sms.txt", "a")
        file.write(out_string)
      rescue IOError => e
        #Some error occurred, directory not writeable etc.
      ensure
        file.close unless file == nil
    end    

    render :xml => '<?xml version="1.0" encoding="UTF-8"?>
    <Response>
      <SendSms Recipient="' + params['Sender'] + '">
      	Hello, I got your message! Thank you!
      </SendSms>
    </Response>'
    
  end
  
end
Imports OPSSDK
Imports OPSSDKCommon.Model.Message

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.MessageReceived, AddressOf ReceiveAndReplySMS
        Console.ReadLine()
    End Sub

    Private Sub ReceiveAndReplySMS(sender As Object, e As Message)
        Console.WriteLine("Sender: " & e.Sender & ". Content:" & e.Content)

        Dim sms = New SMSMessage(e.Sender, "Hello, I got your message! Thank you!")
        apiExtension.SendMessage(sms)
    End Sub
End Module
import urllib.parse
from cgi import escape
import datetime

def application(environ, start_response):

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

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

        f = open('C:/sms.txt', 'a')
        for key, value in receivedData.items():
            f.write("{}: {}\r\n".format(str(key), str(value)))
        f.write("\r\n")
        f.close()
        
        result = sendSms(escape(receivedData['Sender'][0]))

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

    return [result]

def sendSms(sender):
    today = datetime.datetime.now();
    
    return """<xml version="1.0" encoding="UTF-8"?>
        <Response>
            <SendSms Recipient="{1}">Hello, I got your SMS at {0}! Thank you!</SendSms>"
        </Response>""".format(today.strftime("%Y-%m-%d %H:%M"), sender)

using OPSSDK;
using System;
using OPSSDKCommon.Model.Message;

namespace OPS_QuickStartExample_CSharp
{
    class Program
    {
        private static IAPIExtension apiExtension;

        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.MessageReceived += ReceiveAndReplySMS;
            Console.ReadLine();
        }

        private static void ReceiveAndReplySMS(object sender, Message e)
        {
            Console.WriteLine("Sender: " + e.Sender + ". Content:" + e.Content);

            var sms = new SMSMessage(e.Sender, "Hello, I got your message! Thank you!");
            apiExtension.SendMessage(sms);
        }
    }
}
#!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 modules that let read data passed
&ReadParse(%in); #Read in from HTTPPost parameters

#Logging into file
open(my $fh, '>>', 'sms.txt');
print $fh "NotificationName:$in{'NotificationName'}; Sender:$in{'Sender'}; Recipient:$in{'Recipient'}; ID:$in{'ID'}; ApiExtension:$in{'ApiExtension'}; Message:$in{'Message'}\n";
close $fh;

print
'<Response>
	<SendSms Recipient="'.$in{'Sender'}.'">Hello, I got your message! Thank you!</SendSms>
</Response>'
package pbxsampleapp;

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

public class ReceiveSendResponseMessage
{
    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("/incomingsms", 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 recipientNumber = parameters.get("Sender").toString();
            httpExchange.getResponseHeaders().add("Content-type", "text/xml");
            String response = "<?xml version=\"1.0\"?>"
                    + "<Response>"
                    + "<SendSms Recipient=\""+recipientNumber+"\" Sender=\"1234567\">"
                        + "Hello, I got your message! 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 - Handle the IncomingSMS notification and reply an SMS to the Sender

This application will write the parameters into a file every time when it gets a request from the API Extension. After that, use the Sender parameter and send back an SMS message to that number with SendSMS OzML Command.

You can read information about the IncomingSMS notification parameters.
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 XE\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 XE through this client. Try to login with the client into the running Ozeki Phone System XE, 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 MessageReceived event of the apiExtension. This event will be triggered every time, when the selected API Extension receives an SMS. This event will provide you the received SMS itself. In the event handler you can use the SMS message as you wish (write the SMS into file, Database etc.).

In the next step you will send back another SMS to the original sender in the mentioned event handler. Please create a new SMSMessage. Get the original Sender of the incoming SMS, and add this string as the Recipient of the new SMS. Add the content of the SMS, too, at the initialisation. After that, use the SendMessage method of the apiExtension and add the new SMS as the parameter.

From now on, every time when the selected API Extension receives an SMS, your program will also receive it, and it will send back an SMS to the original sender in the mentioned event handler.

You can read information about the IncomingSMS notification parameters.

More information