package prizedraw; import com.twilio.Twilio; import com.twilio.base.ResourceSet; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; import org.joda.time.DateTime; import java.util.Collections; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static java.util.stream.Collectors.toList; public class TwilioRaffle { private static final DateTime DRAW_START = new DateTime(2019,5,27,9,0); private static final DateTime DRAW_END = new DateTime(2019,5,28,16,30); private static final int NUMBER_OF_WINNERS = 3; private static final PhoneNumber CONTEST_NUMBER = new PhoneNumber(System.getenv("CONTEST_NUMBER")); private static final String CONGRATULATIONS_YOU_WON_MESSAGE = "\uD83C\uDF89 Congratulations - you won a prize in the Twilio Prize Draw at JBcnConf \uD83C\uDF89\n\n" + "Head to the Twilio booth and show us this message to collect your prize \uD83C\uDF8A - we will give them out in the order you arrive so don't delay."; public static void main(String[] args) { Twilio.init(System.getenv("ACCOUNT_SID"), System.getenv("AUTH_TOKEN")); ResourceSet allMessages = Message.reader().setTo(CONTEST_NUMBER).read(); StreamSupport.stream(allMessages.spliterator(), false) // Create a java.util.stream.Stream .filter( m -> m.getDateSent().isAfter(DRAW_START)) // Filter out entries which were too early... .filter( m -> m.getDateSent().isBefore(DRAW_END)) // ...or too late. .map(Message::getFrom) // Take the FromNumber from each message. .distinct() // Remove duplicates, then... .collect(Collectors.collectingAndThen(toList(), // ...collect into a list so that... list -> { Collections.shuffle(list); // ...we can shuffle the order. return list.stream(); })) .limit(NUMBER_OF_WINNERS) // Make sure we don't select too many winners .forEach( winner -> { Message.creator( winner, CONTEST_NUMBER, CONGRATULATIONS_YOU_WON_MESSAGE).create(); // Send a message to all the winners! }); } }