Skip to content

Telegram Bot: Forwarding Messages from Private Group

Is there any way using Python / JS to forward messages which I, as a member, do receive in a private read-only group? I’m trying to set it up using python-telegram-bot but it seems I gotta add the bot to the group to have it interact with the contents sent in the group. But I can’t as Im just a reading / receiving member…

Is there maybe a way without using the Telegram API, but using some sort of JS Browser automation to forward those? This is the only thing which comes to my mind… Thanks in advance!

Answer

Answering my own question in case someone needs it.

As @CallMeStag pointed out, one needs a library which support “User bots”. These are librarys directly implementing the MTProto.

For python, e.g. Pyrogram is suitable and very easy to use.

First of all, one needs an API key and API hash to identify the Python Script on the Telegram server to communicate in the MTProto.

https://my.telegram.org/auth?to=apps -> Login using your credentials and create an “App”. Define those into API_ID and API_HASH below.

Now, I use this code to copy messages from the SOURCE_CHAT to the TARGET_chat:

#!/usr/bin/env python3
from pyrogram import Client
from pyrogram import filters

# ~~~~~~ CONFIG ~~~~~~~~ #
ACCOUNT = "@xy"
PHONE_NR = '+49....'

# https://my.telegram.org/auth?to=apps
API_ID = 1111111 
API_HASH = "your_hash"

# CHAT ID
SOURCE_CHAT = -11111 
TARGET_CHAT = -22222
# ~~~~~~~~~~~~~~~~~~~~~~ #

app = Client(
    ACCOUNT,
    phone_number=PHONE_NR,
    api_id=API_ID,
    api_hash=API_HASH
)

# filters.chat(SOURCE_CHAT)
@app.on_message(filters.chat(SOURCE_CHAT))
def my_handler(client, message):
    message.copy(  # copy() so there's no "forwarded from" header
        chat_id=TARGET_CHAT,  # the channel you want to post to
        caption="Copied from XYZ"  # Caption
    )

app.run()

To find out the CHAT_ID of Source and Target, I temporarly disabled the Filter, and printed the message.

@app.on_message()
def my_handler(client, message):
    print(message)

Doing so, enables you to: whenever receiving a message in the specific group, you can find message.chat.id (attention: negative Values!). Configure those for SOURCE_CHAT and TARGET_CHAT in the full script above.

EDIT: Another option to get all chat IDs for all dialogues without first needing someone to send a message in the channel/group/private/chat:

def getAllChatIDs():
    for x in app.get_dialogs():
        print (x.chat.type, x.chat.title, x.chat.id)

Simply call it once and you’ll get a list of dialogues 🙂