Skip to main content

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

ParameterTypeRequiredDescription
messageDataArrayBufferYesMessage content as binary data
participantIdsstring[]YesArray of participant IDs to receive the message
isReliablebooleanNoWhether message must be delivered reliably (default: true)

Examples

Send Private Message

Send a private message to a specific player:

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');

Send Game Action to Specific Player

Send a game action that only affects a specific player:

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' });

Send Message to Multiple Players

Send the same message to multiple specific players:

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');

Send Spectator Data

Send game data to spectators only:

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);

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:

ErrorCauseSolution
Message and target player ID are requiredMissing parametersEnsure both messageData and participantIds are provided
Invalid participant IDTarget player not in roomVerify participant IDs are current and valid
Not in roomSender not connected to roomJoin room before sending messages
Message too largeMessage exceeds size limitReduce 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

Next Steps