caching-messages

# Caching Messages

By default D++ does not cache messages. The example program below demonstrates how to instantiate a custom cache using dpp::cache which will allow you to cache messages and query the cache for messages by ID.

This can be adjusted to cache any type derived from dpp::managed including types you define yourself.

This example will cache and hold onto messages forever! In a real world situation this would be bad. If you do use this, you should use the dpp::cache::remove() method periodically to remove stale items. This is left out of this example as a learning exercise to the reader. For further reading please see the documentation of dpp::cache.

    #include<dpp/dpp.h>
    #include<sstream>

    intmain(){
    /*Createbot*/
    dpp::clusterbot("token",dpp::i_default_intents|dpp::i_message_content);/*Becausewe'rehandlingmessages,weneedtousethe"i_message_content"intent!*/

    /*Createacachetocontaintypesofdpp::message*/
    dpp::cache<dpp::message>message_cache;

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

    /*Messagehandler*/
    bot.on_message_create([&message_cache](constdpp::message_create_t&event){
    /*Makeapermanentpointerusingnew,foreachmessagetobecached*/
    dpp::message*m=newdpp::message();

    /*Storethemessageintothepointerbycopyingit*/
    *m=event.msg;

    /*Storethenewpointertothecacheusingthestore()method*/
    message_cache.store(m);
    });

    /*Theeventisfiredwhensomeoneissuesyourcommands*/
    bot.on_slashcommand([&message_cache](constdpp::slashcommand_t&event){
    /*Checkwhichcommandtheyran*/
    if(event.command.get_command_name()=="get"){

    dpp::message*find_msg=message_cache.find(std::get<std::string>(event.get_parameter("message_id")));

    /*Iffind_msgisnull,telltheuserandreturn.*/
    if(!find_msg){
    event.reply("ThereisnomessagecachedwiththisID");
    return;
    }

    event.reply("Thismessagehadthefollowingcontent:"+find_msg->content);
    }
    });

    bot.on_ready([&bot](constdpp::ready_t&event){
    if(dpp::run_once<struct register_bot_commands>()){

    /*Createanewcommand.*/
    dpp::slashcommandnewcommand("get","Getthecontentsofamessagethatwascachedviaanid",bot.me.id);

    /*Addaparameteroption.*/
    newcommand.add_option(dpp::command_option(dpp::co_string,"message_id","TheIDofthemessageyouwanttofind",true));

    /*Registerthecommand*/
    bot.global_command_create(newcommand);
    }
    });

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

    return0;
    }