Exemplo n.º 1
0
def ban_user(event: MySignalEvent) -> str:
    user_id = find_mention_by_event(event)
    if user_id:
        if event.command == '+чс':
            try:
                if event.api('account.ban', owner_id=user_id) == 1:
                    msg = '😡 Забанено'
            except VkApiResponseException as e:
                if e.error_msg.endswith('already blacklisted'):
                    msg = '❗ Пользователь уже забанен'
                else:
                    msg = f'❗ Ошиб_очка: {e.error_msg}'
        else:
            try:
                if event.api('account.unban', owner_id=user_id) == 1:
                    msg = '💚 Разбанено'
            except VkApiResponseException as e:
                if e.error_msg.endswith('not blacklisted'):
                    msg = '👌🏻 Пользователь не забанен'
                else:
                    msg = f'❗ Ошиб_очка: {e.error_msg}'
    else:
        msg = "❗ Необходимо пересланное сообщение или упоминание"
    event.msg_op(2, msg)
    return "ok"
Exemplo n.º 2
0
 def farming(event: MySignalEvent) -> str:
     comment_id = event.api('wall.createComment', message='ферма', **farm_data)['comment_id']
     event.msg_op(2, '⏱ Комментарий оставлен, танцуем!')
     sleep(2)
     reply_text = event.api('wall.getComments', **farm_data,
                            comment_id=comment_id)['items'][0]['text']
     event.msg_op(2, reply_text)
     return "ok"
Exemplo n.º 3
0
def status(event: MySignalEvent) -> str:
    status = " ".join(event.args) + ' ' + event.payload
    msg = event.msg_op(1, 'Устанавливаю статус...')
    try:
        event.api("status.set", text=status)
        event.msg_op(2, 'Статус успешно установлен')
    except:
        event.msg_op(2, 'Ошибка установки статуса')
    return "ok"
Exemplo n.º 4
0
def sticker(event: MySignalEvent) -> str:
    data = StringIO()
    with open(logpath, 'r', encoding='utf-8') as log:
        data.write(log.read())
    data.name = 'log.txt'
    data.seek(0)
    url = event.api('docs.getMessagesUploadServer',
                    type='doc',
                    peer_id=event.chat.peer_id)['upload_url']
    file_data = requests.post(url, files={'file': data}).json()['file']
    doc = event.api('docs.save', file=file_data, title='log.txt')['doc']
    event.msg_op(1, attachment=f"doc{doc['owner_id']}_{doc['id']}")
Exemplo n.º 5
0
def voice_create(event: MySignalEvent) -> str:
    name = re.findall(r"([^|]+)\|?([^|]*)", ' '.join(event.args))
    if not name:
        event.msg_op(2, "❗ Не указано название")
        return "ok"
    category = name[0][1].lower().strip() or 'без категории'
    name = name[0][0].lower().strip()

    if category == 'все':
        event.msg_op(
            2,
            '❗ Невозможно создать голосовое сообщение ' + 'с категорией "все"')
        return "ok"

    try:
        if event.reply_message['attachments'][0]['type'] != 'audio_message':
            raise TypeError
    except (KeyError, IndexError, TypeError):
        event.msg_op(2, "❗ Необходим ответ на голосовое сообщение")
        return "ok"

    attach = event.reply_message['attachments'][0]['audio_message']
    data = requests.get(attach['link_mp3'])
    audio_msg = io.BytesIO(data.content)
    audio_msg.name = 'voice.mp3'
    upload_url = event.api('docs.getUploadServer',
                           type='audio_message')['upload_url']
    uploaded = requests.post(upload_url, files={
        'file': audio_msg
    }).json()['file']
    audio = event.api('docs.save', file=uploaded)['audio_message']
    del (audio_msg)
    voice = f"audio_message{audio['owner_id']}_{audio['id']}_{audio['access_key']}"

    event.db.voices, exist = delete_template(name, event.db.voices)
    event.db.voices.append({
        "name": name,
        "cat": category,
        "attachments": voice
    })
    event.db.save()

    event.msg_op(
        2, f'✅ Голосовое сообщение "{name}" ' +
        ('перезаписано' if exist else 'сохранено') +
        f'\nДлительность - {attach["duration"]} сек.')
    return "ok"
Exemplo n.º 6
0
def whois(event: MySignalEvent) -> str:
    if event.args == None:
        event.msg_op(1, 'Кто?', reply_to=event.msg['id'])
        return "ok"
    var = event.api('utils.resolveScreenName', screen_name=event.args[0])
    type = 'Пользователь' if var['type'] == 'user' else "Группа" if var[
        'type'] == 'group' else "Приложение"
    event.msg_op(1, f"{type}\nID: {var['object_id']}")
    return "ok"
Exemplo n.º 7
0
def little_theft(event: MySignalEvent) -> str:
    if not event.args[0].startswith('ав'): return "ok"
    event.msg_op(3)
    uid = event.reply_message['from_id']
    if not uid:
        return "ok"
    image_url = event.api('users.get', fields='photo_max_orig',
                          user_ids=uid)[0]['photo_max_orig']
    image = io.BytesIO(requests.get(url=image_url).content)
    image.name = 'ava.jpg'
    upload_url = event.api('photos.getOwnerPhotoUploadServer')['upload_url']
    data = requests.post(upload_url, files={'photo': image}).json()
    del (image)
    post_id = event.api('photos.saveOwnerPhoto',
                        photo=data['photo'],
                        hash=data['hash'],
                        server=data['server'])['post_id']
    event.msg_op(1, '😑😑😑', attachment=f'wall{event.db.duty_id}_{post_id}')
    return "ok"
Exemplo n.º 8
0
def trusted_users(event: MySignalEvent) -> str:
    users = event.api('users.get', user_ids=",".join([str(i) for i in event.db.trusted_users]))

    message = event.responses['trusted_list']
    itr = 0
    for user in users:
        itr += 1
        message += f"\n{itr}. [id{user['id']}|{user['first_name']} {user['last_name']}]"
    
    event.msg_op(2, message)

    return "ok"
Exemplo n.º 9
0
def tosms(event: MySignalEvent):
    cm_id = re.search(r'\d+', event.msg['text'])[0]
    msg = event.api('messages.getByConversationMessageId',
                    conversation_message_ids=cm_id,
                    peer_id=event.chat.peer_id)['items']
    if msg:
        if msg[0].get('action'):
            event.msg_op(2, 'Это сообщение - действие, не могу переслать')
        else:
            event.msg_op(1, 'Вот ента:', forward_messages=msg[0]['id'])
    else:
        event.msg_op(2, '❗ ВК вернул пустой ответ')
    return "ok"
Exemplo n.º 10
0
def change_friend_status(event: MySignalEvent) -> str:
    user_id = find_mention_by_event(event)
    if user_id:
        if event.command.startswith('-др'):
            try:
                status = event.api('friends.delete', user_id=user_id)
                if status.get('friend_deleted'):
                    msg = "💔 Пользователь удален из друзей"
                elif status.get('out_request_deleted'):
                    msg = "✅ Отменена исходящая заявка"
                elif status.get('in_request_deleted'):
                    msg = "✅ Отклонена входящая заявка"
                elif status.get('suggestion_deleted'):
                    msg = "✅ Отклонена рекомендация друга"
                else:
                    msg = "❗ Произошла ошибка"
            except VkApiResponseException as e:
                msg = f"❗ Произошла ошибка VK №{e.error_code} {e.error_msg}"
        else:
            try:
                status = event.api('friends.add', user_id=user_id)
                if status == 1: msg = "✅ Заявка отправлена"
                elif status == 2: msg = "✅ Пользователь добавлен"
                else: msg = "✅ Заявка отправлена повторно"
            except VkApiResponseException as e:
                if e.error_code == 174:
                    msg = "🤔 Ты себя добавить хочешь?"
                elif e.error_code == 175:
                    msg = "❗ Ты в ЧС данного пользователя"
                elif e.error_code == 176:
                    msg = "❗ Пользователь в ЧС"
                else:
                    msg = f"❗ Ошибка: {e.error_msg}"
    else:
        msg = "❗ Необходимо пересланное сообщение или упоминание"
    event.msg_op(2, msg)
    return "ok"
Exemplo n.º 11
0
def pollcreate(event: MySignalEvent) -> str:
    answers = event.payload.split('\n')
    if not answers:
        event.msg_op(2, 'Необходимо указать варианты ответов (с новой строки)')
        return
    if len(answers) > 10:
        answers = answers[:10]
        warning = '⚠️ Максимальное количество ответов - 10'
    else:
        warning = ''
    poll = event.api('polls.create',
                     question=" ".join(event.args),
                     add_answers=json.dumps(answers, ensure_ascii=False))
    event.msg_op(2, warning, attachment=f"poll{poll['owner_id']}_{poll['id']}")
    return "ok"
Exemplo n.º 12
0
def info(event: MySignalEvent) -> str:
    update_info = ''
    last_v, changes = get_last_version()
    if last_v != __version__:
        update_info = 'Доступно обновление! Новая версия: ' + last_v + '\n'
        if changes != '':
            update_info += 'Что нового:\n' + changes + '\n\n'
    owner = event.api('users.get', user_ids=event.db.duty_id)[0]
    message = event.responses['info_myself'].format(чаты=len(
        event.db.chats.keys()),
                                                    владелец=ment_user(owner),
                                                    ид=event.chat.iris_id,
                                                    имя=event.chat.name,
                                                    версия=__version__)
    event.msg_op(2, update_info + message)
    return "ok"
Exemplo n.º 13
0
def ass_crackin(event: MySignalEvent) -> str:
    if event.args[0] != 'жопы': return "ok"
    fail = True
    event.msg_op(2, '☝🏻 Начинаю взлом жопы...')
    time.sleep(1)
    event.msg_op(1,
                 'передать 1 [id332619272|челику]\nна пивас',
                 disable_mentions=1)
    time.sleep(4)
    for msg in event.api('messages.getHistory',
                         count=10,
                         peer_id=event.chat.peer_id)['items']:
        if '🍬 [id332619272|' in msg['text']:
            fail = False
            event.msg_op(1, '💚 Взлом жопы прошел успешно')
            break
    if fail:
        event.msg_op(1,
                     '👀 Взлом жопы прошел неудачно, ослабьте анальную защиту')
    return "ok"
Exemplo n.º 14
0
def readmes(event: MySignalEvent) -> str:
    restricted = {'user'}
    if event.args:
        if event.args[0].lower() in {'все', 'всё'}:
            restricted = set()
        elif event.args[0].lower() == 'беседы':
            restricted = {'group', 'user'}
        elif event.args[0].lower() == 'группы':
            restricted = {'chat', 'user'}
    event.msg_op(2, "🕵‍♂ Читаю сообщения...")
    convers = event.api('messages.getConversations', count=200)['items']
    chats = private = groups = 0
    to_read = []
    code = 'API.messages.markAsRead({"peer_id": %s});'
    to_execute = ''
    for conv in convers:
        conv = conv['conversation']
        if conv['in_read'] != conv['last_message_id']:
            if conv['peer']['type'] in restricted:
                continue
            to_read.append(conv['peer']['id'])
            if conv['peer']['type'] == 'chat': chats += 1
            elif conv['peer']['type'] == 'user': private += 1
            elif conv['peer']['type'] == 'group': groups += 1

    while len(to_read) > 0:
        for _ in range(25 if len(to_read) > 25 else len(to_read)):
            to_execute += code % to_read.pop()
        event.api.exe(to_execute, event.db.me_token)
        time.sleep(0.1)  # TODO: это вообще нужно на PA?
        to_execute = ''

    message = '✅ Диалоги прочитаны:'
    if chats: message += f'\nБеседы: {chats}'
    if private: message += f'\nЛичные: {private}'
    if groups: message += f'\nГруппы: {groups}'
    if message == '✅ Диалоги прочитаны:':
        message = '🤔 Непрочитанных сообщений нет'

    event.msg_op(2, message)
    return "ok"
Exemplo n.º 15
0
def users_getter(
    event: MySignalEvent
) -> Tuple[MySignalEvent, List[dict], List[dict]]:  # noqa
    all_users = event.api('messages.getConversationMembers',
                          peer_id=event.chat.peer_id)

    def find_member_info(uid: int, group: bool) -> dict:
        for user in all_users['groups'] if group else all_users['profiles']:
            if user['id'] == uid:
                return user

    users = []
    groups = []
    for member in all_users['items']:
        if member['member_id'] > 0:
            info = find_member_info(member['member_id'], False)
            info.update(member)
            users.append(info)
        else:
            info = find_member_info(abs(member['member_id']), True)
            info.update(member)
            groups.append(info)
    return event, users, groups