Last active
February 26, 2024 06:56
-
-
Save 0neday/68c0003514180cc00b2916f2b7ef2483 to your computer and use it in GitHub Desktop.
publish vultr billing and traffic using vultr api by public mqtt broker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
import paho.mqtt.client as mqtt | |
import paho.mqtt.publish as publish | |
from requests.structures import CaseInsensitiveDict | |
# http get | |
url = 'https://api.vultr.com/v2/' | |
VULTR_API_KEY = '' | |
total = 0 | |
headers = CaseInsensitiveDict() | |
headers["Accept"] = "application/json" | |
headers["Authorization"] = "Bearer " + VULTR_API_KEY | |
# mqtt broker | |
broker_address = "broker.hivemq.com" | |
port = 1883 | |
# get first instant id | |
def get_instance(): | |
getInstance = json.loads(requests.get(url + 'instances', headers=headers).content) | |
instanceId = getInstance['instances'][0]['id'] | |
return instanceId | |
# billing | |
accountInfo = json.loads(requests.get(url + 'account', headers=headers).content) | |
billing = accountInfo['account']['pending_charges'] | |
balance = accountInfo['account']['balance'] | |
# data use | |
getInstanceBandwidth = requests.get(url + 'instances/' + get_instance() + '/bandwidth', headers=headers).content | |
bandwidth = json.loads(getInstanceBandwidth)['bandwidth'] | |
for key in bandwidth: | |
total = total + bandwidth[key]['incoming_bytes'] | |
# json out | |
js = { | |
"billing": billing, | |
'balance': balance, | |
"traffic": total | |
} | |
message = json.dumps(js) | |
print(message) | |
# mqtt broker | |
publish.single("vultr/billing_traffic", payload=message, qos=1, retain=1, hostname=broker_address, | |
port=port, client_id="", keepalive=60, will=None, auth=None, tls=None, | |
protocol=mqtt.MQTTv311, transport="tcp") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment