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_update_data(self): context = FSMContext(MemoryStorage(), chat=1, user=1) async with context.proxy() as data: data.update(key1="value1", key2="value2") async with context.proxy() as data: assert data['key1'] == "value1" assert data['key2'] == "value2"
async def timeout_callback( loop , user_id , book_id ) : end_time = loop.time() + 300 while True : print( datetime.datetime.now() ) if (loop.time() + 1) >= end_time : break await asyncio.sleep( 150 ) print( 'timer done, let\'t start connecting them!' ) user = get_user( user_id ) if user.waits_conversation and not user.in_conversation : my_chat = Chats.objects( creator_id=user_id ).first() my_chat.time_out() while True : chatslist = get_waiting_chats( book_id , user_id ) pp( list( x.creator_id for x in chatslist ) ) user = get_user( user_id ) my_chat = Chats.objects( creator_id=user_id ).first() if not user.waits_conversation or user.in_conversation or not my_chat : print( 'func closed' ) break if len( chatslist ) >= 4 : available_users = list( get_user( chat.creator_id ) for chat in chatslist ) book = get_book( book_id ) for chat in chatslist : await close_chat_and_disconnect_users( book , chat ) await close_chat_and_disconnect_users( book , my_chat ) new_chat = Chats( creator_id=user_id , book_id=book_id , invited_users=available_users ) new_chat.get_emodzi() await set_chat_by_id( user_id , str( new_chat.id ) ) await AuthorState.in_conversation.set() for u in available_users : await set_chat_by_id( u.user_id , str( new_chat.id ) ) u_state = FSMContext( storage , u.user_id , u.user_id ) await delete_temp_messages( u_state ) mes = await s( u.user_id , f'Вас приглашают обсудить книгу *{book.article}*' , reply_markup=accept_decline_markup , parse_mode='Markdown' ) await add_to_temp( mes , state=u_state ) user.chat_waiting() await asyncio.create_task( timeout_callback( loop , user_id , book_id ) ) break await asyncio.sleep( 10 ) print( 'still waiting' )
async def cancel_offer(call: types.CallbackQuery, offer: EscrowOffer): """React to offer cancellation. While first party is transferring, second party can't cancel offer, because we can't be sure that first party hasn't already completed transfer before confirming. """ if offer.trx_id: return await call.answer(i18n("cancel_after_transfer")) if offer.memo: if offer.type == "buy": escrow_user = offer.init elif offer.type == "sell": escrow_user = offer.counter if call.from_user.id != escrow_user["id"]: return await call.answer(i18n("cancel_before_verification")) escrow_instance = get_escrow_instance(offer.escrow) if isinstance(escrow_instance, StreamBlockchain): escrow_instance.remove_from_queue(offer._id) sell_answer = i18n("escrow_cancelled", locale=offer.init["locale"]) buy_answer = i18n("escrow_cancelled", locale=offer.counter["locale"]) offer.cancel_time = time() await offer.delete_document() await call.answer() await tg.send_message(offer.init["id"], sell_answer, reply_markup=start_keyboard()) await tg.send_message(offer.counter["id"], buy_answer, reply_markup=start_keyboard()) sell_state = FSMContext(dp.storage, offer.init["id"], offer.init["id"]) buy_state = FSMContext(dp.storage, offer.counter["id"], offer.counter["id"]) await sell_state.finish() await buy_state.finish()
async def save_callback_data(cls, call: types.CallbackQuery, name: str = None, dispatcher: Dispatcher = None): dispatcher = dispatcher or cls.dispatcher if dispatcher is None: raise Exception("dispatcher not set") name = cls if name is None else cls.get_window(name=name) if name is None: return async with FSMContext( storage=dispatcher.storage, chat=call.message.chat.id, user=call.from_user.id).proxy() as proxy: if cls.multiselect: proxy.setdefault(name.data_name, set()).add(call.data) else: proxy[name.data_name] = call.data
async def accept_decline_callback( c: types.CallbackQuery , state: FSMContext ) : await c.answer() data = await state.get_data() # mark = get_accept_decline(data) # try : await c.message.delete() except exceptions.MessageToDeleteNotFound : pass u_id = c.from_user.id u = get_user( u_id ) chat = Chats.objects( id=data[ 'chat_id' ] ).first() if c.data == 'accept' : if chat : print( f'user @{c.from_user.username} with id {c.from_user.id} accepted conversation ' ) await s( u_id , 'Вы присоединились к обсуждению!' , reply_markup=simple_markup_back_end ) u.connect_chat() if not chat.visited : await delete_temp_messages( FSMContext( storage , chat.creator_id , chat.creator_id ) ) get_user( chat.creator_id ).update( waits_conversation=False , in_conversation=True ) await s( chat.creator_id , in_contact , reply_markup=accept_decline_markup ) # await creator_data.update(waiting_message_id=mes.message_id) chat.visited = True chat.connected_users.append( u ) chat.save() await AuthorState.in_conversation.set() else : print( f'user @{c.from_user.username} with id {c.from_user.id} accepted conversation but chat does not exist' ) await s( u_id , 'Чат уже не существует' ) u.disconnect_chat() # await c.message.edit_text( 'Чат уже не существует' ) elif c.data == 'decline' : print( f'user @{c.from_user.username} with id {c.from_user.id} declined conversation ' ) # await disconnect_user_from_conversation( state ) u.disconnect_chat()
async def run_check(dbhelper: DBHelper) -> None: """Check for every user if it has updates""" # TODO add error catch for user_id in dbhelper.all_user(): logging.info("checker.run_check: user_id = %s", user_id) user_session: UserSession = UserSession(user_id) await user_session.create(dbhelper=dbhelper) if not user_session.is_logged_in or user_session.glpi_id is None: # TODO notify user if he is suddenly unlogged (due password change or else) continue old_tickets: typing.Dict[int, typing.Dict] = dbhelper.all_tickets_glpi( user_session.glpi_id) try: new_tickets: typing.Dict[ int, typing.Dict] = user_session.get_all_my_tickets(open_only=False, full_info=False) except GLPIError as err: # logging.info(err.__dict__) error_text = str(err) logging.info("error_text = %s", error_text) if "Incorrect username or password" in error_text: await generic.logout( user_id, FSMContext(storage=dbhelper, chat=user_id, user=user_id)) continue else: raise logging.debug("checker.run_check: old_tickets = %d %s", len(old_tickets), old_tickets) logging.debug("checker.run_check: new_tickets = %d %s", len(new_tickets), new_tickets) messages, have_changes = check_diff(old_tickets, new_tickets, user_session=user_session) if have_changes: dbhelper.write_tickets_glpi(glpi_id=user_session.glpi_id, data=new_tickets) logging.info("checker.run_check: messages = %s", messages) await process_messages(user_id, *messages)
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 tg_context(self, user=None, chat=None): fsm = FSMContext(self.storage, chat, user) async with fsm.proxy() as p: yield p