publish vultr billing and traffic using vultr api by public mqtt broker
This file contains 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