collecting-reactions

# Collecting Reactions

D++ comes with many useful helper classes, but amongst these is something called dpp::collector. Collector is a template which can be specialised to automatically collect objects of a predetermined type from events for a specific interval of time. Once this time period is up, or the class is otherwise signalled, a method is called with the complete set of collected objects.

In the example below, we will use it to collect all reactions on a message.

    #include<dpp/dpp.h>

    /*Tocreateacollectorwemustderivefromdpp::collector.Asdpp::collectorisacomplicatedtemplate,
    *variouspre-madeformsexistsuchasthisone,reaction_collector.
    */
    classreact_collector:publicdpp::reaction_collector{
    public:
    /*Collectorwillrunfor20seconds*/
    react_collector(dpp::cluster*cl,dpp::snowflakeid):dpp::reaction_collector(cl,20,id){}

    /*Overridethe"completed"eventandthenoutputthenumberofcollectedreactionsasamessage.*/
    virtualvoidcompleted(conststd::vector<dpp::collected_reaction>&list)override{
    if(list.size()){
    owner->message_create(dpp::message(list[0].react_channel.id,"Icollected"+std::to_string(list.size())+"reactions!"));
    }else{
    owner->message_create(dpp::message("...Igotnothin'."));
    }
    }
    };

    intmain(){
    /*Createbot*/
    dpp::clusterbot("token",dpp::i_default_intents|dpp::i_message_content);

    /*Pointertoreactioncollector*/
    react_collector*r=nullptr;

    bot.on_log(dpp::utility::cout_logger());

    /*Messagehandler*/
    bot.on_message_create([&r,&bot](constdpp::message_create_t&event){

    /*Ifsomeonesendsamessagethathasthetext'collectreactions!'startareactioncollector*/
    if(event.msg.content=="collectreactions!"&&r==nullptr){
    /*Createanewreactioncollectortocollectreactions*/
    r=newreact_collector(&bot,event.msg.id);
    }

    });

    /*Startbot*/
    bot.start(dpp::st_wait);

    return0;
    }