Soporte & Consultoria

Soporte Remoto y Consultoria skype : ambiorixg12.
Nota no se brinda ningun tipo de consulta o soporte fuera del blog de forma gratuita

domingo, 22 de diciembre de 2024

while endwhile

 exten=>330,1,answer()

same=>n,Set(i=1)

same=>n,While($[${i} < 5])

;same=>n,Agi(/var/www/html/dial_agi.php,${i})

same=>n,Saydigits(${i})

same=>n,Set(i=$[${i} + 1])

same=>n,EndWhile()


;; code after  while end

same=>n,playback(demo-thanks)

same=>n,hangup()


jueves, 12 de diciembre de 2024

confbridge

cmd.php?coference=989898000036&action=resume



<?php
require_once("./confbridgeinfo.php");  // get conf channel info

//Function to run the  commands
function runcmd($command){

$socket = fsockopen("127.0.0.1","7831", $errno, $errstr,60);
      if (!$socket){
        echo "$errstr ($errno)\n";
        }else{
            fputs($socket, "Action: Login\r\n");
            fputs($socket, "UserName: admin\r\n");
            fputs($socket, "Secret: 193\r\n\r\n");

            fputs($socket, "Action: Command\r\n");
            fputs($socket, "Command: $command\r\n\r\n");

            fputs($socket, "Action: Logoff\r\n\r\n");
           while (!feof($socket)){
          echo fgets($socket).'<br>';

 
           }
            fclose($socket);
            }


}       


// end  of the function section //

$coference=$_GET['coference'];

$action=$_GET['action'];

if($action=="hold"){
 $hold="channel originate Local/600@hold-context extension $coference@sidialConfBridges";


$agent_chan=get_conf_info($coference)[1];
 
$mute="confbridge mute $coference $agent_chan";
runcmd($hold);
runcmd($mute);

}

elseif($action=="resume"){

echo $hold_channel=get_conf_info($coference)[0];

 $unhold="channel request hangup $hold_channel";
 $unmute="confbridge unmute $coference all";

runcmd($unhold);
runcmd($unmute);
}
else {

///Nothing for now
}


?>

----------------------------


confbridgeinfo.php

<?php

$arr=array();


function  get_conf_info($agent){
$socket = fsockopen("127.0.0.1","7831", $errno, $errstr,60);
      if (!$socket){
        echo "$errstr ($errno)\n";
        }else{
            fputs($socket, "Action: Login\r\n");
            fputs($socket, "UserName: admin\r\n");
            fputs($socket, "Secret: 1333\r\n\r\n");

            fputs($socket, "Action: ConfbridgeList\r\n");
            fputs($socket, "Conference: $agent\r\n\r\n");

            fputs($socket, "Action: Logoff\r\n\r\n");
           while (!feof($socket)){
         // echo fgets($socket).'<br>';
          $arr[]=fgets($socket);
 
           }
            fclose($socket);
            }


foreach($arr as $key=>$value){
//echo "$key - $value<br>";


if(substr_count($value,"hold")){
  
 
 $arr['channel']=  explode(" ",$value)[1];
  
}



elseif(substr_count($value,"SIP")){
  
 
 $arr['agent']=  explode(" ",$value)[1];
  
}


} 

if (isset($arr['agent'])) {
      
return   $channels=explode(" ","$arr[channel] $arr[agent]");



} else {
    // If the channel does not exist, create an error message and encode $arr
    $arr['e'] = "No conference channel found";

}

}


//print_r(get_conf_info($argv[1]));
?>

channel originate from AMI

 <?php



$conferece=$_GET['conference'];


$action=$_GET['action'];


if($action=="hold"){

 $command="channel originate Local/600@hold-context extension $conferece@contextConfBridges";


}


elseif($action=="resume"){




}

$socket = fsockopen("127.0.0.1","7831", $errno, $errstr,60);

      if (!$socket){

        echo "$errstr ($errno)\n";

        }else{

            fputs($socket, "Action: Login\r\n");

            fputs($socket, "UserName: admin\r\n");

            fputs($socket, "Secret: 113333\r\n\r\n");


            fputs($socket, "Action: Command\r\n");

            fputs($socket, "Command: $command\r\n\r\n");


            fputs($socket, "Action: Logoff\r\n\r\n");

           while (!feof($socket)){

          echo fgets($socket).'<br>';


 

           }

            fclose($socket);

            }

 
?>


get confbridge channel info

 <?php

header('Content-Type: application/json');

$arr=array();

$agent=$_GET['agent'];


$socket = fsockopen("127.0.0.1","7831", $errno, $errstr,60);
      if (!$socket){
        echo "$errstr ($errno)\n";
        }else{
            fputs($socket, "Action: Login\r\n");
            fputs($socket, "UserName: admin\r\n");
            fputs($socket, "Secret: 113333333\r\n\r\n");

            fputs($socket, "Action: ConfbridgeList\r\n");
            fputs($socket, "Conference: $agent\r\n\r\n");

            fputs($socket, "Action: Logoff\r\n\r\n");
           while (!feof($socket)){
         // echo fgets($socket).'<br>';
          $arr[]=fgets($socket);
 
           }
            fclose($socket);
            }


foreach($arr as $key=>$value){
//echo "$key - $value<br>";  // to show  all values


if(substr_count($value,"hold")){   ///search value 
  
 
 $arr['channel']=  explode(" ",$value)[1];  //grab the exact info
  
}

} 

if (isset($arr['channel'])) {
      
    echo json_encode(array('channel' => trim($arr['channel'])));
//foreach($arr as  $k=>$v){
//echo  "$k:$v";

//}

} else {
    // If the channel does not exist, create an error message and encode $arr
    $arr['e'] = "No conference channel found";
    echo json_encode(array('e' => $arr['e']));

}


?>

domingo, 8 de diciembre de 2024

get channel name function

$channel = "SIP/8001-3455ac;";


function get_channel($channel, $device) {

    // Ensure $device is treated as a string for consistency in comparison

    if (strpos($channel, (string)$device) !== false) {

        // Use a more robust way to extract the channel before the dash

        return explode("-", $channel)[0];

    }

    return null;  // Return null if the device is not found

}



$device = 8001;

$channelResult = get_channel($channel, $device);


if ($channelResult) {

    echo "Channel: " . $channelResult;

} else {

    echo "Device not found in the channel.";

}


jueves, 5 de diciembre de 2024

channel redirect , channel originate, channel request hanguip

CLI> channel redirect SIP/989898000036-00000007 hold-context,600,1


989898000036@sidialConfBridges



channel redirect SIP/989898000036-00000007 sidialConfBridge,989898000036,1



 channel redirect SIP/989898000036-00000008 sidialConfBridges,989898000036,1


atest*CLI> channel originate Local/600@hold-context extension 989898000036@sidialConfBridges



atest*CLI> channel request hangup Local/600@hold-context-00000016;1

[hold-context]
exten => 600,1,Answer()
exten => 600,n,MusicOnHold(default)
exten => 600,n,Hangup()

pjsip template

res_pjsip Configuration Examples

 

 ;===============TRANSPORT


[simpletrans]

type=transport

protocol=udp

bind=0.0.0.0


;===============ENDPOINT TEMPLATES


[endpoint-basic](!)

type=endpoint

context=internal

disallow=all

allow=ulaw


[auth-userpass](!)

type=auth

auth_type=userpass


[aor-single-reg](!)

type=aor

max_contacts=1


;===============EXTENSION 6001


[6001](endpoint-basic)

auth=auth6001

aors=6001


[auth6001](auth-userpass)

password=6001

username=6001


[6001](aor-single-reg)


;===============EXTENSION 6002


[6002](endpoint-basic)

auth=auth6002

aors=6002


[auth6002](auth-userpass)

password=6002

username=6002


[6002](aor-single-reg)


;===============EXTENSION 6003


[6003](endpoint-basic)

auth=auth6003

aors=6003


[auth6003](auth-userpass)

password=6003

username=6003


[6003](aor-single-reg)


https://docs.asterisk.org/Configuration/Channel-Drivers/SIP/Configuring-res_pjsip/res_pjsip-Configuration-Examples/

domingo, 1 de diciembre de 2024

Ajax call file

<title>AJAX Timer Example</title>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


<script>


function callAgentConf() {

    // Fetch the session variable via PHP and inject it into the URL

    $.ajax({

        type: "GET",  // Use GET method

        url: "call_file.php",  // Path to the PHP script

        data: { wpExten: "<?= $_SESSION['wpExten']; ?>" },  // Pass the session variable using GET

        success: function(data) {

            console.log(data); // Log the response from the server

            if (data == 'ok') {

                txtCallStatus.innerHTML = "<i><?=$TEXT_Entrato_in_conferenza?></i>"; // Success message

                gotConf = false; // Set a variable (you can modify or use it as needed)

            } else {

                txtCallStatus.innerHTML = "<i><?=$TEXT_Errore_Non_entrato_in_conferenza?></i>"; // Error message

            }

        }

    });

}


// Call the function after 1 second

setTimeout('callAgentConf()', 1000);

</script> </head> <body>

------------

 <?php

session_start();  // Make sure session is started if you are using session variables


// Retrieve the 'wpExten' GET parameter from the URL (passed via AJAX)

if (isset($_GET['wpExten'])) {

    // Use the GET parameter to set $myPaddedUserId

    $myPaddedUserId = "989898" . str_pad($_GET['wpExten'], 6, '0', STR_PAD_LEFT);


    // Debugging: Output the $myPaddedUserId to make sure it was set correctly

    // echo "Using wpExten: " . $myPaddedUserId;


    // Running the system command to kick the user from the conference bridge

    $sysCmd = "/usr/bin/sudo /usr/sbin/asterisk -rx 'confbridge kick ".$myPaddedUserId." all'";

    $foo = `$sysCmd`;  // Execute the system command


    // Prepare the .call file contents

    $callFilePath = "/tmp/" . rand(1000000, 9999999) . ".call";

    $dialString = "Channel: SIP/" . $myPaddedUserId;

    $callFileContents = $dialString . "\n" .

                        "MaxRetries: 0\n" .

                        "Context: sidialConfBridges\n" .

                        "Extension: " . $myPaddedUserId . "\n" .

                        "Set: myExten=" . $myPaddedUserId . "\n" .

                        "CallerID: conf <conf>\n" .

                        "WaitTime: 10";


    // Write the .call file

    $fh = fopen($callFilePath, "w");

    fwrite($fh, $callFileContents);

    fclose($fh);


    // Move the .call file to the outgoing directory

    $sysCmd = "/usr/bin/sudo /bin/mv " . $callFilePath . " /var/spool/asterisk/outgoing/" . rand(1000000, 9999999) . ".call";

    $foo = `$sysCmd`;  // Execute the system command


    // Output 'ok' to indicate success

    echo "ok";

} else {

    // If the 'wpExten' parameter is not provided, return an error

    echo "error: wpExten parameter missing";

}

?>


lunes, 18 de noviembre de 2024

domingo, 10 de noviembre de 2024

agi commands



#!/bin/php 
<?php
$agent=7000;


$timeout=12;




echo "EXEC Dial \"PJSIP/$agent,$timeout\"\n";




//echo "EXEC G

echo "EXEC Dial \"PJSIP/6000,10\"\n";


echo "EXEC Goto \"internal,100,1\"\n";



echo "EXEC Playback goodbye\n";
 

echo "SET VARIABLE $variableName \"$variableValue\"\n";

echo "EXEC  saydigits 0133";

echo "EXEC Verbose \"TEST VAR IS :  $var \"\n";

?>

miércoles, 30 de octubre de 2024

Real Time Transcription

 https://www.youtube.com/watch?v=ypcsB5Ld6zw&


https://community.asterisk.org/t/is-it-possible-to-transcribe-live-calls-with-asterisk/98992/7


https://platform.openai.com/docs/guides/audio/next-steps


https://platform.openai.com/docs/guides/realtime/quickstart


https://openai.com/index/introducing-the-realtime-api/

miércoles, 16 de octubre de 2024

pjsip example template

 https://docs.asterisk.org/Configuration/Channel-Drivers/SIP/Configuring-res_pjsip/res_pjsip-Configuration-Examples/

lunes, 7 de octubre de 2024

calling script

 <?php

//error_reporting(E_ALL);

//ini_set('display_errors', 1);

header('Content-Type: application/json');

echo json_encode($_REQUEST, JSON_PRETTY_PRINT);


$timeout=100;

$host="127.0.0.1";

$port=5038;


$src = preg_replace('/\s+/', '', $_GET['src']);

$dst = preg_replace('/\s+/', '', $_GET['dst']);

$trunk = preg_replace('/\s+/', '', $_GET['trunk']);

$cid = preg_replace('/\s+/', '', $_GET['cid']);

$id = preg_replace('/\s+/', '', $_GET['id']);


$socket = fsockopen("$host","$port", $errno, $errstr, 10);

      if (!$socket){

        echo "$errstr ($errno)\n";

        }else{

            fputs($socket, "Action: Login\r\n");

            fputs($socket, "UserName: admin\r\n");

            fputs($socket, "Secret: oy13xtq7h\r\n\r\n");


          $wrets=fgets($socket,128);

       //       echo $wrets;

              fputs($socket, "Action: Originate\r\n" );

              fputs($socket, "Channel: Local/$src@internal\r\n" );

              fputs($socket, "Exten: $dst\r\n" );

               fputs($socket, "Context: internal\r\n" );

               fputs($socket, "Priority: 1\r\n" );

               fputs($socket, "CallerID: $cid\r\n" );

                fputs($socket, "Variable: __ext=$ext\r\n" );

               fputs($socket, "Variable: __dest=$dest\r\n" );

               fputs($socket, "Variable: __cid=$callerid\r\n" );

             fputs($socket, "Async: yes\r\n\r\n" );   

        fputs($socket, "Action: Logoff\r\n\r\n");

           while (!feof($socket)){

 $result=fgets($socket);

 $result= stristr($result,"$number");

 $d=strlen($result);




}


fclose($socket);

 }


?>


;;;;;;;;;;;;;;;;
exten=>_*x.,1,Noop(${EXTEN})
same=>n,Agi(/root/vars.py,${EXTEN})
same=>n,Noop(------${prefix} ${cid} ${dst}---)
;same=>n,Set(CALLERID(num)=${cid})

same => n,ExecIf($[${LEN(${cid})} > 0]?Set(CALLERID(num)=${cid}):)

same=>n,goto(internal,**${prefix}${dst},1)
same=>n,hangup()
---------
nano /root/vars.py   
                                                                        
#!/usr/bin/env python3
import sys
number=sys.argv[1]

e=number.split('*')

e=[int(a) for a in e if len(a)>0]

cid='cid'

dst='dst'
prefix='prefix'

print(f'SET VARIABLE {prefix} "{e[0]}"\n')

print(f'SET VARIABLE {cid} "{e[1]}"\n')

print(f'SET VARIABLE {dst} "{e[2]}"\n')



.....
[usa]
exten=>_**1.,1,Gosub(monitor,${EXTEN:3},1)
same=>n,Dial(PJSIP/zadarma/sip:+${EXTEN:3}@185.45.155.17:5060,,r)
same=>n,hangup()
exten=>h,1,Noop(${path}${STRFTIME(${EPOCH},,%Y-%m-%d_%H-%M-%S)}-${EXTEN}_${src}.wav)
same=>n,System(python3 /root/s3_recordings.py ${file})

[voipcloud]
exten=>_**4.,1,Gosub(monitor,${EXTEN:3},1)
same=>n,Set(CALLERID(num)=+61480039787)
same=>n,Dial(PJSIP/t1/sip:+${EXTEN:3}@sipm2.au.voipcloud.online:7060,,r)
same=>n,hangup()

exten=>h,1,Noop(${path}${STRFTIME(${EPOCH},,%Y-%m-%d_%H-%M-%S)}-${EXTEN}_${src}.wav)
same=>n,System(python3 /root/s3_recordings.py ${file})


sábado, 28 de septiembre de 2024

Python delay script for asterisk

 


#!/usr/bin/env python


import subprocess

import time

import sys


# Check if the caller argument is provided

if len(sys.argv) < 2:

    print("Usage: script.py <caller>")

    sys.exit(1)


caller = sys.argv[1]


i = 0

while i < 30:

    print(i)

    time.sleep(1)

    i += 1


# Run the command and capture the output

command = ['/usr/sbin/asterisk', '-x', 'channel redirect {} vc_lookup,100,play'.format(caller)]

try:

    result = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    output, error = result.communicate()


    # Print the output

    print(output)

    if error:

print("Error:", error)


except Exception as e:

    print("An error occurred:", str(e))

lunes, 23 de septiembre de 2024

google tts asterisk using python virtual env

 [vaccine-rev]

exten=>100,1,Answer()

same=>n,Set(fname=${CHANNEL})

same=>n,agi(/var/www/html/google_tts/tts.py,${fname:4},"Total number of students registered with this telephone number.")

same=>n,playback(/var/www/html/google_tts/audios/${fname:4})

same=>n,Saynumber(3)

same=>n,agi(/var/www/html/google_tts/tts.py,${fname:4},"David is missing the following vaccines:")

same=>n,playback(/var/www/html/google_tts/audios/${fname:4})


same=>n,hangup()

---------
#!/var/www/html/google_tts/myenv/bin/python3

import os
import sys

import google.cloud.texttospeech as tts

# Set the path to your Google Cloud credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/var/www/html/google_tts/voice.json"

def text_to_wav(voice_name: str, text: str):
    language_code = "-".join(voice_name.split("-")[:2])
    text_input = tts.SynthesisInput(text=text)
    voice_params = tts.VoiceSelectionParams(
        language_code=language_code, name=voice_name
    )

    # Set the audio configuration with 8000 Hz sample rate
    audio_config = tts.AudioConfig(
        audio_encoding=tts.AudioEncoding.LINEAR16,
        sample_rate_hertz=8000  # Set sample rate to 8000 Hz
    )

    client = tts.TextToSpeechClient()
    response = client.synthesize_speech(
        input=text_input,
        voice=voice_params,
        audio_config=audio_config,
    )

    # Change the path to save the file in the desired location
    filename = f"/var/www/html/google_tts/audios/{sys.argv[1]}.wav"  # Specify the desired save path
    with open(filename, "wb") as out:
        out.write(response.audio_content)
        print(f'Generated speech saved to "{filename}"')

# Ensure the command line argument is provided
if len(sys.argv) > 1:
    text_to_wav("en-US-Studio-O", sys.argv[2])


#######

(myenv) [root@freepbx google_tts]# pip list
Package                   Version
------------------------- ---------
cachetools                4.2.4
certifi                   2024.8.30
charset-normalizer        2.0.12
google-api-core           2.8.2
google-auth               2.22.0
google-cloud-texttospeech 2.11.1
googleapis-common-protos  1.56.3
grpcio                    1.48.2
grpcio-status             1.48.2
idna                      3.10
pip                       21.3.1
proto-plus                1.23.0
protobuf                  3.19.6
pyasn1                    0.5.1
pyasn1-modules            0.3.0
requests                  2.27.1
rsa                       4.9
setuptools                39.2.0
six                       1.16.0
urllib3                   1.26.20
(myenv) [root@freepbx google_tts]# pip freeze
cachetools==4.2.4
certifi==2024.8.30
charset-normalizer==2.0.12
google-api-core==2.8.2
google-auth==2.22.0
google-cloud-texttospeech==2.11.1
googleapis-common-protos==1.56.3
grpcio==1.48.2
grpcio-status==1.48.2
idna==3.10
proto-plus==1.23.0
protobuf==3.19.6
pyasn1==0.5.1
pyasn1-modules==0.3.0
requests==2.27.1
rsa==4.9
six==1.16.0
urllib3==1.26.20




martes, 11 de junio de 2024

asterisk click to call and CDR post

<?php /* http://45.32.165.238/ami/webcall.php?src=101&dst=8095445555&trunk=400&cid=18007142323 */ $timeout=100; $host="127.0.0.1"; $port=5038; $src = preg_replace('/\s+/', '', $_GET[src]); $dst = preg_replace('/\s+/', '', $_GET[dst]); $trunk = preg_replace('/\s+/', '', $_GET[trunk]); $cid = preg_replace('/\s+/', '', $_GET[cid]); $id = preg_replace('/\s+/', '', $_GET[id]); $pitch = preg_replace('/\s+/', '', $_GET[pitch]); $num=$dst; $ext=$src ; $context="outbound-click-to-call"; $socket = fsockopen("$host",$port,$errno, $errstr, $timeout); fputs($socket, "Action: Login\r\n"); fputs($socket, "UserName: admin\r\n"); // fputs($socket, "Secret: Krtzv\r\n\r\n"); // // $wrets=fgets($socket,128); fputs($socket, "Action: Originate\r\n" ); fputs($socket, "Channel: Local/$src@from-internal/n\r\n" ); fputs($socket, "Exten: $dst\r\n" ); fputs($socket, "Context: $context\r\n" ); fputs($socket, "Priority: 1\r\n" ); fputs($socket, "CallerID: $cid\r\n" ); fputs($socket, "Variable: __trunk=$trunk\r\n" ); fputs($socket, "Variable: __dst=$dst\r\n" ); fputs($socket, "Variable: __src=$src\r\n" ); fputs($socket, "Variable: __cid=$cid\r\n" ); fputs($socket, "Variable: __id=$id\r\n" ); fputs($socket, "Variable: __pitch=$pitch\r\n" ); fputs($socket, "Async: yes\r\n\r\n" ); fputs($socket, "Action: Logoff\r\n\r\n"); sleep (1); $wrets=fgets($socket,128); echo $wrets; ?> <?php
// Define the API endpoint
$url = 'https://asterisk-voip.com';
// Initialize a cURL session
$ch = curl_init($url);
// Define the headers
$headers = [
'Accept: application/json',
'Authorization: Basic 12345password',
'Content-Type: multipart/form-data',
'X-CSRF-TOKEN: '
];
// Define the form data
$postFields = [
'to' => "$argv[1]",
'from' => "$argv[2]",
'recording_file' => new CURLFile("$argv[3]"), // Replace with the actual file path
'start_time' => "$argv[5]",
'end_time' => "$argv[6]",
'call_length' => "$argv[4] Seconds"
];
// Set the cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} else {
// Print the response
echo $response;
}
// Close the cURL session
curl_close($ch);
?>
---------
[outbound-click-to-call]
exten => _X.,1,Set(calltime=${STRFTIME(${EPOCH},,%Y%m%d%H%M%S)})
same => n,Set(path=/var/www/html/click_2_call/monitor)
same => n,MixMonitor(${path}/${calltime}-${CALLERID(num)}-${EXTEN:3}.wav)
same=>n,Set(CALLERID(num)=9496504600)
same => n,Dial(PJSIP/${EXTEN}@Synapseglobal,120)
exten => h,1,Set(start_time=${CUT(CDR(start), ,2)}) ; Extract the time portion
same => n,Set(end_time=${CUT(CDR(end), ,2)})
same => n,NoOp(Start Time Portion: ${start_time})
same => n,NoOp(End Time Portion: ${end_time})
same => n,Set(result=${SHELL(php /var/www/html/click_2_call/post_cdr.php "${CDR(dst)}" "${CDR(src)}" "${MIXMONITOR_FILENAME}" "${CDR(billsec)}" "${start_time}" "${end_time}")})
same=>n,hangup()