Ejemplo n.º 1
0
def groupbot(event: Event):
    group_id = 0 - int(event.obj['group_id'])
    for item in event.api("messages.getConversations", count=100,
                          filter="all")['items']:
        conv = item['conversation']
        if conv['peer']['type'] == "chat":
            sleep(0.3)
            for msg in event.api('messages.getHistory',
                                 peer_id=conv['peer']['id'])['items']:
                if msg[cmid_key] == event.msg[cmid_key]:
                    if msg.get('action', {}).get('member_id') == group_id:
                        peer_id = msg['peer_id']
                        break
    msg_id = event.api.msg_op(
        1, peer_id, '👀 Обнаружена группа Ириса, пытаюсь выдать админку...')
    try:
        if event.api('messages.setMemberRole',
                     peer_id=peer_id,
                     member_id=group_id,
                     role='admin') == 1:
            event.api.msg_op(2, peer_id,
                             '✅ Ириска назначен администратором беседы',
                             msg_id)
    except VkApiResponseException as e:
        if e.error_code == 15:
            event.api.msg_op(2, peer_id, FAILED_MSG, msg_id)
        else:
            event.api.msg_op(2, peer_id, f'❗ Ошибка VK: {e.error_msg}', msg_id)
Ejemplo n.º 2
0
def bind_chat(event: Event) -> str:
    search_res = event.api("messages.search",
                           q=event.msg['text'],
                           count=10,
                           extended=1)
    for msg in search_res['items']:
        if msg[cmid_key] == event.msg[cmid_key]:
            if msg['from_id'] == event.msg['from_id']:
                message = msg
                break
    for conv in search_res['conversations']:
        if conv['peer']['id'] == message['peer_id']:  # type: ignore
            chat_name = conv['chat_settings']['title']
            break
    chat_raw = {
        "peer_id": message['peer_id'],  # type: ignore
        "name": chat_name,  # type: ignore
        "installed": False
    }
    event.db.chats.update({event.obj['chat']: chat_raw})
    event.db.save()
    event.chat = Chat(chat_raw, event.obj['chat'])
    event.api.msg_op(1, event.chat.peer_id,
                     event.responses['chat_bind'].format(имя=event.chat.name))
    return "ok"
Ejemplo n.º 3
0
def callback():
    event = Event(request)
    if event.db.secret != event.secret:
        return "Неверный секретный код"
    if event.user_id != event.db.duty_id:
        return "Неверный ID дежурного"
    data = [d for d in dp.event_run(event)]
    for d in data:
        if d != "ok" and not isinstance(d, dict):
            return "<ошибочка>" + json.dumps(
                {"ошибка": d}, ensure_ascii=False, indent=2)
    return json.dumps(data[0], ensure_ascii=False) if data else "ok"
Ejemplo n.º 4
0
def callback():
    event = Event(request)

    if event.secret != event.db.secret:
        return 'Неверная секретка', 500

    d = dp.event_run(event)
    if d == "ok":
        return json.dumps({"response": "ok"}, ensure_ascii=False)
    elif type(d) == dict:
        return json.dumps(d, ensure_ascii=False)
    else:
        return r"\\\\\ашипка хэз бин произошла/////" + '\n' + d
Ejemplo n.º 5
0
def bind_chat(event: Event) -> str:
    for chat in event.api("messages.getConversations", count=100)['items']:
        diff = chat['last_message']['conversation_message_id'] - event.msg['conversation_message_id']
        if diff < 0 or diff > 50:
            continue
        conv = chat['conversation']
        if conv['peer']['type'] == "chat":
            message = event.api('messages.getByConversationMessageId', peer_id=conv['peer']['id'],
                conversation_message_ids=event.msg['conversation_message_id'])['items']
            if not message:
                continue
            if message[0]['from_id'] == event.msg['from_id'] and message[0]['date'] == event.msg['date']:
                chat_dict = {"peer_id": conv['peer']['id'],
                             "name": conv['chat_settings']['title'],
                             "installed": False}
                event.db.chats.update({event.obj['chat']: chat_dict})
                event.db.save()
                event.chat = Chat(chat_dict, event.obj['chat'])
                break
    event.api.msg_op(1, event.chat.peer_id,
                     event.responses['chat_bind'].format(имя=event.chat.name))
    return "ok"
Ejemplo n.º 6
0
def groupbots(event: Event) -> str:
    group_id = 0 - int(event.obj['group_id'])
    for item in event.api("messages.getConversations", count=100, filter="all")['items']:
        conv = item['conversation']
        if conv['peer']['type'] == "chat":
            sleep(0.3)
            for msg in event.api('messages.getHistory', peer_id = conv['peer']['id'])['items']:
                if msg['conversation_message_id'] == event.msg['conversation_message_id']:
                    if msg.get('action', {}).get('member_id') == group_id:
                        peer_id = msg['peer_id']
                        break
    msg_id = event.api.msg_op(1, peer_id, '👀 Обнаружена группа Ириса, пытаюсь выдать админку...')
    try:
        if event.api('messages.setMemberRole', peer_id = peer_id,
                     member_id = group_id, role = 'admin') == 1:
            event.api.msg_op(2, peer_id, '✅ Ириска назначен администратором беседы', msg_id)
    except VkApiResponseException as e:
        if e.error_code == 15:
            event.api.msg_op(2, peer_id, '❗ Не получилось назначить группу администратором.\nСкорее всего это либо чат сообщества, либо у меня нет прав для назначения администраторов', msg_id)
        else:
            event.api.msg_op(2, peer_id, f'❗ Ошибка VK: {e.error_msg}', msg_id)
    return "ok"
Ejemplo n.º 7
0
def delete_messages_from_user(event: Event) -> str:
    event.obj['silent'] = False

    amount = event.obj.get("amount")

    msg_ids = []
    ct = datetime.now().timestamp()

    for msg in get_msgs(event.chat.peer_id, event.api):
        if ct - msg['date'] >= 86400: break
        if msg['from_id'] in event.obj['member_ids'] and not msg.get('action'):
            msg_ids.append(msg['id'])

    if amount:
        if amount < len(msg_ids):
            msg_ids = msg_ids[:len(msg_ids) - (len(msg_ids) - amount)]

    if not msg_ids:
        event.api.msg_op(1, event.chat.peer_id, event.responses['del_err_not_found'])
        return "ok"

    return msg_delete(event, del_info(event), msg_ids)
Ejemplo n.º 8
0
def to_group(event: Event) -> str:
    def send(text, **kwargs):
        return event.api.msg_op(1, event.chat.peer_id, text, **kwargs)

    event.set_msg()

    def parse_attachments(event: Event) -> typing.Tuple[str, typing.List[str]]:
        def get_payload(text: str) -> str:
            regexp = r"(^[\S]+)|([\S]+)|(\n[\s\S \n]+)"
            _args = re.findall(regexp, text)
            payload = ""
            for arg in _args:
                if arg[2] != '':
                    payload = arg[2][1:]
            return payload

        def upload_photo(url: str) -> str:
            server = event.api("photos.getWallUploadServer",
                               group_id=event.obj['group_id'])
            photo = requests.get(url).content
            with open('tmp.jpg', 'wb') as f:
                f.write(photo)

            data = requests.post(server['upload_url'],
                                 files={
                                     'photo': open('tmp.jpg', "rb")
                                 }).json()
            attach = event.api("photos.saveWallPhoto",
                               group_id=event.obj['group_id'],
                               **data)[0]

            return f"photo{attach['owner_id']}_{attach['id']}_{attach['access_key']}"

        payload = get_payload(event.msg['text'])

        attachments = []
        if event.reply_message != None:
            if payload == "":
                payload = event.reply_message['text']
            message = get_msg(event.api, event.chat.peer_id,
                              event.reply_message[cmid_key])
            for attachment in message.get('attachments', []):

                a_type = attachment['type']

                if a_type in ['link']: continue

                if a_type == 'photo':
                    attachments.append(
                        upload_photo(attachment['photo']['sizes'][
                            len(attachment['photo']['sizes']) - 1]['url']))
                else:
                    attachments.append(
                        f"{a_type}{attachment[a_type]['owner_id']}_{attachment[a_type]['id']}_{attachment[a_type]['access_key']}"
                    )

        attachments.extend(event.attachments)
        return payload, attachments

    text, attachments = parse_attachments(event)

    try:
        data = event.api('wall.post',
                         owner_id=(-1) * event.obj['group_id'],
                         from_group=1,
                         message=text,
                         attachments=",".join(attachments))

        send(event.responses['to_group_success'],
             attachment=f"wall-{event.obj['group_id']}_{data['post_id']}")
    except VkApiResponseException as e:
        if e.error_code == 214:
            send(event.responses['to_group_err_forbidden'])
        elif e.error_code == 220:
            send(event.responses['to_group_err_recs'])
        elif e.error_code == 222:
            send(event.responses['to_group_err_link'])
        else:
            send(event.responses['to_group_err_vk'] + str({e.error_msg}))
    except:
        send(event.responses['to_group_err_unknown'])

    return "ok"
Ejemplo n.º 9
0
def delete_by_type(event: Event) -> str:
    event.obj['silent'] = False

    typ = event.obj['type']
    if typ == 'stickers': typ = 'sticker'
    elif typ == 'voice': typ = 'audio_message'
    elif typ == 'gif': typ = 'doc'
    elif typ == 'article': typ = 'link'

    msg_ids = []
    ct = (event.obj['time'] +
          86400 if event.obj.get('time') else datetime.now().timestamp())

    amount = event.obj.get('amount', 1000)

    null_admins = False

    if not event.obj['admin_ids']:
        null_admins = True
        event.obj['admin_ids'] = []
    else:
        if type(event.obj['admin_ids']) == str:
            event.obj['admin_ids'] = event.obj['admin_ids'].split(',')
        if type(event.obj['admin_ids'][0]) == str:
            event.obj['admin_ids'] = [int(i) for i in event.obj['admin_ids']]

    users = {}

    def append(msg):
        msg_ids.append(msg['id'])
        users.update({msg['from_id']: users.get(msg['from_id'], 0) + 1})

    if typ in {'any', 'period'}:
        for msg in get_msgs(event.chat.peer_id, event.api):
            if ct - msg['date'] > 86400 or len(msg_ids) == amount:
                break
            if msg['from_id'] in event.obj['admin_ids']:
                continue
            append(msg)
    else:
        for msg in get_msgs(event.chat.peer_id, event.api):
            atts = msg.get('attachments')
            if ct - msg['date'] > 86400 or len(msg_ids) == amount:
                break
            if msg['from_id'] in event.obj['admin_ids']:
                continue
            if typ == 'forwarded' and msg['fwd_messages']:
                append(msg)
            elif atts:
                for att in atts:
                    if att['type'] == typ:
                        append(msg)
                    elif typ == 'doc' and att.get('doc'):
                        if att['doc'].get('ext') == 'gif':
                            append(msg)
                    elif typ == 'link' and att.get('link'):
                        if att['link'].get('description') == 'Article':
                            append(msg)

    if not msg_ids:
        event.api.msg_op(1, event.chat.peer_id,
                         event.responses['del_err_not_found'])
        return "ok"

    event.obj['silent'] = True
    event.api.raise_excepts = False

    msg_delete(event, del_info(event), msg_ids)

    if null_admins:
        event.api.msg_op(
            1, event.chat.peer_id, 'Ирис не прислал список администраторов.' +
            'Попробуй обновить чат (команда "обновить чат")')
        return "ok"

    message = 'Удалены сообщения следующих пользователей:\n'

    for user in event.api('users.get',
                          user_ids=','.join([str(i) for i in users.keys()])):
        message += f'{ment_user(user)} ({users.get(user["id"])})\n'

    event.api.msg_op(1, event.chat.peer_id, message, disable_mentions=1)
    return "ok"