構(gòu)建自己的 Smart Life 私有云(二)-> 連通 IFTTT & Slack 上一篇 我們破解了涂鴉的插座,搭建了自己的 web 服務,暴露了一個接口來控制插座的開關(guān)。這篇我們配合 IFTTT、Slack 來控制插座:
說 “OK Google” 喚醒 Google Assistant,然后說 “幫我打開臥室的電源”,最后插座被打開。 創(chuàng)建 Slack 機器人 Angelia
,對它發(fā)消息“幫我打開臥室的電源”,然后插座打開, Angelia
回復說 “好的,已經(jīng)打開”。 通過 Slack 機器人 Angelia
,發(fā)送 Slash Commands,打開關(guān)閉插座。 創(chuàng)建自己私人的 Slack Workspace 打開 Slack,根據(jù)提示創(chuàng)建自己的 Slack Workspace: https://slack.com/create
比如我的 Workspace 為 https://wangjie.slack.com 。
創(chuàng)建 Slack App 創(chuàng)建完畢登錄之后,默認應該有 #general
、#random
等 channel,但暫時不用這兩個 channel。
接下來,我們來創(chuàng)建一個 App。
打開 https://api.slack.com/ ,點擊 Start Building
輸入 App 名稱和你要添加到的 workspace。
設置 Bot 信息 創(chuàng)建完畢之后,我們需要設置這個 app 的機器人相關(guān)信息,打開 app 設置頁面 ,選擇 Bot Users
:
設置機器人的名稱(Display name 和 Default name)。勾選 Always Show My Bot as Online
,點擊 Save Changes
。
設置 Events API Event API 可以在各種時間發(fā)生的時候觸發(fā)調(diào)用,比如 消息發(fā)送的時候、channels 改變的時候等等。
我們先回到我們的 web 服務,打開上一章創(chuàng)建的 AngeliaController
,新增一個處理 Event 的 api:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @PostMapping("/say/at") fun say(@RequestBody request: BotEventRequestVo): JSONObject { logger.info("[slack event request]request -> \n$request") return JsonResult.success( "token" to request.token, "challenge" to request.challenge, "message" to message ) } data class BotEventRequestVo( val challenge: String?, val token: String?, val team_id: String?, val api_app_id: String?, val event: BotEventVo?, val type: String?, val event_id: String?, val event_time: String?, val authed_users: List<String>? ) data class BotEventVo( val type: String?, val user: String?, val text: String?, val client_msg_id: String?, val ts: String?, val channel: String?, val event_ts: String?, val channel_type: String? )
構(gòu)建,部署到服務器。
打開 Slack App 設置頁面的 Event Subscriptions
:
在 Request URL
中填寫剛剛在我們 web 服務上創(chuàng)建的接口 http://[server ip]:xxx/angelia/say/at
,并且點擊驗證。
注意:這里認證的依據(jù)是,你的接口 Response 需要返回請求中的 challenge
數(shù)據(jù)就算認證成功。
然后在 Subscribe to Bot Events
中添加訂閱的事件,需要增加的是 message.im
message.im
表示當你跟 bot 的私聊中產(chǎn)生消息的時候(有可能是你發(fā)送消息給 Bot,也有可能是 Bot 發(fā)消息給你),事件就會觸發(fā)。
點擊保存。
這時,當你在 Slack 中發(fā)送消息給機器人的時候,你的 web 服務端就能收到請求了。
處理事件 你的 web 服務器收到請求之后,需要對此進行處理,所以你需要去解析發(fā)的消息中的信息,然后打開/關(guān)閉對應設備(插座)的開關(guān)。完善之前的 say
接口:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 @Autowired lateinit var tuyaClientService: TuyaClientService @Autowired lateinit var angeliaSlackProperties: AngeliaSlackProperties /** * Angelia 機器人 對話入口 */ @PostMapping("/say/at") fun say(@RequestBody request: BotEventRequestVo): JSONObject { try { val text = request.event?.text val eventType = request.event?.type if (eventType == "message" // 直接對話 || request.event.user != angeliaSlackProperties.angelia_id // angelia自己發(fā)的忽略掉 ) { val message = angeliaBotService.parseTuyaClient(text) ?: "Sorry, I can not understand." angeliaSlackService.postMessage(JSONObject().apply { this["text"] = "$message" this["channel"] = request.event.channel this["as_user"] = true }) } return JsonResult.success( "token" to request.token, "challenge" to request.challenge, "message" to "Request eventId(${request.event_id}) done." ) } catch (e: Exception) { angeliaSlackService.postMessage(JSONObject().apply { this["text"] = "Sorry! Something is wrong: ${e.message}" this["channel"] = request.event?.channel this["as_user"] = true }) return JsonResult.error(e.message) } }
上面代碼的邏輯很簡單:
首先,eventType是直接對話的(與機器人 bot 私聊),并且是我發(fā)給機器人的(機器人發(fā)給我的消息不用處理)才會去處理 然后通過 angeliaBotService.parseTuyaClient()
方法進行文本解析和處理 如果解析不出來,則返回 null,message 就是 “Sorry, I can not understand.” 最后返回 Response(帶上 message),這里的 message 就是 Bot 發(fā)送給我的數(shù)據(jù)。 這里需要做一些 Slack 的配置 slack.properties:
1 2 3 4 5 6 7 8 # token for bot angelia.slack.bot_token=Bearer xoxb-2923xxxxxxxxxxxxxxxxxxxx # slack api angelia.slack.api_base_url=https://slack.com/api angelia.slack.api_chat_post_message=/chat.postMessage angelia.slack.angelia_id=UCWxxxxxx
angelia.slack.bot_token
:是 Bot 發(fā)送消息到 Slack 的token,這個 token 可以在 app 設置頁面的 OAuth & Permissions
中拿到
注意:是下面的那個 Bot User OAuth Access Token
,并且添加到配置文件的時候需要加上 Bearer
(注意后面有個空格)
angelia.slack.api_base_url
和 angelia.slack.api_chat_post_message
是發(fā)送消息的 url,不用改動。
angelia.slack.angelia_id
表示機器人的id,可以通過在 slack 左側(cè)選中機器人右鍵復制鏈接,path 最后部分就是 id
最后,你就能在 slack 中打開與機器人聊天框,發(fā)送“關(guān)閉插座a”來控制插座:
集成 Google Assistant 和 IFTTT 首先確保你的手機裝有 Google Assistant(Google Home 先不討論。。。是的,我沒買- -)。
首先我們需要在 web 服務器端再創(chuàng)建如下一個接口:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 /** * 插座控制接口 */ @PostMapping("/control/plug") fun controlPlug(@RequestBody request: PlugRequestVo): JSONObject { val dev = tuyaClientProperties.findDev(request.alias) return try { if (null == dev) { JsonResult.error("Device named ${request.alias} is not found") } else { tuyaClientService.controlPlug(dev.devId, request.turnOn) JsonResult.success() } } catch (e: Exception) { JsonResult.error(e.message) } } data class PlugRequestVo( val alias: String, val turnOn: Boolean )
構(gòu)建部署到服務器。
然后打開IFTTT、注冊(如果還沒有賬戶)登錄,創(chuàng)建 Applet
This :選擇 Google Assistant:
That :選擇 Webhook:
注意:POST 請求,在 body 中填寫如上 json 數(shù)據(jù)。 關(guān)閉的 Applet 也是類似,把 body 中的 turnOn 改成 false 就可以了
最后,你就可以通過 “OK, Google” 喚醒 Google Assistant,然后說”Turn on plug a”來打開插座了。
吐槽下涂鴉的 Google Assistant 本來想直接使用 Google Assistant 的 Smart Life 的,但是一直沒成功,很多人也在反映這個事情,不過貌似沒什么效果(看下面這個評分,估計反映一直是被無視的- -):
使用 Slack 的 Slash Command 控制 在 web 服務中再新增兩個接口用于 Slash Command:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 /** * 插座控制接口,F(xiàn)or Slack command line(slash commands) */ @PostMapping("/plug/turnon") fun plugTurnOnForCommand(@RequestBody body: String): JSONObject { return JsonResult.success("text" to plugControlForCommand(body, true)) } /** * For Slack command line(slash commands) */ @PostMapping("/plug/turnoff") fun plugTurnOffForCommand(@RequestBody body: String): JSONObject { return JsonResult.success("text" to plugControlForCommand(body, false)) } /** * For Slack command line(slash commands) control */ private fun plugControlForCommand(body: String, turnOn: Boolean): String { try { return body.split("&").map { val pair = it.split("=") Pair(pair[0], URLDecoder.decode(pair[1], "UTF-8")) }.firstOrNull { it.first == "text" }?.let { val dev = tuyaClientProperties.findContainsDev(it.second) if (null == dev) { "Sorry for failed command, Device named ${it.second} is not found." } else { tuyaClientService.controlPlug(dev.devId, turnOn) "${if (turnOn) "Turn On" else "Turn Off"} Done(${it.second})." } } ?: "Sorry for failed command, Device name required." } catch (e: Exception) { return "Sorry for failed command, ${e.message}." } }
打開 App 設置頁面的 Slash Commands
,
點擊 Create New Command
,
然后在聊天的輸入框中就可以通過”/“顯示 command 提示,選擇命令,后面跟上你要執(zhí)行該命令的設備別名就行了。
其它場景 還有其它很多場景可以實現(xiàn)。比如:
結(jié)合 IFTTT,當離開家門100m遠的時候,自動觸發(fā) webhook,讓你的私有云幫你把電源、智能們關(guān)閉。 實時檢測你的位置和家門,如果你不在家,自動調(diào)用 Google Calendar 確定你的日程安排,如果又沒有外出的安排,則通過 Slack 發(fā)送 Interactive messages 到你手機上提醒,提供按鈕一鍵鎖門。 小細節(jié),晚上手機充電的時候,可以設定手機一旦充滿,關(guān)閉電源,又如果手機電源掉電過快,低于90%的電量,重新自動開啟電源,確保你早上起床的時候手機電量肯定在某個值之上。 等等等等,太多的智能場景可以去實現(xiàn)。 章尾 現(xiàn)在越來越多的廠商制作著各種各樣的智能設備,但是又在自己的一畝三分地固步自封。做個插座,提供一個 app 控制下開關(guān)、定個時、做個 schedule 就是所謂的智能了,你買了我的設備就必須要用我的軟硬件產(chǎn)品。那些需要用戶花心思去考慮什么時候我該怎么的設備不是冰冷的,沒有生命的么?智能是人類賦予了設備生命,掌握了“思考”的能力,現(xiàn)在的生活如此多元化,再牛的公司也不可能覆蓋你的所有生活領(lǐng)域,如果買了這樣的智能設備但自此被囚困在這里,我想,這才是我非智能生活的開始吧。