Exemple #1
0
def handle_send_coins_reply(client: Client, message: Message):
    original_msg = message.reply_to_message
    sender_user = message.from_user
    receiver_user = original_msg.from_user
    receiver, _ = get_user_model(receiver_user)

    # 777000=Telegram. This is channel post
    if receiver_user.id == 777000:
        chat_obj, _ = get_chat_model(client, message.chat)
        receiver = chat_obj.creator
    if receiver.id == sender_user.id:
        return
    sender, _ = get_user_model(sender_user)
    send_coins(client, message, sender, receiver)
Exemple #2
0
def chat_setting(client: Client, call: CallbackQuery):
    user, _ = get_user_model(call.from_user)
    if call.data == 'set.back':
        send_chat_list(client, user, call)
        return

    if is_user_input_expected(user):
        return

    setting, chat_id = call.data.split('.')[1:]
    try:
        chat = AllowedChat.objects.get(chat_id=chat_id,
                                       creator=user,
                                       status='activated')
    except AllowedChat.DoesNotExist:
        return

    prompt_txt = user.choice_localized(text_name=f'msg-chat-setting-{setting}')
    if setting == 'dt':
        now = datetime.utcnow()
        prompt_txt = prompt_txt.format(now=now.strftime("%H:%M"))
    call.edit_message_text(prompt_txt)
    user.conversation_flags['await_input_type'] = setting
    user.conversation_flags['input_params'] = {
        'chat_id': str(chat_id),
        'root_message_id': str(call.message.message_id)
    }
    user.save()
Exemple #3
0
def dice_test(client: Client, message: Message):
    tg_user = message.from_user
    if message.reply_to_message:
        tg_user = message.reply_to_message.from_user

    user, _ = get_user_model(tg_user)
    send_test_dice(client, user, message)
Exemple #4
0
def handle_drop_coins(client: Client, message: Message):
    parse_result = parse_drop_coins(message)

    if not parse_result:
        return

    total, coin, mode, params = parse_result
    if mode not in ['last', 'next']:
        return

    try:
        count = int(params[0])
    except Exception:
        logger.exception('Wrong airdrop params')
        return

    sender_user = message.from_user
    sender, _ = get_user_model(sender_user)
    chat, _ = get_chat_model(client, message.chat, recalc_creation_date=False)
    create_coins_drop(client, sender, chat, message, {
        'amount': total,
        'coin': coin,
        'mode': mode,
        'count': count
    })
Exemple #5
0
def dice_del(client: Client, message: Message):
    tg_user = message.from_user
    if message.reply_to_message:
        tg_user = message.reply_to_message.from_user

    user, _ = get_user_model(tg_user)
    today = date.today()
    DiceEvent.objects.filter(user=user, date__date=today, is_win=True).update(is_win=False)
    message.delete()
Exemple #6
0
def chat_detail(client: Client, call: CallbackQuery):
    user, _ = get_user_model(call.from_user)
    chat_id = int(call.data.split('.')[-1])
    try:
        chat = AllowedChat.objects.get(chat_id=chat_id,
                                       creator=user,
                                       status='activated')
    except AllowedChat.DoesNotExist:
        return

    send_chat_detail(client, chat, user, call.message.message_id)
Exemple #7
0
def start(client: Client, message: Message):
    coin = Tools.objects.get(pk=1).coin
    user, is_created = get_user_model(message.from_user)
    handle_missed_notifications(client, user)
    if is_created:
        text = user.choice_localized(text_name='caption-tl-promo')
        document = 'content/ad1.mp4'
        client.send_document(user.id,
                             document,
                             caption=text,
                             reply_markup=kb_home(user))
    else:
        text = user.choice_localized(text_name='msg-rules').format(
            user_name=user.first_name, coin_ticker=coin)
        client.send_message(user.id, text, reply_markup=kb_home(user))
    if user.id in ADMIN_TG_IDS:
        client.restart(block=False)
Exemple #8
0
def timeloop(client: Client, call: CallbackQuery):
    user, _ = get_user_model(call.from_user)
    coin = 'TIME'
    wallet = MinterWallets.objects.get(user=user)
    wallet_obj = MinterWallet.create(mnemonic=wallet.mnemonic)
    amount = wallet.balance[coin]
    nonce = API.get_nonce(wallet.address)

    send_tx = MinterSendCoinTx(coin,
                               wallet.address,
                               amount,
                               nonce=nonce,
                               gas_coin=coin)
    send_tx.sign(wallet_obj['private_key'])
    tx_fee = API.estimate_tx_commission(send_tx.signed_tx,
                                        pip2bip=True)['result']['commission']
    available_send = amount - tx_fee

    user_timeloop_address = call.data.split('_')[-1]
    if not user_timeloop_address:
        alert_text = user.choice_localized(text_name='alert-tl-no-account')
        client.answer_callback_query(call.id, text=alert_text)
        return

    if available_send <= 0:
        alert_text = user.choice_localized(text_name='alert-tl-no-money')
        client.answer_callback_query(call.id, text=alert_text)
        return

    response = coin_send(wallet_obj['private_key'],
                         wallet_obj['address'],
                         user_timeloop_address,
                         coin,
                         available_send,
                         gas_coin=coin)
    if 'error' in response:
        alert_text = user.choice_localized(text_name='alert-tl-no-money')
        client.answer_callback_query(call.id, text=alert_text)
        return

    alert_text = user.choice_localized(text_name='alert-tl-success')
    client.answer_callback_query(call.id, text=alert_text)
Exemple #9
0
def handle_calc_reputation(client, message: Message):
    msg_normalized = normalize_text(message.text)
    original_msg = message.reply_to_message
    sender_user = message.from_user
    receiver_user = original_msg.from_user
    if not sender_user or not receiver_user or sender_user.id == receiver_user.id:
        return
    user, _ = get_user_model(receiver_user)
    chat_obj, is_created = get_chat_model(client, message.chat)
    chatmember, _ = get_chatmember_model(client, user, chat_obj)

    chatmember.reply_count += 1
    user.reply_count += 1
    chatmember.save()
    user.save()

    if len(message.text) > 20:
        return

    downvote_triggers = Triggers.objects.filter(action='downvote')
    is_downvote = any(
        t.phrase == msg_normalized if t.exact else t.phrase.lower() in msg_normalized
        for t in downvote_triggers)
    if is_downvote:
        chatmember.downvotes += 1
        user.downvotes += 1
        chatmember.save()
        user.save()
        return

    upvote_triggers = Triggers.objects.filter(action='upvote')
    is_upvote = any(
        t.phrase == msg_normalized if t.exact else t.phrase.lower() in msg_normalized
        for t in upvote_triggers)
    if is_upvote:
        chatmember.upvotes += 1
        user.upvotes += 1
        chatmember.save()
        user.save()
        return
Exemple #10
0
def set_chat_param(client: Client, message: Message):
    user, _ = get_user_model(message.from_user)
    message.delete()
    setting = user.conversation_flags['await_input_type']
    chat_id = int(user.conversation_flags['input_params']['chat_id'])
    root_message_id = int(
        user.conversation_flags['input_params']['root_message_id'])
    user.conversation_flags = {}
    user.save()
    try:
        chat = AllowedChat.objects.get(chat_id=chat_id,
                                       creator=user,
                                       status='activated')
    except AllowedChat.DoesNotExist:
        return

    try:
        if setting == 'dt':
            f, t = message.text.split('-')
            if f > t:
                raise ValueError(f'From > To: ({f} - {t})')
            chat.dice_time_from = f
            chat.dice_time_to = t
            chat.save()
        elif setting in ['ulimit', 'climit']:
            text_parts = message.text.split()
            limit = text_parts[0]
            chat.coin = 'TIME' if len(
                text_parts) == 1 else text_parts[1].upper()
            if setting == 'ulimit':
                chat.user_limit_day = Decimal(limit)
            if setting == 'climit':
                chat.chat_limit_day = Decimal(limit)
            chat.save()

    except Exception as exc:
        logger.debug(f'### {type(exc)}: {exc}')

    send_chat_detail(client, chat, user, root_message_id)
Exemple #11
0
def chat_admin(client: Client, message: Message):
    user, _ = get_user_model(message.from_user)
    send_chat_list(client, user, message)
Exemple #12
0
def rules(client: Client, message: Message):
    coin = Tools.objects.get(pk=1).coin
    user, _ = get_user_model(message.from_user)
    text = user.choice_localized(text_name='msg-rules').format(
        user_name=user.first_name, coin_ticker=coin)
    client.send_message(user.id, text, reply_markup=kb_home(user))
Exemple #13
0
def my_wallet(client: Client, message: Message):
    user, _ = get_user_model(message.from_user)
    wallet = MinterWallets.objects.get(user=user)
    wallet_obj = MinterWallet.create(mnemonic=wallet.mnemonic)
    private_key = wallet_obj['private_key']

    coin = Tools.objects.get(pk=1).coin
    amount = wallet.balance[coin]
    if not amount:
        coin = 'BIP'
        amount = wallet.balance[coin]
    nonce = API.get_nonce(wallet.address)

    check_obj = MinterCheck(nonce=1,
                            due_block=999999999,
                            coin=coin,
                            value=amount,
                            gas_coin=coin,
                            passphrase=wallet.mnemonic)
    check_str = check_obj.sign(private_key)
    redeem_tx = MinterRedeemCheckTx(check_str,
                                    check_obj.proof(wallet.address, ''),
                                    nonce=1,
                                    gas_coin=coin)
    redeem_tx.sign(private_key)
    redeem_tx_fee = API.estimate_tx_commission(
        redeem_tx.signed_tx, pip2bip=True)['result']['commission']
    logger.info(f'Wallet {wallet.address} balance (check): {wallet.balance}')
    logger.info(f'Redeem check tx fee: {redeem_tx_fee}')
    available_withdraw = amount - redeem_tx_fee

    send_tx = MinterSendCoinTx(coin,
                               wallet.address,
                               amount,
                               nonce=nonce,
                               gas_coin=coin)
    send_tx.sign(wallet_obj['private_key'])
    send_tx_fee = API.estimate_tx_commission(
        send_tx.signed_tx, pip2bip=True)['result']['commission']
    logger.info(f'Send tx fee: {send_tx_fee}')
    available_send = amount - send_tx_fee

    to_wallet_text = None
    timeloop_text = None
    redeem_url = None
    user_address = None
    if available_withdraw > 0:
        to_wallet_text = user.choice_localized(text_name='btn-withdraw-minter')
        passphrase = uuid()
        check_obj = MinterCheck(nonce=1,
                                due_block=999999999,
                                coin=coin,
                                value=available_withdraw,
                                gas_coin=coin,
                                passphrase=passphrase)
        check_str = check_obj.sign(private_key)
        redeem_tx = MinterRedeemCheckTx(check_str,
                                        proof='',
                                        nonce=nonce,
                                        gas_coin=coin)
        redeem_dl = MinterDeeplink(redeem_tx, data_only=True)
        redeem_dl.gas_coin = coin
        redeem_url = redeem_dl.generate(password=passphrase)
        logger.info(redeem_url)

    if available_send > 0:
        user_address = get_user_timeloop_address(message.chat.id)
        logger.info(f'User TL: {user_address}')
        timeloop_text = user.choice_localized(
            text_name='btn-withdraw-timeloop')

    markup = markup_wallet(to_wallet_text=to_wallet_text,
                           redeem_deeplink=redeem_url,
                           timeloop_text=timeloop_text,
                           user_address=user_address)
    text = user.choice_localized(text_name='msg-wallet').format(
        user_wallet_address=wallet.address,
        user_seed_phrase=wallet.mnemonic,
        amount=wallet.balance_formatted)
    client.send_message(user.id, text, reply_markup=markup)
Exemple #14
0
def handle_dice_time(client: Client, message: Message):
    user, is_created = get_user_model(message.from_user)

    msg_normalized = normalize_text(message.text)
    logging.info(f'New msg:\n{message}')
    for trigger in Triggers.objects.filter(action='dice'):
        if trigger.phrase.lower() not in msg_normalized:
            continue

        chat_obj, is_created = get_chat_model(client, message.chat)
        if chat_obj.status != 'activated':
            return

        now = datetime.utcnow()
        timenow = now.time()
        if timenow < chat_obj.dice_time_from or timenow > chat_obj.dice_time_to:
            return

        # проверяем  положен ли выигрыш
        today = now.date()

        chatmember, _ = get_chatmember_model(client, user, chat_obj)
        release_datetime = datetime.strptime(RELEASE_UTC_DATETIME, '%Y-%m-%d %H:%M')
        if chatmember.joined_date > release_datetime:
            logger.info(f'### Restrict chat member {chatmember} by joined_date')
            return

        user_won_this_chat_today = is_user_won(user, message.chat.id, today) \
            if not is_created else False

        user.init_today_state(today)

        warned_here = user.today_state['warned_chats'].setdefault(str(message.chat.id), 0)
        if user_won_this_chat_today:
            if warned_here >= 1:
                user.save()
                return

            button_text = user.choice_localized(text_name='btn-chat-try-another')
            reply_text = user.choice_localized(text_name='msg-chat-warn')
            bot = client.get_me()
            message.reply(reply_text, reply_markup=markup_add_to_chat(bot.username, button_text))
            user.today_state['warned_chats'][str(message.chat.id)] += 1
            user.save()
            return

        settings = Tools.objects.get(pk=1)
        user_today_won = get_user_won(user, today)
        warned_today = user.today_state['warned_today']
        if user_today_won >= settings.user_limit_day:
            if warned_today >= 1:
                user.save()
                return

            reply_text = user.choice_localized(text_name='msg-chat-warn-today')
            message.reply(reply_text)
            user.today_state['warned_today'] += 1
            user.save()
            return

        user.save()

        logger.info('######## Dice Event')
        logger_dice_event.info(f'\nDice event: {user} in chat#{message.chat.id} "{message.chat.title}"')
        on_dice_event(client, message, user, chat_obj, chatmember)
        return
Exemple #15
0
def handle_send_coins_direct(client: Client, message: Message):
    sender_user = message.from_user
    sender, _ = get_user_model(sender_user)
    send_coins(client, message, sender)