asterisk AGI編程

Introduction

The AGI facility allows you to launch scripts, written in just about any language, from an Asterisk dial plan. Communication between your script and Asterisk is via standard input and standard output.
撥號方案中,可以採用各種語言很方便的通過AGI接口編寫實施腳本。腳本和Asterisk之間通過標準的輸入輸出進行交互。

Starting your script

Each item in an extension is of the form:

    exten => extension-number,priority,application,arguments

To launch an AGI script the application is 'agi' and the argument is the filename of your script. The script:
執行AGI腳本時,Application應用就是'agi',參數是腳本的文件名,同時腳本需要滿足以下條件

  • must be executable 必須可執行,chomd 755
  • must be located in /var/lib/asterisk/agi-bin  必須放置在指定目錄
  • must be specified complete with an extension 必須指定完整分機信息

For example to run a Python script named 'test.py' then a suitable extension item would be:

    exten => 1,2,agi,test.py

When your script runs, you get a message saying so on the asterisk console provided you have your 'verbosity' level set to 3 or higher. If your script isn't found (you mis-typed the name) you will get a message saying failed to execute ... no such file or directory. If your script isn't executable (you forgot to give it execute permission) you will get a message saying failed to execute ... permission denied.
腳本執行時,可以從控制檯上得到不同基本的詳細信息,例如,文件不能被執行,或者找不到文件等等。

In any case, don't pay too much attention to the console message saying agi script test.py completed returning 0. This simply indicated that executing (or attempting to execute) the script is done; it does NOT imply that the script executed successfully.
無論如何,不要在意控制檯上輸入的返回0,這僅僅表示腳本執行了,並不代表腳本執行成功。

Your script can issue messages to the Asterisk console by sending them to standard error. At least in the initial stages of developing an agi script it isn't a Bad Idea to have the script issue messages along the line of Hi, I'm starting now and Terminating normally just so you know your script ran and completed successfully.
通過向Asterisk控制檯信息輸出,可以得到AGI腳本的執行信息,至少在開發初期中,控制檯信息輸出是個好辦法。

You can also use the agi VERBOSE command (documented below) to send messages to the console with the added advantage that you can suppress or enable such messages depending on the verbosity setting.
通過agi VERBOSE命令,可以將信息發送到asterisk控制檯上,並且而通過verbosity設置可以關閉開啓這個功能。

Passing arguments to your AGI script
傳遞參數到AGI腳本

Yes Virginia you can pass arguments to your AGI script. You do so by following the name of your script with a vertical bar then the text you want to pass in. Extending the above example, to pass in "yada" as an argument we get:
在腳本名稱後緊跟豎線和需要傳送的文本,就可以把需要的參數傳入腳本

    exten => 1,2,agi,test.py|yada

AGI scripts *always* receive two arguments. The first argument is the full path to the script itself. The second argument is the stuff passed in from the "exten" line. It's that second argument we are concerned with here. A few things to note about the second argument:
AGI腳本總是接收2種參數,1是腳本的完整路徑,2是撥號方案中'Exten'傳遞的參數,需要關注的就是第2中參數,有幾點注意:

  • If no argument is given on the "exten" line or if the argument given is empty, then the argument received is an empty string.
    如果exten語句種沒有給定參數,或者參數值爲空,那麼接收到的參數爲空字符串
  • The argument received consists of everything on the line following the vertical bar up until a vertical bar, a semi-colon or a comma. That means the argument may contain spaces.
    接收的參數爲緊跟在豎線後面的一行數據,到豎線、分號、逗號結束,這意味着參數可以包含很多間隔隔開。
  • Quotes, single or double, are simply taken as part of the argument; they have no special effect.
    單引號,雙引號作爲參數的以部分,沒有特殊效果
  • By the time you get the argument any trailing spaces have been deleted but leading spaces are not deleted.
    得到參數時,會刪除後面的空格,不會刪除前面的空格


 

Communicating with Asterisk

In theory communicating with Asterisk is wonderfully simple:
與Asterisk通信是非常簡單的

  • You write to standard output to send a command to Asterisk.
    通過標準的輸出,發送命令到Asterisk
  • You read from standard input to get the reply from Asterisk.
    通過標準的輸入,從Asterisk接收信息

A few things to note:

  • At script startup time Asterisk sends various pieces of information to your script and you should read these items, via standard input, before doing much else. Each item is sent on a line terminated with a newline and the end of the list is indicated by an empty line. The list of items received will look something like this:
       agi_request: test.py
    agi_channel: Zap/1-1
    agi_language: en
    agi_type: Zap
    agi_callerid:
    agi_dnid:
    agi_context: default
    agi_extension: 3
    agi_priority: 1
    If you need the information provided then save it; otherwise feel free to throw it away.
    如果需要這些數據,就先保存起來,否則不用處理它
  • Commands sent to Asterisk must be terminated with a newline character.
    命令發送到Asterisk必須以換行符結束
  • The result returned by AGI commands is a text string, generally of the form:
    AGI命令返回文本字符串,如下格式
    200 Result=<number>
    although some commands return additional information after the number. If you send Asterisk an invalid command your result will be
    有時會在number數字後附加一些信息。如果向Asterisk發送了無效的命令,信息如下:
    510 Invalid or unknown command
    All commands return a result. Commands which don't really need to return a result return 0 as the number. Commands which do need to return a result return various values, as described under the heading 'Returns' below.
    所有的命令都有返回結果,不需要返回值的將返回數字0,需要返回值的在'Returns'後顯示註解信息。

 



 

ANSWER



Purpose
目的

Answer channel if not already in answer state.
如果通道不再應答狀態,則應答該通道

Returns

-1 on channel failure, or 0 if successful.

 



AUTOHANGUP <time>



Purpose

Cause the channel to automatically hangup at <time> seconds in the future. If <time> is 0 then the autohangup feature is disabled on this channel.
在指定時間自動通道掛機,如果時間爲0,則該命令在此通道上無效

Returns

0

Note

If the channel is hungup prior to <time> seconds, this setting has no effect. |
如果掛機發生在設定事件之前,此設置無效

 



CHANNEL STATUS [<channelname>]



Purpose

Return the status of the specified channel. If no channel name is specified, return the status of the current channel.
返回指定通道的狀態,如果通道沒有指定,返回當前通道狀態

Returns

-1 There is no channel that matches the given <channelname>   沒有匹配的通道
0 Channel is down and available     通道沒有上線(激活)但有效
1 Channel is down, but reserved     通道沒有上線(激活)但有預留
2 Channel is off hook          通道在掛機狀態
3 Digits (or equivalent) have been dialed  通道準備撥號
4 Line is ringing    通道正在振鈴
5 Remote end is ringing         通道遠端正在振鈴
6 Line is up                               線路激活可用
7 Line is busy                           線路忙

Examples

CHANNEL STATUS
Return the status of the current channel.

CHANNEL STATUS Zap/9-1
Return the status of channel Zap/9-1

Note

The <channelname> to use is the same as the channel names reported by the Asterisk console 'show channels' command.
通道名稱與asterisk控制檯上 show channels命令顯示的通道名字一致

 



EXEC <application> <options>



Purpose

Executes the specified Asterisk <application> with given <options>.
帶參數執行指定的Asterisk 應用

Returns

Whatever the application returns, or -2 on failure to find the application.
返回值-2表示執行錯誤,沒有找到指定應用

 



GET DATA <filename> [<timeout> [<max digits>]]



Purpose

Plays the given file and receives DTMF data. This is similar to STREAM FILE, but this command can accept and return many DTMF digits, while STREAM FILE returns immediately after the first DTMF digit is detected.
播放指定的語音文件,同時獲取DTMF按鍵信號,與STREAMFILE類似,但此命令能夠接收到多個DTMF按鍵,而STREAMFILE在接收到第一個DTMF按鍵時立刻返回。

Returns

  • If the command ended due to timeout then the result is of the form
        200 Result=<digits> (timeout)
    where <digits> will be zero or more ASCII characters depending on what the user pressed.

  • If the command ended because the maximum number of digits were entered then the result is of the form
        200 Result=<digits>
    and the number of digits returned will be equal to <max digits>.

  • In either case what you get are actual ASCII characters. For example if the user pressed the one key, the three key and then the star key, the result would be
        200 Result=13* (timeout)
    This differs from other commands with return DTMF as numbers representing ASCII characters.


Notes

  • Don't give an extension with the filename.
    音頻文件名稱命名不要與分機相同
  • Asterisk looks for the file to play in /var/lib/asterisk/sounds
  • If the user doesn't press any keys then the message plays, there is <timeout> milliseconds of silence then the command ends.
    如果用戶沒有按鍵,聲音播放完畢後,靜默<超時時間>,然後命令結束
  • The user has the opportunity to press a key at any time during the message or the post-message silence. If the user presses a key while the message is playing, the message stops playing. When the first key is pressed a timer starts counting for <timeout> milliseconds. Every time the user presses another key the timer is restarted. The command ends when the counter goes to zero or the maximum number of digits is entered, whichever happens first.
    在播放音頻和靜默時間內,用戶可以按鍵打斷,按鍵將停止播放音頻,超時時間計時從用戶第一個按鍵開始計時,每次按鍵重新計時,當用戶按鍵複合最大按鍵數量或超時時間結束,命令結束
  • If you don't specify a time out then a default timeout of 2000 is used following a pressed digit. If no digits are pressed then 6 seconds of silence follow the message.
    如果沒有定義超時時間,缺省的時間爲按鍵後20秒,如果沒有按鍵,靜默6秒後命令結束
  • If you want to specify <max digits> then you *must* specify a <timeout> as well.
    如果想定義最大按鍵,最好定義超時時間
  • If you don't specify <max digits> then the user can enter as many digits as they want.
    如果沒有定義最大按鍵,用戶可以按任意多的按鍵
  • Pressing the # key has the same effect as the timer running out: the command ends and any previously keyed digits are returned. A side effect of this is that there is no way to read a # key using this command.
    按#號箭的效果相當於超時時間結束,命令終止並返回#號建前面的按鍵,不能獲取到#號建本身

 



GET VARIABLE <variablename>



Purpose

Fetch the value of a variable.
取得變量值

Returns

Returns 0 if the variable hasn't been set. Returns 1 followed by the value of the variable in parenthesis if it has been set.

Example

SET VARIABLE Baffy "This is a test"200 result=1GET VARIABLE Baffy200 result=1 (This is a test)

 



HANGUP [<channelname>]



Purpose

Hangup the specified channel. If no channel name is given, hang up the current channel.

Returns

If the hangup was successful then the result is 200 result=1

If no channel matches the <channelname> you specified then the result is 200 result=-1

Examples

HANGUP
Hangup the current channel.

HANGUP Zap/9-1
Hangup channel Zap/9-1

Notes

The <channelname> to use is the same as the channel names reported by the Asterisk console 'show channels' command.
<channelname>與控制檯上'show channels'命令顯示的通道名字相同

With power comes responsibility. Hanging up channels other than your own isn't something that is done routinely. If you are not sure why you are doing so, then don't.

 



RECEIVE CHAR <timeout>



Purpose

Receive a character of text from a connected channel. Waits up to <timeout> milliseconds for a character to arrive, or infinitely if <timeout> is zero.
從鏈接的通道上獲取文本的字符,在超時時間內獲取到達的字符,如果超時時間爲0,則持續接收。

Returns

  • If a character is received, returns the ASCII value of the character as a decimal number. For example if the character 'A' is received the result would be
    如果一個字符串到達,以10進制數字的方式返回字符的ASCII碼,例如A的返回值爲:65
        result=65
  • If the channel does not support text reception or if the no character arrives in <timeout> milliseconds then the result is
    如果通道不支持文本接收,或者在超時時間內沒有字符被接收,結果如下
        result=0 (timeout)
  • On error or failure the result is
        result=-1


Note

Most channels do not support the reception of text.
大多數通道不支持接收文本

 



RECORD FILE <filename> <format> <escape digits> <timeout> [BEEP]



Purpose

Record sound to a file until an acceptable DTMF digit is received or a specified amount of time has passed. Optionally the file BEEP is played before recording begins.
錄製通道內的聲音,生成文件,直到接收到DTMF確認結束按鍵,或者超時時間結束。在錄製聲音時,可以選擇在錄製前提示'BEEP滴'。

Returns

  • The documentation in the code says on hangup the result is -1, however when I tried it the hangup result was
    源代碼文檔中描述掛機返回結果爲-1,但實際測試結果爲0(hangup)
        result=0 (hangup)
  • If an error occurs then the result is -1. This can happen, for example, if you ask for a non-existent format.
    如果有錯誤發生,返回值爲-1,例如沒有可生成的語音文件格式
  • If the user presses an acceptable escape digit then the result is a number representing the ASCII digit pressed. For example if recording terminated because the user pressed the '2' key the result is
        result=50 (dtmf)


Example

RECORD FILE baffy gsm 123 5000 beep
Record sound in gsm format to file 'baffy.gsm'. Play a beep before starting to record. Stop recording if user presses '1', '2' or '3', after five seconds of recording, or if the user hangs up.

Notes

  • Don't put an extension on the filename; the filename extension will be created based on the <format> specified.
  • The file will be created in
    /var/lib/asterisk/sounds

  • <format> specifies what kind of file will be recorded. GSM is a commonly used format. To find out what other formats are supported start Asterisk with at a verbosity level of at least 2 (-vvc) and look for the messages that appear saying "== Registered file format <whatever>'. Most but not all registered formats can be used, for example, Asterisk can read but not write files in 'mp3' format.
    錄音格式有很多種,GSM是常用的一種,可以在控制檯上(高等級模式,至少2個V)查看註冊到系統的文件格式,但不是所有的註冊文件格式都可以使用,例如Asterisk可以讀取但不能生成mp3文件格式
  • If you don't want ANY digits to terminate recording then specify "" instead of a digit string. To change the above example so no digits terminate recording use RECORD FILE baffy gsm "" 5000 beep
    如果不需要任何按鍵確認錄音結束,使用""代替確認按鍵字符
  • <timeout> is the maximum record time in milliseconds, or -1 for no timeout. When this document was written [Nov 2002] I was unable to get <timeout> to work; this command always kept recording until I pressed an escape digit or hung up, as if -1 had been specified for timeout. A patch to correct this has been submitted but has not yet shown up in the CVS tree.
    超時時間是定義的最大錄音時間週期,或者爲-1即沒有超時時間。在此文檔2002年11月編寫的時候,超時時間還不能正常工作。

 



SAY DIGITS <digit string> <escape digits>



Purpose

Say the given digit string, returning early if any of the given DTMF escape digits are received on the channel. If no DTMF digits are to be received specify "" for <escape digits>.
播音給定的數字字符,當取消按鍵確認收到則命令結束,如果不需要取消按鍵,採用""帶入函數

Returns

Zero if playback completes without a digit being received, or the ASCII numerical representation of the digit pressed, or -1 on error or hangup.

Example

SAY DIGITS 123 78#

The digits 'one', 'two', 'three' are spoken. If the user presses the '7', '8' or '#' key the speaking stops and the command ends. If the user pressed no keys the result would be 200 result=0. If the user pressed the '#' key then the result would be 200 result=35.

 



SAY NUMBER <number> <escape digits>



Purpose

Say the given number, returning early if any of the given DTMF escape digits are received on the channel. If no DTMF digits are to be accepted specify "" for <escape digits>.
播音指定的數值。

Returns

Zero if playback completes without a digit being received, or the ASCII numerical representation of the digit pressed, or -1 on error or hangup.

Example

SAY NUMBER 123 789

The phrase 'one hundred twenty three' is spoken. If the user presses the '7', '8' or '9' key the speaking stops and the command ends. If the user pressed no keys the result would be 200 result=0. If the user pressed the '#' key then the result would be 200 result=35.

 



SEND IMAGE <image>



Purpose

Send the specified image on a channel. The image name should not should not include the extension.


Returns

Zero if the image is sent or if the channel does not support image transmission. Returns -1 only on error or hangup.

Notes

  • Asterisk looks for the image in /var/lib/asterisk/images
  • Most channels do not support the transmission of images.

 



SEND TEXT "<text to send>"



Purpose

Send the given text to the connected channel.

Returns

0 if text is sent or if the channel does not support text transmission. Returns -1 only on error or hangup.

Example

SEND TEXT "Hello world"

Note

Most channels do not support transmission of text.

 



SET CALLERID <caller ID specification>



Purpose

Changes the caller ID of the current channel
設置當前通道的主叫號碼

Returns

Always returns 200 result=1

Example

SET CALLERID "John Smith"<1234567>

Notes

This command will let you take liberties with the <caller ID specification> but the format shown in the example above works well: the name enclosed in double quotes followed immediately by the number inside angle brackets.
這條命令可以按照規定格式任意修改主叫號碼,格式:名字用雙引號後面緊跟角括號裏面的數字
  • If there is no name then you can omit it.
    如果沒有名字,可以省略
  • If the name contains no spaces you can omit the double quotes around it.
    如果名字中沒有空格,可以省略雙引號
  • The number must follow the name immediately; don't put a space between them.
    號碼必須緊跟名字,而且中間不能有空格
  • The angle brackets around the number are necessary; if you omit them the number will be considered to be part of the name.
    數字兩邊的角括號是必須的,如果省略他,會被認爲號碼是名字的一部分

 



SET CONTEXT <new context>



Purpose

Sets the context for continuation upon exiting the application.
設置應用結束後的context從而繼續流程

Returns

Always returns 200 result=0.

Example

SET CONTEXT demo

Notes

  • Setting the context does NOT automatically reset the extension and the priority; if you want to start at the top of the new context you should set extension and priority yourself.
    設置context不會自動重設extension和priority,如果想從頭開始執行,需要手動設置extension和priority
  • If you specify a non-existent context you receive no error indication (the result returned is still 'result=0') but you do get a warning message on the Asterisk console.
    如果設置了不存在的context,沒有任何錯誤提示,在控制檯上將不會收到任何警告信息,仍然返回result=0

 



SET EXTENSION <new extension>



Purpose

Set the extension to be used for continuation upon exiting the application.

Returns

Always returns 200 result=0.

Example

SET EXTENSION 23

Note

  • Setting the extension does NOT automatically reset the priority. If you want to start with the first priority of the extension you should set the priority yourself.
  • If you specify a non-existent extension you receive no error indication (the result returned is still 'result=0') but you do get a warning message on the Asterisk console.

 



SET PRIORITY <new priority number>



Purpose

Set the priority to be used for continuation upon exiting the application.

Returns

Always returns 200 result=0.

Example

SET PRIORITY 5

Note

If you specify a non-existent priority you receive no error indication of any sort: the result returned is still 'result=0' and no warning is issued on the Asterisk console.

 



SET VARIABLE <variablename> <value>



Purpose

Sets a variable to the specified value. The variables so created can later be used by later using ${<variablename>}
in the dialplan.
設置變量的初始值,變量將被創建,並在後面的撥號方案中以${變量名字}形式使用

Returns

Always returns 200 result=1.

Example

SET VARIABLE station zap/3

Creates a variable named 'station' with the value 'zap/3'.

Notes

  • Unlike most of Asterisk, variable names are case sensitive. The names 'Baffy' and 'baffy' refer to two separate and distinct variables.
    與Asterisk的大多數變量不同,agi的變量是大小寫敏感的。

  • If the value being assigned contains spaces then put it inside double quotes.
    變量在賦值的時候,如果值中包含空格,必須加雙引號

  • If you want double quotes inside the value then you have to escape them. For example to create a variable CID whose value is "John Doe"<555-1212> you could use:
    如果值中有雙引號,需要去避免它,採用下面的格式

    SET VARIABLE CID "/"John Doe /"<555-1212>

    Be aware that the language you are using may eat the backslash before it gets passed to Asterisk; you may have to use two backslashes or otherwise tell the language that, yes, you really do want a backslash in the string you are sending.
    需要注意的是,開發語言可能會吃掉傳遞給asterisk的反斜線,因此需要使用2個反斜線,或者明確的告訴開發語言,字符串中的反斜線真正的含義。


  • These variables live in the channel Asterisk creates when you pickup a phone and as such they are both local and temporary. Variables created in one channel can not be accessed by another channel. When you hang up the phone, the channel is deleted and any variables in that channel are deleted as well.
    這些變量僅僅以本地的臨時的形式在接通電話時產生,並在於asterisk的通道。在一個通道上產生的變量不能被其他通道訪問,當掛機時,通道刪除,同時變量也刪除。

 



STREAM FILE <filename> <escape digits>



Purpose

Play the given audio file, allowing playback to be interrupted by a DTMF digit. This command is similar to the GET DATA command but this command returns after the first DTMF digit has been pressed while GET DATA can accumulated any number of digits before returning.
播放指定的語音文件,允許按鍵終止播放,這命令與GET DATA類似,但只返回用戶的第一個按鍵,GET DATA可以積累返回用戶的很多按鍵

Returns

If playback finished with no acceptable digit being pressed the result is zero. If an acceptable digit was pressed the result is the decimal representation of the pressed digit. If the channel was disconnected or an error occurred the result is -1.

Example

STREAM FILE welcome #

Plays the file 'welcome'. If the user presses the '#' key the playing stops and the command returns 200 result=35

Note

  • Don't give an extension with the filename.
  • Asterisk looks for the file to play in /var/lib/asterisk/sounds
  • Use double quotes if the message should play completely. For example to play audio file 'welcome' without allowing interruption by digits use: STREAM FILE welcome ""
    如果需要語音文件完整播放,需要定義中斷按鍵爲""

 



TDD MODE <setting>



Purpose

Enable or disable TDD transmission/reception on the current channel.
在當前通道上啓用關閉 TDD(分時雙功模式)收發模式

Returns

1 if successful or 0 if the channel is not TDD capable.

Example

TDD MODE on

Note

The argument <setting> can be 'on' or 'tdd' to enable tdd mode. It can also be 'mate' which apparently sets some unspecified tdd mode. If it is anything else ('off' for example) then tdd mode is disabled.

 



VERBOSE <message> [<level>]



Purpose

Sends <message> to the Asterisk console via the 'verbose' message system.
通過Verbose向Asterisk控制檯發送信息

Returns

Always returns 1

Example

VERBOSE Hello 3

Sends the message "Hello" to the console if the current Asterisk verbosity level is set to 3 or greater.

Notes

  • <level> is the verbosity level in the range 1 through 4.
    <level>是顯示信息的詳細程度,範圍1-4

  • If your message contains spaces, then enclose it in double quotes.
    如果輸出的信息包含空格,需要用雙引號引起真個信息

  • The Asterisk verbosity system works as follows. The Asterisk user gets to set the desired verbosity at startup time or later using the console 'set verbose' command. Messages are displayed on the console if their verbose level is less than or equal to desired verbosity set by the user. More important messages should have a low verbose level; less important messages should have a high verbose level.
    Asterisk信息輸出工作方式:在Asterisk啓動的時候設置level,或者使用控制檯命令‘set verbose’信息顯示將按照設定的級別顯示,重要信息需要低級別,一般信息需要高級別即可

 



WAIT FOR DIGIT <timeout>



Purpose

Waits up to 'timeout' milliseconds for channel to receive a DTMF digit

Returns

-1 on channel failure, 0 if no digit is received in timeout or the numerical value of the ascii of the digit received.

Note

Use -1 for the timeout value if you want the call to wait indefinitely.

Example

WAIT FOR DIGIT 3000

If the user didn't press a digit within three seconds then the response is 200 result=0. If the user pressed the 9 digit the response is 200 result=57.  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章