Skip to content

Instantly share code, notes, and snippets.

@and7ey
Last active October 9, 2024 11:56
Show Gist options
  • Save and7ey/dc81815a332a819f387373f9b8ddb283 to your computer and use it in GitHub Desktop.
Save and7ey/dc81815a332a819f387373f9b8ddb283 to your computer and use it in GitHub Desktop.
Home Assistant - Pyscript - Modify input_boolean entity when there is an active (in delivery) VkusVill order
"""
service: pyscript.vkusvill_get_orders
data:
token: <YOUR-TOKEN>
number: '<YOUR-CARD-NUMBER>'
var: 'input_boolean.vkusvill_delivery_in_progress'
"""
import aiohttp
import json
url = 'https://mobile.vkusvill.ru/api/v1/orders'
@service(supports_response="optional")
def vkusvill_get_orders(token, number, var, return_response=True):
log.info(f'Starting to get VkusVill orders for card {number}...')
id_order = None
id_status = None
status_name = None
url_get_last_order = url + f'?number={number}&cnt=1' # get only one (the latest) order
headers = {
'x-vkusvill-device': 'xiaomi',
'x-vkusvill-source': '4',
'x-vkusvill-version': '3.11.6 (311006)',
'x-vkusvill-token': token
}
async with aiohttp.ClientSession() as session:
async with session.get(url_get_last_order, headers=headers) as resp:
if resp.status == 200:
data_str = resp.text()
log.debug(data_str)
data_json = json.loads(data_str)
if data_json and data_json.get('data', {}).get('orders', []):
orders = data_json.get('data', {}).get('orders', [])
if len(orders) > 0:
last_order = orders[0].get('orders', [])[0]
if last_order:
log.info(last_order)
id_order = last_order.get('id_order', None)
id_status = last_order.get('id_status', None)
status_name = last_order.get('status_name', None)
if id_order and id_status == 4: # Доставка
log.info(f'VkusVill order {id_order} is being delivered')
input_boolean.turn_on(entity_id=var) # change the status of delivery to on
else:
log.info('No orders being delivered found')
input_boolean.turn_off(entity_id=var) # change the status of delivery to off
else:
log.error('No last VkusVill order found')
input_boolean.turn_off(entity_id=var) # change the status of delivery to off
else:
log.error('No VkusVill orders found')
input_boolean.turn_off(entity_id=var) # change the status of delivery to off
else:
log.error(f'Failed to get VkusVill orders, the error code is {resp.status}')
input_boolean.turn_off(entity_id=var) # change the status of delivery to off
log.info('Finished to get VkusVill orders')
return {'id_order': id_order,
'id_status': id_status,
'status_name': status_name
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment