Skip to content
Advertisement

Telegram API Python – Automatically forward user input message (including formatting) to another chat_id

Good evening.

I hope that you are well.

I have posted an excerpt below of some Telegram bot code which auto forwards any messages it receives to another channel which has the bot added :-

api_key = ""
bot = telebot.TeleBot(api_key)

chat_id = "1234"

@bot.message_handler(func=lambda m: True)
def handle_posts(m: telebot.types.Message):
message_from = m.from_user.id
if message_from == 123456 or message_from == 654321:
    print("You are an authorized user")

    bot.forward_message(chat_id, m.chat.id, m.message_id)
else:
    print("You are not an authorized user")

This code works fine for any text based messages that are sent to the bot (which includes standard formatting such as Bold, Italic, Underline, Emojis, Hyperlinks etc.) however if I attempt to attach an image to a message and then send it, the message is not forwarded on at all.

Does anyone have any idea how I can handle image based messages so that they forward successfully please? Does it need another function that deals with a different telebot.types method perhaps?

Many thanks in advance

Jimmy

Advertisement

Answer

I have a bot that does something like this, but I only need to handle text and photos separately. I hope this code snipped helps!

# imports
from logging import Filter
from telegram import Update
from telegram.ext import *
import telegram
from dotenv import load_dotenv
import os

# get the telegram bot api_key from environment file
load_dotenv()
API_KEY = os.getenv('API_KEY')

# you will need the groub_b_id saved as a global variable or
# in some other document
group_b_id = 1234567890

# create the bot, updater, and dispatcher
bot = telegram.Bot(token=API_KEY)
updater = Updater(API_KEY, use_context=True)
dp = updater.dispatcher


def get_chat_id(update: Update, context: CallbackContext):
    # gets the chat_id of the current chat
    global bot
    chat_id = update.effective_chat.id
    bot.send_message(chat_id, "This chat's id is: " + str(chat_id))

def auto_forward(update: Update, context: CallbackContext):
    # automatically forwards messages from this chat to
    # chat_b
    
    global bot, group_b_id
    chat_id = update.effective_chat.id
    username = update.effective_message.from_user.name
    chat_title = update.effective_message.chat.title
    msg_txt = update.effective_message.text
    
    bot.send_message(
        group_b_id, 
        text=f"'{msg_txt}'nwas just sent in chat {chat_title} by {username}"
    )
    
def auto_forward_image(update: Update, context: CallbackContext):
    # get variables
    global bot, group_b_id
    chat_id = update.effective_chat.id
    username = update.effective_message.from_user.name
    chat_title = update.effective_message.chat.title
    
    # get the third best quality photo
    photos = len(update.message.photo)
    img_index = max(photos-3, 0) # change -3 to -2 to get second best etc
    img = update.message.photo[img_index]
    
    # send message to GroupB the group that you want the stuff forwarded to
    bot.send_message(group_b_id, str(username) + " just sent me an image from the `" + str(chat_title) + "` chat:")
    bot.send_photo(group_b_id, img)
        

# sets up the handlers
dp.add_handler(CommandHandler('get_chat_id', get_chat_id))
dp.add_handler(MessageHandler(Filters.text, auto_forward))
dp.add_handler(MessageHandler(Filters.photo, auto_forward_image))

# Start the Bot
updater.start_polling()
updater.idle()

just make sure that you add the bot to both chats as an admin or this will not work since the bot needs admin priveleges to respond to all messages not just commands.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement