Discussion of article "How to create bots for Telegram in MQL5" - page 52

 
Lorentzos Roussos #:

There was no code when i replied , i see that you can replace the bot.SendMessage with a function that adds the message to a burst list . You could also keep growing the message and send it out of the loop but you would hit character limitations there.

A brief schematic could be like this : 

  1. You have a string array called "Outbox"
  2. A time interval within which you process the Outbox , so "OnTimer()" (you may already be using it if you are reading from telegram too)
  3. You then enforce -yourself- a milliseconds limit between each message not with the Sleep() function but by remembering when the last message was sent
  4. You can use GetTickCount() for polling milliseconds and you would store the last ms that the message left and subtract it from the current ms to get the distance in time.There is a very very very rare occasion here that the end time is < than the start time in which case you do this : (UINT_MAX-start_time+end_time)
  5. If your distance in milliseconds since the last message is bigger than the limit in milliseconds you enforce then you send the next message from the Outbox
  6. Instead of calling bot.SendMessage in the loop you now call Outbox.add_message_for_sending or something.
  7. With a modification that also stores the chat ids you could also store where the message is going and that would be the solution for multiple users.

Thank you for replying. I will try your way

 
Hello mate. Great article. It works well for channels and groups and I have to make the bot an admin. But what if I want to send it to a personal telegram chat, how can I add the bot to a personal chat? Is that possible or must I send the messages to a channel? 
What do you think?
 
lbgraf #:
Hello!
Thank you so much for this kind of work!!!!
Could you please tell me how to change font, background, text colour?
Thanks

For example for bold font you need to enable HTML sending in Telegram.mqh.

const bool    _as_HTML=true

And then send text in <b> tag.

 
Herman Makmur #:

Never mind....

I found the answer by setting AsHTML flag to true...

bot.SendMessage(InpTelegramId,"<b>Balance: $10056.21</b>",true);

Sorry...


Hi, can u share the code on how to do that ? I am also searching for the code to make the Text Bolded and in Italic style and send to telegram server.

 
Hello Andriy Voitenko, I haveslightly modified the code of SendScreenShot() function as bot.SendPhoto(_chat_id,filename,screen_id,_symbol+"_"+StringSubstr(EnumToString(_period),7)) does not match the input parameters of any of the SendPhoto() function models in the <Telegram .mqh>, when sending a .gif file I get error 400 that something does not work exactly in one of SendPhoto() functions (I use the second function model out of three presented in <Telegram.mqh> file 655 line) could you please update the code to make it work?
.
Andriy Voitenko #:

Roman, if you need the bot only for sending screenshots, you can do it this way:

1. Ask the @MyTelegramID_bot for your chat number.

2. Write a simple bot that will check for new items and send pictures to the chat with the specified ID. An example is:

#include <Telegram.mqh>
//+------------------------------------------------------------------+
//| Input parameters|
//+------------------------------------------------------------------+
input ENUM_LANGUAGES    InpLanguage=LANGUAGE_EN;//Language
input string            InpToken="";//Token
input long              ChatId=0;   //Chat ID
//---
CCustomBot bot;
int pos_count;
//+------------------------------------------------------------------+
int OnInit()
  {
   bot.Token(InpToken);
   int res=bot.GetMe();
   if(res!=0)
     {
      Print(GetErrorDescription(res));
     }
   pos_count=PositionCount(_Symbol);
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
void OnTick()
  {
   int pos_count_new=PositionCount(_Symbol);
   if(pos_count_new>pos_count)
     {
      pos_count=pos_count_new;
      int result=SendScreenShot(ChatId,_Symbol,0,NULL);
      if(result!=0)
         Print(GetErrorDescription(result,InpLanguage));
     }
  }
//+------------------------------------------------------------------+
int PositionCount(const string _symbol)
  {
   int count=0;
   int orders_total=OrdersTotal();
   for(int i=0; i<orders_total; i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         PrintError(ERR_ORDER_SELECT);
         return(-1);
        }
      //---
      if(_symbol==NULL || OrderSymbol()==_symbol)
         count++;
     }
//---
   return(count);
  }
//+------------------------------------------------------------------+
int SendScreenShot(const long _chat_id,
                   const string _symbol,
                   const ENUM_TIMEFRAMES _period,
                   const string _template=NULL)
  {
   int result=0;

   long chart_id=ChartOpen(_symbol,_period);
   if(chart_id==0)
      return(ERR_CHART_NOT_FOUND);

   ChartSetInteger(ChartID(),CHART_BRING_TO_TOP,true);

//--- update chart
   int wait=60;
   while(--wait>0)
     {
      if(SeriesInfoInteger(_symbol,_period,SERIES_SYNCHRONIZED))
         break;
      Sleep(500);
     }

   if(_template!=NULL)
      if(!ChartApplyTemplate(chart_id,_template))
         PrintError(_LastError,InpLanguage);

   ChartRedraw(chart_id);
   Sleep(500);

   ChartSetInteger(chart_id,CHART_SHOW_GRID,false);

   ChartSetInteger(chart_id,CHART_SHOW_PERIOD_SEP,false);

   string filename=StringFormat("%s%d.gif",_symbol,_period);

   if(FileIsExist(filename))
      FileDelete(filename);
   ChartRedraw(chart_id);

   Sleep(100);

// if(ChartScreenShot(chart_id,filename,800,600,ALIGN_RIGHT))
   if(ChartScreenShot(chart_id,filename,1024,768,ALIGN_RIGHT))
     {
      Sleep(100);

      bot.SendChatAction(_chat_id,ACTION_UPLOAD_PHOTO);

      //--- waitng 30 sec to save screenshot
      wait=60;
      while(!FileIsExist(filename) && --wait>0)
         Sleep(500);

      //---
      string screen_id;
      result=bot.SendPhoto(_chat_id,filename,screen_id,_symbol+"_"+StringSubstr(EnumToString(_period),7));
     }

   ChartClose(chart_id);
   return(result);
  }

//+------------------------------------------------------------------+
 

Hi everyone,

I am trying to send a message from MT5 to Telegram using a bot. However, I could not send the message from MT5 to Telegram due to the error: Error Code 400 Description "Bad request: chat not found"

Has anyone encountered the same problem? Can you give some reasons why this error might have occurred?

I did a lot of research online, but I could not get the right answers.

Forum on trading, automated trading systems and testing trading strategies

MT5 to Telegram Error: Error Code 400 Description "Bad request: chat not found"

Cerilo Cabacoy, 2023.11.21 18:14

Sir, thanks for your reply. Below is the full source code. It is just a simple expert advisor that extracts data from a text file and then attempts to send the data to a Telegram channel. However, it encountered the error mentioned.

#property copyright "Copyright 2022, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

#include <Telegram.mqh>
CCustomBot tgbot;

input string TelegramBotToken = "6770842913:AAGcnR666ddL7hCB8HeTNs6HdNe28y3F-ik";
input string TelegramChatID = "-1002063516288";
input string TelegramAPIurl = "https://api.telegram.org";
input string namefile = "WagScores.txt";

datetime h1time = 0;
string channelname = "";
//+------------------------------------------------------------------+
int OnInit() {

   tgbot.Token(TelegramBotToken);
   int res = tgbot.GetMe();      Print("GetMe() results: "+(string)res);
   channelname = tgbot.Name();   Print("bot name: "+channelname);
   
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {

   
}
//+------------------------------------------------------------------+
void OnTick() {

   ChartRedraw();
   if(NewH1Bar()) {
      string data[];
      string output = "";
      GetTxtDataToArray(namefile,data); 
      string message = StringFormat("Time: %s\n",TimeToStr(TimeCurrent()));  
      StringAdd(output,message);   
      for(int i = 0; i < ArraySize(data); i++) {
         string strmsg = StringFormat("%s\n",data[i]);
         StringAdd(output,strmsg);     
      }     
      int res = tgbot.SendMessage(TelegramChatID,output);      Print((string)__LINE__+" "+(string)res);
      SendNotification(output);
   }
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
bool NewH1Bar() { 
     
   datetime newtime = iTime(Symbol(),PERIOD_H1,0);
   if(newtime==h1time) return false;
   h1time = newtime;                                
   return true;
}
//+------------------------------------------------------------------+   
void GetTxtDataToArray(string filename,string &array[]) { 
             
   if(!FileIsExist(filename)) return;
   int handle = FileOpen(filename,FILE_TXT|FILE_READ|FILE_ANSI);
   if(handle==INVALID_HANDLE) { Print(""+__FUNCTION__+" "+(string)__LINE__+" opening file error"); return; }
   FileSeek(handle,0,SEEK_SET);
   while(!FileIsEnding(handle)) {
      string line = FileReadString(handle); 
      ArrayResize(array,ArraySize(array)+1);         
      array[ArraySize(array)-1] = line;
   }
   FileClose(handle);    
}

OOP in MQL5 by Example: Processing Warning and Error Codes
OOP in MQL5 by Example: Processing Warning and Error Codes
  • www.mql5.com
The article describes an example of creating a class for working with the trade server return codes and all the errors that occur during the MQL-program run. Read the article, and you will learn how to work with classes and objects in MQL5. At the same time, this is a convenient tool for handling errors; and you can further change this tool according to your specific needs.
 

Forum on trading, automated trading systems and testing trading strategies

Adding emoji in telegram messages.

Frédéric LEBRE, 2023.12.04 13:56

Hello, 

Please could you help me.

I try to send a message to telegram using emoji.

when emoji unicode is for example : U+2702 i use as string value " \x2702" and if works.

SendTelegramMessage(TelegramApiUrl, TelegramBotToken, ChatId, "\x2702");

But when unicode is like this : U+1F648 nothing works.

I included <Telegram.mqh> as i read in topics, but i do not know how to do more.

Thx for your answers.

 
Thanks for the cool library! However, there is a question. I have not found a method to send a message to the user. I am trying to make it so that when the Expert Advisor found a signal, notified me directly. I don't want to make a group
 
Roboboy18 send a message to the user. I am trying to make it so that when the Expert Advisor found a signal, notified me directly. I do not want to make a group

I found how to do it, if anyone is interested, please ask me).

 
Roboboy18 #:

Found how to do it, anyone interested ask )

You could just write it down. So that others do not need to look for you and ask.