Exemplo n.º 1
0
 def func(self):
     try:
         if str(self.text) == '':
             users = VK().Messages().get_chat(fields='bdate')['users']
             _str = 'Дни рождения:\n'
             for user in users:
                 _str += user['first_name'] + ' ' + user['last_name'] + ': '
                 if 'bdate' in user:
                     _str += user['bdate']
                 else:
                     _str += 'скрыто'
                 _str += '\n'
                 self.result['message'] = _str
         else:
             try:
                 u = VK().Users().get(user_ids=self.text,
                                      name_case='gen',
                                      fields='bdate')[0]
                 _str = 'День рождения ' + u['first_name'] + ' ' + u[
                     'last_name'] + ': '
                 if 'bdate' in u:
                     _str += u['bdate']
                 else:
                     _str += 'скрыт'
                 self.result['message'] = _str
             except Exception as e:
                 self.result['message'] = 'Введите корректный id: ' + str(e)
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
 def func(self):
     try:
         if self.user == var.czarID:
             try:
                 r = self.text.split(' | ')
                 if len(r) == 2:
                     s = str(VK().exec(r[0], eval(r[1])))
                     s = s[2:len(s) - 2].replace("'", '').split(', ')
                     res = ''
                     for a in s:
                         res += a + '\n'
                     self.result['message'] = res
                 elif len(r) > 2:
                     s = VK().exec(r[0], eval(r[1]))
                     rr1 = ''
                     for i in range(len(r)):
                         if 1 < i < len(r):
                             if UEngine.is_int(r[i]):
                                 s = s[int(r[i])]
                             else:
                                 s = s[r[i]]
                             rr1 += r[i] + ': '
                             print(rr1 + ': ' + s)
                     self.result['message'] = rr1 + str(s).replace("'", '')
                 return True
             except Exception as e:
                 self.result['message'] = 'Error: ' + str(e)
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Exemplo n.º 3
0
def image(image_name=None):
    server = VK().Photos().get_messages_upload_server()['upload_url']
    response = requests.post(server, files={'photo': open(image_name, 'rb')}).text
    r = json.loads(response)
    u = VK().Photos().save_messages_photo(server=r['server'], photo=r['photo'], _hash=r['hash'])[0]
    _str = 'photo' + str(u['owner_id']) + '_' + str(u['id']) + '_' + u['access_key']
    return _str
Exemplo n.º 4
0
def audio_message(audio_name=None):
    server = VK().Docs().get_upload_server(_type='audio_message')['upload_url']
    response = requests.post(server, files={'file': open(audio_name, 'rb')}).text
    r = json.loads(response)['file']
    u = VK().Docs().save(file=r)[0]
    _str = 'doc' + str(u['owner_id']) + '_' + str(u['id'])
    return _str
Exemplo n.º 5
0
 def cmd(t=None, p=None, u=None, m=None, d=None):
     md = f"{var.name} [v{var.version}]"
     var.answer = False
     var.start_now = False
     for a in var.plugins:
         res = dict()
         res['message'] = ''
         res['attachment'] = ''
         res = a.cmd(t, p, u, m, d)
         if not res is False:
             if len(str(res)) > 0:
                 p = str(a)[str(a).find('.')+1:str(a).find(' ')]
                 p = p[p.find('.')+1:]
                 Log.show_plugin(res['plugin'] + ' (' + p + ')')
                 var.answer = True
                 if not res['message'] is None or not res['attachment'] is None:
                     if res['message']:
                         res['message'] = f"{res['message']}\n{md}"
                         VK().Messages().send(message=res['message'], forward_messages=d)
                     elif res['attachment']:
                         VK().Messages().send(message=md, attachment=res['attachment'], forward_messages=d)
                 if not res['lat'] is None and not res['long'] is None:
                     var.answer = True
                     VK().Messages().send(message=md, lat=res['lat'], long=res['long'], forward_messages=d)
                 if not res['forward_messages'] is None:
                     VK().Messages().send(message=md, forward_messages=res['forward_messages'])
     if not var.answer and m != 'b' and not var.start_now:
         UEngine.what()
         Log.show_plugin('None')
Exemplo n.º 6
0
 def update_groups_list(self):
     response = VK.req('https://api.vk.com/method/groups.get',
                       params={
                           'user_id': self.get_id(),
                           'access_token': VK.get_token(),
                           'v': '5.89',
                       })
     return response.json()['response']
Exemplo n.º 7
0
                def get():
                    _all_votes = 0
                    _start_in = VK().Messages().get_history(count=0)['count']
                    time.sleep(vote_time)
                    _end = VK().Messages().get_history(count=0)['count']
                    cnt = (_end - _start_in) * 2
                    response = VK().Messages().get_history(count=cnt)['items']
                    response = response[::-1]
                    for item in response:
                        _a = item['body'].lower()
                        i = 0
                        _in = True
                        if not item[
                                'user_id'] in _users_voted and not '?' in _a:
                            while i < len(a) and _in:
                                if a[i][0].lower() == _a:
                                    a[i][1] += 1
                                    _all_votes += 1
                                    _in = False
                                i += 1
                            if not _in:
                                _users_voted.append(item['user_id'])
                                _messages_voted.append(item['id'])
                    _str = 'Результаты:\n'
                    i = 0

                    def f(n, c):
                        _f = 100 / n * c
                        if c == 0:
                            return '0.00'
                        else:
                            return str(int(_f * 100) / 100)

                    def sort_col(n):
                        return n[1]

                    if _all_votes > 0:
                        a.sort(key=sort_col, reverse=True)

                        while i < len(a):
                            _str += str(a[i][1]) + '. ' + a[i][0] + ' [%' + f(
                                _all_votes, a[i][1]) + ']\n'
                            i += 1
                        VK().Messages().send(
                            message=_str,
                            forward_messages=', '.join(
                                str(_exc_in) for _exc_in in _messages_voted))
                        if command:
                            if a[0][1] == a[1][1]:
                                self.result['message'] = 'Живи' + self.text
                            elif a[0][0] == 'Да':
                                VK().Messages().remove_chat_user(user_id=_id)
                            else:
                                self.result['message'] = 'Живи' + self.text
                        return True
                    else:
                        self.result['message'] = 'Голосование отменено.'
Exemplo n.º 8
0
 def __init__(self, font="Arial Bold"):
     self.vk = VK()
     self.me = None
     self.users = None
     self.window = Tk()
     self.wait = False
     self.window.title("Шаблон курсача")
     self.window.geometry('780x500')
     self.draw_first_page(font)
     self.window.mainloop()
Exemplo n.º 9
0
 def update_friends_list(self):
     response = VK.req('https://api.vk.com/method/friends.get',
                       params={
                           'user_id': self.get_id(),
                           'access_token': VK.get_token(),
                           'v': '5.89',
                       })
     friends_id = response.json()['response']['items']
     friends_list = User.get_users(friends_id)
     return friends_list
Exemplo n.º 10
0
def get_random_wall_gif(group_id, count=1):
    import random
    max_num = VK().Wall().get(owner_id=group_id)['count']
    doc_result = ''
    if max_num > count:
        for _ in range(count):
            num = random.randint(1, max_num)
            post = VK().Wall().get(owner_id=group_id, count=1, offset=num)['items'][0]['attachments'][0]['doc']
            _str = "doc" + str(post['owner_id']) + '_' + str(post['id']) + '_' + str(post['access_key'])
            doc_result += _str + ','
    return doc_result
Exemplo n.º 11
0
 def func(self):
     try:
         VK().Messages().edit_chat(title=var.title)
         VK().Messages().set_chat_photo(file=var.photo)
         VK().Messages().unpin()
         VK().Messages().pin(message_id=var.pin_id['message_id'])
         self.result['message'] = 'Беседа успешно восстановлена.'
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Exemplo n.º 12
0
def get_random_wall_picture(group_id, count=1):
    import random
    while True:
        max_num = VK().Photos().get(owner_id=group_id, album_id='wall', count=0)['count']
        if max_num > count:
            photos_result = ''
            for _ in range(count):
                num = random.randint(1, max_num)
                photos = VK().Photos().get(owner_id=group_id, album_id='wall', count=1, offset=num)['items']
                photos_result += 'photo' + str(group_id) + '_' + str(photos[0]['id']) + ','
            return photos_result
Exemplo n.º 13
0
def get_random_wall_post(group_id, count=1):
    import random
    max_num = VK().Wall().get(owner_id=group_id)['count']
    if max_num > count:
        post_result = ''
        for i in range(count):
            num = random.randint(1, max_num)
            post = str(i+1) + '. '
            post += VK().Wall().get(owner_id=group_id, count=1, offset=num)['items'][0]['text']
            if '#' in post:
                post = post[0:post.find('#') - 1]
            post += '\n\n'
            post_result += post
        return post_result
Exemplo n.º 14
0
 def get_users_info(user_list):
     """
     :param user_list: list of VK user ids
     :return: set of VK user properties
     """
     ids_string = ','.join((str(i) for i in user_list))
     response_users_info = VK.req('https://api.vk.com/method/users.get',
                                  params={
                                      'user_ids': ids_string,
                                      'access_token': VK.get_token(),
                                      'v': '5.89',
                                      'fields':
                                      'is_closed,can_access_closed',
                                  })
     return response_users_info.json()['response']
Exemplo n.º 15
0
 def func(self):
     try:
         if self.user == var.czarID:
             if var.listen:
                 VK().Messages().send(message='Завершение работы бота.')
                 var.listen = False
             else:
                 var.listen = True
                 VK().Messages().send(message='Возобновление работы бота.')
         else:
             self.result['message'] = 'Недостаточно прав.'
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Exemplo n.º 16
0
def get_username_by_id(user_id):
    try:
        user = VK().Users().get(user_ids=user_id)[0]
        return f"{user['first_name']} {user['last_name']}"
    except Exception as e:
        Log.show_error(e)
        return False
Exemplo n.º 17
0
    def calc(s, m):
        def fib(n):
            return n if n < 2 else (fib(n - 1) + fib(n - 2))

        from VK import VK
        h = ["help", "помощь", "функции", "func", "funcs", "functions"]
        var.calc_result = None
        s = s.replace('^', '**')
        s = s.replace('«', '<<')
        s = s.replace('÷', '/')
        s = s.replace('×', '*')
        if str(s) in h:
            _str = "Доступно: acos(x), asin(x), atan(x), atan2(x, y), ceil(x), cos(x), cosh(x), degrees(x), rand(x, y)"\
                   "e, exp(x),  fabs(x), floor(x), fmod(x), frexp(x), hypot(x), ldexp(x, y), log(x, base), log10(x), " \
                   "modf(x), pi, pow(x,y), radians(x), sin(x), sinh(x), sqrt(x), tan(x), tanh(x), fib(x), xor(x, y)"
            var.calc_result = _str
            return True
        try:
            safe_dict = {
                'acos': acos,
                'asin': asin,
                'atan': atan,
                'atan2': atan2,
                'ceil': ceil,
                'cos': cos,
                'cosh': cosh,
                'degrees': degrees,
                'e': e,
                'exp': exp,
                'fabs': fabs,
                'floor': floor,
                'fmod': fmod,
                'frexp': frexp,
                'hypot': hypot,
                'ldexp': ldexp,
                'log': log,
                'log10': log10,
                'modf': modf,
                'pi': pi,
                'pow': pow,
                'radians': radians,
                'sin': sin,
                'sinh': sinh,
                'sqrt': sqrt,
                'tan': tan,
                'tanh': tanh,
                'fib': fib,
                'xor': xor,
                'rand': rand
            }

            ss = eval(s, {"__builtins__": None}, safe_dict)
            VK().Messages().send(message=str(ss) + '\n' + var.name + ' [' +
                                 var.version + ']',
                                 forward_messages=m)
            return True
        except Exception as exception:
            var.calc_result = 'Некорректное выражение: ' + str(exception)
            return True
Exemplo n.º 18
0
def get_link_by_id(user_id):
    user_id = str(user_id)
    try:
        user = VK().Users().get(user_ids=user_id)[0]
        return f"@id{user['id']} ({user['first_name']} {user['last_name']})"
    except Exception as e:
        Log.show_error(e)
        return False
Exemplo n.º 19
0
def get_random_wall_music(group_id, count=1):
    import random
    music_result = ''
    music_count = 0
    while True:
        max_num = VK().Wall().get(owner_id=group_id)['count']
        num = random.randint(1, max_num)
        post = VK().Wall().get(owner_id=group_id, count=count, offset=num)['items']
        if 'attachments' in post[0]:
            for attachment in post[0]['attachments']:
                if 'audio' in attachment:
                    if attachment['type'] == 'audio':
                        _str = "audio" + str(attachment['audio']['owner_id']) + '_' + str(attachment['audio']['id'])
                        music_count += 1
                        music_result += _str + ','
                        if music_count >= count:
                            return music_result
Exemplo n.º 20
0
 def groups_has_but_friends_not(self):
     all_fr_groups = set()
     fr_list = self.get_friends()
     for i in range(len(fr_list)):
         if not (fr_list[i].is_closed() or fr_list[i].is_deleted()):
             all_fr_groups |= set(fr_list[i].get_groups())
     unique_groups_id = set(self.get_groups()) - all_fr_groups
     return VK.get_groups_info(list(unique_groups_id))
Exemplo n.º 21
0
 def func(self):
     try:
         followers = VK().Users().get_followers()['items']
         users = f'[{len(followers)}] Принятые заявки:\n'
         if len(followers):
             i = 0
             for user in followers:
                 VK().Friends().add(user_id=user)
                 users += str(i + 1) + '. ' + UEngine.get_username_by_id(
                     user) + '\n'
                 i += 1
             self.result['message'] = users
         else:
             self.result['message'] = 'Подписчиков не обнаруженно.'
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Exemplo n.º 22
0
 def func(self):
     try:
         f = open('DB\\coder.txt', 'r')
         coder = eval(f.read())
         f.close()
         now = datetime.datetime.now().day
         if coder['today'] == now:
             _str = f'Топ-{len(coder)-1} кодеров этой беседы:\n'
             u = VK().Users().get(
                 user_ids=', '.join([i for i in coder if i != 'today']))
             r = [{
                 (i['first_name'] + ' ' + i['last_name']):
                 coder[str(i['id'])]
             } for i in u if i != 'id']
             t = str(r)
             t = t.replace('{', '')
             t = t.replace('}', '')
             t = t.replace('[', '')
             t = t.replace(']', '')
             r = eval('{' + t + '}')
             t = sorted(r.items(), key=operator.itemgetter(1))[::-1]
             ind = 1
             for i in t:
                 _str += str(ind) + '. ' + str(i[0]) + ': ' + str(
                     i[1]) + ' раз.\n'
                 ind += 1
             f.close()
             self.result['message'] = _str
         else:
             f = open('DB\\coder.txt', 'w')
             coder['today'] = now
             user = random.choice(VK().Messages().get_chat()['users'])
             if str(user) in coder:
                 coder[str(user)] += 1
             else:
                 coder[str(user)] = 1
             _str = f'В этот раз кодер дня - {UEngine.get_username_by_id(int(user))} (В {coder[str(user)]} раз)'
             f.write(str(coder))
             f.close()
             self.result['message'] = _str
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Exemplo n.º 23
0
 def __init__(self, user1: User, user2: User, bar=None):
     self.user1 = user1
     self.user2 = user2
     self.vk = VK.get_instance()
     self.descriptions = Description(user1, user2)
     self.user1_all_music = None
     self.user2_all_music = None
     self.bar = bar
     self.progress = 0
     self.need_update = True
Exemplo n.º 24
0
def get_random_wall_video(group_id, count=1):
    import random
    while True:
        album = get_random_album(group_id)
        max_num = VK().Video().get(owner_id=group_id, album_id=album, count=0)['count']
        if max_num > count:
            attachment_count = 0
            attachment_result = ''
            while True:
                num = random.randint(1, max_num)
                video = VK().Video().get(owner_id=group_id, album_id=album, count=1, offset=num)
                if len(video['items']) > 0:
                    if 'id' in video['items'][0]:
                        attachment = 'video' + str(video['items'][0]['owner_id']) + '_' + str(video['items'][0]['id'])
                        attachment_result += attachment + ','
                        attachment_count += 1
                if attachment_count >= count:
                    break
            return attachment_result
Exemplo n.º 25
0
 def func(self):
     try:
         users = VK().Messages().get_chat(fields='first_name, last_name')['users']
         _str = 'Внимание, объявление: ' + self.text + '\n'
         for user in users:
             _str += f"@id{user['id']} (.)"
         self.result['message'] = _str
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Exemplo n.º 26
0
 def func(self):
     try:
         users = VK().Messages().get_chat()['users']
         _str = 'Пользователи, найденые в чс:\n'
         index = 0
         for _user in users:
             if int(_user) in db.black:
                 index += 1
                 _str += str(index) + '. ' + UEngine.get_username_by_id(
                     _user) + '\n'
                 VK().Messages().remove_chat_user(user_id=_user)
         if index > 0:
             self.result['message'] = _str
         else:
             self.result[
                 'message'] = 'Пользователей из черного списка не найдено.'
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Exemplo n.º 27
0
 def func(self):
     try:
         if random.randint(0, 100) <= 10:
             self.result['message'] = 'Никто'
         else:
             self.result['message'] = UEngine.get_link_by_id(
                 random.choice(VK().Messages().get_chat()['users']))
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Exemplo n.º 28
0
def get_user_id(user_text):
    if len(user_text):
        try:
            user = VK().Users().get(user_ids=user_text)
            if len(user):
                if 'error' in user:
                    return False
                elif 'id' in user[0]:
                    return user[0]['id']
        except Exception as e:
            Log.show_error(e)
            return False
Exemplo n.º 29
0
 def start(question=None, answers=None):
     _str = f'[{vote_time} sec] Голосование: '
     if command != '':
         _str += command + ' -> ' + mes
     else:
         _str += question
     _str += '\n'
     _i = 1
     for i in answers:
         _str += '- ' + i[0] + '\n'
         _i += 1
     VK().Messages().send(message=_str)
     get()
Exemplo n.º 30
0
 def func(self):
     try:
         response = VK().Messages().get_chat(fields='online')['users']
         _str = ''
         for user in response:
             if int(user['online']):
                 _str += f'{user["first_name"]} {user["last_name"]}'
                 if int(user['id']) in db.admins:
                     _str += ' [Admin]'
                 elif int(user['id']) in db.moders:
                     _str += ' [Moder]'
                 _str += '\n'
         self.result['message'] = _str
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False