Esempio n. 1
0
async def test_get_user_profile_photo(bot: Bot):
    """ getUserProfilePhotos method test """
    from .types.dataset import USER_PROFILE_PHOTOS, USER
    user = types.User(**USER)

    async with FakeTelegram(message_data=USER_PROFILE_PHOTOS):
        result = await bot.get_user_profile_photos(user_id=user.id, offset=1, limit=1)
        assert isinstance(result, types.UserProfilePhotos)
Esempio n. 2
0
async def test_get_me(bot: Bot, event_loop):
    """ getMe method test """
    from .types.dataset import USER
    user = types.User(**USER)

    async with FakeTelegram(message_dict=USER, loop=event_loop):
        result = await bot.me
        assert result == user
Esempio n. 3
0
def get_id_user(message: types.Message) -> types.User | None:
    text = message.text or message.caption or ""
    for word in text.lower().split():
        if word.startswith("id"):
            with suppress(ValueError):
                user_id = int(word.removeprefix("id"))
                return types.User(id=user_id)
    return None
Esempio n. 4
0
def check_target(target_user: dict, msg: types.Message):
    filter_rez = filter_check(msg, CONF_CANT_BE_SAME)
    assert filter_rez != {}, f"msg text {{{msg.text}}}"
    target_user = types.User(**target_user)
    founded_user = filter_rez["target"]
    if founded_user.id is None:
        assert founded_user.username == target_user.username, f"msg text {{{msg.text}}} user: {{{target_user}}}"
    else:
        assert founded_user == target_user, f"msg text {{{msg.text}}} user: {{{target_user}}}"
Esempio n. 5
0
async def test_unban_chat_member(bot: Bot, event_loop):
    """ unbanChatMember method test """
    from .types.dataset import USER, CHAT
    user = types.User(**USER)
    chat = types.Chat(**CHAT)

    async with FakeTelegram(message_dict=True, loop=event_loop):
        result = await bot.unban_chat_member(chat_id=chat.id, user_id=user.id)
        assert isinstance(result, bool)
        assert result is True
Esempio n. 6
0
async def save_user_karma(callback_query: types.CallbackQuery, callback_data: typing.Dict[str, str]):
    await callback_query.answer()
    index = int(callback_data["index"])
    chat_id = int(callback_data["chat_id"])
    elem = get_element_approve(index)
    user_tg = types.User(**json.loads(elem['founded_user']))

    user = await User.get_or_create_from_tg_user(user_tg)
    await save_karma(user, chat_id, elem['karma'])
    await callback_query.message.edit_text(**next_approve(get_element_approve(index + 1), index + 1, chat_id))
Esempio n. 7
0
async def test_kick_chat_member(bot: Bot):
    """ kickChatMember method test """
    from .types.dataset import USER, CHAT
    user = types.User(**USER)
    chat = types.Chat(**CHAT)

    async with FakeTelegram(message_data=True):
        result = await bot.kick_chat_member(chat_id=chat.id, user_id=user.id, until_date=123)
        assert isinstance(result, bool)
        assert result is True
Esempio n. 8
0
async def test_promote_chat_member(bot: Bot):
    """ promoteChatMember method test """
    from .types.dataset import USER, CHAT
    user = types.User(**USER)
    chat = types.Chat(**CHAT)

    async with FakeTelegram(message_data=True):
        result = await bot.promote_chat_member(chat_id=chat.id, user_id=user.id, can_change_info=True,
                                               can_delete_messages=True, can_edit_messages=True,
                                               can_invite_users=True, can_pin_messages=True, can_post_messages=True,
                                               can_promote_members=True, can_restrict_members=True)
        assert isinstance(result, bool)
        assert result is True
Esempio n. 9
0
def get_mentioned_user(message: types.Message) -> typing.Optional[types.User]:
    possible_mentioned_text = message.text or message.caption
    if not possible_mentioned_text:
        return None
    entities = message.entities or message.caption_entities
    if not entities:
        return None
    for ent in entities:
        if ent.type == "text_mention":
            return ent.user
        elif ent.type == "mention":
            username = ent.get_text(possible_mentioned_text).lstrip("@")
            return types.User(username=username)
    return None
Esempio n. 10
0
async def test_restrict_chat_member(bot: Bot, event_loop):
    """ restrictChatMember method test """
    from .types.dataset import USER, CHAT
    user = types.User(**USER)
    chat = types.Chat(**CHAT)

    async with FakeTelegram(message_dict=True, loop=event_loop):
        result = await bot.restrict_chat_member(
            chat_id=chat.id,
            user_id=user.id,
            can_add_web_page_previews=False,
            can_send_media_messages=False,
            can_send_messages=False,
            can_send_other_messages=False,
            until_date=123)
        assert isinstance(result, bool)
        assert result is True
Esempio n. 11
0
    def chat_and_user_from_update(
            self,
            update: Optional[types.Message]) -> Tuple[types.Chat, types.User]:
        chat = types.Chat()
        user = types.User()
        if update is None:
            return chat, user

        if update.message:
            user = update.message.from_user
            chat = update.message.chat

        elif update.edited_message:
            user = update.edited_message.from_user
            chat = update.edited_message.chat

        elif update.channel_post:
            chat = update.channel_post.chat

        elif update.edited_channel_post:
            chat = update.edited_channel_post.chat

        elif update.inline_query:
            user = update.inline_query.from_user

        elif update.chosen_inline_result:
            user = update.chosen_inline_result.from_user

        elif update.callback_query:
            if update.callback_query.message:
                chat = update.callback_query.message.chat
            user = update.callback_query.from_user

        elif update.shipping_query:
            user = update.shipping_query.from_user

        elif update.pre_checkout_query:
            user = update.pre_checkout_query.from_user

        elif update.poll:
            pass

        elif update.poll_answer:
            pass

        return chat, user
Esempio n. 12
0
    @staticmethod
    def state(func) -> AsyncFunction:
        @functools.wraps(func)
        async def wrapper(*args, state=None, **kwargs):
            if state is None:
                state = await get_current_state()
            return await func(*args, **kwargs, state=state)

        return wrapper


if __name__ == '__main__':
    from asyncio import run
    from pprint import pp

    types.User.set_current(types.User(id=123))

    @SetCurrent.user
    @SetCurrent.dp
    @SetCurrent.msg
    @SetCurrent.chat
    @SetCurrent.query
    @SetCurrent.inline_query
    @SetCurrent.bot
    @SetCurrent.udata
    @SetCurrent.raw_state
    @SetCurrent.state
    async def test(**kwargs):
        pp(kwargs)

    run(test(dp=2, chat=3, state='ask_price'))
Esempio n. 13
0
from babel import Locale

from aiogram import types
from .dataset import USER

user = types.User(**USER)


def test_export():
    exported = user.to_python()
    assert isinstance(exported, dict)
    assert exported == USER


def test_id():
    assert isinstance(user.id, int)
    assert user.id == USER['id']
    # assert hash(user) == USER['id']


def test_bot():
    assert isinstance(user.is_bot, bool)
    assert user.is_bot == USER['is_bot']


def test_name():
    assert user.first_name == USER['first_name']
    assert user.last_name == USER['last_name']
    assert user.username == USER['username']

Esempio n. 14
0
async def show_order(
    order: typing.Mapping[str, typing.Any],
    chat_id: int,
    user_id: int,
    message_id: typing.Optional[int] = None,
    location_message_id: typing.Optional[int] = None,
    show_id: bool = False,
    invert: typing.Optional[bool] = None,
    edit: bool = False,
    locale: typing.Optional[str] = None,
):
    """Send detailed order.

    :param order: Order document.
    :param chat_id: Telegram ID of chat to send message to.
    :param user_id: Telegram user ID of message receiver.
    :param message_id: Telegram ID of message to edit.
    :param location_message_id: Telegram ID of message with location object.
        It is deleted when **Hide** inline button is pressed.
    :param show_id: Add ID of order to the top.
    :param invert: Invert price.
    :param edit: Enter edit mode.
    :param locale: Locale of message receiver.
    """
    if locale is None:
        locale = i18n.ctx_locale.get()

    new_edit_msg = None
    if invert is None:
        user = await database.users.find_one({"id": user_id})
        invert = user.get("invert_order", False)
    else:
        user = await database.users.find_one_and_update(
            {"id": user_id}, {"$set": {
                "invert_order": invert
            }})
        if "edit" in user:
            if edit:
                if user["edit"]["field"] == "price":
                    new_edit_msg = i18n(
                        "new_price {of_currency} {per_currency}",
                        locale=locale)
                    if invert:
                        new_edit_msg = new_edit_msg.format(
                            of_currency=order["buy"],
                            per_currency=order["sell"])
                    else:
                        new_edit_msg = new_edit_msg.format(
                            of_currency=order["sell"],
                            per_currency=order["buy"])
            elif user["edit"]["order_message_id"] == message_id:
                await tg.delete_message(user["chat"],
                                        user["edit"]["message_id"])
                await database.users.update_one(
                    {"_id": user["_id"]},
                    {"$unset": {
                        "edit": True,
                        STATE_KEY: True
                    }})

    if location_message_id is None:
        if order.get("lat") is not None and order.get("lon") is not None:
            location_message = await tg.send_location(chat_id, order["lat"],
                                                      order["lon"])
            location_message_id = location_message.message_id
        else:
            location_message_id = -1

    header = ""
    if show_id:
        header += "ID: {}\n".format(markdown.code(order["_id"]))

    if order.get("archived"):
        header += markdown.bold(i18n("archived", locale=locale)) + "\n"

    creator = await database.users.find_one({"id": order["user_id"]})
    header += "{} ({}) ".format(
        markdown.link(creator["mention"],
                      types.User(id=creator["id"]).url),
        markdown.code(creator["id"]),
    )
    if invert:
        act = i18n("sells {sell_currency} {buy_currency}", locale=locale)
    else:
        act = i18n("buys {buy_currency} {sell_currency}", locale=locale)
    header += act.format(buy_currency=order["buy"],
                         sell_currency=order["sell"]) + "\n"

    lines = [header]
    field_names = {
        "sum_buy": i18n("buy_amount", locale=locale),
        "sum_sell": i18n("sell_amount", locale=locale),
        "price": i18n("price", locale=locale),
        "payment_system": i18n("payment_system", locale=locale),
        "duration": i18n("duration", locale=locale),
        "comments": i18n("comments", locale=locale),
    }
    lines_format: typing.Dict[str, typing.Optional[str]] = {}
    for name in field_names:
        lines_format[name] = None

    if "sum_buy" in order:
        lines_format["sum_buy"] = "{} {}".format(order["sum_buy"],
                                                 order["buy"])
    if "sum_sell" in order:
        lines_format["sum_sell"] = "{} {}".format(order["sum_sell"],
                                                  order["sell"])
    if "price_sell" in order:
        if invert:
            lines_format["price"] = "{} {}/{}".format(order["price_buy"],
                                                      order["buy"],
                                                      order["sell"])
        else:
            lines_format["price"] = "{} {}/{}".format(order["price_sell"],
                                                      order["sell"],
                                                      order["buy"])
    if "payment_system" in order:
        lines_format["payment_system"] = order["payment_system"]
    if "duration" in order:
        lines_format["duration"] = "{} - {}".format(
            datetime.utcfromtimestamp(
                order["start_time"]).strftime("%d.%m.%Y"),
            datetime.utcfromtimestamp(
                order["expiration_time"]).strftime("%d.%m.%Y"),
        )
    if "comments" in order:
        lines_format["comments"] = "«{}»".format(order["comments"])

    keyboard = types.InlineKeyboardMarkup(row_width=6)

    keyboard.row(
        types.InlineKeyboardButton(
            i18n("invert", locale=locale),
            callback_data="{} {} {} {}".format(
                "revert" if invert else "invert",
                order["_id"],
                location_message_id,
                int(edit),
            ),
        ))

    if edit and creator["id"] == user_id:
        buttons = []
        for i, (field, value) in enumerate(lines_format.items()):
            if value is not None:
                lines.append(f"{i + 1}. {field_names[field]} {value}")
            else:
                lines.append(f"{i + 1}. {field_names[field]} -")
            buttons.append(
                types.InlineKeyboardButton(
                    f"{i + 1}",
                    callback_data="edit {} {} {} 0".format(
                        order["_id"], field, location_message_id),
                ))

        keyboard.add(*buttons)
        keyboard.row(
            types.InlineKeyboardButton(
                i18n("finish", locale=locale),
                callback_data="{} {} {} 0".format(
                    "invert" if invert else "revert", order["_id"],
                    location_message_id),
            ))

    else:
        for field, value in lines_format.items():
            if value is not None:
                lines.append(field_names[field] + " " + value)

        keyboard.row(
            types.InlineKeyboardButton(
                i18n("similar", locale=locale),
                callback_data="similar {}".format(order["_id"]),
            ),
            types.InlineKeyboardButton(
                i18n("match", locale=locale),
                callback_data="match {}".format(order["_id"]),
            ),
        )

        if creator["id"] == user_id:
            keyboard.row(
                types.InlineKeyboardButton(
                    i18n("edit", locale=locale),
                    callback_data="{} {} {} 1".format(
                        "invert" if invert else "revert",
                        order["_id"],
                        location_message_id,
                    ),
                ),
                types.InlineKeyboardButton(
                    i18n("delete", locale=locale),
                    callback_data="delete {} {}".format(
                        order["_id"], location_message_id),
                ),
            )
            keyboard.row(
                types.InlineKeyboardButton(
                    i18n("unarchive", locale=locale) if order.get("archived")
                    else i18n("archive", locale=locale),
                    callback_data="archive {} {}".format(
                        order["_id"], location_message_id),
                ),
                types.InlineKeyboardButton(
                    i18n("change_duration", locale=locale),
                    callback_data="edit {} duration {} 1".format(
                        order["_id"], location_message_id),
                ),
            )
        elif "price_sell" in order:
            if (get_escrow_instance(order["buy"]) is not None
                    or get_escrow_instance(order["sell"]) is not None):
                keyboard.row(
                    types.InlineKeyboardButton(
                        i18n("escrow", locale=locale),
                        callback_data="escrow {} sum_buy 0".format(
                            order["_id"]),
                    ))

        keyboard.row(
            types.InlineKeyboardButton(
                i18n("hide", locale=locale),
                callback_data="hide {}".format(location_message_id),
            ))

    answer = "\n".join(lines)

    if message_id is not None:
        await tg.edit_message_text(
            answer,
            chat_id,
            message_id,
            reply_markup=keyboard,
            parse_mode=types.ParseMode.MARKDOWN,
            disable_web_page_preview=True,
        )
        if new_edit_msg is not None:
            keyboard = types.InlineKeyboardMarkup()
            keyboard.row(
                types.InlineKeyboardButton(i18n("unset", locale=locale),
                                           callback_data="unset"))
            await tg.edit_message_text(
                new_edit_msg,
                chat_id,
                user["edit"]["message_id"],
                reply_markup=keyboard,
            )
    else:
        await tg.send_message(
            chat_id,
            answer,
            reply_markup=keyboard,
            parse_mode=types.ParseMode.MARKDOWN,
            disable_web_page_preview=True,
        )