75 lines
2.3 KiB
JavaScript
75 lines
2.3 KiB
JavaScript
/**
|
|
* Prepare the environment by installing a docker container with the Nostr relay server.
|
|
* docker pull scsibug/nostr-rs-relay
|
|
* docker run -p 7000:8080 scsibug/nostr-rs-relay
|
|
*
|
|
* Install the necessary dependencies by running the following command:
|
|
* npm install
|
|
*
|
|
* Run the script with the following command: node listen.js
|
|
* This script listens for new messages on the Nostr network.
|
|
* It connects to a Nostr relay server and subscribes to text notes/messages.
|
|
* When a new message is received, it prints the message content, sender's public key, and timestamp.
|
|
*
|
|
* Test with the send.js script to send a message.
|
|
* run the send.js script with the following command: node send.js
|
|
*/
|
|
|
|
|
|
import { Relay } from 'nostr-tools/relay'
|
|
import { verifyEvent } from 'nostr-tools/pure'
|
|
|
|
// If not running in Node.js, comment the following 3 lines:
|
|
import WebSocket from 'ws'
|
|
import { useWebSocketImplementation } from 'nostr-tools/relay'
|
|
useWebSocketImplementation(WebSocket)
|
|
|
|
const RELAY_URL = 'ws://localhost:7000' // Replace with your preferred relay
|
|
|
|
async function listenForMessages() {
|
|
try {
|
|
const relay = await Relay.connect(RELAY_URL)
|
|
console.log(`Connected to ${relay.url}`)
|
|
|
|
const sub = relay.subscribe(
|
|
[
|
|
{
|
|
kinds: [1], // Listen for text notes/messages
|
|
since: Math.floor(Date.now() / 1000) // Only get new messages from now on
|
|
}
|
|
],
|
|
{
|
|
onevent(event) {
|
|
if (verifyEvent(event)) {
|
|
console.log('New message received:')
|
|
console.log(`From: ${event.pubkey}`)
|
|
console.log(`Content: ${event.content}`)
|
|
console.log(`Timestamp: ${new Date(event.created_at * 1000).toLocaleString()}`)
|
|
console.log('---')
|
|
} else {
|
|
console.log('Received an invalid event')
|
|
}
|
|
},
|
|
oneose() {
|
|
console.log('Subscription stream ended')
|
|
},
|
|
onerror(error) {
|
|
console.error('Subscription error:', error)
|
|
}
|
|
}
|
|
)
|
|
|
|
// Keep the script running
|
|
process.on('SIGINT', () => {
|
|
console.log('Closing subscription and relay connection')
|
|
sub.close()
|
|
relay.close()
|
|
process.exit()
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('Error connecting to relay:', error)
|
|
}
|
|
}
|
|
|
|
listenForMessages() |