Pushing initial code

This commit is contained in:
Dom 2024-07-12 00:02:19 +01:00
parent 2915d7dc80
commit 995c851d16
3 changed files with 149 additions and 0 deletions

104
ShipmentNotifier.py Normal file
View File

@ -0,0 +1,104 @@
import requests
import json
import yaml
import logging
from datetime import datetime, timedelta
SETTINGS = yaml.safe_load(open('settings.yaml'))
def log(log_message, level):
logger = logging.getLogger('sn-logger')
log_message_types = {
'debug': logger.debug,
'info': logger.info,
'warning': logger.warning,
'error': logger.error,
'critical': logger.critical
}
if not logger.handlers:
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(levelname)s] %(message)s')
file_handler = logging.FileHandler('logs/' + 'log_' + datetime.now().strftime("%Y-%m-%d_%H:%M:%S") + '.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
log_message_types[level](log_message)
def isShipmentWithinLastTenMinutes(shipmentCreationTime):
currentTime = datetime.now()
shipmentTime = datetime.strptime(shipmentCreationTime, '%Y-%m-%dT%H:%M:%SZ')
timeDelta = currentTime - shipmentTime
log(f'Current time: {currentTime}', 'info')
log(f'Shipment creation time: {shipmentTime}', 'info')
log(f'Time delta: {timeDelta}', 'info')
if timeDelta < timedelta(minutes=10):
return True
else:
return False
def getAccessToken(settings=SETTINGS):
AccessToken = requests.post(
'https://api.amazon.com/auth/o2/token',
{
'grant_type': 'refresh_token',
'refresh_token': settings['REFRESH_TOKEN'],
'client_id': settings['CLIENT_ID'],
'client_secret': settings['CLIENT_SECRET'],
}
)
return AccessToken.json()['access_token']
def sendDiscordNotification(settings=SETTINGS, content=None):
notification = {"content": content}
requests.post(settings['DISCORD_WEBHOOK'], json=notification)
def getInboundShipments(settings=SETTINGS):
InboundShipments = requests.get(
settings['SPAPI_ENDPOINT'] + '/inbound/fba/2024-03-20/inboundPlans?pageSize=10&sortBy=CREATION_TIME&sortOrder=DESC&status=SHIPPED',
headers = {
'x-amz-access-token': getAccessToken(),
}
)
return InboundShipments.json()['inboundPlans']
def parseInboundShipments(settings=SETTINGS):
InboundShipments = getInboundShipments()
inboundPlanIDs = []
shipmentData = {}
for shipment in InboundShipments:
log('Got shipment creation date: {}'.format(shipment['createdAt']), 'info')
if isShipmentWithinLastTenMinutes(shipment['createdAt']):
log('Adding inbound plan to list: {}'.format(shipment['inboundPlanId']), 'info')
inboundPlanIDs.append(shipment['inboundPlanId'])
if inboundPlanIDs:
for ID in inboundPlanIDs:
getShipment = requests.get(
settings['SPAPI_ENDPOINT'] + f'/inbound/fba/2024-03-20/inboundPlans/{ID}/items',
headers = {
'x-amz-access-token': getAccessToken(),
}
)
if getShipment.json()['items']:
itemDict = {}
totalItemCount = 0
for item in getShipment.json()['items']:
itemDict.update({item.get('msku'): item.get('quantity')})
totalItemCount += item['quantity']
itemDict.update({'Total item count': totalItemCount})
shipmentData.update({ID: itemDict})
newline = '\n' #Escapes are not allowed inside fstrings
sendDiscordNotification(content=f':package: New shipment detected! :package:\nShipment contents:\n{newline.join(f"- {MSKU}: {Count}" for MSKU, Count in shipmentData[ID].items())}')
parseInboundShipments()

View File

@ -0,0 +1,40 @@
[INFO] Got shipment creation date: 2024-07-10T09:34:31Z
[INFO] Current time: 2024-07-12 00:00:02.372223
[INFO] Shipment creation time: 2024-07-10 09:34:31
[INFO] Time delta: 1 day, 14:25:31.372223
[INFO] Got shipment creation date: 2024-07-09T15:47:43Z
[INFO] Current time: 2024-07-12 00:00:02.374225
[INFO] Shipment creation time: 2024-07-09 15:47:43
[INFO] Time delta: 2 days, 8:12:19.374225
[INFO] Got shipment creation date: 2024-07-08T12:23:20Z
[INFO] Current time: 2024-07-12 00:00:02.374439
[INFO] Shipment creation time: 2024-07-08 12:23:20
[INFO] Time delta: 3 days, 11:36:42.374439
[INFO] Got shipment creation date: 2024-07-05T12:57:09Z
[INFO] Current time: 2024-07-12 00:00:02.374646
[INFO] Shipment creation time: 2024-07-05 12:57:09
[INFO] Time delta: 6 days, 11:02:53.374646
[INFO] Got shipment creation date: 2024-07-05T11:39:06Z
[INFO] Current time: 2024-07-12 00:00:02.374851
[INFO] Shipment creation time: 2024-07-05 11:39:06
[INFO] Time delta: 6 days, 12:20:56.374851
[INFO] Got shipment creation date: 2024-07-04T13:50:17Z
[INFO] Current time: 2024-07-12 00:00:02.375084
[INFO] Shipment creation time: 2024-07-04 13:50:17
[INFO] Time delta: 7 days, 10:09:45.375084
[INFO] Got shipment creation date: 2024-07-03T13:29:03Z
[INFO] Current time: 2024-07-12 00:00:02.375289
[INFO] Shipment creation time: 2024-07-03 13:29:03
[INFO] Time delta: 8 days, 10:30:59.375289
[INFO] Got shipment creation date: 2024-07-02T14:06:09Z
[INFO] Current time: 2024-07-12 00:00:02.375483
[INFO] Shipment creation time: 2024-07-02 14:06:09
[INFO] Time delta: 9 days, 9:53:53.375483
[INFO] Got shipment creation date: 2024-07-01T14:54:48Z
[INFO] Current time: 2024-07-12 00:00:02.375667
[INFO] Shipment creation time: 2024-07-01 14:54:48
[INFO] Time delta: 10 days, 9:05:14.375667
[INFO] Got shipment creation date: 2024-06-28T06:20:41Z
[INFO] Current time: 2024-07-12 00:00:02.375851
[INFO] Shipment creation time: 2024-06-28 06:20:41
[INFO] Time delta: 13 days, 17:39:21.375851

5
settings.yaml Normal file
View File

@ -0,0 +1,5 @@
REFRESH_TOKEN: TOKEN
CLIENT_ID: CLIENTID
CLIENT_SECRET: CLIENTSECRET
DISCORD_WEBHOOK: DISCORDWEBHOOK
SPAPI_ENDPOINT: SPAPIENDPOINT