Search code examples
telegramtelegram-botpython-telegram-bot

How to forward image to another chat with telegram bot python api?


User sends image to telegram bot. Is it possible to forward image or send it to another chat without saving?

my code

def reg_text(message):
global text
text = message.text
if len(text.split()) < 2:
    bot.send_message(message.from_user.id, "Too short message.")
    bot.register_next_step_handler(message, reg_text)

else:
    bot.send_message(message.from_user.id, "Perfect! Send an image")
    bot.register_next_step_handler(message, reg_photo)

def reg_photo(message): #get image id and send it to another chat (which is constant)


Solution

  • I have a working bot and among many features, one is exactly what you want to achieve. This def works identifying if a image or a document was sent by the user. If it's a document (if part of the loop), the bot send the document to a channel on Telegram; if it's a image (else part of the loop), the bot send the image to the same channel.

    def file_handler (update, context):
    
        if update.message['photo'] == []:
            fileID = update.message['document']['file_id']
            fileName = update.message['document']['file_name']
            context.bot.sendDocument(chat_id = channel_chat_id,
                                     caption = 'image caption',
                                     document = fileID)
    
        else:
            fileID = update.message['photo'][-1]['file_id']
            context.bot.sendPhoto(chat_id = channel_chat_id,
                                  caption = 'image caption',
                                  photo = fileID)
    

    Remembering that on def main() you must have a MessageHandler to handle def file_handler.

    dp = updater.dispatcher
    dp.add_handler(MessageHandler(Filters.document | Filters.photo, file_handler))
    

    Let me know if this works for you!