def cmd_remove_transaction(update, context):
    """remove transaction command"""
    LOGGER.info(
            '%s: CMD remove transaction',
            update.message.from_user.username
        )
    if not util.check_permission(
                update, ['chairman'], 'CMD remove transaction'
            ):
        return
    try:
        transaction_id = int(context.args[0])
    except (ValueError, IndexError):
        LOGGER.warning(
                '%s: CMD remove transaction, incorrect <transaction_id>',
                update.message.from_user.username,
            )
        update.message.reply_text('Probleem met <transaction_id>')
        update.message.reply_text('/remove_transaction <transaction_id>')
        return
    database.remove_transaction(transaction_id)
    update.message.reply_text(
            'Removed transaction {}'.format(transaction_id),
            parse_mode=ParseMode.MARKDOWN
        )
    cmd_transactions(update, context)
Beispiel #2
0
def cmd_investors(update, context):
    """List investors"""
    LOGGER.info('%s: CMD investors', update.message.from_user.username)
    if not util.check_permission(update, ['trader', 'investor', 'chairman'],
                                 'CMD investors'):
        return
    investors = []
    total = 0
    for investor in database.get_investors():
        investor_dict = {
            'telegram_username': investor.telegram_username,
            'name': investor.name,
            'investment': 0
        }
        investor_dict['investment'] += util.total_investment(investor)
        total += investor_dict['investment']
        investors.append(investor_dict)
    investors_msgs = ['*Investors:*', '```']
    for investor in investors:
        investors_msgs.append('{:10}: $ {:>8}'.format(
            investor['name'],
            str(Value(investor['investment'])),
        ))
    if not investors:
        investors_msgs.append('no investors')
    investors_msgs.append('Totaal    : $ {:>8}'.format(str(Value(total))))
    investors_msgs.append('```')
    update.message.reply_text('\n'.join(investors_msgs),
                              parse_mode=ParseMode.MARKDOWN)
Beispiel #3
0
def cmd_total(update, context):
    """Total command"""
    LOGGER.info('%s: CMD total', update.message.from_user.username)
    if not util.check_permission(update, ['trader', 'investor', 'chairman'],
                                 'CMD total'):
        return
    total = util.get_total()
    total_msgs = ['*Totaal:*', '```']
    total_money = 0
    for item_id, item in total.items():
        total_msgs.append('{:>12} {:>12}'.format(
            ITEMS_INV[item_id],
            str(util.round_number(item['amount'], 10)),
        ))
        total_msgs.append('$ {:>10} $ {:>8}/1\n'.format(
            str(util.round_number(item['amount'] * item['average'], 10)),
            str(util.round_number(item['average'], 8)),
        ))
        if item_id:
            total_money += item['amount'] * item['average']
        else:
            total_money += item['amount']
    total_msgs.append('total')
    total_msgs.append('$ {:>10}'.format(str(util.round_number(total_money,
                                                              10))))
    total_msgs.append('```')
    update.message.reply_text('\n'.join(total_msgs),
                              parse_mode=ParseMode.MARKDOWN)
def conv_transaction_cancel(update, context):
    """Cancel transaction"""
    LOGGER.info('%s: CONV add_transaction, CMD cancel',
                update.message.from_user.username)
    update.message.reply_text('Transaction gecanceld.')
    context.user_data.clear()

    return ConversationHandler.END
def conv_transaction_start(update, context):
    """Start message"""
    LOGGER.info('%s: CONV add_transaction, CMD start',
                update.message.from_user.username)
    if not util.check_permission(update, ['trader', 'chairman'],
                                 'CONV add_transaction'):
        return ConversationHandler.END
    update.message.reply_text('Stuur de beschrijving voor transactie:')

    return TRANSACTION
def cmd_transactions(update, context):
    """transactions command"""
    LOGGER.info('%s: CMD transactions', update.message.from_user.username)
    if not util.check_permission(
                update, ['trader', 'investor', 'chairman'], 'CMD transactions'
            ):
        return
    try:
        limit = int(context.args[0])
    except (IndexError, KeyError):
        limit = 5
    try:
        item_id = ITEMS[context.args[1]]
    except (IndexError, KeyError):
        item_id = None

    transactions = database.get_transactions(limit, item_id)
    transactions_msgs = ['*Transacties:*']
    for transaction in transactions:
        transaction_total = 0
        transactions_msgs.append(
                '*{}*: {} {} ({})'.format(
                        transaction.id,
                        transaction.date_time.strftime("%Y-%m-%d %H:%M"),
                        transaction.user.name,
                        transaction.user.telegram_username,
                    )
            )
        transactions_msgs.append('```')
        transactions_msgs.append('├ {}'.format(transaction.description))
        for detail in transaction.details:
            transactions_msgs.append(
                    '{} {:>14} {:>14}'.format(
                            '├' if len(transaction.details) - 1 else '└',
                            ITEMS_INV[detail.item_id],
                            str(Value(detail.amount)),
                        )
                )
            transactions_msgs.append(
                    '{} $ {:>10}/1 $ {:>12}'.format(
                            '│' if len(transaction.details) - 1 else ' ',
                            str(Value(detail.money / detail.amount)),
                            str(Value(detail.money)),
                        )
                )
            transaction_total += detail.money
        if len(transaction.details) - 1:
            transactions_msgs.append('└         totaal $ {:>12}'.format(
                    str(Value(transaction_total))
                ))
        transactions_msgs.append('```')
    update.message.reply_text(
            '\n'.join(transactions_msgs), parse_mode=ParseMode.MARKDOWN
        )
Beispiel #7
0
def main():
    """Main method"""
    LOGGER.info('starting application')
    telegram_bot.run()

    try:
        while True:
            time.sleep(100)
    except KeyboardInterrupt:
        LOGGER.info('Exiting application')
        SCHEDULER.shutdown()
        sys.exit()
def conv_transaction_ask_details(update, context):
    """Transaction ask details"""
    LOGGER.info('%s: CONV add_transaction, description: "%s"',
                update.message.from_user.username, update.message.text)
    context.user_data['transaction'] = {
        'telegram_username': update.message.from_user.username,
        'telegram_id': update.message.from_user.id,
        'description': update.message.text,
        'details': [],
    }
    update.message.reply_text('Voeg transactie details toe.\n' + INSTRUCTIONS,
                              parse_mode=ParseMode.MARKDOWN)

    return DETAIL
def conv_transaction_detail_add(update, context):
    """Add transaction detail"""
    command = update.message.text.split(' ')[0]
    LOGGER.info('%s: CONV add_transaction, CMD %s',
                update.message.from_user.username, command)
    try:
        item_id = ITEMS[context.args[0]]
    except (IndexError, KeyError):
        LOGGER.warning('%s: CONV add_transaction, CMD %s, incorrect item name',
                       update.message.from_user.username, command)
        update.message.reply_text('Probleem met <name>.')
        update.message.reply_text(
            '{} <item> <amount> <price_each>'.format(command))
        return DETAIL

    try:
        if command == '/sell':
            amount = Value(-abs(Value(context.args[1])))
        elif command == '/buy':
            amount = Value(abs(Value(context.args[1])))
    except (IndexError, ValueError):
        LOGGER.warning('%s: CONV add_transaction, CMD %s, incorrect amount',
                       update.message.from_user.username, command)
        update.message.reply_text('Probleem met <amount>.')
        update.message.reply_text(
            '{} <item> <amount> <price_each>'.format(command))
        return DETAIL

    try:
        price = Value(context.args[2])
    except (IndexError, ValueError):
        LOGGER.warning(
            '%s: CONV add_transaction, CMD %s, incorrect price each',
            update.message.from_user.username, command)
        update.message.reply_text('Probleem met <price_each>.')
        update.message.reply_text(
            '{} <item> <amount> <price_each>'.format(command))
        return DETAIL

    if command == '/sell':
        price = abs(amount * price)
    elif command == '/buy':
        price = -abs(amount * price)

    context.user_data['transaction']['details'].append({
        'item_id': item_id,
        'amount': amount,
        'money': Value(price),
    })

    print_transaction(update, context)

    update.message.reply_text(
        'Voeg meer details toe '
        'of verwijder details met: `/remove <index>`. '
        'Sla de transactie op met: `/save`.',
        parse_mode=ParseMode.MARKDOWN)

    return DETAIL
Beispiel #10
0
def cmd_users(update, context):
    """users command"""
    LOGGER.info('%s: CMD users', update.message.from_user.username)
    if not util.check_permission(update, ['trader', 'chairman'], 'CMD users'):
        return
    users = database.get_users()
    users_msgs = ['*Users:*', '```']
    for user in users:
        users_msgs.append('{:12} {}'.format(user.name,
                                            ', '.join(user.get_roles())))
    if not users:
        users_msgs.append('no users')
    users_msgs.append('```')
    update.message.reply_text('\n'.join(users_msgs),
                              parse_mode=ParseMode.MARKDOWN)
Beispiel #11
0
def cmd_limits(update, context):
    """limits command"""
    LOGGER.info('%s: CMD limits', update.message.from_user.username)
    if not util.check_permission(update, ['trader', 'investor', 'chairman'],
                                 'CMD limits'):
        return
    limits = database.get_limits()
    limits_msgs = ['*Limieten:*', '```']
    for resource_id, limit in limits.items():
        limits_msgs.append('{:10}: {:>9}'.format(ITEMS_INV[resource_id],
                                                 str(Value(limit))))
    if not limits:
        limits_msgs.append('no limits')
    limits_msgs.append('```')
    update.message.reply_text('\n'.join(limits_msgs),
                              parse_mode=ParseMode.MARKDOWN)
Beispiel #12
0
def cmd_set_role(update, context):
    """Set role"""
    LOGGER.info('%s: CMD user set role', update.message.from_user.username)
    if not util.check_permission(update, ['chairman'], 'CMD user set role'):
        return
    roles = [
        'chairman',
        'trader',
        'investor',
    ]
    try:
        telegram_username = context.args[0]
        if telegram_username[:1] == '@':
            telegram_username = telegram_username[1:]
    except (IndexError, ValueError):
        LOGGER.warning(
            '%s: CMD user set role, incorrect <username>',
            update.message.from_user.username,
        )
        update.message.reply_text('Probleem met <username>')
        update.message.reply_text('/set_role <username> <role> <boolean>')
        return

    try:
        role = context.args[1]
        if role not in roles:
            raise ValueError
    except (IndexError, ValueError):
        LOGGER.warning(
            '%s: CMD user set role, incorrect <role>',
            update.message.from_user.username,
        )
        update.message.reply_text('Probleem met <role>')
        update.message.reply_text('/set_role <username> <role> <boolean>')
        return

    try:
        boolean = bool(context.args[2].lower() == 'true')
    except (IndexError, ValueError):
        LOGGER.warning(
            '%s: CMD user set role, incorrect <boolean>',
            update.message.from_user.username,
        )
        update.message.reply_text('Probleem met <boolean>')
        update.message.reply_text('/set_role <username> <role> <boolean>')
        return

    database.set_role(telegram_username, role, boolean)

    update.message.reply_text('role set: {} {} {}'.format(
        telegram_username, role, boolean),
                              parse_mode=ParseMode.MARKDOWN)
    cmd_users(update, context)
def conv_transaction_save(update, context):
    """Save transaction"""
    LOGGER.info('%s: CONV add_transaction, CMD save',
                update.message.from_user.username)

    if len(context.user_data['transaction']['details']) == 0:
        update.message.reply_text(
            'Oelewapper! '
            'Je hebt geen transactie details toegevoegd.\n' + INSTRUCTIONS,
            parse_mode=ParseMode.MARKDOWN)
        return DETAIL

    database.save_transaction(context.user_data['transaction'])

    update.message.reply_text('Transaction opgeslagen')
    context.user_data.clear()

    transaction.cmd_transactions(update, context)

    return ConversationHandler.END
Beispiel #14
0
def cmd_set(update, context):
    """Set limit"""
    LOGGER.info('%s: CMD set limit', update.message.from_user.username)
    if not util.check_permission(update, ['chairman'], 'CMD set limit'):
        return
    try:
        item_name = context.args[0]
    except IndexError:
        LOGGER.info('No item name given')
        update.message.reply_text('/set_limit <item_name> <amount>')
        update.message.reply_text('No item name given')
        return

    try:
        item_id = ITEMS[item_name]
    except IndexError:
        LOGGER.info('Item name not found')
        update.message.reply_text('/set_limit <item_name> <amount>')
        update.message.reply_text('Item name not found')
        return

    try:
        amount = context.args[1]
    except IndexError:
        LOGGER.info('No amount given')
        update.message.reply_text('/set_limit <item_name> <amount>')
        update.message.reply_text('No amount given')
        return

    try:
        amount = int(amount)
    except IndexError:
        LOGGER.info('Ammount is not an int')
        update.message.reply_text('/set_limit <item_name> <amount>')
        update.message.reply_text('Ammount is not an int')
        return

    database.set_limit(item_id, amount)

    update.message.reply_text('Limit created: {} {}'.format(item_name, amount),
                              parse_mode=ParseMode.MARKDOWN)
Beispiel #15
0
def cmd_set_investment(update, context):
    """Set investment"""
    LOGGER.info('%s: CMD set investment', update.message.from_user.username)
    if not util.check_permission(update, ['chairman'], 'CMD set investment'):
        return
    try:
        telegram_username = context.args[0]
        if telegram_username[:1] == '@':
            telegram_username = telegram_username[1:]
    except (IndexError, ValueError):
        LOGGER.warning(
            '%s: CMD set investment, incorrect <investment>',
            update.message.from_user.username,
        )
        update.message.reply_text('Probleem met <username>')
        update.message.reply_text('/set_investment <username> <amount>')
        return

    try:
        amount = Value(context.args[1])
    except (IndexError, ValueError):
        LOGGER.warning(
            '%s: CMD set investment, incorrect <amount>',
            update.message.from_user.username,
        )
        update.message.reply_text('Probleem met <amount>')
        update.message.reply_text('/set_investment <username> <amount>')
        return

    database.set_investment(telegram_username, amount)

    update.message.reply_text('investment set: {} $ {}'.format(
        telegram_username, amount),
                              parse_mode=ParseMode.MARKDOWN)
    cmd_investors(update, context)
Beispiel #16
0
def cmd_remove(update, context):
    """Set limit"""
    LOGGER.info('%s: CMD remove limit', update.message.from_user.username)
    if not util.check_permission(update, ['chairman'], 'CMD remove limit'):
        return
    try:
        item_name = context.args[0]
    except IndexError:
        LOGGER.info('No item name given')
        update.message.reply_text('/remove_limit <item_name>')
        update.message.reply_text('No item name given')
        return

    try:
        item_id = ITEMS[item_name]
    except IndexError:
        LOGGER.info('Item name not found')
        update.message.reply_text('/remove_limit <item_name>')
        update.message.reply_text('Item name not found')
        return

    database.remove_limit(item_id)

    update.message.reply_text('Limit removed: {}'.format(item_name),
                              parse_mode=ParseMode.MARKDOWN)
Beispiel #17
0
def check_permission(update, roles, action):
    """Check permissions"""
    executor = database.get_user_by_telegram_id(update.message.from_user.id)
    if not executor:
        executor = database.get_user_by_telegram_username(
            update.message.from_user.username)
        if executor:
            executor.telegram_id = update.message.from_user.id
            executor = database.save_user(executor)
        else:
            executor = database.add_user(update.message.from_user.first_name,
                                         update.message.from_user.id,
                                         update.message.from_user.username)
    if TESTING:
        return True
    for role in executor.get_roles():
        if role in roles:
            return True
    LOGGER.warning('%s: %s, not allowed', update.message.from_user.username,
                   action)
    update.message.reply_text(
        'Rollen die recht hebben op dit command: {}'.format(', '.join(roles)))
    return False
Beispiel #18
0
def run():
    """run function"""
    LOGGER.info('starting Telegram')

    dispatcher = TELEGRAM_UPDATER.dispatcher

    # general commands
    dispatcher.add_handler(CommandHandler('start', general.cmd_start))
    dispatcher.add_handler(CommandHandler('hulp', general.cmd_hulp))
    dispatcher.add_handler(CommandHandler('help', general.cmd_help))
    dispatcher.add_handler(CommandHandler('total', general.cmd_total))

    # limit
    dispatcher.add_handler(CommandHandler('limits', limit.cmd_limits))
    dispatcher.add_handler(CommandHandler('set_limit', limit.cmd_set))
    dispatcher.add_handler(CommandHandler('remove_limit', limit.cmd_remove))

    # user
    dispatcher.add_handler(CommandHandler('users', user.cmd_users))
    dispatcher.add_handler(CommandHandler('set_role', user.cmd_set_role))

    # investor
    dispatcher.add_handler(CommandHandler('investors', investor.cmd_investors))
    dispatcher.add_handler(
        CommandHandler('set_investment', investor.cmd_set_investment))

    # transaction
    dispatcher.add_handler(add_transaction.conversation)
    dispatcher.add_handler(
        CommandHandler('transactions', transaction.cmd_transactions))
    dispatcher.add_handler(
        CommandHandler('remove_transaction',
                       transaction.cmd_remove_transaction))

    TELEGRAM_UPDATER.start_polling()
    TELEGRAM_UPDATER.idle()