You are not logged in.

Announcement

 Téléchargez la dernière version stable de GLPI      -     Et vous, que pouvez vous faire pour le projet GLPI ? :  Contribuer
 Download last stable version of GLPI                      -     What can you do for GLPI ? :  Contribute

#1 2023-10-10 12:09:09

epigraphe
Member
Registered: 2022-04-08
Posts: 5

How to link a document to a ticket? (python) - Solved

Hello. I'm trying to make an application in GLPI, which will have an audio file attached.
I wrote a request. It works, creates a separate ticket and a separate document. But I can’t link the document and the ticket.
If I try to run the code, I get this error: list indices must be integers or slices, not str

Please tell me how to link the document to the application?

URL = '://apirest.php'

APPTOKEN = 'GMx'
USERTOKEN = 'zWrQ' #SD

try:
    with glpi_api.connect(URL, APPTOKEN, USERTOKEN) as glpi:
        ticket_data = {
            "name": f"Test Name ({gen_random_str})",
            "content": f"{input_text}",
            "_users_id_requester": f"{glpi_user_id}"
        }
        ticket = glpi.add('Ticket', ticket_data)

        document_name = "My test document"
        file_path = '/var/spool/asterisk/voicemail/default/1234/INBOX/msg0000.wav'

        uploaded_document = glpi.upload_document(document_name, file_path)

        document_id = uploaded_document['id']
        ticket_id = ticket['id']
        user_id = "7"

        link_url = f"{URL}/apirest.php/Document/{document_id}/Document_Item/"
        headers = {
            "App-Token": APPTOKEN,
            "Session-Token": USERTOKEN,
            "Content-Type": "application/json"
        }

        payload = {
            "input": {
                "documents_id": document_id,
                "items_id": ticket_id,
                "itemtype": "Ticket",
                "entities_id": "0",
                "users_id": user_id
            }
        }

        response = requests.post(link_url, headers=headers, json=payload)
        if response.status_code == 200:
            print("Success")
        else:
            print(f"Error: {response.status_code}")

except glpi_api.GLPIError as err:
    print(str(err))
except Exception as e:
    print(f"Error: {str(e)}")

Last edited by epigraphe (2023-10-11 12:36:07)

Offline

#2 2023-10-11 10:01:26

epigraphe
Member
Registered: 2022-04-08
Posts: 5

Re: How to link a document to a ticket? (python) - Solved

I fixed that error, but now I'm completely confused:
The script now creates a ticket and uploads the file to the document.
At the moment when the document and ticket are supposed to communicate, I get a 401 error.

Document_ID: 1234
Ticket_ID: 5678
Error: 401
Response Text: ["ERROR_SESSION_TOKEN_INVALID","session_token may be invalid"]

How can this be if both the document and the ticket are created with these parameters?

URL = 'apirest.php'

APPTOKEN = 'GMx'
USERTOKEN = 'zWLrkrQ' #SD

try:
    with glpi_api.connect(URL, APPTOKEN, USERTOKEN) as glpi:
        ticket_data = {
            "name": f"Test Name ({gen_random_str})",
            "content": f"{input_text}",
            "_users_id_requester": f"{glpi_user_id}"
        }
        ticket = glpi.add('Ticket', ticket_data)
        print(f"Ticket: {ticket}")
        document_name = "My test document"
        file_path = '/var/spool/asterisk/voicemail/default/1234/INBOX/msg0000.wav'

        uploaded_document = glpi.upload_document(document_name, file_path)
        print(f"Uploaded_Document: {uploaded_document}")

        document_id = uploaded_document['id']
        print(f"Document_ID: {document_id}")
        ticket_id = ticket[0]['id']
        print(f"Ticket_ID: {ticket_id}")
        user_id = "7"

        link_url = f"{URL}/apirest.php/Document/{document_id}/Document_Item/"
        headers = {
            "App-Token": APPTOKEN,
            "Session-Token": USERTOKEN,
            "Content-Type": "application/json"
        }

        print(document_id, ticket_id, user_id)
        payload = {
            "input": {
                "documents_id": document_id,
                "items_id": ticket_id,
                "itemtype": "Ticket",
                "entities_id": "0",
                "users_id": user_id
            }
        }

        response = requests.post(link_url, headers=headers, json=payload)
        if response.status_code == 200:
            print("Success")
        else:
            print(f"Error: {response.status_code}")
            print(f"Response Text: {response.text}")

except glpi_api.GLPIError as err:
    print(str(err))
except Exception as e:
    print(f"Error: {str(e)}")

Last edited by epigraphe (2023-10-11 12:36:35)

Offline

#3 2023-10-11 11:55:53

epigraphe
Member
Registered: 2022-04-08
Posts: 5

Re: How to link a document to a ticket? (python) - Solved

Third try. I got confused and used user token instead of session token. I fixed it, but now I get:


Response Text: ["ERROR_RESOURCE_NOT_FOUND_NOR_COMMONDBTM"," apirest.php/#ERROR_RESOURCE_NOT_FOUND_NOR_COMMONDBTM"]


APPTOKEN = 'AW'
USERTOKEN = 'zQ' #SD
try:
    # Add a step to retrieve the session token
    init_uri = '/initSession'
    response = requests.get(
        url="{}{}".format(URL, init_uri),
        params={
            "app_token": APPTOKEN,
            "user_token": USERTOKEN
        }
    )

    print('Response HTTP Status Code: {status_code}'.format(status_code=response.status_code))
#    print('Response HTTP Response Body: {content}'.format(content=response.content))

    resp_json = response.json()
    session_token = resp_json.get('session_token')
    if session_token:
        print(f"Session Token: {session_token}")
    else:
        print("Session token not found in the response.")

    with glpi_api.connect(URL, APPTOKEN, USERTOKEN) as glpi:
        ticket_data = {
            "name": f"Test Name ({gen_random_str})",
            "content": f"{input_text}",
            "_users_id_requester": f"{glpi_user_id}"
        }
        ticket = glpi.add('Ticket', ticket_data)
        print(f"Ticket: {ticket}")

       
        document_name = "My test document"
        file_path = '/var/spool/asterisk/voicemail/default/1234/INBOX/msg0000.wav'

       
        uploaded_document = glpi.upload_document(document_name, file_path)
        print(f"Uploaded_Docu#ment: {uploaded_document}")

       
        document_id = uploaded_document['id']
        print(f"Document_ID: {document_id}")
        ticket_id = ticket[0]['id']
        print(f"Ticket_ID: {ticket_id}")
        user_id = "7"

        #link_url = f"{URL}/apirest.php/Document/{document_id}/Document_Item/"
        link_url = f"{URL}/apirest.php/Document/1/Document_Item/"
        headers = {
            "App-Token": APPTOKEN,
            "Session-Token": session_token,
            "Content-Type": "application/json"
        }

        print(document_id, ticket_id, user_id)
        payload = {
            "input": {
                "documents_id": document_id,
                "items_id": ticket_id,
                "itemtype": "Ticket",
                "entities_id": "0",
                "users_id": user_id
            }
        }

        response = requests.post(link_url, headers=headers, json=payload)
        if response.status_code == 200:
            print("Success")
        else:
            print(f"Error: {response.status_code}")
            print(f"Response Text: {response.text}")

except glpi_api.GLPIError as err:
    print(str(err))
except Exception as e:
    print(f"Error: {str(e)}")

Last edited by epigraphe (2023-10-11 12:36:49)

Offline

#4 2023-10-11 12:35:45

epigraphe
Member
Registered: 2022-04-08
Posts: 5

Re: How to link a document to a ticket? (python) - Solved

Working version

URL = 'apirest.php'

APPTOKEN = 'AW'
USERTOKEN = 'zQ' #SD
try:
    # Add a step to retrieve the session token
    init_uri = '/initSession'
    response = requests.get(
        url="{}{}".format(URL, init_uri),
        params={
            "app_token": APPTOKEN,
            "user_token": USERTOKEN
        }
    )

    print('Response HTTP Status Code: {status_code}'.format(status_code=response.status_code))
#    print('Response HTTP Response Body: {content}'.format(content=response.content))

    resp_json = response.json()
    session_token = resp_json.get('session_token')
    if session_token:
        print(f"Session Token: {session_token}")
    else:
        print("Session token not found in the response.")

    with glpi_api.connect(URL, APPTOKEN, USERTOKEN) as glpi:
        ticket_data = {
            "name": f"Test Name ({gen_random_str})",
            "content": f"{input_text}",
            "_users_id_requester": f"{glpi_user_id}"
        }
        ticket = glpi.add('Ticket', ticket_data)
        print(f"Ticket: {ticket}")

        document_name = "My test document"
        file_path = '/var/spool/asterisk/voicemail/default/1234/INBOX/msg0000.wav'

        uploaded_document = glpi.upload_document(document_name, file_path)
        print(f"Uploaded_Docu#ment: {uploaded_document}")

        document_id = uploaded_document['id']
        print(f"Document_ID: {document_id}")
        ticket_id = ticket[0]['id']
        print(f"Ticket_ID: {ticket_id}")
        user_id = "7"

        link_url = f"{URL}/Document/{document_id}/Document_Item/"
        #link_url = f"{URL}/apirest.php/Document/1/Document_Item/"
        print(link_url)
        headers = {
            "App-Token": APPTOKEN,
            "Session-Token": session_token,
            "Content-Type": "application/json"
        }

        print(document_id, ticket_id, user_id)
        payload = {
            "input": {
                "documents_id": document_id,
                "items_id": ticket_id,
                "itemtype": "Ticket",
#                "entities_id": "0",
                "users_id": "7"
            }
        }

        response1 = requests.post(link_url, headers=headers, json=payload)
        if response1.status_code == 200:
            print("Success")
        else:
            print(f"Error: {response1.status_code}")
            print(f"Response Text: {response1.text}")

except glpi_api.GLPIError as err:
    print(str(err))
except Exception as e:
    print(f"Error: {str(e)}")

Last edited by epigraphe (2023-10-11 12:37:01)

Offline

#5 2023-11-21 11:30:52

pablo.galvarez
Member
Registered: 2023-11-16
Posts: 5

Re: How to link a document to a ticket? (python) - Solved

Hi!

I'm trying the same as you but i get ["ERROR_GLPI_ADD", "No tiene permisos para realizar esta acción."] with 400 as response code every time. This is my code:

--- general_functions.py ---

items = {'itemtype': 'Ticket', 'items_id': ticket_id, 'documents_id': document_information['id']}

--- api_glpi.py ---

    def link_document_to_ticket(self, document_id, items):
        response = requests.post(
            url=self._set_method('Document', document_id, 'Document_Item'),
            headers={
                'Session-Token': self.session.headers['Session-Token'],
                'App-Token': self.session.headers['App-Token'],
                'Content-Type': 'application/json'
            },
            json={'input': items},
            verify=False,
        )

Do you know if i'm doing something wrong? Maybe GLPI version (10.0.3)?

Thanks!

Offline

Board footer

Powered by FluxBB