Esempio n. 1
0
def on_post():
    """Выполнить пост на стене ВКонтакте."""
    access_token = edt_access_token.get().strip()
    vk = Vk(access_token)
    try:
        # Данные из текстовых полей
        owner_id = int(edt_owner_id.get())
        message = edt_message.get(1.0, Tk.END).strip()
        location = {"lat": float(edt_lat.get()), "long": float(edt_long.get())}
        image_filename = edt_image_filename.get().strip()
        link = edt_link.get().strip()

        # Пост
        post_id = vk.wall_post(owner_id, message, location, image_filename,
                               link)

        messagebox.showinfo(
            TITLE, "Пост №{} успешно отправлен на публикацию!".format(post_id))
    except requests.exceptions.ConnectionError as err:
        messagebox.showerror(
            TITLE,
            "Не удается выполнить запрос к ресурсу...\n\n{}".format(err))
    except Exception as err:
        messagebox.showerror(
            TITLE,
            "Во время работы приложения произошла ошибка:\n\n{}".format(err))
def download_users(age_from, age_to, city_id, downloaded_users_file):
    months = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,
              7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
    downloaded_users_list = get_lists_from_file(downloaded_users_file)
    users_info_list = get_lists_from_file(users_info_file)
    for age in range(age_from, age_to+1):
        for month in months.keys():
            for day in range(1, months[month]+1):
                print('''processed: day = {}, month = {}, age = {}'''.format(day, month, age))
                while True:
                    users = Vk.get_uids(age, month, day, city_id)
                    if users:
                        break
                    Vk.get_token()
                need_to_write_users = list()
                for user in users:
                    if not check_in_file(user.uid, downloaded_users_list):
                        dir_of_photos = os.path.join(vk_dir, age.__str__())
                        get_profile_photos(user.uid, dir_of_photos, downloaded_users_file)
                    if check_in_file(user.uid, users_info_list):
                        print('We have this user in info too! ' + user.name + ' ' + user.last_name)
                    else:
                        print('added info ' + user.name + ' ' + user.last_name)
                        need_to_write_users.append(user)
                write_users_to_file(need_to_write_users, users_info_file)
Esempio n. 3
0
    def __init__(self, token, vk_client_id):
        self.poller = Poller()
        self.updater = Updater(token=token)
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.reg_actions()
        self.restore()
Esempio n. 4
0
def main_loop():
    last_fm = LastFm(keys.last_fm_username, keys.last_fm_password, keys.last_fm_api_key, keys.last_fm_shared_secret)
    vk = Vk(keys.vk_access_token)
    default_status = None
    old_track_status = ""
    while True:
        track = last_fm.get_last_fm_now_playing(keys.last_fm_username)
        if track:
            print('Now playing track:{}'.format(track.name))
            new_track_status = 'Слушает {} - {} через Яндекс Музыку'.format(track.artist, track.name)
            if default_status is None:
                default_status = vk.get_status()
                print('Default status is none, setting default: {}'.format(default_status))
                vk.set_status(new_track_status)
                print('Setting new status on vk: {}'.format(new_track_status))
                old_track_status = new_track_status
                print('Setting old status: {}'.format(old_track_status))
            else:
                print('Default status: {}'.format(default_status))
                if old_track_status != new_track_status:
                    print('Old track status differs from new, setting to: {}'.format(new_track_status))
                    old_track_status = new_track_status
                    vk.set_status(new_track_status)
                else:
                    print('Old track status and new are the same: {}'.format(new_track_status))
        else:
            print('No now playing track')
            if default_status:
                print('Default status exist, setting it to vk: {}'.format(default_status))
                vk.set_status(default_status)
                default_status = None
            else:
                print('Default status is None')
        time.sleep(10)
Esempio n. 5
0
def main():
    vk = Vk(
        '7dd1fb5a7dd1fb5a7dd1fb5a397d8e54f877dd17dd1fb5a27c7084cec8da279527764d1'
    )
    base_urls = get_wall_ids(vk, group_id)
    base_infos = get_article_info(vk, base_urls)
    csv_writer(base_infos, 'result.cvs')
Esempio n. 6
0
 def __init__(self):
     self.vk = Vk(Config.token)
     self.db = DB(run_seeders=True)
     controller_essay = ControllerEssay()
     self.handlers = [
         *ControllerBaseRules().handlers, *ControllerStatistics().handlers,
         *ControllerActionWithUser().handlers, *ControllerJokes().handlers,
         *ControllerSettings().handlers, *ControllerCallAdmin().handlers,
         *ControllerRandomPost().handlers, *controller_essay.handlers,
         *ControllerLowPriority().handlers
     ]
     self.special_handlers = [
         handler for handler in self.handlers if handler.get('special')
     ]
     p = Process(target=controller_essay.proceed_essays, args=(self.vk, ))
     p.start()
Esempio n. 7
0
    def __init__(self, token, vk_client_id):
        self.poller = Poller()
        self.updater = Updater(token=token)
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.reg_actions()
        self.restore()
Esempio n. 8
0
    def from_api(token, params):
        chat = Vk.api('messages.getChat', token, params)
        if chat == None:
            return Vk_chat()

        vk_chat = Vk_chat(**chat)
        vk_chat.persist()
        return vk_chat
Esempio n. 9
0
def main():

    login = input('Enter vk.com username: '******'Enter vk.com password: '******'3742196')

    res = vk.login(login, password)

    if not res:
        print('Incorrect login or password')
        exit()

    if not vk.oauth():
        print("Can't get access token")
        exit()

    cnf = configparser.ConfigParser()

    cnf['main'] = {
        'token': vk.token,
        'uids': vk.my_uid,
    }

    savePath = '{}/Music'.format(os.getenv('HOME'))

    d = input('Directory for saving audios [{}]: '.format(savePath))
    if d:
        savePath = d

    cnf['main']['path'] = savePath

    if not os.path.exists(savePath):
        os.makedirs(savePath)

    res = input('Do you want to add another uids except {}? [y/n]: '.format(
        vk.my_uid))

    if res.lower() == 'y':
        ids = input('Enter uids seperate by comma: ')
        cnf['main']['uids'] += ',' + ids.strip()

    with open('config.ini', 'w') as f:
        cnf.write(f)

    return 0
Esempio n. 10
0
    def from_api(token, params):
        users = Vk.api('users.get', token, params)
        if users == None:
            return Vk_user()

        if len(users) == 0:
            return Vk_user()

        user = Vk_user(**users[0])
        user.persist()
        return user
Esempio n. 11
0
    def add(self, client):
        if client.next_server == None:
            # TODO: fetch next poll server
            next_server = Vk.get_long_poll_server(token=client.vk_token,
                    chat_id=client.chat_id)
            if next_server == None:
                return

            client.next_server = next_server

        self.clients.put(client)
Esempio n. 12
0
    def from_api(token, params):
        users = Vk.api('users.get', token, params)
        if users == None:
            return Vk_user()

        if len(users) == 0:
            return Vk_user()

        user = Vk_user(**users[0])
        user.persist()
        return user
Esempio n. 13
0
def get_profile_photos(id_, start_dir, downloaded_users_file):
    dir_of_photos = os.path.join(start_dir, id_)
    if not os.path.exists(dir_of_photos):
        os.makedirs(dir_of_photos)
    images = Vk.get_profile_photos(id_)
    Internet.load_images(images, dir_of_photos, need_reload_file)
    with open(downloaded_users_file, 'a+') as downloaded_users:
        downloaded_users.seek(0)
        lines = downloaded_users.readlines()
        if not check_in_file(id_, lines):
            downloaded_users.write(id_ + '\n')
Esempio n. 14
0
def downloaded_friends(user_ids, dir_, deep=2):
    downloaded_users_file_friends = os.path.join(dir_, 'downloaded_users.txt')
    users_info_file_friends = os.path.join(dir_, 'user_info.txt')
    downloaded_users_list = get_lists_from_file(downloaded_users_file_friends)
    users_info_list = get_lists_from_file(users_info_file_friends)
    count = 0
    next_iter_uids = set()
    for uid in user_ids:
        count += 1
        if not check_in_file(uid, downloaded_users_list):
            get_profile_photos(uid, dir_, downloaded_users_file_friends)
        user = get_user_info_from_list(uid, users_info_list)
        if user is not None:
            print('We have this user in info too! ' + user.name + ' ' + user.last_name + ' (id ' +
                  user.uid.__str__() + '), ' + count.__str__() + '\\' + len(user_ids).__str__())
            user_friends_file = os.path.join(dir_, uid)
            user_friends_file = os.path.join(user_friends_file, 'friends.txt')
            users = get_users_from_file(user_friends_file)
        else:
            user = Vk.get_user_info(uid)
            if user is not None:
                print('added info ' + user.name + ' ' + user.last_name + ' (id ' + user.uid.__str__() + '), '
                      + count.__str__() + '\\' + len(user_ids).__str__())
                write_users_to_file([user], users_info_file_friends)
                for i in range(3):
                    users = Vk.get_friends(uid)
                    if users:
                        break
                    Vk.get_token()
                path_to_write = os.path.join(dir_, uid)
                path_to_write = os.path.join(path_to_write, 'friends.txt')
                write_users_in_file(path_to_write, users, open_mode='w')
        if deep > 0:
            next_iter_uids = next_iter_uids | set([user.uid for user in users])

    if next_iter_uids:
        downloaded_friends(next_iter_uids, dir_, deep-1)
Esempio n. 15
0
    def _run(self):
        print('In _run')
        while self.is_running:
            if not self.clients.empty():
                client = self.clients.get()
                updates = Vk.poll(client)
                if updates == None:
                    print("Updates are none")
                    continue

                client.persist()
                self.add(client)
                self.exec_cb(updates=updates, client=client)

        print('Exit _run')
def get_profile_photos(id_, start_dir, downloaded_users_file, need_reload_file):
    dir_of_photos = os.path.join(start_dir, id_.__str__())

    images = Vk.get_profile_photos(id_.__str__())
    if 9 < len(images) < 1000:
        if not os.path.exists(dir_of_photos):
            os.makedirs(dir_of_photos)
        Internet.Internet.load_images(images.keys(), dir_of_photos, need_reload_file)
        with open(os.path.join(dir_of_photos, id_.__str__() + '.txt'), 'w+', encoding='utf-8') as info:
            for image, likes in images.items():
                f = image.split('/')[-1]
                info.write(f + ',' + likes.__str__() + '\n')
    with open(downloaded_users_file, 'a+') as downloaded_users:
        downloaded_users.seek(0)
        lines = downloaded_users.readlines()
        if not Download_profiles.check_in_file(id_.__str__(), lines):
            downloaded_users.write(id_.__str__() + '\n')
    print('LOADED id = ' + id_.__str__())
Esempio n. 17
0
class Bot:
    def __init__(self, token, vk_client_id):
        self.poller = Poller()
        self.updater = Updater(token=token)
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.reg_actions()
        self.restore()

    def run(self):
        self.poller.async_run(self.on_update)
        self.updater.start_polling()
        self.updater.idle()
        self.poller.stop()
        self.persist()
        db.close()

    def persist(self):
        for _, client in self.clients.items():
            client.persist()

    def restore(self):
        for _, client in self.clients.items():
            self.add_poll_server(client)

    def reg_actions(self):
        dispatcher = self.updater.dispatcher
        dispatcher.addTelegramCommandHandler('start', self.start)
        dispatcher.addTelegramCommandHandler('whoami', self.whoami)
        dispatcher.addTelegramCommandHandler('pick', self.pick)
        dispatcher.addTelegramCommandHandler('unpick', self.unpick)
        dispatcher.addTelegramCommandHandler('details', self.details)
        dispatcher.addErrorHandler(self.error)
        dispatcher.addUnknownTelegramCommandHandler(self.unknown)
        dispatcher.addTelegramMessageHandler(self.on_message)

    def start(self, bot, update):
        chat_id = update.message.chat_id
        auth_url = self.vk.get_auth_url()
        # Send first info messages
        bot.sendMessage(chat_id=chat_id,
                text=message.WELCOME(auth_url),
                reply_markup=ReplyKeyboardHide())
        bot.sendMessage(chat_id=chat_id, text=message.COPY_TOKEN)
        # Create new client
        client = Client(next_action=action.ACCESS_TOKEN,
                        chat_id=chat_id)
        self.clients[chat_id] = client
        client.persist()

    def whoami(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            return

        client = self.clients[chat_id]
        bot.sendMessage(chat_id=chat_id,
            text=message.WHOAMI(client.vk_user.get_name()),
            reply_markup=Bot.keyboard(client.keyboard_markup()))

    def pick(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.seen_now()
        recepient = update.message.text[6:]
        client.expect_message_to(recepient)
        bot.sendMessage(chat_id=chat_id,
                text=message.TYPE_MESSAGE(recepient),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=Bot.keyboard(client.keyboard_markup()))

    def unpick(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.next_action = action.NOTHING
        client.persist()
        bot.sendMessage(chat_id=chat_id,
                text=message.UNPICK(client.next_recepient.get_name()),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=Bot.keyboard(client.keyboard_markup()))
        client.next_recepient = None

    def details(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.seen_now()
        user = client.next_recepient
        if user == None:
            bot.sendMessage(chat_id=chat_id,
                    text=message.FIRST_PICK_USER,
                    reply_markup=Bot.keyboard(client.keyboard_markup()))
            return

        if user.photo != None:
            bot.sendPhoto(chat_id=chat_id, photo=user.photo)

        bot.sendMessage(chat_id=chat_id,
                text=message.USER_NAME(user.get_name()),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=Bot.keyboard(client.keyboard_markup()))

        participants = user.participants()
        if participants != None:
            bot.sendMessage(chat_id=chat_id,
                    text=message.PARTICIPANTS(participants),
                    parse_mode=ParseMode.MARKDOWN,
                    reply_markup=Bot.keyboard(client.keyboard_markup()))



    def error(self, bot, update, error):
        logger.warn('Update "%s" caused error "%s"' % (update, error))

    def on_message(self, bot, update):
        chat_id = update.message.chat_id

        if not chat_id in self.clients:
            return self.start(bot, update)

        client = self.clients[chat_id]
        client.seen_now()

        if client.next_action == action.ACCESS_TOKEN:
            return self.on_token_message(bot, update, client)
        elif client.next_action == action.MESSAGE:
            return self.on_typed_message(bot, update, client)

        self.echo(update.message.chat_id)

    def on_token_message(self, bot, update, client):
        parseresult = urlparse(update.message.text)
        if parseresult.scheme=='https':
            parseparams = parse_qs(parseresult.fragment)
            access_token = parseparams.get('access_token')[0]
            client.load_vk_user(access_token)
        else:
            client.load_vk_user(update.message.text)
        name = client.vk_user.get_name()
        client.next_action = action.NOTHING
        self.add_poll_server(client)
        bot.sendMessage(chat_id=update.message.chat_id,
                text=message.TOKEN_SAVED(name),
                reply_markup=Bot.keyboard(client.keyboard_markup()))

    def on_typed_message(self, bot, update, client):
        client.send_message(update.message.text)

    @run_async
    def add_poll_server(self, client):
        if client.vk_token != None:
            self.poller.add(client)

    def echo(self, chat_id):
        self.updater.bot.sendMessage(chat_id=chat_id, text=message.ECHO)

    def unknown(self, bot, update):
        bot.sendMessage(chat_id=update.message.chat_id,
                text=message.UNKNOWN)

    @staticmethod
    def keyboard(keyboard_markup):
        return ReplyKeyboardMarkup(
            keyboard_markup,
            selective=True,
            resize_keyboard=True)

    def on_update(self, updates, client):
        for update in updates:
            self.process_update(update, client)

    def process_update(self, update, client):
        if len(update) == 0:
            return

        if update[0] == 4:
            # When new message received
            self.receive_vk_message(update, client)

    def receive_vk_message(self, update, client):
        flags = update[2]
        from_id = update[3]
        text = update[6]
        attachments = update[7]

        if flags & 2 == 2:
            # Skip when message is outgoing
            return

        from_name = ''

        if from_id & 2000000000 == 2000000000:
            # Message came from chat
            chat_id = from_id - 2000000000
            chat = Vk_chat.fetch(client.vk_token, chat_id)
            from_name = chat.name_from(attachments['from'])
            client.add_interaction_with(chat)
        else:
            user = Vk_user.fetch_user(client.vk_token, from_id)
            from_name = user.get_name()
            client.add_interaction_with(user)

        self.updater.bot.sendMessage(chat_id=client.chat_id,
                text=message.NEW_MESSAGE(from_name, text),
                reply_markup=Bot.keyboard(client.keyboard_markup()),
                parse_mode=ParseMode.MARKDOWN)
        client.persist()
Esempio n. 18
0
class Bot:
    def __init__(self, token, vk_client_id):
        self.poller = Poller()
        self.updater = Updater(token=token)
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.reg_actions()
        self.restore()

    def run(self):
        self.poller.async_run(self.on_update)
        self.updater.start_polling()
        self.updater.idle()
        self.poller.stop()
        self.persist()
        db.close()

    def persist(self):
        for _, client in self.clients.items():
            client.persist()

    def restore(self):
        for _, client in self.clients.items():
            self.add_poll_server(client)

    def reg_actions(self):
        dispatcher = self.updater.dispatcher
        dispatcher.addTelegramCommandHandler('start', self.start)
        dispatcher.addTelegramCommandHandler('whoami', self.whoami)
        dispatcher.addTelegramCommandHandler('pick', self.pick)
        dispatcher.addTelegramCommandHandler('unpick', self.unpick)
        dispatcher.addTelegramCommandHandler('details', self.details)
        dispatcher.addErrorHandler(self.error)
        dispatcher.addUnknownTelegramCommandHandler(self.unknown)
        dispatcher.addTelegramMessageHandler(self.on_message)

    def start(self, bot, update):
        chat_id = update.message.chat_id
        auth_url = self.vk.get_auth_url()
        # Send first info messages
        bot.sendMessage(chat_id=chat_id,
                        text=message.WELCOME(auth_url),
                        reply_markup=ReplyKeyboardHide())
        bot.sendMessage(chat_id=chat_id, text=message.COPY_TOKEN)
        # Create new client
        client = Client(next_action=action.ACCESS_TOKEN, chat_id=chat_id)
        self.clients[chat_id] = client
        client.persist()

    def whoami(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            return

        client = self.clients[chat_id]
        bot.sendMessage(chat_id=chat_id,
                        text=message.WHOAMI(client.vk_user.get_name()),
                        reply_markup=Bot.keyboard(client.keyboard_markup()))

    def pick(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.seen_now()
        recepient = update.message.text[6:]
        client.expect_message_to(recepient)
        bot.sendMessage(chat_id=chat_id,
                        text=message.TYPE_MESSAGE(recepient),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_markup=Bot.keyboard(client.keyboard_markup()))

    def unpick(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.next_action = action.NOTHING
        client.persist()
        bot.sendMessage(chat_id=chat_id,
                        text=message.UNPICK(client.next_recepient.get_name()),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_markup=Bot.keyboard(client.keyboard_markup()))
        client.next_recepient = None

    def details(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.seen_now()
        user = client.next_recepient
        if user == None:
            bot.sendMessage(chat_id=chat_id,
                            text=message.FIRST_PICK_USER,
                            reply_markup=Bot.keyboard(
                                client.keyboard_markup()))
            return

        if user.photo != None:
            bot.sendPhoto(chat_id=chat_id, photo=user.photo)

        bot.sendMessage(chat_id=chat_id,
                        text=message.USER_NAME(user.get_name()),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_markup=Bot.keyboard(client.keyboard_markup()))

        participants = user.participants()
        if participants != None:
            bot.sendMessage(chat_id=chat_id,
                            text=message.PARTICIPANTS(participants),
                            parse_mode=ParseMode.MARKDOWN,
                            reply_markup=Bot.keyboard(
                                client.keyboard_markup()))

    def error(self, bot, update, error):
        logger.warn('Update "%s" caused error "%s"' % (update, error))

    def on_message(self, bot, update):
        chat_id = update.message.chat_id

        if not chat_id in self.clients:
            return self.start(bot, update)

        client = self.clients[chat_id]
        client.seen_now()

        if client.next_action == action.ACCESS_TOKEN:
            return self.on_token_message(bot, update, client)
        elif client.next_action == action.MESSAGE:
            return self.on_typed_message(bot, update, client)

        self.echo(update.message.chat_id)

    def on_token_message(self, bot, update, client):
        parseresult = urlparse(update.message.text)
        if parseresult.scheme == 'https':
            parseparams = parse_qs(parseresult.fragment)
            access_token = parseparams.get('access_token')[0]
            client.load_vk_user(access_token)
        else:
            client.load_vk_user(update.message.text)
        name = client.vk_user.get_name()
        client.next_action = action.NOTHING
        self.add_poll_server(client)
        bot.sendMessage(chat_id=update.message.chat_id,
                        text=message.TOKEN_SAVED(name),
                        reply_markup=Bot.keyboard(client.keyboard_markup()))

    def on_typed_message(self, bot, update, client):
        client.send_message(update.message.text)

    @run_async
    def add_poll_server(self, client):
        if client.vk_token != None:
            self.poller.add(client)

    def echo(self, chat_id):
        self.updater.bot.sendMessage(chat_id=chat_id, text=message.ECHO)

    def unknown(self, bot, update):
        bot.sendMessage(chat_id=update.message.chat_id, text=message.UNKNOWN)

    @staticmethod
    def keyboard(keyboard_markup):
        return ReplyKeyboardMarkup(keyboard_markup,
                                   selective=True,
                                   resize_keyboard=True)

    def on_update(self, updates, client):
        for update in updates:
            self.process_update(update, client)

    def process_update(self, update, client):
        if len(update) == 0:
            return

        if update[0] == 4:
            # When new message received
            self.receive_vk_message(update, client)

    def receive_vk_message(self, update, client):
        flags = update[2]
        from_id = update[3]
        text = update[6]
        attachments = update[7]

        if flags & 2 == 2:
            # Skip when message is outgoing
            return

        from_name = ''

        if from_id & 2000000000 == 2000000000:
            # Message came from chat
            chat_id = from_id - 2000000000
            chat = Vk_chat.fetch(client.vk_token, chat_id)
            from_name = chat.name_from(attachments['from'])
            client.add_interaction_with(chat)
        else:
            user = Vk_user.fetch_user(client.vk_token, from_id)
            from_name = user.get_name()
            client.add_interaction_with(user)

        self.updater.bot.sendMessage(chat_id=client.chat_id,
                                     text=message.NEW_MESSAGE(from_name, text),
                                     reply_markup=Bot.keyboard(
                                         client.keyboard_markup()),
                                     parse_mode=ParseMode.MARKDOWN)
        client.persist()
Esempio n. 19
0
import os
from flask import Flask, request
from tools import EventProcessor
from message_new_handler import MessageNewHandler
from vk import Vk
#import logging

access_token = os.environ.get('access_token', '')
group_id = int(os.environ.get('group_id', 0))
server_confirmation_key = os.environ.get('server_confirmation_key', None)
secret = os.environ.get('secret', '')

server = Flask(__name__)
event_processor = EventProcessor(group_id, True, secret)
vk = Vk(access_token)
message_new_handler = MessageNewHandler(vk)

@event_processor.confirmation()
def confirm_handler_fn(event):
    if server_confirmation_key == None:
        raise Exception("server confirmation key is not set")
    return server_confirmation_key
    
@event_processor.message_new()
def message_new_handler_fn(event):
    message_new_handler.handle(event)
    return "ok"

@event_processor.error()
def error_handler_fn(error):
    #print(error)
Esempio n. 20
0
        Укажите ID пользователя VK и количество фотографий для сохранения на Яндекс.Диск 
    """
    print(help_inf)


# информация о программе
show_help()

# входные данные
token_vk = input('Введите токен для VK: ')
token_yd = input('Введите токен для Яндекс.Диск: ')
vk_id = input_int(
    'Введите ID пользователя VK (если не указан, определяется по токену): ')
count_save = input_int(
    'Введите количество файлов для сохранения на Яндекс.Диск (если не указано,то 5 файлов): ',
    5)

# with open('token.txt') as file:
#      token_vk = file.readline().strip()
#      token_yd = file.readline().strip()
# vk_id = 1#650124345 #552934290

my_vk = Vk(token_vk, '5.130')
my_ya_disk = YandexDisk(token_yd)

# читаем фотографии пользователя из VK
my_photos = my_vk.read_photos(vk_id)

# сохраняем фотографии на Яндекс.Диск
result = my_ya_disk.save_photos(my_photos, count_save)
Esempio n. 21
0
 def send_message(self, token, message):
     params = {'chat_id': self.id, 'message':message}
     message_id = Vk.api('messages.send', token, params)
Esempio n. 22
0
def main():
    vk = Vk(VK_TOKEN, '5.130')
    vk_bot = VkBot(VK_BOT_TOKEN)

    start_key = vk_bot.get_keyboard(start_button)
    continue_key = vk_bot.get_keyboard(continue_button)
    change_criteria_key = vk_bot.get_keyboard(change_criteria_button)

    database_users = crud.load_users()
    users = []
    city_dict = {}
    criteria = {}

    long_poll = VkLongPoll(vk_bot.session)
    for event in long_poll.listen():
        if event.type == VkEventType.MESSAGE_NEW:
            if event.to_me:
                request = event.text.lower()

                if request == "привет":
                    flag = 0
                    for user_id in database_users:
                        if user_id == event.user_id:
                            criteria = crud.load_criteria(event.user_id)
                            flag = 1
                            break
                    if flag == 0:
                        info = vk.get_user_info(event.user_id)
                        user = User(event.user_id, vk.get_criteria(info))
                        users.append(user)
                        crud.insert_user(user)
                        user.count_to_load, target_users = vk.search_users(
                            user.criteria, user.viewed_list, user.black_list)
                        vk_bot.send_message(
                            event.user_id, f"привет {user.first_name}, "
                            f"нашел для тебя {user.count_to_load} пользователей\n "
                        )
                        vk_bot.send_message(event.user_id,
                                            user.display_criteria())
                        vk_bot.send_message(event.user_id, "сделай выбор:",
                                            start_key)
                    elif flag == 1:
                        user = User(event.user_id, criteria)
                        user.viewed_list = crud.load_viewed_list(event.user_id)
                        user.loaded_list = user.viewed_list.copy()
                        user.black_list = crud.load_black_list(event.user_id)
                        user.favorite_list = crud.load_favorite_list(
                            event.user_id)
                        user.count_to_load, target_users = vk.search_users(
                            user.criteria, [], user.black_list)
                        user.count_loaded = len(
                            user.viewed_list) if user.viewed_list else 0
                        users.append(user)

                        if user.count_not_viewed(
                        ) > 0 and user.count_loaded > 0:
                            vk_bot.send_message(
                                event.user_id,
                                f"привет {user.first_name}, продолжим?\n"
                                f"осталось {user.count_not_viewed()} пользователей\n"
                                f"\n{user.display_criteria()}\n", continue_key)
                        else:
                            clear_current_search_data(user)
                            vk_bot.send_message(
                                event.user_id,
                                f"привет {user.first_name}, искать снова?\n"
                                f"нашел {user.count_to_load} пользователей\n"
                                f"\n{user.display_criteria()}\n", start_key)
                else:
                    for user in users:
                        if request in ('начать поиск', 'продолжить поиск'):
                            if user.id == event.user_id:
                                count, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                if request == 'начать поиск':
                                    user.count_to_load = count
                                    vk_bot.send_message(
                                        event.user_id,
                                        f"нашел {user.count_to_load} пользователей"
                                    )
                                else:
                                    vk_bot.send_message(
                                        event.user_id,
                                        f"осталось {count} пользователей")
                                vk_bot.send_message(event.user_id,
                                                    "загружаю...")

                                for i, target_user in enumerate(target_users):
                                    photos = vk.get_photos(target_user)
                                    top_3_photos = vk.get_top_photos(photos, 3)
                                    attachments = vk_bot.get_attachments(
                                        top_3_photos)
                                    vk_bot.send_message(
                                        event.user_id,
                                        f"https://vk.com/id{str(target_user)}",
                                        None, attachments)
                                    user.viewed_list.append(target_user)
                                    if i == user.max_number - 1:
                                        break
                                crud.insert_users_search(user)
                                user.count_loaded = len(user.loaded_list)

                                if user.count_not_viewed() > 0:
                                    vk_bot.send_message(
                                        event.user_id,
                                        f"осталось {user.count_not_viewed()} пользователей"
                                        f"\nсделай выбор:", continue_key)
                                else:
                                    clear_current_search_data(user, 1)
                                    vk_bot.send_message(
                                        event.user_id, "сделай выбор:",
                                        start_key)

                        elif request == 'изменить параметры':
                            if user.id == event.user_id:
                                vk_bot.send_message(
                                    event.user_id,
                                    f"{user.display_criteria()}\n"
                                    "сделай выбор:", change_criteria_key)

                        elif request == 'пол':
                            if user.id == event.user_id:
                                user.change_sex()
                                crud.update_sex(user)
                                clear_current_search_data(user, 1)
                                vk_bot.send_message(
                                    event.user_id, f"пол изменен\n"
                                    f"{user.display_criteria()}", start_key)
                                count, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"нашел {count} пользователей")

                        elif request == 'возраст':
                            if user.id == event.user_id:
                                vk_bot.send_message(
                                    event.user_id,
                                    "введите возраст в формате '30-35'")

                        elif re.match(re.compile(age_pattern), request):
                            if user.id == event.user_id:
                                age_from, age_to = re.match(
                                    re.compile(age_pattern), request).groups()
                                user.change_age(age_from, age_to)
                                crud.update_age(user)
                                clear_current_search_data(user, 1)
                                count, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"возраст изменен\n{user.display_criteria()}",
                                    start_key)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"нашел {count} пользователей")

                        elif request == 'город':
                            if user.id == event.user_id:
                                vk_bot.send_message(
                                    event.user_id,
                                    "введите город в формате 'г Москва'")

                        elif re.match(re.compile(city_pattern), request):
                            if user.id == event.user_id:
                                city_query = re.match(re.compile(city_pattern),
                                                      request).groups()[0]
                                city_dict, city_key = vk.get_cities(
                                    city_query, user.criteria['country_id'])
                                if len(city_key) > 0:
                                    city_key = vk_bot.get_keyboard(
                                        {'buttons': city_key})
                                    vk_bot.send_message(
                                        event.user_id, "подтвердите выбор:",
                                        city_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id, "город не найден",
                                        change_criteria_key)

                        elif re.match(re.compile(id_city_pattern), request):
                            if user.id == event.user_id:
                                city_id = re.match(re.compile(id_city_pattern),
                                                   request).groups()[0]
                                user.change_city(city_id, city_dict[city_id])
                                crud.update_city(user)
                                clear_current_search_data(user, 1)
                                user.count_to_load, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"город изменен\n{user.display_criteria()}",
                                    start_key)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"нашел {user.count_to_load} пользователей"
                                )

                        elif request == 'статус':
                            if user.id == event.user_id:
                                vk_bot.send_message(event.user_id,
                                                    user.STATUS_LABEL)

                        elif re.match(re.compile(status_pattern), request):
                            if user.id == event.user_id:
                                status = int(
                                    re.match(re.compile(status_pattern),
                                             request).groups()[0])
                                user.change_status(status)
                                crud.update_status(user)
                                clear_current_search_data(user, 1)
                                count, target_users = vk.search_users(
                                    user.criteria, user.viewed_list,
                                    user.black_list)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"статус изменен\n{user.display_criteria()}",
                                    start_key)
                                vk_bot.send_message(
                                    event.user_id,
                                    f"нашел {count} пользователей")

                        elif request == '+':
                            if user.id == event.user_id:
                                reply_message = vk_bot.get_reply_message(
                                    event.peer_id, event.user_id)
                                if re.match(re.compile(id_reply_pattern),
                                            reply_message):
                                    favorite_user_id = int(
                                        re.match(re.compile(id_reply_pattern),
                                                 reply_message).groups()[0])
                                    if favorite_user_id not in user.favorite_list:
                                        crud.insert_favorite(
                                            user, favorite_user_id)
                                        user.favorite_list.append(
                                            favorite_user_id)
                                        vk_bot.send_message(
                                            event.user_id,
                                            f"пользователь добавлен в избранное",
                                            continue_key)
                                    else:
                                        vk_bot.send_message(
                                            event.user_id,
                                            'пользователь уже в списке',
                                            continue_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id,
                                        "чтобы добавить в избранное, отправь '+' "
                                        "\nв ответе на сообщение со ссылкой "
                                        "на пользователя")

                        elif request == '-':
                            if user.id == event.user_id:
                                reply_message = vk_bot.get_reply_message(
                                    event.peer_id, event.user_id)
                                if re.match(re.compile(id_reply_pattern),
                                            reply_message):
                                    black_list_user_id = int(
                                        re.match(re.compile(id_reply_pattern),
                                                 reply_message).groups()[0])
                                    if black_list_user_id not in user.black_list:
                                        crud.insert_black_user(
                                            user, black_list_user_id)
                                        user.black_list.append(
                                            black_list_user_id)
                                        user.clear_black_list_info(
                                            black_list_user_id)
                                        user.count_to_load, target_users = vk.search_users(
                                            user.criteria, [], user.black_list)
                                        vk_bot.send_message(
                                            event.user_id,
                                            f"пользователь добавлен в черный список",
                                            continue_key)
                                    else:
                                        vk_bot.send_message(
                                            event.user_id,
                                            'пользователь уже в списке',
                                            continue_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id,
                                        "чтобы добавить в черный список, отправь '-' "
                                        "\nв ответе на сообщение со ссылкой "
                                        "на пользователя")

                        elif request == 'черный список':
                            if user.id == event.user_id:
                                if user.black_list:
                                    for black_user in user.black_list:
                                        vk_bot.send_message(
                                            event.user_id,
                                            f"https://vk.com/id{str(black_user)}"
                                        )
                                    vk_bot.send_message(
                                        event.user_id, 'сделай выбор',
                                        continue_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id, 'список пуст',
                                        continue_key)

                        elif request == 'избранное':
                            if user.id == event.user_id:
                                if user.favorite_list:
                                    for favorite_user in user.favorite_list:
                                        vk_bot.send_message(
                                            event.user_id,
                                            f"https://vk.com/id{str(favorite_user)}"
                                        )
                                    vk_bot.send_message(
                                        event.user_id, 'сделай выбор',
                                        continue_key)
                                else:
                                    vk_bot.send_message(
                                        event.user_id, 'список пуст',
                                        continue_key)

                        else:
                            if user.id == event.user_id:
                                vk_bot.send_message(
                                    event.user_id, "не понял вашего ответа...")
Esempio n. 23
0
import datetime
import requests
import json
import os
import random
from vk import Vk
from tools import EventProcessor
from message_new_handler import MessageNewHandler

#config

access_token = os.environ.get('access_token', '')
group_id = int(os.environ.get('group_id', 0))

vk = Vk(access_token)
event_processor = EventProcessor(group_id)
message_new_handler = MessageNewHandler(vk)


@event_processor.message_new()
def message_new_handler_fn(event):
    message_new_handler.handle(event)
    return "ok", 200


#main
result = vk.vk_method_get('groups.getLongPollServer', {
    'group_id': group_id
}).json()
if Vk.IsError(result):
    print(result)
Esempio n. 24
0
	def run(self):

		

		if 'main' in self.cnf and 'token' in self.cnf['main']:
			self.vk = Vk(self.client_id, self.cnf['main']['token'])
		else:
			self.log('не задан токен в конфиге, запустите config.py')
			return

		try:
			uids = [x.strip() for x in self.cnf['main']['uids'].split(',')]
		except:
			uids = ['']

		try:
			path = self.cnf['main']['path']
		except:
			path = '{}/music'.format(os.getenv('HOME'))

		if not os.path.exists(path):
			os.makedirs(path)

		if not self.vk.oauth():
			self.log('не смогли авторизоваться с указанным токеном, запустите config.py')
			return

		delay = 30
		if 'main' in self.cnf and 'delay' in self.cnf['main']:
			try:
				delay = int(self.cnf['main']['delay'])
			except:
				pass

		while True:

			for uid in uids:
				audios = self.vk.get_audios(uid)

				if not audios:
					continue

				for a in audios['response']:

					fname = '{}/{}_{}.mp3'.format(path, a['owner_id'], a['aid'])
					if os.path.exists(fname):
						continue

					self.log('загружаем аудио {} - {}'.format(a['artist'], a['title']))
					try:
						r = self.vk.request.get(a['url'])
						with open(fname, 'wb') as f:
							f.write(r.content)

						tag = stagger.tags.Tag23()
						tag.artist = a['artist']
						tag.title = a['title']
						tag.write(fname)


					except Exception as e:
						self.log('не смогли загузить {}: {}'.format(a['url'], e))
					
			time.sleep(delay)
Esempio n. 25
0
class VkDaemon(daemon):

	client_id = ''#сюда client_id созданного приложения

	def __init__(self, pid):

		try:
			self.log_f = open('/var/log/vk_audio.log', 'a')
		except Exception as e:
			print("Can't open log file: {}".format(e))
		return super().__init__(pid)

	def __del__(self):
		try:
			self.log_f.close()
		except:
			pass

	def log(self, text):
		try:
			self.log_f.write('{} {}\n'.format(time.strftime('%d.%m.%Y %H:%M:%S'), text))
			f.flush()
		except:
			pass

	def start(self):
		self.cnf = configparser.ConfigParser()
		try:
			self.cnf.read('config.ini')
		except:
			self.log('не смогли открыть файл конфига')
			return

		return super().start()

	def run(self):

		

		if 'main' in self.cnf and 'token' in self.cnf['main']:
			self.vk = Vk(self.client_id, self.cnf['main']['token'])
		else:
			self.log('не задан токен в конфиге, запустите config.py')
			return

		try:
			uids = [x.strip() for x in self.cnf['main']['uids'].split(',')]
		except:
			uids = ['']

		try:
			path = self.cnf['main']['path']
		except:
			path = '{}/music'.format(os.getenv('HOME'))

		if not os.path.exists(path):
			os.makedirs(path)

		if not self.vk.oauth():
			self.log('не смогли авторизоваться с указанным токеном, запустите config.py')
			return

		delay = 30
		if 'main' in self.cnf and 'delay' in self.cnf['main']:
			try:
				delay = int(self.cnf['main']['delay'])
			except:
				pass

		while True:

			for uid in uids:
				audios = self.vk.get_audios(uid)

				if not audios:
					continue

				for a in audios['response']:

					fname = '{}/{}_{}.mp3'.format(path, a['owner_id'], a['aid'])
					if os.path.exists(fname):
						continue

					self.log('загружаем аудио {} - {}'.format(a['artist'], a['title']))
					try:
						r = self.vk.request.get(a['url'])
						with open(fname, 'wb') as f:
							f.write(r.content)

						tag = stagger.tags.Tag23()
						tag.artist = a['artist']
						tag.title = a['title']
						tag.write(fname)


					except Exception as e:
						self.log('не смогли загузить {}: {}'.format(a['url'], e))
					
			time.sleep(delay)
Esempio n. 26
0
 def send_message(self, token, message):
     params = {'user_id': self.uid, 'message': message}
     message_id = Vk.api('messages.send', token, params)
Esempio n. 27
0
class App:
    vk = None
    db = None
    handlers = []
    special_handlers = []

    def __init__(self):
        self.vk = Vk(Config.token)
        self.db = DB(run_seeders=True)
        controller_essay = ControllerEssay()
        self.handlers = [
            *ControllerBaseRules().handlers, *ControllerStatistics().handlers,
            *ControllerActionWithUser().handlers, *ControllerJokes().handlers,
            *ControllerSettings().handlers, *ControllerCallAdmin().handlers,
            *ControllerRandomPost().handlers, *controller_essay.handlers,
            *ControllerLowPriority().handlers
        ]
        self.special_handlers = [
            handler for handler in self.handlers if handler.get('special')
        ]
        p = Process(target=controller_essay.proceed_essays, args=(self.vk, ))
        p.start()

    def process_new_message(self, event):
        try:
            user = self.db.session.query(User).filter(
                User.user_id == event.user_id).first()
            if not user:
                user = self.db.add(User(event.user_id))
            else:
                self.db.update(user,
                               {User.last_interaction_date: datetime.today()})

            if event.user_id in Config.admin_ids or \
                    Settings.bot and not user.banned:
                handlers = self.handlers
                if user.path == Buttons.get_key(Buttons.call_admin):
                    handlers = self.special_handlers

                coincidence = next(
                    (rule for rule in handlers
                     if rule['condition'](self.vk, event, user) and (
                         'main' in rule or 'admin' in rule
                         and event.user_id in Config.admin_ids)))
                if coincidence:
                    if 'admin' in coincidence and event.user_id in Config.admin_ids:
                        coincidence['admin'](self.vk, event, user)
                    elif 'main' in coincidence:
                        coincidence['main'](self.vk, event, user)
        except StopIteration:
            return None
        except Exception as e:
            self.write_error_message(event.user_id)
            self.write_log(self.vk, event.message_id, e)
            self.db.session.rollback()

    def process_unread_messages(self):
        count = 200
        while count == 200:
            conversations, count = self.vk.get_unread_conversations()
            for conversation in conversations:
                user = self.db.session.query(User).filter(
                    User.user_id == conversation['conversation']['peer']
                    ['id']).first()
                if user.path != Buttons.get_key(
                        Buttons.call_admin) and not user.banned:
                    self.vk.send(user.user_id, [
                        'что-то я залип на некоторое время, можешь повторить что ты там говорил?',
                        'извини, что не отвечал, делал свои дела. ну ты знаешь, дела обычного бота бедрока: '
                        'банил всяких гандонов и генерировал мемы. так на чем мы остановились?'
                    ])

    @staticmethod
    def write_log(vk, message_id, e):
        print(e)
        msg = ''
        if type(e) is ApiError:
            request_params = [
                param for param in e.error["request_params"]
                if param['key'] not in ['message', 'keyboard', 'user_id']
            ]
            # if next(iter([param for param in e.error["request_params"] if param['key'] == 'keyboard']), None):
            #     request_params.append({
            #         'keyboard': json.loads(next(iter(
            #             [param for param in e.error["request_params"] if param['key'] == 'keyboard']
            #         ), None)['value'])
            #     })
            msg = f'{e.error["error_code"]}: {e.error["error_msg"]}\n' \
                  f'{json.dumps(request_params, indent=2, ensure_ascii=False)}'
        else:
            msg = '\n'.join(str(arg) for arg in e.args)

        # vk.send(Config.developer, f'{msg}\nstacktrace:\n{traceback.format_exc()}', forward_messages=message_id)
        vk.send(Config.developer, f'{msg}\n', forward_messages=message_id)

    def write_error_message(self, user_id):
        elevator_photos = [
            f'photo-{Config.group_id}_{id}' for id in Config.elevator_photos
        ]
        elevator_audios = [f'audio{id}' for id in Config.elevator_audios]
        self.vk.send(
            user_id,
            'что-то пошло не так. попытайтся снова через некоторое время. '
            'если ошибка повторяется несколько раз, то напиши админу',
            attachments=[
                f'{elevator_photos[random.randint(0, len(elevator_photos) - 1)]},'
                f'{elevator_audios[random.randint(0, len(elevator_audios) - 1)]}'
            ])