com.viber.bot.api.MessageToMapConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of viber-bot Show documentation
Show all versions of viber-bot Show documentation
Use this library to communicate with the Viber API to develop a bot for https://developers.viber.com/.
package com.viber.bot.api;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.MoreObjects;
import com.viber.bot.message.Message;
import com.viber.bot.message.MessageKeyboard;
import com.viber.bot.message.TrackingData;
import com.viber.bot.profile.BotProfile;
import com.viber.bot.profile.UserProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
class MessageToMapConverter {
private static final Logger logger = LoggerFactory.getLogger(MessageToMapConverter.class);
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final String EMPTY_STRING = "";
static Map mapMessage(final @Nonnull BotProfile from, final @Nonnull UserProfile to,
final @Nonnull Message message, final @Nonnull Optional optionalKeyboard,
final @Nonnull Optional optionalTrackingData) {
final Map messageMap = message.getMapRepresentation();
messageMap.put("tracking_data", isPresentAndNotEmpty(optionalTrackingData) ? serializeTrackingData(optionalTrackingData.get()) : null);
messageMap.put("keyboard", isPresentAndNotEmpty(optionalKeyboard) ? optionalKeyboard.get() : null);
return new HashMap() {{
put("receiver", to.getId());
put("sender", new HashMap() {{
put("name", from.getName());
put("avatar", MoreObjects.firstNonNull(from.getAvatar(), ""));
}});
putAll(messageMap);
}};
}
private static String serializeTrackingData(final TrackingData trackingData) {
try {
return objectMapper.writeValueAsString(trackingData);
} catch (final Exception e) {
logger.warn("Could not serialize tracking data", trackingData);
return EMPTY_STRING;
}
}
private static boolean isPresentAndNotEmpty(final Optional optional) {
return optional.isPresent() && !optional.get().isEmpty();
}
}