import { AppClient } from '@ni-paas-im/server-sdk';
const app = new AppClient({ appKey: process.env.IM_APP_KEY, appSecret: process.env.IM_APP_SECRET, baseUrl: 'http://127.0.0.1:8080' });
export async function openLiveRoom({ roomId, title, anchorId, rtcRoomId }) {
const room = await app.createChatroom({ chatroomId: roomId, name: title, owner: anchorId });
await app.openApi('chatroom.destroy.policy.set', {
chatroomId: room.chatroomId,
destroyType: 'fixed',
idleMs: 4 * 60 * 60 * 1000,
});
await app.openApi('chatroom.kv.set', {
chatroomId: room.chatroomId,
key: 'announcement',
value: JSON.stringify({ text: '欢迎进入直播间,文明发言', updatedAt: Date.now() }),
ttlMs: 30 * 60 * 1000,
});
await app.openApi('chatroom.rtc.bind', { chatroomId: room.chatroomId, rtcRoomId });
await app.openApi('chatroom.whitelist.add', { chatroomId: room.chatroomId, userIds: [anchorId, 'ops_1'] });
await app.openApi('chatroom.message.priority.set', {
chatroomId: room.chatroomId,
messageTypes: ['image', 'file', 'location'],
});
return room;
}
export async function closeLiveRoom(chatroomId) {
return app.destroyChatroom({ chatroomId });
}
import { createClient, ConversationType, Events } from '@ni-paas/im-web';
const client = createClient({ appkey: 'YOUR_APP_KEY', serverUrl: 'http://127.0.0.1:8080' });
await client.connect(TOKEN);
client.addEventListener(Events.CHATROOM_EVENT, (event) => {
if (event.kind === 'destroyed') showEnded(event.chatroomId);
if (event.kind === 'member_changed') updateOnline(event.onlineCount);
});
client.addEventListener(Events.MESSAGES, ({ messages }) => {
for (const message of messages) {
if (message.conversationType === ConversationType.CHATROOM) appendDanmaku(message);
}
});
await client.joinChatroom('live_1001');
await client.sendTextMessage(ConversationType.CHATROOM, 'live_1001', '主播好!');
const announcement = await fetch('/api/live/announcement?room=live_1001').then((r) => r.json());
client.joinChatroom("live_1001", object : ResultCallback<Chatroom> {
override fun onSuccess(room: Chatroom) {
client.sendTextMessage(ConversationType.CHATROOM, "live_1001", "主播好!", null, object : SendMessageCallback {
override fun onSuccess(message: Message) = Unit
override fun onError(error: IMError) = showError(error.code, error.message)
})
}
override fun onError(error: IMError) = showError(error.code, error.message)
})
await client.joinChatroom('live_1001');
await client.sendTextMessage(3, 'live_1001', '主播好!');
client.addEventListener('CHATROOM_EVENT', (event) {
if (event.kind == 'destroyed') showEnded(event.chatroomId);
if (event.kind == 'member_changed') updateOnline(event.onlineCount);
});