Beispiel #1
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 #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 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 #4
0
 def __init__(self, token, group_id, db):
     log.info("Starting bot initialization")
     log.info(f"Initializing VK API with {token[:4]}**** token")
     self.vk_session = VkApi(token=token)  # Initializing session
     self.vk_api = self.vk_session.get_api()  # Initializing API
     log.info("Ended VK API initialization")
     self.group_id = group_id
     self.group_name = f"club{self.group_id}"
     log.info(f"Initializing LongPoll for {self.group_name}")
     try:
         self.long_poll = VkBotLongPoll(
             self.vk_session, self.group_id)  # Initializing LongPoll API
     except ApiError as e:
         e_str = str(e)
         if "[5]" in e_str:
             print("Token not valid!")
         elif "[100]" in e_str:
             print("Group ID not valid!")
         else:
             print(f"Something went wrong...\n{e_str}")
         exit()
     log.info(f"Ended LongPoll initialization")
     self.db = db
     self.score = 0
     self.auto_shitpost = 1
     self.auto_shitpost_limiter = 10
     self.msg_recipient = ""
     log.info("Ended bot initialization! Bot is up and running...")
 def __init__(self, config_path=CONFIG_PATH, cache_dir=CACHE_DIR.name):
     self.cache_dir = cache_dir
     self.config_path = config_path
     # Чтение конфигурации бота из файла config.ini
     self.config = configparser.ConfigParser()
     self.config.read(self.config_path)
     # Инициализация Telegram бота
     bot_token = self.config.get('global', 'bot_token')
     # Указан ли прокси в конфиге
     if self.config.get('global', 'proxy_url'):
         log.warning('Бот будет работать через прокси. Возможны перебои в работе бота.')
         request = Request(proxy_url=self.config.get('global', 'proxy_url'), connect_timeout=15.0, read_timeout=15.0)
     else:
         request = None
     self.bot = Bot(bot_token, request=request)
     # Чтение из конфига логина и пароля ВК
     vk_login = self.config.get('global', 'login')
     vk_pass = self.config.get('global', 'pass')
     # Чтение из конфига пути к файлу со стоп-словами
     self.stop_list = self.config.get('global', 'stop_list', fallback=[])
     if self.stop_list:
         # Инициализация списка стоп-слов
         with open(self.stop_list, 'r', encoding='utf-8') as f:
             self.stop_list = [i.strip() for i in f.readlines()]
     # Инициализация ВК сессии
     self.session = VkApi(login=vk_login, password=vk_pass, auth_handler=auth_handler, captcha_handler=captcha_handler)
     self.session.auth()
     self.api_vk = self.session.get_api()
Beispiel #6
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 #7
0
 def get_photo_from_vk(self):
     vk_obj = VkApi()
     if self.count is None:
         upload_list = vk_obj.get_max_size_photos(self.user_id)
     else:
         upload_list = vk_obj.get_max_size_photos(self.user_id, self.count)
     return upload_list
Beispiel #8
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 #9
0
Datei: ecc.py Projekt: re1ard/ecc
	def __init__(self,l,p,agkey = ''):
		self.api = VkApi(l,p)
		self.api.auth()
		#######################
		self.methods = methods(self.api,agkey)
		#######################
		self.lp = VkLongPoll(self.api)
		#######################
		self.config = self.loadcfg()
		#######################
		self.ecc_arg = u'ecc'
		#######################
		self.chat_admins = {}
		self.chat_users = {}
		#######################
		self.action_cfg = {
			#'chat_title_update':{
			#		'permition': 't',
			#		'try':0
			#			},
			'chat_invite_user':{
					'permition': 'i',
					'try':1
						}
			}
		#######################
		self.chat_cfg = {
			'admin_id':0,
			'moders':{},
			'title':'',
			'enable':True
				}
Beispiel #10
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 #11
0
 def __init__(self, group_id, token):
     self.group_id = group_id
     self.token = token
     self.vk = VkApi(token=token)
     self.api = self.vk.get_api()
     self.long_poller = VkBotLongPoll(self.vk, group_id=self.group_id)
     self.time_stamp = time.time()
Beispiel #12
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 #13
0
def set_widget():
    service = VkApi(token=bot.get_settings("service_token"), api_version=bot.vk.api_version)
    widget = {
        "title": "Список лучших игроков клана",
        "title_url": "https://vk.com/kronos_bs",
        "more": "Перейти к полному списку",
        "more_url": "https://vk.com/topic-187742365_41459579",
        "head": [{
            "text": "Игрок",
            "align": "left"
        }, {
            "text": "Трофеи",
            "align": "right"
        }],
        "body": []
    }
    members = brawl.get_club_members("#R020J99L", limit=11).response["items"]
    for k in range(0, len(members)):
        widget["body"].append([{
            "text": "{}. {}".format(k+1, members[k]["name"])
        }, {
            "text": bot.get_messages("widget_member", t=members[k]["trophies"])
        }])
    widget["title_counter"] = len(members)
    
    try:
        service.method("appWidgets.update", {
            "type": "table",
            "code": "return " + dumps(widget,  ensure_ascii=False, separators=(",", ":")) + ";"
        })
    except:
        bot.log_exception()
Beispiel #14
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 #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 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 #17
0
def _send_startup_event(group_id, group_secret):
    account = random.choice(tech_accounts)
    sess = VkApi(token=account['access_token'])
    payload = {'group_id': abs(group_id)}
    resp = sess.method('messages.allowMessagesFromGroup', payload)

    data_json = {
        "type": "message_new",
        "object": {
            "date": int(time.time()),
            "from_id": account['id'],
            "id": 777,
            "out": 0,
            "peer_id": account['id'],
            "text": "/startup",
            "conversation_message_id": 777,
            "fwd_messages": [],
            "important": False,
            "random_id": 0,
            "attachments": [],
            "is_hidden": False
        },
        "group_id": abs(group_id),
        "secret": group_secret
    }
    data = json.dumps(data_json)
    req = requests.post(DJANGO_URL, data=data)
    return 1
Beispiel #18
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 #19
0
    def __init__(self, group_id, token, db_engine):
        self.group_id = group_id
        self.token = token

        self.vk = VkApi(token=token)
        self.long_poller = VkLongPoll(self.vk)
        self.api = self.vk.get_api()
        self.engine = db_engine
Beispiel #20
0
    def __init__(self):
        self.loadEnv()

        self.token = environ['token']
        self.api_v = environ['api_v']

        self.vk = VkApi(token=self.token)
        self.longPoll = longpoll.VkLongPoll(self.vk)
Beispiel #21
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 #22
0
def main():
    vk_session = VkApi(settings.LOGIN, settings.PASSWORD, scope='wall')
    vk_session.auth(token_only=True)
    tools = VkTools(vk_session)
    input_url = input('Введите ссылку на пост: ')

    all_comments = get_all_comments(input_url, tools)
    print('\n'.join(all_comments))
Beispiel #23
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 #24
0
 def connect(self) -> None:
     self.vk_session = VkApi(token=self.__vk_key)
     self.vk = self.vk_session.get_api()
     self.upload = VkUpload(self.vk_session)
     self.long_poll = VkLongPoll(self.vk_session)
     self.weather_forecaster = WeatherForecaster(self.__weather_key, self.vk, self.upload)
     self.schedule_parser = ScheduleParser(self.vk, self.upload)
     print("Бот успешно подключен к чату")
Beispiel #25
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 #26
0
    def __init__(self, token, q):  #  Main class...
        super().__init__()

        self.token = token
        self.q = q

        self.vk_session = VkApi(token=self.token)
        self.vk = self.vk_session.get_api()
Beispiel #27
0
 def __init__(self, token=None):
     self.vk = VkApi(token=token)
     self.log = getLogger('VK')
     try:
         self.who_am_i()
     except ApiError:
         self.log.fatal('Invalid VK token passed')
         exit(-1)
def connect(login, password):
    try:
        conn = VkApi(login=login, password=password)
        conn.auth()
        return conn
    except Exception as e:
        print(e)
        sys.exit(0)
Beispiel #29
0
 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))
Beispiel #30
0
 def photoUploadServer():
     """
     Возвращает данные сервера для зарузки фото
     :return:
     """
     vk_session = VkApi(token=TOKEN)
     vk = vk_session.get_api()
     response = vk.photos.getMessagesUploadServer(peer_id=0)
     return response
Beispiel #31
0
    def on_login(self):
        # verify login and password
        login = self.ui.login_edit.text()
        password = self.ui.pass_edit.text()

        if len(login) == 0 or len(password) == 0:
            return
        user = User(login, password)
        api = VkApi()
        api.login(user)
Beispiel #32
0
def connect(login, password, owner_id=None):
    """Initialize connection with `vk.com <https://vk.com>`_ and try to authorize user with given credentials.

    :param login: user login e. g. email, phone number
    :type login: str
    :param password: user password
    :type password: str

    :return: :mod:`vk_api.vk_api.VkApi` connection
    :rtype: :mod:`VkApi`
    """
    connection = VkApi(login, password)
    connection.authorization()
    connection.owner_id = owner_id or get_user_id(connection)
    return connection
Beispiel #33
0
    def __init__(self):
        super().__init__()

        self.ui = Ui_MainWidget()
        self.ui.setupUi(self)

        api = VkApi()
        if api.isLogedIn():
            self.track_list = VkAudio.parse(api.audio_get(api.current_user_id, api.audio_get_count(api.current_user_id)))

            for track in self.track_list:
                btn = QPushButton()
                btn.setText(track.artist + track.title)
                btn.clicked.connect(partial(self.on_track_click, track.url))
                self.ui.track_list.add_widget_item(btn)

        self.show()
Beispiel #34
0
def vk():
    login = os.environ['LOGIN']
    password = os.environ['PASSWORD']
    vk = VkApi(login, password)
    vk.auth(token_only=True)
    return vk