Automate Forwarding Messages in Telegram Using a Bot

To ensure that the quoted message is forwarded correctly without duplicating it in the destination channel, follow these steps:

Steps:

  1. Forward the original message first:

    • When a new message arrives, check if it quotes another message.

    • If it does, ensure the quoted message is forwarded first.

    • Track the message IDs in both source and destination channels to maintain the context.

  2. Maintain a mapping of message IDs:

    • Use a dictionary to store the mapping between the source message ID and the corresponding message ID in the destination channels.

    • This mapping will be used to reference the correct message when forwarding the quoted message.

  3. Check for existing messages:

    • Before forwarding a new message, check if the quoted message already exists in the destination channels.

    • If it exists, use the existing message ID to create the quote reference.

  4. Forward or Quote Messages:

    • If the quoted message does not exist in the destination channel, forward it first.

    • Use the mapped message ID to set thereply_to argument when forwarding the message with the quote.

import requests;
import time

# Replace with your bot token

BOT_TOKEN = '12345'
API_URL = f'https://api.telegram.org/bot%7BBOT_TOKEN%7D'

# Replace with the chat ID of the source and destination channels

SOURCE_CHANNEL_ID = -12345  # Use negative ID for channels
DESTINATION_CHANNEL_IDS = [-12345, -12345]  # Use negative ID for channels

auto_forward = False
forwarded_messages = {}

def get_updates(offset=None):
"""Get updates from the Telegram API."""
url = f'{API_URL}/getUpdates'
params = {'timeout': 100, 'offset': offset}
response = requests.get(url, params=params)
result_json = response.json()['result']
return result_json

def send_message(chat_id, text):
"""Send a text message to a channel."""
url = f'{API_URL}/sendMessage'
data = {'chat_id': chat_id, 'text': text}
response = requests.post(url, data=data)
return response.json()

def forward_message(chat_id, from_chat_id, message_id, reply_to_message_id=None):
"""Forward a message to a channel with optional reply context."""
url = f'{API_URL}/copyMessage'
data = {
'chat_id': chat_id,
'from_chat_id': from_chat_id,
'message_id': message_id
}
if reply_to_message_id:
data['reply_to_message_id'] = reply_to_message_id

    response = requests.post(url, data=data)
    return response.json()

def main():
"""Main function to run the bot."""
global auto_forward
update_id = None

    while True:
        updates = get_updates(offset=update_id)
    
        for update in updates:
            if 'update_id' in update:
                update_id = update['update_id'] + 1
    
            if 'message' in update:
                message = update['message']
                chat_id = message['chat']['id']
                text = message.get('text', '')
    
                if text == '/start' and not auto_forward:
                    auto_forward = True
                    send_message(chat_id, "Auto-forwarding started.")
                elif text == '/stop' and auto_forward:
                    auto_forward = False
                    send_message(chat_id, "Auto-forwarding stopped.")
    
            if auto_forward and 'channel_post' in update and update['channel_post']['chat']['id'] == SOURCE_CHANNEL_ID:
                channel_post = update['channel_post']
                message_id = channel_post['message_id']
                reply_to_message = channel_post.get('reply_to_message', None)
    
                if message_id in forwarded_messages:
                    continue
    
                quoted_message_id = None
                forwarded_quoted_message_ids = {}
    
                if reply_to_message:
                    quoted_message_id = reply_to_message.get('message_id')
                    quoted_message_text = reply_to_message.get('text')
                    print(f"Quoted Message ID: {quoted_message_id}", quoted_message_text)
    
                for dest_channel_id in DESTINATION_CHANNEL_IDS:
                    if reply_to_message:
                        # Forward the quoted message first if it exists and hasn't been forwarded yet
                        if quoted_message_id and dest_channel_id not in forwarded_quoted_message_ids:
                            result_quoted = forward_message(
                                chat_id=dest_channel_id,
                                from_chat_id=SOURCE_CHANNEL_ID,
                                message_id=quoted_message_id
                            )
                            if result_quoted['ok']:
                                forwarded_quoted_message_ids[dest_channel_id] = result_quoted['result']['message_id']
                                print(f"Successfully forwarded quoted message to {dest_channel_id}.")
                            else:
                                print(f"Failed to forward quoted message to {dest_channel_id}. Error: {result_quoted.get('description')}")
    
                    # Forward the main message quoting the already forwarded quoted message
                    if dest_channel_id in forwarded_quoted_message_ids:
                        result_main = forward_message(
                            chat_id=dest_channel_id,
                            from_chat_id=SOURCE_CHANNEL_ID,
                            message_id=message_id,
                            reply_to_message_id=forwarded_quoted_message_ids[dest_channel_id]
                        )
                    else:
                        result_main = forward_message(
                            chat_id=dest_channel_id,
                            from_chat_id=SOURCE_CHANNEL_ID,
                            message_id=message_id
                        )
    
                    if result_main['ok']:
                        print(f"Successfully forwarded main message to {dest_channel_id}.")
                    else:
                        print(f"Failed to forward main message to {dest_channel_id}. Error: {result_main.get('description')}")
    
                forwarded_messages[message_id] = True
    
        time.sleep(1)

if __name__ == '__main__':
main()

New contributor

Ashvini Kuhikar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật