Skip to content

Instantly share code, notes, and snippets.

@bas-vk bas-vk/chat.js
Last active Mar 21, 2018

Embed
What would you like to do?
whisper chat demo
var chat = {
username: "<not set>",
topic: "0xfeedbabe",
key: "",
identity: "",
pollInterval: null,
filter: null,
setUsername: function(name) {
this.username = name;
return true;
},
join: function(password) {
// create key from shared secret
this.key = shh.generateSymKeyFromPassword(password);
// create pub/priv key for identity
this.identity = shh.newKeyPair();
pubKey = shh.getPublicKey(this.identity);
console.log("identity", pubKey.substr(2, 8));
// create message filter (console doesn't support subscriptions)
me = this;
this.filter = shh.newMessageFilter({
symKeyID: this.key,
topics: [this.topic],
}, function(err, message) {
if (err) {
console.error(err);
} else {
printMessage(message, me.username);
}
});
this.say("joined");
return true;
},
pollMessages: function() {
messages = shh.getFilterMessages(this.filter);
for (i = 0; i < messages.length; i++) {
printMessage(messages[i], this.username);
}
}
say: function(text) {
message = {
symKeyId: this.key,
topic: this.topic,
payload: web3.toHex(this.username + ": " + text),
powTime: 5,
powTarget: shh.info().minPow,
sig: this.identity
};
return shh.post(message);
}
leave: function() {
shh.deleteMessageFilter(this.filter);
clearInterval(this.pollInterval);
this.say("left...")
console.log("chat room left");
return true;
},
}
// start helper functions
function time(message) {
date = new Date(message.timestamp * 1000);
hours = date.getHours();
minutes = "0" + date.getMinutes();
seconds = "0" + date.getSeconds();
return hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
}
function sender(message) {
return message.sig.substr(2, 8)
}
function printMessage(message, myUsername) {
line = web3.toAscii(message.payload);
parts = line.split(":");
name = parts[0]
if (name !== myUsername) {
console.log("[" + time(message) + " " + name + "/" + sender(message) + "]" + parts.slice(1).join(":"));
}
}
// end helper functions
console.log("Supported functions:");
console.log("* chat.setUsername(<name:string>)");
console.log("* chat.join(<password:string>)");
console.log("* chat.leave()");
console.log("* chat.say(<message:string>)");
console.log();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.