def setUp(self): self.reserves = [] self.strings = RuReserve self.chat = Chat() self.chat.id = 101 self.user = User() self.user.first_name = "Firstname" self.user.id = 111 dp = Dispatcher() self.data_adapter = MemoryDataAdapter() self.state_manager = StateManager(self.data_adapter) self.processor = ReserveProcessor(dp, self.state_manager, self.strings) message = Message() message.chat = self.chat message.from_user = self.user message.message_id = 121 message.text = "Some text" message.answer = self.answer_mock message.delete = self.delete_mock message.edit_text = self.edit_text_mock self.test_message = message callback = CallbackQuery() callback.bot = Bot() callback.answer = self.callback_answer_mock callback.message = message callback.from_user = User() callback.from_user.id = 101 self.test_callback_query = callback
def bg( self, user_id: Optional[int] = None, chat_id: Optional[int] = None, stack_id: Optional[str] = None, ) -> "BaseDialogManager": if user_id is not None: user = User(id=user_id) else: user = self.user if chat_id is not None: chat = Chat(id=chat_id) else: chat = self.chat same_chat = (user.id == self.user.id and chat.id == self.chat.id) if stack_id is None: if same_chat: stack_id = self.stack_id intent_id = self.intent_id else: stack_id = DEFAULT_STACK_ID intent_id = None else: intent_id = None return BgManager( user=user, chat=chat, bot=self.bot, registry=self.registry, intent_id=intent_id, stack_id=stack_id, )
async def full_card_number_sent(call: types.CallbackQuery, offer: EscrowOffer): """Confirm that full card number is sent and ask for first and last 4 digits.""" await offer.update_document( {"$set": { "pending_input_from": call.from_user.id }}) await call.answer() if call.from_user.id == offer.init["id"]: counter = offer.counter await tg.send_message( counter["id"], i18n("ask_address {currency}").format(currency=offer.buy)) await tg.send_message( call.message.chat.id, i18n("exchange_continued {user}").format( user=markdown.link(counter["mention"], User(id=counter["id"]).url)), parse_mode=ParseMode.MARKDOWN, ) await offer.update_document( {"$set": { "pending_input_from": counter["id"] }}) counter_state = FSMContext(dp.storage, counter["id"], counter["id"]) await counter_state.set_state(states.Escrow.receive_address.state) await states.Escrow.receive_card_number.set() else: await tg.send_message( call.message.chat.id, i18n("send_first_and_last_4_digits_of_card_number {currency}"). format(currency=offer.sell if offer.type == "buy" else offer.buy), ) await states.Escrow.receive_card_number.set()
async def test_replies_with_correct_user_mention(self, bot, odesli_api): """Send a reply with correct user mention for a user without username. """ message = make_mock_message( text='check this one: https://www.deezer.com/track/1') message.from_user = User( id=1, is_bot=False, first_name='test_first_name', last_name='test_last_name', username=None, language_code='ru', ) reply_text = ( '<b><a href="tg://user?id=1">test_first_name test_last_name</a> ' 'wrote:</b> check this one: [1]\n' '\n' '1. Test Artist 1 - Test Title 1\n' '<a href="https://www.test.com/d">Deezer</a> | ' '<a href="https://www.test.com/g">Google Music</a> | ' '<a href="https://www.test.com/sc">SoundCloud</a> | ' '<a href="https://www.test.com/yn">Yandex Music</a> | ' '<a href="https://www.test.com/s">Spotify</a> | ' '<a href="https://www.test.com/ym">YouTube Music</a> | ' '<a href="https://www.test.com/y">YouTube</a> | ' '<a href="https://www.test.com/am">Apple Music</a> | ' '<a href="https://www.test.com/t">Tidal</a>') await bot.dispatcher.message_handlers.notify(message) assert message.reply.called_with_text == reply_text
def bg( self, user_id: Optional[int] = None, chat_id: Optional[int] = None, stack_id: Optional[str] = None, ) -> "BaseDialogManager": if user_id is not None: user = User(id=user_id) else: user = self.event.from_user if chat_id is not None: chat = Chat(id=chat_id) else: chat = get_chat(self.event) same_chat = (user.id == self.event.from_user.id and chat.id == get_chat(self.event).id) intent_id = None if stack_id is None: if same_chat: stack_id = self.current_stack().id if self.current_context(): intent_id = self.current_context().id else: stack_id = DEFAULT_STACK_ID return BgManager( user=user, chat=chat, bot=self.event.bot, registry=self.registry, intent_id=intent_id, stack_id=stack_id, )
def bg(self, user_id: Optional[int] = None, chat_id: Optional[int] = None) -> BgManagerProto: if self.disabled: raise IncorrectBackgroundError("Please call `manager.bg()` " "before starting background task") self.check_disabled() if user_id is not None: user = User(id=user_id) else: user = self.event.from_user if chat_id is not None: chat = Chat(id=chat_id) else: chat = get_chat(self.event) return BgManager( user, chat, self.event.bot, self.registry, self.current_intent(), self.context.state, )
def get_aiogram_user_by_pyrogram(user: pyrogram.types.User) -> User: return User( id=user.id, is_bot=user.is_bot, first_name=user.first_name, last_name=user.last_name, username=user.username, language_code=user.language_code, )
def make_mock_message( text: str, chat_type: ChatType = ChatType.GROUP, raise_on_delete: bool = False, inline: bool = False, is_reply: bool = False, ) -> mock.Mock: """Make a mock message with given text. :param text: text of the message :param chat_type: chat type. See `aiogram.types.ChatType` enum :param raise_on_delete: raise exception on message delete :param inline: message is an inline query :param is_reply: message is a reply :return: mock message """ spec = InlineQuery if inline else Message message = mock.Mock(spec=spec) message.content_type = ContentType.TEXT if inline: message.query = text message.message_id = 'id' else: message.text = text message.from_user = User( id=1, is_bot=False, first_name=None, last_name='TestLastName', username='******', language_code='ru', ) message.chat = mock.Mock(spec=Chat) message.chat.type = chat_type types.User.set_current(message.from_user) types.Chat.set_current(message.chat) async def reply_mock_fn(text, parse_mode, reply=True): """Reply mock.""" assert parse_mode == 'HTML' assert reply == is_reply # Save text argument for assertion reply_mock.called_with_text = text reply_mock = mock.Mock(side_effect=reply_mock_fn) message.reply = reply_mock async def delete_mock_fn(): """Delete mock.""" if raise_on_delete: raise MessageCantBeDeleted(message='Test exception') delete_mock = mock.Mock(side_effect=delete_mock_fn) message.delete = delete_mock return message
async def full_card_number_message(message: types.Message, offer: EscrowOffer): """React to sent message while sending full card number to fiat sender.""" if message.from_user.id == offer.init["id"]: user = offer.counter else: user = offer.init mention = markdown.link(user["mention"], User(id=user["id"]).url) await tg.send_message( message.chat.id, i18n("wrong_full_card_number_receiver {user}").format(user=mention), parse_mode=ParseMode.MARKDOWN, )
def setUp(self): self.data_adapter = MemoryDataAdapter() self.state_provider.data_adapter = self.data_adapter self.chat = Chat() self.chat.id = 101 self.user = User() self.user.id = 111 state_data1 = {"state": "main", "state_type": "reserve"} state_data2 = {"state": "book", "state_type": "reserve"} self.data_adapter.append_data("101-111-121", state_data1) self.data_adapter.append_data("101-111-122", state_data2)
async def validate_offer(call: types.CallbackQuery, offer: EscrowOffer): """Ask support for manual verification of exchange.""" if offer.type == "buy": sender = offer.counter receiver = offer.init currency = offer.sell elif offer.type == "sell": sender = offer.init receiver = offer.counter currency = offer.buy escrow_instance = get_escrow_instance(offer.escrow) answer = "{0}\n{1} sender: {2}{3}\n{1} receiver: {4}{5}\nBank: {6}\nMemo: {7}" answer = answer.format( markdown.link("Unconfirmed escrow.", escrow_instance.trx_url(offer.trx_id)), currency, markdown.link(sender["mention"], User(id=sender["id"]).url), " ({})".format(sender["name"]) if "name" in sender else "", markdown.link(receiver["mention"], User(id=receiver["id"]).url), " ({})".format(receiver["name"]) if "name" in receiver else "", offer.bank, markdown.code(offer.memo), ) await tg.send_message(config.SUPPORT_CHAT_ID, answer, parse_mode=ParseMode.MARKDOWN) await offer.delete_document() await call.answer() await tg.send_message( call.message.chat.id, i18n("request_validation_promise"), reply_markup=start_keyboard(), )
def bg(self, user_id: Optional[int] = None, chat_id: Optional[int] = None) -> BgManagerProto: if user_id is not None: user = User(id=user_id) else: user = self.user if chat_id is not None: chat = Chat(id=chat_id) else: chat = self.chat return BgManager( user, chat, self.bot, self.registry, self.current_intent(), self.current_state, )
def get_current_user(): """Returns current user instance""" return User().get_current()
async def set_init_send_address(address: str, message: types.Message, offer: EscrowOffer): """Set ``address`` as sender's address of initiator. Send offer to counteragent. """ locale = offer.counter["locale"] buy_keyboard = InlineKeyboardMarkup() buy_keyboard.row( InlineKeyboardButton(i18n("show_order", locale=locale), callback_data=f"get_order {offer.order}")) buy_keyboard.add( InlineKeyboardButton(i18n("accept", locale=locale), callback_data=f"accept {offer._id}"), InlineKeyboardButton(i18n("decline", locale=locale), callback_data=f"decline {offer._id}"), ) mention = markdown.link(offer.init["mention"], User(id=offer.init["id"]).url) answer = i18n( "escrow_offer_notification {user} {sell_amount} {sell_currency} " "for {buy_amount} {buy_currency}", locale=locale, ).format( user=mention, sell_amount=offer.sum_sell, sell_currency=offer.sell, buy_amount=offer.sum_buy, buy_currency=offer.buy, ) if offer.bank: answer += " " + i18n("using {bank}", locale=locale).format(bank=offer.bank) answer += "." update_dict = {"init.send_address": address} if offer.type == "sell": insured = await get_insurance(offer) update_dict["insured"] = Decimal128(insured) if offer[f"sum_{offer.type}"].to_decimal() > insured: answer += "\n" + i18n( "exceeded_insurance {amount} {currency}").format( amount=insured, currency=offer.escrow) await offer.update_document({ "$set": update_dict, "$unset": { "pending_input_from": True } }) await tg.send_message( offer.counter["id"], answer, reply_markup=buy_keyboard, parse_mode=ParseMode.MARKDOWN, ) sell_keyboard = InlineKeyboardMarkup() sell_keyboard.add( InlineKeyboardButton(i18n("cancel"), callback_data=f"escrow_cancel {offer._id}")) await tg.send_message(message.from_user.id, i18n("offer_sent"), reply_markup=sell_keyboard) await dp.current_state().finish()
def user(self): return User().get_current()
async def ask_credentials( call: types.CallbackQuery, offer: EscrowOffer, ): """Update offer with ``update_dict`` and start asking transfer information. Ask to choose bank if user is initiator and there is a fiat currency. Otherwise ask receive address. """ await call.answer() is_user_init = call.from_user.id == offer.init["id"] has_fiat_currency = "RUB" in {offer.buy, offer.sell} if has_fiat_currency: if is_user_init: keyboard = InlineKeyboardMarkup() for bank in SUPPORTED_BANKS: keyboard.row( InlineKeyboardButton( bank, callback_data=f"bank {offer._id} {bank}")) await tg.send_message(call.message.chat.id, i18n("choose_bank"), reply_markup=keyboard) await states.Escrow.bank.set() else: if offer.type == "buy": request_user = offer.init answer_user = offer.counter currency = offer.sell else: request_user = offer.counter answer_user = offer.init currency = offer.buy keyboard = InlineKeyboardMarkup() keyboard.add( InlineKeyboardButton(i18n("sent"), callback_data=f"card_sent {offer._id}")) mention = markdown.link(answer_user["mention"], User(id=answer_user["id"]).url) await tg.send_message( request_user["id"], i18n( "request_full_card_number {currency} {user}", locale=request_user["locale"], ).format(currency=currency, user=mention), reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN, ) state = FSMContext(dp.storage, request_user["id"], request_user["id"]) await state.set_state(states.Escrow.full_card.state) answer = i18n( "asked_full_card_number {user}", locale=answer_user["locale"]).format( user=markdown.link(request_user["mention"], User(id=request_user["id"]).url)) await tg.send_message( answer_user["id"], answer, parse_mode=ParseMode.MARKDOWN, ) return await tg.send_message( call.message.chat.id, i18n("ask_address {currency}").format( currency=offer.sell if is_user_init else offer.buy), ) await offer.update_document( {"$set": { "pending_input_from": call.from_user.id }}) await states.Escrow.receive_address.set()
async def get_bot_user_mock(): from aiogram.types import User return User(**dataset.USER)