Example #1
0
def less_callback(bot, message):
    with db:
        chat = Chats.get(Chats.cid == message.chat.id)

    clean_chat(chat.mids, chat.cid, bot, message)

    user = bot.get_chat_member(chat_id=message.chat.id,
                               user_id=message.from_user.id)

    if message.from_user.id == chat.invited_by or\
            user.status == 'administrator' or\
            user.status == 'creator':
        if chat.less is False:
            text = silenced_mode_on_phrase
            chat.less = True
        else:
            chat.less = False
            text = silenced_mode_off_phrase
        mid = bot.send_message(chat_id=chat.cid, text=text,
                               parse_mode='html').message_id
        chat.mids = json.dumps([mid])
        with db:
            chat.save()
    else:
        text = admins_only_phrase
        mid = bot.send_message(chat_id=chat.cid, text=text,
                               parse_mode='html').message_id
        chat.mids = json.dumps([mid])
        with db:
            chat.save()
Example #2
0
def validate_callback(update: Update, context: CallbackContext):
    cid = update.effective_message.chat.id
    q = update.message.document

    clean_chat(update, context)

    if q is None:
        mid = update.message.reply_text(no_file_text).message_id
        context.chat_data['message_ids'].append(mid)
        return

    q = q.to_dict()
    if q['file_size'] > 5 * (10**7):
        mid = update.message.reply_text(big_file_text).message_id
        context.chat_data['message_ids'].append(mid)

        return

    context.chat_data.update({
        'query': q,
        'update': update,
        'current_section': 'file_section'
    })

    file_functions_callback(update, context)
Example #3
0
def taco_mention_callback(bot, message):
    """ callback for taco-transfer by mention """

    cid = get_cid(message)
    store_name(message)

    chat = Chats.get(Chats.cid == message.chat.id)
    clean_chat(chat.mids, chat.cid, message, bot)

    ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format(message.from_user.id))
    ok_keyboard = InlineKeyboardMarkup([[ok_button]])

    mentioned_users = list()
    for entity in message.entities:
        if entity.type == 'mention':
            user = message.text[entity.offset: entity.offset + entity.length].lower()
            mentioned_users.append(user)
    mentioned_users = list(set(mentioned_users))   # removing duplicates

    if len(mentioned_users) > 1:
        if chat.less is True:
            text = only_one_receiver_phrase.split('\n')[0]
        else:
            text = only_one_receiver_phrase
        mid = bot.send_message(chat_id=cid,
                         text=text,
                         reply_to_message_id=get_mid(message),
                               reply_markup=ok_keyboard,
                         parse_mode='html').message_id

        chat.mids = json.dumps([mid])
        chat.save()
        return

    sender = message.from_user
    receiver_username: str = ensure_no_at_sign(mentioned_users[0])

    try:
        receiver = bot.get_chat_member(chat_id=cid,
                                       user_id=receiver_username).user

    except Exception:
        """ here should be except UserNotParticipant, but it still raises this exception """
        if chat.less is True:
            text = user_not_present_phrase.split('\n')[0]
        else:
            text = user_not_present_phrase
        mid = bot.send_message(chat_id=cid,
                         text=text.format(ensure_username(receiver_username)),
                         reply_to_message_id=get_mid(message),
                               reply_markup=ok_keyboard,
                         parse_mode='html').message_id

        chat.mids = json.dumps([mid])
        chat.save()

        return

    give_tacos(bot, message, sender, receiver)
Example #4
0
def start_callback(update: Update, context: callbackcontext):
    """ /start callback (private chat only)"""

    clean_chat(update, context)
    store_user(update)

    update.message.reply_text(text=start_phrase,
                              parse_mode=ParseMode.HTML)
Example #5
0
def chat_reply_callback(bot, message):
    """ callback for taco-transfer """

    store_name(sender := message.from_user)
    store_name(receiver := message.reply_to_message.from_user)

    chat = Chats.get(Chats.cid == message.chat.id)
    clean_chat(chat.mids, chat.cid, bot, None)

    give_tacos(bot, message, sender, receiver)
Example #6
0
def taco_top_callback(bot, message):
    """ shows top-5(or less) taco-users in chat """

    cid = get_cid(message)
    mid = get_mid(message)
    store_name(message)

    chat = Chats.get(Chats.cid == message.chat.id)
    clean_chat(chat.mids, chat.cid, message, bot)

    ok_button = InlineKeyboardButton('OK',
                                     callback_data='delete:{}'.format(
                                         message.from_user.id))
    ok_keyboard = InlineKeyboardMarkup([[ok_button]])

    tacos = Tacos.get(Tacos.chat == cid)

    balances = json.loads(tacos.taco_balance)

    if len(balances) == 0:  # in case tacos-table is empty
        bot.send_message(text=empty_top_phrase,
                         chat_id=cid,
                         reply_to_message_id=mid,
                         reply_markup=ok_keyboard,
                         parse_mode='html')
        return

    top = list()

    while len(balances) > 0 and len(top) < 5:
        top_uid = max(balances, key=balances.get)
        username = resolve_name(top_uid)
        top.append([username, balances.get(top_uid)])
        del balances[top_uid]

    formatted_top = ''
    for user in top:
        if "@" in user[0]:
            user_link = "https://t.me/{}".format(user[0][1:])
        else:
            user_link = "tg://user?id={}".format(user[0])

        formatted_top += '{}. <a href="{}">{}</a> - <code>{}</code> tacos!\n'.format(
            top.index(user) + 1, user_link, user[0][1:], user[1])

    mid = bot.send_message(text=taco_top_phrase.format(len(top),
                                                       formatted_top),
                           chat_id=cid,
                           reply_to_message_id=mid,
                           reply_markup=ok_keyboard,
                           parse_mode='html',
                           disable_web_page_preview=True).message_id

    chat.mids = json.dumps([mid])
    chat.save()
Example #7
0
def new_user_callback(update: Update, context: CallbackContext):
    username = update.message.chat.username
    update.message.reply_text(welcome_text.format(username))
    if context.chat_data.get('url_section', None) is None:
        context.chat_data.update({'url_section': {}})
        context.chat_data.update({'file_section': {}})
        context.chat_data.update({'short_text_section': {}})
        context.chat_data.update({'history_section': {}})

    clean_chat(update, context)
    menu_callback(update, context)
Example #8
0
def menu_callback(update: Update, context: CallbackContext):
    cid = update.effective_message.chat.id
    q = update.message.text

    clean_chat(update, context)
    context.bot.send_message(chat_id=cid,
                             text=choose_text,
                             parse_mode=ParseMode.HTML,
                             reply_markup=menu_kb)

    return ConversationHandler.END
Example #9
0
def autohide_delay_callback(bot, message):
    with db:
        chat = Chats.get(Chats.cid == message.chat.id)

    clean_chat(chat.mids, chat.cid, bot, message)

    try:

        user = bot.get_chat_member(chat_id=message.chat.id,
                                   user_id=message.from_user.id)
    except Exception as e:
        print(e)
        bot.send_message(
            chat_id=chat.cid,
            text='<b>An error occurred, please contact @Lor3m.</b>',
            parse_mode='html')
        return

    if message.from_user.id == chat.invited_by or\
            user.status == 'administrator' or\
            user.status == 'creator':

        if (args := len(message.command)) == 1:
            delay = 15
        elif args > 2:
            bot.send_message(chat_id=chat.cid,
                             text=autohide_delay_wrong_value_phrase,
                             parse_mode='html')
            return
        else:
            try:
                delay = int(message.command[1])
            except ValueError:
                bot.send_message(chat_id=chat.cid,
                                 text=autohide_delay_wrong_value_phrase,
                                 parse_mode='html')
                return

        if delay < 1 or delay > 120:
            bot.send_message(chat_id=chat.cid,
                             text=autohide_delay_wrong_value_phrase,
                             parse_mode='html')
            return

        chat.autohide_delay = delay

        mid = bot.send_message(chat_id=chat.cid,
                               text=autohide_delay_set_phrase.format(delay),
                               parse_mode='html').message_id

        chat.mids = json.dumps([mid])
        with db:
            chat.save()
Example #10
0
def query_callback(update: Update, context: callbackcontext):
    """ search query callback (private chat only) """

    cid = get_cid(update)
    q = update.message.text

    clean_chat(update, context)
    store_user(update)

    message_id = context.bot.send_message(chat_id=cid,
                                          text=searching_phrase,
                                          parse_mode=ParseMode.HTML).message_id

    results = parse_html(get_html(add_url(format_query(q))))

    if len(results) == 0:

        context.bot.edit_message_text(chat_id=cid,
                                      message_id=message_id,
                                      text=no_results_phrase,
                                      parse_mode=ParseMode.HTML)

        context.chat_data.update({'message_ids': [message_id]})

        return

    context.chat_data.update({'results': results})

    download_button = InlineKeyboardButton(text=download_button_text,
                                           callback_data='download:0')

    if len(results) > 1:
        next_button = InlineKeyboardButton(text=next_button_text,
                                           callback_data='track:1')

        keyboard = InlineKeyboardMarkup([[download_button],
                                         [next_button]])
    else:

        keyboard = InlineKeyboardMarkup([[download_button]])

    context.bot.edit_message_text(chat_id=cid,
                                  message_id=message_id,
                                  text=track_form.format(1,
                                                         len(results),
                                                         results[0]['performer'],
                                                         results[0]['title'],
                                                         results[0]['duration']),
                                  parse_mode=ParseMode.HTML,
                                  reply_markup=keyboard)

    context.chat_data.update({'message_ids': [message_id]})
Example #11
0
def validate_callback(update: Update, context: CallbackContext):
    cid = update.effective_message.chat.id
    q = update.message.text.lstrip().rstrip()

    clean_chat(update, context)

    if not validators.url(q):
        mid = update.message.reply_text(text=unvalid_text).message_id
        context.chat_data.update({'message_ids': [mid]})
        return
    context.chat_data.update({
        'query': q,
        'update': update,
        'current_section': 'url_section'
    })

    url_functions_callback(update, context)
Example #12
0
def my_tacos_callback(bot, message):
    """ shows users taco-balance """

    cid = get_cid(message)
    chat = Chats.get(Chats.cid == message.chat.id)

    clean_chat(chat.mids, chat.cid, message, bot)

    store_name(message)

    uid = str(get_uid(message))
    tacos = Tacos.get(Tacos.chat == cid)

    ok_button = InlineKeyboardButton('OK',
                                     callback_data='delete:{}'.format(
                                         message.from_user.id))
    ok_keyboard = InlineKeyboardMarkup([[ok_button]])

    balances = json.loads(tacos.taco_balance)

    if uid in balances.keys():
        balance = balances.get(uid)
    else:
        balances.update({uid: default_taco_amount})
        tacos.taco_balance = json.dumps(balances)
        tacos.save()
        balance = default_taco_amount

    if chat.less is True:
        comment = ''
    else:
        if balance < 25:
            comment = balance_comment_low
        elif balance > 60:
            comment = balance_comment_high
        else:
            comment = balance_comment_medium

    mid = bot.send_message(chat_id=cid,
                           text=balance_phrase.format(balance, comment),
                           reply_to_message_id=get_mid(message),
                           reply_markup=ok_keyboard,
                           parse_mode='html').message_id

    chat.mids = json.dumps([mid])
    chat.save()
Example #13
0
def less_callback(bot, message):
    chat = Chats.get(Chats.cid == message.chat.id)
    clean_chat(chat.mids, chat.cid, message, bot)

    if message.from_user.id == chat.invited_by:
        if chat.less is False:
            text = '<b>Silenced mode has been turned ON.</b>'
            chat.less = True
        else:
            chat.less = False
            text = '<b>Silenced mode has been turned OFF.</b>'
        mid = bot.send_message(chat_id=chat.cid, text=text,
                               parse_mode='html').message_id
        chat.mids = json.dumps([mid])
        chat.save()
    else:
        text = '<b>Sorry, but only user that invited me can use this command :(</b>'
        mid = bot.send_message(chat_id=chat.cid, text=text,
                               parse_mode='html').message_id
        chat.mids = json.dumps([mid])
        chat.save()
    pass
Example #14
0
def validate_callback(update: Update, context: CallbackContext):
    cid = update.effective_message.chat.id
    q = update.message.text.lstrip().rstrip()

    clean_chat(update, context)

    if len(q) > 500:
        mid = update.message.reply_text(big_text)
        context.chat_data.update({'message_ids': [mid]})
        return

    if not validators.url(q) and len(q.split(' ')) == 1:
        mid = update.message.reply_text(unvalid_text)
        context.chat_data.update({'message_ids': [mid]})
        return

    context.chat_data.update({
        'query': q,
        'update': update,
        'current_section': 'short_text_section'
    })

    short_text_functions_callback(update, context)
Example #15
0
def give_tacos(bot, message, sender, receiver):
    cid = get_cid(message)
    tacos = Tacos.get(Tacos.chat == cid)

    chat = Chats.get(Chats.cid == message.chat.id)
    clean_chat(chat.mids, chat.cid, message, bot)

    ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format(message.from_user.id))
    ok_keyboard = InlineKeyboardMarkup([[ok_button]])

    if receiver.username is None:
        first_name = receiver.first_name
        last_name = receiver.last_name
        if last_name is None:
            receiver_name = first_name
        else:
            receiver_name = first_name + " " + last_name
    else:
        receiver_name = "@" + receiver.username

    if receiver.is_bot:  # no tacos for bots
        if chat.less is True:
            text = no_bots_allowed_phrase.split('\n')[0]
        else:
            text = no_bots_allowed_phrase
        mid = bot.send_message(chat_id=cid,
                         text=text,
                         reply_to_message_id=get_mid(message),
                               reply_markup=ok_keyboard,
                         parse_mode='html').message_id

        chat.mids = json.dumps([mid])
        chat.save()
        return

    sender_id = str(sender.id)
    receiver_id = str(receiver.id)

    if sender_id == receiver_id:  # self-tacoing is forbidden
        if chat.less is True:
            text = self_tacoing_phrase.split('\n')[0]
        else:
            text = self_tacoing_phrase
        mid = bot.send_message(chat_id=cid,
                         text=text,
                         reply_to_message_id=get_mid(message),
                         parse_mode='html').message_id

        chat.mids = json.dumps([mid])
        chat.save()
        return

    tacos_sent = len(
        re.findall(taco_emoji, message.text)
    )

    if tacos.taco_balance is None:  # initialising/restoring user-balances
        amounts = dict()
        amounts.update({sender_id: default_taco_amount})
        amounts.update({receiver_id: default_taco_amount})
    else:
        amounts = json.loads(tacos.taco_balance)
        if sender_id not in amounts.keys():
            amounts.update({sender_id: default_taco_amount})
        if receiver_id not in amounts.keys():
            amounts.update({receiver_id: default_taco_amount})

    if tacos_sent > amounts.get(sender_id):  # can't send more than you have
        if chat.less is True:
            text = balance_low_phrase.split('\n')[0]
        else:
            text = balance_low_phrase
        mid = bot.send_message(chat_id=cid,
                         text=text,
                         reply_to_message_id=get_mid(message),
                         parse_mode='html').message_id

        chat.mids = json.dumps([mid])
        chat.save()
        return

    amounts.update(
        {sender_id: amounts.get(sender_id) - tacos_sent}
    )
    amounts.update({receiver_id: amounts.get(receiver_id) + tacos_sent})
    if chat.less is True:
        comment = ''
    else:
        if tacos_sent < 3:
            comment = taco_transfer_comment_low
        elif tacos_sent > 9:
            comment = taco_transfer_comment_high
        else:
            comment = taco_transfer_comment_medium.format(receiver_name)

    mid = bot.send_message(chat_id=cid,
                     text=taco_transfer_phrase.format(tacos_sent, receiver_name, comment),
                           reply_markup=ok_keyboard,
                     reply_to_message_id=get_mid(message),
                     parse_mode='html').message_id

    chat.mids = json.dumps([mid])
    chat.save()

    tacos.taco_balance = json.dumps(amounts)  # saving data
    tacos.save()
Example #16
0
def taco_top_callback(bot, message):
    """ shows top-5(or less) taco-users in chat """

    cid = get_cid(message)
    mid = get_mid(message)

    store_name(message.from_user)

    chat = Chats.get(Chats.cid == message.chat.id)
    clean_chat(chat.mids, chat.cid, bot, message)

    ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format(message.from_user.id))
    ok_keyboard = InlineKeyboardMarkup([[ok_button]])

    tacos = Tacos.get(Tacos.chat == cid)

    balances = tacos.taco_balance

    if len(balances) == 0:

        if chat.autohide:
            msg = bot.send_message(text=empty_top_phrase,
                                   chat_id=cid,
                                   parse_mode='html')

            time = datetime.datetime.now() + datetime.timedelta(minutes=chat.autohide_delay)

            sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg])

        else:
            bot.send_message(text=empty_top_phrase,
                             chat_id=cid,
                             reply_markup=ok_keyboard,
                             parse_mode='html')
        return

    top = list()

    while len(balances) > 0 and len(top) < 5:
        top_uid = max(balances, key=balances.get)
        username = resolve_name(top_uid)
        top.append([username, balances.get(top_uid)])
        del balances[top_uid]

    formatted_top = ''
    for user in top:
        if "@" in user[0]:
            user_link = "https://t.me/{}".format(user[0][1:])
        else:
            user_link = "tg://user?id={}".format(user[0])

        formatted_top += '{}. <a href="{}">{}</a> - <code>{}</code> tacos!\n'.format(top.index(user) + 1,
                                                                                     user_link,
                                                                                     user[0][1:],
                                                                                     user[1])

    if chat.autohide:
        msg = bot.send_message(text=taco_top_phrase.format(len(top),
                                                           formatted_top),
                               chat_id=cid,
                               parse_mode='html',
                               disable_web_page_preview=True)

        time = datetime.datetime.now() + datetime.timedelta(minutes=chat.autohide_delay)

        sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg])

    else:
        bot.send_message(text=taco_top_phrase.format(len(top),
                                                     formatted_top),
                         chat_id=cid,
                         reply_markup=ok_keyboard,
                         parse_mode='html',
                         disable_web_page_preview=True)

    chat.mids.append(mid)
    chat.save()