callback agendado

30
Callback Agendado Acompanhando as listas de discussões sobre Asterisk nosso amigo José Sanchez perguntou se existiria a possibilidade de adicionar ao seu PBX Asterisk uma facilidade encontrada nas centrais telefonicas convencionais de mercado. O Callback agendado em caso de ramal ocupado. Uma das caracteristicas mais atraentes do Asterisk é sua flexibilidade em relação a customizações. Valendo-se desta caracterisitica resolvi criar esse tutorial para incorporar ao seu PBX Asterisk uma funcionalidade padrão encontrada em sistemas convencionais. Como funciona: Vamos imaginar que o José (ramal 6001) precisa falar urgentemente com Ana (ramal 6050) do departamento de recursos humanos, ele acaba de ganhar uma viagem de 15 dias para as Ilhas Canário com direito a um acompanhante e necessita antecipar suas férias o quanto antes, do contrário perderá a viagem. Então ele tira o seu telefone do gancho e liga desesperadamente para Ana, mas o ramal de Ana está ocupado pois ela acaba de receber flores do seu marido e logo ligou para sua melhorar amiga para contar a novidade, ou seja, o ramal não irá desocupar tão cedo. José, desesperado tem que preencher o formulario no site da empresa que o premiou e não terá tempo de fazer as duas coisas, ou preenche o formulario ou fica tentando ligar para Ana. Neste caso a solução do CallBack Agendado o ajudaria perfeitamente. Quando ligar para Ana e o ramal estiver ocupado o PBX da o sinal de Busy e logo após informa: Disque 9 para conectar-se imediatamente a esse ramal assim que desocupar ou deixe um recado em sua caixa postal após o sinal. Configurando o CallBack Agendado

Upload: marcus-andreas

Post on 04-Mar-2015

182 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Callback Agendado

Callback AgendadoAcompanhando as listas de discussões sobre Asterisk nosso amigo José Sanchez perguntou se existiria a possibilidade de adicionar ao seu PBX Asterisk uma facilidade encontrada nas centrais telefonicas convencionais de mercado. O Callback agendado em caso de ramal ocupado.

Uma das caracteristicas mais atraentes do Asterisk  é sua flexibilidade em relação a customizações. Valendo-se desta caracterisitica resolvi criar esse tutorial para incorporar ao seu PBX Asterisk uma funcionalidade padrão encontrada em sistemas convencionais.

Como funciona:

Vamos imaginar que o José (ramal 6001) precisa falar urgentemente com Ana (ramal 6050) do departamento de recursos humanos, ele acaba de ganhar uma viagem de 15 dias para as Ilhas Canário com direito a um acompanhante e necessita antecipar suas férias o quanto antes, do contrário perderá a viagem.

Então ele tira o seu telefone do gancho e liga desesperadamente para Ana, mas o ramal de Ana está ocupado pois ela acaba de receber flores do seu marido e logo ligou para sua melhorar amiga para contar a novidade, ou seja, o ramal não irá desocupar tão cedo. José, desesperado tem que preencher o formulario no site da empresa que o premiou e não terá tempo de fazer as duas coisas, ou preenche o formulario ou fica tentando ligar para Ana.

Neste caso a solução do CallBack Agendado o ajudaria perfeitamente. Quando ligar para Ana e o ramal estiver ocupado o PBX da o sinal de Busy e logo após informa: Disque 9 para conectar-se imediatamente a esse ramal assim que desocupar ou deixe um recado em sua caixa postal após o sinal.

Configurando o CallBack Agendado

O CallBack agendado é composto de 2 blocos em seu DialPlan(extensions.conf) e um shell script.

Os nomes em verde são arquivos de audio que necessitam ser gravados.

Dialplan (extensions.conf)

;Esse é contexto de discagens dos seus ramais, no meu caso: 6000 ~ 6199

[ramais]

exten => _6[0-1][0-9][0-9],1,Dial(Local/${EXTEN},20,Tt)

Page 2: Callback Agendado

exten => _6[0-1][0-9][0-9],n,goto(status-${DIALSTATUS})

;————————————————————————————————

exten => _6[0-1][0-9][0-9],n(status-BUSY),Noop(** Ramal Ocupado – Com opção de Callback **)

exten => _6[0-1][0-9][0-9],n,Set(R-DESTINO=${EXTEN})

exten => _6[0-1][0-9][0-9],n,Playback(ramal-ocupado)

exten => _6[0-1][0-9][0-9],n,Playback(digite-9-callback)

exten => _6[0-1][0-9][0-9],n,Read(digito||1|9) ; utilize pipe para Asterisk 1.4 e coma para Asterisk 1.6

exten => _6[0-1][0-9][0-9],n,GotoIf($(digito) = 9)?callback,s,1:voicemail,s,1)

;————————————————————————————————

exten => _6[0-1][0-9][0-9],n(status-NOANSWER),Noop(** Ramal não Atende **)

exten => _6[0-1][0-9][0-9],n,Playback(ramal-naoatende)

exten => _6[0-1][0-9][0-9],n,Hangup()

;————————————————————————————————

exten => _6[0-1][0-9][0-9],n(status-CHANUNAVAIL),Noop(** Ramal Indisponivel **)

exten => _6[0-1][0-9][0-9],n,Playback(ramal-indisponivel)

exten => _6[0-1][0-9][0-9],n,Goto(voicemail,s,1)

;————————————————————————————————

exten => _6[0-1][0-9][0-9],n(status-CONGESTION),Noop(** Rede Congestionada **)

exten => _6[0-1][0-9][0-9],n,Playback(rede-congestionada)

exten => _6[0-1][0-9][0-9],n,Goto(voicemail,s,1)

;————————————————————————————————

;Esse é o contexto do CallBack Agendado

[callback]

Page 3: Callback Agendado

exten => s,1,Set(RAMAL-DESTINO=${R-DESTINO})

exten => s,n,Set(RAMAL-ORIGEM=${CALLERID(num)})

exten => s,n,System(/var/lib/asterisk/scripts/callback-agendado.sh ${RAMAL-ORIGEM} ${RAMAL-DESTINO})

exten => s,n,Playback(callback-agendado-ativo)

exten => s,n,hangup()

Shell Script (callback-agendado.sh)

#!/bin/bash

################################################### CallBack Agendado# Autor: Mestre Asterisk# http://mestreasterisk.com.br## Descrição: Ao ligar para um ramal que está# ocupado você tem a opção de digitar 9 para# agendar um callback assim que o mesmo estiver# desocupado.##################################################

make_callfile(){ORIGEM=$1DESTINO=$2

CALLFILE=$(cat <<-EOF1Channel: SIP/$ORIGEMMaxRetries: 120RetryTime: 5WaitTime: 10Context: ramaisExtension: $DESTINOPriority: 1)

FILE_NAME=”$TEMP_SPOOL”/$(date +%YNaVM%S)-$RAMAL_DESTINO.callecho “$CALLFILE” >> $FILE_NAMEchown root /$FILE_NAMEchmod 777 /$FILE_NAMEmv /$FILE_NAME /var/spool/asterisk/outgoing

Page 4: Callback Agendado

}

#VARIAVEIS DIRETORIOSASTERISK_CFG=”/etc/asterisk”TEMP_SPOOL=”/var/spool/asterisk”

make_callfile “$1″ “$2″

exit

Copie o script callback-agendado.sh para

/var/lib/asterisk/scripts

De permissão na pasta:

chmod 777 /var/lib/asterisk/scripts

Veja também: http://www.voip-info.org/wiki/view/Asterisk+tips+callback

Testando o CallBack

Para testar o CallBack agendado basta ocupar um ramal fazendo uma chamada para qualquer lugar e depois de outro ramal ligar para ele.

Se o status do ramal estiver ocupado ele abrira um menu para que agende o callback quando o ramal desocupar, discando 9. Quando o ramal desocupar automaticamente o Asterisk ira disparar uma chamada para o ramal de origem e outra para o ramal destino, assim conectando os dois.

Se reparar no bloco [ramais] irá perceber que existem outros status, como: NOANSWER,  CHANUNAVAIL e CONGESTION. Você poderá utilizar o CallBack Agendado para cada um desses status, basta seguir a lógica do status BUSY.

Call Files1 - Copy the wakeup.php file into

the /var/lib/asterisk/agi-binmake sure the PHP file is executable. You might have to run DOS2UNIX against it since I'm lazy and use my windows editor on it

Page 5: Callback Agendado

2 - Next update your extensions file to include an extension to call to schedule your wakeup calls.

exten => 77,1,AGI(wakeup.php)exten => 77,n,Hangup

3 - Reload your extensions table in asterisk with "dialplan reload" or stop and start asterisk.

When you call into Extension 77 you should be prompted for all your wakeup call time. This program uses the standard and additional sound files. So nothing else should be needed.

Para iniciar llamadas en asterisk desde una aplicacion externa como puede ser un CRM o un automarcador, hay varias formas para hacerlo.

Hay exactamente dos maneras de hacer lo:

Usando ficheros .call, es un fichero que situandole en el directorio /var/spool/asterisk/outgoing/fichero.call genera una llamada y la transfiere a una extensions.

Usando la API del manager del asterisk para activar dicha llamada.

 

1. Fichero de llamadas:la forma de usarlos es muy sencilla generamos un fichero con los parametros de la llamada, lo movemos al directosio /var/spool/asterisk/outgoing/ , Astersik detecta inmediatamente que hay un fichero en dicho directorio llama al destinatario y luego lo enlaza con la extensions local. A continuacion explicaremos los paramteros que acepta dicho fichero y lo ilustraremos con ejemplo de un proyecto real de automarcacion. Estos prametros especifican a donde llamar y como llamar:

o Channel: <channel>: el canal a usar para la llamadas salientes.o CallerID: Name <number> Identificador de llamada con el

formato,CallerID: Nombre <1234>o MaxRetries: <number> Numero de intentos si falla la llamada.o RetryTime: <number> Segundos entre intentoso WaitTime: <number> Segundos de espera antes de colgaro Account: pone al accountcode.

Si lia llamada es contestada, la conectamos con el siguiente canal y o aplicacion

o Context: Contexto en extensions.confo Extension: <ext> Extension definida en extensions.confo Priority: <priority> Prioridad de la extension en la que

deseamos conectaro Set: para asignar una variable para la llamada.

Page 6: Callback Agendado

o Application: En el lugar de usar una extension podemos llamar directamente a una aplicacion del asterisk.

o Data: Las opciones para la aplicacion.

Ejemplo1: realizar una llamada y pasarla a una extensio, ejemplo de la integracion de una aplicacion click2call de un CRM con asterisk.

donde le decimos que primero llame al usuario  local 100 y una vez contestada la llamada, llame al 902505009

Channel: SIP/100 MaxRetries: 2 RetryTime: 60 WaitTime: 90 Context:  salientes Extension:  902505009 Priority: 1 

Ejemplo2: Ejemplo de una aplicacion de email2fax, que despues de recibir el correo y extraer el asunto que es el numfax, y del adjunto el fihcero de fax en formato tif lo enviamos usando la aplicacion  txfax. 

Channel: ZAP/g1/numfaxMaxRetries: 1WaitTime: 20account: cliente-testfaxApplication: txfaxData: /tmp/fax/fax12.tif|caller

NOTA: para que funcione el autocall usando ficheros, hay que tener el modulo pbx_spool.so

13. Ahora vamos a usar la segunda forma de generar llamadas en el asterisk, usando la API del manager de asterisk, para dicha tarea nos interesa un comando del manager en concreto, ya que realiza la tarea que necesitamos y usa una sintaxis parecida a la de los ficheros .call, dicha sintaxis la detallaremos a continuacion:                               

Channel: el canal a usar para la llamadas salientes. Context: Contexto a utilizar cuando conecta la llamada. Exten: Extension a usar cuando se establece la conexion. Priority: Prioridad de la extension. Timeout: Timeout (en millisegundos por defecto30000

millisegunds) CallerID: identificador de llamada. Variable: Variables del canal tanto para el canal externo como el

local, con un maximo de 32 variables. Account: Accountcode, para aplicaciones de facturacion. Application: aplicacion de asterisk.

Page 7: Callback Agendado

Data : Parametros para la aplicacion. Async: para definir si la generacion ser sincrona o asincrona, la

asincrona es ideal en caso de que queramos genrar muchas llamadas sin recibir confirmacion ni respuesta de nuestro asterisk.

o ActionID: el id de la action a la hora de usar la API.

Ejemplo: una vez tenemos una conexion abierta con el manager de asterisk le tenemos que enviar los siguiente parametros, este ejemplo es el mismo que usar el SUGARCRM para realizar llamadas usando el asterisk:

Action: Originate Channel: SIP/101 Context: salientes Exten: 902505009 Priority: 1 Callerid: xxxxxxxxx Timeout: 30000 Variable: var1=23|var2=24|var3=25 ActionID: ABC45678901234567890  

; This is a sample section from an extensions.conf file showing how to auto-dial an outbound call; and play a prerecorded message when the call is answered.; To install this application:; Create message directory see [record-outboundmsgs] below for details; If needed, modify extension numbers and context names to make compatible with your local dialing plan; Add the contexts below to your /etc/extensions.conf file; Record messages see [record-outboundmsgs] below for details; Create a call file to test;; The outbound call can be triggered by a call file or manager commands via a telnet session;; Creating a call file to call 7026241632 using context @syndeo in the sip.conf file; set the caller ID to 7022340175 when placing the call; A correct Caller ID may be required when using some VOIP to PSTN gateway services.;; cat <<EOF > /var/spool/asterisk/tmp01; Channel: SIP/7026241632@syndeo; Callerid: 7022340175; MaxRetries: 5; RetryTime: 300; WaitTime: 45; Context: outboundmsg1; Extension: s; Priority: 1; EOF; mv /var/spool/asterisk/tmp01 /var/spool/asterisk/outgoing;

Page 8: Callback Agendado

;; For more information see:; http://www.voip-info.org/wiki-Asterisk+auto-dial+out+deliver+message; http://www.voip-info.org/wiki-Asterisk+auto-dial+out; http://www.voip-info.org/wiki-Asterisk+manager+dialout;

[outboundmsg1]exten => s,1,Set(TIMEOUT(digit)=5) ; Set Digit Timeout to 5 secondsexten => s,2,Set(TIMEOUT(response)=10) ; Set Response Timeout to 10 secondsexten => s,3,Answerexten => s,4,Wait(1)exten => s,5,Background(outboundmsgs/msg1) ; "play outbound msg"exten => s,6,Background(outboundmsgs/how_to_ack) ; "Press 1 to replay or 2 to acknowledge receiving this message"exten => 1,1,Goto(s,5) ; replay messageexten => 2,1,Goto(msgack,s,1) ; acknowledge messageexten => t,1,Playback(vm-goodbye)exten => t,2,Hangup; at this point we could do something like reschedule the call to try again later; or send an email saying the msg was not received,; or ...

[outboundmsg2]exten => s,1,Set(TIMEOUT(digit)=5) ; Set Digit Timeout to 5 secondsexten => s,2,Set(TIMEOUT(response)=10) ; Set Response Timeout to 10 secondsexten => s,3,Answerexten => s,4,Wait(1)exten => s,5,Background(outboundmsgs/msg2) ; "play outbound msg"exten => s,6,Background(outboundmsgs/how_to_ack) ; "Press 1 to replay or 2 to acknowledge receiving this message"exten => 1,1,Goto(s,5) ; replay messageexten => 2,1,Goto(msgack,s,1) ; acknowledge messageexten => t,1,Playback(vm-goodbye)exten => t,2,Hangup; at this point we could do something like reschedule the call to try again later; or send an email saying the msg was not received,; or ...

[msgack]exten => s,1,Playback(outboundmsgs/thankyou)exten => s,2,Playback(vm-goodbye)exten => s,3,Hangup; at this point we might want to log the message acknowledgement somewhere; and perhaps trigger some additional processing

Page 9: Callback Agendado

[record-outboundmsgs]; Record voice files;; Before using this the first time; mkdir /var/lib/asterisk/sounds/outboundmsgs; chown asterisk_user:asterisk_user /var/lib/asterisk/sounds/outboundmsgs; (Where asterisk_user = the user that asterisk runs under: = root for many installations);; In a context for incoming calls put something like; include => record-outboundmsgs;; Then call; 2051 to Record a new outbound msg1; 2052 to Record a new outbound msg2;; 2061 to Record the msg played when the recipient acks the message; 2062 to Record the "How to ACK message";; After dialing one of the extensions above:; Wait for the record start tone; Record your message; Press # to stop recording; Listen to an automatic playback of your new message;; outbound msg1exten => 2051,1,Wait(2)exten => 2051,2,Record(outboundmsgs/msg1:gsm)exten => 2051,3,Wait(2)exten => 2051,4,Playback(outboundmsgs/msg1)exten => 2051,5,wait(2)exten => 2051,6,Hangup;; outbound msg2exten => 2052,1,Wait(2)exten => 2052,2,Record(outboundmsgs/msg2:gsm)exten => 2052,3,Wait(2)exten => 2052,4,Playback(outboundmsgs/msg2)exten => 2052,5,wait(2)exten => 2052,6,Hangup;;; Msg played when msg is ackedexten => 2061,1,Wait(2)exten => 2061,2,Record(outboundmsgs/thankyou:gsm)exten => 2061,3,Wait(2)exten => 2061,4,Playback(outboundmsgs/thankyou)exten => 2061,5,wait(2)exten => 2061,6,Hangup;; Msg played after outbound msg: "Press 1 to replay or 2 to acknowledge receiving this message"exten => 2062,1,Wait(2)exten => 2062,2,Record(outboundmsgs/how_to_ack:gsm)exten => 2062,3,Wait(2)exten => 2062,4,Playback(outboundmsgs/how_to_ack)exten => 2062,5,wait(2)exten => 2062,6,Hangup

Page 10: Callback Agendado

Asterisk call files are structured files which, when moved to the appropriate directory, are able to automatically place calls using Asterisk. Call files are a great way place calls automatically without using more complex Asterisk features like the AGI, AMI, and dialplan, and require very little technical knowledge to use.

The Asterisk dial plan extensions.conf responds to someone calling an extension on a channel. If you want to initiate a call from an external application, there are several ways to do this.

There are basically four ways to initiate outgoing calls in Asterisk

Use .call files. A call file is a text file that when placed in the correct directory makes Asterisk make an outgoing call.

Use the manager API to activate a call. See Asterisk manager dialout Use the Asterisk CLI originate command FollowMe command of Asterisk 1.4: Since this has the abitility to fork (create

multiple calls) it could be 'misused' to initiate outgoing calls.

See also additional Digium documents.

New in Asterisk 1.8: A new application Originate has been introduced, that allows asynchronous call origination from the dialplan.

How Does It Work?

Move a call file into /var/spool/asterisk/outgoing/ (or the equivalent astspooldir directory defined in asterisk.conf).

If autoload=no in modules.conf be sure to load pbx_spool.so, otherwise call files will not work.

If the modification date on the call file is in the future, Asterisk will wait until the system time matches the modification time before executing the call file.

Asterisk will notice and immediately execute the directives defined in the call file. This can include either connecting to an Asterisk dial plan context, or performing a single Asterisk dial plan function call.

Asterisk will then remove the call file from the spooling directory (typically /var/spool/asterisk/outgoing).

Examples: See Minimal Call File Example and Syntax of Call Files sections.

Syntax of call files

Page 11: Callback Agendado

Specify where and how to callo Channel: <channel>: Channel to use for the call.o CallerID: "name" <number> Caller ID, Please note: It may not work if

you do not respect the format: CallerID: "Some Name" <1234>o MaxRetries: <number> Number of retries before failing (not including

the initial attempt, e.g. 0 = total of 1 attempt to make the call). Default is 0.

o RetryTime: <number> Seconds between retries, Don't hammer an unavailable phone. Default is 300 (5 min).

o WaitTime: <number> Seconds to wait for an answer. Default is 45.o Account: Set the account code to use.

If the call answers, connect it here:o Context: <context-name> Context in extensions.confo Extension: <ext> Extension definition in extensions.confo Priority: <priority> Priority of extension to start witho Set: Set a variable for use in the extension logic (example: file1=/tmp/to

); in Asterisk 1.0.x use 'SetVar' instead of 'Set'o Application: Asterisk Application to run (use instead of specifiying

context, extension and priority)o Data: The options to be passed to application

New (?) in Asterisk 1.4o Set: Can now also write to dialplan functions like CDR()o AlwaysDelete: Yes/No - If the file's modification time is in the future,

the call file will not be deletedo Archive: Yes/No - Move to subdir "outgoing_done" with "Status:

value", where value can be Completed, Expired or Failed.

At least one of app or extension must be specified, along with channel and destination

Minimal Call File Example

The most minimal call file example that we can make does nothing more than dial a number, and play a sound file.

hello-world.call

Channel: SIP/trunkname/18882223333Application: PlaybackData: hello-world

To run the call file above, you would type the following commands (we assume that the file already belongs to the asterisk user:

Page 12: Callback Agendado

mv hello-world.call /var/spool/asterisk/outgoing/

How does this work? Asterisk does the following when reading the above call file:

Dial the number 18882223333 out of the trunkname SIP trunk. Once the call has been answered, play the sound file

/var/lib/asterisk/sounds/hello-world (this sound file is included by default) Hang up the call.

As you can see, this is a very minimal call file example.

The 'failed' extension

If the call is not answered, and the standard extension failed with priority 1 exists in the same context, control will jump there (feature introduced in either Asterisk 1.2 or 1.4. NOTE: This works in asterisk 1.2.14)

o Note 1: This only works if you made the call with context, extension, and priority defined, and didn't use the application, data form.

o Note 2: This is a good place to update the CDR UserField with a value of the phone number that was being dialed using the SetCDRUserfield() application. Asterisk (as of 1.2.10) does not make the dialed channel (eg. IAX2/15551234567) available anywhere, so you have to pass it to yourself using Set: field of the .call file. (Along with anything else you want pass to the channel in this same variable).

o Note 3: The ${REASON} channel variable receives a value that represents the reason why the call failed. See more on Asterisk Reason variable.

Example

In .call file:Set: PassedInfo=15551234567-moreinfo-evenmoreinfo

extensions.confexten => failed,1,Set(NumberDialed=${CUT(PassedInfo,,1)})exten => failed,n,SetCDRUserField(${NumberDialed})

Page 13: Callback Agendado

Scope of variables

Make sure you know what prefixing a variable with _ or __ does! Especially Asterisk 1.0 and 1.2 behave differently for what concerns a) passing

on variables to channels and b) global variables Consider using DBGet and DBPut if you experience trouble passing variables

Creating and Moving Call Files

Because Asterisk can grab these files at any time (e.g. when the file is only 1 / 2 written), do not create the file directly in the /var/spool/asterisk/outgoing directory. Do something like this:

Create the call file in a different directory - e.g. /var/spool/asterisk/tmp/callfile-18882223333-01252010-104400.call

If Asterisk is running as a different user than you are creating the call file with (eg: If Asterisk runs as 'asterisk', but you are creating the call file as 'root',) then you will need to change the file's ownership permissions before sending it to the Asterisk spooling directory: chown asterisk:asterisk /var/spool/asterisk/tmp/callfile-18882223333-01252010-104400.call

mv /var/spool/asterisk/tmp/callfile-18882223333-01252010-104400.call /var/spool/asterisk/outgoing/

This works because the Unix move operation (mv command) merely moves the "inode" — the pointer to the file — making the entire file appear all at once and eliminates the possibility that Asterisk could read and act upon a partially written file. (Note that this is only true if the source and destination are on the same file system; otherwise, it does the equivalent of a "cp"; see below.)

Note: Using the copy command (cp) is not a safe method for adding a file to the outbound directory since other programs can read the new file in the midst of the copy operation when the file is only partially written. If you want to use CP you should copy the file in your call file directory under permissions which don't allow asterisk to read or remove it, then chown the file. This will save you from having to create an extra backup of the file.

Page 14: Callback Agendado

VB Scripts for creating your call files from a simple text file and then moving the files to asterisk spool directory using pscp.

First you have to create the text files using a text file that has all the phone numbers, this script expects the text file to be in format of one phone number per line.It then goes thru the text file and creates a new subfolder in current working directory for each 20 phone numbers it finds.It uses the phone number as the file name for each call file. Each subfolder that contains 20 call files is named with a number starting from 1.Once the call files are created use the second script to move it into the spool directory using pscp.Pscp is a free file transfer program that works over SSH, before you use this script make sure you have putty on your machine, create a saved session on putty for your asterisk system.

;!!!!!!!!!!!!!!!!!!!!!;Creates call text files taking the numbers from a flat text file that has one phone number per line;expample phonenumbers.txt;1234567890;2134567890;a text file that contains the 2 lines above (without the colons) will create 2 text files one for each number;you can copy and paste this whole code into a .vbs file in windows and then execute it.;put the file in the same directory as the text file with the phone numbers are.

Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFilePhones = objFSO.OpenTextFile("C:\calls\Phone.txt",1) ;change this line to your pathstrfname=1strcnt=1Set objFolders=objFSO.CreateFolder(strfname)Do While objFilePhones.AtEndOfStream = False

If strcnt=20 then;change this number to anything else if you want more or fewer simultaneous calls.

strfname=strfname+1

Set objFolders=objFSO.CreateFolder(strfname)strcnt=1

end ifstrLine = objFilePhones.ReadLine

strFullName = objFSO.BuildPath(strfname, strLine)Set objFileCalls = objFSO.CreateTextFile(strFullName)objFileCalls.closeSet objFileCalls = objFSO.OpenTextFile(strFullName,2)objFileCalls.Write("Channel: ");put your channel information

here, add a 1 before the number if your provider requires thatobjFileCalls.WriteLine(strLine)objFileCalls.WriteLine("CallerID: Name <1234>");change caller

id as needed

Page 15: Callback Agendado

objFileCalls.WriteLine("MaxRetries: 0");change this if you want it to retry

objFileCalls.WriteLine("RetryTime: 3")objFileCalls.WriteLine("WaitTime: 30");change this if you want

it to ring longer before giving upobjFileCalls.WriteLine("Context: test");put context hereobjFileCalls.WriteLine("Extension: 800");put extension hereobjFileCalls.WriteLine("Priority: 1");put priority hereobjFileCalls.Closestrcnt=strcnt+1

Loop;end code for first script that creates the call files.;the next script moves the files to the asterisk spool directory expecting pscp to be located under c:\pscp.exe and a ;named saved session to your asterisk box in putty as asterisk.;paste as neededSet objFSO = CreateObject("Scripting.FileSystemObject")

strcnt=1strfldr="C:\calls\"&strcnt

for i=1 to 1000 ;assuming that you don't have more than 1000 folders or 20000 files, if you do change this numberIf objFSO.FolderExists(strfldr) Then

strfldr="C:\calls\"&strcnt ;change path as neededSet objShell = CreateObject("WScript.Shell")strcmd="C:\pscp -pw passwordhere c:\calls\"&strcnt&"\*

root@asterisk:/var/spool/asterisk/outgoing" ;change username and password as needed, as well as path to pscp and call files

objShell.Run strcmdstrcnt=strcnt+1

elseexit for

End If

wscript.sleep(36000);change time interval between every folder it moves, when I created it I was dealing with recordings of ;15-20 seconds and 30 second wait time to answer the call, since I didn't want more than 20 calls ;simultaneous this worked for me. change as you like

next;end second file, paste this to a new .vbs file under the same directory then execute it.;end code

Examples

Example 1

Filename: 1.call

Page 16: Callback Agendado

Channel: Zap/1/1XXXXXXXXXXXXMaxRetries: 2RetryTime: 60WaitTime: 30Context: callmeExtension: 800Priority: 2

This will hook up to priority 2 of extension 800 in context callme in extensions.conf.

Example 2

To create a call to 14109850123 on an analog channel in group 2 and then connect it to the hypothetical extension 84 (which would map to 84,1,Dial(SIP/84) ) inside your network, here's the file you'd create in /var/spool/asterisk/outgoing:

1.2. Create the call on group 2 dial lines and set up3. some re-try timers4.

Channel: Zap/g2/14109850123MaxRetries: 2RetryTime: 60WaitTime: 30

1.2. Assuming that your local extensions are kept in the3. context called [extensions]4.

Context: extensionsExtension: 84Priority: 1

The above examples are good if you want to automatically play some recorded message, or something automatic that must start when the other party picks up the phone. In fact if you use the above for a conversation, you will have the outgoing phone ring, and when the other person picks up his phone, only then your extension starts to ring, so you miss the initial "hello" and maybe some more words!If you have outgoing calls in your dialplan defined in the [outgoing] context, to call

Page 17: Callback Agendado

14109850123 do this:

Example 3

To create a call to 14109850123 on a SIP phones called bt101, here's the file you'd create in /var/spool/asterisk/outgoing (whatever name is good, of course must be accessible and deletable by asterisk GNU/Linux user):

Channel: SIP/bt101MaxRetries: 1RetryTime: 60WaitTime: 30

1.2. Assuming that your outgoing call logic is kept in the3. context called [outgoing]4.

Context: outgoingExtension: 14109850123Priority: 1

Example 4

Auto dial a number and play a prerecorded message, allow replay, and message acknowledgementSee: Auto-dial and Deliver Message

Example 5

To create a call to an internal or external extension connected to an AGI

Channel: Local/1000@from-internalMaxRetries: 0RetryTime: 15WaitTime: 15Application: AGIData: myagi.agi

Page 18: Callback Agendado

On a trixbox/freepbx system this will dial internal extension 1000 (or you can put even an outside # here and it will follow outbound rules) and connect it to an AGI program. Note that unlike in extensions.conf where you can specify AGI(file.agi), here it must be separated. I use one agi to detect an incoming call to a special extension#, record the caller id, and then create the .call file to call back that number and connect it to a second agi.

Example 6: Use Asterisk as a PA system for emergency announcements.

Your Asterisk PABX can easily be used to send a voice message instantly to all (or a group of) phones.

It is quite easy to set this up. First you need to record 2 prompt sounds:

pa-welcome.wav

Please record you broadcast after the beep. End by pressing the hash key

pa-confirm.wav

Press 1 to send your message to all phones. Press 0 to cancel.

In your dialplan you create a context called [pa-system] and you Goto that context if the user dials 911 (or any other extension you find appropriate).

exten => 911,1,Goto(pa-system,s,1)

[pa-system]exten => s,1,Answerexten => s,n,Wait(2)exten => s,n,Playback(pa-welcome)exten => s,n,Wait(1)exten => s,n,Record(pa-message.wav)exten => s,n,Wait(1)exten => s,n,Background(pa-confirm)exten => s,n,WaitExten(10)exten => s,n,Hangup()exten => 1,1,System(cp /etc/asterisk/pa-system/*.call /tmp/)exten => 1,n,System(mv /tmp/*.call /var/spool/asterisk/outgoing/)exten => 0,1, Hangup()

Now what the above context does is to copy call files that you have prepared from a directory you create under /etc/asterisk to the outgoing queue. To avoid timing problems we first copy the files to the temp directory and then move them to the outgoing queue.

Page 19: Callback Agendado

The call file you create has to have the extension .call and is best to have the extension as file name. For example:

Filename: 218.call

Channel: SIP/218Callerid: 911MaxRetries: 10RetryTime: 5WaitTime: 20Context: pa-call-fileExtension: 10

So all call files in the directory /etc/asterisk/pa-system have the same content, except for the first line where you put the channel (like Zap/1 of SIP/218)The Context line refers to the context that will be executed. You have to create that context in you extensions.conf too:

[pa-call-file]exten => 10,1,Answer()exten => 10,n,Wait(1)exten => 10,n,Playback(pa-message)exten => 10,n,Wait(1)exten => 10,n,Hangup()

And you have a functional PA system!

One more feature you can add:If you use (SIP) phones that support a distinctive ringtone, you can program these phones to ring differently when Callerid 911 calls (to indicate it's an emergency).

How to schedule a Call in the Future

Files with a modified date in the future are ignored until that time arrives. Create the file in /var/spool/asterisk/tmp, modify the mtime using "touch", and then move it...

$ dateMon Mar 19 13:52:30 EDT 2007$ touch -d 20080101 /var/spool/asterisk/tmp/blah$ mv /var/spool/asterisk/tmp/blah .

Page 20: Callback Agendado

$ ls -l blah-rw-r--r-- 1 andrew users 0 Jan 1 00:00 blah

Bash example: to schedule a call in 100 s :

1. gives you the current time in seconds since dawn of UNIX

NOW=`date +%s`

1. add 100 seconds

let NOW=$NOW+100

1. create a timestamp used by 'touch -t' (no space between %M. %S, but the Wiki wants a space at this place)

TOUCH_TMSP=`date -d "1970-01-01 $NOW sec GMT" +%Y%m%d%H%M. %S`

1. and do the touch

touch -t $TOUCH_TMSP blah

Edit: many modern `touch´ binaries support all -d options of `date´. You can schedule a call in the future before moving it to /var/spool/asterisk/outgoing with

touch -d "1 week 2 days 4 hours 49 minutes 11 seconds" my_call_file_name

Tip on managing the number of simultaneous outbound calls

You can limit the number of simultaneous outgoing calls by managing the number of files in the outbound directory (/var/spool/asterisk/outgoing). For example, to limit Asterisk to only doing 10 simultaneous outdials just limit the number of files in the outbound directory to 10 at any one time. As the number decreases, you can move additional files into the directory to maintain the number of outgoing calls at the desired level.

Note: There are various user reports of Asterisk choking (=not processing some of the .call files) when too many files are moved simultaneously into the outgoing directory. Therefore it may be advisable to move them step-by-step with a slight delay.However, even then it is possible that Asterisk once in a while 'forgets' to process a call file (seen e.g. in 1.0.9). Possible soltuions:

Page 21: Callback Agendado

1. Find the cause and fix it in the source code, 2. Use the Manager API which hopefully doesn't exhibit this problem, 3. Design your application to cope with this effect, for example counter check

the existence of CDR data against your .call file details (execution time, destination, accountcode etc).

More examples

Asterisk auto-dial out deliver message Asterisk tips callback : How to create a callback system with .call files Asterisk tips Wake-Up Call PHP : Create, manage and execute Wake-Up calls

via phone A telephone reminder system for Asterisk

Callfiles and Call Detail Records

Avoid missing CDR records: Use either a) Context/Extension/Priority in the call file instead of Application/Data, or b) call a Local channel instead of directly calling the desired channel. Else Asterisk will bypass the process that tracks the call and no CDR record will be generated. When using Context/Extension/Priority, you are really using a Goto type function which just puts the call into the correct part of the dialplan and to it is the same as if the caller had dialed the call manually and so the call is logged.

The phone number you are dialling will not be stored in the CDR by * - if you need this information for CDR processing you can set the CallerID in the call file to this number and it will be stored. However, this will present the person you are calling their own phone number, which doesn't make much sense. A better solution might be to put the number you are dialing in the Set: channel variable in the .call file and later put it into the UserField of the CDR. See example above in the first section.

Tips and hints

Create the call file elsewhere, and move it (better not use copy, see above) into the directory after you're done creating it. Asterisk is very aggressive in grabbing these files, and if you're still creating it when it grabs the file, you'll get errors, so best to create first and then copy in to the outgoing directory all at once.

The call file must be owned by the user asterisk runs as, so asterisk can utime() it, or you will get permission errors.

Page 22: Callback Agendado

If you are using POTS (Plain Old Telephone System) lines attached to a channel bank with FXO cards, it's likely that you will run into problems sensing when your callee picks up their phone - especially to cell phones. Once Asterisk hands off a call to an FXO line (ie, it starts to ring), the system counts the call as 'answered', and continues its merry way. This means that your voice prompts get played to a ring tone, and your users are presented with a silent call.

Some things to try:

o In zapata.conf, try adding callprogress=yes above your channel => n definition for the FXO lines. (remember that settings set above the channel flow down, and that you need to clear this setting with a callprogress=no for any channels you might not want this to affect!)

This is experimental, only sometimes works, and only for North American tones.

On my system, this setting failed miserably, to the point that I could no longer make outgoing calls, and calls were dropped.

o Another option (At least in example 3), is to repeat your message. Note the ResponseTimeout(2), to set the pause between repeats to 2 seconds, and the GoTo(s|1), to repeat the prompts.

o Yet another option is to use an application like "WaitForSilence" that will wait for a certain amount of silence before beginning to play the message. See bugs.digium.com #2467 for this app, which will probably soon appear in CVS.

Try app_machinedetect.c application for detection of answering machines. This works best with PRI, VoIP, or a POTS with callprogress enabled. (This will cause a 'dead-air' silent pause at the beginning of all calls and with well-chosen settings will not provide better than 80-90% accuracy.)

Be advised that, if you create a new .call file and move it into the outgoing Asterisk directory for processing AND it has the same file name as a .call file which was just processed, Asterisk will throw the new file in the bit bucket.

A Few Ideas

What Can You Do With This Interface?

Setup a cron job to dial out at specific times. Stress test your server for call load. Prank call your friends with pre-recorded messages. War dialing. Auto-dialing / telemarketing. Create an alarm program to wake you up in the mornings. Create auto-callback functionality from your extensions. Connect calls between your extension and a number using a web interface /

other application.

Page 23: Callback Agendado

The possibilities are endless!

Programming Libraries For Creating / Using CallFiles

There are several programming libraries which abstract file operations and simplify the call file process.

http://pycall.org|pycall - A flexible python library for creating and using Asterisk callfiles.