').text(message);
var $container = $('');
$container.append($user).append($message);
$chatWindow.append($container);
$chatWindow.scrollTop($chatWindow[0].scrollHeight);
}
// Alert the user they have been assigned a random username
print('Logging in...');
// Get an access token for the current user, passing a username (identity)
// and a device ID - for browser-based apps, we'll always just use the
// value "browser"
$.getJSON('/token', {
device: 'browser'
}, function(data) {
// Alert the user they have been assigned a random username
username = data.identity;
print('You have been assigned a random username of: '
+ '' + username + '', true);
// Initialize the Chat client
chatClient = new Twilio.Chat.Client(data.token);
chatClient.getSubscribedChannels().then(createOrJoinGeneralChannel);
});
function createOrJoinGeneralChannel() {
// Get the general chat channel, which is where all the messages are
// sent in this simple application
print('Attempting to join "general" chat channel...');
var promise = chatClient.getChannelByUniqueName('general');
promise.then(function(channel) {
generalChannel = channel;
console.log('Found general channel:');
console.log(generalChannel);
setupChannel();
}).catch(function() {
// If it doesn't exist, let's create it
console.log('Creating general channel');
chatClient.createChannel({
uniqueName: 'general',
friendlyName: 'General Chat Channel'
}).then(function(channel) {
console.log('Created general channel:');
console.log(channel);
generalChannel = channel;
setupChannel();
});
});
}
// Set up channel after it has been found
function setupChannel() {
// Join the general channel
generalChannel.join().then(function(channel) {
print('Joined channel as '
+ '' + username + '.', true);
});
// Listen for new messages sent to the channel
generalChannel.on('messageAdded', function(message) {
printMessage(message.author, message.body);
});
}
// Send a new message to the general channel
var $input = $('#chat-input');
$input.on('keydown', function(e) {
if (e.keyCode == 13 && generalChannel) {
generalChannel.sendMessage($input.val())
$input.val('');
}
});
});