Advice on how to improve function to get lastest message from Discord

 

I wanted to share a function I have developed to get the latest message from a Discord channel. It requires only the channel ID and the Discord Bot Token, and returns a string with the latest message in the chat. It can be combined with another function to send messages from an EA to Discord.

I wonder if among those of you that work on network connectivity can there be suggestions on how to improve it?. Currently, the problem I see is that it makes frequent requests to Discord by using "GET" in the WebRequest MQL5 function. It will be nice to have such functionality (Getting the latest message) via websocket, such that the connectivity with Discord is established only when a new message arrives; this will prevent wasting resources making calls to Discord during times when no new messages exist.


string LastMessageFromDiscord(string Channel_ID, string BotToken)
{
   string last_message;   //holder for text from last message
   string url, headers;   //holders for data to send to discrod to get rsponse
   char data[];           // Data we will send (body) array of type char
   char result[];         // Data received as an array of type char
   string result_headers; // String with response headers
   
   
   headers = "Authorization: Bot " + BotToken ;                              // Request header
   url="https://discord.com/api/v9/channels/" + Channel_ID + "/messages";    // URL 
   
   //--- Calling the function and getting the status_code
   int status_code = WebRequest("GET", url, headers, 5000, data, result, result_headers);
   
   //--- Response to string
   string Res= CharArrayToString(result);
   
   //-- get lattest messages
   int pos=StringFind(Res,"\"content\":\"");
      if(pos!=-1)
        {
         pos+=StringLen("\"content\":\"");
         int end_pos=StringFind(Res,"\"",pos);
         last_message=StringSubstr(Res,pos,end_pos-pos);
         return(last_message);
        } else {return("No message");}
            
  }
Websockets for MetaTrader 5
Websockets for MetaTrader 5
  • www.mql5.com
Before the introduction of the network functionality provided with the updated MQL5 API, MetaTrader programs have been limited in their ability to connect and interface with websocket based services. But of course this has all changed, in this article we will explore the implementation of a websocket library in pure MQL5. A brief description of the websocket protocol will be given along with a step by step guide on how to use the resulting library.
 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
For the Code provided by Camilo Maro to work. You need to create a Bot on Discord and check the Bot as an Administrator or check Sending or Receiving Messages