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 mark_as_read(self): TIME_TO_READ = 5 now = time.time() mid = self.id #to_mark = db.mark_as_read.find_one() global MESSAGES_TO_MARK_AS_READ if 'MESSAGES_TO_MARK_AS_READ' not in globals(): MESSAGES_TO_MARK_AS_READ = [-now] MESSAGES_TO_MARK_AS_READ.append(mid) start_from = -MESSAGES_TO_MARK_AS_READ[0] if start_from <= 0 or now - start_from >= config.TIME_TO_MARK_AS_READ: to_mark_str = ','.join(map(str, MESSAGES_TO_MARK_AS_READ[1:])) api.query('messages.markAsRead', {'message_ids': to_mark_str}, timeout=0.03, verify_ssl=False) #r = requests.get(self.prefix + 'messages.markAsRead', params=pars) #html = json.loads(r.text) MESSAGES_TO_MARK_AS_READ = [-now]
def run(self): dialog = self.dialog args = dialog.last_message.args if len(args) > 0: query = u' '.join(args) else: query = None if query: pars = { 'query': query } r = api.query(u'execute.search_songs', pars, bot=dialog.bot) audio = r["response"] return dialog.answer(u'Найдено по запросу "' + query + u'":', audio) else: pars['user_id'] = config.MUSIC_ID r = api.query(u'execute.song', pars, bot=dialog.bot) audio = r["response"] return dialog.answer(u'Рекомендовано вам :)', unicode(audio))
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 main(from_shell=False): bot = Bot() if from_shell: print u'Bot ' + unicode(bot.name) + u' is running!' while True: try: time_offset = math.ceil(sleep_enough()) response = api.query('messages.get',\ {'count': unicode(config.NUMBER_MESSAGES), 'time_offset': unicode(time_offset)}, bot=bot) if response is None or response.get('response') is None: sleep_time = config.SLEEP_SERVER_FALL if response is None else config.SLEEP_VK_NO_RESPONSE time.sleep(sleep_time) print response.get('error') continue messages = response['response'] messages = messages['items'][::-1] for mess in messages: message = Message(mess, bot) if message.is_mine(): if message.id not in MESSAGES_RESPONDED: message.mark_as_read() message.identify_command() dialog = Dialog(message) sleep_enough() successful = dialog.run() if successful: MESSAGES_RESPONDED.append(message.id) MESSAGES_RESPONDED.popleft() else: del message except Exception as e: if from_shell: print traceback.format_exc() try: logger.error(traceback.format_exc()) except: logger.error(u'Mistake in except, lololol.') continue
def answer(self, text, attachment=None, domain=None, title=None): receiver = 'chat_id' if self.dialog_id < 0 else 'user_id' receiver_id = abs(self.dialog_id) pars = { 'message': text, receiver: unicode(receiver_id), #'access_token': tokens.get_token(), 'guid': random.randint(0, 1000000), } if attachment is not None: pars['attachment'] = attachment if title is not None: pars['title'] = title if domain is not None: del pars[receiver] pars['domain'] = domain response = api.query(u'messages.send', args=pars, bot=self.bot) info = vk_utils.get_bot_info() if info is None: logger.err(u'Не удалось получить информацию о боте, ответ не отправлен. ') return None if response is None: logger.log(u'Ничего не пришло в ответ от Vk в classes.py@answer') return response if response.get('error') is None: if info['status'] != 'ok': #api.query(u'account.setOnline') vk_utils.set_bot_status(info, 'ok') else: logger.log(u'Пришла ошибка от VKAPI во время отправки сообщения. ' \ + unicode(response['error']['error_msg'])) if response['error']['error_code'] == 14: vk_utils.set_bot_status(info, 'error', response['error']['captcha_sid']) return response
def dump_anon(self, sender_id, original, domain, mid): message = api.query('execute.get_anon_info', {'domain': domain, 'mid': mid['response']}) if message is not None: r = message.get('response') else: return None user_id = r['user']['user_id'] user_name = r['user']['first_name'] + u' ' + r['user']['last_name'] anon_text = r['message']['body'] datte = r['message']['date'] entry = { 'user_id': user_id, 'anon_id': sender_id, 'text': original, 'date': datte, 'user_name': user_name, 'hashed': hash(anon_text) } anon_messages = db.anon_messages hist = anon_messages.history return hist.insert(entry)
#!/usr/bin/python # -*- coding: utf-8 -*- from utils import api import constants from time import sleep pars = {"out": 1, "count": 1000} friends_to_del = api.query(u"friends.getRequests", pars) friends_to_del = friends_to_del["response"]["items"] for friend in friends_to_del: pars = {"user_id": friend} res = api.query(u"friends.delete", pars) print res sleep(0.3)
#!/usr/bin/python # -*- coding: utf-8 -*- from utils import api api.query(u'execute.add_friends')
def get_users(uids): if not isinstance(uids, list): if isinstance(uids, int) or isinstance(uids, str) or isinstance(uids, unicode): uids = [uids] else: logger.error(u'В функцию получения информации передали не строку и не число. ') return False users = cdb.users unknown_uids = [] answer = [] for uid in uids: user = users.find_one({'id': int(uid)}) if int(uid) < 0: answer.append({'id': int(uid), 'money': 0, 'first_name': u'', \ 'last_name': u'', 'domain': u'', 'sex': 2}) continue if user is None: unknown_uids.append(str(uid)) answer.append(int(uid)) else: answer.append(user) if len(unknown_uids) == 0: return answer pars = { 'user_ids': u','.join(unknown_uids), 'lang': u'ru', 'fields': u'domain, sex', } r = api.query(u'users.get', pars) time.sleep(0.4) if r is None or r.get('error'): err = u'Ошибка во время получения информации о пользователях. ' if r is not None and r.get('error'): err += unicode(r['error']) logger.error(err) if r is not None and r.get('error').get('error_code') == 6: time.sleep(2); r = api.query(u'users.get', pars) else: return False info = r['response'] merged_answer = [] if len(info) > 0: users = cdb.users for user in answer: if isinstance(user, int): ok = False for el in info: if int(el['id']) == user: el['money'] = 0 users.save(el) merged_answer.append(el) ok = True break if not ok: merged_answer.append({'id': user, 'money': 0, 'first_name': u'', \ 'last_name': u'', 'domain': u'', 'sex': 2}) else: merged_answer.append(user) return merged_answer else: return answer
from utils import api from datetime import datetime from datetime import timedelta import time import logger active_dialogs = list(db.dialogs.find(fields=['last_message', 'dialog_id'])) now = datetime.now() params = { 'count': 1, 'preview_length': 1, 'unread': 1, 'offset': 0, } amo = api.query(u'messages.getDialogs', params)['response']['count'] print amo params['count'] = 200 dialogs = [] for i in xrange(0, amo + 2, 200): time.sleep(0.5) params['offset'] = i try: r = api.query(u'messages.getDialogs', params)['response']['items'] for el in r: if el['message'].get('chat_id'): dialogs.append(el['message']['chat_id']) except Exception as e: logger.log(u'Ошибка во время получения диалогов. ' + unicode(e)) print e continue