Discusión sobre el artículo "Cómo crear un bot para Telegram en el lenguaje MQL5" - página 52

 
Lorentzos Roussos #:

No había código cuando respondí , veo que se puede reemplazar el bot.SendMessage con una función que añade el mensaje a una lista de ráfaga . También podrías seguir creciendo el mensaje y enviarlo fuera del bucle pero ahí chocarías con limitaciones de caracteres.

Un breve esquema podría ser así :

  1. Tienes un array de cadenas llamado "Bandeja de salida".
  2. Un intervalo de tiempo dentro del cual procesas el Outbox, así que "OnTimer()" (puede que ya lo estés usando si también estás leyendo de telegram)
  3. Entonces impones -tú mismo- un límite de milisegundos entre cada mensaje, no con la función Sleep() sino recordando cuándo se envió el último mensaje.
  4. Puedes usar GetTickCount() para sondear los milisegundos y almacenar los últimos ms que dejó el mensaje y restarlo de los ms actuales para obtener la distancia en tiempo.Hay una muy muy muy rara ocasión aquí que el tiempo final es < que el tiempo de inicio en cuyo caso haces esto : (UINT_MAX-start_time+end_time)
  5. Si la distancia en milisegundos desde el último mensaje es mayor que el límite en milisegundos que has impuesto, entonces envías el siguiente mensaje desde la bandeja de salida.
  6. En lugar de llamar a bot.SendMessage en el bucle ahora llamas a Outbox.add_message_for_sending o algo así.
  7. Con una modificación que también almacene los ids de chat también podrías almacenar a dónde va el mensaje y esa sería la solución para múltiples usuarios.

Gracias por contestar, lo intentaré a tu manera.

 
Hola compañero. Gran artículo. Funciona bien para canales y grupos y tengo que hacer el bot un admin. Pero si quiero enviarlo a un chat personal de Telegram, ¿cómo puedo añadir el bot a un chat personal? ¿Es posible o debo enviar los mensajes a un canal?
¿Qué te parece?
 
lbgraf #:
¡Hola!
Muchas gracias por este tipo de trabajo!!!!
¿Podría decirme cómo cambiar la fuente, el fondo y el color del texto?
Gracias

Por ejemplo, para la fuente en negrita necesitas habilitar el envío HTML en Telegram.mqh.

const bool    _as_HTML=true

Y luego enviar el texto en la etiqueta <b>.

 
Herman Makmur #:

No importa....

Encontré la respuesta poniendo la bandera AsHTML a true...

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

Lo siento...


Hola, ¿puedes compartir el código de cómo hacer eso? También estoy buscando el código para hacer que el texto en negrita y en cursiva estilo y enviar al servidor de telegramas.

 
Hola Andriy Voitenko, Hemodificado ligeramente el código de la función SendScreenShot() como bot.SendPhoto(_chat_id,filename,screen_id,_symbol+"_"+StringSubstr(EnumToString(_period),7)) no coincide con los parámetros de entrada de ninguno de los modelos de la función SendPhoto() en el <Telegram .mqh>, al enviar un archivo .gif obtengo el error 400 de que algo no funciona exactamente en una de las funciones SendPhoto() (utilizo el segundo modelo de función de los tres presentados en el archivo <Telegram.mqh> línea 655) ¿podría actualizar el código para que funcione?
.
Andriy Voitenko #:

Roman, si necesitas el bot solo para enviar capturas de pantalla, puedes hacerlo de esta manera:

1. Pide al @MyTelegramID_bot tu número de chat.

2. Escribe un bot sencillo que compruebe si hay novedades y envíe imágenes al chat con el ID especificado. Un ejemplo es:

#include <Telegram.mqh>
//+------------------------------------------------------------------+
//| Parámetros de entrada|
//+------------------------------------------------------------------+
input ENUM_LANGUAGES    InpLanguage=LANGUAGE_EN;//Idioma
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);

//--- actualizar gráfico
   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);

      //--- espera 30 segundos para guardar la captura de pantalla
      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);
  }

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

Hola a todos,

Estoy intentando enviar un mensaje desde MT5 a Telegram utilizando un bot. Sin embargo, no he podido enviar el mensaje desde MT5 a Telegram debido al error: Código de error 400 Descripción "Bad request: chat not found"

¿Alguien se ha encontrado con el mismo problema? ¿Puede dar algunas razones por las que este error puede haber ocurrido?

Hice un montón de investigación en línea, pero no pude obtener las respuestas correctas.

Foro sobre trading, sistemas automatizados de trading y prueba de estrategias de trading

Error de MT5 a Telegram: Código de error 400 Descripción "Mala petición: chat no encontrado"

Cerilo Cabacoy, 2023.11.21 18:14

Señor, gracias por su respuesta. Abajo está el código fuente completo. Se trata de un simple expert advisor que extrae datos de un archivo de texto y luego intenta enviar los datos a un canal de Telegram. Sin embargo, se encontró con el error mencionado.

#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.
[Eliminado]  

Foro sobre trading, sistemas automatizados de trading y prueba de estrategias de trading

Añadir emoji en los mensajes de telegram.

Frédéric LEBRE, 2023.12.04 13:56

Hola,

Por favor, ¿podría ayudarme.

Intento enviar un mensaje a telegram utilizando emoji.

cuando el unicode del emoji es por ejemplo : U+2702 uso como valor de cadena " \x2702 " y si funciona.

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

Pero cuando unicode es así : U+1F648 nada funciona.

Incluí <Telegram.mqh> como leí en los temas, pero no sé cómo hacer más.

Gracias por sus respuestas.

 
Gracias por esta biblioteca tan chula. Sin embargo, hay una pregunta. No he encontrado un método para enviar un mensaje al usuario. Estoy intentando que cuando el Asesor Experto encuentre una señal, me lo notifique directamente. No quiero hacer un grupo
 
Roboboy18 enviar un mensaje al usuario. Estoy tratando de hacerlo de modo que cuando el Asesor Experto encontró una señal, me notificó directamente. No quiero hacer un grupo

He encontrado cómo hacerlo, si alguien está interesado, por favor pregúnteme).

 
Roboboy18 #:

Encontrado cómo hacerlo, cualquier persona interesada preguntar )

Podrías escribirlo. Para que otros no tengan que buscarte y preguntar.