名称:使用-nostr 描述:使用Nostr协议发布笔记、发送加密消息和与中继交互。
NOSTR发布技能
使用nostr-sdk库
来源:https://github.com/besoeasy/nostr-sdk
概述
使用nostr-sdk模块的最小直接导出,发布消息、发送加密私信,并与Nostr去中心化社交协议交互。
安装:
npm install nostr-sdk
关键概念:
- nsec:Bech32格式的私钥(以
nsec1开头) - npub:Bech32格式的公钥(以
npub1开头) - 中继:传播Nostr事件的WebSocket服务器
- 事件:表示帖子、私信等的签名JSON对象
- POW:工作证明(挖矿),用于减少垃圾信息
默认中继:
- wss://relay.damus.io
- wss://nos.lol
- wss://relay.snort.social
- wss://nostr-pub.wellorder.net
- wss://nostr.oxtr.dev
- 以及9个以上以实现最大覆盖
技能
发布公共笔记
向Nostr发布公共文本笔记。
用法:
const { posttoNostr } = require("nostr-sdk");
const result = await posttoNostr("Hello Nostr! #introduction", {
nsec: "nsec1...your-private-key",
tags: [],
relays: null,
powDifficulty: 4
});
console.log(result);
参数:
message:要发布的文本内容tags:可选标签数组(例如,[['t', 'topic']])relays:可选自定义中继列表(若为null则使用默认值)powDifficulty:工作证明难度(默认:4,0表示禁用)
自动提取的标签:
- 话题标签:
#nostr→["t", "nostr"] - 提及:
@npub1...→["p", <pubkey>] - 链接:URL自动保留
- 笔记:
note1...引用 →["e", <event-id>]
响应:
{
success: true,
eventId: "abc123...",
published: 12, // 成功发布到12个中继
failed: 2, // 在2个中继上失败
totalRelays: 14,
powDifficulty: 4,
errors: []
}
何时使用:
- 用户想要发布公共消息
- 分享带有话题标签的内容
- 广播公告
回复帖子
回复现有的Nostr帖子。
用法:
const { replyToPost } = require("nostr-sdk");
const result = await replyToPost(
"note1...event-id", // 事件ID(笔记或十六进制格式)
"Great post! @npub1...author", // 回复消息
"npub1...author-pubkey", // 作者的公钥
[], // 额外标签
null, // 使用默认中继
4 // POW难度
);
何时使用:
- 回应特定帖子
- 线程对话
- 参与内容互动
发送加密私信(NIP-4)
使用旧版NIP-4标准发送加密私信。
用法:
const { sendmessage } = require("nostr-sdk");
const result = await sendmessage(
"npub1...recipient", // 收件人的公钥
"Secret message here", // 消息内容
{ nsec: "nsec1...your-private-key" }
);
何时使用:
- 与旧版Nostr客户端兼容
- 基础加密消息
- 广泛客户端支持
限制:
- 发送者/收件人元数据可见
- 旧版加密(NIP-04)
发送现代加密私信(NIP-17)
使用NIP-17发送礼物包裹的加密消息(推荐)。
用法:
const { sendMessageNIP17 } = require("nostr-sdk");
const result = await sendMessageNIP17(
"npub1...recipient", // 收件人的公钥
"Private message!", // 消息内容
{ nsec: "nsec1...your-private-key" }
);
好处:
- 密封发送者(隐藏谁发送了消息)
- 更好的元数据保护
- 现代NIP-44加密
- 每个消息使用临时密钥
何时使用:
- 需要最大隐私
- 现代应用
- 隐藏发送者身份
接收消息(NIP-4)
监听传入的私信。
用法:
const { getmessage } = require("nostr-sdk");
const unsubscribe = getmessage((message) => {
console.log("来自:", message.senderNpub);
console.log("消息:", message.content);
console.log("时间:", new Date(message.timestamp * 1000));
}, {
nsec: "nsec1...your-private-key",
since: Math.floor(Date.now() / 1000) - 3600 // 最后一小时
});
// 停止监听:
// unsubscribe();
消息对象:
{
id: "event-id",
sender: "hex-pubkey",
senderNpub: "npub1...",
content: "decrypted message",
timestamp: 1234567890,
event: { /* 完整事件 */ }
}
何时使用:
- 构建聊天机器人
- 接收私信
- 监控消息
接收现代消息(NIP-17)
监听传入的NIP-17礼物包裹消息。
用法:
const { getMessageNIP17 } = require("nostr-sdk");
const unsubscribe = getMessageNIP17((message) => {
console.log("来自:", message.senderNpub);
console.log("内容:", message.content);
console.log("包裹ID:", message.wrappedEventId);
}, {
nsec: "nsec1...your-private-key",
since: Math.floor(Date.now() / 1000) - 300 // 最后5分钟
});
// 停止监听:
// unsubscribe();
何时使用:
- 接收现代私信
- 传入私信的最大隐私
- 支持NIP-17协议
获取全局动态
从全局Nostr动态获取最近的帖子。
用法:
const { getGlobalFeed } = require("nostr-sdk");
const events = await getGlobalFeed({
limit: 50, // 最多50个帖子
since: Math.floor(Date.now() / 1000) - 3600, // 最后一小时
until: null, // 到现在为止
kinds: [1], // 仅文本笔记
authors: null, // 所有作者
relays: null // 使用默认值
});
events.forEach(event => {
console.log("作者:", event.authorNpub);
console.log("内容:", event.content);
console.log("笔记ID:", event.noteId);
console.log("发布时间:", event.createdAtDate);
});
何时使用:
- 构建阅读器
- 监控公共帖子
- 趋势内容分析
生成密钥
生成新的Nostr密钥对。
用法:
const { generateNewKey } = require("nostr-sdk");
const keys = generateNewKey();
console.log(keys);
// {
// privateKey: "hex-private-key",
// publicKey: "hex-public-key",
// nsec: "nsec1...",
// npub: "npub1..."
// }
快速生成:
const { generateRandomNsec } = require("nostr-sdk");
const nsec = generateRandomNsec();
console.log(nsec); // nsec1...
转换密钥
在密钥格式之间转换。
用法:
const { nsecToPublic } = require("nostr-sdk");
const publicInfo = nsecToPublic("nsec1...your-key");
console.log(publicInfo);
// {
// publicKey: "hex-public-key",
// npub: "npub1..."
// }
快速入门示例
示例1:发布消息
const { posttoNostr } = require("nostr-sdk");
async function postHello() {
const result = await posttoNostr("Hello from my bot! #nostr #automation", {
nsec: "nsec1...your-private-key"
});
console.log("已发布:", result.eventId);
}
postHello();
示例2:发送私密私信
const { sendMessageNIP17 } = require("nostr-sdk");
async function sendPrivateMessage() {
const result = await sendMessageNIP17(
"npub1...recipient",
"This is a secret message!",
{ nsec: "nsec1...your-private-key" }
);
console.log("已发送:", result.success ? "是" : "否");
}
sendPrivateMessage();
示例3:监听私信
const { getMessageNIP17 } = require("nostr-sdk");
console.log("正在监听消息...");
const unsubscribe = getMessageNIP17((msg) => {
console.log(`来自 ${msg.senderNpub} 的消息: ${msg.content}`);
}, {
nsec: "nsec1...your-private-key"
});
// 保持运行或调用unsubscribe()停止
示例4:快速发布(无需设置)
const { posttoNostr } = require("nostr-sdk");
// 如果未提供密钥,则自动生成
const result = await posttoNostr("Quick post!", {
nsec: "nsec1...your-key" // 可选 - 如果省略则生成新密钥
});
决策树
用户想要发布到Nostr?
├─ 是公共帖子吗?
│ ├─ 是回复其他帖子吗?
│ │ ├─ 是 → 使用replyToPost()
│ │ └─ 否 → 使用posttoNostr()
│ └─ 需要垃圾信息防护吗?
│ ├─ 是 → 设置powDifficulty为4+
│ └─ 否 → 设置powDifficulty为0
│
├─ 是私密消息吗?
│ ├─ 需要最大隐私吗?
│ │ ├─ 是 → 使用sendMessageNIP17()
│ │ └─ 否 → 使用sendmessage()
│ │
│ └─ 需要接收消息吗?
│ ├─ 使用NIP-17 → getMessageNIP17()
│ └─ 使用NIP-4(旧版) → getmessage()
│
└─ 需要读取帖子吗?
└─ 使用getGlobalFeed()
密钥管理
安全最佳实践:
- 永远不要将nsec密钥提交到git
- 将密钥存储在环境变量或安全保险库中
- 为测试生成新密钥
- 为不同目的使用不同密钥
环境变量:
export NOSTR_NSEC="nsec1...your-private-key"
const { posttoNostr } = require("nostr-sdk");
await posttoNostr("健康检查日志", {
nsec: process.env.NOSTR_NSEC
});
错误处理
常见错误:
私钥未设置→ 提供nsec或生成密钥无效的nsec格式→ 检查bech32编码发布到Nostr失败→ 检查中继连接解密消息失败→ 收件人私钥错误
最佳实践:
const { posttoNostr } = require("nostr-sdk");
try {
const result = await posttoNostr("Hello", {
nsec: process.env.NOSTR_NSEC
});
if (!result.success) {
console.error("发布失败:", result.errors);
}
} catch (error) {
console.error("错误:", error.message);
}
清理
直接导出函数不需要类实例,因此没有客户端清理步骤。
资源
- 库:https://github.com/besoeasy/nostr-sdk
- Nostr协议:https://nostr.com
- NIPs(Nostr实现可能性):https://github.com/nostr-protocol/nips
- 密钥工具:
- https://nostrcheck.me(密钥转换器)
- https://snort.social(网页客户端)
- https://damus.io(iOS客户端)