예제 #1
0
async def test_sign_in_rewrite(client: TelegramClient):

    sleep(sleep_time)
    # ...Sign In Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign in", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    m = re.search(r"Log No.(\d+)", reply)
    if m:
        log_id = m.group(1)
    sleep(sleep_time)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("Rewrite the log", "Do you really want to do remove log No."),
            ("Yes, I delete and write again", "You have relogged as below."),
            ("Office", "I see"),
            ("Not Available",
             "You have logged as below. Do you want to confirm"),
            ("Confirm", "Confirmed"),
        ]

        log_id = await check_assert_with_qna(qna, conv)

    # earase log after use
    await erase_log(bot_id, str(log_id), client)
async def test_get_back_edit(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself

    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "back to work",
                                             client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("With KOICA Colleagues", "I see"),
            ("Not Available", "You have logged as below."),
            ("Go_back", "Did you have lunch with KOICA collague"),
            ("With KOICA Colleagues", "I see"),
            ("Not Available", "You have logged as below."),
            ("Confirm", "Confirmed"),
        ]

        log_id = await check_assert_with_qna(qna, conv)

        # earase log after use
        await erase_log(bot_id, str(log_id), client)
예제 #3
0
async def test_sign_out_first(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself

    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign out", client)
    m = re.search(r"Log No.(\d+)", reply)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    if m:
        log_id = m.group(1)
        print(log_id)

    # conversation
    async with client.conversation(bot_id) as conv:

        sleep(sleep_time)

        qna = [
            ("I worked at Office", "I see"),
            ("Not Available", "You have signed out as below"),
            ("Confirm", "Confirmed"),
        ]

        await check_assert_with_qna(qna, conv)
예제 #4
0
async def test_sign_out_report(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself

    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign out", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    # conversation
    async with client.conversation(bot_id) as conv:

        sleep(sleep_time)

        qna = [
            ("Home", "I see"),
            ("Not Available", "You have logged as below."),
            (
                "Send content of today",
                "Please text me the today's work.",
            ),
            ("It is a test", "Content of Work"),
            ("Save content", "Content has been saved"),
            ("Confirm", "No sign in information"),
        ]

        await check_assert_with_qna(qna, conv)
예제 #5
0
async def test_sign_out_rewrite(client: TelegramClient):

    sleep(sleep_time)
    # Getting information about yourself

    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign out", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    sleep(sleep_time)
    # Signing Out conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("Rewrite the log", "Do you really want to do remove log No."),
            ("Yes, I delete and write again", "You have relogged as below."),
            ("Home", "I see"),
            ("Not Available",
             "You have logged as below. Do you want to confirm"),
            (
                "Send content of today",
                "Please text me the today's work.",
            ),
            ("It is a test", "Content of Work"),
            ("Save content", "Content has been saved"),
            ("Confirm", "No sign in information"),
        ]

        log_id = await check_assert_with_qna(qna, conv)

    # earase log after use
    await erase_log(bot_id, str(log_id), client)
예제 #6
0
async def test_get_back_edit(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself

    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "back to work",
                                             client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)
    m = re.search(r"Log No.(\d+)", reply)
    log_id = m.group(1)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("With KOICA Colleagues", "I see"),
            ("Not Available", "You have gotten back as below"),
            ("Edit", "Did you have lunch with KOICA Colleauge"),
            ("With KOICA Colleagues", "I see"),
            ("Not Available", "You have gotten back as below"),
            ("Confirm", "Confirmed"),
        ]

        await check_assert_with_qna(qna, conv)

        # earase log after use
        await erase_log(bot_id, str(log_id), client)
예제 #7
0
async def test_sign_out_edit(client: TelegramClient):

    # Getting information about yourself

    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign out", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("Home", "I see"),
            ("Not Available", "You have logged as below."),
            (
                "Send content of today",
                "Please text me the today's work.",
            ),
            ("It is a test", "Content of Work"),
            ("Save content", "Content has been saved"),
            ("Go back", "Where do you work?"),
            ("Office", "I see"),
            ("Not Available",
             "You have logged as below. Do you want to confirm"),
            ("Confirm", "No sign in information"),
            ("/work_content", ""),
        ]

        log_id = await check_assert_with_qna(qna, conv)

        # earase log after use
        await erase_log(bot_id, str(log_id), client)
예제 #8
0
async def test_mipt(client: TelegramClient):
    try:
        async with client.conversation(bot, timeout=30) as conv:
            await conv.send_message("MIPT")
            resp = await conv.get_response()
    except asyncio.exceptions.TimeoutError:
        raise Exception("request is being processed for a long time")
예제 #9
0
async def test_sign_out_edit(client: TelegramClient):

    # Getting information about yourself

    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign out", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)
    m = re.search(r"Log No.(\d+)", reply)
    log_id = m.group(1)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            (
                "I would like to report",
                "OK. Please text me what you have done",
            ),
            ("It is a test", "Content of Work"),
            ("YES", "I see"),
            ("/로그북", ""),
            ("/work_content", ""),
            ("Not Available", "You have signed out as below"),
            ("Edit", "Would you like to share your today's content of work"),
            ("I worked at Office", "I see"),
            ("Not Available", "You have signed out as below"),
            ("Confirm", "Confirmed"),
            ("/로그북", ""),
            ("/work_content", ""),
        ]

        await check_assert_with_qna(qna, conv)

        # earase log after use
        await erase_log(bot_id, str(log_id), client)
예제 #10
0
async def test_sign_in_edit(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself

    # ...Sign In Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign in", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("Office", "I see"),
            ("Not Available",
             "You have logged as below. Do you want to confirm"),
            ("Go back", "Where do you work?"),
            ("Office", "I see"),
            ("Not Available",
             "You have logged as below. Do you want to confirm"),
            ("Confirm", "Confirmed"),
        ]

        log_id = await check_assert_with_qna(qna, conv)

        # earase log after use
        await erase_log(bot_id, str(log_id), client)
예제 #11
0
async def test_sign_in_edit(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself

    # ...Sign In Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign in", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)
    m = re.search(r"Log No.(\d+)", reply)
    log_id = m.group(1)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("Office", "I see"),
            ("Not Available",
             "You have signed in as below. Do you want to confirm"),
            ("Edit", "Would you like to share where you work"),
            ("Office", "I see"),
            ("Not Available",
             "You have signed in as below. Do you want to confirm"),
            ("Confirm", "Confirmed"),
        ]

        await check_assert_with_qna(qna, conv)

        # earase log after use
        await erase_log(bot_id, str(log_id), client)
예제 #12
0
async def test_trans(client: TelegramClient):
    async with client.conversation(bot, timeout=5) as conv:
        await conv.send_message("Привет, меня зовут тест, я тестирую бота. "
                                "Hi, my name is test, I test the bot")
        resp = await conv.get_response()
        text = 'Hi, my name is test, I test the bot. ' \
               'Hi, my name is test, I test the bot'
        assert text == resp.raw_text
예제 #13
0
async def test_start(client: TelegramClient):
    async with client.conversation(bot, timeout=10) as conv:
        await conv.send_message("/start")
        resp = await conv.get_response()

        text = 'Привет, я личный бот Армана.' \
               '\nЕсли не знаешь что делать напиши /help.'

        assert text == resp.raw_text
예제 #14
0
async def test_help(client: TelegramClient):
    # Create a conversation
    with client.conversation("@dante_dog_bot", timeout=5) as conv:
        # Send a command
        await conv.send_message("/help")
        # Get response
        resp: Message = await conv.get_response()
        # Make assertions
        assert "@dante_dog_bot" in resp.raw_text
        assert "👍" in resp.raw_text
        assert "👎" in resp.raw_text
예제 #15
0
async def test_start(client: TelegramClient):
    async with client.conversation(bot, timeout=10) as conv:
        await conv.send_message("/start")
        resp = await conv.get_response()

        text = "Добро пожаловать!" \
               "\n\nЯ - бот созданный переводить введеный тобой текст, на один из 16 доступный языков." \
               "\n\nВсё что от тебя нужно, выбрать язык, на который нужно перевести текст, а остальное я сделаю сам.\n" \
               "По умолчанию стоит английский язык." \
               "\n\n/lang - чтобы изменить языка"
        assert text == resp.raw_text
예제 #16
0
async def test_help(client: TelegramClient):
    async with client.conversation(bot, timeout=10) as conv:
        await conv.send_message("/help")
        resp = await conv.get_response()

        text = 'Это бот который может выдавать последние новости про Реал Мадрид' \
               ' и про МФТИ.\nНапиши "Real Madrid" и получишь новость' \
               ' про Реал Мадрид.\nНапиши "MIPT" и получишь новость про МФТИ.\n' \
               'А если написать сообщение он повторно отправит его' \
               ' и предложить две кнопки: "Real Madrid" и "Mipt".'

        assert text == resp.raw_text
예제 #17
0
async def test_start(client: TelegramClient):
    # Create a conversation
    with client.conversation("@dante_dog_bot", timeout=5) as conv:
        # User > /start
        await conv.send_message("/start")
        # Bot < Let's create a message with emoji like-buttons. First, send
        # me the message. It can be anything — a text, photo, video, even a
        # sticker.

        # Get response
        resp: Message = await conv.get_response()
        # Make assertions
        assert "create a message" in resp.raw_text

        # User > Message body L9b_vp7IV6hVAR5ADsYxYL9w7YPQw-HLlqHopcwf20I
        message = f"Message body {token_urlsafe(32)}"
        # Bot < Now send me one or more emoticons that we will use for buttons
        # (up to 6 emoji). Use /cancel if you changed your mind.
        await conv.send_message(message)
        resp = await conv.get_response()
        assert "emoticon" in resp.raw_text
        assert "6" in resp.raw_text
        assert "/cancel" in resp.raw_text

        # User > 🆗🆒❤️🤣
        #emojis = ["🆗", "🆒", "❤️", "🤣"]
        # await conv.send_message(emojis.join(""))

        # Bot < 👍 Post created. Now use the ‘Publish’ button to send it to
        # your friends.
        resp = await conv.get_response()
        assert "👍" in resp.raw_text
        assert "Publish" in resp.raw_text

        # Bot < Message body L9b_vp7IV6hVAR5ADsYxYL9w7YPQw-HLlqHopcwf20I
        # [🆗][🆒][❤️][🤣]
        # [    Publish    ]
        resp = await conv.get_response()
        assert resp.raw_text == message
        #assert resp.button_count == len(emojis) + 1
        #assert [i.text for i in resp.buttons[0]] == emojis
        assert resp.buttons[1][0].text == "Publish"

        # Test reaction
        # Click on button [🆗]
        #answer: BotCallbackAnswer = await resp.click(text=emojis[0])
        # Bot gives response > You 🆗 this.
        #assert emojis[0] in answer.message
        # Bot (edited) < Message body L9b_vp7IV6hVAR5ADsYxYL9w7YPQw-HLlqHopcwf20I
        # [🆗1][🆒][❤️][🤣]
        # [     Publish    ]
        resp = conv.get_edit(message=resp)
        assert "1" in resp.buttons[0][0].text
예제 #18
0
async def test_handle_photo_msg(client: TelegramClient):
    # Create a conversation
    print('here is tests are continue')
    async with client.conversation("@audio_dot_bot", timeout=5) as conv:
        # Send a command
        await conv.send_message(open('tests/static/photo/test_image.jpg',
                                     'rb'))
        # Get response
        resp: Message = await conv.get_response()
        # Make assertions
        assert "@audio_dot_bot" in resp.raw_text
        assert "👍" in resp.raw_text
        assert "👎" in resp.raw_text
예제 #19
0
async def test_sign_out_rewrite(client: TelegramClient):

    sleep(sleep_time)
    # Getting information about yourself

    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign out", client)
    m = re.search(r"Log No.(\d+)", reply)
    log_id = m.group(1)

    reply = await get_reply_of_message_of_id(bot_id, "", client)

    sleep(sleep_time)
    # Signing Out conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("Delete and Sign Out Again", "Do you really want to do remove log No."),
            ("REMOVE SIGN OUT LOG", "has been Deleted"),
        ]

        await check_assert_with_qna(qna, conv)

        response = await conv.get_response()
        print(response.text)
        assert "Would you like to share your today's content of work" in response.text

        qna = [
            (
                "I would like to report",
                "OK. Please text me what you have done",
            ),
            ("It is a test", "Content of Work"),
            ("YES", "I see"),
            ("Not Available", "You have signed out as below"),
            ("Confirm", "Confirmed"),
        ]

        await check_assert_with_qna(qna, conv)

    # earase log after use
    await erase_log(bot_id, str(log_id), client)
async def test_edit(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself

    # ...Edit Test
    reply = await get_reply_of_message_of_id(bot_id, "/edit", client)
    m = re.search(r"Log No.(\d+)", reply)
    log_id = m.group(1)
    print(log_id)
    # conversation
    async with client.conversation(bot_id) as conv:

        sleep(sleep_time)

        qna = [
            (log_id, "Do you really want to do edit log"),
            ("YES", "start to edit Log"),
            ("SKIP", "Bye"),
        ]

        await check_assert_with_qna(qna, conv)
예제 #21
0
async def test_get_back_rewrite(client: TelegramClient):

    sleep(sleep_time)
    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "back to work",
                                             client)

    reply = await get_reply_of_message_of_id(bot_id, "", client)
    m = re.search(r"Log No.(\d+)", reply)
    if m:
        log_id = m.group(1)
    sleep(sleep_time)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            (
                "Delete and Get Back to Work Again",
                "Do you really want to do remove log No.",
            ),
            ("REMOVE GET BACK LOG", "has been Deleted"),
        ]

        await check_assert_with_qna(qna, conv)

        response = await conv.get_response()
        print(response.text)
        assert "Did you have lunch with KOICA Colleauge" in response.text

        qna = [
            ("With KOICA Colleagues", "I see"),
            ("Not Available", "You have gotten back as below"),
            ("Confirm", "Confirmed"),
        ]

        await check_assert_with_qna(qna, conv)

    # earase log after use
    await erase_log(bot_id, str(log_id), client)
예제 #22
0
async def test_sign_in_rewrite(client: TelegramClient):

    sleep(sleep_time)
    # ...Sign In Test
    reply = await get_reply_of_message_of_id(chat_room_id, "sign in", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    m = re.search(r"Log No.(\d+)", reply)
    if m:
        log_id = m.group(1)
    sleep(sleep_time)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("Delete and Sign In Again",
             "Do you really want to do remove log No."),
            ("REMOVE SIGN IN LOG", "has been Deleted"),
        ]

        await check_assert_with_qna(qna, conv)

        response = await conv.get_response()
        print(response.text)
        assert "Would you like to share where you work" in response.text

        qna = [
            ("Office", "I see"),
            ("Not Available",
             "You have signed in as below. Do you want to confirm"),
            ("Confirm", "Confirmed"),
        ]

        await check_assert_with_qna(qna, conv)

    # earase log after use
    await erase_log(bot_id, str(log_id), client)
예제 #23
0
async def test_get_back_first(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself

    # ...Get back Test
    await get_reply_of_message_of_id(chat_room_id, "back to work", client)

    reply = await get_reply_of_message_of_id(bot_id, "", client)
    m = re.search(r"Log No.(\d+)", reply)
    if m:
        log_id = m.group(1)
        print(log_id)
    # conversation
    async with client.conversation(bot_id) as conv:

        sleep(sleep_time)

        qna = [
            ("Without any member of KOICA", "I see"),
            ("Not Available", "You have gotten back as below"),
            ("Confirm", "Confirmed"),
        ]

        await check_assert_with_qna(qna, conv)
예제 #24
0
async def test_sign_in_first(client: TelegramClient):
    sleep(sleep_time)
    # Getting information about yourself
    reply = await get_reply_of_message_of_id(chat_room_id, "sign in", client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    m = re.search(r"Log No.(\d+)", reply)
    if m:
        log_id = m.group(1)
        print(log_id)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        sleep(sleep_time)

        qna = [
            ("Office", "I see"),
            ("Not Available",
             "You have logged as below. Do you want to confirm"),
            ("Confirm", "Confirmed"),
        ]

        await check_assert_with_qna(qna, conv)
async def test_get_back_rewrite(client: TelegramClient):

    sleep(sleep_time)
    # ...Get back Test
    reply = await get_reply_of_message_of_id(chat_room_id, "back to work",
                                             client)
    reply = await get_reply_of_message_of_id(bot_id, "", client)

    # Signing in conversation
    async with client.conversation(bot_id) as conv:

        qna = [
            ("Rewrite the lunch log",
             "Do you really want to do remove log No."),
            ("Yes, I delete and write again", "You have relogged as below."),
            ("With KOICA Colleagues", "I see"),
            ("Not Available", "You have logged as below."),
            ("Confirm", "Confirmed"),
        ]

        log_id = await check_assert_with_qna(qna, conv)

    # earase log after use
    await erase_log(bot_id, str(log_id), client)
예제 #26
0
def process_in(in_str, message_obj, chat_id):
    m = 0
    users = []
    botdb = MongoClient('localhost', 27017).bot
    #reply = 'Не понял :(\nНайти номер - "@bot номер ххххх"\nДобавить номер в базу - "@bot добавь номер ххххх"\nПоиск телефона по базе антипаркон - "@bot пробей х456хх77"\nОстальные комманды - "@bot старт (или помощь)"'
    reply = 'Не понял :( Если нужно найти номер - "@bot номер ххххх", остальные комманды - "@bot помощь"'
    hello_replies = [
        'Салют!', 'Привет!', 'Халлоу!', 'Прувэт!', 'Алоха', 'Шалом :)'
    ]
    in_str = in_str[1:len(in_str)].strip() if in_str.startswith(
        ',') else in_str.strip()
    #remove multiple spaces
    in_str = " ".join(in_str.split())

    msg = in_str.split(' ')
    if len(msg):
        if msg[0] in ('Номер', 'номер'):
            if len(msg) >= 2 and msg[1] and len(msg[1]) >= 3:
                num_in = msg[1]
                print('DEBUG: num in = ', num_in)
                num_norm = normalize_num(num_in)
                print('DEBUG: num norm = ', num_norm)
                #reply = find_num(num_norm, False)
                reply, users = find_num2(num_norm, chat_id, False)

                #fixme
                m = 1
                #m = 0
            else:
                reply = "Не совсем понял запрос. Надо, к примеру, так: @bot номер 640 или @bot номер в861рт (минимум 3 символа)"

        elif msg[0] in ('Добавь', 'добавь', 'Добавить', 'добавить'):
            #print("DEBUG,", msg)
            if len(msg) >= 3 and msg[1] and msg[2] and msg[1] in ('номер',
                                                                  'Номер'):
                num_norm = normalize_num(msg[2])
                print('DEBUG: num norm = ', num_norm)
                if len(num_norm) <= 10 and len(num_norm) >= 3:
                    res = botdb.numbers.find({
                        'number': num_norm,
                        'chat_id': chat_id
                    })
                    if res.count():
                        reply = "Такой номер уже есть в базе, но спасибо ;)"
                    else:
                        botdb.numbers.insert({
                            'number':
                            num_norm,
                            'name':
                            message_obj['sender']['pushname'],
                            'phone':
                            message_obj['sender']['id']['user'],
                            'chat_id':
                            chat_id
                        })
                        reply = 'Ок, я запомнил номер тачки %s - это %s ' % (
                            num_norm, message_obj['sender']['pushname'])
                else:
                    reply = "Слишком длинный или слишком короткий номер (минимально 3 символа, максимально 10), не могу добавить."
            elif len(msg) >= 3 and msg[1] and msg[2] and msg[1] in ('др', 'Др',
                                                                    'ДР',
                                                                    'днюху'):
                print("DEBUG: dr_add mode")
                dr = msg[2]
                if dr and len(dr) and validate_date(dr):
                    dr_dt = datetime.strptime(dr, '%Y-%m-%d')
                    botdb.drs.insert({
                        'name':
                        message_obj['sender']['pushname'],
                        'phone':
                        message_obj['sender']['id']['user'],
                        'day':
                        dr_dt.day,
                        'month':
                        dr_dt.month,
                        'year':
                        dr_dt.year,
                        'chat_id':
                        chat_id
                    })
                    reply = "Ок, спасибо, я записал твой день рождения! ;)"
                else:
                    reply = "Не понял формат даты. Нужно использовать ГГГГ-ММ-ДД. Например *@bot добавь др 1983-08-17* "
            else:
                reply = """Не совсем понял запрос. \nНадо, к примеру, так: *@bot добавь номер в861рт77* . Добавить можно только свой номер!\nИли *@bot добавь др 1983-08-17* - я запомню твой день рождения и приготовлю подарочек ;)"""

        elif msg[0] in ('помощь', 'Помощь', 'Help', 'help', 'Комманды',
                        'комманды', 'старт', 'начало', 'Старт', 'Начало'):
            reply = "Привет, я - бот.\n\n*!!! Важное обновление от 28 Августа 2019 - теперь то, что вы пишете мне в личку - это наш личный чат и он не относится к другим публичным чатам !!!*\n\nПонимаю следующие комманды:\n*@bot Номер в861рт77*\n - поищу по базе - кто скрывается за этим номером.\n Можно только цифры или часть букв - все равно найду\n*@bot Добавь номер в861рт77* - добавить номер в базу"
            reply += "\n*@bot Статистика* - небольшая стата по чату за сутки"
            reply += "\n*@bot Пробей х345х67* - поиск номера в базе антипаркон"
            reply += "\n*@bot Добавь др 1983-08-17* - запомнить день рождения, приготовить подарки :) "
            reply += "\n*@bot Пометка бота под картинкой* - бот постарается найти номер на фотке и пробить по базе одноклубников."
            reply += "\n*@bot чип* - голосование за лучший чип."

        elif msg[0] in ('Статистика', 'статистика', 'Стата', 'стата'):
            dt_from = datetime(datetime.now().year,
                               datetime.now().month,
                               datetime.now().day, 0, 0, 0)
            dt_to = datetime(datetime.now().year,
                             datetime.now().month,
                             datetime.now().day, 23, 59, 59)
            ms_obj = start_of_month()
            month_start = datetime(ms_obj.year, ms_obj.month, ms_obj.day, 0, 0,
                                   0)
            et_obj = date.today() - timedelta(1)
            yt_from = datetime(et_obj.year, et_obj.month, et_obj.day, 0, 0, 0)
            yt_to = datetime(et_obj.year, et_obj.month, et_obj.day, 23, 59, 59)

            reply = "*Всего сообщений за:*\n"
            res = botdb.botstats.find({
                'dt': {
                    '$gte': dt_from,
                    '$lte': dt_to
                },
                'chat_id': chat_id
            })
            reply += "- сегодня: %d\n" % res.count()

            res = botdb.botstats.find({
                'dt': {
                    '$gte': yt_from,
                    '$lte': yt_to
                },
                'chat_id': chat_id
            })
            reply += "- вчера: %d\n" % res.count()
            print("DEBUG:", month_start, dt_to)
            res = botdb.botstats.find({
                'dt': {
                    '$gte': month_start,
                    '$lte': dt_to
                },
                'chat_id': chat_id
            })
            reply += "- месяц: %d\n" % res.count()

            res = botdb.botstats.aggregate([{
                "$match": {
                    'chat_id': chat_id
                }
            }, {
                "$group": {
                    "_id": {
                        "month": {
                            "$month": "$dt"
                        },
                        "day": {
                            "$dayOfMonth": "$dt"
                        },
                        "year": {
                            "$year": "$dt"
                        }
                    },
                    "cnt": {
                        "$sum": 1
                    }
                }
            }, {
                "$sort": {
                    "cnt": -1
                }
            }])
            if res:
                r = res.next()
                reply += "\nБольше всего сообщений ({0}) было {3}.{2}.{1}\n".format(
                    r['cnt'], r['_id']['year'], r['_id']['month'],
                    r['_id']['day'])

            res = botdb.botstats.aggregate([{
                "$match": {
                    'dt': {
                        '$gte': dt_from,
                        '$lte': dt_to
                    },
                    'chat_id': chat_id
                }
            }, {
                "$group": {
                    "_id": "$name",
                    "total": {
                        "$sum": 1
                    }
                }
            }, {
                "$sort": {
                    "total": -1
                }
            }, {
                "$limit": 10
            }])
            reply += "\n*Топ 10 авторов сегодня:*\n"
            for r in res:
                reply += "@%s: %d\n" % (r['_id'], r['total'])
                users.append(str(r['_id']))

            res = botdb.botstats.find({
                'dt': {
                    '$gte': dt_from,
                    '$lte': dt_to
                },
                'blya_counter': 1
            })
            #reply += "Слово бл* написали %d раз\n" % res.count()
            res = botdb.botstats.aggregate([{
                "$match": {
                    'dt': {
                        '$gte': dt_from,
                        '$lte': dt_to
                    },
                    'blya_counter': 1,
                    'chat_id': chat_id
                }
            }, {
                "$group": {
                    "_id": "$name",
                    "total": {
                        "$sum": 1
                    }
                }
            }, {
                "$sort": {
                    "total": -1
                }
            }, {
                "$limit": 5
            }])
            reply += "\n*Топ 5 культурных людей:*\n"
            for r in res:
                reply += "@%s: %d\n" % (r['_id'], r['total'])
                if str(r['_id']) not in users:
                    users.append(str(r['_id']))

            res = botdb.botstats.aggregate([{
                "$match": {
                    'chat_id': chat_id
                }
            }, {
                "$group": {
                    "_id": "$name",
                    "total": {
                        "$sum": 1
                    }
                }
            }, {
                "$sort": {
                    "total": -1
                }
            }, {
                "$limit": 5
            }])
            reply += "\n*Топ 5 болтунов за все время:*\n"
            for r in res:
                reply += "@%s: %d\n" % (r['_id'], r['total'])
                if str(r['_id']) not in users:
                    users.append(str(r['_id']))
            m = 0

        elif msg[0] in ('матсата', 'ктопиздабол', 'ктопиздобол',
                        'матершинники', 'стата2'):
            dt_from = datetime(datetime.now().year,
                               datetime.now().month,
                               datetime.now().day, 0, 0, 0)
            dt_to = datetime(datetime.now().year,
                             datetime.now().month,
                             datetime.now().day, 23, 59, 59)
            ms_obj = start_of_month()
            month_start = datetime(ms_obj.year, ms_obj.month, ms_obj.day, 0, 0,
                                   0)
            et_obj = date.today() - timedelta(1)
            yt_from = datetime(et_obj.year, et_obj.month, et_obj.day, 0, 0, 0)
            yt_to = datetime(et_obj.year, et_obj.month, et_obj.day, 23, 59, 59)

            reply = "*Всего сообщений за:*\n"
            res = botdb.botstats.find({
                'dt': {
                    '$gte': dt_from,
                    '$lte': dt_to
                },
                'chat_id': chat_id
            })
            reply += "- сегодня: %d\n" % res.count()

            res = botdb.botstats.find({
                'dt': {
                    '$gte': dt_from,
                    '$lte': dt_to
                },
                'blya_counter': 1
            })
            reply += "Слово бл* написали %d раз\n" % res.count()
            res = botdb.botstats.aggregate([{
                "$match": {
                    'dt': {
                        '$gte': dt_from,
                        '$lte': dt_to
                    },
                    'blya_counter': 1,
                    'chat_id': chat_id
                }
            }, {
                "$group": {
                    "_id": "$name",
                    "total": {
                        "$sum": 1
                    }
                }
            }, {
                "$sort": {
                    "total": -1
                }
            }, {
                "$limit": 5
            }])
            reply += "\n*Топ 5 культурных людей:*\n"
            for r in res:
                reply += "@%s: %d\n" % (r['_id'], r['total'])
                if str(r['_id']) not in users:
                    users.append(str(r['_id']))

            res = botdb.botstats.aggregate([{
                "$match": {
                    'chat_id': chat_id
                }
            }, {
                "$group": {
                    "_id": "$name",
                    "total": {
                        "$sum": 1
                    }
                }
            }, {
                "$sort": {
                    "total": -1
                }
            }, {
                "$limit": 5
            }])
            reply += "\n*Топ 5 болтунов за все время:*\n"
            for r in res:
                reply += "@%s: %d\n" % (r['_id'], r['total'])
                if str(r['_id']) not in users:
                    users.append(str(r['_id']))
            m = 0

        elif msg[0] in ('Стоп', 'стоп', 'Хватит', 'хватит', 'Заткнись',
                        'заткнись', 'Молчи', 'молчи', 'Замолчи', 'замолчи'):
            reply = ""
        elif msg[0] in ('Test', 'test', 'тест', 'Тест'):
            m = 1
            reply = "Тест с пометкой @79261415371"
            users = ['79261415371']
        elif msg[0] in ('Пробей', 'пробей'):
            print("DEBUG: requests -> telegram")
            print("DEBUG: ", msg)
            api_id = 668594
            api_hash = '50c644ca8f583f0710a46209dac7f56c'
            tgclient = TelegramClient('session_name',
                                      api_id,
                                      api_hash,
                                      proxy=(socks.HTTP, 'easy-dns.ru', 3128,
                                             True, 'cli', 'clicli'))
            print("DEBUG: Telegram cli prestart!")
            try:
                tgclient.start()
                print("DEBUG: Telegram cli started!")
                with tgclient.conversation('AntiParkonBot') as conv:
                    num = msg[1]
                    if msg[1] == 'номер' and msg[2] and len(msg[2]):
                        num = msg[2]
                    conv.send_message(num)
                    reply = conv.get_response().raw_text
            except Exception as e:
                print("DEBUG: %s" % e)
                reply = "Нет связи с Telegram ботом. Коллега в запое."

            try:
                tgclient.disconnect()
                print("DEBUG: Telegram cli closed!")
            except Exception:
                pass

        elif msg[0] in ('Голос', 'голос', 'чип', 'Чип', 'Голосование',
                        'голосование', 'ЧИП'):
            reply = process_poll(msg, message_obj['sender']['id']['user'])

        else:
            # dialogflow
            print("Debug: dialogflow")
            request = apiai.ApiAI(
                '4278b35c7bc6411a8bc04adf22e3a5e7').text_request()
            request.lang = 'ru'
            request.session_id = '%s-%s' % (
                message_obj['sender']['id']['user'], chat_id)
            request.query = in_str
            responseJson = json.loads(
                request.getresponse().read().decode('utf-8'))
            response = responseJson['result']['fulfillment']['speech']
            #print ("Debug: ", responseJson)
            if response:
                reply = response.replace("<br>", "\n")
            #print ("Debug: ", responseJson)

    return reply, m, users
예제 #27
0
async def test_lang(client: TelegramClient):
    async with client.conversation(bot, timeout=5) as conv:
        await conv.send_message("/lang")
        resp = await conv.get_response()
        text = 'Выбери язык, сейчас установлен English:'
        assert text == resp.raw_text
예제 #28
0
from telethon import TelegramClient, sync

api_id = 627128
api_hash = 'b5033c8a72cf750833eeb12dced27266'

client = TelegramClient('testBot', api_id, api_hash).start()
bot = client.get_entity('DecideLocasteBoothBot')

print("Running test suite...")
import random

intrandom = random.randint(1, 100000000000)
username = "******" + str(intrandom)
with client.conversation(bot) as conv:
    conv.send_message('/start')
    welcome = conv.get_response().raw_text
    assert welcome == "Welcome!", "Missing Welcome message"
    explanation = conv.get_response().raw_text
    assert explanation == "I'm DecideLocasteBoothBot, the Telegram virtual booth assistant for Decide Locaste", "Missing bot explanation message"
    first = conv.get_response()
    assert first.raw_text == "First of all, you need to sign up or to log in with your Decide Locaste credentials in order to access your votings", "Missing sign up or login message"
    assert first.reply_markup != None, "Not showing actions buttons with Sign up, Log in and Cancel"

    conv.send_message('Mensaje fuera de lo esperado')
    catchall = conv.get_response().raw_text
    assert catchall == "Sorry It seems like I can not understand your petition", "Missing catch all message"

    conv.send_message('Sign up')
    work = conv.get_response().raw_text
    assert work == "Let's get to work", "Missing Let's get to work message"
    introduce_username_signup = conv.get_response().raw_text