Example #1
0
def broadcast_message(text: str,
                      buttons: Optional[list[dict[str, str]]] = None,
                      *args):
    """
    Celery task used to broadcast new messages to users

    :param text: Text to be sent #TODO: [11/13/2020 by Mykola] Add formatting, such as HTML or Markdown
    :param buttons: List of inline buttons in format [{'text': 'text', 'callback_data': 'callback_data', **kwargs}]
    :return:
    """
    from main import dp
    executor.start(dp, broadcaster(text, buttons))
Example #2
0
async def broadcaster() -> int:
    """
    Simple broadcaster

    :return: Count of messages
    """
    count = 0
    await init_pg(db)

    async with db['db'].acquire() as conn:
        data = await all_users(conn)

        try:
            for user in data:
                if await send_message(user['id'], '<b>Hello!</b>'):
                    count += 1
                await asyncio.sleep(
                    .05
                )  # 20 messages per second (Limit: 30 messages per second)
        finally:
            log.info(f"{count} messages successful sent.")
            await close_pg(db)

        return count


if __name__ == '__main__':
    # Execute broadcaster
    executor.start(dp, broadcaster())
Example #3
0
        row = cursorObj.fetchone()
        if None == row:
            cursorObj.execute(
                "INSERT INTO vacancy VALUES (?, ?, DateTime('now', 'localtime'))",
                (link, new_link[link]))
            conn.commit()
            print(
                str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +
                ' ' + link, new_link[link])

            send_link[link] = new_link[link]
            time.sleep(8)
        conn.close()

    try:
        executor.start(dp, send_telegram(send_link))
    except:
        print('telegramm not connected')

    new_link.clear()
    send_link.clear()

    if 9 <= int(datetime.datetime.now().strftime("%H")) <= 22:
        print(
            str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +
            ' Ожидание 5 мин')
        # time.sleep(301)
    else:
        print(
            str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +
            ' Ожидание 20 мин')
Example #4
0
def start_script():
    bot = Bot(token=config.TG_BOT_TOKEN)
    dp = Dispatcher(bot)

    last_known_id = read_id()
    logger.info(f"Last known ID: {last_known_id}")

    items: Union[dict, None] = get_data_from_vk(
        config.VK_TOKEN,
        config.REQ_VERSION,
        config.VK_DOMAIN,
        config.REQ_FILTER,
        config.REQ_COUNT,
    )
    if not items:
        return

    if "is_pinned" in items[0]:
        items = items[1:]
    logger.info(f"Got a few posts with IDs: {items[-1]['id']} - {items[0]['id']}.")

    new_last_id: int = items[0]["id"]

    if new_last_id > last_known_id:
        for item in items[::-1]:
            item: dict
            if item["id"] <= last_known_id:
                continue
            logger.info(f"Working with post with ID: {item['id']}.")
            if blacklist_check(config.BLACKLIST, item["text"]):
                continue
            if whitelist_check(config.WHITELIST, item["text"]):
                continue
            if config.SKIP_ADS_POSTS and item["marked_as_ads"]:
                logger.info("Post was skipped as an advertisement.")
                continue
            if config.SKIP_COPYRIGHTED_POST and "copyright" in item:
                logger.info("Post was skipped as an copyrighted post.")
                continue

            item_parts = {"post": item}
            group_name = ""
            if "copy_history" in item and not config.SKIP_REPOSTS:
                item_parts["repost"] = item["copy_history"][0]
                group_name = get_group_name(
                    config.VK_TOKEN,
                    config.REQ_VERSION,
                    abs(item_parts["repost"]["owner_id"]),
                )
                logger.info("Detected repost in the post.")

            for item_part in item_parts:
                prepare_temp_folder()
                repost_exists: bool = True if len(item_parts) > 1 else False

                logger.info(f"Starting parsing of the {item_part}")
                parsed_post = parse_post(
                    item_parts[item_part], repost_exists, item_part, group_name
                )
                logger.info(f"Starting sending of the {item_part}")
                executor.start(
                    dp,
                    send_post(
                        bot,
                        config.TG_CHANNEL,
                        parsed_post["text"],
                        parsed_post["photos"],
                        parsed_post["docs"],
                    ),
                )

        write_id(new_last_id)
Example #5
0
    log.addHandler(sh)

    log.debug('Checking queue for new posts')
    new_post = check_queue(args)
    if not new_post:
        log.debug('No posts in queue')
        sys.exit()
    log.debug('Queue have posts')
    log.debug(
        f"Posting {service_db[new_post['service']]['name']}:{new_post['post_id']} to VK"
    )
    wall_id = post_to_vk(new_post)
    log.debug('Adding to history')
    add_to_history(new_post, wall_id)
    log.debug('Posting to Telegram')
    await post_to_tg(new_post, wall_id)
    log.debug('Posting to Tumblr')
    try:
        post_to_tumblr(new_post)
    except Exception as ex:
        log.error("Tumblr posting failed", exc_info=True)
    if new_post.get('pic_name'):
        os.remove(QUEUE_FOLDER + new_post['pic_name'])
    await post_info(new_post)
    log.debug('Posting finished')
    update_header()


if __name__ == '__main__':
    executor.start(dp, main())
Example #6
0
        await asyncio.sleep(1.5)


async def _chat_link_cache(channel, cache={}):
    if channel not in cache:
        chat_id = (await bot.get_chat(channel)).linked_chat_id
        cache[channel] = chat_id
    return cache[channel]


async def _get_img():
    browser = await launch()
    page = await browser.newPage()
    await page.setViewport(dict(width=1500, height=1500))
    await page.goto('https://sova.kpi.in.ua/pic/')
    img = await page.screenshot(type='png')
    await browser.close()
    return img

if __name__ == '__main__':
    faculty = Faculty.objects.get(id=10106)
    faculty.poll_result_link = -1001407513106

    teacher = Teacher.objects.get(id='d1bfd5d9-efde-40af-992e-7f8e798a5f69')

    async def test():
        img = await _get_img()
        await _send_new_post(faculty, teacher, img, ["peq1", 'hui2'])

    executor.start(dp, test())
Example #7
0
            log = []
            with open("build.log", "r") as file1:
                log = file1.readlines()
            str1 = ""
            for i in log[-3000:]:
                str1 += i
            nekobin_key = requests.post(
                "https://nekobin.com/api/documents", json={"content": str1}
            ).json()["result"]["key"]
            message_track = await edit_message(
                518221376,
                "[Build Log](https://nekobin.com/" + nekobin_key + ")",
                message_track,
            )
            raise RuntimeError

        message_track = await edit_message(
            518221376, "`Build Succeeded\!`", message_track
        )

    except:
        await send_message(518221376, "Build Failed\!")
        print("Our Build Failed, but your traceback should help you!")
        import traceback
        traceback.print_exc()
        exit(127)


if __name__ == "__main__":
    executor.start(dp, runner())
Example #8
0
        current_last_change = modification_date(game_logs)
        if last_change != current_last_change:
            break
    return True


def get_text():
    """
    Parse the last line of minecraft server logs

    :return: Parsing text
    """
    last_line = ""
    with open(game_logs, "r") as f1:
        last_line = f1.readlines()[-1]
    if last_line.find("joined") != -1 or last_line.find("left") != -1:
        text = last_line.split("]: ")[1]  # '<b>${text}</b>'
        return text
    return ""


if __name__ == "__main__":
    # Infinite loop for every new connection
    while True:
        # wait for new connection
        if is_changed():
            text = get_text()
            # if not empty then send message all saved users
            if text:
                executor.start(dp, broadcaster(text))
Example #9
0
from aiogram.utils import executor

from .bot import channel_publish, dp

if __name__ == "__main__":
    executor.start(dp, channel_publish())