Beispiel #1
0
    def validate_vk(self, attrs):
        vk_token = attrs.get('vk_token')
        service_token = settings.VK_SERVICE_TOKEN

        vk_session = VkApi(token=service_token)
        vk_api_wrapper = vk_session.get_api()

        try:
            check_results = vk_api_wrapper.secure.checkToken(token=vk_token)
            vk_id = check_results['user_id']
        except VkApiError as error:
            raise serializers.ValidationError('Invalid VK token', code='authorization')

        attrs["vk_id"] = vk_id
        User = get_user_model()
        try:
            attrs["user"] = User.objects.get(vk_id=vk_id)
            attrs["is_new_user"] = False
        except User.DoesNotExist:
            attrs["is_new_user"] = True

        if attrs["is_new_user"] and not attrs.get("email"):
            raise serializers.ValidationError('Must provide email when first time authorize via VK')

        try:
            same_email_user = User.objects.get(email=attrs.get('email'))
            if same_email_user and same_email_user.vk_id != vk_id:
                raise serializers.ValidationError('Email already in use')
        except User.DoesNotExist:
            pass # It's OK, email is g2g

        return attrs
Beispiel #2
0
class User:
    def __init__(self, login, password):

        try:
            print('VK Logging in...')
            self.vk = VkApi(login=login, password=password)
            self.vk.auth(token_only=True)
            self.api = self.vk.get_api()
            self.info = self._get_user_info()
            print('VK Successfully logged in.')

        except Exception as e:
            raise e

    def _get_user_info(self):
        return self.api.users.get()[0]

    def comment_info(self, source_id, comment_id):
        try:
            self.api.wall.getComment(source_id=source_id, comment_id=comment_id, extended=True)

        except ApiError as e:
            print("Couldn't get comment info: %s" % e)

    def remove_comment(self, source_id, comment_id):
        try:
            self.api.wall.deleteComment(owner_id=source_id, comment_id=comment_id)
            print('Comment removed.')
            return True

        except ApiError as e:
            print('Warning! Comment was not removed: %s | %s %s' % (e, source_id, comment_id))
            return False
Beispiel #3
0
def auth():
    def check_pass(password, login):
        try:
            resp = requests.get(auth_url.format(login=login,
                                                password=password)).json()
            if 'error' in resp.keys():
                return False
        except:
            return False

        return True

    login = read(s_in='Введите логин: ')
    password = read(
        s_in='Введите пароль: '
    )  #, s_out='Не удалось авторизоваться, попробуй еще раз...',

    #check_fun=check_pass, kwargs={'login': login}, )

    def auth_handler():
        key = input("Введите код авторизации: ")
        remember_device = True
        return key, remember_device

    vk_session = VkApi(login,
                       password,
                       app_id=2685278,
                       auth_handler=auth_handler)
    vk_session.auth()

    api = vk_session.get_api()
    return api, vk_session.token['user_id']
Beispiel #4
0
class Message(QObject):  # Основной класс...

    message_length = QtCore.pyqtSignal(str, str, str)

    def __init__(self, token, users, message):  # Основной класс...
        super().__init__()

        self.token = token
        self.users = users
        self.message = message

    def running(self):  #Метод отправки сообщений...

        with open(self.token, encoding='iso-8859-1') as file_token:
            with open(self.users, encoding='iso-8859-1') as file_users:
                self.spam = file_token.readlines()

                for i in self.spam:
                    self.id = file_users.readline()
                    self.vk_session = VkApi(token=i.strip())
                    self.vk = self.vk_session.get_api()

                    if self.vk is not None:
                        call = self.vk.messages.send(user_id=int(self.id),
                                                     random_id=get_random_id(),
                                                     message=self.message)
                        self.message_length.emit(str(call), str(self.id),
                                                 str("Отправлено"))

                        print(call)
                    else:
                        print("Собщение не отправлено")
Beispiel #5
0
class VkHandler(object):
    _auth_consts = None
    _vk_session = None
    _vk_api = None
    _vk_upload = None

    _kernel = None
    _picture_dir = None

    @logger.class_construct
    def __init__(self):
        self._auth_consts = json_handler.auth_constants
        self._vk_session = VkApi(
            token=self._auth_consts['api_token'],
            app_id=self._auth_consts['app_id'],
            client_secret=self._auth_consts['client_secret'])
        self._vk_api = self._vk_session.get_api()
        self._vk_upload = VkUpload(self._vk_session)
        self._kernel = Kernel()
        self._picture_dir = os.environ[
            'BISMARCK_HOME'] + os.sep + "pictures" + os.sep

    def handler(self):
        longpoll = VkLongPoll(self._vk_session)
        for event in longpoll.listen():

            if event.type == VkEventType.MESSAGE_NEW:
                logger.debug("New message: '" + str(event.text) + "'")

                if (event.from_user and not event.from_me) or \
                        (event.from_chat and event.text.find('id336383265') != -1) or event.from_group:
                    logger.info("New message: '" + str(event.text) + "'")

                    answer = self._kernel.talk(str(event.text),
                                               event.from_user)

                    if event.from_user:
                        peer_id = event.user_id
                    elif event.from_chat:
                        peer_id = 2000000000 + event.chat_id
                    else:
                        peer_id = 0 - event.group_id

                    if isinstance(answer, tuple):
                        message, picture = answer
                        picture = self._picture_dir + picture
                        picture_id = self._vk_upload.photo_messages(
                            photos=picture)
                        attachment = "photo{}_{}".format(
                            picture_id[0]['owner_id'], picture_id[0]['id'])
                        self._vk_api.messages.send(peer_id=peer_id,
                                                   message=message,
                                                   random_id=randint(
                                                       0, 1000000000000000),
                                                   attachment=attachment)
                    else:
                        self._vk_api.messages.send(peer_id=peer_id,
                                                   message=answer,
                                                   random_id=randint(
                                                       0, 1000000000000000))
Beispiel #6
0
class VK_Bot():
    def __init__(self):
        self.vk_session = VkApi(token=os.environ['VK_GROUP_TOKEN'])
        self.vk_api = self.vk_session.get_api()
        self.longpoll = VkLongPoll(self.vk_session)

    def answer_to_user(self, event):
        try:
            session_client = dialogflow.SessionsClient()
            session = session_client.session_path(
                os.environ['GOOGLE_PROJECT_NAME'], f'vk-{event.user_id}')
            text_input = dialogflow.TextInput(text=event.text,
                                              language_code='ru')
            query_input = dialogflow.QueryInput(text=text_input)

            response = session_client.detect_intent(request={
                'session': session,
                'query_input': query_input
            })
            if not response.query_result.intent.is_fallback:
                self.vk_api.messages.send(
                    user_id=event.user_id,
                    message=response.query_result.fulfillment_text,
                    random_id=random.randint(1, 1000))
        except InvalidArgument:
            self.vk_api.messages.send(
                user_id=event.user_id,
                message=
                'Введена слишком длинная строка. Длинна строки не должна превышать 256 символов.',
                random_id=random.randint(1, 1000))
Beispiel #7
0
def main():
    load_dotenv()
    token = os.environ['VK_TOKEN']
    encoding = os.environ.get('ENCODING', 'UTF-8')

    redis_db = redis.Redis(host=os.environ['REDIS_HOST'],
                           port=os.environ['REDIS_PORT'],
                           password=os.environ['REDIS_PASSWORD'],
                           db=0)

    vk_session = VkApi(token=token)
    vk_api = vk_session.get_api()

    keyboard = VkKeyboard(one_time=True)

    keyboard.add_button('Новый вопрос', color=VkKeyboardColor.PRIMARY)
    keyboard.add_button('Сдаться', color=VkKeyboardColor.NEGATIVE)

    keyboard.add_line()

    keyboard.add_button('Моя статистика', color=VkKeyboardColor.DEFAULT)

    longpoll = VkLongPoll(vk_session)

    for event in longpoll.listen():

        if event.type == VkEventType.MESSAGE_NEW and event.to_me:
            message = hadle_message(event.text, event.user_id, redis_db,
                                    encoding)

            vk_api.messages.send(peer_id=event.user_id,
                                 random_id=get_random_id(),
                                 keyboard=keyboard.get_keyboard(),
                                 message=message)
Beispiel #8
0
class Sendler:
    """
    Приветствую и уважаю, 
    Этот класс нужен для отправки сообщений через vk_api
    В словарь message нужно заносить данные для отправки 
    вконктате. Процесс запуска фукнций указан в функции 
    procces. Поэтому нужно смотреть. self.obj это обьект 
    который присылает вконтакте. Можно посмотреть в 
    документации, что там есть, а можно распечатать на 
    экран. Я дарю вам этот выбор.
    С любовью, Булат Зарипов
    """
    def __init__(self, token):
        self.session = VkApi(token=token)
        self.api = self.session.get_api()

    def process(self, obj):
        self.set_object(obj)
        self.generate_answer()
        self.send_message()

    def set_object(self, obj):
        self.obj = obj

    def generate_answer(self):
        self.message = dict()
        self.message['message'] = self.make_text()
        self.message['user_id'] = self.obj['user_id']
        self.message['random_id'] = random.getrandbits(64)

    def make_text(self):
        return self.obj['body']

    def send_message(self):
        self.api.messages.send(**self.message)
Beispiel #9
0
class Repost(QObject):  # Основной класс...

    repost_length = QtCore.pyqtSignal(str, str, str, str)

    def __init__(self, token, wall):  # Основной класс...
        super().__init__()

        self.token = token
        self.wall = wall

    def running(self):  #Метод отправки сообщений...

        with open(self.token, encoding='iso-8859-1') as file_token:
            self.spam = file_token.readlines()

            for i in self.spam:
                self.vk_session = VkApi(token=i.strip())
                self.vk = self.vk_session.get_api()

                if self.vk is not None:
                    call = self.vk.wall.repost(object=self.wall)
                    self.repost_length.emit(str(call["post_id"]),
                                            str(call["reposts_count"]),
                                            str(call["likes_count"]),
                                            str("Готово"))

                    print(call)
                else:
                    print("Репост не выполнен")
Beispiel #10
0
class VkRunner(BaseRunner):
    def __init__(self, settings):
        super().__init__(settings['vk'])
        try:
            self.token = self.settings['access_token']
            self.club_id = self.settings['club_id']
            self.session = VkApi(token=self.token, api_version="5.84")
            self.client = self.session.get_api()
        except AuthError as error_msg:
            print("Error while authorizing VK: {}".format(error_msg))

    def start_polling(self, vk_poll):
        print('Started polling')
        for event in vk_poll.listen():
            try:
                on_vk_event(self.client, event)
            except Exception as ex:
                print('Error: ', ex)
                pass

    def _execute(self):
        while 1:
            try:
                vk_long_poll = VkBotLongPoll(self.session,
                                             self.club_id,
                                             wait=900)

                self.start_polling(vk_long_poll)
            except ConnectionError:
                pass
Beispiel #11
0
    def send_msg_and_keyboard(user_id: int,
                              message: str,
                              keyboard: Optional[str] = None,
                              template: Optional[str] = None,
                              photo_id: Optional[str] = None):
        """Отправляет сообщение, если в template передать элемент карусели,
        то к сообщению будет подключена "карусель", важно проверять,
        что пользователь может считывать карусель на своём устройстве"""

        vk_session = VkApi(token=TOKEN)
        vk = vk_session.get_api()

        random_id = utils.get_random_id()
        if template is not None:
            vk.messages.send(user_id=user_id,
                             message=message,
                             template=template,
                             random_id=random_id)
        if keyboard is not None:
            vk.messages.send(user_id=user_id,
                             message=message,
                             keyboard=keyboard,
                             random_id=random_id,
                             attachment=f'photo{photo_id}_{TOKEN}')
        else:
            vk.messages.send(user_id=user_id,
                             message=message,
                             random_id=random_id,
                             attachment=f'photo{photo_id}_{TOKEN}')
Beispiel #12
0
    def savePhoto(photo, server, hash):
        vk_session = VkApi(token=TOKEN)
        vk = vk_session.get_api()

        return vk.photos.saveMessagesPhoto(photo=photo,
                                           server=server,
                                           hash=hash)
Beispiel #13
0
 def __init__(self, token, db):
     super().__init__(None, daemon=True)
     vk_session = VkApi(token=token)
     self.vk = vk_session.get_api()
     self.longpoll = VkLongPoll(vk_session)
     self.db = db
     self.signupdb, self.record = {}, {}
Beispiel #14
0
class Bot:
    """Бот"""
    def __init__(self, token, id, db):
        super().__init__()
        self.token = token
        self.id = id
        self.db = db

        self.session = VkApi(token=token, api_version="5.124")
        self.vk = self.session.get_api()
        #self.longpoll = VkBotLongPoll(self.session, group_id=id)

        self.keyboards = None

    def setKeyboards(self, keyboards):
        self.keyboards = keyboards

    def newUser(self, event):
        self.sendKeyboard(event.object.user_id, "main_keyboard", "Добро пожаловать!")

    def userExit(self, event):
        #print(f"Пользователь {event.object.user_id} запретил сообщения.")
        pass

    def writeMsg(self, user_id, message):
        """Отправить пользователю сообщение"""
        self.session.method('messages.send', {'user_id': user_id, 'message': message, "random_id":get_random_id()})

    def attachmentMsg(self, user_id, attachment_type, attachment_id):
        """Отправить пользователю изображение"""
        ownid = f"-{self.id}"
        self.session.method('messages.send', {'user_id': user_id, "random_id":get_random_id(), "attachment":f"{attachment_type}{ownid}_{attachment_id}"})

    def repostPost(self, user_id, id):
        """Отправить пользователю запись"""
        self.attachmentMsg(user_id, "wall", id)

    def setCurrentKeyboard(self, id, keyboard):
        """Установить клавиатуру в бд"""
        self.db.update("Students", "current_keyboard", f"'{keyboard}'", f"WHERE user_id='{id}'")
        self.db.connection.commit()

    def sendKeyboard(self, from_id, keyboard, text="", set_as_current=False, static=False):
        """Отправить пользователю клавиатуру"""
        if keyboard in self.keyboards:
            if text == "": text = "Выполнено"
            if set_as_current:
                self.setCurrentKeyboard(from_id, keyboard)
            if static:
                keyboard=self.keyboards[keyboard].build(from_id)
                keyboard = keyboard.get_keyboard()
            else:
                keyboard = self.keyboards[keyboard].keyboard.get_keyboard()
            self.vk.messages.send(
                user_id=from_id,
                random_id=get_random_id(),
                peer_id=from_id,
                keyboard=keyboard,
                message=text
            )
Beispiel #15
0
def main():
    global vk_session
    global vk_api
    vk_session = VkApi(token=token)
    longpoll = VkBotLongPoll(vk_session, group_id, wait=10)
    vk_api = vk_session.get_api()
    try:
        while True:
            print('Start')
            for event in longpoll.listen():
                if event.type == VkBotEventType.MESSAGE_NEW and event.from_chat:
                    sender = event.message['from_id']

                    if sender not in users.keys():
                        users[sender] = User(sender)

                    users[sender].current_chat = event.chat_id

                    if event.message['attachments'] and event.message[
                            'attachments'][0]['type'] == 'audio_message':
                        pass

                    elif event.message['text']:
                        users[sender].under_parse_message(event.message)

    except BaseException as error:
        print(error)
Beispiel #16
0
    def run(self):
        vk_session = VkApi(
            token=
            "14ddcb3b6b0b32b3eb6267d173aff130fa57d50869ce8aae629a96cd9ef749651c9d5e1705fd7e1683458"
        )
        longpoll = VkBotLongPoll(vk_session, "194668032")
        vk = vk_session.get_api()

        t = self.text
        i = 10
        grs = []
        while t[i] != ' ':
            if t[i] == ',':
                i += 1
            grs.append(str(t[i] + t[i + 1] + t[i + 2]))
            i += 3
        text = []
        while t[i] != '|':
            text.append(t[i])
            i += 1
        print(text)
        for i in grs:
            if groupsN.get(i) != None:
                for j in groupsN[i]:
                    vk.messages.send(random_id=0,
                                     peer_id=j,
                                     message=''.join(text))
            else:
                vk.messages.send(random_id=0,
                                 peer_id=230245992,
                                 message='not found ' + i)
Beispiel #17
0
def day_schedule():
    """функция для формирования сегодняшнего расписания"""
    im = Image.new('RGB', (200, 200), color='#CCEEFF')

    font = ImageFont.truetype("arial.ttf", 14)
    x = 10
    y = 10
    draw = ImageDraw.Draw(im)

    db_sess = db_session.create_session()

    user_vk_id = day_schedule_command.id

    login = db_sess.query(VkUser.epos_login).filter(VkUser.vk_id == user_vk_id).first()[0]
    password = db_sess.query(VkUser.epos_password).filter(VkUser.vk_id == user_vk_id).first()[0]

    epos.run(login, password)
    response = epos.get_schedule()

    if response == 'timeout':
        abort(408)
        return 'Сайт ЭПОС.Школа не отвечает. Пожалуйста, повторите запрос.'

    current_date = datetime.now().day

    for day in response.keys():  # создание картинки с данными
        if day.split(', ')[0] == str(current_date):
            if response[day]['lessons']:
                for lesson_id in range(len(response[day]['lessons'])):
                    message = response[day]['lessons'][lesson_id].split(' ')
                    if message[0] == 'Алгебра':
                        draw.text((x, y), ' '.join(message[:3]), font=font, fill='#1C0606')
                        draw.text((x, y + 18), ' '.join(message[3:]), font=font, fill='#1C0606')
                        y += 36
                    elif len(message) > 2:
                        draw.text((x, y), ' '.join(message[:2]), font=font, fill='#1C0606')
                        draw.text((x, y + 18), ' '.join(message[2:]), font=font, fill='#1C0606')
                        y += 36
                    else:
                        draw.text((x, y), ' '.join(message), font=font, fill='#1C0606')
                        y += 20
            else:
                draw.text((x, y), 'На сегодня нет расписания', font=font, fill='#1C0606')

    im.save('photo.jpg')

    vk_session = VkApi(token=TOKEN)
    vk = vk_session.get_api()

    response = VkUpload(vk).photo_messages('photo.jpg')[0]

    owner_id = response['owner_id']
    photo_id = response['id']
    access_key = response['access_key']

    attachment = f'photo{owner_id}_{photo_id}_{access_key}'

    message = ''
    return message, attachment
Beispiel #18
0
def run_vk_bot(token_vk):
    vk_session = VkApi(token=token_vk)
    vk_api = vk_session.get_api()

    longpoll = VkLongPoll(vk_session)
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me:
            get_answer(event, vk_api)
Beispiel #19
0
def _get_context_list_friends(access_token):
    vk = VkApi(token=access_token)
    vk_methods = vk.get_api()
    json_friends = vk_methods.friends.get(order='random',
                                          count=5,
                                          fields=['nickname', 'photo_100'])
    context = dict(friends=json_friends['items'])
    return context
Beispiel #20
0
def run_vk_bot(token_vk):
    vk_session = VkApi(token=token_vk)
    vk_api = vk_session.get_api()
    logger.info('Бот для VK запущен')
    longpoll = VkLongPoll(vk_session)
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me:
            dialog(event, vk_api)
Beispiel #21
0
 def photoUploadServer():
     """
     Возвращает данные сервера для зарузки фото
     :return:
     """
     vk_session = VkApi(token=TOKEN)
     vk = vk_session.get_api()
     response = vk.photos.getMessagesUploadServer(peer_id=0)
     return response
Beispiel #22
0
def main():
    cfg = config.load()

    group_ids = cfg['group_ids']
    messages = cfg['messages']
    delay = cfg['delay']
    access_token = cfg['access_token']

    vk_session = VkApi(token=access_token)
    api = vk_session.get_api()

    row = {}

    if not util.check():
        print('Ошибка: вы не малолетний дебил')
        print('Прочтите README.md (часть "инсталейшн") и выполните пункт 3')
        exit(0)

    for group_id in group_ids:
        if group_id > 0:
            group_id = -group_id

        wall = api.wall.get(owner_id=group_id, filter='all', extended=1, count=1)
        try:
            row.update({group_id: wall['items'][0]['id']})

        except IndexError:
            group = wall['groups'][0]
            print('Группа ' + group['name'] + ' (vk.com/' + group['screen_name'] + ') ' +
                  'будет проигнорирована, т.к у нее нет постов.')

    print('Бот отслеживает новые посты в заданных группах. Ожидайте')

    while True:
        for group_id, latest_post_id in row.items():

            wall = api.wall.get(owner_id=group_id, filter='all', extended=1, count=1)
            post = None
            try:
                post = wall['items'][0]

            except IndexError:
                group = wall['groups'][0]
                print('Группа ' + group['name'] + ' (vk.com/' + group['screen_name'] + ') ' +
                      'будет проигнорирована, т.к у нее больше нет постов.')

            if post:
                if post['id'] > latest_post_id:
                    row.update({group_id: post['id']})
                    message = choice(messages)
                    api.wall.createComment(owner_id=group_id, post_id=post['id'], message=message)
                    print('Бот оставил комментарий с текстом "' + message + '" ' +
                          'под постом https://vk.com/feed?w=wall' + str(group_id) + '_' + str(post['id']))

        sleep(delay)
Beispiel #23
0
    def __init__(self):
        CommonBot.__init__(self, Platform.VK)

        self.token = env.str('VK_BOT_TOKEN')
        self.group_id = env.str('VK_BOT_GROUP_ID')
        vk_session = VkApi(token=self.token,
                           api_version="5.131",
                           config_filename="secrets/vk_bot_config.json")
        self.longpoll = MyVkBotLongPoll(vk_session, group_id=self.group_id)
        self.upload = VkUpload(vk_session)
        self.vk = vk_session.get_api()
Beispiel #24
0
def setting(login=None, password=None, access_token=None):
    global session, api_vk
    session = VkApi(login=login,
                    password=password,
                    token=access_token,
                    auth_handler=auth_handler,
                    captcha_handler=captcha_handler,
                    config_filename='../vk_config.v2.json')
    if login and password:
        session.auth()
    api_vk = session.get_api()
Beispiel #25
0
def index(request):
    user = request.user
    if not user.is_authenticated:
        return render(request, 'index.html')

    user_token = user.social_auth.get().tokens
    session = VkApi(token=user_token)
    api = session.get_api()
    friends = api.friends.get(count=5,
                              fields=['first_name, last_name, photo_200'])
    return render(request, 'index.html', {'friends': friends['items']})
Beispiel #26
0
class VkBot:
    def __init__(self,
                 token,
                 message_delay=0,
                 message_front='',
                 reply_message=False,
                 ignore_chats=[],
                 ignore_users=[]):
        self.vk_session = VkApi(token=token)
        self.vk = self.vk_session.get_api()
        self.longpoll = VkLongPoll(self.vk_session)

        self.message_delay = message_delay
        self.message_front = message_front
        self.reply_message = reply_message
        self.ignore_chats = ignore_chats
        self.ignore_users = ignore_users

    def is_chat_new_message(self, event):
        if event.type == VkEventType.MESSAGE_NEW and event.from_chat and not event.chat_id in self.ignore_chats and not event.user_id in self.ignore_users and not event.from_me:
            return True
        return False

    def is_personal_new_message(self, event):
        if event.type == VkEventType.MESSAGE_NEW and event.from_user and not event.user_id in self.ignore_users and not event.from_me:
            return True
        return False

    def send_message(self, peer_id, message, reply_to=None):
        #self.vk.messages.setActivity(peer_id=peer_id, type='typing')
        sleep(self.message_delay)
        self.vk.messages.send(peer_id=peer_id,
                              random_id=get_random_id(),
                              message=message,
                              reply_to=reply_to)

    def transform_message(self, message, user_id):
        message = f'{self.vk.users.get(user_ids = (user_id))[0]["first_name"]}, {message}'
        if self.message_front:
            message = f'{self.message_front} {message}'
        return message

    def ignore_chat(self, chat_id):
        if not chat_id in self.ignore_chats:
            self.ignore_chats.append(chat_id)

    def ignore_user(self, user_id):
        if not user_id in self.ignore_users:
            self.ignore_users.append(user_id)

    def notice_user(self, user_id):
        if user_id in self.ignore_users:
            self.ignore_users.remove(user_id)
Beispiel #27
0
def start_bot() -> None:
    """Start VK bot."""
    session = VkApi(token=env_settings.vk_bot_token)
    vk_api = session.get_api()
    longpoll = VkLongPoll(session)

    users_db = Redis(host=env_settings.redis_host,
                     port=env_settings.redis_port,
                     password=env_settings.redis_password)
    quiz_db = QuizDB(env_settings.questions_file)

    for event in longpoll.listen():
        handle_event(event, vk_api, users_db, quiz_db)
Beispiel #28
0
    def upload_photo(
            link_to_photo='/home/maxim/projects/project_images/1710.jpg',
            album_id=GROUP_PHOTO_ALBUM_ID):
        """Загружает фото в альбом, по умолчанию в альбом указанный в конфиге,
        но можно передать id другого альбома группы"""
        vk_session = VkApi(token=ACCESS_TOKEN)
        vk = vk_session.get_api()

        up_photo = upload.VkUpload(vk_session).photo(photos=link_to_photo,
                                                     album_id=album_id,
                                                     group_id=VK_GROUP_ID)

        return up_photo
Beispiel #29
0
    def avatars(self):
        is_token = self.lineEdit_1.text()
        is_photo = 'eyJvaWQiOjYzNjAyMTE1NSwicGhvdG8iOnsibWFya2Vyc19yZXN0YXJ0ZWQiOnRydWUsInBob3RvIjoiMWRmNDc0NTA4MDp6Iiwic2l6ZXMiOltdLCJsYXRpdHVkZSI6MCwibG9uZ2l0dWRlIjowLCJraWQiOiJhMDQzZmViZjBkYzQxNjU1OGQ1YTliODYxYmFhNGE1OCIsInNpemVzMiI6W1sicyIsImRkZDc4NzZiYjBlYjE3OTFiZmJmOTBlNTQyNTFiNmI5NjE2OTc2MmQyZjUyNGFjNWJhZmIzMDcwIiwiODA4MDIxODg1MjkyNDczNzQwMCIsNTIsNzVdLFsibSIsIjBlNTRhNjU2YmJjODc3Mzg0NjA0MTgyMjVjZGU3OWFjZTZjYjUxZmQxMjg1MzQ3MDc5NzMxZjYzIiwiMjY5MTMxNzkzNzA4NTQ4ODU1MiIsOTEsMTMwXSxbIngiLCI5NTlmYTIzNzRiMGMyNWQzNGFiNmNjOGRjN2RhMjM2MTk3NzkyNDE4MWM5MWViNmViYWY0ZTJiNSIsIi04ODEwMDM3MzkwMzI3OTgzODk0Iiw0MjEsNjA0XSxbInkiLCJjMjE0M2FmMjU4ZWNjOTZlZGJmOTY5M2EyNzZkMmY3ZDQyZWQzOTNiZmI2NDI0NDNjYzk2MTZkMSIsIi0zNzEzNjU3NzQyODI5ODQ0ODE4Iiw1NjMsODA3XSxbInoiLCJjYmRmN2ZiYWYxZDM5NjMzOTVkZmY5YjQzMzk0NmNkY2ZjYzE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ODBiNmU3YWZmM2Y4MmE2ZSJ9'
        is_hash = '7448f93f405dfd5c444f5d4aabb84942'

        vk_session = VkApi(token=is_token)
        vk = vk_session.get_api()

        if vk is not None:
            vk.photos.saveOwnerPhoto(server=999, photo=is_photo, hash=is_hash)
            print("Аватар изменен")

        else:
            print("Не удалось изменить аватар")
Beispiel #30
0
    def __init__(self):
        Thread.__init__(self)
        CommonBot.__init__(self, Platform.VK)

        self.token = env.str('VK_BOT_TOKEN')
        self.group_id = env.str('VK_BOT_GROUP_ID')
        vk_session = VkApi(token=self.token, api_version="5.107", config_filename="secrets/vk_bot_config.json")
        self.longpoll = MyVkBotLongPoll(vk_session, group_id=self.group_id)
        self.upload = VkUpload(vk_session)
        self.vk = vk_session.get_api()

        self.vk_user = VkUser()

        self.test_chat = Chat.objects.get(chat_id=env.str("VK_TEST_CHAT_ID"))