Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: stream examples #841

Merged
merged 1 commit into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 37 additions & 19 deletions packages/examples/automated-chat/index.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,57 @@
import { PushAPI } from '@pushprotocol/restapi';
import { createSocketConnection, EVENTS } from '@pushprotocol/socket';
import { CONSTANTS, PushAPI } from '@pushprotocol/restapi';
import { ethers } from 'ethers';

// Creating a random signer from a wallet, ideally this is the wallet you will connect
const signer = ethers.Wallet.createRandom();

// Initialize wallet user, pass 'prod' instead of 'staging' for mainnet apps
const userAlice = await PushAPI.initialize(signer, { env: 'prod' });
const userAlice = await PushAPI.initialize(signer, { env: CONSTANTS.ENV.PROD });

// This will be the wallet address of the recipient
const pushAIWalletAddress = '0x99A08ac6254dcf7ccc37CeC662aeba8eFA666666';

// Create Socket to Listen to incoming messages
const pushSDKSocket = await createSocketConnection({
user: signer.address,
socketType: 'chat',
socketOptions: { autoConnect: true, reconnectionAttempts: 3 },
env: 'prod',
});
// IMPORTANT: Setup stream events before stream.connect()
// Checkout all chat stream listen options - https://push.org/docs/chat/build/stream-chats/
const stream = await userAlice.initStream(
[
CONSTANTS.STREAM.CHAT,
CONSTANTS.STREAM.CONNECT,
CONSTANTS.STREAM.DISCONNECT,
]
);

// Setup responder for CONSTANTS.STREAM.CONNECT event
stream.on(CONSTANTS.STREAM.CONNECT, () => {
console.log('Stream Connected');

pushSDKSocket.on(EVENTS.CONNECT, (message) => {
console.log('Socket Connected');

// Send a message to Bob after socket connection so that messages as an example
console.log('Sending message to PushAI Bot');
const aliceMessagesPushAI = userAlice.chat.send(pushAIWalletAddress, {
userAlice.chat.send(pushAIWalletAddress, {
content: "Gm gm! It's a me... Mario",
});

});

// Setup responder for CONSTANTS.STREAM.DISCONNECT event
stream.on(CONSTANTS.STREAM.DISCONNECT, () => {
console.log('Stream Disconnected');
});

// Setup responder for CONSTANTS.STREAM.CHAT event
// React to message payload getting recieved
pushSDKSocket.on(EVENTS.CHAT_RECEIVED_MESSAGE, (message) => {
console.log('Encrypted Message Received');
stream.on(CONSTANTS.STREAM.CHAT, (message) => {
console.log('Message Received');
console.log(message);

pushSDKSocket.disconnect();
if (message.origin === 'self') {
console.log("Message sent by your wallet, please wait for few moments for PushAI response");
}
if (message.origin === 'other') {
console.log("Message received by PushAI.eth");

// disconnect stream
stream.disconnect();
}
});

// now that response logic for streams are setup
// finally connect stream
await stream.connect();
2 changes: 1 addition & 1 deletion packages/examples/automated-chat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@pushprotocol/restapi": "1.4.19",
"@pushprotocol/restapi": "1.4.35",
"@pushprotocol/socket": "0.5.2",
"ethers": "5.7.2"
},
Expand Down
13 changes: 13 additions & 0 deletions packages/examples/stream-chat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# About Automated Chat
Automated chat example shows how you can receive chats when you talk to someone using Push Chat. In this example, we establish a socket connection and then send a message to pushai.eth, which is an automated chat bot that replies back.

## What's the use case
You can use this example to see the functionality of sockets and how you can respond to messages from backend (server) when a wallet messages you (or a wallet you own). Some use cases are:

- Creating an automated support bot
- Creating an AI chat bot

## Install instructions
1. Navigate to this directory from the terminal
2. do `npm install` or `yarn install`
3. do `yarn start`
115 changes: 115 additions & 0 deletions packages/examples/stream-chat/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { CONSTANTS, PushAPI } from '@pushprotocol/restapi';
import { EVENTS, createSocketConnection } from '@pushprotocol/socket';
import { ethers } from 'ethers';

// Creating a random signer from a wallet, ideally this is the wallet you will connect
const signerAlice = ethers.Wallet.createRandom();
const signerBob = ethers.Wallet.createRandom();

// Initialize wallet user, pass 'prod' instead of 'staging' for mainnet apps
const userAlice = await PushAPI.initialize(signerAlice, { env: CONSTANTS.ENV.PROD });
const userBob = await PushAPI.initialize(signerBob, { env: CONSTANTS.ENV.PROD });

// Initialize stream but don't connect yet
// Checkout all chat stream listen options - https://push.org/docs/chat/build/stream-chats/
const streamAlice = await userAlice.initStream(
[
CONSTANTS.STREAM.CHAT,
CONSTANTS.STREAM.CHAT_OPS,
CONSTANTS.STREAM.CONNECT
]
);

const streamBob = await userBob.initStream(
[
CONSTANTS.STREAM.CHAT,
CONSTANTS.STREAM.CHAT_OPS,
CONSTANTS.STREAM.CONNECT
]
);

let aliceConnected = false;
let bobConnected = false;

// IMPORTANT: Setup stream events before stream.connect()
// Connect stream - Alice
streamAlice.on(CONSTANTS.STREAM.CONNECT, () => {
aliceConnected = true;
console.log('Alice Stream Connected');

// Call sendMessage which checks if both Alice and Bob are connected
// amd sends a message from Alice to Bob
sendMessage();
});

// Connect stream - Bob
streamBob.on(CONSTANTS.STREAM.CONNECT, () => {
bobConnected = true;
console.log('Bob Stream Connected');

// Call sendMessage which checks if both Alice and Bob are connected
// amd sends a message from Alice to Bob
sendMessage();
});

const sendMessage = async () => {
if (aliceConnected && bobConnected) {
// Send a message to Bob after socket connection so that messages as an example
console.log('Sending message from Alice to Bob as we know Alice and Bob stream are both connected and can respond');
console.log('Wait few moments to get messages streaming in');
await userAlice.chat.send(signerBob.address, {
content: "Gm gm! It's a me... Alice!",
});
}
};

// Listen for chat messages - Alice
streamAlice.on(CONSTANTS.STREAM.CHAT, (chat) => {
if (chat.origin === 'other') { // means chat that is coming is sent by other (not self as stream emits both your and other's messages)
console.log('Alice received chat message', chat);
}
});

// Listen for chat messages - Bob
streamBob.on(CONSTANTS.STREAM.CHAT, async (chat) => {
if (chat.origin === 'other') { // means chat that is coming is sent by other (not self as stream emits both your and other's messages)
console.log('Bob received chat message', chat);

// Since Bob and Alice are not connected, approve Alice's request
await userBob.chat.accept(chat.from);
console.log('Bob approved Alice, only required once per chat', chat);

// send response to Alice
await userBob.chat.send(chat.from, {
content: "Nice to meet you Alice! This is Bob!",
});

// disconnect the streams
await streamAlice.disconnect();
await streamBob.disconnect();
}
});

// Listen for chat ops - Alice
streamAlice.on(CONSTANTS.STREAM.CHAT_OPS, (chatops) => {
console.log('Alice received chat ops', chatops);
});

// Listen for chat ops - Bob
streamBob.on(CONSTANTS.STREAM.CHAT_OPS, (chatops) => {
console.log('Bob received chat ops', chatops);
});

// Listen for disconnect - Alice
streamAlice.on(CONSTANTS.STREAM.DISCONNECT, () => {
console.log('Alice disconnected');
});

// Listen for disconnect - Bob
streamBob.on(CONSTANTS.STREAM.DISCONNECT, () => {
console.log('Bob disconnected');
});

// Events and methods for socket connection are set, now connect stream
await streamAlice.connect();
await streamBob.connect();
Loading
Loading