Skip to content

Instantly share code, notes, and snippets.

@Armster15
Last active August 12, 2020 00:29
Show Gist options
  • Save Armster15/337974c16348d13f217eb64c22bf963e to your computer and use it in GitHub Desktop.
Save Armster15/337974c16348d13f217eb64c22bf963e to your computer and use it in GitHub Desktop.
"""
This was created by Armster15 and is offically
licensed under the Unlicense.
For information about the license and to view its
contents, please visit https://unlicense.org/
WHAT IS THIS?
=============
This is for getting the number of characters
you used in the current month for Amazon Polly.
This is useful if you want to control
the costs on Amazon Polly. You can
monitor your usage and if you want to,
you can use this to, say for example,
stop using Amazon Polly if it exceeds
your desired quota.
HOW TO USE
==========
Make sure that you have enabled Cost Manager
and that your user has access to it. Once
you set up both of those, then all you need to
do is run the function and it will
return an integer of the number of characters
you used!
"""
import boto3
import datetime
costExplorer = boto3.client('ce')
def GetPollyCharUsage():
"""
Returns number of characters used this month
in Amazon Polly
"""
def last_day_of_month(month, year):
"""
Helper function to return the last day of the month
"""
from dateutil.relativedelta import relativedelta
rawOutput = datetime.datetime(int(year), int(month), 1) + relativedelta(months=1, days=-1)
return rawOutput.day
now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
lastday = last_day_of_month(month, year)
response = costExplorer.get_cost_and_usage(
TimePeriod={
'Start': f'{year}-{month}-01',
'End': f'{year}-{month}-{lastday}'
},
Granularity='MONTHLY',
Metrics=[
'USAGE_QUANTITY',
],
GroupBy=[
{
'Type': 'DIMENSION',
'Key': 'SERVICE'
}
]
)
response = response["ResultsByTime"][0]["Groups"]
for key in response:
if "Polly" in "".join(key["Keys"]):
response = key
break
response = response["Metrics"]["UsageQuantity"]["Amount"]
return int(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment