Bitmoji
The bitmoji capability brings the player's own Bitmoji into your game, as a rigged 3D model or as a head-and-shoulders image. Where Snapchat serves friends' Bitmoji, it can bring in some of the player's friends too.
Plan a fallback
Not every player has a Bitmoji, and any Bitmoji request can fail. Keep a default character in your game's zip, and show it when:
snapchat.isSupported('bitmoji')isfalse.getAvatarInfo()reportshasAvatar: false.- A request rejects with
ERR_INTERNAL. - The game runs on the desktop stub, whose 3D avatar is an empty placeholder.
snapchat.isStubistruethere.
Check for an avatar before you request one, because the media calls reject with ERR_INTERNAL for a player without a Bitmoji:
const { hasAvatar } = await snapchat.bitmoji.getAvatarInfo();
if (!hasAvatar) useDefaultCharacter();
Media URLs
get3DAvatar() and get2DAvatar() resolve with a url. Treat it as short-lived and opaque:
- Load it as soon as you get it. It expires after about five minutes.
- Call the API again for each load rather than keeping the URL.
- Don't parse it. It has no file extension, so tell your loader the asset type instead.
3D character
get3DAvatar() returns the player's Bitmoji as a rigged GLB with no animations. Author your animation clips on the Bitmoji rig, bundle them in your zip, and play them on the avatar. Build your default character on the same rig, so the same clips play on both. If you need one, download Snap's public default Bitmoji (about 2.5 MB) once and add it to your zip. A Lens can't fetch it at runtime.
Every Bitmoji has the same rig, and it's Snap's own, not a Mixamo-style humanoid. Joints are named like L_armUpper0001_bind_JNT, and most have a child that isn't a joint (L_armUpper0001_bind_JNT_SSC) before the next joint. Find bones by name anywhere under the root, not among a node's direct children. A clip authored on another skeleton leaves the avatar in its bind pose.
// The default character, bundled in the zip.
let url = './assets/avatar_default.glb';
if (snapchat.isSupported('bitmoji') && !snapchat.isStub) {
try {
const { hasAvatar } = await snapchat.bitmoji.getAvatarInfo();
if (hasAvatar) url = (await snapchat.bitmoji.get3DAvatar()).url;
} catch (e) {
console.warn('Using the default avatar:', e.message);
}
}
// Hand url to your engine's GLB loader straight away.
Smaller models
get3DAvatar() takes meshQuality and textureQuality to trade detail for download size. Each is 'low', 'medium', or 'high', and both default to 'high': the full model, which every engine can load. They work the same for a friend's Bitmoji.
textureQuality: 'medium'or'low'returns smaller textures.meshQuality: 'medium'or'low'returns a simplified mesh compressed withEXT_meshopt_compression. Load it with a loader that supports that extension, such as PlayCanvas 2.24 or later, as Low-poly Bitmoji shows. Bundle the decoder in your zip, like the rest of your code.
Snapchat versions before 14.33 ignore both options and return the full model, with no error and no way to tell which one you got. A game that asks for less must still be able to load the full-size GLB:
const { url } = await snapchat.bitmoji.get3DAvatar({
meshQuality: 'medium',
textureQuality: 'low',
});
// Load url with a meshopt-capable loader: it reads both the smaller and the full-size GLB.
2D image
get2DAvatar() returns a head-and-shoulders render of the avatar. size is 'small', 'medium', or 'large', and defaults to 'medium':
const { url } = await snapchat.bitmoji.get2DAvatar({ size: 'large' });
portraitImg.src = url;
Variants
getVariants() returns the IDs of a set of variants that Snapchat curates, the same set its own selfie picker offers. The IDs have no names, so to let the player choose one, render each variant at the small size, about six at a time, and use the images as the labels:
const { variants } = await snapchat.bitmoji.getVariants();
for (let i = 0; i < variants.length; i += 6) {
const batch = variants.slice(i, i + 6);
const images = await Promise.all(
batch.map((variant) =>
snapchat.bitmoji.get2DAvatar({ variant, size: 'small' })
)
);
images.forEach(({ url }, j) => addVariantButton(batch[j], url));
}
You can also pick variant IDs while you build the game and keep them as data. Either way, variants can retire. Requesting a retired one rejects with ERR_INVALID_PARAMS, so fall back to the default image:
let image;
try {
image = await snapchat.bitmoji.get2DAvatar({
variant: savedVariant,
size: 'large',
});
} catch (e) {
if (e.message !== snapchat.errors.INVALID_PARAMS) throw e;
// The variant has retired: show the default image instead.
image = await snapchat.bitmoji.get2DAvatar({ size: 'large' });
}
avatarImg.src = image.url;
Friends' Bitmoji
getFriendAvatars() returns some of the player's friends as { avatars: [{ avatar }] }, where each avatar is an opaque handle. Pass an entry straight back to get3DAvatar(), get2DAvatar(), or getAvatarInfo(), and the call answers for that friend instead of the player. Leave avatar out, or pass null, for the player.
Check that it's supported
Friends' Bitmoji is bitmoji version 2. Call snapchat.init() first, then check it like any capability:
await snapchat.init();
const servesFriends = snapchat.isSupported('bitmoji', 2);
A friend call made before init() resolves rejects with ERR_NOT_INITIALIZED and logs a console warning, on the desktop stub too, so a missing init() shows up while you build. After the check, ERR_INVALID_PARAMS means a bug in your call, such as a bad count.
Which friends you get
- Who: up to
maxBatchCount(20 by default, at most 50) of the player's most recent friends who are mutual, aren't blocked, have a Bitmoji, and let friends use it. Never the player. - Order: Snapchat shuffles them once and keeps that list for the session. Every call returns the first
countof the same list, so the order says nothing about who the player talks to most. Ask once for the most you'll show. A later call with a largercountreturns the same first handles, then more. - Fewer friends: a short list, or an empty one, is normal. It's never padded, so fill the rest of the scene with your own characters.
- Cooldown: when Snapchat finds no eligible friends, or can't read the friend list (
ERR_INTERNAL), it keeps that answer for a cooldown, 30 seconds by default, before it looks again. A call within the cooldown gets the same result. Ask again at a natural break, such as the next round, not in a loop. - Handles: a handle only works in the Lens session that got it. A new session, or another Lens, gets new ones, and an old handle rejects with
ERR_INVALID_PARAMSrather than answering with the player. Don't store or parse handles. - Pass the entry: call
get3DAvatar(friend), notget3DAvatar(friend.avatar). A bare string target rejects withERR_INVALID_PARAMS. Entries never carry a field named like a call option, so{ ...friend, size: 'small' }is always safe.
let friends = [];
if (servesFriends) {
try {
({ avatars: friends } = await snapchat.bitmoji.getFriendAvatars({
count: 3,
}));
} catch (e) {
if (e.message !== snapchat.errors.INTERNAL) throw e; // ERR_INVALID_PARAMS: fix the call
// The friend list is unavailable right now: play solo this round.
}
}
for (const friend of friends) {
const { url } = await snapchat.bitmoji.get2DAvatar({
...friend,
size: 'small',
});
addFriendPortrait(url);
}
Each friend's 3D avatar is a full GLB, about 1 to 3 MB, so load only the friends you show, and free each one when it leaves the scene.
With PlayCanvas
These recipes use the PlayCanvas Engine. app is your pc.Application (this.app inside a script), and snapchat.init() has already run. With ES modules, the same names come from playcanvas instead of the pc global.
Two helpers keep loading and freeing side by side. Neither needs a file extension in the URL, because the asset type is enough:
// Registers and loads an asset; resolves when it's ready, and rejects (unregistering it) on error.
function loadAsset(name, type, url) {
const asset = new pc.Asset(name, type, { url });
return new Promise((resolve, reject) => {
asset.ready(() => resolve(asset));
asset.once('error', (err) => {
app.assets.remove(asset);
reject(err);
});
app.assets.add(asset);
app.assets.load(asset);
});
}
// Frees an asset from loadAsset. Destroy the entities that use it first.
function unloadAsset(asset) {
asset.unload(); // for a GLB, this also frees its meshes, materials, and textures
app.assets.remove(asset);
}
Bitmoji as a 3D character
Load the player's avatar, or the default one, and play a clip from your zip on it through the anim component:
async function loadAvatar() {
if (snapchat.isSupported('bitmoji') && !snapchat.isStub) {
try {
const { hasAvatar } = await snapchat.bitmoji.getAvatarInfo();
if (hasAvatar) {
const { url } = await snapchat.bitmoji.get3DAvatar();
return await loadAsset('avatar', 'container', url);
}
} catch (e) {
console.warn('Using the default avatar:', e.message);
}
}
return loadAsset('avatar', 'container', 'assets/avatar_default.glb');
}
const [avatarAsset, danceAsset] = await Promise.all([
loadAvatar(),
loadAsset('dance', 'container', 'assets/dance.glb'),
]);
const avatar = avatarAsset.resource.instantiateRenderEntity();
avatar.addComponent('anim');
avatar.anim.assignAnimation(
'Dance',
danceAsset.resource.animations[0].resource
);
app.root.addChild(avatar);
When the character leaves the game, or before you load a different avatar, destroy the entity first, so nothing still renders the freed meshes. Keep danceAsset loaded for the next avatar, and free it once the game no longer needs the clip:
avatar.destroy();
unloadAsset(avatarAsset);
Low-poly Bitmoji
PlayCanvas 2.24 and later load the smaller models once you give the engine the meshoptimizer decoder. Without it, a model requested with meshQuality: 'medium' or 'low' fails to load, and loadAsset() rejects with an error that tells you to call meshoptInitialize. The full-size model loads either way.
The decoder comes from the meshoptimizer package, and your bundler builds it into the game:
npm install meshoptimizer
Initialize it once at startup with meshoptInitialize, before you load any avatar:
import { meshoptInitialize } from 'playcanvas';
import { MeshoptDecoder } from 'meshoptimizer/decoder';
meshoptInitialize({ decoder: MeshoptDecoder });
Without a bundler, copy meshopt_decoder.mjs from the package into your zip and pass its path instead. The engine imports it the first time a compressed model loads, and resolves the path against the page, not the engine:
pc.meshoptInitialize({ url: 'lib/meshopt_decoder.mjs' });
Then ask for the smaller model and load it like any other. In loadAvatar() from Bitmoji as a 3D character, pass the options to get3DAvatar():
const { url } = await snapchat.bitmoji.get3DAvatar({
meshQuality: 'medium',
textureQuality: 'low',
});
return await loadAsset('avatar', 'container', url);
For a friend, spread the entry in with the options, such as get3DAvatar({ ...friend, meshQuality: 'low', textureQuality: 'low' }). On Snapchat before 14.33, the same code gets the full model and the decoder goes unused.
The decoder runs on the main thread. When you load a group of friends at once, numWorkers moves decoding to Web Workers, such as meshoptInitialize({ decoder: MeshoptDecoder, numWorkers: 2 }).
Bitmoji as a UI image
Show the image on an element, here portrait, an entity with an image element component. Keep your own placeholder texture, placeholderTexture, for players without a Bitmoji:
async function loadAvatarImage() {
if (!snapchat.isSupported('bitmoji')) return null;
try {
const { url } = await snapchat.bitmoji.get2DAvatar({ size: 'large' }); // rejects without a Bitmoji
return await loadAsset('avatar-image', 'texture', url);
} catch (e) {
console.warn('No Bitmoji image:', e.message);
return null;
}
}
const imageAsset = await loadAvatarImage();
if (imageAsset) portrait.element.texture = imageAsset.resource;
To free it, put the placeholder back first:
portrait.element.texture = placeholderTexture;
unloadAsset(imageAsset);
Friends as characters
Load up to count friends' avatars, skipping any that fail. The list may be shorter than count, or empty. The stub's 3D models are empty placeholders, so on the desktop this loads no friends:
async function loadFriends(count) {
if (!snapchat.isSupported('bitmoji', 2) || snapchat.isStub) return [];
let avatars = [];
try {
({ avatars } = await snapchat.bitmoji.getFriendAvatars({ count }));
} catch (e) {
if (e.message !== snapchat.errors.INTERNAL) throw e; // ERR_INVALID_PARAMS: fix the call
console.warn('No friends this round:', e.message);
}
const assets = await Promise.all(
avatars.map(async (friend, i) => {
try {
const { url } = await snapchat.bitmoji.get3DAvatar(friend);
return await loadAsset(`friend-${i}`, 'container', url);
} catch (e) {
console.warn('Skipping a friend:', e.message);
return null;
}
})
);
return assets.filter(Boolean);
}
const friendAssets = await loadFriends(3);
for (const asset of friendAssets) {
app.root.addChild(asset.resource.instantiateRenderEntity());
}
Free each friend the same way as the player's avatar: destroy its entities, then unloadAsset().
BitmojiAPI in the API reference lists every parameter and return value.