微信開發系列之七 - 使用Redis儲存微信聊天記錄
In the second blog Wechat development series 2 – development Q&A service using nodejs of this series, we have developed a kind of Q&A service in Wechat which leverages a free Tuning Restful service so that you could chat with this service:
In this blog, I will show the steps how to store all of those conversation logs via Redis, so that you can review the conversations within Wechat app or delete them if necessary.
Implemented feature
Two new sub menus “Review” and “Delete” are developed under menu “Conversation”:
Once Review menu is pressed, the conversation log will be read out from Redis and displayed in Wechat app:
Delete menu will trigger the deletion of the conversation log belonging to current user who has pressed it. Once conversation is deleted, corresponding notification will be sent out if user has pressed the Review menu again.
Implementation detail
(1) Since as before my WeChat server runs on Heroku, which supports Redis as well. Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries. In this blog I will use Redis to store conversation logs.
It is very easy in Heroku to enable an application with Redis support, just select your application from drop down list and press Continue:
The default plan “Hobby Dev” is completely for free and enough for this prototype development.
Once done, in you application dashboard you can see the Redis as addon:
and the actual url for this Redis instance is automatically set in application variable which could be used in your program:
You don’t need any additional configuration on Redis, which is now ready for development. (2) follow the steps in blog Wechat development series 5 – embedded your UI5 application to Wechat app to create menu and two submenu.
It is enough to create menu via postman. You’d better first remove the old menu done in previous blog and recreate a new menu from scratch:
the source code of HTTP post payload for the new menu creation:
{
"button":[
{
"name":"UI5",
"sub_button":[{
"type": "view",
"name": "Jerry List",
"url": "
},{
"type": "click",
"name": "Other UI5 application",
"key": "dataQuery"
}]
},
{
"name":"Conversation",
"sub_button":[{
"type": "click",
"name": "Review",
"key": "review"
},{
"type": "click",
"name": "Delete",
"key": "delete"
}]
}
]
}
(3) Now every time when Tuning service receives a query from end user and is ready to send the answer of this query, add logic to record this conversation detail. Just add one line for logging in tuning.js:
The conversationLogService is implemented in conversationLogService.js, which simply delegates the logging call to Redis service wrapper module.
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();}Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();}function logConversation(wholeContent, question, answer){
var fromUserId = formattedValue(getXMLNodeValue('FromUserName', wholeContent));
var toUserId = formattedValue(getXMLNodeValue('ToUserName', wholeContent));
var fromUserName = config.userMap[fromUserId] || fromUserId;
var toUserName = config.userMap[toUserId] || toUserId;
var datetime = "Send Time: " + new Date().today() + " " + new Date().timeNow();
redisClient.insert(toUserId, objectToString(fromUserName, toUserName, datetime, question, answer));};function objectToString(fromUserName, toUserName, datetime, question, answer){
var record = {
"from": fromUserName,
"to": toUserName,
"sendTime": datetime,
"question": question,
"answer": answer
};
return JSON.stringify(record); }function getList(sToUserOpenId){
return redisClient.getList(sToUserOpenId);}function deleteLog(sToUserOpenId){
return redisClient.clearList(sToUserOpenId);}var oService = {
log: logConversation,
getLog: getList,
deleteLog: deleteLog}module.exports = oService;
Redis service wrapper module is implemented in file redisClient.js.
This wrapper module is built on top of open source Redis module for nodejs, whose source code could be found from github: https:// github.com/NodeRedis/no de_redis
var redis = require("redis"),
client = redis.createClient(process.env.REDIS_URL || "redis://h:p99a8dd0d92871b9ffe7a026e6d70beecd7f2a0e743fa1e2840a58ce048f41c4a@ec2-34-237-158-248.compute-1.amazonaws.com:9479"); // by default localhost will be used!!client.on("error", function (err) {
console.log("Trouble......... Redis startup failed: " + err);});function insertIntoList(sOpenId, oElement){
client.lpush(sOpenId, oElement);}function clearList(sOpenId){
return new Promise(function(resolve,reject){
client.del(sOpenId, function(error, count){
if(error){
console.log("error when clear list:" + error);
reject(error);
}
var reply = "list clear successfully";
console.log(reply);
resolve(reply);
});
});}function getListContent(sOpenId){
return new Promise(function(resolve,reject){
client.lrange(sOpenId, 0, -1, function(err, reply) {
console.log("content for list: " + sOpenId + " **********: " + reply + "***");
var content = reply;
if( content == ""){
content = "no conversation log found.";
console.log("reject content: " + content);
reject(content);
}
else {
resolve(formatToWechat(content));
}
});
});}function formatToWechat(raw){
var formatted = "[" + raw + "]";
var result = "";
var logs = JSON.parse(formatted);
for( var i = 0; i < logs.length; i++){
var record = "record[" + i + "]:" + " [[from]] " + logs[i].from
+ " [[to]] " + logs[i].to + " [[sendTime]] " + logs[i].sendTime + " [[question]] " + logs[i].question
+ " [[answer]] " + logs[i].answer;
if( i === 0){
result = record;
}
else{
result = result + "\n" + "\n" + record;
}
}
return result;}var oRedisClient = {
insert: insertIntoList,
clearList: clearList,
getList: getListContent};module.exports = oRedisClient;
(4) implement event handling logic when menu “review” and “delete” are pressed.
Corresponding API provided by Redis are called to read log records from Redis or just clear the list where the log records are stored.
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24475491/viewspace-2724274/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- [開源] 企業微信-會話內容存檔 實時拉取企業微信聊天記錄會話
- 微信公眾平臺開發(七) 聊天機器人功能開發機器人
- iOS開發之微信聊天頁面實現iOS
- 微信小程式開發系列七:微信小程式的頁面跳轉微信小程式
- 微信QQ聊天記錄分析工具-微Q
- 微信開發之錄音檔案
- 原生微信小程式開發記錄微信小程式
- vivo手機匯出微信聊天記錄方法
- 微信程式開發系列教程(三)使用微信API給微信使用者發文字訊息API
- QQ聊天記錄儲存如何實現?
- 微信小程式使用記錄微信小程式
- 重灌系統如何儲存qq聊天記錄
- 微信開發系列教程(二)
- iOS開發之微信聊天工具欄的封裝iOS封裝
- 微信開發學習日記(七):開源微商城wemall
- 七牛儲存使用筆記筆記
- 電腦微信資料夾儲存在什麼位置 電腦微信聊天記錄在哪個資料夾裡面
- 微信開發之微信域名防封介面
- 微信小程式storage儲存微信小程式
- 微信小程式開發—專案實戰之聊天機器人微信小程式機器人
- 微信公眾號Java開發記錄(一)接入Java
- 劫持微信聊天記錄並分析還原 —— 訪問資料庫並檢視聊天記錄(五)資料庫
- .Net微信網頁開發之使用微信JS-SDK自定義微信分享內容網頁JS
- .Net微信網頁開發之使用微信JS-SDK呼叫微信掃一掃功能網頁JS
- C#微信開發系列教程C#
- 微信小程式開發系列六:微信框架API的呼叫微信小程式框架API
- 微信開發系列之一 - 微信公眾號開發的開發環境搭建開發環境
- 電腦微信聊天記錄在哪個資料夾裡面
- 將微信聊天記錄中的檔案傳送到郵箱
- 微信開發 微信支付
- 微信程式開發系列教程(二)使用JavaScript給微信使用者傳送訊息JavaScript
- 微信小程式開發記錄_01程式碼構成微信小程式
- 寒假小軟體開發記錄05--微信分享
- C與微信新玩法之儲存媒體資訊轉發給好友
- php 微信開發之 微信支付 v3 配置PHP
- 微信小程式--聊天室小程式(雲開發)微信小程式
- iPhone手機如何備份微信聊天記錄到電腦上iPhone
- 刪除的微信聊天記錄怎麼恢復?(已解決)