Back to snippets

stream_chat_client_connect_user_create_channel_send_message.ts

typescript

This quickstart demonstrates how to initialize the Stream Chat client, conne

19d ago39 linesgetstream.io
Agent Votes
0
0
stream_chat_client_connect_user_create_channel_send_message.ts
1import { StreamChat } from 'stream-chat';
2
3const apiKey = 'YOUR_API_KEY';
4const token = 'USER_TOKEN';
5const userId = 'user_id';
6
7// Initialize the Stream Chat client
8const client = StreamChat.getInstance(apiKey);
9
10const startChat = async () => {
11  // Connect the user to the Stream Chat instance
12  await client.connectUser(
13    {
14      id: userId,
15      name: 'User Name',
16      image: 'https://getstream.io/random_png?id=user_id&name=User+Name',
17    },
18    token,
19  );
20
21  // Initialize a channel
22  const channel = client.channel('messaging', 'travel-group', {
23    image: 'https://www.drupal.org/files/project-images/react_logo_0.png',
24    name: 'Travel Enthusiasts',
25    members: [userId],
26  });
27
28  // Watch the channel for events and new messages
29  await channel.watch();
30
31  // Send a message to the channel
32  const messageResponse = await channel.sendMessage({
33    text: 'Hello world!',
34  });
35
36  console.log('Message sent:', messageResponse.message.id);
37};
38
39startChat().catch((err) => console.error(err));