Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 0neday/68c0003514180cc00b2916f2b7ef2483 to your computer and use it in GitHub Desktop.
Save 0neday/68c0003514180cc00b2916f2b7ef2483 to your computer and use it in GitHub Desktop.
publish vultr billing and traffic using vultr api by public mqtt broker
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