Пример #1
0
def query_settings(callbackquery):
    try:
        key, data = parse_inline_data(callbackquery.data)

        karma = Karma.get_transaction(data[0])
        if karma:
            if not sender_is_admin(karma.chat, callbackquery.from_user.id):
                return bot.answer_callback_query(callbackquery.id,
                                                 'You shall not pass!')

            karma.cancel()
            if karma.rollback:
                bot.answer_callback_query(
                    callbackquery.id,
                    'Transaction ' + data[0] + ' is canceled!')
                text = '#karma #WARNING #Transaction\nCanceled: #{}\nby {} ({})'.format(
                    data[0], get_username_or_name(callbackquery.from_user),
                    callbackquery.from_user.id)
                bot.send_message(LOGGING_CHAT, text)
                notify_chat_admins(karma.chat, text)
            else:
                bot.answer_callback_query(
                    callbackquery.id,
                    'Transaction ' + data[0] + ' is activated!')
                text = '#karma #WARNING #Transaction\nRestored: #{}\nby {} ({})'.format(
                    data[0], get_username_or_name(callbackquery.from_user),
                    callbackquery.from_user.id)
                bot.send_message(LOGGING_CHAT, text)
                notify_chat_admins(karma.chat, text)

        bot.answer_callback_query(callbackquery.id, 'Wrong transaction!')
    except:
        with CrashReport(*sys.exc_info()) as c:
            log.warning(c.formatted_traceback)
            c.save()
Пример #2
0
def cmd_start(message, user, chat):
    typing(message)
    if message.chat.type == 'private':
        bot.send_message(
            message.chat.id,
            _('hello {user_name}', locale=user.locale).format(
                user_name=get_username_or_name(message.from_user)))
Пример #3
0
def cmd_top(message):
    try:
        typing(message)
        karma_records = Karma.objects(chat=message.chat.id)
        users = {}
        for karma in karma_records:
            if karma.rollback:
                continue
            if karma.from_user and karma.transfer:
                users[karma.from_user] = users.get(karma.from_user,
                                                   0) - karma.amount
            if karma.to_user:
                users[karma.to_user] = users.get(karma.to_user,
                                                 0) + karma.amount

        text = ['Статистика:']

        if bot_id in users:
            users.pop(bot_id)

        for index, (user, karma) in enumerate(sorted(users.items(),
                                                     key=lambda x: x[1],
                                                     reverse=True),
                                              start=1):
            if index > 10:
                break
            text.append('{}) {}: {}'.format(
                index, get_username_or_name(bot.get_chat(user)), karma))
        bot.send_message(message.chat.id,
                         '\n'.join(text),
                         disable_notification=True)
    except:
        crash_message(message)
Пример #4
0
def cmd_statistic(message):
    try:
        typing(message)
        if bool(message.reply_to_message):
            user = message.reply_to_message.from_user
        else:
            user = message.from_user
        karma = get_cached_user_karma(user.id, message.chat.id)

        # TODO: translate
        bot.reply_to(
            message, 'Статистика пользователя {user}:\nКарма: {karma}'.format(
                user=get_username_or_name(user), karma=karma))
    except:
        crash_message(message)
Пример #5
0
def reset_chat_karma(chat):
    chat_karma = Karma.objects(chat=chat.id)

    counter = 0
    for karma in chat_karma:
        if not karma.rollback:
            karma.revoke()
            counter += 1

    # reset_cache()
    reset_cached_chat_karma(chat)
    generate_karma_cache()

    log.warning('Reset karma for chat: {} (<code>{}</code>)\n'
                '<code>{}</code> transactions'.format(
                    chat.title or get_username_or_name(chat), chat.id,
                    counter))
    return counter
Пример #6
0
def cmd_messages_count(message):
    try:
        typing(message)
        date = datetime.now(TIMEZONE) - timedelta(days=1)
        users = Messages.calculate(message.chat.id, date)

        text = ['Топ флудеров за последние 24 часа:']

        if bot_id in users:
            users.pop(bot_id)

        for index, (user, karma) in enumerate(sorted(users.items(),
                                                     key=lambda x: x[1],
                                                     reverse=True),
                                              start=1):
            if index > 10:
                break
            text.append('{}) {}: {} сбщ.'.format(
                index, get_username_or_name(bot.get_chat(user)), karma))
        bot.send_message(message.chat.id,
                         '\n'.join(text),
                         disable_notification=True)
    except:
        crash_message(message)
Пример #7
0
def log_transaction(transaction,
                    chat=0,
                    from_user=0,
                    to_user=0,
                    amount=0,
                    description='',
                    transfer=True):
    try:
        if type(chat) is telebot.types.Chat:
            chat = chat
        else:
            chat = bot.get_chat(chat)
    except:
        chat = None

    try:
        if type(from_user) is telebot.types.User:
            from_user = from_user
        else:
            from_user = bot.get_chat(from_user)
    except:
        from_user = None

    try:
        if type(to_user) is telebot.types.User:
            to_user = to_user
        else:
            to_user = bot.get_chat(to_user)
    except:
        to_user = None

    message = ['#karma #INFO #Transaction ID: #{}'.format(transaction)]
    if chat:
        message.append('Dialog: {} (<code>{}</code>)'.format(
            chat.title or get_username_or_name(chat), chat.id))

    if from_user:
        message.append('From: {} (<code>{}</code>)'.format(
            get_username_or_name(from_user), from_user.id))
        if transfer:
            message.append('\tResult amount: <i>{}</i>'.format(
                get_cached_user_chat(from_user.id,
                                     chat.id).get(KARMA_FIELD_NAME, 0)))
    if to_user:
        message.append('To: {} (<code>{}</code>)'.format(
            get_username_or_name(to_user), to_user.id))
        message.append('\tResult amount: <i>{}</i>'.format(
            get_cached_user_chat(to_user.id, chat.id).get(KARMA_FIELD_NAME,
                                                          0)))
    else:
        message.append('To: <code>/dev/null</code>')

    message.append('Description: <code>{}</code>'.format(description))
    message.append('Amount: <code>{}</code>'.format(amount))

    markup = telebot.types.InlineKeyboardMarkup()
    markup.add(
        telebot.types.InlineKeyboardButton('Cancel',
                                           callback_data=generate_inline_data(
                                               'CANCEL_TRANSACTION',
                                               [str(transaction)])))
    bot.send_message(LOGGING_CHAT,
                     '\n'.join(message),
                     parse_mode='html',
                     reply_markup=markup)
    notify_chat_admins(chat.id, '\n'.join(message), markup=markup)
Пример #8
0
def vote_message(message, description='', amount=1):
    # TODO: anti spam
    if bool(
            message.reply_to_message
    ) and message.reply_to_message.from_user.id != message.from_user.id:
        user_cache = get_cached_user_chat(message.from_user.id,
                                          message.chat.id)
        last_message = user_cache.get('last_message', 0)
        timeout = user_cache.get('karma_change_timeout', ANTI_FLOOD_TIMEOUT)
        warn_count = user_cache.get('karma_change_warn', 0) + 1
        update_cached_user(
            message.from_user.id, message.chat.id, {
                'last_message':
                time.time(),
                'karma_change_timeout':
                time.time() - last_message + ANTI_FLOOD_TIMEOUT * warn_count,
                'karma_change_warn':
                warn_count
            })
        if time.time() - last_message < timeout:
            log.warning(
                '#flood {user} (<code>{user_id}</code>) is flooding <b>x{count}</b>!\n'
                'Chat "{chat}" (<code>{chat_id}</code>)\n'
                'Set timeout: {timeout:.1f}'.format(
                    user=get_username_or_name(message.from_user),
                    user_id=message.from_user.id,
                    count=warn_count,
                    chat=message.chat.title,
                    chat_id=message.chat.id,
                    timeout=get_cached_user_chat(message.from_user.id,
                                                 message.chat.id).get(
                                                     'karma_change_timeout',
                                                     ANTI_FLOOD_TIMEOUT)))
            return bot.reply_to(
                message,
                _('anti spam karma {timeout:.0f}s').format(
                    timeout=timeout - (time.time() - last_message)))
        update_cached_user(message.from_user.id, message.chat.id, {
            'karma_change_timeout': ANTI_FLOOD_TIMEOUT,
            'karma_change_warn': 0
        })

        karma_transaction(message.chat,
                          message.from_user,
                          message.reply_to_message.from_user,
                          amount=amount,
                          description=bool_to_str(amount > 0, 'good message',
                                                  'bad message'),
                          transfer=False)
        user = get_dialog_object(message.reply_to_message.from_user.id)

        if user.subscribe:
            try:
                if amount > 0:
                    text = _('{user} thanked you chatting {chat}',
                             locale=user.locale)
                elif amount < 0:
                    text = _(
                        '{user} did not like your message in the chat {chat}',
                        locale=user.locale)
                else:
                    text = _(
                        'User {user} is indifferent to your message in the chat {chat}',
                        locale=user.locale)

                if len(description):
                    text += '\n' + _('Comment: {text}')
                bot.send_message(
                    message.reply_to_message.from_user.id,
                    text.format(user=get_username_or_name(message.from_user),
                                chat=get_chat_url_or_title(message),
                                text=description),
                    disable_web_page_preview=True,
                    parse_mode='markdown')
                bot.forward_message(message.reply_to_message.from_user.id,
                                    message.chat.id,
                                    message.reply_to_message.message_id,
                                    disable_notification=True)
            except:
                pass