AGISTATUS allways return Success

I am running a python script through AGI, and I set differents cases in the scripts, but always return Success although I raise an exception in the script.
The part of the plan that call AGI is:

same => n,AGI(rest_call.py,${CALLER_ID})
same => n,Set(RESULT=${AGISTATUS})
same => n,NoOp(Return Code: ${RESULT})
same => n,GotoIf($[“${RESULT}” = “SUCCESS”]?success:fail)

same => n(success),NoOp(El caso fue exitoso)
same => n,Playback(es_419/custom/ok_rest)
same => n,Hangup()

same => n(fail),NoOp(El caso NO fue exitoso)
same => n,Playback(es_419/custom/error_rest)
same => n,Hangup()

What does raising an exception actually do in your script? AGI itself has no idea about exceptions, it just launches a script and does some back/forth. In this case it sounds like the AGI was successfully launched.

Excuse me This is my first Post, Yes this is my python script

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
from json import JSONEncoder
import configparser

from DtoYoisen import DtoYoisen
import sys
import requests
import logging
import os
 

def main():

    dataConfig = configparser.ConfigParser()
    dataConfig.read("/opt/asterisk/rest_call.ini")

    url = dataConfig["General"]["URL"]
    logFileName = dataConfig["General"]["logFile"]

    logger = logging.getLogger(__name__)
    logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename=logFileName, encoding='utf-8', level=logging.DEBUG)
    logger.info("Iniciando Logger")
    logger.info("URL: " + url)

    serviceId= int(dataConfig["YoisenRequest"]["serviceId"])
    hsmElementName=dataConfig["HSM"]["hsmElementName"]
    hsmNamespace=dataConfig["HSM"]["hsmNamespace"]
    hsmLanguage=dataConfig["HSM"]["hsmLanguage"]
    hsmBodyParam1=dataConfig["HSM"]["hsmBodyParam1"] 
    hsmBodyParam2=dataConfig["HSM"]["hsmBodyParam2"] 
    header=dataConfig["YoisenRequest"]["Headers"]
    bearerToken=dataConfig["YoisenRequest"]["token"]
    logger.debug("Header :"+ header)

    caller_id = sys.argv[1] 
    #caller_id = "1125559999"
    if len(caller_id) == 10:
        caller_id = "549" + caller_id
    elif len(caller_id) < 10:
        sys.stderr.write("El ANI es menor a 10 digitos")
        sys.stderr.flush()
        print("failed")
        #sys.exit(2)
        raise Exception("El ANI es menor a 10 digitos")

    jsonResquest = DtoYoisen()
    jsonBody= jsonResquest.get_model_hsm_without_buttons_and_tags(serviceId,
                          caller_id,
                          "null",
                          hsmElementName,
                          hsmNamespace,
                          hsmLanguage,
                          "null",
                          hsmBodyParam1,
                          hsmBodyParam2)

    logger.debug("JSON :"+ jsonBody)
    # print("JSON :"+ jsonBody)
   
    headers = {
    'Authorization': f'Bearer {bearerToken}',
    'Content-Type': f'{header}'
    }
    # logger.debug("Headers: " + headers)

    logger.info("Ejecutando: REST")
    response = requests.post(url, data=jsonBody, headers = headers)
    logger.info("REST ejecutado")
    if response.status_code == 200:
        logger.info('Success: ' + str(response.status_code))
        print("success") 
        sys.exit(response.status_code)       # Código de salida 0
    else:
        logger.info('Fallo. Status Code: ' +  str(response.status_code))
        print("failed")   # Indica fallo
        #sys.stderr.write("Error.  Status Code: " +  str(response.status_code))
        #sys.stderr.flush()
        raise Exception("Servicio REST no disponible. Status Code: " +  str(response.status_code))
         #sys.exit(response.status_code)       # Código de salida 1

if __name__ == "__main__":
    main()

AGI always return status is success, if it executed successfully.

Set the channel variable in script and check after AGI is executed, that solve your problem

On Tue, 21 Jan, 2025, 6:23 pm jcolp via Asterisk Community, <notifications@asterisk.discoursemail.com> wrote:

jcolp Asterisk Project Lead
January 21

What does raising an exception actually do in your script? AGI itself has no idea about exceptions, it just launches a script and does some back/forth. In this case it sounds like the AGI was successfully launched.


Visit Topic or reply to this email to respond.

You are receiving this because you enabled mailing list mode.

To unsubscribe from these emails, click here.

Thanks for your answer. i’m starting with Asterisk. Could you give me an example of how can i set a variable in the python script, please?

agi.set_variable(‘variable_name’, variable_value)

https://github.com/jfernandz/pyst2/blob/master/examples/agi_script.py

Good Luck :blush:

On Tue, Jan 21, 2025 at 6:58 PM fpedroza via Asterisk Community <notifications@asterisk.discoursemail.com> wrote:

fpedroza
January 21

Sudhakar:

channel

Thanks for your answer. i’m starting with Asterisk. Could you give me an example of how can i set a variable in the python script, please?


Visit Topic or reply to this email to respond.

You are receiving this because you enabled mailing list mode.

To unsubscribe from these emails, click here.

Looks to me that the OP isn’t really using AGI. They are using the AGI applications to launch a non-AGI compliant script. I can’t find anything that instantiates an AGI class library, or otherwise does the AGI initialisation, and they are passing parameters on the command line.

They need to use AGI properly, for which they should read the basic documentation, rather than asking for canned code, or should use System, instead of AGI.

Your suggestion assumes a particular library.

Thank You for your answers.
I reslved the problem using the following command in python script
print(f’SET VARIABLE “RESULT” “FAILED”')
Where RESULT is a Channel Variable.
But I couldn’t do the same throught AGI library
I don the following in the code

from asterisk.agi import AGI

agi = AGI()
agi.verbose(“python agi started”, 1)

And when I run from Asterisk Server throught the following error

  File "/usr/local/lib/python3.11/dist-packages/pyst2-0.5.1-py3.11.egg/asterisk/agi.py", line 628, in verbose
    self.execute('VERBOSE', self._quote(message), level)
  File "/usr/local/lib/python3.11/dist-packages/pyst2-0.5.1-py3.11.egg/asterisk/agi.py", line 150, in execute
    return self.get_result()
           ^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/pyst2-0.5.1-py3.11.egg/asterisk/agi.py", line 180, in get_result
    code = int(code)
           ^^^^^^^^^
ValueError: invalid literal for int() with base 10: ''

I couldn’t install the library pyst2 with pip, because Asterisk is installed in Debian 12 and I had to to clone the repository and run the setup.py.
Any idea if it’s missing some library in the server.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.