Beispiel #1
0
async def controller(event_loop):
    """
    Session-scoped fixture that all tests use to receive their BotController instance
    """
    print("Initializing...")
    examples_dir = Path(__file__).parent.parent

    # Using the configuration of `config.ini` (see examples/README)
    client = InteractionClient(
        session_name="my_account",
        global_action_delay=1.8,  # Space out all messages by 1.8 seconds
        workdir=examples_dir,  # Load configuration from parent folder
        config_file=os.path.join(examples_dir, "config.ini"),
    )

    controller = BotController(
        bot_under_test="@BotListBot",
        client=client,
        min_wait_consecutive=
        2.0,  # Wait at least 2 seconds to collect more than one message
        max_wait_response=10,  # Wait a max of 10 seconds for responses, ...
        raise_no_response=
        False,  # ... then check for response.empty instead of raising
    )

    print("Starting integration test service...")
    await controller.start()
    # event_loop.run_until_complete(controller.start())
    print("Client ready.")

    yield controller  # py.test sugar to separate setup from teardown

    # Teardown
    await controller.stop()
Beispiel #2
0
def create_game_controller(client: Client = None) -> BotController:
    return BotController(
        peer="@IdleTownBot",
        client=client or create_client(),
        global_action_delay=2.0,  # The @IdleTownBot has a spam limit of about 1.9s
        max_wait=8,  # Maximum time in seconds to wait for a response from the bot
        wait_consecutive=None,  # Do not wait for more than one message
    )
Beispiel #3
0
async def controller(client):
    c = BotController(
        client=client,
        peer="@WtfTicketsBot",
        max_wait=8.0,
        wait_consecutive=0.8,
    )
    await c.initialize(start_client=False)
    yield c
Beispiel #4
0
async def run_example(client: Client):
    controller = BotController(
        peer="@StatInfoTestBot",
        client=client,
        max_wait=8,  # Maximum timeout for responses (optional)
        wait_consecutive=
        2,  # Minimum time to wait for more/consecutive messages (optional)
        raise_no_response=
        True,  # Raise `InvalidResponseError` when no response received (defaults to True)
        global_action_delay=
        2.5,  # Choosing a rather high delay so we can follow along in realtime (optional)
    )

    # expecting 2 messages in reply for /start command
    async with controller.collect(count=2) as response:  # type: Response
        await controller.send_command("start")

    assert response.num_messages == 2

    async with controller.collect(count=1) as response:  # type: Response
        await controller.send_command("help")

    assert response.num_messages == 1
    assert "The following commands are available" in response.full_text

    async with controller.collect(count=1) as response:  # type: Response
        await controller.send_command("statistics")

    assert response.num_messages == 1

    # expecting to get statistics for today
    current_date = str(date.today())
    assert current_date in response.full_text

    async with controller.collect(count=1) as response:  # type: Response
        await controller.send_command("country")

    assert response.num_messages == 1
    assert "Please, enter country name." in response.full_text

    async with controller.collect(count=1) as response:  # type: Response
        await client.send_message(controller.peer_id, "Russian Federation")

    assert response.num_messages == 1
    assert "Russian Federation" in response.full_text

    async with controller.collect(count=1) as response:  # type: Response
        await controller.send_command("contacts")

    assert response.num_messages == 1
    assert "4 members" in response.full_text

    async with controller.collect(count=1) as response:  # type: Response
        await client.send_message(controller.peer_id, "hi")

    assert response.num_messages == 1
    assert "To get to know me better" in response.full_text
Beispiel #5
0
async def controller(client):
    c = BotController(
        client=client,
        peer=bot_name,
        #peer="@BotListBot",
        max_wait=10.0,
        wait_consecutive=0.8,
    )
    await c.initialize(start_client=False)
    yield c
Beispiel #6
0
async def controller(client):
    c = BotController(
        client=client,
        peer=
        "@CovidReportsBot",  # We are going to run tests on https://t.me/CovidReportsBot
        max_wait=10.0,  # Maximum timeout for responses (optional)
        wait_consecutive=
        0.8,  # Minimum time to wait for more/consecutive messages (optional)
    )

    await c.clear_chat()
    await c.initialize(start_client=False)
    yield c
    def __init__(self, session_name, log_level=logging.INFO):
        self.purchase_balance = None
        self.withdrawal_balance = None
        self.diamonds = None

        self.menu = None  # type: Optional[ReplyKeyboard]
        self.logger = logging.getLogger(self.__class__.__name__)
        self.logger.setLevel(log_level)

        client = InteractionClient(session_name=session_name,
                                   global_action_delay=1.0,
                                   config_file=os.path.join(
                                       examples_dir, 'config.ini'))

        self.controller = BotController(bot_under_test='@DinoParkNextBot',
                                        client=client)

        self.controller.start()

        self._update_keyboard()
        self.update_balance()
Beispiel #8
0
from pyrogram import filters as f

from tgintegration import BotController

examples_dir = Path(__file__).parent
print(examples_dir)

# This example uses the configuration of `config.ini` (see examples/README)
client = Client(
    "tgintegration_examples",
    config_file=str(examples_dir / "config.ini"),
    workdir=str(examples_dir),
)


controller = BotController(peer="@deerspangle", client=client, raise_no_response=False)


async def main():
    await controller.initialize()

    while True:
        async with controller.collect(
            f.chat("@TgIntegration"), max_wait=30
        ) as response:
            await client.send_message(
                "@TgIntegration",
                "Hi @deerspangle! Please say something in the next 30 seconds...",
            )

        await client.send_message(
Beispiel #9
0
async def run_example(client: Client):
    controller = BotController(
        peer=
        "@BotListBot",  # We are going to run tests on https://t.me/BotListBot
        client=client,
        max_wait=8,  # Maximum timeout for responses (optional)
        wait_consecutive=
        2,  # Minimum time to wait for more/consecutive messages (optional)
        raise_no_response=
        True,  # Raise `InvalidResponseError` when no response received (defaults to True)
        global_action_delay=
        2.5,  # Choosing a rather high delay so we can follow along in realtime (optional)
    )

    print("Clearing chat to start with a blank screen...")
    await controller.clear_chat()

    print("Sending /start and waiting for exactly 3 messages...")
    async with controller.collect(count=3) as response:  # type: Response
        await controller.send_command("start")

    assert response.num_messages == 3
    print("Three messages received, bundled as a `Response`.")
    assert response.messages[0].sticker
    print("First message is a sticker.")

    print("Let's examine the buttons in the response...")
    inline_keyboard = response.inline_keyboards[0]
    assert len(inline_keyboard.rows[0]) == 3
    print("Yep, there are three buttons in the first row.")

    # We can also press the inline keyboard buttons, in this case based on a pattern:
    print("Clicking the button matching the regex r'.*Examples'")
    examples = await inline_keyboard.click(pattern=r".*Examples")

    assert "Examples for contributing to the BotList" in examples.full_text
    # As the bot edits the message, `.click()` automatically listens for "message edited"
    # updates and returns the new state as `Response`.

    print(
        "So what happens when we send an invalid query or the peer fails to respond?"
    )
    from tgintegration import InvalidResponseError

    try:
        # The following instruction will raise an `InvalidResponseError` after
        # `controller.max_wait` seconds. This is because we passed `raise_no_response=True`
        # during controller initialization.
        print("Expecting unhandled command to raise InvalidResponseError...")
        async with controller.collect():
            await controller.send_command("ayylmao")
    except InvalidResponseError:
        print("Ok, raised as expected.")

    # If `raise_` is explicitly set to False, no exception is raised
    async with controller.collect(raise_=False) as response:  # type: Response
        print("Sending a message but expecting no reply...")
        await client.send_message(controller.peer_id, "Henlo Fren")

    # In this case, tgintegration will simply emit a warning, but you can still assert
    # that no response has been received by using the `is_empty` property.
    assert response.is_empty

    print("Success!")
"""
Full version of the GitHub README.
"""
import asyncio
from tgintegration import BotController, InteractionClient

print("Initializing service...")
# This example uses the configuration of `config.ini` (see examples/README)
client = InteractionClient(
    session_name="tgintegration_examples"  # Arbitrary file path to the Pyrogram session file
)

controller = BotController(
    bot_under_test="@BotListBot",
    client=client,
    max_wait_response=8,  # Maximum timeout for bot responses
    min_wait_consecutive=2,  # Minimum time to wait for consecutive messages
    raise_no_response=True,  # Raise `InvalidResponseError` when no response received
)


async def main():

    print("Starting...")
    await controller.start()

    print("Clearing chat to start with a blank screen...")
    await controller.clear_chat()

    print("Send the /start command to the bot_under_test and 'await' exactly three messages...")
    response = await controller.send_command_await("start", num_expected=3)
Beispiel #11
0
import os
import asyncio
from tgintegration import BotController, InteractionClient

loop = asyncio.get_event_loop()

client = InteractionClient(
    session_name='test_bot',  # Arbitrary file path to the Pyrogram session file
    api_id=os.environ.get('BOT_API_ID'),  # See "Requirements" above, ...
    api_hash=os.environ.get(
        'BOT_API_HASH'),  # alternatively use a `config.ini` file
)

client = BotController(
    bot_under_test='@Shop_final_task_bot',
    client=client,
    max_wait_response=15,  # Maximum timeout for bot re_sponses
    min_wait_consecutive=2  # Minimum time to wait for consecutive messages
)


async def test():
    await client.start()
    await client.clear_chat()

    response = await client.send_command_await('start', num_expected=1)

    assert response.num_messages == 1
    assert 'Dear customer!' in response.messages[0].text

    inline_keyboard = response.inline_keyboards[0]
    assert len(inline_keyboard.rows[0]) == 2
Beispiel #12
0
async def main():
    # This example uses the configuration of `config.ini` (see examples/README)
    client = InteractionClient(
        session_name=SESSION_NAME,
        global_action_delay=
        2.3,  # The @IdleTownBot has a spam limit of about 1.9s
        workdir=examples_dir,  # Load configuration from parent folder
        config_file=os.path.join(examples_dir, "config.ini"),
    )

    controller = BotController(
        bot_under_test="@IdleTownBot",
        client=client,
        max_wait_response=
        15,  # Maximum time in seconds to wait for a response from the bot
        min_wait_consecutive=None,  # Do not wait for more than one message
    )

    client.load_config()

    await controller.start()
    for _ in range(MAX_RUNS or 999999):
        try:
            # Setup
            await controller.clear_chat()
            await asyncio.sleep(2)
            start = await controller.send_command_await("start")

            # Extract keyboard buttons of /start response
            main_buttons = get_buttons(start)

            # Get World Exp if possible
            if "worldexp" in main_buttons:
                worldexp = await controller.send_message_await(
                    main_buttons["worldexp"])
                confirm_buttons = get_buttons(
                    await controller.send_message_await(
                        get_buttons(worldexp)["claimx1"]))
                await controller.send_message_await(confirm_buttons["yes"])

            # Construct buildings
            build_buttons = get_buttons(await controller.send_message_await(
                main_buttons["buildings"]))

            for building in ["lumbermill", "goldmine", "armory", "smithy"]:
                response_text = ""
                while "you don't have enough" not in response_text.lower():
                    response_text = (await controller.send_message_await(
                        build_buttons[building])).full_text

            # Upgrade Hero Equipment
            hero = get_buttons(await controller.send_message_await(
                main_buttons["hero"]))
            equip_buttons = get_buttons(await controller.send_message_await(
                hero["equipment"]))

            # For every possible equipment, upgrade it until there are not enough resources left
            for equip in (b for k, b in equip_buttons.items() if "up" in k):
                while True:
                    response_text = (
                        await controller.send_message_await(equip)).full_text
                    if "you don't have enough" in response_text.lower():
                        break

            # Attack Player
            battle = get_buttons(await controller.send_message_await(
                main_buttons["battle"]))
            arena = get_buttons(await
                                controller.send_message_await(battle["arena"]))
            normal_match = get_buttons(await controller.send_message_await(
                arena["normalmatch"]))

            if "fight" in normal_match:
                fight = get_buttons(await controller.send_message_await(
                    normal_match["fight"]))

            # Attack Boss
            bosses = get_buttons(await
                                 controller.send_message_await(battle["bosses"]
                                                               ))
            if "attackmax" in bosses:
                await controller.send_message_await(bosses["attackmax"])
        except KeyboardInterrupt:
            print("Done.")
            break
        except:
            traceback.print_exc()
            pass

    await client.stop()
Beispiel #13
0
async def controller(client, bot) -> BotController:
    bot_user = await bot.client.get_me()
    controller = BotController(peer=bot_user.username, client=client)
    await controller.initialize(start_client=False)
    return controller