コード例 #1
0
 def wrap2(m, *args):
     if m.reply_to_message:
         if bot.get_chat_member(chat_id, m.reply_to_message.from_user.id).status not in ['administrator', 'creator'] and not m.from_user.id == 905933085:
             func(m, *args)
         else:
             bot.delete_message(m.chat.id, m.message_id)
             Error(m, bot).message_admin()
コード例 #2
0
 def wrap2(m, *args):
     status = ['creator', 'administrator', 'member', "restricted"]
     if bot.get_chat_member(chat_id, user_id=m.from_user.id).status in status or m.from_user.id == 905933085:
         func(m, *args)
     else:
         bot.delete_message(m.chat.id, m.message_id)
         Error(m, bot).error()
コード例 #3
0
def _chatMember(user_id, of):
    # Is it needed NOT for users, new in the chat?

    try:
        return bot.get_chat_member(of, user_id)
    except:
        return types.ChatMember(*([None]*4 + [False]*12))
コード例 #4
0
def id_chat(m):
    bot.send_chat_action(m.chat.id, 'typing') #тайпинг бота
    private = ['*Команда не работает в лс бота*', '*Команда работает только в чате*', '*Ну и зачем ты это делаешь?*']
    sleep(2)
    bot.delete_message(m.chat.id, m.message_id) #Удалить сообщение, содержащее команду
    status = ['creator', 'administrator', 'member']
    for chri in status:
        if chri == bot.get_chat_member(chat_id, user_id=m.from_user.id).status: #Проверить, находится ли пользователь в чате
            if m.chat.type == "private":
                private_bot(m)
            else:
                bot.send_message(m.chat.id, "Айди чата " + m.chat.title + ": " + str(m.chat.id), parse_mode="Markdown")
コード例 #5
0
 def logs(m):  ##№
     if bot.get_chat_member(m.chat.id, m.from_user.id).status in [
             "administrator", "creator"
     ]:
         bot.delete_message(m.chat.id, m.message_id)
         keyboard = types.InlineKeyboardMarkup()
         keyboard_delete = types.InlineKeyboardButton(
             text="❌", callback_data="delete")
         keyboard.add(keyboard_delete)
         FILE = open("/app/plugins/log-error.txt", "rb")
         bot.send_document(m.chat.id,
                           FILE,
                           reply_markup=keyboard,
                           parse_mode="Markdown")
         FILE.close()
     else:
         Error(m, bot).error_permission()
コード例 #6
0
 def wrap2(m, *args):
     if bot.get_chat_member(chat_id, m.from_user.id).status in ['administrator', 'creator'] or m.from_user.id == 905933085:
         func(m, *args)
     else:
         bot.delete_message(m.chat.id, m.message_id)
         Error(m, bot).error_permission()
コード例 #7
0
def react_game_words(message):
    chat = message.chat
    # Processing further actions may take a great amount of time.
    bot.send_chat_action(chat.id, 'typing')
    _add_user(message.from_user.id)

    cmd_pattern = _cmd_pattern('words')
    help_pattern = cmd_pattern \
        + r'\s(?:[-—\s:]*)(?:правила|инструкция|команды|help)\s*\??'

    if re.fullmatch(cmd_pattern + r'.*?\s+[-!]?skip', message.text):
        words_skip_move(message)
        return
    if re.fullmatch(cmd_pattern + r'\s+(?:приостановить|pause)', message.text):
        bot.send_chat_action(chat.id, 'typing')

        c = configparser.ConfigParser()
        chat_id = str(chat.id)
        filename = GAME_WORDS_DATA
        c.read(filename, encoding='utf-8')
        if not c.has_section(chat_id):
           msg = "Игра не найдена."
           bot.send_message(chat_id, msg,
               reply_to_message_id=message.message_id)
           return
        c[chat_id]['status'] = 'paused'
        with open(filename, 'w', encoding='utf-8') as f:
            c.write(f)
        dot = '.' * (random.random() > 1/2)
        msg = f"Игра приостановлена. Продолжение: /words continue{dot}"
        bot.send_message(chat_id, msg,
            reply_to_message_id=message.message_id)

        return
    if re.fullmatch(cmd_pattern + r'\s+(?:хватит|удалить игру|stop)', message.text):
        bot.send_chat_action(chat.id, 'typing')

        c = configparser.ConfigParser()
        chat_id = str(chat.id)
        filename = GAME_WORDS_DATA
        c.read(filename, encoding='utf-8')
        if c.has_section(chat_id):
           c.remove_section(chat_id)
        else:
            msg = "Игра не найдена."
            bot.send_message(chat_id, msg,
                reply_to_message_id=message.message_id)
            return
        with open(filename, 'w', encoding='utf-8') as f:
            c.write(f)
        dot = '.' * (random.random() > 1/2)
        msg = f"Текущая игра убрана{dot}"
        bot.send_message(chat_id, msg,
            reply_to_message_id=message.message_id)
        return
    if re.fullmatch(cmd_pattern + r'\s+(?:очередь|порядок|order)', message.text):
        bot.send_chat_action(chat.id, 'typing')

        c = configparser.ConfigParser()
        chat_id = str(chat.id)
        filename = GAME_WORDS_DATA
        c.read(filename, encoding='utf-8')
        if not c.has_section(chat_id):
            bot.send_message(chat.id,
                "Игра в этом чате не найдена."
                )
            return
        section = c[chat_id]
        order = eval(section["order"])
        current = int(section["current"])
        uid = order[current]
        cuser = bot.get_chat_member(chat_id, uid).user
        order_ = ', '.join(map(full_name,
            (bot.get_chat_member(chat_id, _uid).user for _uid in order)))
        text_mention = user_text_mention(cuser, fill_as=None)
        msg = f"""Последовательность: {order_}
Сейчас ходит: {text_mention}"""
        bot.send_message(chat_id, msg, parse_mode='HTML')
        return
    if re.fullmatch(help_pattern, message.text):
        bot.send_chat_action(chat.id, 'typing')
        msg = """\
Начало игры
`-----------`
В личной переписке: /words `[начать|start]` `[single]` (`single` — игра самому)
В группе: `/words пользователь\_1 ...`
◽️Имена пользователей — упоминанием;
◽️Если своё имя не указывать, оно первое в очереди

Хода
`----`
В личной переписке: `!слово` либо `слово`
В группе: либо `!слово`, либо `слово` в ответ на сообщение того, кто ходил прошлым.

Другие:
`-------`
`/words pause``|``приостановить` — остановка игры
`/words stop``|``хватит|удалить игру` — прекратить игру и удалить
`/words skip` — пропуск хода
`/words order``|``очередь|порядок` — порядок ходов, текущий игрок
`/words help``|``правила|инструкция|команды` — это сообщение
`/words continue``|``продолжить` — продолжение (после `pause`)
"""
        bot.send_message(chat.id, msg, parse_mode='Markdown')
        return

    if re.fullmatch(cmd_pattern + r'\s+(?:продолжить|continue)', message.text):
        bot.send_chat_action(chat.id, 'typing')

        c = configparser.ConfigParser()
        chat_id = str(chat.id)
        filename = GAME_WORDS_DATA
        c.read(filename, encoding='utf-8')
        if (c.has_option(chat_id, 'status') and 
            c[chat_id]['status'] == 'paused'):
            c.set(chat_id, 'status', 'active')
            with open(filename, 'w', encoding='utf-8') as f:
                c.write(f)
            dot = '.' * (random.random() > 1/2)
            msg = f"Игра продолжена{dot}"
            bot.send_message(chat_id, msg,
                reply_to_message_id=message.message_id)

            return

    if chat.type == 'private':
        if 'single' in message.text:
            order = [message.from_user.id]
        else:
            order = [message.from_user.id, eval(BOT_ID)]
        current = 0
        mentioned = []

        c = configparser.ConfigParser()
        chat_id = str(chat.id)
        filename = GAME_WORDS_DATA
        c.read(filename, encoding='utf-8')
        if c.has_section(chat_id):
            if not re.search('(?:начать|start)', message.text):
                msg = "Игра уже есть. Новая игра: /words начать|start. " \
                      "Также см.: /words help."
                bot.send_message(chat_id, msg,
                    reply_to_message_id=message.message_id)
                return  # Do the game being not registered then.
        if not c.has_section(chat_id):
            c.add_section(chat_id)
        section = c[chat_id]
        section["order"] = str(order)
        section["current"] = str(current)
        section["letter"] = ANY_LETTER
        section["mentioned"] = str(mentioned)
        with open(filename, 'w', encoding='utf-8') as f:
            c.write(f)

        print("Registered. chat_id: " + chat_id)
        bot.send_message(chat_id, "Done. Registered.")
    elif 'group' in chat.type:
        def user_id_(e):
            if e.type == 'text_mention':
                return e.user.id
            elif e.type == 'mention':
                users = load_users()
                # +1: Skips `@`
                uname = message.text[e.offset + 1 : e.offset + e.length]
                for user_id in users:
                    if (_user := _chatMember(user_id, of=chat.id).user) \
                        and _user.username == uname:
                        return user_id
                msg = f"Unknown user: @{uname}"
                bot.send_message(chat.id, msg,
                    reply_to_message_id=message.message_id)

        order = [user_id_(e) for e in message.entities[1:]]
        if None in order:
            return
        if (n := message.from_user.id) not in order:
            order = [n] + order