BearyChat FP(函数式编程) hubot SDK。
dependencies: [
.package(url: "https://github.com/bearyinnovative/FuncBot.git", from: "0.0.1"),
]
你只需要调用一个函数
run(main, with: "your_rtm_token")
main
的类型是 IO<()>
。
let main = RTM.loopToRead >>- Console.echo
run(main, with: "your_rtm_token")
所以你可以循环读取 hubot 收到的消息,并在控制台中打印出来。
调用 Message.filter(to:)
来将 JSON 字符串映射到正常的传入消息。
let main = RTM.loopToRead
>>- Message.filter(to: Message.Normal.self)
>>- Console.echoLn
调用 RTM.sendMsg
来发送 Outgoing
消息。
let main = RTM.loopToRead
>>- Console.debug { print("Did read string: \($0)") }
>>- Message.filter(for: Message.Normal.self)
>>- Message.map {
Message.Outgoing(type: .P2P(to: $0.uid),
vchannelId: $0.vchannelId,
text: "Hello " + $0.text,
referKey: $0.key)
}
>>- RTM.sendMsg
run(main, with: "your_rtm_token")
let baike: (String) -> IO<String> = { keyword in
IO { send in
let appid = ""
var request = URLRequest(url: URL(string: "https://baike.baidu.com/api/openapi/BaikeLemmaCardApi")!)
request.httpBody = "appid=\(appid)&bk_key=\(keyword)".data(using: .utf8)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request){ data, _, _ in
guard let data = data, let desc: String = data.json?["abstract"] else {
print("Parse error!")
return
}
send(desc)
}.resume()
}
}
let main = RTM.loopToRead
>>- Message.filter(for: Message.Normal.self)
>>- Message.replyBindText(refer: true, baike)
>>- RTM.sendMsg
run(main, with: "your_rtm_token")
let actions = [
"\\baike": baike(appId: "your_app_id"),
"\\huoxing": huoxing(appId: "your_app_id"),
"辣鸡": { _ in .return("闭嘴,无耻小人!") },
"苟": { _ in .return("利国家生死以") },
"岂": { _ in .return("因祸福避趋之") }
]
let main = RTM.loopToRead
>>- Message.filter(to: Message.Normal.self)
>>- Message.reply(with: actions, refer: true, empty: "唔知你讲咩~")
>>- RTM.sendMsg
run(main, with: "your_rtm_token")