Beispiel #1
0
def Account(u, c):
    print("Account Calling")
    SearchData = SearchUserID(u.effective_user.id, "AddrGenByUser")
    reply_markup = IKM([[IKB("Địa Chỉ Nhận Tiền", None, 141)],
                        [IKB("Trở Lại", None, 1)]])
    if SearchData != None:
        if GetBalance(SearchData[0][1]) == False:
            verified = "Chưa Xác Minh"
        else:
            verified = "Đã Xác Minh"
        if SearchData[0][2] == 0.0:
            text = f"Địa Chỉ Token: {SearchData[0][1]}\nSố Dư TRX: {SearchData[0][2]} ( ❗ Không Đủ Số Dư Để Chuyển Token )\nTình Trạng Xác Minh: {verified}"
        else:
            text = f"Địa Chỉ Token: {SearchData[0][1]}\nSố Dư TRX: {GetBalance(SearchData[0][1])}\nTình Trạng Xác Minh: {verified}"
        Send(text, reply_markup, u, c)
    elif SearchData == None:
        text = "Đang Tạo Địa Chỉ Token Cho Bạn, Có Thể Mất Tối Đa 1 Phút"
        reply_markup = IKM([[IKB("Trở Lại", None, 1)]])
        Send(text, reply_markup, u, c)
        New = GenAddr()
        user_id = u.effective_user.id
        InsertData("AddrGenByUser", "",
                   f'''{user_id},"{New[0]}",0.0,"{New[1]}",False''')
        time.sleep(5)
        c.bot.delete_message(u.effective_chat.id,
                             u.effective_message.message_id + 1)
        Account(u, c)
Beispiel #2
0
def creating_joining(update, context):
    ud = context.user_data
    chat_id = update.effective_chat.id
    if 'name_user' in ud.keys():
        add_user(ud['name_user'], chat_id)
    message = ("Do you want to join an existing community "
               "or create your own?")
    keyboard = InlineKeyboardMarkup([
        [IKB('Join existing community', callback_data='join')],
        [IKB('Create my own', callback_data='create')],
    ])
    bot = context.bot
    if 'last_message' not in ud:
        last_message = bot.send_message(chat_id=chat_id,
                                        text=message,
                                        reply_markup=keyboard)
        ud['last_message'] = last_message
    else:
        last_message = ud['last_message']
        bot.edit_message_text(
            message_id=last_message.message_id,
            chat_id=chat_id,
            text=message,
            reply_markup=keyboard,
        )
    return ConversationStage.CREATING_JOINING
Beispiel #3
0
def ask_for_date(update, context):
    chat_id = update.effective_chat.id
    bot = context.bot
    weekday_in_two_days = get_weekday(datetime.date.today() +
                                      datetime.timedelta(days=2))
    keyboard = InlineKeyboardMarkup([
        [
            IKB('Today', callback_data='today'),
            IKB('Tomorrow', callback_data='tmo'),
        ],
        [
            IKB(f'On {weekday_in_two_days}', callback_data='in_2_days'),
            IKB('Show calendar', callback_data='show_calendar'),
        ],
        [IKB('Back', callback_data='back')],
    ])
    message = get_message(
        context,
        epilog='I advise you to hide your '
        'keyboard now to better '
        'see my messages! \n \n'
        'When do '
        'you '
        'want to cook?',
    )
    last_message = context.user_data['last_message']
    bot.edit_message_text(
        message_id=last_message.message_id,
        chat_id=chat_id,
        text=message,
        reply_markup=keyboard,
    )

    return ConversationStage.SELECTING_WEEKDAY_OR_SHOW_CALENDAR
Beispiel #4
0
def community_action(update, context):
    chat_id = update.effective_chat.id
    user = get_user_from_chat_id(chat_id)
    community = user.community
    message = emojize(
        f'You\'re in the community \n :family: {community.name} \n '
        f':desert_island: whose '
        f'description '
        f'is :  {community.description} \n What do you want to do?')
    buttons = [
        [IKB('Quit community', callback_data='quit')],
    ]
    if user.admin:
        buttons.append([IKB('Invite people', callback_data='invite')])
    buttons.append([IKB('Back', callback_data='back')])
    keyboard = InlineKeyboardMarkup(buttons)
    bot = context.bot
    ud = context.user_data
    if 'last_message' in ud:
        last_message = ud['last_message']
        bot.edit_message_text(
            message_id=last_message.message_id,
            chat_id=chat_id,
            text=message,
            reply_markup=keyboard,
        )
    else:
        ud['last_message'] = bot.send_message(chat_id=chat_id,
                                              text=message,
                                              reply_markup=keyboard)
    return ConversationStage.ACTION
Beispiel #5
0
def ask_for_confirmation(update, context):
    ud = context.user_data
    money = ud['money_or_meal']
    to_whom = ud['user_transaction']
    amount = emojize_number(ud['amount'])
    amount += '€' if money else ' meals'
    balance = (
        str(to_whom.money_balance) + '€'
        if money
        else str(to_whom.meal_balance) + ' meals'
    )
    message = emojize(
        f'You\'re about to give  \n :money_bag: {amount} \n'
        f'{money_mouth_face} to {to_whom.name}\n'
        f':balance_scale: whose balance is : {balance}. \n'
        f'This user should give you the equivalent amount in real '
        f'life in '
        f'exchange\n'
        f'Do you confirm?'
    )
    keyboard = InlineKeyboardMarkup(
        [
            [IKB('Confirm', callback_data='confirm')],
            [IKB('Back', callback_data='back')],
        ]
    )
    update.callback_query.edit_message_text(
        text=message, reply_markup=keyboard,
    )
    return ConversationStage.CONFIRMING
Beispiel #6
0
def ask_money_or_meal(update, context):
    chat_id = update.effective_chat.id
    ud = context.user_data
    bot = context.bot
    keyboard = InlineKeyboardMarkup(
        [
            [IKB('Give money', callback_data='money')],
            [IKB('Give meal points', callback_data='meal')],
            [IKB('Back', callback_data='back')],
        ]
    )
    message = 'What kind of transaction do you want to make?'
    if 'last_message' not in ud:
        last_message = bot.send_message(
            chat_id=chat_id, text=message, reply_markup=keyboard
        )
        ud['last_message'] = last_message
    else:
        last_message = ud['last_message']
        bot.edit_message_text(
            message_id=last_message.message_id,
            chat_id=chat_id,
            text=message,
            reply_markup=keyboard,
        )
    return ConversationStage.MONEY_OR_MEAL
Beispiel #7
0
    def online_init(self, bot, update):
        chat_id = update.message.chat_id
        loc = self.location[chat_id]
        text = update.message.text
        add_data, text = (
            text, self.user_data[chat_id][0]) if loc == 'search' else ('',
                                                                       text)
        data_list, max_page = self.get_data(bot, chat_id, loc, text, add_data)
        if not data_list:
            return
        text_message = func_data.text_gen(data_list, loc, add_text=add_data)
        if loc == 'library':
            loc = func_data.analog[text] + ' ' + loc
        if loc == 'search':
            loc = '{} {} {}'.format(add_data, text, loc)

        keyboard = [[
            IKB(str(i + 1), callback_data='item {} {} {}'.format(i, 0, loc))
            for i in range(len(data_list[0]))
        ]]
        keyboard += [[
            IKB('⬅', callback_data='prev 0 {} ' + loc),
            IKB('➡️', callback_data='next 0 ' + loc)
        ]]
        update.message.reply_text(text=text_message + '\n\nCurrent page: 1/' +
                                  str(max_page + 1),
                                  reply_markup=IKM(keyboard))
Beispiel #8
0
def cancelling(update, context):
    meal = context.user_data['meal_being_processed']
    cancel_meal = context.user_data['cancel_meal']
    too_late = (
        not cancel_meal
        and datetime.strptime(meal.deadline, datetime_format) <= datetime.now()
    )
    context.user_data['too_late'] = too_late
    if too_late:
        message = (
            'The deadline for confirming participation has passed, '
            'are you sure you want to cancel? I will send '
            'a message to the cook and you won\'t be charged for '
            'the meal but you won\'t be '
            'given your meal points back'
        )
    else:
        optional = 'your participation at '
        nothing = ''
        message = (
            f'*Are you sure you want to cancel '
            f'{optional if not cancel_meal else nothing} '
            f'this meal?* \n'
        )
        message += create_meal_message(meal)
    keyboard = InlineKeyboardMarkup(
        [
            [IKB('Confirm', callback_data='confirm')],
            [IKB('Back', callback_data='back')],
        ]
    )
    update.callback_query.edit_message_text(
        text=message, reply_markup=keyboard,
    )
    return ConversationStage.CANCELING
Beispiel #9
0
    def online_button_checker(self, bot, update):
        query = update.callback_query
        chat_id = query.message.chat.id
        message_id = query.message.message_id
        action, *args, loc = query.data.split(' ')
        add_data = args[-2] if loc == 'search' else ''
        data_list, max_page = self.get_data(bot, chat_id, loc, args[-1],
                                            add_data)
        if not data_list:
            return

        if action in ['prev', 'next'] and max_page or action == 'cancel':
            page = int(args[0])
            if action == 'next':
                page = 0 if page == max_page else page + 1
            if action == 'prev':
                page = max_page if page == 0 else page - 1
            text_message = func_data.text_gen(data_list, loc, page, add_data)
            if loc == 'library':
                loc = args[-1] + ' ' + loc
            if loc == 'search':
                loc = '{} {} {}'.format(*args[-2:], loc)
            keyboard = [[
                IKB(str(i + 1),
                    callback_data='item {} {} {}'.format(i, page, loc))
                for i in range(len(data_list[page]))
            ]]
            keyboard += [[
                IKB('⬅', callback_data='prev {} {}'.format(page, loc)),
                IKB('➡️', callback_data='next {} {}'.format(page, loc))
            ]]
            bot.edit_message_text(
                text=text_message +
                '\n\nCurrent page: {}/{}'.format(page + 1, max_page + 1),
                chat_id=chat_id,
                message_id=message_id,
                reply_markup=IKM(keyboard))
        elif action == 'item':
            k = int(args[0])
            page = int(args[1])
            item = data_list[page][k]
            message = self.get_message(loc, page, item, args[-1], chat_id,
                                       add_data)
            bot.edit_message_text(chat_id=chat_id,
                                  message_id=message_id,
                                  text=message[0],
                                  reply_markup=message[1])
        elif action in ['accept', 'reject'] and loc == 'confirm':
            user_id = int(args[0])
            ids = [chat_id, message_id]
            self.conf_user(bot, ids, user_id, action)
        elif loc in ['library', 'search']:
            ids = [chat_id, message_id]
            self.modify_document(bot, ids, action, args)
        elif loc == 'users':
            ids = [chat_id, message_id]
            self.user_flip(bot, ids, action, args)
        elif loc == 'my_orders':
            ids = [chat_id, message_id]
            self.manage_orders(bot, ids, action, args)
Beispiel #10
0
def verify_token(update, context):
    token_str = update.message.text
    token = get_token(token_str)
    last_message = context.user_data['last_message']
    bot = context.bot
    chat_id = update.effective_chat.id
    bot.delete_message(message_id=update.message.message_id, chat_id=chat_id)
    if token is None:
        message = "The token was not right! Try again!"
        bot.edit_message_text(
            message_id=last_message.message_id,
            chat_id=chat_id,
            text=message,
            reply_markup=back_keyboard,
        )
        return ConversationStage.JOINING
    else:
        community = token.community
        message = emojize(f'You\'re about to join the community \n :family: '
                          f'{community.name} '
                          f'\n:desert_island: whose description is:'
                          f' {community.description}. \n'
                          f'Do you confirm?')
        keyboard = InlineKeyboardMarkup([
            [IKB('Confirm', callback_data='confirm')],
            [IKB('Back', callback_data='back')],
        ])
        bot.edit_message_text(
            message_id=last_message.message_id,
            chat_id=chat_id,
            text=message,
            reply_markup=keyboard,
        )
        context.user_data['token'] = token
        return ConversationStage.VERIFYING
Beispiel #11
0
def save_community_description(update, context):
    description = update.message.text
    ud = context.user_data
    ud['community_description'] = description
    last_message = ud['last_message']
    bot = context.bot
    chat_id = update.effective_chat.id
    bot.delete_message(message_id=update.message.message_id, chat_id=chat_id)
    message = get_message(
        context,
        epilog='If you\'re satisfied with this '
        'community description you can '
        'confirm',
    )
    keyboard = InlineKeyboardMarkup([
        [IKB('Confirm', callback_data='confirm')],
        [IKB('Back', callback_data='back')],
    ])
    bot.edit_message_text(
        message_id=last_message.message_id,
        chat_id=chat_id,
        text=message,
        reply_markup=keyboard,
    )
    return ConversationStage.CONFIRMING
Beispiel #12
0
def Start(update, context):
    bot = context.bot
    chat_id = update.effective_chat.id
    text = '''<b><i>Deposit Now And Receive 120% Profits In 20 Days</i>\n<u>Minium 10$ Maximum 500$</u>
🔥 <i>Bonus Up To 140% Profits From Now To <u>15/11/2020</u></i></b>'''
    reply_markup = IKM([[IKB("Account", None, 1),
                         IKB("Support", None, 2)], [IKB("Stat", None, 3)]])
    bot.send_message(chat_id, text, "HTML", True, True, None, reply_markup)
Beispiel #13
0
def quit(update, context):
    chat_id = update.effective_chat.id
    bot = context.bot
    user = get_user_from_chat_id(chat_id)
    members = user.community.members
    ud = context.user_data
    last_message = ud['last_message']
    all_meals = get_all_meals(user)
    # admins = [member for member in user.community.members if member.admin]
    if len(members) < 2:
        message = (
            f'Are you sure you want to quit the community? Since you\'re '
            f'the last member this will delete it')
        keyboard = InlineKeyboardMarkup([
            [IKB('Confirm', callback_data='confirm')],
            [IKB('Back', callback_data='back')],
        ])
        bot.edit_message_text(
            message_id=last_message.message_id,
            chat_id=chat_id,
            text=message,
            reply_markup=keyboard,
        )
        return ConversationStage.QUITTING
    # elif len(admins) < 2 and user.admin:
    #     bot.edit_message_text(message_id=last_message.message_id,
    #         chat_id=chat_id, text='To quit this community you need to name '
    #                               'another administrator'
    #     )  # propose
    #     # to name another admin
    #     return ConversationHandler.END
    elif user.money_balance < 0:
        prefix = ('*To quit the community you need to '
                  'have a money balance superior to zero.'
                  '\nAsk another user to make a '
                  'transaction* \n')
        first_message(update, context, prefix)
        return ConversationHandler.END
    elif len(all_meals) == 0:
        prefix = ('*To quit the community you need to have no meal ongoing '
                  'please cancel your participation and the ones you organize '
                  'before leaving.')
        first_message(update, context, prefix)
        return ConversationHandler.END
    else:
        message = f'Are you sure you want to quit the community?'
        keyboard = InlineKeyboardMarkup([
            [IKB('Confirm', callback_data='confirm')],
            [IKB('Back', callback_data='back')],
        ])
        bot.edit_message_text(
            message_id=last_message.message_id,
            chat_id=chat_id,
            text=message,
            reply_markup=keyboard,
        )
        return ConversationStage.QUITTING
Beispiel #14
0
def Account(bot, chat_id):
    text = '''👤 <b>Account Balance:
    💵 Withdrawable Balance: {function}$
    💎 Active Investment: {function}$
    🚧 Pending Withdraw: {function}$
    ✔️ Total Withdrawn: {function}$</b>'''
    reply_markup = IKM(
        [[IKB("Invest", None, 11),
          IKB("Auto Withdraw", None, 12)], [IKB("Back", None, 0)]])
    bot.send_message(chat_id, text, "HTML", True, True, None, reply_markup)
Beispiel #15
0
def Start(u, c):
    print("Start Calling")
    reply_markup = IKM(
        [[IKB("Danh Sách Airdrop", None, 11)],
         [IKB("Thông Báo Mới Nhất", channel_link),
          IKB("Hỗ Trợ", group_link)], [IKB("Thông Tin Tài Khoản", None, 14)]])
    Send(test, reply_markup, u, c)
    if u.effective_message.text == "/start":
        c.bot.delete_message(u.effective_chat.id,
                             u.effective_message.message_id)
Beispiel #16
0
def reminder_keyboard_build(time_left):
    float_hours = make_labels(time_left)
    button_list = []
    for float_hour in float_hours:
        button_list.append(make_button(float_hour))
    buttons = [
        button_list[i:i + 2]  # noqa : E203 whitespace before ':'
        for i in range(0, len(button_list), 2)
    ]
    buttons.append([IKB(text="Until last minute", callback_data='00:00:00')])
    buttons.append([IKB(text="Back", callback_data='back')])
    keyboard = InlineKeyboardMarkup(buttons)
    return keyboard
Beispiel #17
0
    def online_init(self, bot, update):
        chat = update.message.chat_id
        loc = self.location[chat]
        text = update.message.text
        data_list, max_page = self.get_data(bot, chat, loc, text)
        if not data_list:
            return
        text_message = func_data.text_gen(data_list, loc)
        if loc == 'library':
            loc = func_data.analog[text] + " " + loc

        keyboard = [
            [IKB(str(i + 1), callback_data="item {} {} {}".format(i, 0, loc)) for i in range(len(data_list[0]))]]
        keyboard += [[IKB("⬅", callback_data='prev 0 {} ' + loc), IKB("➡️", callback_data='next 0 ' + loc)]]
        update.message.reply_text(text=text_message + "\n\nCurrent page: 1/" + str(max_page + 1),
                                  reply_markup=IKM(keyboard))
Beispiel #18
0
def Deposit(bot, chat_id):
    text = '''<b>Choose One Currency Type Available For Deposit<i>
❗ Auto Withdraw Will Send Your Profit To Deposit Address|Account!</i>
Payeer: <code>P1031638149</code>
BTC: <code>1LxudDaPdWjdp8RW7xyNpjdWL4J1AZZdQe</code>
ETH: <code>0x94f29C62DaDea7fB6a34E65C4446fE54E94151CF</code>
LTC: <code>LY6iiqXWv1njZFtay5BKjgeMVJsyvpCLC4</code></b>'''
    reply_markup = IKM([[IKB("Back", None, 1)]])
    bot.send_message(chat_id, text, "HTML", True, False, None, reply_markup)
Beispiel #19
0
def Stat(bot, chat_id):
    text = '''<b>Bot Statistics
    👥 Total User: {function}
    ➕ Total Investments: {function}$
    ➖ Total Withdrawals: {function}$
    ⬆️ Total Profit To Admin From All Investor: {function}$</b>
    <u>Version: {function}</u>'''
    reply_markup = IKM([[IKB("Back", None, 0)]])
    bot.send_message(chat_id, text, "HTML", True, True, None, reply_markup)
Beispiel #20
0
def make_button(float_hour):
    hour = int(float_hour)
    minute = int(60 * (float_hour - hour))
    hour_text = f'{hour} h ' if hour > 0 else ''
    minute_text = f'{minute} minutes ' if minute > 0 else ''
    button = IKB(
        text=hour_text + minute_text + 'before',
        callback_data=f'{hour}:{minute}',
    )
    return button
Beispiel #21
0
def save_name(update, context):
    ud = context.user_data
    bot = context.bot
    chat_id = update.effective_chat.id
    name = update.message.text
    last_message = ud['last_message']
    bot.delete_message(message_id=update.message.message_id, chat_id=chat_id)
    ud['name_user'] = name
    message = f'Are you satisfied with the name \'{name}\'?'
    keyboard = InlineKeyboardMarkup([
        [IKB('Confirm', callback_data='confirm')],
        [IKB('Change name', callback_data='back')],
    ])
    bot.edit_message_text(
        message_id=last_message.message_id,
        chat_id=chat_id,
        text=message,
        reply_markup=keyboard,
    )
    return ConversationStage.NAME_SAVED
Beispiel #22
0
def Set(u, c):
    reply_markup = IKM([[IKB("Menu Chính", None, 1)]])
    Addr = re.split("^/set ", u.effective_message.text)
    if len(Addr) == 2:
        InsertData("AddrByUser", "", f"{u.effective_user.id},'{Addr[1]}'")
    else:
        Send("Địa Chỉ Bạn Vừa Nhập Sai Hoặc Lỗi Gì Đó!", reply_markup, u, c)
        return None
    Send(
        f"Địa Chỉ Rút Tiền Của Bạn Sẽ Được Lưu Sau 2-60 giây Nữa!\nĐể Tránh Tình Trạng Quá Tải!",
        reply_markup, u, c)
def reply_answer(update: Update, question: str, pos: int):
    answer = get_answers(question, pos)
    warning = answer.get('warning')

    if warning:
        update.message.reply_text(warning, quote=True)
        return

    text = answer.get('answer', 'Not found')
    link = answer.get('link', 'Not found')
    button = [[IKB('Go to Source', url=link)], ]
    markup = InlineKeyboardMarkup(button)

    update.message.reply_text(
        f'`{text[:3000]}` \n/next',
        reply_markup=markup,
        parse_mode=ParseMode.MARKDOWN,
        quote=True)
Beispiel #24
0
def ask_for_meal_name(update, context):
    ud = context.user_data
    bot = context.bot
    chat_id = update.effective_chat.id
    message = ('Tell me what you want to cook! '
               '(just type the name of the meal as an answer to this message)')
    back_keyboard = InlineKeyboardMarkup([[IKB('Back', callback_data='back')]])
    if 'last_message' in ud:
        last_message = ud['last_message']
        bot.edit_message_text(
            message_id=last_message.message_id,
            chat_id=chat_id,
            text=message,
            reply_markup=back_keyboard,
        )
    else:
        ud['last_message'] = bot.send_message(chat_id=chat_id,
                                              text=message,
                                              reply_markup=back_keyboard)
    return ConversationStage.TYPING_MEAL_NAME
def add_button(update: Update, context: CallbackContext):
    args = ' '.join(context.args).strip()
    if not args:
        update.message.reply_text(
            'Please send the text and link with the command. \nExample: \n\n`/add Click here - https://aahnik.github.io`',
            parse_mode=ParseMode.MARKDOWN)
        return
    try:
        splitted = args.split('-')
        print(splitted)
        text = splitted[0].strip()
        url = splitted[1].strip()
        print(text, url)
    except Exception as err:
        update.message.reply_text(str(err)[:2000])
        return

    user_d = context.user_data
    if not 'buttons' in user_d:
        user_d['buttons'] = []
    user_d['buttons'].append([IKB(text, url=url)])
    update.message.reply_text('Done')
    main_menu(update, context)
Beispiel #26
0
    def show_nations_menu(self, bot, game):
        players = game.players.values()

        try:
            player = random.choice([p for p in players if p.nation is None])

        except IndexError:
            self.nations_menu_finalize(bot, game)
            return

        taken = {p.nation for p in players}
        available = [n for n in nations if n not in taken]
        available.append("RANDOM")

        keyboard = IKM([[IKB(n, callback_data="NATION_" + n)]
                        for n in available])

        handle = player.get_handle(bot, game.chat_id)
        message = bot.send_message(game.chat_id,
                                   handle + " choose a nation",
                                   reply_markup=keyboard)

        game.assigning = player.id
        game.assigning_message = message
Beispiel #27
0
from emoji import emojize
from telegram import InlineKeyboardButton as IKB
from telegram import InlineKeyboardMarkup
from telegram.ext import ConversationHandler

from foodshare.bdd.database_communication import (
    add_community,
    add_user,
    add_user_to_community,
    get_token,
)
from foodshare.handlers.start_conversation.first_message import first_message

from . import ConversationStage, get_message

back_keyboard = InlineKeyboardMarkup([[IKB('Back', callback_data='back')]])


def creating_joining(update, context):
    ud = context.user_data
    chat_id = update.effective_chat.id
    if 'name_user' in ud.keys():
        add_user(ud['name_user'], chat_id)
    message = ("Do you want to join an existing community "
               "or create your own?")
    keyboard = InlineKeyboardMarkup([
        [IKB('Join existing community', callback_data='join')],
        [IKB('Create my own', callback_data='create')],
    ])
    bot = context.bot
    if 'last_message' not in ud:
Beispiel #28
0
    def get_message(self,
                    loc,
                    page,
                    item,
                    doc_type=None,
                    chat_id=None,
                    add_text=''):
        message = [0, 0]
        if loc == 'confirm':
            message[0] = 'Check whether all data is correct:\nName: {name}' \
                         '\nAddress: {address}\nPhone: {phone}\nStatus: {status}'.format(**item)
            message[1] = IKM([[
                IKB('Accept✅',
                    callback_data='accept {} {}'.format(item['id'], loc)),
                IKB('Reject️❌',
                    callback_data='reject {} {}'.format(item['id'], loc)),
                IKB('Cancel⤵️', callback_data='cancel {} {}'.format(page, loc))
            ]])
        elif loc in ['library', 'search']:
            text = 'Title: {title}\nAuthors: {authors}\n'
            if doc_type == 'book':
                text += 'Description: {description}\nFree copy: {free_count}'
            elif doc_type == 'article':
                text += 'Journal: {journal}\nIssue: {issue}\nDate: {date}\nFree copy: {free_count}'
            elif doc_type == 'media':
                text += 'Free copy: {free_count}'
            c = add_text + " " + doc_type if add_text else doc_type
            cancel = IKB('Cancel',
                         callback_data='cancel {} {} {}'.format(page, c, loc))
            edit = IKB('Edit',
                       callback_data='edit {} {} {} library'.format(
                           page, item['id'], doc_type))
            delete = IKB('Delete',
                         callback_data='del {} {} {} library'.format(
                             page, item['id'], doc_type))
            if self.controller.user_type(chat_id) == 2:
                cb = 'order {} {} library' if item[
                    'free_count'] > 0 else 'queue {} {} library'
                keyboard = [[
                    IKB('Order the document',
                        callback_data=cb.format(item['id'], doc_type)), cancel
                ]]
            elif self.controller.user_type(chat_id) == 3:
                if item['free_count'] == item['count']:
                    keyboard = [[edit, delete, cancel]]
                else:
                    keyboard = [[edit, cancel]]
            else:
                keyboard = [[cancel]]
            message[0] = text.format(**item)
            message[1] = IKM(keyboard)
        if loc == 'my_orders':
            keys = [
                'user_id', 'doc', 'table', 'time', 'time_out', 'active', 'id'
            ]
            user, doc, doc_type, time, time_out, active, order_id = [
                item[i] for i in keys
            ]
            message[0] = 'Title: {}\nAuthors: {}\nAvailable till: {}'.format(
                doc['title'], doc['authors'], time_out)
            keyboard = []
            if active and not [
                    j for i in utils.to_list(doc['queue']) for j in i
            ]:
                keyboard += [
                    IKB('Renew🔄',
                        callback_data='renew {} {}'.format(order_id, loc))
                ]
            elif not active:
                keyboard += [
                    IKB('Repeal❌',
                        callback_data='repeal {} {}'.format(order_id, loc))
                ]
            keyboard += [
                IKB('Cancel⤵️', callback_data='cancel {} {}'.format(page, loc))
            ]
            message[1] = IKM([keyboard])
        if loc == 'users':
            user = item
            user_id = user['id']
            orders = self.controller.get_user_orders(user_id)
            text = 'Name: {name}\nAddress: {address}\nPhone: {phone}\nStatus: {status}\nTaken documents: '.format(
                **user)
            text += '{}\nOverdue documents: '.format(len(orders))
            overdue = filter(
                lambda i: datetime.strptime(i['time_out'], '%Y-%m-%d') <
                datetime.today(), orders)
            text += str(len(list(overdue)))
            keyboard = [[
                IKB('Edit',
                    callback_data='edit {} {} {}'.format(page, user_id, loc)),
                IKB('Cancel️',
                    callback_data='cancel {} {} {}'.format(
                        page, doc_type, loc))
            ]]
            if orders:
                keyboard[0].insert(
                    1,
                    IKB('Orders',
                        callback_data='orders {} {} {}'.format(
                            page, user_id, loc)))
            else:
                keyboard[0].insert(
                    1,
                    IKB('Delete',
                        callback_data='delete {} {} {}'.format(
                            page, user_id, loc)))
            message[0] = text.format(**user)
            message[1] = IKM(keyboard)

        return message
 def modify_document(self, bot, ids, action, args):
     chat, message_id = ids
     if action == 'order':
         doc_id, doc_type = args
         status, report = self.controller.check_out_doc(chat, int(doc_id), type_bd=doc_type)
         message = "Your order was successful.\nYou may take the document during library working hours." if status else "You already have this document"
         bot.edit_message_text(text=message, chat_id=chat, message_id=message_id)
     elif action == 'queue':
         doc_id, doc_type = args
         status, report = self.controller.add_queue_order(chat, doc_type, int(doc_id))
         message = "You was added in queue.\nYou will be notified when the document be available" if status else report
         bot.edit_message_text(text=message, chat_id=chat, message_id=message_id)
     elif action == 'del':
         message = "Are you sure want to delete this document?"
         markup = IKM([[IKB('Yes', callback_data='yes {} {} library'.format(*args[1:])),
                        IKB('No', callback_data='cancel {} {} library'.format(args[0], args[-1]))]])
         bot.edit_message_text(chat_id=chat, message_id=message_id, text=message, reply_markup=markup)
     elif action == 'yes':
         message = 'Document was deleted successfully'
         self.controller.delete_document(*args)
         bot.edit_message_text(text=message, chat_id=chat, message_id=message_id)
     elif action == 'edit':
         doc_type = args[-1]
         callback = ['e{} {} {} {} library'.format(i, *args) for i in range(9)]
         keyboard = [[IKB("Title", callback_data=callback[0]), IKB("Author", callback_data=callback[1])]]
         if doc_type == 'book':
             keyboard += [
                 [IKB("Description", callback_data=callback[2]), IKB("Keywords", callback_data=callback[3])],
                 [IKB("Price", callback_data=callback[4]), IKB("Count", callback_data=callback[5])]]
         elif doc_type == 'article':
             keyboard += [[IKB("Journal", callback_data=callback[2]), IKB("Issue", callback_data=callback[3])],
                          [IKB("Editors", callback_data=callback[4]), IKB("Date", callback_data=callback[5])],
                          [IKB("Keywords", callback_data=callback[6]), IKB("Price", callback_data=callback[7])],
                          IKB("Count", callback_data=callback[8])]
         elif doc_type == 'media':
             keyboard += [[IKB("Keywords", callback_data=callback[2]), [IKB("Price", callback_data=callback[3])],
                           IKB("Count", callback_data=callback[4])]]
         keyboard += [[IKB('Cancel️', callback_data='cancel {} {} library'.format(args[0], args[-1]))]]
         text = "Choose edited parameter"
         bot.edit_message_text(text=text, chat_id=chat, message_id=message_id,
                               reply_markup=IKM(keyboard))
     elif action in ['e{}'.format(i) for i in range(9)]:
         doc_type = args[-1]
         doc_id = args[1]
         parameter = func_data.lists[doc_type][int(action[1])]
         parameter_db = func_data.lists[doc_type + "_bd"][int(action[1])]
         doc = self.controller.get_document(doc_id, doc_type)
         keyboard = [[IKB('Cancel️', callback_data='cancel {} {} library'.format(args[0], args[-1]))]]
         text = 'Enter new {}.\nOld value - {}.'.format(parameter, doc[parameter_db])
         self.location[chat] = "doc_modify"
         self.user_data[chat] = [doc, parameter_db, doc_type]
         bot.edit_message_text(text=text, chat_id=chat, message_id=message_id, reply_markup=IKM(keyboard))
Beispiel #30
0
def WithdrawAddr(u, c):
    print("WithdrawAddr Calling")
    Data = "Hãy Nhập Theo Mẫu '/set <Địa Chỉ Của Bạn>' Để Đặt Địa Chỉ Rút Tiền!"
    reply_markup = IKM([[IKB("Trở Lại", None, 14)]])
    Send(Data, reply_markup, u, c)