예제 #1
0
파일: hastebin.py 프로젝트: samuelfirst/bot
async def command_paste(message: types.Message):
    messages_to_delete = []
    if message.reply_to_message and message.reply_to_message.from_user.id != bot.id:
        content = message.reply_to_message.text or message.reply_to_message.caption
        dst = message.reply_to_message
        member = await bot.get_chat_member(message.chat.id,
                                           message.from_user.id)
        if isinstance(member, ChatMemberOwner) or (
                isinstance(member, ChatMemberAdministrator)
                and member.can_delete_messages):
            messages_to_delete.append(dst)
    else:
        content = message.get_args()
        dst = message
        messages_to_delete.append(dst)

    if not content or (len(content) < 30 and content.count('\n') < 2):
        return await message.reply(_("Content to move is too short!"))

    content = content.encode()
    response = await hastebin.create_document(content)

    document_url = hastebin.format_url(response["key"])
    text = _(
        "Message originally posted by {author} was moved to {url} service\n"
        "Content size: {size} bytes").format(
            author=dst.from_user.get_mention(as_html=True),
            url=md.hlink("HasteBin", document_url),
            size=len(content),
        )
    await dst.reply(text, allow_sending_without_reply=True)

    for message_to_delete in messages_to_delete:
        with suppress(TelegramAPIError):
            await message_to_delete.delete()
예제 #2
0
async def message_start(message: types.Message):
    user = message.from_user.full_name
    source_url = md.hlink("Github", "https://github.com/cyberdas/async_bot_telegram")
    await message.answer(
        f"Привет, {user}!\n"
        f"Команда /help выведет список доступных команд.\n"
        f"Команда /settings позволит изменить настройки.\n"
        f"Исходники: {source_url}", parse_mode="HTML")
예제 #3
0
async def notify_superusers(chats: Union[List[int], List[str], int, str]):
    # Generate chats
    chats = [
        {
            "chat_id": chat_id,
            "mention": md.hlink(title=f"ID:{chat_id}", url=f"tg://user?id={chat_id}"),
        }
        for chat_id in chats
    ]

    # Run broadcaster
    await TextBroadcaster(
        chats=chats,
        text=md.hbold("$mention, The bot is running!"),
    ).run()
예제 #4
0
async def users(msg: atp.Message, session: AsyncSession):
    users_list = (await session.execute(select(User))).scalars().all()
    await msg.answer("Users list\n" + "\n".join([
        md.hlink(user.name, f"tg://user?id={user.id}") for user in users_list
    ]))
예제 #5
0
async def links(msg: types.Message, state: FSMContext, locale):
    urls = extractor.find_urls(msg.text)

    # Return if message not contain urls
    if not urls:
        if msg.chat.type == types.chat.ChatType.PRIVATE:
            await msg.answer(
                _('No links to music services were found in the message\\.'))
        return

    if not msg.chat.type == types.chat.ChatType.PRIVATE and not is_supported_link(
            urls[0]):
        return

    # Send bot `typing...`
    await bot.send_chat_action(chat_id=msg.chat.id,
                               action=types.ChatActions.TYPING)

    # Get user data from state
    user_data = await state.get_data()

    # Set layout if it not defined early
    if user_data.get(LINKS_LAYOUT_NAME) is None:
        async with state.proxy() as data:
            data[LINKS_LAYOUT_NAME] = LinksLayout.COMBINED.value

    for url in urls:
        new_url = url
        shazam = Shazam(url)
        if shazam.is_shazam_url():
            new_url = await shazam.find_links()
        message: List[str] = []

        try:
            linksdata = await odesli.links(url=new_url)
        except Exception as e:
            print(e)
            await msg.answer(
                _('Unfortunately, we have no data for this link 😥\.'))
            return

        entity = linksdata.entitiesByUniqueId[linksdata.entityUniqueId]

        def links_by_platform(platform: Platform) -> Optional[str]:
            return getattr(linksdata.linksByPlatform.get(platform), 'url',
                           None)

        message.append(
            md.hlink(
                f"{entity.artistName} - {entity.title}\n",
                get_streaming_hell_link(id=entity.id,
                                        type=entity.type,
                                        platform=entity.platforms[0])))

        # Compose message text for `SEPARATE` layout
        if user_data.get(LINKS_LAYOUT_NAME) == LinksLayout.SEPARATE.value:
            listen_links: list[str] = []
            buy_links: list[str] = []
            for key, value in platforms.items():
                if links_by_platform(key) and value['isStore'] is False:
                    listen_links.append(
                        md.hlink(value['name'], links_by_platform(key)))
                elif links_by_platform(key) and value['isStore'] is True:
                    buy_links.append(
                        md.hlink(value['name'], links_by_platform(key)))

            if listen_links:
                message.append(md.hbold(_('🎧 Listen')))
                message.extend(listen_links)
                message.append(
                    md.hlink(
                        'VK',
                        get_vk_search_link(
                            f"{entity.artistName} - {entity.title}")))
            if buy_links:
                message.append(md.hbold(_('\n🛍 Buy')))
                message.extend(buy_links)

        # Compose message text for `COMBINED` layout
        if user_data.get(LINKS_LAYOUT_NAME) == LinksLayout.COMBINED.value:
            for key, value in platforms.items():
                if links_by_platform(key):
                    message.append(
                        md.hlink(value['name'], links_by_platform(key)))
            message.append(
                md.hlink(
                    'VK',
                    get_vk_search_link(
                        f"{entity.artistName} - {entity.title}")))

        # Compose message text for `MINIMAL` layout
        if user_data.get(LINKS_LAYOUT_NAME) == LinksLayout.MINIMAL.value:
            for key, value in platforms.items():
                if links_by_platform(key):
                    message.append(
                        md.hlink(value['name'], links_by_platform(key)))
                    message.append(md.text(' | '))
            message.append(
                md.hlink(
                    'VK',
                    get_vk_search_link(
                        f"{entity.artistName} - {entity.title}")))

        caption = md.text(*message, sep='\n')
        if user_data.get(LINKS_LAYOUT_NAME) == LinksLayout.MINIMAL.value:
            caption = md.text(*message, sep='')

        # Delete user message that contains streaming link
        bot_member = await bot.get_chat_member(chat_id=msg.chat.id,
                                               user_id=bot.id)
        if msg.chat.type == types.ChatType.PRIVATE:
            await bot.delete_message(chat_id=msg.chat.id,
                                     message_id=msg.message_id)
        elif bot_member.can_delete_messages:
            await bot.delete_message(chat_id=msg.chat.id,
                                     message_id=msg.message_id)

        # Send found streaming links
        await msg.answer_photo(photo=entity.thumbnailUrl,
                               caption=caption,
                               parse_mode=types.ParseMode.HTML)