Visitar URL original
Most likely the client time has to be synchronized · Issue #62 · hydrogram/hydrogram · GitHub
Skip to content

Most likely the client time has to be synchronized #62

Open

Description

@matheuszbb

Checklist

  • I am sure the error is coming from Hydrogram's code and not elsewhere
  • I have searched in the issue tracker for similar bug reports, including closed ones
  • I ran pip3 install -U https://github.com/hydrogram/hydrogram/archive/dev.zip and reproduced the issue using the latest development version

Description

The Hydrogram bot does not connect to Telegram in any way and does not report any error.Unless you enable logging in debug mode, it's possible to find the error. Otherwise, Hydrogram does not report the error, and the bot is not started.

Solution:
sudo date -s "$(curl -s --head http://google.com | grep ^Date: | sed 's/Date: //g')"

Steps to reproduce

To reproduce the error, simply have your server's time out of sync with Telegram. When trying to connect using Hydrogram, no error is reported, leaving the user unable to understand why it doesn't connect.

Code example

import os
import logging
from hydrogram import Client, filters

# Configurar logs detalhados
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[
        logging.StreamHandler(),  # Exibe logs no console
        logging.FileHandler("debug.log", encoding="utf-8")  # Salva logs em arquivo
    ]
)


# Configurando as variáveis de ambiente diretamente (substitua pelos seus valores reais)
API_ID = os.getenv("API_ID", 123456)  # Substitua pelo seu API_ID
API_HASH = os.getenv("API_HASH", "abc123def456")  # Substitua pelo seu API_HASH
BOT_TOKEN = os.getenv("BOT_TOKEN", "seu_bot_token_aqui")  # Substitua pelo seu BOT_TOKEN

logging.debug("Configurando o cliente...")
try:
    app = Client(
        name="my_bot",
        api_id=API_ID,
        api_hash=API_HASH,
        bot_token=BOT_TOKEN,
    )
    logging.info("Cliente configurado com sucesso.")
except Exception as e:
    logging.critical(f"Erro ao configurar o cliente: {e}")
    raise

# Função simples para responder mensagens privadas
@app.on_message(filters.private)
async def hello(client, message):
    logging.debug(f"Recebeu uma mensagem: {message.text}")
    await message.reply("Hello from Hydrogram!")

# Executar o cliente
logging.debug("Iniciando o cliente...")
try:
    app.run()
except Exception as e:
    logging.critical(f"Erro crítico ao executar o cliente: {e}")

Logs

2025-04-05 11:22:34,653 - hydrogram.session.session - INFO - Discarding packet: The msg_id belongs to over 30 seconds in the future. Most likely the client time has to be synchronized.

2025-04-05 11:22:34,653 - hydrogram.session.session - INFO - NetworkTask stopped

2025-04-05 11:22:34,653 - hydrogram.connection.connection - INFO - Disconnected

Activity

  1. HitaloM commented on Apr 18, 2025

    @HitaloM
    Member

    The problem is very simple: the clock of your server is not synchronized with the Telegram servers. If the difference is more than 30 seconds, Hydrogram can't connect. This is a Telegram security feature; your server's clock must be reasonably synchronized with theirs.

  2. AndrielFR commented on Apr 18, 2025

    @AndrielFR

    and does not report any error.Unless you enable logging in debug mode

    the logging level of this "error" is the info level, the lowest, anyone who uses any library in any programming language, during the development phase, has to activate the logs, to understand what is happening.

    from what you are saying, you want this information not to be logged, but rather printed, which is bad practice.

    the responsibility does not lie with those who develop the library, as they have already done their part, they have logged what the problem is, the responsibility lies with those who use it and do not even do the minimum, which is to activate the logs.

  3. matheuszbb commented on Apr 18, 2025

    @matheuszbb
    Author

    e não relata nenhum erro. A menos que você habilite o registro no modo de depuração

    o nível de registro desse "erro" é o infonível mais baixo, qualquer pessoa que use qualquer biblioteca em qualquer linguagem de programação, durante a fase de desenvolvimento, tem que ativar os registros para entender o que está acontecendo.

    pelo que você está dizendo, você quer que essas informações não sejam registradas, mas sim impressas, o que é uma prática ruim.

    a responsabilidade não é de quem desenvolve a biblioteca, pois eles já fizeram a sua parte, já registraram qual é o problema, a responsabilidade é de quem utiliza e não faz nem o mínimo, que é ativar os logs.

    I understand your point of view; however, let's assume someone is running the hydrogram for the very first time, and this problem occurred. They are not like us, who will stop and debug; the person simply wouldn't use this amazing project.

    I use critical logs, so in my case, the bot simply stopped without prior warning. Do you believe that a novice would take the trouble to do this? The answer is simple: they don't even have knowledge of logs. Therefore, when this failure happens and the error remains silent—only appearing if debug logging is activated, as was my case—it becomes a silent error.

    So yes, I believe it is a good idea to inform the developers that this happens, and it must have happened to others who kept quiet about it, which is not my case. I like the project, and as such, I came to make my contribution so that it gets even better.

  4. matheuszbb commented on Apr 19, 2025

    @matheuszbb
    Author

    The problem is very simple: the clock of your server is not synchronized with the Telegram servers. If the difference is more than 30 seconds, Hydrogram can't connect. This is a Telegram security feature; your server's clock must be reasonably synchronized with theirs.

    I noticed this in practice, but I'm trying to report that this becomes a silent error. The purpose of my report is precisely this: not all people who use the library are aware of logs to verify this. In other words, when the error occurs, the bot becomes unusable, and the developer doesn't know why, as the error remains silent until debug logging is used. At that moment, many users of this incredible library stop using it without knowing the reason.

    My report aims to help improve the library, as I am trying to do. Those of us who have knowledge strive to improve it. My contribution is this: to alert, as I understand that many other people experience similar issues but never report them. The problem happens to others, and the project doesn't gain more adopters because the developer ends up abandoning it, as it didn't work right away.

  5. AndrielFR commented on Apr 19, 2025

    @AndrielFR

    I understand your point of view; however, let's assume someone is running the hydrogram for the very first time, and this problem occurred. They are not like us, who will stop and debug; the person simply wouldn't use this amazing project.

    ok, so I propose that the devs emphasize the use and activation of logs in the bot development phase, both in the readme and in the documentation, this should avoid problems like this.

  6. matheuszbb commented on Apr 19, 2025

    @matheuszbb
    Author

    I understand your point of view; however, let's assume someone is running the hydrogram for the very first time, and this problem occurred. They are not like us, who will stop and debug; the person simply wouldn't use this amazing project.

    ok, so I propose that the devs emphasize the use and activation of logs in the bot development phase, both in the readme and in the documentation, this should avoid problems like this.

    Dear fellow developer, I believe you have not dealt with amateur users, and therefore you may not know that such people, when encountering a new library that doesn't work, simply abandon it and move on to others. We are among the few who take the trouble to investigate errors. I only want to improve the project.

    As I mentioned before, I use logs at a critical level, so this problem remained silent in my log. I hope you now understand my point of view when I ask developers to inform users more explicitly. As I have already said, this problem occurs, and you are unaware of it. Imagine yourself in the shoes of a developer who installed the library and tried to use it immediately, without receiving any error message. The bot simply didn't respond.

  7. AndrielFR commented on Apr 19, 2025

    @AndrielFR

    The bot simply didn't respond.

    I understand you, really, so to what I said previously, I add that this specific error should have the level raised to warning, which does not require the activation of logs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions