Saturday, July 27, 2024
Ana SayfaCosmic Meta QASoftware DevelopmentTroubleshooting Inconsistent Message Reception in Pyrogram for Telegram Channels

Troubleshooting Inconsistent Message Reception in Pyrogram for Telegram Channels

Question

I’ve joined a certain Telegram channel with two different Telegram accounts. I run the below code to start both sessions using Pyrogram and print the received messages. However, I noticed that when a message is received on the Telegram channel, only one of the sessions prints it while the other doesn’t. When I tested using my own test Telegram channel, both sessions printed the message as expected. I’m at a loss why this problem happens with the other channel. Both accounts are subscribed to the channel, and the message is seen on both phones. What could possibly cause this behavior?

Here’s the code I’m using:

#!/usr/bin/python3

from pyrogram import Client, filters, idle
from pyrogram.handlers import MessageHandler
import config
from pytz import timezone
from datetime import datetime
import requests
import asyncio

CHANNEL_ID = -1000123456789

def india_number_handler(client, message):
    message_handler('india_number', message)

def uk_number_handler(client, message):
    message_handler('uk_number', message) 

def message_handler(session_name, message):
    if message.sender_chat is not None and message.sender_chat.id == CHANNEL_ID and message.text is not None:
        print(datetime.now().strftime('%d-%m-%Y-%H:%M:%S-%f') + ': ' + session_name + ' received channel message: ' + message.text, flush=True)

async def main():
    app_india = Client("india_number", api_id=config.getEnv("api_id"), api_hash=config.getEnv("api_hash"))
    app_uk = Client("uk_number", api_id=config.getEnv("api_id"), api_hash=config.getEnv("api_hash"))
    app_india.add_handler(MessageHandler(india_number_handler))
    app_uk.add_handler(MessageHandler(uk_number_handler))    
    await app_india.start()
    await app_uk.start()
    await idle()
    await app_india.stop()
    await app_uk.stop()

asyncio.run(main())

Answer

To address the issue where only one of your sessions receives and prints messages from a specific Telegram channel, while both accounts receive messages on the mobile app, you need to consider several factors. This can be caused by session misconfiguration, API limitations, or other unexpected behavior in the code or the Telegram API. Here’s a detailed troubleshooting guide to help you identify and resolve the issue.

Detailed Troubleshooting Guide

1. Verify Both Sessions Are Subscribed

Ensure both accounts are subscribed to the channel and have permission to receive messages. This might sound basic, but it’s essential to confirm that both accounts have the necessary permissions.

2. Check API Limits and Restrictions

Telegram imposes various API rate limits. Make sure you are not hitting any rate limits that could affect one of the accounts. Review the Telegram API documentation for details on limits and how to handle them.

3. Add Logging for Debugging

Enhance your code with additional logging to understand the flow better and catch any potential issues. Log when each session starts, when handlers are added, and any exceptions that might occur.

4. Ensure Proper Session Initialization

Make sure both sessions are correctly initialized and running. A misconfiguration in session setup might cause one session to not function correctly.

5. Verify Handler Attachment

Double-check that the handlers are properly attached to each session. Handlers must be set correctly for each client instance to ensure they can handle incoming messages.

6. Examine Channel and Message Properties

Ensure the message properties, such as sender_chat and sender_chat.id, are correctly checked. A mismatch or typo here can prevent messages from being correctly identified and processed.

Updated Code with Enhanced Logging

Here’s an updated version of your script with enhanced logging and error handling to help identify the issue:

#!/usr/bin/python3

from pyrogram import Client, filters, idle
from pyrogram.handlers import MessageHandler
import config
from datetime import datetime
import asyncio

CHANNEL_ID = -1000123456789

def india_number_handler(client, message):
    message_handler('india_number', message)

def uk_number_handler(client, message):
    message_handler('uk_number', message) 

def message_handler(session_name, message):
    if message.sender_chat is not None and message.sender_chat.id == CHANNEL_ID and message.text is not None:
        print(f"{datetime.now().strftime('%d-%m-%Y-%H:%M:%S-%f')}: {session_name} received channel message: {message.text}", flush=True)
    else:
        print(f"{datetime.now().strftime('%d-%m-%Y-%H:%M:%S-%f')}: {session_name} received a non-matching message", flush=True)

async def main():
    app_india = Client("india_number", api_id=config.getEnv("api_id"), api_hash=config.getEnv("api_hash"))
    app_uk = Client("uk_number", api_id=config.getEnv("api_id"), api_hash=config.getEnv("api_hash"))

    app_india.add_handler(MessageHandler(india_number_handler))
    app_uk.add_handler(MessageHandler(uk_number_handler))

    try:
        await app_india.start()
        print("India session started")
    except Exception as e:
        print(f"Failed to start India session: {e}", flush=True)

    try:
        await app_uk.start()
        print("UK session started")
    except Exception as e:
        print(f"Failed to start UK session: {e}", flush=True)

    await idle()

    await app_india.stop()
    print("India session stopped")

    await app_uk.stop()
    print("UK session stopped")

asyncio.run(main())

Additional Considerations

  1. Server-Side Logs: Check the logs on the Telegram server to see if there are any indications of why messages might not be delivered to one of the sessions.
  2. Network Issues: Verify that there are no network issues affecting one of the sessions. A network issue might prevent the message from being received by one of the clients.
  3. Pyrogram Version: Ensure you are using the latest version of Pyrogram, as updates often include bug fixes and improvements.

Conclusion

By enhancing logging and systematically checking each part of your setup, you should be able to identify why one of your sessions isn’t receiving messages. This process ensures that your Telegram bot or client handles messages reliably across multiple sessions.

Useful Links

Cosmic Meta
Cosmic Metahttps://cosmicmeta.io
Cosmic Meta Digital is your ultimate destination for the latest tech news, in-depth reviews, and expert analyses. Our mission is to keep you informed and ahead of the curve in the rapidly evolving world of technology, covering everything from programming best practices to emerging tech trends. Join us as we explore and demystify the digital age.
RELATED ARTICLES

CEVAP VER

Lütfen yorumunuzu giriniz!
Lütfen isminizi buraya giriniz

- Advertisment -

Most Popular

Recent Comments