Created
February 7, 2018 00:32
-
-
Save mhjb/214f050375b8f4ae9a8932fe1efd300a to your computer and use it in GitHub Desktop.
clmbot library module incl Messenger list template builder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_ = require 'underscore' | |
stars = (n) -> | |
num_stars = Math.round ((n - 1) * -5) # 0 = perfect score; 1 = total mismatch | |
if num_stars | |
Array(num_stars + 1).join '★' | |
else | |
'' | |
truncate_to_word = (string, maxLength) -> | |
if string.length > maxLength | |
truncatedString = string.substring 0, maxLength | |
truncatedString | |
.substring 0, Math.min truncatedString.length, truncatedString.lastIndexOf ' ' | |
.concat ' …' | |
else | |
string | |
module.exports = | |
# https://developers.facebook.com/docs/messenger-platform/send-api-reference/list-template | |
list_template_builder: (results) -> | |
if process.env.ngrok_subdomain | |
base_url = "http://#{process.env.ngrok_subdomain}_clm.ngrok.io" | |
else | |
base_url = process.env.clm_hostname | |
results = _.first results, 4 | |
attachment: | |
type: 'template' | |
payload: | |
template_type: 'list' | |
top_element_style: 'compact' | |
elements: results.map (result) -> | |
subtitle = "#{stars result.score} [#{result.score.toFixed 2}] #{truncate_to_word result.item.a, 70}" | |
if result.item.a.length > 600 | |
title: result.item.q | |
subtitle: subtitle | |
buttons: [ | |
type:"web_url" | |
url: "#{base_url}/#{result.item.id}" | |
title: "View" | |
webview_height_ratio: "compact" | |
] | |
else | |
title: result.item.q | |
subtitle: subtitle | |
buttons: [ | |
type:"postback" | |
title: "View" | |
payload: result.item.a | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment