Search code examples
pythontelegram-botaiogram

Send paid media aiogram 3.10


How to send blurred paid media in channel? Here is me code, but I cannot find solution https://docs.aiogram.dev/en/dev-3.x/api/types/input_media_photo.html

import asyncio
import logging
from aiogram import Bot, Dispatcher
from aiogram.filters import CommandStart
from aiogram.types import Message, InputPaidMediaPhoto

 

TOKEN = "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"


PHOTO_URL = 'https://i.imgur.com/i2CvF2q.jpeg' 

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

bot = Bot(token=TOKEN)
dp = Dispatcher()


@dp.message(CommandStart())
async def command_start(message: Message):
    await message.answer_paid_media(star_count=500, media=[InputPaidMediaPhoto(media=PHOTO_URL)])


async def main():
    await dp.start_polling(bot)

if __name__ == '__main__':
    asyncio.run(main())

Solution

  • import aiocron, os, httpx, random, asyncio
    from aiogram import Bot, Dispatcher, types
    from aiogram.utils import executor
    from aiogram.utils.exceptions import TelegramAPIError
    from config import *
    
    bot = Bot(token=API_TOKEN)
    dp = Dispatcher(bot)
     
    
    
    
    async def send_paid_media_command():
        links = []
        if os.path.exists(LINKS_FILE):
            with open(LINKS_FILE, 'r') as file:
                links = file.read().splitlines()
        
        if not links:
            await bot.send_message(my_id, "No more photos to send.")
            return
        
        media = [{"type": "photo", "media": link} for link in links[:10]]
        payload = {
            "chat_id": CHANNEL_nsfw,
            "star_count": STAR_COUNT,
            "media": media
        }
    
        api_url = f'https://api.telegram.org/bot{API_TOKEN}/sendPaidMedia'
    
        try:
            async with httpx.AsyncClient() as client:
                response = await client.post(api_url, json=payload)
                response.raise_for_status()
                result = response.json()
                
                if not result['ok']:
                    raise TelegramAPIError(f"Telegram API error: {result['description']}")
                
                # Если отправка была успешной, удаляем ссылки
                remaining_links = links[10:]
                with open(LINKS_FILE, 'w') as file:
                    file.write('\n'.join(remaining_links))
                
                if not remaining_links:
                    await bot.send_message(my_id, "No more NSFW photos to send.")
            
        except httpx.HTTPStatusError as e:
            await bot.send_message(my_id, f"HTTP error while sending paid media: {e.response.text}")
        except TelegramAPIError as e:
            await bot.send_message(my_id, f"Telegram API error while sending paid media: {e}")
        except Exception as e:
            await bot.send_message(my_id, f"Unexpected error while sending paid media: {e}")
        finally:
            # Если отправка была успешной, но что-то пошло не так в процессе, всё равно удаляем отправленные ссылки
            if 'remaining_links' not in locals():
                remaining_links = links[10:]
                with open(LINKS_FILE, 'w') as file:
                    file.write('\n'.join(remaining_links))