Skip to content

Instantly share code, notes, and snippets.

@jiftechnify
Created April 19, 2023 02:28
Show Gist options
  • Save jiftechnify/5fbe5b296b74248c00593b55cb993c5d to your computer and use it in GitHub Desktop.
Save jiftechnify/5fbe5b296b74248c00593b55cb993c5d to your computer and use it in GitHub Desktop.
post text to a Nostr relay
import {
Event,
Relay,
UnsignedEvent,
getEventHash,
getPublicKey,
nip19,
relayInit,
signEvent,
} from "nostr-tools";
import "websocket-polyfill";
const connectToRelay = async (relayUrl: string) => {
const relay = relayInit(relayUrl);
relay.on("connect", () => {
console.log("connected to the relay");
});
relay.on("error", () => {
console.log("failed to connect to the relay");
});
await relay.connect();
return relay;
};
const sendEvent = async (relay: Relay, event: Event) => {
return new Promise<void>((resolve, reject) => {
const pub = relay.publish(event);
pub.on("ok", () => {
resolve();
});
pub.on("failed", (reason: unknown) => {
console.log("failed to send event:", reason);
reject(Error("failed to send event"));
});
});
};
const NSEC = process.env["NSEC"] as string;
const post = async (
content: string,
currTime: number = Math.floor(new Date().getTime() / 1000)
) => {
const relay = await connectToRelay("wss://relay-jp.nostr.wirednet.jp");
const { type, data } = nip19.decode(NSEC);
if (type !== "nsec") {
console.log("NSEC is not an nsec");
return;
}
const senderPrivkey = data as string;
const senderPubkey = getPublicKey(senderPrivkey);
const ev: UnsignedEvent = {
kind: 1,
pubkey: senderPubkey,
content: content,
created_at: currTime,
tags: [],
};
const evId = getEventHash(ev);
const evSig = signEvent(ev, senderPrivkey);
await sendEvent(relay, { ...ev, id: evId, sig: evSig });
relay.close();
};
// usage: NSEC=<nsec> node -r esbuild-register post.ts <content>
if (process.argv.length <= 2) {
console.log("please specify content to post");
}
const content = process.argv[2] as string;
post(content).catch((e) => console.error(e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment