Send Message to Specific Player
Send messages to specific players in a Standard Room using the standardmessage method. This is perfect for private messages, targeted game actions, or player-specific updates that shouldn't be broadcast to everyone.
Method Signature
MoitribeSDK(gameId, 'standardmessage', params, callback)
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
messageData | ArrayBuffer | Yes | Message content as binary data |
participantIds | string[] | Yes | Array of participant IDs to receive the message |
isReliable | boolean | No | Whether message must be delivered reliably (default: true) |
Examples
Send Private Message
Send a private message to a specific player:
- JavaScript
- TypeScript
function sendPrivateMessage(targetParticipantId, message) {
const privateMessage = {
type: 'privateMessage',
message: message,
sender: 'player123',
timestamp: Date.now()
};
const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(privateMessage)).buffer;
MoitribeSDK('my-game-id', 'standardmessage', {
messageData: messageData,
participantIds: [targetParticipantId],
isReliable: true // Private messages should be reliable
}, (result) => {
if (result.success) {
console.log(`Private message sent to ${targetParticipantId}`);
displayPrivateMessage(message, 'You', targetParticipantId);
} else {
console.error('Failed to send private message:', result.msg);
showErrorMessage('Message failed to send');
}
});
}
// Usage
sendPrivateMessage('participant456', 'Nice move! Want to team up?');
sendPrivateMessage('participant789', 'Your strategy is really working well');
import MoitribeSDK from '@veniso/moitribe-js';
interface PrivateMessage {
type: 'privateMessage';
message: string;
sender: string;
timestamp: number;
}
function sendPrivateMessage(targetParticipantId: string, message: string): void {
const privateMessage: PrivateMessage = {
type: 'privateMessage',
message: message,
sender: 'player123',
timestamp: Date.now()
};
const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(privateMessage)).buffer;
MoitribeSDK('my-game-id', 'standardmessage', {
messageData: messageData,
participantIds: [targetParticipantId],
isReliable: true // Private messages should be reliable
}, (result) => {
if (result.success) {
console.log(`Private message sent to ${targetParticipantId}`);
displayPrivateMessage(message, 'You', targetParticipantId);
} else {
console.error('Failed to send private message:', result.msg);
showErrorMessage('Message failed to send');
}
});
}
// Usage
sendPrivateMessage('participant456', 'Nice move! Want to team up?');
sendPrivateMessage('participant789', 'Your strategy is really working well');
Send Game Action to Specific Player
Send a game action that only affects a specific player:
- JavaScript
- TypeScript
function sendGameAction(targetParticipantId, action, data) {
const gameAction = {
type: 'gameAction',
action: action,
data: data,
sender: 'player123',
timestamp: Date.now()
};
const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(gameAction)).buffer;
MoitribeSDK('my-game-id', 'standardmessage', {
messageData: messageData,
participantIds: [targetParticipantId],
isReliable: true // Game actions must be reliable
}, (result) => {
if (result.success) {
console.log(`Game action sent to ${targetParticipantId}: ${action}`);
} else {
console.error('Failed to send game action:', result.msg);
}
});
}
// Example game actions
sendGameAction('participant456', 'cardDraw', { card: 'Ace of Spades' });
sendGameAction('participant789', 'powerUp', { type: 'speed', duration: 5000 });
sendGameAction('participant456', 'damage', { amount: 25, source: 'fireball' });
import MoitribeSDK from '@veniso/moitribe-js';
interface GameAction {
type: 'gameAction';
action: string;
data: any;
sender: string;
timestamp: number;
}
function sendGameAction(targetParticipantId: string, action: string, data: any): void {
const gameAction: GameAction = {
type: 'gameAction',
action: action,
data: data,
sender: 'player123',
timestamp: Date.now()
};
const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(gameAction)).buffer;
MoitribeSDK('my-game-id', 'standardmessage', {
messageData: messageData,
participantIds: [targetParticipantId],
isReliable: true // Game actions must be reliable
}, (result) => {
if (result.success) {
console.log(`Game action sent to ${targetParticipantId}: ${action}`);
} else {
console.error('Failed to send game action:', result.msg);
}
});
}
// Example game actions
sendGameAction('participant456', 'cardDraw', { card: 'Ace of Spades' });
sendGameAction('participant789', 'powerUp', { type: 'speed', duration: 5000 });
sendGameAction('participant456', 'damage', { amount: 25, source: 'fireball' });
Send Message to Multiple Players
Send the same message to multiple specific players:
- JavaScript
- TypeScript
function sendToTeam(teamMemberIds, message) {
const teamMessage = {
type: 'teamMessage',
message: message,
sender: 'player123',
timestamp: Date.now()
};
const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(teamMessage)).buffer;
MoitribeSDK('my-game-id', 'standardmessage', {
messageData: messageData,
participantIds: teamMemberIds, // Array of participant IDs
isReliable: true
}, (result) => {
if (result.success) {
console.log(`Team message sent to ${teamMemberIds.length} players`);
displayTeamMessage(message, 'You', teamMemberIds);
} else {
console.error('Failed to send team message:', result.msg);
}
});
}
// Usage
const myTeam = ['participant456', 'participant789'];
sendToTeam(myTeam, 'Let\'s coordinate our next move!');
sendToTeam(myTeam, 'I\'ll attack from the left, you cover the right');
import MoitribeSDK from '@veniso/moitribe-js';
interface TeamMessage {
type: 'teamMessage';
message: string;
sender: string;
timestamp: number;
}
function sendToTeam(teamMemberIds: string[], message: string): void {
const teamMessage: TeamMessage = {
type: 'teamMessage',
message: message,
sender: 'player123',
timestamp: Date.now()
};
const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(teamMessage)).buffer;
MoitribeSDK('my-game-id', 'standardmessage', {
messageData: messageData,
participantIds: teamMemberIds, // Array of participant IDs
isReliable: true
}, (result) => {
if (result.success) {
console.log(`Team message sent to ${teamMemberIds.length} players`);
displayTeamMessage(message, 'You', teamMemberIds);
} else {
console.error('Failed to send team message:', result.msg);
}
});
}
// Usage
const myTeam: string[] = ['participant456', 'participant789'];
sendToTeam(myTeam, 'Let\'s coordinate our next move!');
sendToTeam(myTeam, 'I\'ll attack from the left, you cover the right');
Send Spectator Data
Send game data to spectators only:
- JavaScript
- TypeScript
function sendToSpectators(spectatorIds, gameState) {
const spectatorData = {
type: 'spectatorUpdate',
gameState: gameState,
timestamp: Date.now()
};
const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(spectatorData)).buffer;
MoitribeSDK('my-game-id', 'standardmessage', {
messageData: messageData,
participantIds: spectatorIds,
isReliable: false // Spectator data can be unreliable for performance
}, (result) => {
if (result.success) {
console.log(`Spectator update sent to ${spectatorIds.length} spectators`);
} else {
console.error('Failed to send spectator update:', result.msg);
}
});
}
// Usage
const spectators = ['spectator001', 'spectator002'];
const currentGameState = {
players: [
{ id: 'player123', score: 150, position: { x: 100, y: 200 } },
{ id: 'player456', score: 120, position: { x: 300, y: 400 } }
],
round: 3,
timeRemaining: 45
};
sendToSpectators(spectators, currentGameState);
import MoitribeSDK from '@veniso/moitribe-js';
interface SpectatorUpdate {
type: 'spectatorUpdate';
gameState: any;
timestamp: number;
}
function sendToSpectators(spectatorIds: string[], gameState: any): void {
const spectatorData: SpectatorUpdate = {
type: 'spectatorUpdate',
gameState: gameState,
timestamp: Date.now()
};
const encoder = new TextEncoder();
const messageData = encoder.encode(JSON.stringify(spectatorData)).buffer;
MoitribeSDK('my-game-id', 'standardmessage', {
messageData: messageData,
participantIds: spectatorIds,
isReliable: false // Spectator data can be unreliable for performance
}, (result) => {
if (result.success) {
console.log(`Spectator update sent to ${spectatorIds.length} spectators`);
} else {
console.error('Failed to send spectator update:', result.msg);
}
});
}
// Usage
const spectators: string[] = ['spectator001', 'spectator002'];
const currentGameState = {
players: [
{ id: 'player123', score: 150, position: { x: 100, y: 200 } },
{ id: 'player456', score: 120, position: { x: 300, y: 400 } }
],
round: 3,
timeRemaining: 45
};
sendToSpectators(spectators, currentGameState);
Getting Participant IDs
You can get participant IDs from the room object:
// In your room callbacks
onRoomCreated: (status, room) => {
if (status) {
// Get all participant IDs
const allParticipantIds = room.participants.map(p => p.participantID);
console.log('Available participants:', allParticipantIds);
// Get specific participant info
room.participants.forEach(participant => {
console.log(`Player: ${participant.name} (${participant.participantID})`);
});
}
}
Response Format
The callback receives a response object:
{
success: boolean;
msg?: string; // Error message if failed
}
Message Data Format
ArrayBuffer Conversion
All messages must be sent as ArrayBuffer:
// String to ArrayBuffer
const encoder = new TextEncoder();
const messageData = encoder.encode(stringMessage).buffer;
// Object to ArrayBuffer
const jsonString = JSON.stringify(object);
const messageData = encoder.encode(jsonString).buffer;
Message Structure
Include a type field for message identification:
const message = {
type: 'messageType', // Required for message routing
// ... other data
};
Target Selection Strategies
Single Target
participantIds: ['participant456']
Multiple Targets
participantIds: ['participant456', 'participant789', 'participant123']
Dynamic Target Selection
function getTeamMembers(room, teamName) {
return room.participants
.filter(p => p.team === teamName)
.map(p => p.participantID);
}
const teamMembers = getTeamMembers(currentRoom, 'red');
sendToTeam(teamMembers, 'Red team strategy update');
Error Handling
Common errors and solutions:
| Error | Cause | Solution |
|---|---|---|
Message and target player ID are required | Missing parameters | Ensure both messageData and participantIds are provided |
Invalid participant ID | Target player not in room | Verify participant IDs are current and valid |
Not in room | Sender not connected to room | Join room before sending messages |
Message too large | Message exceeds size limit | Reduce message size or split into multiple messages |
warning
Always verify that participant IDs are current and valid before sending messages. Players may leave the room, making their IDs invalid.
Best Practices
Target Validation
- Always validate participant IDs before sending
- Handle cases where targets are no longer in the room
- Use room participant data for accurate targeting
Message Efficiency
- Send to multiple targets in one call when possible
- Use unreliable messages for frequent, non-critical data
- Keep messages small and focused
Error Handling
- Check callback results for all sends
- Implement retry logic for important messages
- Provide user feedback for failed sends
Privacy Considerations
- Use private messages for sensitive information
- Be careful about broadcasting private data
- Consider message security for competitive games