I have a Lambda function that is designed to turn ON/OFF my Philip HUE lightbulbs. I am able to execute the python script & it runs (error-free) on my local machine. However, when I trigger the Lambda function (using an IoT Button) I get the following error message.
[ERROR] TypeError: list indices must be integers or slices, not str
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 13, in lambda_handler
if data["state"]["on"] == False:
Does anyone have any ideas/insight? Here is the full Python script:
import requests,json
bridgeIP = "ip_here"
userID = "userID_here"
lightID = "4" #Represents the ID assigned to lightbulb, in the living room.
def lambda_handler(lightID, lambda_context):
url = f"http://{bridgeIP}/api/{userID}/lights/{lightID}"
r = requests.get(url)
data = json.loads(r.text)
if data["state"]["on"] == False:
r = requests.put(f"{url}/state", json.dumps({"on":True}))
elif data["state"]["on"] == True:
r = requests.put(f"{url}/state", json.dumps({"on":False}))
lambda_handler(lightID, 4)
The last line in my script calls the lambda_handler() function. I'm told that I do not need this line because my Lambda calls the function when the Lambda Function is triggered. However I (believe) that I do need to manually call the function, when executing the script on my local machine.
The dataString
variable represented a dictionary (NOT a list) of values. It was necessary for me to use the nestedGet() function to determine the value of the "on" key.
{"on":True} vs {"on":False})
The final version of my fully-functional python script can be found here.