Giter Site home page Giter Site logo

lucasheld / uptime-kuma-api Goto Github PK

View Code? Open in Web Editor NEW
211.0 7.0 17.0 362 KB

A Python wrapper for the Uptime Kuma Socket.IO API

Home Page: https://uptime-kuma-api.readthedocs.io

License: MIT License

Python 99.34% Jinja 0.45% Shell 0.20%
uptime-kuma python api kuma monitor monitoring

uptime-kuma-api's Introduction

uptime-kuma-api

A wrapper for the Uptime Kuma Socket.IO API

uptime-kuma-api is a Python wrapper for the Uptime Kuma Socket.IO API.

This package was developed to configure Uptime Kuma with Ansible. The Ansible collection can be found at https://github.com/lucasheld/ansible-uptime-kuma.

Python version 3.7+ is required.

Supported Uptime Kuma versions:

Uptime Kuma uptime-kuma-api
1.21.3 - 1.23.2 1.0.0 - 1.2.1
1.17.0 - 1.21.2 0.1.0 - 0.13.0

Installation

uptime-kuma-api is available on the Python Package Index (PyPI).

You can install it using pip:

pip install uptime-kuma-api

Documentation

The API Reference is available on Read the Docs.

Example

Once you have installed the python package, you can use it to communicate with an Uptime Kuma instance.

To do so, import UptimeKumaApi from the library and specify the Uptime Kuma server url (e.g. 'http://127.0.0.1:3001'), username and password to initialize the connection.

>>> from uptime_kuma_api import UptimeKumaApi, MonitorType
>>> api = UptimeKumaApi('INSERT_URL')
>>> api.login('INSERT_USERNAME', 'INSERT_PASSWORD')

Now you can call one of the existing methods of the instance. For example create a new monitor:

>>> result = api.add_monitor(type=MonitorType.HTTP, name="Google", url="https://google.com")
>>> print(result)
{'msg': 'Added Successfully.', 'monitorId': 1}

At the end, the connection to the API must be disconnected so that the program does not block.

>>> api.disconnect()

With a context manager, the disconnect method is called automatically:

from uptime_kuma_api import UptimeKumaApi

with UptimeKumaApi('INSERT_URL') as api:
    api.login('INSERT_USERNAME', 'INSERT_PASSWORD')
    api.add_monitor(
        type=MonitorType.HTTP,
        name="Google",
        url="https://google.com"
    )

uptime-kuma-api's People

Contributors

lucasheld avatar vinalti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

uptime-kuma-api's Issues

New type 'group' is not a valid MonitorType

➜  python3 uptimekuma.30s.py
<class 'ValueError'>
("'group' is not a valid MonitorType",)
'group' is not a valid MonitorType
📛
---
No monitor! | color='red'
Click here to configure | href='file:///Users/lucek/Downloads/uptimekuma.30s.py'

TypeError: 'type' object is not subscriptable on 0.7.0 with python3.7

Hello.
uptime-kuma-api==0.7.0 if failing with python3.7 with this error:

from uptime_kuma_api import UptimeKumaApi, MonitorType
  File "/home/user/.local/lib/python3.7/site-packages/uptime_kuma_api/__init__.py", line 11, in <module>
    from .api import UptimeKumaApi
  File "/home/user/.local/lib/python3.7/site-packages/uptime_kuma_api/api.py", line 188, in <module>
    timeRange: list[dict] = None
TypeError: 'type' object is not subscriptable

0.6.0 version is working fine with python3.7
Both version are working fine with Python3.9.6.

How we do some Log.info

Hello, how we can do send some log (info, warning, danger)

for example I would to my log from a flaskapp or fastapi app to uptime kuma, do you have a example ? thanks in advance

Support for a new notification type?

Hi,

I forked Uptime Kuma to be able to add a new notification type (custom to our setup). We have build an API pod based on your code that talks to Uptime Kuma. Now I need to adjust the API pod to support the new notification type. I would like to know if you could extend the code so that I do not have to fork your project too? If rather not extend it, that is totally understandable.

I could send you what is new in Uptime Kuma. Basically this new notification type is a copy of the notif. type SMTP with added parameters and a set template in it so it will send an XML email (taking values added in in the UI).

Thx

Timeout on get_monitors()

Hello !
Got timeout on api.get_monitors() while api.get_monitor(1) is working.
I got 50 monitors.
Here is the trace:
Traceback (most recent call last): File "get.py", line 10, in <module> monitors = api.get_monitors() File "/home/victor/.local/lib/python3.10/site-packages/uptime_kuma_api/api.py", line 1175, in get_monitors r = list(self._get_event_data(Event.MONITOR_LIST).values()) File "/home/victor/.local/lib/python3.10/site-packages/uptime_kuma_api/api.py", line 538, in _get_event_data raise Timeout(f"Timed out while waiting for event {event}") uptime_kuma_api.exceptions.Timeout: Timed out while waiting for event monitorList
And I don't have any errors on Uptime Kuma logs.

Someone has any ideas ?

Thanks

EDIT : NETWORK ISSUE THREW K8S INGRESS

get_monitor_status for all monitors

Great project, thanks!
I would like to get the status of all monitors (number of up, down, pending, ....)
I am not using any status pages right now.

The uptime kuma main webpage shows 'quick stats'. This is exactly what I want to get via API.

the snippet below takes about 15 seconds for 50 monitors, which is a bit inefficient.

    id = monitor["id"]
    st = api.get_monitor_status(id)

is there a better way to get all stati? I am only interested in the number of monitors that are up. I don't need the IDs.

Inconsistant Status calls using get_monitor_status

I drafted a quick and dirty python blob to test the ability to retrieve a monitor status but am getting very inconsistent results.

`import time
from uptime_kuma_api import UptimeKumaApi
from uptime_kuma_api.exceptions import UptimeKumaException
import argparse

UPTIME_KUMA_URL = 'http://192.168.22.2'
UPTIME_KUMA_USER = 'MYUSER'
UPTIME_KUMA_PASSWORD = 'MYPASSSWORD'

def poll_monitor_status(monitor_id):
api = UptimeKumaApi(UPTIME_KUMA_URL)
api.login(UPTIME_KUMA_USER, UPTIME_KUMA_PASSWORD)

try:
    monitor_status_response = api.get_monitor_status(monitor_id)
    monitor_status = monitor_status_response.name  # Correctly retrieve status
    print(f"Monitor ID {monitor_id} Status: {monitor_status}")
    
except UptimeKumaException as ex:
    print(f"An error occurred for monitor ID {monitor_id}: {ex}")
    
    # Detailed logging lines
    if hasattr(ex, 'response'):
        print("Error response content:", ex.response.content)
api.disconnect()
time.sleep(1)

if name == "main":
parser = argparse.ArgumentParser(description="Poll monitor status from Uptime Kuma API")
parser.add_argument("monitor_id", type=int, help="ID of the monitor to check")
args = parser.parse_args()

poll_monitor_status(args.monitor_id)

`

Below is me running the command a few times to show the inconsistency.

printer1@floorplan % python3 test.py 59 An error occurred for monitor ID 59: monitor does not exist printer1@floorplan % python3 test.py 59 An error occurred for monitor ID 59: monitor does not exist printer1@floorplan % python3 test.py 59 Monitor ID 59 Status: UP printer1@floorplan % python3 test.py 59 An error occurred for monitor ID 59: monitor does not exist

These commands were run within 5 seconds of each other, with no changes in network status , no changes of anything inside the script etc..

Any help troubleshooting would be greatly appreciated.

Turn off authentication via API

Hi again,

Is there an API to turn on / off authentication on Uptime Kuma? Ie. there is a new kuma app running and so far no username / pass set. Can I call an API to turn off authentication?

edit_monitor() doesn't run code from _build_monitor_data()

First, let me say thank you so much for putting this api and accompanying ansible collection together - this is exactly what I was looking for to manage my Uptime Kuma monitors!

The specific issue I am having is that adding a notification to existing monitors wasn't working. Specifically, I was getting this error when running the edit_monitor() function.

...
api.edit_monitor(id_=31, notificationIDList=[1])
...
uptime_kuma_api.exceptions.UptimeKumaException: insert into `monitor_notification` (`monitor_id`, `notification_id`) values (31, '0') - SQLITE_CONSTRAINT: FOREIGN KEY constraint failed

After digging through api.py and a little debugging, I am pretty sure that the issue is that there is some important code included in _build_monitor_data() that doesn't get called when edit_monitor() is called. For my specific issue, I think this code block is the critical piece. As this looks to be responsible for converting the list/array of integer notification ids to the dictionary of {id: True} that the Uptime Kuma socket API is looking for.

def _build_monitor_data(
...
):
...
dict_notification_ids = {}
if notificationIDList:
    for notification_id in notificationIDList:
        dict_notification_ids[notification_id] = True
notificationIDList = dict_notification_ids
...

However, I am not sure if there might be other code in this section that would be important for other monitor attributes that might be edited via edit_monitor() and is currently being missed when that function is called?

For completeness, I'll just document that currently edit_monitor() simply passes its args to data.update(), without running the args through the code above to translate the format, which I believe is the root cause of my issue.

Using the raw api library, I am able to work around this by calling edit_monitor() using notificationIDList={1: True} instead of notificationIDList=[1], but I don't think that is the intent, is it? This work around doesn't seem to work in ansible since notificationIDList is looking for a list, not a dict. Please let me know if I am just missing something here.

Thanks again for putting these packages together, they are really going to help me out.

error "list indices must be integers or slices, not str"

Looping over all monitors to get their status I tend to run into the below issue.
Is it possible there is a type issue in your code?

image

my code is roughly

    monitors = api.get_monitors()
    n_monitors = len(monitors)

    cnt_up = 0
    cnt_active = 0

    for monitor in monitors:
        id = monitor["id"]
        name = monitor["name"]
        if monitor["active"]:
            #print(id)
            #print(name)
            cnt_active += 1
            st = 9981 #default value
            
            for n in range(1):
                    st = api.get_monitor_status(id) 
                    if st == 1:
                                    cnt_up += 1

Custom Headers on login

Thank for this API since the official one is still missing.

I would really want to use Uptime-Kuma but we need programmatic access to the API for configuration, so this API is the perfect fit (even with ansible support 👍). But I use custom authentifikation which is handelnd by a reverse proxy, so that I can use oauth and other nice features.

Unfortunately the API only supports Uptime-Kuma own auth mechanism and the is no native way to change it. It would be really nice to allow custom auth or at least set extra header on the initial socketIO connection.

Right now I solved it by overriding the connect method:

class UptimeKumaApiExtended(UptimeKumaApi):

    def connect(self) -> None:
        """
        Connects to Uptime Kuma.

        Called automatically when the UptimeKumaApi instance is created.

        :raises UptimeKumaException: When connection to server failed.
        """
        url = self.url.rstrip("/")
        try:
            self.sio.connect(f'{url}/socket.io/', wait_timeout=self.wait_timeout, headers=headers)
        except:
            raise UptimeKumaException("unable to connect")

Is there a option to support this use case naively?

If you are open for collaboration I can provide a example implementation in the near future.

detailed usage of adding monitors and listing monitors

Hi,
awesome tool. can we get some more example of how to add new monitors and list existing monitors?

currently we are getting the following error when trying to add a monitor.

api.add_monitor(type=MonitorType.HTTP, name="Test API", url="https://gm.com")
Traceback (most recent call last):
File "", line 1, in
File "/home/xx/python-venvs/uptime/lib/python3.6/site-packages/uptime_kuma_api/api.py", line 637, in add_monitor
return self._call('add', data)
File "/home/xx/python-venvs/uptime/lib/python3.6/site-packages/uptime_kuma_api/api.py", line 340, in _call
r = self.sio.call(event, data)
File "/home/xx/python-venvs/uptime/lib/python3.6/site-packages/socketio/client.py", line 469, in call
callback=event_callback)
File "/home/xx/python-venvs/uptime/lib/python3.6/site-packages/socketio/client.py", line 394, in emit
namespace + ' is not a connected namespace.')
socketio.exceptions.BadNamespaceError: / is not a connected namespace.

Bug: `api.add_tag()` takes 1 positional

Hey 👋

I think a find a new bug in this wrapper.

When I tried to add a tag using api.add_tag("test", "FF0000"), I got the following error :

vscode/workspaces/KumaCompanion (main) $ kuma tag add --name test -c "#FFFFFF"
Traceback (most recent call last):
  File "/workspaces/KumaCompanion/src/main.py", line 44, in <module>
    main()
  File "/workspaces/KumaCompanion/src/main.py", line 38, in main
    args.func(args)
  File "/workspaces/KumaCompanion/src/commands/tag/add.py", line 13, in add_tag
    api.add_tag("TEST", "#FF0000")
TypeError: UptimeKumaApi.add_tag() takes 1 positional argument but 3 were given

Here a snippet of my code :

def add_tag(args):
    # Connection to Uptime Kuma API
    api = KumaCompanion().get_api()

    # Creating a new tag
    # Add tag
    api.add_tag("TEST", "#FF0000")

Do you have any solutions ?

Please provide an example of adding a notification

Could you please provide an example?
I would like to set up a notificaton as

Notification Type: SMTP
Friendly Name: Default alert
Hostname 
Port 
Username 
Password 
From Email 
To Email: 
Default enabled: True
Apply on all existing monitors: True

What we tried so far
endpoint for the addmonitors

# Add a SMTP email notification
@app.route('/addnotification', methods=['POST'])
def add_smtp_notification():
      name = request.form['name']
      type = NotificationType.SMTP
      isDefault = True
      applyExisting = True
      smtpHost =  request.form['smtpHost']
      smtpPort = request.form['smtpPort']
      smtpIgnoreTLSError = True
      smtpUsername = request.form['smtpUsername']
      smtpPassword = request.form['smtpPassword']
      customSubject = request.form['subject']
      smtpFrom = request.form['smtpFrom']
      smtpTo = request.form['smtpTo']
      api = UptimeKumaApi('URL') 
      api.login()                  
      return api.add_notification(
        name=name,
        type=type,
        isDefault=isDefault,
        applyExisting=applyExisting,
        smtpHost =  smtpHost,
        smtpPort = smtpPort,
        smtpIgnoreTLSError = smtpIgnoreTLSError,
        smtpUsername = smtpUsername,
        smtpPassword = smtpPassword,
        customSubject = customSubject,
        smtpFrom = smtpFrom,
        smtpTo = smtpTo,
        smtpDkimskipFields = True
        ), api.disconnect()

curl -d "name=TestNotification2&smtpHost=URL&smtpPort=25&smtpUsername=username&smtpPassword=password&subject=TestNotification&smtpFrom=email&smtpTo=adress" -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:5000/addnotification

   raise TypeError(f"missing {len(missing_arguments)} required argument: {missing_arguments_str}")
TypeError: missing 9 required argument: 'smtpSecure', 'smtpDkimDomain', 'smtpDkimKeySelector', 'smtpDkimPrivateKey', 'smtpDkimHashAlgo', 'smtpDkimheaderFieldNames', 'smtpDkimskipFields', 'smtpCC', 'smtpBCC'

Example for a getmonitor operation

# Get existing notifications
@app.route('/getnotifications', methods=['GET'])
def get_notifications():
      api = UptimeKumaApi('URL') 
      api.login()
      return api.get_notifications(), api.disconnect()
curl http://localhost:5000/getnotifications
[{"active":true,"applyExisting":true,"id":1,"isDefault":true,"name":"Test notification","smtpFrom":"[email protected]","smtpHost":"xxx.com","smtpIgnoreTLSError":true,"smtpPassword":"pass","smtpPort":25,"smtpSecure":false,"smtpTo":"[email protected]","smtpUsername":"username","type":"smtp","userId":1}]

Add global timeouts

In some cases, certain events never arrive. This can happen, for example, if you call the cert_info method without having a monitor that uses TLS. It is difficult to address all these special cases individually. Especially without documentation when this happens.
Instead, timeouts for all methods would be useful, also for other errors. In order not to block the application forever.

Doesn't work behind reverse proxy

Hello,

I Try to use your librarie behind traefik, but connection are always refuse :/

Traceback (most recent call last):
  File "/home/user/.local/lib/python3.10/site-packages/uptime_kuma_api/api.py", line 550, in connect
    self.sio.connect(f'{url}/socket.io/', wait_timeout=self.wait_timeout)
  File "/home/user/.local/lib/python3.10/site-packages/socketio/client.py", line 338, in connect
    raise exceptions.ConnectionError(exc.args[0]) from None
socketio.exceptions.ConnectionError: Unexpected response from server

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/git/k3s/main.py", line 306, in <module>
    STACK = UptimeKuma().get()
  File "/home/user/git/k3s/models/uptime_kuma.py", line 8, in __init__
    self.api = UptimeKumaApi(url)
  File "/home/user/.local/lib/python3.10/site-packages/uptime_kuma_api/api.py", line 417, in __init__
    self.connect()
  File "/home/user/.local/lib/python3.10/site-packages/uptime_kuma_api/api.py", line 552, in connect
    raise UptimeKumaException("unable to connect")
uptime_kuma_api.exceptions.UptimeKumaException: unable to connect
make: *** [Makefile:141 : retry] Erreur 1

My code :

from uptime_kuma_api import UptimeKumaApi, MonitorType

class UptimeKuma:

    def __init__(self, url="https://myurl.behind.reverseproxy"):
        self.api = UptimeKumaApi(url)
        self.api.login()

How do I add monitors to status pages?

Hi, can you tell me how I can change the status_page data using the python api. Apparently, the following function save_status_page(self, slug: str, **kwargs) is used for this, but I don't quite understand how to insert data into it correctly.
print(api.save_status_page(slug="google", data={'domainNameList': ["google.com"]}))
I get html code and
requests.exceptions.JSONDecodeError: [Errno Expecting value]

api.delete_monitor() does nothing

api.delete_monitor(id) reports {'msg': 'Deleted Successfully.'} with valid (or invalid) ID, but does nothing.
(add_monitor works fine, so it is not an issue with the installation, kuma instance, login creds, etc.)

Kuma 1.21.3
API 0.13.0
Python 3.8.13

myuser@MyServer:/home/MyPath/kuma# ./kapi-add.py
{'msg': 'Added Successfully.', 'monitorID': 13}

myuser@MyServer:/home/MyPath/kuma# ./kapi-get.py 13
{'id': 13, 'name': 'newmonitor', 'description': None, 'url': 'HTTPS://newmon.domain.com', 'method': 'GET', .......

myuser@MyServer:/home/MyPath/kuma# ./kapi-del.py 13
{'msg': 'Deleted Successfully.'}
myuser@MyServer:/home/MyPath/kuma# ./kapi-del.py 13
{'msg': 'Deleted Successfully.'}
myuser@MyServer:/home/MyPath/kuma# ./kapi-del.py 13
{'msg': 'Deleted Successfully.'}
myuser@MyServer:/home/MyPath/kuma# ./kapi-del.py 13345345345314531453145134531245
{'msg': 'Deleted Successfully.'}

myuser@MyServer:/home/MyPath/kuma# ./kapi-get.py 13
{'id': 13, 'name': 'newmonitor', 'description': None, 'url': 'HTTPS://newmon.domain.com', 'method': 'GET', ............

Proxy: Rate Limiting / Timeout

Hello 👋

I am currently working on a CLI for uptime-kuma using this wrapper.

But I have some timeout problems using this.

For example, I tried to implement the command kuma monitor ls :

I tried implementing the kuma monitor ls command to display hostname, monitor id, monitor name, status.

But I got 9/10 timeout errors because I need to perform 1 requests to get all monitors + 1 x Ymonitors to get heartbeat status.

I have about 5 monitors in my Uptime Kuma dev instance. So I've made 6 requests and that already seems too many for the API.

Am I missing something? How can I solve this problem, because it's really frustrating?

TypeError: '<' not supported between instances of 'NoneType' and 'int'

This is a bit of a weird one. I'm using the ansible to add a bunch of monitors with the exact same task:

  - name: Create monitors
    lucasheld.uptime_kuma.monitor:
      api_url: "{{ api_url }}"
      api_token: "{{ api_token }}"
      name: "{{ item }}"
      type: http
      url: "https://{{ item }}"
      state: present
    with_items: "{{ urls }}"

most of them are fine, but once or twice, I get the following error.

`File "/usr/local/lib/python3.11/site-packages/uptime_kuma_api/api.py", line 643, in edit_monitor\n _check_arguments_monitor(data)\n File "/usr/local/lib/python3.11/site-packages/uptime_kuma_api/api.py", line 243, in _check_arguments_monitor\n check_argument_conditions(conditions, kwargs)\n File "/usr/local/lib/python3.11/site-packages/uptime_kuma_api/api.py", line 191, in check_argument_conditions\n if min is not None and value < min:\n ^^^^^^^^^^^^\nTypeError: '<' not supported between instances of 'NoneType' and 'int'\n"}

Seems a bit odd that it fails on some but is fine on most.

I haven't been able to debug it more just yet.

`

By the way @lucasheld many thanks for this great tool.

ssl_verify argument not used in get_status_page()

When instantiating an instance of the UptimeKumaApi class, you can disable SSL verification via the ssl_verify argument in the constructor:

def __init__(
    self,
    url: str,
    timeout: float = 10,
    headers: dict = None,
    ssl_verify: bool = True,
    wait_events: float = 0.2
 ) -> None:

This is then set on the Client: self.sio = socketio.Client(ssl_verify=ssl_verify) so any web requests issued by the Client use this variable.

However, there is a single requests.get() within get_status_page() that bypasses the Client, so the ssl_verify arg is not passed:

try:
    r2 = requests.get(f"{self.url}/api/status-page/{slug}", timeout=self.timeout).json()
except requests.exceptions.Timeout as e:
    raise Timeout(e)

As a result, if you instantiate your API with api = UptimeKumaApi("https://localhost:8080", ssl_verify=False), calling api.get_status_page() will fail with an SSL verification error.

Get all Monitors Status

Question:

I need to check if a monitor is Up or Down.
api.get_monitors() gives me the monitor info, but how can I check if the monitor is up or down at this moment?

Bug: api do not return correct timeout error TimeoutError -> Timeout

Hi 👋

The API does not return the timeout error associated with this wrapper when the URL is triggered.
This is due to the fact that socketio returns its own timeout errors, and since no check is performed on the _call() function, the wrapper will return socketio's error.

Which is a shame when you're making custom errors, and cost me 2 hours :D

Memory Leak

It seems like this API has a memory leak.

MemoryLeak

I have used this python program to test it:

import threading
import time
from uptime_kuma_api import UptimeKumaApi

api = UptimeKumaApi("https://up.obco.pro")
print("Connected")
api.login("Yonggan", "PASSWORD")
print("Login")

def update():
    api.get_important_heartbeats()


def uptime_kuma_polling():
    while True:
        update()
        time.sleep(10)


if __name__ == '__main__':
    uptime_kuma_thread = threading.Thread(target=uptime_kuma_polling)
    uptime_kuma_thread.start()

The output was as expected:

mprof: Sampling memory every 0.1s
running new process
running as a Python program...
Connected
Login

So after the Login i am looping every 10 seconds to get the important heatbeats.

This is just a short example. I recognized it because my Horus flask app that is using this API used 1,5GB memory after some hours.

mTLS option is missing in Ansible collection

The choice in the module for adding a monitor only accepts empty, basic or ntlm. When trying to add a new monitor using mtls authentication the play fails.

A 4th choice, mtls needs to be added.

I fixed this locally:
lucasheld/uptime_kuma/plugins/modules/monitor.py, line 406

From:
authMethod=dict(type="str", choices=["", "basic", "ntlm"]),
To:
authMethod=dict(type="str", choices=["", "basic", "ntlm", "mtls"]),

add "wait_timeout" to python-socketio "connect" method

Hi @lucasheld .
Thank you for the great tool.
Some times i have api connection issues with error socketio.exceptions.BadNamespaceError: / is not a connected namespace.
And for me helped adding wait-timeout param to python-socketio "connect" method in api.py:

#api.py:426
def connect(self):
    url = self.url.rstrip("/")
        try:
            self.sio.connect(f'{url}/socket.io/',wait_timeout=5)
        except:
            print("")

Could you please add option to manage wait-timeout from "UptimeKumaApi"?

Use Uptime Kuma API key for authentication

Currently, I have to resort to exposing plaintext login credentials to use this API - it would be cool to use an API key generated in Uptime Kuma to be able to authenticate.

Please let me know if this would be possible. Thanks.

set pathName or parent

Hi I have playing around with the API for some time now,

I cat not pace a new monitor or move a existng on under a existing one.

>>>api.edit_monitor(27, pathName = "Server / Tieto Evry / Google Petter")
{'msg': 'Saved.', 'monitorID': 27
>>> x = api.get_monitor(27)
>>> x["pathName"]
'Butiker / Stadium Ingelsta Norrköping'

"None is not a valid AuthMethod" error

After updating to 1.0 I'm getting the following error whenever I run an ansible task that lists/updates/creates monitors

       monitors = api.get_monitors()
                   ^^^^^^^^^^^^^^^^^^
      File "/home/mishac/Work/personal/home-infrastructure/lib/python3.11/site-packages/uptime_kuma_api/api.py", line 1021, in get_monitors
        parse_auth_method(r)
      File "/home/mishac/Work/personal/home-infrastructure/lib/python3.11/site-packages/uptime_kuma_api/api.py", line 73, in parse_auth_method
        parse_value(data, "authMethod", AuthMethod)
      File "/home/mishac/Work/personal/home-infrastructure/lib/python3.11/site-packages/uptime_kuma_api/api.py", line 57, in parse_value
        parse_value(d, key, type_)
      File "/home/mishac/Work/personal/home-infrastructure/lib/python3.11/site-packages/uptime_kuma_api/api.py", line 60, in parse_value
        data[key] = type_(data[key])
                    ^^^^^^^^^^^^^^^^
      File "/usr/lib/python3.11/enum.py", line 717, in __call__
        return cls.__new__(cls, value)
               ^^^^^^^^^^^^^^^^^^^^^^^
      File "/usr/lib/python3.11/enum.py", line 1133, in __new__
        raise ve_exc
    ValueError: None is not a valid AuthMethod

It looks like my monitors in uptime kuma don't have a valid auth mode set. deleting and recreating them fixes the issue, but there are dozens of monitors so it's a pain in the ass.

I guess a blank/invalid authmethod should be cast to Authmethod.NONE?

Problem when auth is disabled in Uptime Kuma (using SSO instead)

We are running Uptime Kuma in a container and have SSO in front of it. Therefore we would like to disable auth in Uptime Kuma.
Here I encountered an error

>>> api.login('', '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/A69778720/csaba/itsh/_programming/work/uptime-kuma-api/uptime_kuma_api/api.py", line 931, in login
    return self._call('login', {
  File "/Users/A69778720/csaba/itsh/_programming/work/uptime-kuma-api/uptime_kuma_api/api.py", line 320, in _call
    raise UptimeKumaException(r["msg"])
uptime_kuma_api.exceptions.UptimeKumaException: Incorrect username or password.

Do you have any plans to tackle this situation?

Example code not working -SQLITE_ERROR: table monitor has no column named auth_method

Hey, here's my exact code:

from uptime_kuma_api import UptimeKumaApi, MonitorType api = UptimeKumaApi('https://uptime.myDomain.io') api.login('myUsername', 'myPassword') result = api.add_monitor(type=MonitorType.HTTP, name="Google", url="https://google.com") print(result) api.disconnect()

I have verified that the username and password work, however when trying to add a monitor it fails with the following:

uptime_kuma_api.exceptions.UptimeKumaException: insert into monitor (accepted_statuscodes_json, auth_method, body, database_connection_string, dns_resolve_server, dns_resolve_type, expiry_notification, headers, hostname, ignore_tls, interval, maxredirects, maxretries, method, mqtt_password, mqtt_success_message, mqtt_topic, mqtt_username, name, port, proxy_id, retry_interval, type, upside_down, url, user_id) values ('["200-299"]', '', NULL, 'Server=<hostname>,<port>;Database=<your database>;User Id=<your user id>;Password=<your password>;Encrypt=<true/false>;TrustServerCertificate=<Yes/No>;Connection Timeout=<int>', '1.1.1.1', 'A', false, NULL, NULL, false, 60, 10, 0, 'GET', NULL, NULL, NULL, NULL, 'Google', 53, NULL, 60, 'http', false, 'https://google.com', 1) - SQLITE_ERROR: table monitor has no column named auth_method

I also tried using the IP directly, but nothing helped. Also turned off logins but that still did not help

Missing return element in `api.delete_status_page`

Hey 👋

Has api.delete_monitor(monitor_id) is returning :

{
	"msg": "Deleted sucessfully"
}

The same should apply to api.delete_status_page(slug)

Is there a constraint on this, so that this is not the case?

And for consistency in the API, I think api.delete_status_page() should take the status page ID as a parameter, not the slug

Add support for all monitor status values

Currently the monitor status field is a boolean and indicates whether a monitor is DOWN or UP. For this reason, it is currently not possible to determine whether a monitor status is PENDING or MAINTENANCE.

This field needs to be converted to an int with the following values:
0: DOWN
1: UP
2: PENDING
3: MAINTENANCE
(source: https://github.com/louislam/uptime-kuma/blob/8a3bce44ef8fdd8d2ee4b72ec5de064062c8a7b1/src/util.ts#L15C3-L18)

An enum for this status value would be useful.

Assign tags to monitor

First of all, nice work! Thanks!
But currently it is not possible to assign tags to a monitor or is it possible?
Cant find any tag key in the monitor schema API for that ;(

Retrieve monitor status inside get_monitors()

I'm curious if there is a way to get the status of a monitor returned in bulk vs having to call get_monitor_status for each monitor. As my list has grown this has become overwhelming as a process.

Ideally it would be a field returned in the get_monitors() call.

Check connection state

Hello,

Is there some function to check if the connection is already established and login is done?

Trying to get_monitors without previous login, results in a "no end" call. Should this has some timeout?

Add monitor with tag

Could you please show an example for adding a monitor with a tag?

I see an example after I create a monitor and add a tag on it.

    "tags": [
      {
        "color": "#4B5563",
        "id": 1,
        "monitor_id": 7,
        "name": "tagxxx",
        "tag_id": 1,
        "value": "true"
      }

Is it possible to create a monitor with the tag?

In api.py I see a function add_monitor but without the tags as args, and another function

def add_monitor_tag(self, tag_id: int, monitor_id: int, value=""):
        return self._call('addMonitorTag', (tag_id, monitor_id, value))

So am I getting this right that this is a 2 step process? Create the monitor, add the tag.

Add function to parse /metrics

Summary

The endpoint /metrics allow authentication with API key and provide most metrics. It can be useful to retrieve status of monitoring and kuma server in one go.

It is a polling endpoint and therefore it doesn't use the SocketIO protocol but a simple HTTP GET request is enough.

The only drawback is that this endpoint provide data in a specific format for Prometheus, so a good parsing will be required to extract the values.

I propose to add that to the next main release.

Checklist

  • Fetch data from /metrics
  • Authentication with API Key functionnal
  • Parse Prometheus syntax
  • Return clean dictionary / object with retrieved data

Syntax

metric_name [
  "{" label_name "=" `"` label_value `"` { "," label_name "=" `"` label_value `"` } [ "," ] "}"
] value [ timestamp ]

In the sample syntax:

metric_name and label_name carry the usual Prometheus expression language restrictions.
label_value can be any sequence of UTF-8 characters, but the backslash (\), double-quote ("), and line feed (\n) characters have to be escaped as \\, \", and \n, respectively.
value is a float represented as required by Go's ParseFloat() function. In addition to standard numerical values, NaN, +Inf, and -Inf are valid values representing not a number, positive infinity, and negative infinity, respectively.
The timestamp is an int64 (milliseconds since epoch, i.e. 1970-01-01 00:00:00 UTC, excluding leap seconds), represented as required by Go's ParseInt() function.

source

It would seem that it's made to be parsed in Golang, also, a go package already exists for that. I am not sure if we could use that as a "library" or middleware to extract the data.

Alternatively, the prometheus syntax is based on EBNF language. EBNF parsers exists in different languages so we could use that as well.

Ressources

Cannot update status page monitors

Found an actual issue this time. I can't seem to update the monitors on a status page no matter what I do. I am on Uptime-Kuma
Version: 1.17.1 using the latest git clones of your api repo & also tried the ansible module.

I get the following in the API:

result=api.save_status_page(slug="internal-status",monitors=["1","5","9","12"])
File "d:\Work\python\uptime\uptime_kuma_api\api.py", line 641, in save_status_page
return self._call('saveStatusPage', data)
File "d:\Work\python\uptime\uptime_kuma_api\api.py", line 408, in _call
raise UptimeKumaException(r["msg"])
uptime_kuma_api.exceptions.UptimeKumaException: insert into monitor_group (group_id, monitor_id, weight) values (11, NULL, 1) - SQLITE_CONSTRAINT: NOT NULL constraint failed: monitor_group.monitor_id
and the same in ansible:

[localhost]: FAILED! => {"changed": false, "msg": "Traceback (most recent call last):\n File \"/tmp/ansible_lucasheld.uptime_kuma.status_page_payload__6jfsqnw/ansible_lucasheld.uptime_kuma.status_page_payload.zip/ansible_collections/lucasheld/uptime_kuma/plugins/modules/status_page.py\", line 216, in main\n File \"/tmp/ansible_lucasheld.uptime_kuma.status_page_payload__6jfsqnw/ansible_lucasheld.uptime_kuma.status_page_payload.zip/ansible_collections/lucasheld/uptime_kuma/plugins/modules/status_page.py\", line 159, in run\n File \"/usr/local/lib/python3.6/site-packages/uptime_kuma_api/api.py\", line 641, in save_status_page\n return self._call('saveStatusPage', data)\n File \"/usr/local/lib/python3.6/site-packages/uptime_kuma_api/api.py\", line 408, in _call\n raise UptimeKumaException(r[\"msg\"])\nuptime_kuma_api.exceptions.UptimeKumaException: insert into monitor_group (group_id, monitor_id, weight) values (10, NULL, 1) - SQLITE_CONSTRAINT: NOT NULL constraint failed: monitor_group.monitor_id\n"

It seems the monitor_id never gets set into the monitor group section, for some reason it seems it gets a null value at first which causes uptime-kuma to error.

There seems to be no null passed on, the data passed is "[{'name': 'Services', 'monitorList': ['36']}]", not sure if this is an issue with uptime kuma instead of the api though.

Add required notification arguments

When creating a notification, it is currently not checked whether all the required arguments have been defined.

  • extract required arguments for all notification types from the uptime kuma source code using a script
  • add check to test, add and edit notification

need to modify the value of interval and retryInterval to make it lower than 20

Sometimes I need to modify the value of interval and retryInterval to make it lower than 20. I have modified the uptime-kuma related code files and repackaged the docker image, but there is a limit on the api here. I don’t know if this limit can No looser, in order to meet this modification requirements
https://github.com/lucasheld/uptime-kuma-api/blob/master/uptime_kuma_api/api.py#L287

api.edit_monitor(1, interval=5)
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.10/dist-packages/uptime_kuma_api/api.py", line 1332, in edit_monitor
return self._call('editMonitor', data)
File "/usr/local/lib/python3.10/dist-packages/uptime_kuma_api/api.py", line 506, in _call
raise UptimeKumaException(r. get("msg"))
uptime_kuma_api.exceptions.UptimeKumaException: Interval cannot be less than 20 seconds

Support for Quick Stats

I don't know if this is a feature I overlooked, but it would be great to be able to get the quick stats for all monitors, without having to call the API for each individual monitor.

image

Ideally something like get_quick_stats() which returns:

{
    "up": 71,
    "down": 0,
    "maintenance": 0,
    "unknown": 0,
    "pause": 2
}

Support login / use via api-key

Hi,
I wanted to use this wonderful project for some hobby-stuff, but it turns out that the login() method does not support the "api-key" authentication method. In combination with enabled 2FA it is somewhat hard to use this project... Would it be possible to add support for that? Maybe I'm just too stupid to read the documentation properly 😉
~Simon

...and I also tried login_by_token(), which just times out / reports invalid api keys.

Interval modification does not take effect

The display of the return result of the call looks normal, but the modification cannot actually be successful.

api.edit_monitor(2,Interval=30)
{'msg': 'Saved.', 'monitorID': 2}

save_status_page() failing because of unexpected keyword.

doing the following api call:

   api.save_status_page(
        slug="test",
        title="test Title",
        description="This is a test",
        publicGroupList=[
            {
                'name': 'Test',
                'weight': 1,
                'monitorList': [
                    {
                        "id": 33
                    }
                ]
            }
        ]
    )

but I get the following result:
TypeError: UptimeKumaApi._build_status_page_data() got an unexpected keyword argument 'showCertificateExpiry'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.