Telegram bot that takes photos and publishes them

To work and automate the telegrams of the channel, I needed a bot that would take photos and post them in the channel, and as an addition, add the text I needed (if necessary, you can rewrite it so that it attaches messages sent to it). There are many goals, maybe you are an anonymous person who hides your traces, or maybe you want to provide access to posting photos in your channel to your subscribers.

Importing required modules

Let's get started, to write a bot we need python, a library module python-telegram-bot – telegram, and module time.

import time
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext

Let's briefly go through importing classes and functions.

  • Application – the main class for interacting with the Telegram API. It handles user actions when working with the bot.

  • Handler – functions that respond to messages and events when working with the bot.

  • CommandHandler – processes commands such as /start.

  • MessageHandler – processes messages of certain types, in our case an image.

  • filters – a module that is used to create conditions for incoming messages.

  • CallbackContex – an object that is passed to handler functions. Contains information about the context of the handler call.

Constants and global variables

# Ваш токен бота
BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
CHANNEL_ID = '@your_channel' # Ссылка на ваш канал
DEFAULT_CAPTION = "Это текст, который будет добавляться к каждому посту в канал."
  • BOT_TOKEN – your bot's token. We get it when creating a bot in BotFather.

  • CHANNEL_ID – a link to your channel, if it is public it is written with @, but if your channel is private, then from the channel link you need to take the value that starts with -, for example #-00000000, then you need to take -00000000, and add 100. CHANNEL_ID = '-10000000000'.

  • DEFAULT_CAPTION is a predefined text that will be added to each image sent to the channel. You can change this text to any other at your discretion.

Also optional, but I will add a check for the time of the last submission by the user.

# Словарь для хранения времени последней отправки фото пользователем
user_last_photo_time = {}
# Ограничение по времени (12 часов в секундах)
TIME_LIMIT = 12 * 60 * 60  # 12 часов = 43200 секунд
  • user_last_photo_time – a dictionary that stores the last time the user sent an image to the bot.

  • TIME_LIMIT – restriction of sending messages by the user, I set it to 12 hours, but you can set it to any time

Time limit check function

def can_send_photo(user_id):
    current_time = time.time()
    last_time = user_last_photo_time.get(user_id, 0)
    if current_time - last_time >= TIME_LIMIT:
        return True
    return False
  • can_send_photo(user_id): This function checks if enough time (12 hours) has passed since the user last sent a photo.

  • time.time() – returns the current time in seconds.

  • user_last_photo_time.get(user_id, 0) – Gets the last timestamp when the user sent the photo. If there is no data (the user is sending a photo for the first time), returns the value 0.

  • current_time – last_time >= TIME_LIMIT: Checks if 12 hours have passed since the last photo was sent.

    If the condition is true, returns True, otherwise – False.

Image processing

async def handle_image(update: Update, context: CallbackContext):
    user_id = update.message.from_user.id
  • handle_image – this function processes images sent by users.

  • update.message.from_user.id – retrieves the user_id of the user who submitted the image.

    if can_send_photo(user_id):
        photo = update.message.photo[-1]
        caption = DEFAULT_CAPTION
  • can_send_photo(user_id) – checks whether the user can send a photo (taking into account the time limit).

  • photo = update.message.photo[-1] – if several photos were sent from one person, send only the first one to the channel.

  • caption = DEFAULT_CAPTION – takes a predefined text that will be sent along with the image.

        await context.bot.send_photo(
            chat_id=CHANNEL_ID,
            photo=photo.file_id,
            caption=caption
        )
  • context.bot.send.photo – sends the photo to the specified channel.

  • chat_id=CHANNEL_ID – channel identifier where the image will be sent.

  • photo=photo.file_id – image file that will be sent.

  • caption=caption – text that will be attached to the image.

        user_last_photo_time[user_id] = time.time()
        await update.message.reply_text("Изображение с текстом отправлено в канал!")
  • user_last_photo_time[user_id] = time.time() – updates the timestamp of the user sending the image.

  • await update.message.reply_text(“”) – response to the user that his message has been accepted.

    else:
        remaining_time = TIME_LIMIT - (time.time() - user_last_photo_time[user_id])
        hours, remainder = divmod(remaining_time, 3600)
        minutes, _ = divmod(remainder, 60)
        await update.message.reply_text(f"Вы сможете отправить фото через {int(hours)} часов и {int(minutes)} минут.")

If the user tries to send a photo before 12 hours have passed, the bot calculates how much time is left until the next opportunity to send the image and notifies about it.

Processing the /start command

async def start(update: Update, context: CallbackContext):
    await update.message.reply_text("Отправьте мне изображение, и я размещу его в канале вместе с текстом, но не чаще, чем раз в 12 часов.")

start – this is the /start command handler. When the user enters this command, the bot sends them a message with instructions on how to send the image.

The main function is to launch the bot

def main():
    application = Application.builder().token(BOT_TOKEN).build()

    application.add_handler(CommandHandler("start", start))
    application.add_handler(MessageHandler(filters.PHOTO, handle_image))

    application.run_polling()

main() – the main function that launches the bot.

  • Application.builder().token(BOT_TOKEN).build() – creates a bot instance with your token.

  • application.add_handler(CommandHandler(“start”, start)) – adds a command handler for /start.

  • application.add_handler(MessageHandler(filters.PHOTO, handle_image)) – adds an image processor.

  • application.run_polling() – starts the bot in the mode of constantly polling the Telegram server to receive updates.

Ready-made Telegram bot code

import time
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext

# Ваш токен бота
BOT_TOKEN = 'BOT_TOKEN'
CHANNEL_ID = '-100999999'  # Приватный канал

# Словарь для хранения времени последней отправки фото пользователем
user_last_photo_time = {}

# Ограничение по времени (12 часов в секундах)
TIME_LIMIT = 12 * 60 * 60  # 12 часов = 43200 секунд

# Текст, который будет добавляться к посту
DEFAULT_CAPTION = "Добавьте свой текст"

# Функция для проверки ограничения
def can_send_photo(user_id):
    current_time = time.time()
    last_time = user_last_photo_time.get(user_id, 0)
    if current_time - last_time >= TIME_LIMIT:
        return True
    return False

# Функция для обработки изображений
async def handle_image(update: Update, context: CallbackContext):
    user_id = update.message.from_user.id


    # Проверка на временное ограничение (12 часов)
    if can_send_photo(user_id):
        # Разрешаем отправку фото
        photo = update.message.photo[-1]

        # Используем заранее заданный текст как подпись
        caption = DEFAULT_CAPTION

        # Отправляем фото в канал с подписью
        await context.bot.send_photo(
            chat_id=CHANNEL_ID,
            photo=photo.file_id,
            caption=caption
        )

        # Обновляем время последней отправки фото
        user_last_photo_time[user_id] = time.time()

        # Подтверждение пользователю
        await update.message.reply_text("Изображение отправлено в канал!")
    else:
        # Если не прошло 12 часов, отклоняем запрос
        remaining_time = TIME_LIMIT - (time.time() - user_last_photo_time[user_id])
        hours, remainder = divmod(remaining_time, 3600)
        minutes, _ = divmod(remainder, 60)
        await update.message.reply_text(f"Вы сможете отправить фото через {int(hours)} часов и {int(minutes)} минут.")

# Функция для старта
async def start(update: Update, context: CallbackContext):
    await update.message.reply_text("Отправьте мне изображение, и я размещу его в канале, но не чаще, чем раз в 12 часов.")

def main():
    # Создаем экземпляр Application и передаем ему токен бота
    application = Application.builder().token(BOT_TOKEN).build()

    # Обработчик команды /start
    application.add_handler(CommandHandler("start", start))

    # Обработчик изображений
    application.add_handler(MessageHandler(filters.PHOTO, handle_image))

    # Запускаем бота
    application.run_polling()

if __name__ == '__main__':
    main()

To summarize, I wrote this post for several days, and the bot for several hours, and I hope that I described in detail the entire creation process for readers. If you have any questions, please comment on the post.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *