Esempio n. 1
0
def template_list(event: MySignalEvent) -> str:
    category = ' '.join(event.args)
    voices = event.db.voices
    if category == 'все':
        message = '📃 Список всех голосовых сообщений:'
        for i, v in enumerate(voices, 1):
            message += f"\n{i}. {v['name']} | {v['cat']}"
    elif not category:
        cats = {}
        for v in voices:
            cats[v['cat']] = cats.get(v['cat'], 0) + 1
        message = "📚 Категории голосовых сообщений:"
        for cat in cats:
            message += f"\n-- {cat} ({cats[cat]})"
    else:
        message = f'📖 Голосовые сообщения категории "{category}":'
        for v in voices:
            if v['cat'] == category:
                message += f"\n-- {v['name']}"
    if '\n' not in message:
        if voices == []:
            message = '👀 Нет ни одного голосового сообщения... Для создания используй команду "+гс"'  # noqa
        else:
            message = '⚠️ Голосовые сообщения по указанному запросу не найдены'
    event.msg_op(2, message)
    return "ok"
Esempio n. 2
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"
Esempio n. 3
0
def send_private(event: MySignalEvent) -> str:
    def abort(text):
        event.msg_op(2, text)
        return "ok"

    if event.command == 'в':
        if event.args[0] != 'лс':
            return "ok"
    uid = find_mention_by_event(event)
    if uid:
        if not (event.payload or event.attachments):
            if event.args and event.reply_message:
                if event.args[0] == 'лс' and len(event.args == 1):
                    abort('❗ Нет данных')
                else:
                    event.payload = ' '.join(event.args)
            else:
                abort('❗ Нет данных')
        try:
            event.api.msg_op(1,
                             uid,
                             event.payload,
                             attachment=','.join(event.attachments))
            msg = '✅ Сообщение отправлено'
        except VkApiResponseException as e:
            if e.error_code == 902:
                msg = '❗ Пользователь ограничил круг лиц, которые могут отправлять ему сообщения'
            else:
                msg = f'❗ Ошибка VK №{e.error_code}: {e.error_msg}'
        event.msg_op(2, msg)
    else:
        event.msg_op(2, '❗ Необходимо упоминание или ответ на сообщение')
    return "ok"
Esempio n. 4
0
def delete_self_message(event: MySignalEvent) -> str:
    count = re.search(r'\d+', event.msg['text'])
    event.api.raise_excepts = False
    if not count:
        count = 2
    else:
        count = int(count[0]) + 1
    if 'все' in event.msg['text']:
        count = 200

    if not event.db.settings['silent_deleting']:
        event.msg_op(2, event.responses['del_self'])

    event.api.exe("""
    var i = 0;
    var msg_ids = {};
    var tn = %s;
    var count = %s;
    var items = API.messages.getHistory({"peer_id":"%s","count":"200", "offset":"0"}).items;
    while (count > 0 && i < items.length) {
        if (items[i].out == 1){
            msg_ids.push(items[i].id);
            count = count - 1;
            };
        if ((tn - items[i].date) > 86400) {count = 0;};
        i = i + 1;
    };
    API.messages.delete({"message_ids": msg_ids,"delete_for_all":"1"});
    return count;
    """ % (event.msg['date'], count, event.chat.peer_id))
    return "ok"
Esempio n. 5
0
def template_list(event: MySignalEvent) -> str:
    category = ' '.join(event.args)
    templates = event.db.templates
    if category == 'все':
        message = '📃 Список всех шаблонов:'
        for i, t in enumerate(templates, 1):
            message += f"\n{i}. {t['name']} | {t['cat']}"
    elif not category:
        cats = {}
        for t in templates:
            cats[t['cat']] = cats.get(t['cat'], 0) + 1
        message = "📚 Категории шаблонов:"
        for cat in cats:
            message += f"\n-- {cat} ({cats[cat]})"
    else:
        message = f'📖 Шаблоны категории "{category}":'
        for t in templates:
            if t['cat'] == category:
                message += f"\n-- {t['name']}"
    if '\n' not in message:
        if templates == []:
            message = '👀 Нет ни одного шаблона... Для создания используй команду "+шаб"'  # noqa
        else:
            message = '⚠️ Шаблоны по указанному запросу не найдены'
    event.msg_op(2, message)
    return "ok"
Esempio n. 6
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"
Esempio n. 7
0
def repeat(event: MySignalEvent) -> str:
    delay = 0.1
    if event.payload:
        delay = int(event.payload)
    site = " ".join(event.args)  # лол, а почему оно так называется?
    time.sleep(delay)
    event.msg_op(1, site)
    return "ok"
Esempio n. 8
0
def little_theft(event: MySignalEvent) -> str:
    event.msg_op(
        2, """все команды начинаются с ".с"
    .с реши 🌟
    .с боты
    .с люди
    .с беседа""")
    return "ok"
Esempio n. 9
0
def anim_list(event: MySignalEvent) -> str:
    if event.db.anims:
        message = '№Ÿ“ƒ аЁаПаИбаОаК аАаНаИаМаОаК:'
        for i, t in enumerate(event.db.anims, 1):
            message += f"\n{i}. {t['name']}"
    else:
        message = '№Ÿ‘€ ааЕб‚ аНаИ аОаДаНаОаЙ аАаНаИаМаКаИ... аЁаОаЗаДаАб‚бŒ аМаОаЖаНаО аНаА баАаЙб‚аЕ аИаЛаИ аКаОаМаАаНаДаОаЙ +аАаНаИаМаКаА'
    event.msg_op(2, message)
    return "ok"
Esempio n. 10
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"
Esempio n. 11
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"
Esempio n. 12
0
def template_delete(event: MySignalEvent, name: str) -> str:
    event.db.templates, exist = delete_template(name, event.db.templates)
    if exist:
        msg = f'✅ Шаблон "{name}" удален'
        event.db.save()
    else:
        msg = f'⚠️ Шаблон "{name}" не найден'
    event.msg_op(2, msg, delete = 1)
    return "ok"
Esempio n. 13
0
def voice_delete(event: MySignalEvent) -> str:
    name = ' '.join(event.args).lower()
    event.db.voices, exist = delete_template(name, event.db.voices)
    if exist:
        msg = f'✅ Голосовое сообщение "{name}" удалено'
        event.db.save()
    else:
        msg = f'⚠️ Голосовое сообщение "{name}" не найдено'
    event.msg_op(2, msg, delete=2)
    return "ok"
Esempio n. 14
0
def message(event: MySignalEvent) -> str:
    msg = ''
    if event.args != None:
        rng = int(event.args[0])
    else:
        rng = 1
    for _ in range(0, rng):
        msg += 'ᅠ\n'
    event.msg_op(1, msg)
    return "ok"
Esempio n. 15
0
def anim_delete(event: MySignalEvent) -> str:
    name = ' '.join(event.args).lower()
    event.db.anims, exist = delete_template(name, event.db.anims)
    if exist:
        msg = f'тœ… ааНаИаМаКаА "{name}" бƒаДаАаЛаЕаНаА'
        event.db.save()
    else:
        msg = f'тš яИ ааНаИаМаКаА "{name}" аНаЕ аНаАаЙаДаЕаНаА'
    event.msg_op(2, msg, delete=2)
    return "ok"
Esempio n. 16
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"
Esempio n. 17
0
def replace(event: MySignalEvent) -> str:
    text = " ".join(event.args)
    if event.args[0] == 'помощь':
        text = 'здесь будет помощь по команде'
    else:
        text = text.replace('клоун', '🤡')
        text = text.replace('клкл', '👍🏻')
        text = text.replace('кркр', '😎')
        text = text.replace('мдаа', '😐')
        text = text.replace('хмхм', '🤔')
    event.msg_op(2, text)
    return "ok"
Esempio n. 18
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']}")
Esempio n. 19
0
def zh(event: MySignalEvent) -> str:
    mes = event.payload
    rng = len(event.payload)
    if rng > 15:
        event.msg_op(
            1, '❗ Слишком длинное сообщение, будет прокручено не полностью')
        rng = 15
    msg = event.msg_op(1, mes)
    for _ in range(rng):
        mes = mes[-1:] + mes[:-1]
        event.api.msg_op(2, event.chat.peer_id, mes, event.msg['id'])
        time.sleep(1)
    return "ok"
Esempio n. 20
0
def anim_play(event: MySignalEvent) -> str:
    name = ' '.join(event.args).lower()
    anim = None
    for a in event.db.anims:
        if a['name'] == name:
            anim = a
            break
    if anim:
        start_player(event.chat.peer_id, event.msg['id'],
                     event.db.access_token,
                     anim['frames'], anim['speed'], True)
    else:
        event.msg_op(2, f'т— ааНаИаМаКаА "{name}" аНаЕ аНаАаЙаДаЕаНаА')
    return "ok"
Esempio n. 21
0
def template_show(event: MySignalEvent, name: str) -> str:
    template = None
    for temp in event.db.templates:
        if temp['name'] == name:
            template = temp
            break
    if template:
        atts = template['attachments']
        atts.extend(event.attachments)
        event.msg_op(2, temp['payload'] + '\n' + event.payload,
                     keep_forward_messages=1, attachment=','.join(atts))
    else:
        event.msg_op(2, f'❗ Шаблон "{name}" не найден')
    return "ok"
Esempio n. 22
0
def ping(event: MySignalEvent) -> str:
    c_time = datetime.now().timestamp()
    delta = round(c_time - event.msg['date'], 2)

    event.msg_op(
        2,
        event.responses['ping_myself'].format(
            время=delta,
            ответ=pings.get(event.command),
            обработано=round(
                datetime.now().timestamp() - event.time -
                event.vk_response_time, 2),  # noqa
            пингвк=round(event.vk_response_time, 2)))
    return "ok"
Esempio n. 23
0
def mention_search(event: MySignalEvent):
    mention = f'[id{event.db.duty_id}|'
    msg_ids = []

    for msg in get_last_th_msgs(event.chat.peer_id, event.api):
        if event.time - msg['date'] >= 86400: break
        if mention in msg['text']:
            msg_ids.append(str(msg['id']))

    if not msg_ids: msg = 'Ничего не нашел 😟'
    else: msg = 'Собсна, вот что нашел за последние 24 часа:'

    event.msg_op(1, msg, forward_messages=','.join(msg_ids))
    return "ok"
Esempio n. 24
0
def chat_info(event: MySignalEvent, users: List[dict], groups: List[dict]):
    admins = []
    owner = None
    for member in users + groups:
        if member.get('is_owner') is True:
            owner = member
        elif member.get('is_admin') is True:
            admins.append('\n-- ' + format_push(member))
    msg = f"""
    Беседа 🇷🇺: {event.chat.name}
    Создатель: {format_push(owner)} 😎
    """.replace('    ', '')
    event.msg_op(1, msg, disable_mentions=1, reply_to=event.msg['id'])
    return "ok"
Esempio n. 25
0
def chat_info(event: MySignalEvent, users: List[dict], groups: List[dict]):
    admins = []
    owner = None
    for member in users + groups:
        if member.get('is_owner') is True:
            owner = member
        elif member.get('is_admin') is True:
            admins.append('\n-- ' + format_push(member))
    msg = f"""
    Создатель 🇷🇺: {format_push(owner)} 😎
    Администраторы:\n{' '.join(admins) if admins else 'Админы невидимые 🌚👍'}
    """.replace('    ', '')
    event.msg_op(1, msg, disable_mentions=1, reply_to=event.msg['id'])
    return "ok"
Esempio n. 26
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"
Esempio n. 27
0
def fonts_convert(event: MySignalEvent) -> str:
    dest = False
    if event.args:
        if event.args[0] in fonts.keys():
            message = f'{" ".join(event.args[1:])}\n{event.payload}'
            dest = fonts[event.args[0]]
            s = ''.join(translit.get(c, c) for c in message)
            msg = u''.join(dict(zip(eng, dest)).get(c, c) for c in s)
            if event.args[0] == '5':
                msg = msg[::-1]
    if not dest:
        msg = """Просмотр списка шрифтов - .с шрифты
        \nКоманда для конвертации:\n.с шрифт [номер]\n[текст]"""
    event.msg_op(2, msg, keep_forward_messages=1)
    return "ok"
Esempio n. 28
0
def chat_info(event: MySignalEvent, users: List[dict], groups: List[dict]):
    admins = []
    owner = None
    for member in users + groups:
        if member.get('is_owner') is True:
            owner = member
        elif member.get('is_admin') is True:
            admins.append('\n-- ' + format_push(member))
    msg = f"""
    Число людей 🇷🇺: {len(users)} 👤
    Население чата: {len(users) + len(groups)} 👪
    Ботов: {len(groups)} (♡_♡)
    """.replace('    ', '')
    event.msg_op(1, msg, disable_mentions=1, reply_to=event.msg['id'])
    return "ok"
Esempio n. 29
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"
Esempio n. 30
0
def start_update(event: MySignalEvent):
    event.msg_op(
        2, '⏱ Начинаю процесс обновления...'
        if PA else '\nРабота не на pythonanywhere не гарантируется')
    with open(os.path.join(path, "updater.py"), 'w', encoding="utf-8") as data:
        data.write(
            get_updater(event.db.access_token, event.msg['id'],
                        event.chat.peer_id))
    out = subprocess.run(f"{runner} {path}/updater.py",
                         shell=True,
                         cwd=path,
                         capture_output=True)
    with open(os.path.join(os.getcwd(), "update.log"), 'w',
              encoding="utf-8") as data:
        data.write(str(out))
    if PA:
        uwsgi.reload()
    return "ok"