I'm working on a telegram bot project and I need to identify the type of JSON
file I receive.
For example, a message would have :
{
"update_id": 12345,
"message": {
"message_id": 123,
"from": {
"id": 123456,
"is_bot": false,
"first_name": "John",
"last_name": "Tan",
"username": "John123",
"language_code": "en-SG"
},
"chat": {
"id": 123456,
"first_name": "John",
"last_name": "Tan",
"username": "John123",
"type": "private"
},
"date": 1533567761,
"text": "/start",
"entities": [
{
"offset": 0,
"length": 6,
"type": "bot_command"
}
]
}
}
From this I know that message.message_id
exists. In this case:
if (e.postData.contents.message.message_id) {
// would run fine
}
However, other types of JSON
will not have the message object.
Other sources from javascript recommended this function
function isMsg(fn) {
try {
fn;
return true;
} catch(e) {
return false;
}
}
However, it seems that Google Apps Script will throw a TypeError
before I can even run this function. I ran it like this:
if (ifMsg(e.postData.contents.message.message_id)) {
// exception
}
{
"message": "Cannot read property \"message_id\" from undefined.",
"name": "TypeError"
}
Does anyone have other workarounds?
Edit: My question has been answered below by T.J. Crowder. The idea is that a "guard" is required in case higher level objects are also missing. In order to prevent the typeError: Cannot read "something" from undefined, use:
if(level1 && level1.level2 && level1.level2.level3){
//should run fine
}
In my case, this worked for me:
if(contents && contents.message && contents.message.message_id){
//runs fine
}
This works in my case because contents always exist. I found that it solved my issue.