Call Us Today! 877.742.2583

Page tree
Skip to end of metadata
Go to start of metadata


This page provides the documentation of the Lua FreeSWITCH API.

Docs Help Needed

session:execSome API aren't documented, so please feel free to improve the documentation and complete the API examples.

 Click here to expand ToC

API Events

These methods apply to generating events.


event:addBody helps in creating custom event.


You can add as much data to the body as you like, in this case 4 items are to be sent.

The result will be:

 Click here to expand the result






This is a generic API call.

Or, This can be used inside of a dialplan.lua to get certain information


Returns the type of this event, either CUSTOM for custom events or one of the built-in event types


Use this to dump all available Headers to the console.

Or this to display them as an info message.


Sets the priority for the event, but requires a value of type switch_priority_t which doesn't seem to be available in the Lua binding.

event:fire (Sending an Event)

Using luarun to execute this code you can toggle the MWI on a registered phone on and off.

API Sessions

The following methods can be applied to existing sessions.


Answer the session:


Checks whether the session is flagged as answered (true anytime after the call has been answered)


Check to see if this session's channel is bridged to another channel.




Log something to the FreeSWITCH logger from session. Arguments are log level and message.


Destroys the session and releases resources. This is done for you when your script ends, but if your script contains an infinite loop you can use this to terminate the session.


session:execute(app, data)

NOTE: Callbacks (DTMF and friends) CAN NOT EXECUTE during an execute.



NOTE: Callbacks (DTMF and friends) CAN NOT EXECUTE during an execute.






Get digits:

  • getDigits has three arguments: max_digits, terminators, timeout
  • max_digits: maximum number of DTMF tones that will be collected
  • terminators: buffer of characters that will terminate the digit collection
  • timeout: timeout in milliseconds allowed for no input or after last digit is pressed and terminator isn't
  • interdigit: if no input is received timeout specified previously will be use, once input is received this becomes the new timeout. (optional default 0)
  • return: buffer containing collected digits
  • The method blocks until one of the exit criteria is met.


Get the call state, i.e. "CS_EXECUTE". The call states are described in "switch_types.h".


To get system variables such as ${hold_music}


You can hang up a session and provide an optional Hangup Cause Code Table.




You can find the hangup cause of an answered call and/or the reason an originated call did not complete. See Hangup Cause Code Table.

Example call retry based on hangup cause:

Here's a Lua example in code which retries a call depending on the hangup cause. It retries max_retries1 times and alternates between 2 different gateways:

NOTE: originate_str1 and originate_str21 are dial strings for 2 different gateways.



session:insertFile(<orig_file>, <file_to_insert>, <insertion_sample_point>)

Inserts one file into another. All three arguments are required. The third argument is in samples, and is the number of samples into orig_file that you want to insert file_to_insert. The resulting file will be written at the sample rate of the session, and will replace orig_file.

Because the position is given in samples, you'll need to know the sample rate of the file to properly calculate how many samples are X seconds into the file. For example, to insert a file two seconds into a .wav file that has a sample rate of 8000Hz, you would use 16000 for the insertion_sample_point argument.

Note that this method requires an active channel with a valid session object, as it needs the sample rate and the codec info from the session.




session:originate is deprecated, use the following construct instead:

new_session = freeswitch.Session("sofia/gateway/gatewayname/18001234567", session);

The code below is here for the sake of history only; please do not use it going forward.


dest - quoted dialplan destination. For example: "sofia/internal/1000@" or "sofia/gateway/my_sip_provider/my_dest_number"


timeout - origination timeout in seconds

Note: session.originate expects at least 2 arguments.


Plays a file and collects DTMF digits. Digits are matched against a regular expression. Non-matching digits or a timeout can trigger the playing of an audio file containing an error message. Optional arguments allow you to transfer to an extension on failure, and store the entered digits into a channel variable.


digits = session:playAndGetDigits (
          min_digits, max_digits, max_attempts, timeout, terminators,
          prompt_audio_files, input_error_audio_files,
          digit_regex, variable_name, digit_timeout,



min_digitsThe minimum number of digits required.
max_digitsThe maximum number of digits allowed.
max_attemptsThe number of times this function waits for digits and replays the prompt_audio_file when digits do not arrive.
timeoutThe time (in milliseconds) to wait for a digit.
terminatorsA string containing a list of digits that cause this function to terminate.
prompt_audio_fileThe initial audio file to play. Playback stops if digits arrive while playing. This file is replayed after each timeout, up to max_attempts.
input_error_audio_fileThe audio file to play when a digit not matching the digit_regex is received. Received digits are discarded while this file plays. Specify an empty string if this feature is not used.
digit_regexThe regular expression used to validate received digits.
variable_name(Optional) The channel variable used to store the received digits.
digit_timeout(Optional) The inter-digit timeout (in milliseconds). When provided, resets the timeout clock after each digit is entered, thus giving users with limited mobility the ability to slowly enter digits without causing a timeout. If not specified, digit_timeout is set to timeout.
transfer_on_failure(Optional) In the event of a failure, this function will transfer the session to an extension in the dialplan. The syntax is "extension-name [dialplan-id [context]]".



  • This function returns an empty string when all timeouts and retry counts are exhausted.
  • When the maximum number of allowable digits is reached, the function returns immediately, even if a terminator was not entered.
  • If the user forgets to press one of the terminators, but has made a correct entry, the digits are returned after the next timeout.
  • The session has to be answered before any digits can be processed. If you do not answer the call you, the audio will still play, but no digits will be collected.


This example causes FreeSWITCH to play prompt.wav and listen for between 2 and 5 digits, ending with the # key. If the user enters nothing (or something other than a digit, like the * key) error.wav is played, and the process is repeated another two times.

This time, we require only one digit, and it must be 1, 3 or 4. If the user does not comply after three attempts, they are transferred to the operator extension in the "default" XML dial plan.

If the user presses a correct key, that digit is returned to the caller, and the "digits_received" channel variable is set to the same value.

Reminder: If you need to match the * key in the regular expression, you will have to quote it twice:


Pre answer the session:


Play a file and get digits.

session:read has 5 arguments: <min digits> <max digits> <file to play> <inter-digit timeout> <terminators>

This shows how you can figure out which terminator was pressed, if any:


- checks whether the session is still active (true anytime between call starts and hangup)
- also session:ready will return false if the call is being transferred. Bottom line is you should always be checking session:ready on any loops and periodicly throughout your script and exit asap if it returns false.

See #session:hangupCause for more detail on if NOT ready.


syntax is ended_by_silence = session:recordFile(file_name, max_len_secs, silence_threshold, silence_secs)

silence_secs is the amount of silence to tolerate before ending the recording.
ended_by_silence is 0 if recording was ended by something else, eg an input callback getting dtmfs


Play a speech phrase macro.

session:sayPhrase(macro_name [,macro_data] [,language]);
  • macro_name - (string) The name of the say macro to speak.
  • macro_data - (string) Optional. Data to pass to the say macro.
  • language - (string) Optional. Language to speak macro in (ie. "en" or "fr"). Defaults to "en".

To capture events or DTMF, use it in combination with session:setInputCallback


When used with setInputCallback, the return values and meanings are as follows:

  • true or "true" - Causes prompts to continue speaking.
  • Any other string value interrupts the prompt.



By default, lua script hangs up when it is done executing. If you need to run the next action in your dialplan after the lua script, you will need to setAutoHangup to false. The default value is true.


In your lua code, you can use setHangupHook to define the function to call when the session hangs up.

Other possibilities to exit the script (and throwing an error)

return "exit";
return "die";
s:destroy("error message");


When used outside of streaming a file to a channel the return values "true" or "undefined" are accepted as true(which continues the audio stream I believe), anything else will be evaluated as false(which would stop the stream).

TODO: Additional return values can be located in the file ./src/switch_ivr.c around line 3359 with the option for "speed". Could not find out every option effect yet.

Return value effect.

Notice: Every return values are should be STRING.

Return valueEffect(When streaming audio)
"pause"Stop audio util get the next input. After get the another input, then it play continally.
"true"Wait until the audio finish.


Stop the audio, immediately.
None/NULLDon't return None/NULL. It makes type error problem. Especially python.



Set a variable on a session:


  • This will allow callbacks to DTMF to occur and session:execute("sleep", "5000") won't.



Plays pre-recorded sound files for things like numbers, dates, currency, etc. Refer to Misc. Dialplan Tools say for info about the say application.

Arguments: <lang><say_type><say_method>



Stream a file endless to the session

Stream a file endless to the session starting at sample_count?


Transfer the current session. The arguments are extensions, dialplan and context.

execution of your lua script will immediately stop, make sure you set session:setAutoHangup(false) if you don't want your call to disconnect

If instead you do session:execute("transfer", "3000 XML default") then the execution of the LUA script continues even though the call is mostly out of your control now, and bridges most likely will fail.




Instantiates a new IVRMenu object. To see a full example, go to the Lua IVR Menu Example page. 



Binds an action to the menu. See the documentation for IVR Menu.



Executes the instantiated menu on the given session.


Non-Session API

These methods are generic in that they do not apply to a session or an event. For example, printing data to the FreeSWITCH console is neither event- nor session-specific.

 Click here to expand...



When calling a Lua script from the dialplan you always have the session object. However, Lua can also be called from the CLI. In either case, it is possible to execute API commands from within Lua by creating an API object:

In the above snippet, the Lua variable reply would receive the version number from FreeSWITCH.

You can do more intricate things as well, like this:

The Lua variable sofia would contain the total output of the sofia status command.




Log something to the freeswitch logger. Arguments are loglevel, message.


Get an ODBC or core (sqlite) database handle from FreeSWITCH and perform an SQL query through it.

Advantage of this method is that it makes use of connection pooling provided by FreeSWITCH which gives a nice increase in speed when compared to creating a new TCP connection for each LuaSQL env:connect().

It works as follows:

  • freeswitch.Dbh(odbc://my_db:uname:passwd) gets an ODBC db handle from the pool.
  • freeswitch.Dbh("sqlite://my_db") gets a core db (sqlite) db handle from the pool (this automatically creates the db if it didn't exist yet).
  • dbh:connected() checks if the handle is still connected to the database, returns true if connected, false otherwise.
  • dbh:test_reactive("test_sql", "drop_sql", "reactive_sql") performs test_sql and if it fails performs drop_sql and reactive_sql (handy for initial table creation purposes)
  • dbh:query("query", function()) takes the query as a string and an optional Lua callback function that is called on each row returned by the db.
    • The callback function is passed a table representation of the current row for each iteration of the loop. 
      Syntax of each row is: { ["column_name_1"] = "value_1", ["column_name_2"] = "value_2" }.
    • If you (optionally) return a number other than 0 from the callback-function, you'll break the loop.
  • dbh:affected_rows() returns the number of rows affected by the last run INSERT, DELETE or UPDATE on the handle. It does not respond to SELECT operations.
  • dbh:release() (optional) releases the handle back to the pool so it can be re-used by another thread. This is also automatically done when the dbh goes out of scope and is garbage collected (for example when your script returns). Useful for long-running scripts to release the connection sooner.

Take a look here for some examples.

Send an email with optional (converted) attachment.

Note that for this to work you have to have an MTA installed on your server, you also need to have 'mailer-app' configured in your switch.conf.xml.

You can use as follows:, from, headers, body, file, convert_cmd, convert_ext)
  • to (mandatory) a valid email address
  • from (mandatory) a valid email address
  • headers (mandatory) for example "subject: you've got mail!\n"
  • body (optional) your regular mail body
  • file (optional) a file to attach to your mail
  • convert_cmd (optional) convert file to a different format before sending
  • convert_ext (optional) to replace the file's extension


then the following system command will be executed before attaching "message.mp3" to the mail and send it on its way:

mp3enc message.wav message.mp3


This is firing a custom event my::event.


Consumes events from FreeSWITCH.

Usage (single event subscription):

Usage (multiple specific event subscriptions):



Retrieves a global variable


Tells script to sleep for a specified number of milliseconds.
NOTE: Do not use this on a session-based script or bad things will happen.


Create a new session.

Create a new session with execute_on_answer variable set.


API commands

You can write FreeSWITCH API commands *in Lua* by using the lua FreeSWITCH API command to run a script and pass the arguments in, then whatever you write with the stream object is what you get as a reply to that command. For example, given a script in the scripts directory called hello.lua with the following content:

Running 'lua hello.lua' from the FreeSWITCH console would return back "hello world".

Or calling it from the dialplan like so:

Would set the channel variable "foo" to "hello world".

Web page interaction (via mod_xml_rpc)

Example: Call Control

Special Case: env object

When lua is called as the hangup hook there will be a special env object that contains all the channel variables from the channel that just disconnected.

Add an extension to test this feature:


Then add freeswitch/scripts/hook-test.lua:

Watch the FS console and dial 1234 and then hangup. You'll see all your channel variables!

Known issues

  • lua ssl module - If you are using lua ssl module it might crash freeswitch, for me using it in Lua scripts was no issue, but if I was using lua ssl in hangup hook it was crashing freeswitch constantly. Comment from Mike: "Openssl has a global initializer and no way to keep it from only being run once. We run that in FreeSWITCH, then the luassl module re-runs it (corrupting the global openssl structures). There is no scoped way to keep it from doing that without writing a custom ssl lua wrapper specifically for FreeSWITCH. Writing this is a possibility but not something we plan on doing."

See also


  1. Where can I find the lua session api and non-session(freeswitch) api source code ?

    I want to learn more the implementation in FreeSWITCH.

    Are those all in src\mod\languages\mod_lua ? Which source file ?


  2. You can check mod/languages/mod_lua/freeswitch_lua.h and mod/languages/mod_lua/my_swigable_cpp.h to see what's implemented and then the corresponding *.c files to see the actual implementation.

    1. Thank you very much

  3. Where can I find session:setInputCallback arg type value list ?

    One of type is dtmf.