Chatting with Users
Not all conversations are meant to be public. You can create a chat conversation to interact with users in private.
Note: Your bot should never interact with users without obtaining their consent. Be extra careful to avoid potentially spammy behaviour in private conversations!
Accepting Messages
By default, your bot account will only receive messages from users it follows. To receive messages from any (or no) user, you can use the Bot#setChatPreference method.
Valid options for this method are:
- IncomingChatPreference.None - Your bot will not receive any new messages. Existing conversations will be unaffected.
- IncomingChatPreference.Following - Your bot will only receive messages from users it follows. This is the default setting.
- IncomingChatPreference.All - Your bot will receive messages from any user.
This only needs to be set once for your bot account. You can change it at any time.
Starting a Conversation
To chat with a user, you need a Conversation object.
If you know the DID(s) of the user(s) you want to chat with, you can use the Bot#getConversationForMembers method.
This method will fetch an existing conversation if one exists, or create a new one if it doesn’t.
You can obtain a list of all conversations the bot is a part of by calling the Bot#listConversations method.
Sending and Reading Messages
Start by obtaining the Conversation object for the user you want to chat with. You can then send messages to the user and read their responses.
You can read chat history by calling the Conversation#getMessages method. This will return an array of ChatMessage and DeletedChatMessage objects.
You can send messages to the user by calling the Conversation#sendMessage method.
Like posts, you can use a RichText instance to send rich text messages containing links and mentions. More on that in Rich Text.
If you already have a Profile object, you can skip the Conversation object and send and read messages directly.
Receiving Message Events
Of course, you won’t usually know in advance who you want to message. You may want your bot to respond to private messages from any user.
To start, you’ll want to initialize your bot with emitChatEvents set to true
.
Your bot will now emit an event whenever a message is received, which you can handle as follows:
You can access a reference to the sender’s profile and the conversation the message was sent in by calling the getSender and getConversation methods.
With Great Power…
…comes great responsibility. People don’t like unsolicited messages. It’s your responsibility to ensure your bot is well-behaved and makes Bluesky a better place for everyone.