示例#1
0
def read_learn_public(public_id, shell):
    amount = 10
    cur = 0
    public = []
    while cur < amount:
        pars = {
            'owner_id': public_id,
            'count': 100,
            'offset': cur,
        }
        is_lana = 1 if config.BOT_LEARN_PUBLIC == config.MAIN_LEARN_PUBLIC else 0
        posts = api.query(u'wall.get', pars, lana=is_lana)
        if posts is None or posts.get('error') is not None:
            cur += 10
            continue
        posts = posts['response']
        amount = posts['count']
        posts = posts['items']
        for post in posts:
            post['text'] = text_utils.remove_extra_symbols(post['text'])
            if shell:
                print post['text']
            questions = [el.strip() for el in post['text'].split(u'//')]
            public.append({
                'id': post['id'], 
                'question': questions[0], 
                'answers': [],
                'same_as': questions[1:]
                })
            params = {
                'owner_id': post['owner_id'],
                'post_id': post['id'],
                'count': 100,
                'need_likes': 1,
            }
            comments = api.query(u'wall.getComments', params, lana=is_lana)
            time.sleep(0.3)
            if comments is None or comments.get('error') is not None:
                time.sleep(0.5)
                comments = api.query(u'wall.getComments', params, lana=is_lana)
            if comments is None or comments.get('error') is not None:
                logger.log(u'Не удалось получить комменты к посту с вопросом: ' + post['text'])
                continue
            comments = comments['response']['items']
            for comm in comments:
                if comm['likes']['count'] >= config.LIKES_TO_BE_IN_ANSWERS or comm['likes']['user_likes'] == 1:
                    text_to_append = text_utils.remove_links(comm['text'])
                    if comm.get('attachments'):
                        for el in comm['attachments']:
                            text_to_append += config.SPLIT_SIGN + unicode(el['type']) + \
                                            unicode(el[el['type']]['owner_id']) + u'_' + unicode(el[el['type']]['id'])
                    public[-1]['answers'].append(text_to_append)


        cur += len(posts)
    #for post in public:
    #    print post
    return public
    def answer_anon(self):
        fwd = self.dialog.last_message.fwd_messages
        if fwd is None or len(fwd) == 0:
            return self.dialog.answer(u'Пожалуйста, прикрепите анонимное сообщение, на которое хотите ответить.')
        if len(fwd) != 1:
            return self.dialog.answer(u'Пожалуйста, прикрепите только одно сообщение.')

        respond = fwd[0]
        if respond['user_id'] != config.BOT_ID:
            return self.dialog.answer(u'Ой-ой. Мне кажется прикрепленная анонимка не от меня.')
        
        user_id = self.dialog.last_message.user_id
        anon_messages = db.anon_messages
        hashed = hash(respond['body'])
        history = anon_messages.history.find_one({'user_id': user_id, 'hashed': hashed})
        #add time checking here. In case there are same messages.
        if history is None:
            return self.dialog.answer(u'Я не помню такого анонимного сообщения ' + smiles['sad'])

        to_answer = {
            'text': history['text'],
            'anon_id': history['anon_id'],
            'user_name': history['user_name']
        }

        args = self.dialog.last_message.args
        if len(args) <= 1:
            return self.dialog.answer(u'Введите ваше сообщение после слова "ответ".')
        else:
            body = u' '.join(args[1:])
            body = text_utils.remove_links(body)

        text = u'На ваше анонимное сообщение: «' + to_answer['text'] + u'»\n' +\
               unicode(to_answer['user_name']) +\
               u"(id" + unicode(self.dialog.last_message.user_id) + u") ответил: «" 
        text += u"{}»".format(body)

        res = api.query('messages.send', {'user_id': to_answer['anon_id'], 'message': text, 'title': u'Ответ на анонимку'})
        ok = res.get('error')

        time.sleep(0.5)
        if ok is not None:
            self.dialog.answer(u'Ваше сообщение не было отправлено из-за настроек приватности адресата. ')
        else:
            self.dialog.answer(u'Ваш ответ скорее всего уже доставлен:)')

        return res
    def run(self):
        args = self.dialog.last_message.args
        if len(args) == 0:
            return self.dialog.answer(u'Пожалуйста, введите после слова "анонимно" ссылку на профиль человека Вконтакте, которому предназначено сообщение, а потом само сообщение')
        anonid = unicode(args[0])
        if anonid == u'ответ':
            return self.answer_anon()
        anonid = anonid.replace(u'https://vk.com/', u'')
        anonid = anonid.replace(u'http://vk.com/', u'')
        anonid = anonid.replace(u'vk.com/', u'')
        anonid = unicode(anonid)
        if anonid == u'iris_helper' or anonid == u'id224327479' or anonid == u'eric_helper' or anonid == u'id243758493':
            return self.dialog.answer(u'Мне не нужно ничего писать:Р')
        anonmess = u''
        if len(args) > 1:
            anonmess = u' '.join(args[1:])
            old_anon = anonmess
            anonmess = text_utils.remove_links(anonmess)
            if len(anonmess)!=len(old_anon):
                text_had_links = True
            else:
                text_had_links = False
            original_anonmess = anonmess
            anonmess = u'«' + anonmess + u'», – кто-то написал вам анонимно. \n'
            anonmess += u'\nВы можете ответить на анонимку, написав "анонимно ответ <текст>" и прикрепив это сообщение.'
        else:
            return self.dialog.answer(u'Введите сообщение после ссылки на профиль адресата. ')
        #check if clocked here
        res = self.dialog.answer(unicode(anonmess),domain=anonid, title=u'Анонимное сообщение')
        ok = res.get('error')
        time.sleep(0.5)
        if ok is not None:
            self.dialog.answer(u'Ваше сообщение не было отправлено из-за настроек приватности адресата. ')
        else:
            if text_had_links:
                no_links = u'\nЯ вырезала ссылку из вашего сообщения. Давай больше не будем их отправлять, пожалуйста?:)'
            else:
                no_links = ''
            self.dialog.answer(u'Ваше сообщение доставлено с большой вероятностью :)' + no_links)

            self.dump_anon(self.dialog.last_message.user_id, unicode(original_anonmess), anonid, res)
        return
def translate_irisscript(q):
    q = text_utils.remove_links(q)
    now = datetime.now()
    variables = {
        'mood': 6,
        'year': now.year,
        'month': now.month,
        'day': now.day, 
        'hour': now.hour,
        'minute': now.minute,
        'second': now.second,
        'random': random.randint(0, 1000),
    }
    pref = u'varss.'
    relations = {
        u'настроение': pref + u'mood',
        u'год': pref + u'year',
        u'месяц': pref + u'month',
        u'день': pref + u'day',
        u'час': pref + u'hour',
        u'минута': pref + u'minute',
        u'секунда': pref + u'second',
        u'рандом': pref + u'random',
        u'если': u'if',
        u'все': u'endif',
        u'если_иначе': u'elif',
        u'иначе': u'else',
        u'напиши': u'write',
        u'и': u'and',
        u'или': u'or',
        u'больше': u'>',
        u'меньше': u'<',
        u'меньше_равно': u'>=',
        u'больше_равно': u'<=',
        u'равно': u'==',
        u'не_равно': u'!=',
        u'равен': u'==',

    }
    t = u''
    last_pos = 0
    while 1:
        start = q.find(u'{', last_pos)
        if start == -1:
            break
        t += q[last_pos:start]
        end = q.find(u'}', last_pos)
        last_pos = end + 1
        commands = q[start + 1:end].split()  
        commands = [el.lower() for el in commands]
        for i in xrange(len(commands)):
            for el in relations:
                if el == commands[i]:
                    commands[i] = relations[el]
                    break
        if len(commands) == 2 and commands[0] == u'write':
            t += u'{{ ' + commands[1] + u' }}'    
        else:
            t += u'{% ' + u' '.join(commands) + u' %}'    

    t += q[last_pos:]
    #print t
    template = Template(t)
    ans = template.render(varss = variables)
    if len(ans.strip()) == 0:
        return None
    else:
        return ans