跳到主要内容

用法

警告

WalletConnect聊天SDK目前处于Alpha阶段,还没有投入生产.

它的公共API和相关文档仍然可能出现重大的、破坏性的更改。

信息

关于示例实现,请参考我们的react-wallet-chat 示例

初始化您的WalletConnect ChatClient,使用 your Project ID

import { ChatClient } from "@walletconnect/chat-client";

const chatClient = await ChatClient.init({
projectId: "<YOUR PROJECT ID>",
});

为聊天相关的事件设置监听器

chatClient.on("chat_invite", async (event) => {
// React to an incoming invite to chat.
});

chatClient.on("chat_joined", async (event) => {
// React to your peer joining a given chat.
});

chatClient.on("chat_message", (event) => {
// React to an incoming messages for a given chat.
});

chatClient.on("chat_ping", (event) => {
// React to an incoming ping event from a peer on a given chat topic.
});

chatClient.on("chat_left", (event) => {
// React to a peer leaving a given chat.
});

在密钥服务器上注册您的区块链地址

为了允许其他聊天SDK用户邀请您加入聊天,您需要在公钥服务器上注册您的帐户。

密钥服务器期望该地址有一个完整的CAIP-2帐户(如下所示)。

await chatClient.register({ account: `eip155:1:0xa6de541...` });

邀请另一个同伴聊天

要向同伴发送聊天邀请,你可以用你的帐户和一个invite对象调用.invite() :

await chatClient.invite({
account: `eip155:1:0xf5d44...`, // the CAIP-2 formatted account of the recipient.
invite: {
message: "Hey, let's chat!", // an intro message from you
account: `eip155:1:0xa6de541...`, // your CAIP-2 formatted account that you registered previously.
},
});

接受或拒绝到来的邀请

当你的客户端收到来自同行的邀请时,你可以通过调用.accept()/.reject() 和邀请的id来接受/拒绝它。

await chatClient.accept({ id: invite.id });

// or

await chatClient.reject({ id: invite.id });

发送聊天消息

若要在已建立的聊天线程中(即在你或对方接受邀请后)向对方发送消息, 你可以用以下参数调用.message() :

await chatClient.message({
topic: chatThread.topic, // Topic of the chat thread this message should be sent to.
payload: {
message: "Hey, good to hear from you!", // the message you want to send.
authorAccount: `eip155:1:0xa6de541...`, // your CAIP-2 formatted account that you registered previously.
timestamp: Date.now(),
},
});

离开聊天

要离开一个已建立的聊天(删除聊天及其相关消息),调用.leave() 离开聊天:

await chatClient.leave({ topic: chatThread.topic });