Exemplo n.º 1
0
    class Singleton(Bot):
        def __init__(self):
            super().__init__(Database().get_getlink(), message=self.message)
            self.tree = Tree()
            self.Singleton = BotId()
            self.Singleton.set_bot("getlink", super().get_bot())
            self.Singleton.reset_key_id("getlink")

        def message(self, msg):
            content_type, chat_type, chat_id = telepot.glance(msg)
            if content_type == 'text' and chat_type == "private" and msg[
                    "text"] == '/start':
                try:
                    self.Singleton.set_key_id(
                        telepot.message_identifier(
                            send_message(
                                super().get_bot(),
                                chat_id,
                                "Select a bot:",
                                reply_markup=self.create_url_inline_query())),
                        "getlink")
                except TypeError:
                    pass

        def create_url_button(self, topic):
            return InlineKeyboardButton(
                text=topic,
                url="https://t.me/" + self.tree.get_username_by_topic(topic) +
                "?start=foo")

        def create_url_inline_query(self):
            data = []
            for elem in self.tree.get_topic_list():
                data.append([self.create_url_button(elem)])
            return InlineKeyboardMarkup(inline_keyboard=data)
Exemplo n.º 2
0
    def __init__(self,deck,models,funcs,threshold=100,num_players=2,trunk=None,play=False,tournament=False):
        self.deck = deck
        self.num_players = num_players
        self.players = []
        self.models = models
        self.threshold = threshold
        self.play = play
        # if self.play == False: #don't need this because we are using 2 models always
        if tournament == False:
            self.models[-1]._make_predict_function()
            self.models[-2]._make_predict_function()
        else: #fix this #####
            self.models[0][0]._make_predict_function()
            self.models[0][1]._make_predict_function()
            self.models[1][0]._make_predict_function()
            self.models[1][1]._make_predict_function()

        self.funcs = funcs
        self.results = [0,0]
        self.possibilities = np.arange(53)
        self.epsilon = 0.0001
        self.tournament = tournament
        #reusing previously generated tree
        if trunk == None:
            self.trunk = Tree()
        else:
            self.trunk = trunk
Exemplo n.º 3
0
def trainAdaBoost(x, y, num_of_trees):
    rows, _ = np.shape(x)
    class_names = np.unique(y)
    class_names = np.flip(class_names)
    #Weights for each class in each 'parallell' tree
    list_of_ensembles = [
    ]  # Three ensembles for each class_name poor, median, excellent

    for i in range(len(class_names)):
        y_binary = convertOneVsAllToBinary(y, class_names[i])
        ensemble = []
        weights = np.ones(shape=(
            rows,
            1,
        ), dtype=float)

        for _ in range(num_of_trees):
            stump = Tree(x, y_binary, 1, weights)
            stump.train(x, y_binary, 'boosting', weights)
            y_pred = testTree(x, stump)
            y_pred = y_pred.astype(int)
            epsilon = calculateEpsilon(y_binary, y_pred, weights)
            alpha = calculateAlpha(epsilon)
            ensemble.append((
                alpha,
                stump,
            ))

            #reweights
            weights = reweight(y_binary, y_pred, weights)
        # should make three ensembles
        list_of_ensembles.append(ensemble)

    return list_of_ensembles
Exemplo n.º 4
0
def trainTree(x, y, depth, weights=None):
    # return tree that have been trained

    # Initiate tree object
    dTree = Tree(x, y, depth)  # Need to create the tree
    dTree.train(x, y, 'boosting', weights)  # Train it bruh
    # TBD
    return dTree
Exemplo n.º 5
0
 def __init__(self):
     self.keyboard = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="/new_bot", callback_data='n')],[InlineKeyboardButton(text="/delete_bot", callback_data='d')],[InlineKeyboardButton(text="/start", callback_data='s')],[InlineKeyboardButton(text="/change_pwd", callback_data='c')]])
     self.boolvett={}
     self.unconfirmed_bot={}
     self.unc_del={}
     self.tree=Tree()
     self.user_request=self.tree.read_pwd()
     self.admin_pwd=self.tree.get_pwd_admin()
     self.select_str="Please select a topic:"
     self.singleton_id=BotId()
     self.singleton_ban=UserBanned()
     super().__init__(Database().get_creation(),self.message,self.query)
     self.singleton_id.set_bot("creation",super().get_bot())
     self.singleton_id.reset_key_id("creation")
Exemplo n.º 6
0
def trainBaggingEnsemble(x, y, depth, num_of_trees):
    percentage = 3 / 4
    ensemble = []
    rows, _ = np.shape(x)
    row_indexes = np.arange(rows)
    num_of_training_data = math.ceil(rows * percentage)
    for _ in range(num_of_trees):
        # I want to only use 75% of the data when training
        # Randomize which data to pull 75% out of x for each tree
        np.random.shuffle(row_indexes)
        x = x[row_indexes, :]
        y = y[row_indexes, :]

        training_x = x[0:num_of_training_data, :]
        training_y = y[0:num_of_training_data, :]
        dTree = Tree(training_x, training_y, depth)
        dTree.train(training_x, training_y, 'bagging')
        ensemble.append(dTree)

    return ensemble
def build_tree(data):
    lst = return_frequency(data)
    nodes_list = []
    for node_value in lst:
        node = Node(node_value)
        nodes_list.append(node)

    while len(nodes_list) != 1:
        first_node = nodes_list.pop()
        second_node = nodes_list.pop()
        val1, char1 = first_node.value
        val2, char2 = second_node.value
        node = Node((val1 + val2, char1 + char2))
        node.set_left_child(second_node)
        node.set_right_child(first_node)
        sort_values(nodes_list, node)

    root = nodes_list[0]
    tree = Tree()
    tree.root = root
    return tree
Exemplo n.º 8
0
def parse(state):
    for sign in signs:
        if sign[0] == '-':
            pos = 0
            while True:
                if pos == len(state) or state[pos] == sign[0]:
                    break
                if state[pos] == '(':
                    pos, balance = pos + 1, 1
                    while pos < len(state) and balance > 0:
                        balance += state[pos] == '(' and 1 or state[pos] == ')' and -1 or 0
                        pos += 1
                else:
                    pos += 1
            if pos != len(state):
                return Tree(sign, False, parse(state[:pos]), parse(state[pos + 2:]))
        else:
            pos = len(state) - 1
            while True:
                if pos == -1 or state[pos] == sign[0]:
                    break
                if state[pos] == ')':
                    pos, balance = pos - 1, -1
                    while pos >= 0 > balance:
                        balance += state[pos] == '(' and 1 or state[pos] == ')' and -1 or 0
                        pos -= 1
                else:
                    pos -= 1
            if pos != -1:
                return Tree(sign, False, parse(state[:pos]), parse(state[pos + 1:]))

    st = state[0]
    if st == '(':
        return parse(state[1:-1])
    elif st == '!':
        return Tree("!", False, None, parse(state[1:]))
    else:
        return Tree(state, True, None, None)
Exemplo n.º 9
0
 def __init__(self):
     self.keyboard = InlineKeyboardMarkup(inline_keyboard=[
         [InlineKeyboardButton(text="/answer", callback_data='a')],
         [InlineKeyboardButton(text="/report", callback_data='r')],
         [InlineKeyboardButton(text="/start", callback_data='s')],
         [InlineKeyboardButton(text="/list", callback_data='l')],
         [InlineKeyboardButton(text="/free_list", callback_data='fl')],
         [InlineKeyboardButton(text="/ban", callback_data='b')],
         [InlineKeyboardButton(text="/ban_list", callback_data='bl')],
         [InlineKeyboardButton(text="/sban", callback_data='sb')],
         [InlineKeyboardButton(text="/change", callback_data='c')],
         [InlineKeyboardButton(text="/delete", callback_data='d')],
         [InlineKeyboardButton(text="/hints", callback_data='h')],
         [InlineKeyboardButton(text="/add_hint", callback_data='ah')],
         [
             InlineKeyboardButton(text="/change_lang",
                                  callback_data='cl')
         ],
         [
             InlineKeyboardButton(text="/change_role",
                                  callback_data='cr')
         ]
     ])
     self.tree = Tree()
     self.query_bool = {}
     self.lang_bool = {}
     self.query_bool = {}
     self.prev_lang = {}
     self.topic_name = {}
     self.is_logged = {}
     self.singleton_id = BotId()
     self.singleton_ban = UserBanned()
     super().__init__(Database().get_teacher(), self.message,
                      self.query)
     self.tree.send_notification_teacher(super().get_bot())
     self.singleton_id.set_bot("teacher", super().get_bot())
     self.singleton_id.reset_key_id("teacher")
Exemplo n.º 10
0
def check_proof(input_file_name, output_file_name):
    inp = open(input_file_name, "r", encoding="utf-8")
    out = open(output_file_name, "w", encoding="utf-8")
    glist = inp.readlines()

    all_ok = True
    j = 0
    for line in glist:
        j += 1
        if line == "":
            continue
        node = parser.parse(line.rstrip())

        cur_ok = False
        for axiom in axiom_node:
            cur_ok = Tree.is_same(axiom, node, node)
            if cur_ok:
                break

        if not cur_ok:
            prev_node = modus_ponens(str(node))
            cur_ok = prev_node is not None

        if not cur_ok:
            all_ok = False
            break

        past_string_set.add(str(node))

    if all_ok:
        out.write("Доказательство корректно.")
    else:
        out.write("Доказательство некорректно со строки {0}.".format(j))

    inp.close()
    out.close()
Exemplo n.º 11
0
def check_proof(input_file_name, output_file_name):
    inp = open(input_file_name,  "r", encoding="utf-8")
    out = open(output_file_name, "w", encoding="utf-8")
    glist = inp.readlines()

    all_ok = True
    j = 0
    for line in glist:
        j += 1
        if line == "":
            continue
        node = parser.parse(line.rstrip())

        cur_ok = False
        for axiom in axiom_node:
            cur_ok = Tree.is_same(axiom, node, node)
            if cur_ok:
                break

        if not cur_ok:
            prev_node = modus_ponens(str(node))
            cur_ok = prev_node is not None

        if not cur_ok:
            all_ok = False
            break

        past_string_set.add(str(node))

    if all_ok:
        out.write("Доказательство корректно.")
    else:
        out.write("Доказательство некорректно со строки {0}.".format(j))

    inp.close()
    out.close()
Exemplo n.º 12
0
class Durak(object):
    def __init__(self,deck,models,funcs,threshold=100,num_players=2,trunk=None,play=False,tournament=False):
        self.deck = deck
        self.num_players = num_players
        self.players = []
        self.models = models
        self.threshold = threshold
        self.play = play
        # if self.play == False: #don't need this because we are using 2 models always
        if tournament == False:
            self.models[-1]._make_predict_function()
            self.models[-2]._make_predict_function()
        else: #fix this #####
            self.models[0][0]._make_predict_function()
            self.models[0][1]._make_predict_function()
            self.models[1][0]._make_predict_function()
            self.models[1][1]._make_predict_function()

        self.funcs = funcs
        self.results = [0,0]
        self.possibilities = np.arange(53)
        self.epsilon = 0.0001
        self.tournament = tournament
        #reusing previously generated tree
        if trunk == None:
            self.trunk = Tree()
        else:
            self.trunk = trunk
        
    def save_tree(self,tree_path):
        with open(tree_path, 'wb') as handle:
            pickle.dump(self.trunk, handle, protocol = pickle.HIGHEST_PROTOCOL)

    def load_tree(self,tree_path):
        with open(tree_path, 'rb') as handle:
            tree = pickle.load(handle)
        self.trunk = tree
        
    def start_from_state(self,game_state_dict):
        self.play_deck = copy.deepcopy(game_state_dict['deck'])
        self.players = []
        #player1
        hand1 = copy.deepcopy(game_state_dict['hand1'])
        #print(hand1,'hand1')
        hand_1hot1 = convert_str_to_1hot(hand1)
        pl1 = Player(hand1,hand_1hot1,0)
        self.players.append(pl1)
        #player2
        hand2 = copy.deepcopy(game_state_dict['hand2'])
        #print(hand2,'hand2')
        hand_1hot2 = convert_str_to_1hot(hand2)
        pl2 = Player(hand2,hand_1hot2,1)
        self.players.append(pl2)
        #
        trump_card = copy.deepcopy(game_state_dict['trump_card'])
        trump_card_vec = convert_str_to_1hot([trump_card])[0]
        trump_suit = trump_card[1]
        attacking_player = copy.deepcopy(game_state_dict['attacking_player'])
        previous_winner = (False,0)
        first_root = self.trunk.get_child(attacking_player)
        second_root = self.trunk.get_child((attacking_player + 1)%2)

        discard_pile = copy.deepcopy(game_state_dict['discard_pile'])
        discard_pile_1hot = copy.deepcopy(game_state_dict['discard_pile_1hot'])
        self.game_state = Game_state(trump_card,trump_card_vec,trump_suit,len(self.play_deck),attacking_player,previous_winner,first_root,second_root,attacking_player,discard_pile=discard_pile,discard_pile_1hot=discard_pile_1hot)
        
    def init_game(self,previous_winner):
        self.play_deck = copy.deepcopy(self.deck)
        shuffle(self.play_deck)
        self.players = []
        for player_id in range(self.num_players):
            #switching to dealing off the front. Then we can append the trump card to the end
            hand = self.play_deck[:6]
            hand_1hot = convert_str_to_1hot(hand)
            del self.play_deck[:6]
            pl = Player(hand,hand_1hot,player_id)
            self.players.append(pl)
        trump_card = self.play_deck[0]
        trump_card_vec = convert_str_to_1hot([trump_card])[0]
        trump_suit = trump_card[1]
#         print(trump_card,'trump card')
        self.play_deck.append(self.play_deck[0])
        self.play_deck.pop(0)
        attacking_player = self.who_starts(previous_winner)
        #Tree
        first_root = self.trunk.get_child(attacking_player)
        second_root = self.trunk.get_child((attacking_player + 1)%2)
        #Instantiate game state
        self.game_state = Game_state(trump_card,trump_card_vec,trump_suit,len(self.play_deck),attacking_player,previous_winner,first_root,second_root,attacking_player,discard_pile=[],discard_pile_1hot=[])
        
    def update_game_state(self):
        self.game_state.remaining_cards = len(self.play_deck)
        self.game_state.played_cards = []
        self.game_state.played_cards_1hot = []
        self.game_state.played_card = None
        self.game_state.played_card_1hot = None
        self.game_state.picked_up = False
        
    def int_from_1hot(self,card):
        integer = np.where(card==1)[0]
        
    def print_game_state(self):
        print(self.game_state.remaining_cards,'remaining cards')
        print(self.game_state.played_cards,'played cards')
        print(len(self.game_state.played_cards_1hot),'len played cards 1hot')
        print(self.game_state.played_card,'played card')
        #print(self.game_state.played_card_1hot,'played card 1hot')
        print(self.game_state.discard_pile,'discard_pile')
        #print(self.game_state.discard_pile_1hot.shape,'shape of discard_pile_1hot')
        print(self.game_state.attacking_player,'attacking_player')
        print(self.game_state.defending_player,'defending_player')
        for player in self.players:
            print(len(player.hand),'hand length')
        
    def print_player_attributes(self):
        for player in self.players:
            print(len(player.hand),'hand')
            #print(convert_1hot_to_str(player.hand_1hot),'1hot')
        
    def draw_cards(self,player_id):
        if len(self.play_deck) > 0:
            while len(self.players[player_id].hand) < 6 and len(self.play_deck) > 0:
                self.players[player_id].hand.append(self.play_deck.pop(0))
            self.players[player_id].hand_1hot = convert_str_to_1hot(self.players[player_id].hand)
        
    def who_starts(self,previous_winner):
        if previous_winner[0] == True:
            return previous_winner[1]
        else:
            #check for lowest trump, if no trump then check for lowest card. if tie then split based on suit
            return choice([0,1])
            
    def play_game(self):
        #increase root node visit counts
        self.game_state.first_root.update_visit()
        self.game_state.second_root.update_visit()
        while self.game_state.game_over == False:
            #self.print_game_state() #PRINT STATEMENT
            self.attack()
            if self.game_state.played_card:
#                 print('defending')
                self.defend()
            #check if round is over, else continue
            #self.print_player_attributes()
            self.is_round_over()
            if self.game_state.round_over == True:
                self.update_game_state
                self.is_game_over()
        self.record_outcome()
            
    #to account for giving multiple cards. I'll just check for the taking condition 
    #and then allow the attacker to give up to 6 cards
    def attack(self):
#         print('attacking')
        if self.game_state.played_cards:
            #not first action: We will mask our possibility vector with the like rank cards already played
            #53 because of the possibility of picking up the cards (needs to be consistent for the model)
            possibility_vec = np.zeros((1,53)).flatten()
            possibility_vec[52] = 1
            ranks = []
            [ranks.append(card[0]) for card in self.game_state.played_cards]
#             print(ranks,'ranks')
            for i in range(len(self.players[self.game_state.attacking_player].hand)):
                if self.players[self.game_state.attacking_player].hand[i][0] in ranks:
                    location = np.where(self.players[self.game_state.attacking_player].hand_1hot[i]==1)[0]
                    possibility_vec[location] = 1
        else:
            #first action, pick any card Need to locate each card in terms of the entire deck.
            #the possibility vector will be of length 36. with 1s for cards we have and 0s for the rest
#             print('first action')
            #Should just be the hand_1hot vector plus 0
            possibility_vec = np.zeros((1,53)).flatten()
            for i in range(len(self.players[self.game_state.attacking_player].hand)):
                location = np.where(self.players[self.game_state.attacking_player].hand_1hot[i]==1)[0]
                possibility_vec[location] = 1
        #inputs = (self.players[player_id].hand_1hot,self.game_state)
        #wrap all options plus game state into something to pass into model
        #if first action can play any card, else has to match
        #decision = self.funcs[self.game_state.attacking_player](possibility_vec,self.game_state,np.vstack(self.players[self.game_state.attacking_player].hand_1hot),self.players,self.game_state.attacking_player,0,self)
        decision = self.funcs[self.game_state.attacking_player](possibility_vec,self.game_state,np.vstack(self.players[self.game_state.attacking_player].hand_1hot),self.players,self.game_state.attacking_player,0,self)
#         print(decision,'attacking decision')
        if decision == 52:
            #player passed - This is redundent safety
            self.game_state.played_card = None
            self.game_state.played_card_1hot = None
        else:
            #remove card from hand add to played list
            self.remove_card(True,self.game_state.attacking_player,decision)
    
    #defender has the option to defend with any legal card, or take the card
    #Needs current played cards
    def defend(self):
        player_id = self.game_state.defending_player
        possibility_vec = np.zeros((1,53)).flatten()
        attacker_card = self.game_state.played_card
        # print(attacker_card,'attacker_card')
#         [print(card) for card in self.players[self.game_state.defending_player].hand]
#         print('defending players hand')
        #Go through hand and see if any cards can beat it
        for i in range(len(self.players[self.game_state.defending_player].hand)):
            if self.players[player_id].hand[i][0] > attacker_card[0] and self.players[player_id].hand[i][1] == attacker_card[1]            or attacker_card[1] != self.game_state.trump_suit and self.players[player_id].hand[i][1] == self.game_state.trump_suit:
                #possible defend
                location = np.where(self.players[self.game_state.defending_player].hand_1hot[i]==1)[0]
#                 print(location,'defending location')
#                 print(self.players[self.game_state.defending_player].hand[i],'possible card')
                possibility_vec[location] = 1
                i += 1
        #check any cards can defend, otherwise auto pickup
        ### Streamline this later ###
#         if 1 not in possibility_vec:
#             #can't defend, pick up the card
#             picking_up_cards()
#         else:
#             #Add ability to pick up the cards 
#             #pass possibility vec through to model, get action
        ###
        possibility_vec[52] = 1
        decision = self.funcs[self.game_state.defending_player](possibility_vec,self.game_state,np.vstack(self.players[self.game_state.defending_player].hand_1hot),self.players,self.game_state.defending_player,1,self)
#         print(decision,'defend decision')
        if decision == 52:
            self.picking_up_cards()
        else:
            #chose defend
            #remove that card from hand, add to played list
            self.remove_card(False,self.game_state.defending_player,decision)
            
    def picking_up_cards(self):
        #print('picking up cards')
        #self.print_game_state() ## PRINT STATEMENT
        #add all played cards to hand, check if opponent wants to add any more cards?
        #Check which cards are legal up to the remaining cards in defender's hand
        #self.game_state.played_cards.flatten()
        max_cards = len(self.players[self.game_state.defending_player].hand_1hot)
        
        while max_cards > 0 and len(self.players[self.game_state.attacking_player].hand) > 0:
            possibility_vec = np.zeros((1,53)).flatten()
            possibility_vec[52] = 1
#             if not self.game_state.played_cards:
#                 ranks = self.game_state.played_card[0]
           
            ranks = [card[0] for card in self.game_state.played_cards]
#             print(ranks,'ranks')
            for i in range(len(self.players[self.game_state.attacking_player].hand)):
                if self.players[self.game_state.attacking_player].hand[i][0] in ranks:
                    #get 1hot location
                    location = np.where(self.players[self.game_state.attacking_player].hand_1hot[i]==1)[0]
                    possibility_vec[location] = 1
            decision = self.funcs[self.game_state.attacking_player](possibility_vec,self.game_state,np.vstack(self.players[self.game_state.attacking_player].hand_1hot),self.players,self.game_state.attacking_player,2,self)
            if decision == 52:
                #to give more cards or not
                break
            else:
                #add card to self.game_state.played_cards
                self.remove_card(False,self.game_state.attacking_player,decision)
                max_cards -= 1
        #add cards to defender's hand
#         print(self.game_state.played_cards,'played cards')
        self.players[self.game_state.defending_player].hand = self.players[self.game_state.defending_player].hand+self.game_state.played_cards
        self.players[self.game_state.defending_player].hand_1hot = self.players[self.game_state.defending_player].hand_1hot+self.game_state.played_cards_1hot
        #clear played cards
        self.game_state.played_cards = []
        self.game_state.played_cards_1hot = []
        self.game_state.played_card = None
        self.game_state.played_card_1hot = None
        self.game_state.picked_up = True
    
    def remove_card(self,attack,player_id,decision):
        #remove card from player's hand
#         print(attack,player_id,decision,'remove_card vars')
        for i in range(len(self.players[player_id].hand)):
            if np.where(self.players[player_id].hand_1hot[i]==1) == decision:
                #add card to played cards list and played card
                if attack == True:
                    self.game_state.played_card = self.players[player_id].hand[i]
                    self.game_state.played_card_1hot = self.players[player_id].hand_1hot[i]
                    self.game_state.played_cards.append(self.game_state.played_card)
                    self.game_state.played_cards_1hot.append(self.game_state.played_card_1hot)
                    #remove card from hand
                    self.players[player_id].hand.pop(i)
                    self.players[player_id].hand_1hot.pop(i)
                else:
                    self.game_state.played_cards.append(self.players[player_id].hand[i])
                    self.game_state.played_cards_1hot.append(self.players[player_id].hand_1hot[i])
                    self.players[player_id].hand.pop(i)
                    self.players[player_id].hand_1hot.pop(i)
                break
        
    def is_round_over(self):
#         print('is round over')
        #is either player out of cards
        #can the attacker continue to play
        #has the defender picked up the cards
        #then check for whether either player needs to draw up to 6
        #check for number of defender's cards
        current_max = len(self.players[self.game_state.attacking_player].hand)
        number_of_attacks = len(self.game_state.played_cards) % 2
        if number_of_attacks == 6 or current_max == 0 or self.game_state.played_card == None:
            #round is over
            self.game_state.round_over = True
            if self.game_state.picked_up == True:
                #attacker draws
                if len(self.play_deck) > 0:
                    self.draw_cards(self.game_state.attacking_player)
                else:
                    pass
            else:
#                 print('successful defense')
                #successful defense, both draw
                self.draw_cards(self.game_state.attacking_player)
                self.draw_cards(self.game_state.defending_player)
                #update attacker and defender
                self.game_state.attacking_player = (self.game_state.attacking_player + 1) % 2
                self.game_state.defending_player = (self.game_state.defending_player + 1) % 2
                #Move played cards to discard pile
                if self.game_state.played_cards:
                    self.game_state.discard_pile.append(self.game_state.played_cards)
                    self.game_state.discard_pile_1hot.append(self.game_state.played_cards_1hot)
            self.update_game_state()
        else:
            #go to additional rounds
            pass
        
    def is_game_over(self):
        for player in self.players:
            if len(player.hand) == 0 and self.game_state.remaining_cards == 0:
                self.game_state.game_over = True
        
    def record_outcome(self):
        if len(self.players[0].hand) == 0 and len(self.players[1].hand) == 0:
            #tie
            self.players[0].outcome = 0
            self.players[1].outcome = 0
            self.game_state.previous_winner = (False,0)
        elif len(self.players[0].hand) == 0:
            self.players[0].outcome = 1
            self.players[1].outcome = -1
            self.results[0] += 1
            self.results[1] -= 1
            self.game_state.previous_winner = (True,0)
        else:
            self.players[0].outcome = -1
            self.players[1].outcome = 1
            self.results[0] -= 1
            self.results[1] += 1
            self.game_state.previous_winner = (True,1)
Exemplo n.º 13
0
def reset(event):
    sangle.reset()
    siter.reset()


button.on_clicked(reset)

rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)


def colorfunc(label):
    tree.l.set_color(label)
    fig.canvas.draw_idle()


radio.on_clicked(colorfunc)

tree = Tree()
tree.origin(ax)

tree.iterate_tree(ax)
tree.iterate_tree(ax)
tree.iterate_tree(ax)
tree.iterate_tree(ax)
tree.iterate_tree(ax)
tree.iterate_tree(ax)

plt.show()
Exemplo n.º 14
0
 def __init__(self):
     super().__init__(Database().get_getlink(), message=self.message)
     self.tree = Tree()
     self.Singleton = BotId()
     self.Singleton.set_bot("getlink", super().get_bot())
     self.Singleton.reset_key_id("getlink")
Exemplo n.º 15
0
    class Singleton(Bot):

        def __init__(self):
            self.keyboard = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="/new_bot", callback_data='n')],[InlineKeyboardButton(text="/delete_bot", callback_data='d')],[InlineKeyboardButton(text="/start", callback_data='s')],[InlineKeyboardButton(text="/change_pwd", callback_data='c')]])
            self.boolvett={}
            self.unconfirmed_bot={}
            self.unc_del={}
            self.tree=Tree()
            self.user_request=self.tree.read_pwd()
            self.admin_pwd=self.tree.get_pwd_admin()
            self.select_str="Please select a topic:"
            self.singleton_id=BotId()
            self.singleton_ban=UserBanned()
            super().__init__(Database().get_creation(),self.message,self.query)
            self.singleton_id.set_bot("creation",super().get_bot())
            self.singleton_id.reset_key_id("creation")

        def message(self,msg):
            content_type, chat_type, chat_id = telepot.glance(msg)
            if self.singleton_ban.check_ban(chat_id):
                send_message(super().get_bot(),chat_id,"You are banned from this bot","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.topic_keyboard())
                return
            if content_type == 'text' and chat_type=="private":
                if msg["text"]=='/start' or (self.singleton_id.check_time_id(chat_type,self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0 and msg["text"]=="Cancel"):
                    self.del_past_creation(chat_id)
                    send_message(super().get_bot(),chat_id,"Hi, this is the bot to create a new subject.","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
                    self.singleton_id.set_key_id(telepot.message_identifier(send_message(super().get_bot(),chat_id,"Click on a command below:","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.keyboard)),"creation")
                elif msg["text"]=='/delete_bot':
                    self.del_past_creation(chat_id)
                    self.singleton_id.add_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,4,"creation")
                    send_message(super().get_bot(),chat_id,self.select_str,"Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.topic_keyboard())
                    self.boolvett[chat_id]=False
                elif msg["text"]=='/new_bot':
                    self.del_past_creation(chat_id)
                    self.singleton_id.add_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,1,"creation")
                    send_message(super().get_bot(),chat_id,"Please select a new topic, please write the name in english:","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.topic_keyboard())
                elif msg["text"]=='/change_pwd':
                    self.del_past_creation(chat_id)
                    if not self.req_pwd(chat_id):
                        send_message(super().get_bot(),chat_id,"You made too many requests, command aborted","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.topic_keyboard())
                        return
                    self.singleton_id.add_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,4,"creation")
                    send_message(super().get_bot(),chat_id,self.select_str,"Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.topic_keyboard())
                    self.boolvett[chat_id]=True
                elif self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation") != 0:
                    self.switch_creation(chat_id,msg["text"])
                else :
                    send_message(super().get_bot(),chat_id,"Unknown command or bot restarted.","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.topic_keyboard())

        def query(self,msg):
            query_id, from_id, query_data = telepot.glance(msg, flavor="callback_query")
            chat_id=msg["message"]["chat"]["id"]
            if self.singleton_ban.check_ban(chat_id):
                send_message(super().get_bot(),chat_id,"You are banned from this bot","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
                return
            if query_data=='s':
                self.del_past_creation(chat_id)
                send_message(super().get_bot(),chat_id,"Hi, this is the bot to create a new subject.","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
                self.singleton_id.set_key_id(telepot.message_identifier(send_message(super().get_bot(),chat_id,"Click on a command below:","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.keyboard)),"creation")
            elif query_data=='n':
                self.del_past_creation(chat_id)
                self.singleton_id.add_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,1,"creation")
                send_message(super().get_bot(),chat_id,"Please select a new topic, please write the name in english:","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
            elif query_data=='d':
                self.del_past_creation(chat_id)
                self.singleton_id.add_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,4,"creation")
                send_message(super().get_bot(),chat_id,self.select_str,"Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.topic_keyboard())
                self.boolvett[chat_id]=False
            elif query_data=='c':
                self.del_past_creation(chat_id)
                if not self.req_pwd(chat_id):
                    send_message(super().get_bot(),chat_id,"You made too many requests, command aborted","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
                    return
                self.singleton_id.add_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,4,"creation")
                send_message(super().get_bot(),chat_id,self.select_str,"Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.topic_keyboard())
                self.boolvett[chat_id]=True

        def teach_board_topic(self,topic,chat_id):
            send_message(super().get_bot(),chat_id,"If you want go to a bot","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=self.tree.get_creation_keyboard(topic))

        def delete_req(self,time,vett):
            data=[]
            for elem in vett:
                if time < elem:
                    data.append(elem)
            return data

        def select_topic(self,chat_id,text):
            if not re.search("^[a-zA-Z0-9][a-zA-Z0-9 ]{3}[a-zA-Z0-9 ]*[a-zA-Z0-9]$", text):
                send_message(super().get_bot(),chat_id,"The name of the topic is not valid, it must have at least 5 characters and contain only letters, numbers and spaces. The name cannot begin or end with a space. Please retry","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
                return
            if text in self.tree.get_topic_list():
                send_message(super().get_bot(),chat_id,"The topic name has already been used. Please retry","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
                return
            self.unconfirmed_bot[chat_id]={}
            self.unconfirmed_bot[chat_id]["topic"]=text
            self.singleton_id.add_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,2,"creation")
            send_message(super().get_bot(),chat_id,"Paste the token created with the @BotFather bot:","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())

        def token_valid(self,token):
            url="https://api.telegram.org/bot"+token+"/getMe"
            #try:
            try:
                response = urlopen(url)
                data = json.loads(response.read())
                if data['ok'] and token not in self.tree.get_token_list():
                    return True
                else:
                    return False
            except HTTPError:
                return False

        def rand_string(self,string_length=10):
            password_characters = string.ascii_letters + string.digits + string.punctuation
            return ''.join(random.choice(password_characters) for _ in range(string_length))

        def hash_password(self,password):
            """Hash a password for storing."""
            salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
            pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), 
                                        salt, 100000)
            pwdhash = binascii.hexlify(pwdhash)
            return (salt + pwdhash).decode('ascii')

        def send_notify(self,chat_id,pwd,name_bot):
            bot_pwd=self.tree.get_bot_pwd()
            send_message(bot_pwd,self.admin_pwd,"The new password for the "+name_bot+" topic is "+pwd,self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0)
            send_message(super().get_bot(),chat_id,"This is the password to be enabled to answer questions: "+pwd,"Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())

        def save_token(self,chat_id,txt):
            #try:
            if self.token_valid(txt):
                self.unconfirmed_bot[chat_id]["token"]=txt
            else:
                send_message(super().get_bot(),chat_id,"The token is already used or is not valid. Retry with another token. Please retry.","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
                return
            #except telepot.exception:
                #send_message(super().get_bot(),chat_id,"The token is already used or is not valid. Retry with another token. Please retry.",reply_markup=ReplyKeyboardRemove())
                #return
            pwd=self.rand_string()
            self.singleton_id.del_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")
            self.send_notify(chat_id,pwd,self.unconfirmed_bot[chat_id]["topic"])
            self.tree.new_bot(txt,self.unconfirmed_bot[chat_id]["topic"],self.hash_password(pwd))
            self.teach_board_topic(self.unconfirmed_bot[chat_id]["topic"],chat_id)
            del self.unconfirmed_bot[chat_id]

        def cond_hash_first_branch(self,chat_id,text):
            self.singleton_id.del_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")
            if self.tree.verify_password(self.unc_del[chat_id], text):
                self.singleton_ban.del_ban(chat_id)
                pwd=self.rand_string()
                self.send_notify(chat_id,pwd,self.unc_del[chat_id])
                self.tree.change_pwd(self.unc_del[chat_id],self.hash_password(pwd))
                self.teach_board_topic(self.unc_del[chat_id],chat_id)
            else :
                self.singleton_ban.add_ban(chat_id)
                send_message(super().get_bot(),chat_id,"Incorrect password. Command aborted.","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
            del self.unc_del[chat_id]

        def cond_hash_second_branch(self,chat_id,text):
            self.singleton_id.del_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")
            if self.tree.verify_password(self.unc_del[chat_id], text):
                self.singleton_ban.del_ban(chat_id)
                self.tree.delete_bot(self.unc_del[chat_id])
                send_message(super().get_bot(),chat_id,"Topic deleted","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
            else :
                self.singleton_ban.add_ban(chat_id)
                send_message(super().get_bot(),chat_id,"Incorrect password. Command aborted.","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
            del self.unc_del[chat_id]

        def cond_hash(self,chat_id,text):
            if text=="Forgot password?":
                user=super().get_bot().getChat(chat_id)
                bot_pwd=self.tree.get_bot_pwd()
                self.singleton_id.del_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")
                send_message(bot_pwd,self.admin_pwd,"The user "+user['last_name']+" "+user['first_name']+" (@"+user['username']+") lost password for the topic "+self.unc_del[chat_id],self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0)
                send_message(super().get_bot(),chat_id,"A request was sent to the administrator","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())
                del self.unc_del[chat_id]
                return
            if self.boolvett[chat_id]:
                self.cond_hash_first_branch(chat_id,text)
            else:
                self.cond_hash_second_branch(chat_id,text)
            #self.tree.write_ban()

        def choose_topic(self,chat_id,text):
            if text in self.tree.get_topic_list():
                self.singleton_id.add_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,3,"creation")
                send_message(super().get_bot(),chat_id,"Enter the password relating to the topic:","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=create_reply_keyboard([["Forgot password?"]],only_one=False))
                self.unc_del[chat_id]=text
            else :
                self.singleton_id.del_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")
                send_message(super().get_bot(),chat_id,"Topic don't found, command aborted","Cancel",self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")!=0,reply_markup=ReplyKeyboardRemove())

        def switch_creation(self,chat_id,text):
            if self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")==1:
                self.select_topic(chat_id,text)
            elif self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")==2:
                self.save_token(chat_id,text)
            elif self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")==3:
                self.cond_hash(chat_id,text)
            elif self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")==4:
                self.choose_topic(chat_id,text)

        def req_pwd(self,chat_id):
            time=datetime.datetime.today()
            if chat_id not in self.user_request:
                self.user_request[chat_id]=[]
            self.user_request[chat_id]=self.delete_req(time,self.user_request[chat_id])
            self.user_request[chat_id].append(time+datetime.timedelta(days=30))
            self.tree.write_pwd(self.user_request)
            if len(self.user_request[chat_id]) > 10:
                return False
            return True

        def del_past_creation(self,chat_id):
            if chat_id in self.unconfirmed_bot:
                del self.unconfirmed_bot[chat_id]
            if self.singleton_id.check_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation") != 0:
                self.singleton_id.del_time_id("private",self.tree.get_lang(),"en",chat_id,chat_id,"creation")
            if chat_id in self.unc_del:
                del self.unc_del[chat_id]
Exemplo n.º 16
0
import time
from tree_class import Tree
from database_class import Database
from bot_admin_class import BotAdmin
from bot_creation_class import BotCreation
from bot_getlink_class import BotGetlink
from bot_pwd_class import BotPwd
from bot_teacher_class import BotTeacher

database=Database()
bot_admin=BotAdmin()
bot_pwd=BotPwd()
database.set_bot_pwd(bot_pwd)
database.set_bot_admin(bot_admin)
tree=Tree()
bot_creation=BotCreation()
bot_getlink=BotGetlink()
teacher=database.get_teacher()
bot_teacher=BotTeacher()
database.set_bot_teacher(bot_teacher)

print("Init complete")

while True:
    time.sleep(10)
Exemplo n.º 17
0
    class Singleton(Bot):
        def __init__(self):
            self.keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="/answer", callback_data='a')],
                [InlineKeyboardButton(text="/report", callback_data='r')],
                [InlineKeyboardButton(text="/start", callback_data='s')],
                [InlineKeyboardButton(text="/list", callback_data='l')],
                [InlineKeyboardButton(text="/free_list", callback_data='fl')],
                [InlineKeyboardButton(text="/ban", callback_data='b')],
                [InlineKeyboardButton(text="/ban_list", callback_data='bl')],
                [InlineKeyboardButton(text="/sban", callback_data='sb')],
                [InlineKeyboardButton(text="/change", callback_data='c')],
                [InlineKeyboardButton(text="/delete", callback_data='d')],
                [InlineKeyboardButton(text="/hints", callback_data='h')],
                [InlineKeyboardButton(text="/add_hint", callback_data='ah')],
                [
                    InlineKeyboardButton(text="/change_lang",
                                         callback_data='cl')
                ],
                [
                    InlineKeyboardButton(text="/change_role",
                                         callback_data='cr')
                ]
            ])
            self.tree = Tree()
            self.query_bool = {}
            self.lang_bool = {}
            self.query_bool = {}
            self.prev_lang = {}
            self.topic_name = {}
            self.is_logged = {}
            self.singleton_id = BotId()
            self.singleton_ban = UserBanned()
            super().__init__(Database().get_teacher(), self.message,
                             self.query)
            self.tree.send_notification_teacher(super().get_bot())
            self.singleton_id.set_bot("teacher", super().get_bot())
            self.singleton_id.reset_key_id("teacher")

        def condition(self, content_type, msg, chat_id, from_id, topic):
            return content_type == 'text' and self.verify_user(
                msg, chat_id, from_id, topic)

        def start_command(self, txt, chat_type, lang, from_id, chat_id):
            return match_command('/start', txt, chat_type,
                                 super().get_bot().getMe()["username"]) or (
                                     self.singleton_id.check_time_id(
                                         chat_type, self.tree.get_lang(), lang,
                                         from_id, chat_id, "teacher") != 0
                                     and self.tree.check_lang_str(txt, "canc"))

        def sub_message(self, chat_type, chat_id, from_id, topic, user, msg):
            txt = msg["text"]
            lang = self.tree.get_super_user_lang(chat_id, topic)
            if self.start_command(txt, chat_type, lang, from_id, chat_id):
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.singleton_id.start_fun(chat_id, from_id, chat_type, lang,
                                            self.tree.get_lang(), "teacher",
                                            topic, self.keyboard)
            elif match_command('/answer', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 1,
                                              "teacher")
                selection(chat_id, from_id, lang,
                          self.tree.get_res_array(topic, lang,
                                                  "FREE"), chat_type,
                          super().get_bot(), self.tree.get_lang(),
                          self.singleton_id, "teacher")
            elif match_command('/ban', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 3,
                                              "teacher")
                selection(chat_id, from_id, lang,
                          self.tree.get_res_array(topic, lang,
                                                  "FREE"), chat_type,
                          super().get_bot(), self.tree.get_lang(),
                          self.singleton_id, "teacher")
            elif match_command('/report', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 2,
                                              "teacher")
                send_message(
                    super().get_bot(), chat_id,
                    tag_group(chat_type, user) +
                    self.tree.get_string(lang, "report"),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)
            elif match_command('/list', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.list_sel(chat_id, from_id, lang,
                              self.tree.get_res_array(topic, lang, "ANSWER"),
                              chat_type)
            elif match_command('/ban_list', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.list_sel(chat_id, from_id, lang,
                              self.tree.get_res_array(topic, lang, "BANNED"),
                              chat_type)
            elif match_command('/free_list', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.list_sel(chat_id, from_id, lang,
                              self.tree.get_res_array(topic, lang, "FREE"),
                              chat_type)
            elif match_command('/sban', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 5,
                                              "teacher")
                selection(chat_id, from_id, lang,
                          self.tree.get_res_array(topic, lang,
                                                  "BANNED"), chat_type,
                          super().get_bot(), self.tree.get_lang(),
                          self.singleton_id, "teacher")
            elif match_command('/change', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 1,
                                              "teacher")
                selection(chat_id, from_id, lang,
                          self.tree.get_res_array(topic, lang,
                                                  "ANSWER"), chat_type,
                          super().get_bot(), self.tree.get_lang(),
                          self.singleton_id, "teacher")
            elif match_command('/delete', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.tree.delete_tc(chat_id, topic)
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                send_message(super().get_bot(),
                             chat_id,
                             "Permission deleted",
                             self.tree.get_string(lang, "canc"),
                             self.singleton_id.check_time_id(
                                 chat_type, self.tree.get_lang(), lang,
                                 from_id, chat_id, "teacher") != 0,
                             reply_markup=ReplyKeyboardRemove())
            elif match_command('/hints', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.hints(chat_id, from_id, topic, lang, chat_type, user)
            elif match_command('/add_hint', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.add_hints(chat_id, from_id, topic, lang, chat_type, user)
            elif match_command('/change_lang', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 7,
                                              "teacher")
                send_message(super().get_bot(),
                             chat_id,
                             tag_group(chat_type, user) +
                             self.tree.get_string(lang, "lang"),
                             self.tree.get_string(lang, "canc"),
                             self.singleton_id.check_time_id(
                                 chat_type, self.tree.get_lang(), lang,
                                 from_id, chat_id, "teacher") != 0,
                             reply_markup=self.tree.set_keyboard(
                                 ["it", "de", "en", "es", "fr"]))
            elif match_command('/change_role', txt, chat_type,
                               super().get_bot().getMe()["username"]):
                role = self.tree.change_role(chat_id, topic)
                send_message(super().get_bot(),
                             chat_id,
                             self.tree.get_string(lang, role),
                             self.tree.get_string(lang, "canc"),
                             self.singleton_id.check_time_id(
                                 chat_type, self.tree.get_lang(), lang,
                                 from_id, chat_id, "teacher") != 0,
                             reply_markup=ReplyKeyboardRemove())
                self.singleton_id.start_fun(chat_id, from_id, chat_type, lang,
                                            self.tree.get_lang(), "teacher",
                                            topic, self.keyboard)
            elif self.singleton_id.check_time_id(
                    chat_type, self.tree.get_lang(), lang, from_id, chat_id,
                    "teacher") != 0:
                self.switcher(chat_id, from_id, txt, lang, topic, chat_type)

        def message(self, msg):
            content_type, chat_type, chat_id = telepot.glance(msg)
            from_id = msg["from"]["id"]
            topic = self.tree.get_topic(chat_id)
            user = super().get_bot().getChat(from_id)
            if self.condition(content_type, msg, chat_id, from_id, topic):
                self.sub_message(chat_type, chat_id, from_id, topic, user, msg)

        def hints(self, chat_id, from_id, topic, lang, chat_type, user):
            self.tree.set_nlp(lang)
            vett = self.tree.get_hint(topic, lang)
            self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                          lang, from_id, chat_id, "teacher")
            if vett != []:
                send_message(
                    super().get_bot(), chat_id,
                    tag_group(chat_type, user) + list_to_str(vett),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)
            else:
                send_message(
                    super().get_bot(), chat_id,
                    tag_group(chat_type, user) +
                    self.tree.get_string(lang, "empty"),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)

        def add_hints(self, chat_id, from_id, topic, lang, chat_type, user):
            self.tree.set_nlp(lang)
            hints = self.tree.get_hint(topic, lang)
            if len(hints) > 0:
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 6,
                                              "teacher")
                send_message(super().get_bot(),
                             chat_id,
                             tag_group(chat_type, user) +
                             self.tree.get_string(lang, "select_hint"),
                             self.tree.get_string(lang, "canc"),
                             self.singleton_id.check_time_id(
                                 chat_type, self.tree.get_lang(), lang,
                                 from_id, chat_id, "teacher") != 0,
                             reply_markup=create_reply_keyboard(
                                 array_to_matrix(
                                     self.tree.get_hint(topic, lang))))
            else:
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                send_message(super().get_bot(),
                             chat_id,
                             tag_group(chat_type, user) +
                             self.tree.get_string(lang, "empty"),
                             self.tree.get_string(lang, "canc"),
                             self.singleton_id.check_time_id(
                                 chat_type, self.tree.get_lang(), lang,
                                 from_id, chat_id, "teacher") != 0,
                             reply_markup=create_reply_keyboard(
                                 array_to_matrix(
                                     self.tree.get_hint(topic, lang))))

        def query(self, msg):
            query_id, from_id, query_data = telepot.glance(
                msg, flavor="callback_query")
            chat_id = msg["message"]["chat"]["id"]
            chat_type = msg["message"]["chat"]["type"]
            topic = self.tree.get_topic(chat_id)
            user = super().get_bot().getChat(from_id)
            if not self.verify_user(msg, chat_id, from_id, topic):
                return
            lang = self.tree.get_super_user_lang(chat_id, topic)
            if query_data == 's':
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.singleton_id.start_fun(chat_id, from_id, chat_type, lang,
                                            self.tree.get_lang(), "teacher",
                                            topic, self.keyboard)
            elif query_data == 'a':
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 1,
                                              "teacher")
                selection(chat_id, from_id, lang,
                          self.tree.get_res_array(topic, lang,
                                                  "FREE"), chat_type,
                          super().get_bot(), self.tree.get_lang(),
                          self.singleton_id, "teacher")
            elif query_data == 'b':
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 3,
                                              "teacher")
                selection(chat_id, from_id, lang,
                          self.tree.get_res_array(topic, lang,
                                                  "FREE"), chat_type,
                          super().get_bot(), self.tree.get_lang(),
                          self.singleton_id, "teacher")
            elif query_data == 'r':
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 2,
                                              "teacher")
                send_message(
                    super().get_bot(), chat_id,
                    tag_group(chat_type, user) +
                    self.tree.get_string(lang, "report"),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)
            elif query_data == 'l':
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.list_sel(chat_id, from_id, lang,
                              self.tree.get_res_array(topic, lang, "ANSWER"),
                              chat_type)
            elif query_data == 'fl':
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.list_sel(chat_id, from_id, lang,
                              self.tree.get_res_array(topic, lang, "FREE"),
                              chat_type)
            elif query_data == 'bl':
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.list_sel(chat_id, from_id, lang,
                              self.tree.get_res_array(topic, lang, "BANNED"),
                              chat_type)
            elif query_data == 'sb':
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 5,
                                              "teacher")
                selection(chat_id, from_id, lang,
                          self.tree.get_res_array(topic, lang,
                                                  "BANNED"), chat_type,
                          super().get_bot(), self.tree.get_lang(),
                          self.singleton_id, "teacher")
            elif query_data == 'c':
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 1,
                                              "teacher")
                selection(chat_id, from_id, lang,
                          self.tree.get_res_array(topic, lang,
                                                  "ANSWER"), chat_type,
                          super().get_bot(), self.tree.get_lang(),
                          self.singleton_id, "teacher")
            elif query_data == 'd':
                self.tree.delete_tc(chat_id, topic)
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                send_message(super().get_bot(),
                             chat_id,
                             "Permission deleted",
                             self.tree.get_string(lang, "canc"),
                             self.singleton_id.check_time_id(
                                 chat_type, self.tree.get_lang(), lang,
                                 from_id, chat_id, "teacher") != 0,
                             reply_markup=ReplyKeyboardRemove())
            elif query_data == 'h':
                self.hints(chat_id, from_id, topic, lang, chat_type, user)
            elif query_data == 'ah':
                self.add_hints(chat_id, from_id, topic, lang, chat_type, user)
            elif query_data == 'cl':
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 7,
                                              "teacher")
                send_message(super().get_bot(),
                             chat_id,
                             tag_group(chat_type, user) +
                             self.tree.get_string(lang, "lang"),
                             self.tree.get_string(lang, "canc"),
                             self.singleton_id.check_time_id(
                                 chat_type, self.tree.get_lang(), lang,
                                 from_id, chat_id, "teacher") != 0,
                             reply_markup=self.tree.set_keyboard(
                                 ["it", "de", "en", "es", "fr"]))
            elif query_data == 'cr':
                role = self.tree.change_role(chat_id, topic)
                send_message(super().get_bot(),
                             chat_id,
                             self.tree.get_string(lang, role),
                             self.tree.get_string(lang, "canc"),
                             self.singleton_id.check_time_id(
                                 chat_type, self.tree.get_lang(), lang,
                                 from_id, chat_id, "teacher") != 0,
                             reply_markup=ReplyKeyboardRemove())
                self.singleton_id.start_fun(chat_id, from_id, chat_type, lang,
                                            self.tree.get_lang(), "teacher",
                                            topic, self.keyboard)

        def list_sel(self, chat_id, from_id, lang, list1, chat_type):
            user = super().get_bot().getChat(from_id)
            if list1 == []:
                send_message(
                    super().get_bot(), chat_id,
                    tag_group(chat_type, user) +
                    self.tree.get_string(lang, "empty"),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)
            else:
                reply = telepot.message_identifier(
                    send_message(
                        super().get_bot(), chat_id,
                        tag_group(chat_type, user) + "File:",
                        self.tree.get_string(lang, "canc"),
                        self.singleton_id.check_time_id(
                            chat_type, self.tree.get_lang(), lang, from_id,
                            chat_id, "teacher") != 0))[1]
                send_doc(super().get_bot(), chat_id, list_to_str(list1), reply)

        def branch_one(self, msg, chat_id, from_id):
            lang = self.prev_lang[chat_id]
            topic = self.topic_name[chat_id]
            if self.tree.check_teach(lang, msg["text"]):
                send_message(super().get_bot(),
                             chat_id,
                             self.tree.get_string(lang, "teacher"),
                             reply_markup=ReplyKeyboardRemove())
                self.tree.add_teachers([chat_id], self.topic_name[chat_id],
                                       lang)
                del self.topic_name[chat_id]
                del self.prev_lang[chat_id]
            elif self.tree.check_coll(lang, msg["text"]):
                send_message(super().get_bot(),
                             chat_id,
                             self.tree.get_string(lang, "collaborator"),
                             reply_markup=ReplyKeyboardRemove())
                self.tree.add_collaborators([chat_id],
                                            self.topic_name[chat_id], lang)
                del self.topic_name[chat_id]
                del self.prev_lang[chat_id]
            self.singleton_id.start_fun(chat_id, from_id, "private", lang,
                                        self.tree.get_lang(), "teacher", topic,
                                        self.keyboard)
            self.query_bool[chat_id] = False
            self.lang_bool[chat_id] = False

        def branch_two(self, msg, chat_id, from_id, topic):
            if msg["text"] in self.tree.get_flag_list():
                self.prev_lang[chat_id] = self.tree.switcherflag(msg["text"])
                send_message(super().get_bot(),
                             chat_id,
                             self.tree.get_string(self.prev_lang[chat_id],
                                                  "roles"),
                             reply_markup=self.tree.get_lang_board(
                                 self.prev_lang[chat_id],
                                 ["teacher", "collaborator"]))
                self.lang_bool[chat_id] = True

        def sub_branch_three(self, msg, chat_id, from_id, topic):
            if self.is_logged[chat_id]:
                if msg["text"] in self.tree.get_topic_list():
                    send_message(super().get_bot(),
                                 chat_id,
                                 "Copy/paste the password:"******"text"]
                    self.is_logged[chat_id] = False
                    return False
            else:
                if self.tree.verify_password(self.topic_name[chat_id],
                                             msg["text"]):
                    self.singleton_ban.del_ban(chat_id)
                    send_message(super().get_bot(),
                                 chat_id,
                                 "Choose a language:",
                                 reply_markup=self.tree.set_keyboard(
                                     ["it", "de", "en", "es", "fr"]))
                    self.query_bool[chat_id] = True
                    #self.tree.write_ban()
                    return False
            return True

        def branch_three(self, msg, chat_id, from_id, topic):
            if chat_id in self.is_logged:
                if self.sub_branch_three(msg, chat_id, from_id,
                                         topic) == False:
                    return False
                self.singleton_ban.add_ban(chat_id)
                send_message(super().get_bot(),
                             chat_id,
                             "Error, retry:",
                             reply_markup=ReplyKeyboardRemove())
                send_message(super().get_bot(),
                             chat_id,
                             "Please select the topic:",
                             reply_markup=self.tree.topic_keyboard())
                self.is_logged[chat_id] = True
                #self.tree.write_ban()
                if chat_id in self.topic_name:
                    del self.topic_name[chat_id]
            else:
                send_message(super().get_bot(),
                             chat_id,
                             "Please select the topic:",
                             reply_markup=self.tree.topic_keyboard())
                self.is_logged[chat_id] = True

        def verify_user(self, msg, chat_id, from_id, topic):
            if self.singleton_ban.check_ban(chat_id):
                send_message(super().get_bot(),
                             chat_id,
                             "You are banned from this bot",
                             reply_markup=ReplyKeyboardRemove())
                return False
            if chat_id not in self.lang_bool:
                self.lang_bool[chat_id] = False
            if chat_id not in self.query_bool:
                self.query_bool[chat_id] = False
            if self.lang_bool[chat_id] == True:
                self.branch_one(msg, chat_id, from_id)
                return False
            if self.query_bool[chat_id] == True:
                self.branch_two(msg, chat_id, from_id, topic)
                return False
            if topic == None:
                self.branch_three(msg, chat_id, from_id, topic)
                return False
            return True

        def case1(self, chat_id, from_id, txt, lang, topic, chat_type):
            user = super().get_bot().getChat(from_id)
            res = self.tree.get_response(txt, lang, topic)
            if res != None:
                self.tree.set_qid(chat_id, from_id, txt, topic)
                self.singleton_id.add_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id, 4,
                                              "teacher")
                send_message(
                    super().get_bot(), chat_id,
                    tag_group(chat_type, user) +
                    self.tree.get_string(lang, "answer", xxx=txt),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)
            else:
                send_message(
                    super().get_bot(), chat_id,
                    tag_group(chat_type, user) +
                    self.tree.get_string(lang, "error"),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)

        def case3(self, chat_id, from_id, txt, lang, topic, chat_type):
            user = super().get_bot().getChat(from_id)
            self.tree.set_ban(txt, lang, topic)
            vett = self.tree.get_ids_array(topic, lang, txt)
            self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                          lang, from_id, chat_id, "teacher")
            send_message(
                super().get_bot(), chat_id,
                tag_group(chat_type, user) +
                self.tree.get_string(lang, "banned_q", xxx=txt),
                self.tree.get_string(lang, "canc"),
                self.singleton_id.check_time_id(
                    chat_type, self.tree.get_lang(), lang, from_id, chat_id,
                    "teacher") != 0)
            for elem in vett:
                send_message(
                    self.tree.get_bot_by_topic(topic), elem,
                    self.tree.get_string(lang, "banned_q", xxx=txt),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)

        def case4(self, chat_id, from_id, txt, lang, topic, chat_type):
            user = super().get_bot().getChat(from_id)
            question = self.tree.set_res(chat_id, from_id, txt, lang, topic)
            if question == None:
                return
            vett = self.tree.get_ids_array(topic, lang, question)
            self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                          lang, from_id, chat_id, "teacher")
            send_message(
                super().get_bot(), chat_id,
                tag_group(chat_type, user) +
                self.tree.get_string(lang, "answer_q", xxx=question, yyy=txt),
                self.tree.get_string(lang, "canc"),
                self.singleton_id.check_time_id(
                    chat_type, self.tree.get_lang(), lang, from_id, chat_id,
                    "teacher") != 0)
            for elem in vett:
                send_message(
                    self.tree.get_bot_by_topic(topic), elem,
                    self.tree.get_string(lang,
                                         "answer_q",
                                         xxx=question,
                                         yyy=txt),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)

        def case5(self, chat_id, from_id, txt, lang, topic, chat_type):
            user = super().get_bot().getChat(from_id)
            self.tree.set_sban(txt, lang, topic)
            vett = self.tree.get_ids_array(topic, lang, txt)
            self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                          lang, from_id, chat_id)
            send_message(
                super().get_bot(), chat_id,
                tag_group(chat_type, user) + self.tree.get_string(
                    lang, "banned_q", xxx=txt).replace("ban", "sban"),
                self.tree.get_string(lang, "canc"),
                self.singleton_id.check_time_id(
                    chat_type, self.tree.get_lang(), lang, from_id, chat_id,
                    "teacher") != 0)
            for elem in vett:
                send_message(
                    self.tree.get_bot_by_topic(topic), elem,
                    self.tree.get_string(lang, "banned_q",
                                         xxx=txt).replace("ban", "sban"))

        def case6(self, chat_id, from_id, txt, lang, topic, chat_type):
            user = super().get_bot().getChat(from_id)
            splitted = txt[1:-1].split("\" -> \"")
            self.tree.add_question_by_hint(lang, splitted[0], splitted[1],
                                           chat_id, from_id, topic)
            self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                          lang, from_id, chat_id, "teacher")
            send_message(
                super().get_bot(), chat_id,
                tag_group(chat_type, user) + self.tree.get_string(
                    lang, "answer_q", xxx=splitted[0], yyy=splitted[1]),
                self.tree.get_string(lang, "canc"),
                self.singleton_id.check_time_id(
                    chat_type, self.tree.get_lang(), lang, from_id, chat_id,
                    "teacher") != 0)

        def case7(self, chat_id, from_id, txt, lang, topic, chat_type):
            user = super().get_bot().getChat(from_id)
            txt = self.tree.switcherflag(txt)
            if txt == None:
                send_message(
                    super().get_bot(), chat_id,
                    tag_group(chat_type, user) +
                    self.tree.get_string(lang, "error"),
                    self.tree.get_string(lang, "canc"),
                    self.singleton_id.check_time_id(
                        chat_type, self.tree.get_lang(), lang, from_id,
                        chat_id, "teacher") != 0)
                return
            self.tree.set_super_user_lang(chat_id, topic, txt)
            send_message(
                super().get_bot(), chat_id,
                tag_group(chat_type, user) +
                self.tree.get_string(txt, "setted_lang"),
                self.tree.get_string(lang, "canc"),
                self.singleton_id.check_time_id(
                    chat_type, self.tree.get_lang(), lang, from_id, chat_id,
                    "teacher") != 0)
            self.singleton_id.start_fun(chat_id, from_id, chat_type, txt,
                                        self.tree.get_lang(), "teacher", topic,
                                        self.keyboard)

        def get_bot(self):
            return super().get_bot()

        def switcher(self, chat_id, from_id, txt, lang, topic, chat_type):
            self.tree.set_nlp(lang)
            if self.singleton_id.check_time_id(chat_type, self.tree.get_lang(),
                                               lang, from_id, chat_id,
                                               "teacher") == 1:
                self.case1(chat_id, from_id, txt, lang, topic, chat_type)
            elif self.singleton_id.check_time_id(chat_type,
                                                 self.tree.get_lang(), lang,
                                                 from_id, chat_id,
                                                 "teacher") == 2:
                chat = {"chat": chat_id, "from": from_id}
                bot = {"bot": super().get_bot(), "type": "teachers"}
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                seg_bug(chat, txt, lang, chat_type, bot,
                        self.tree.get_database(), self.tree.get_lang())
            elif self.singleton_id.check_time_id(chat_type,
                                                 self.tree.get_lang(), lang,
                                                 from_id, chat_id,
                                                 "teacher") == 3:
                self.case3(chat_id, from_id, txt, lang, topic, chat_type)
            elif self.singleton_id.check_time_id(chat_type,
                                                 self.tree.get_lang(), lang,
                                                 from_id, chat_id,
                                                 "teacher") == 4:
                self.case4(chat_id, from_id, txt, lang, topic, chat_type)
            elif self.singleton_id.check_time_id(chat_type,
                                                 self.tree.get_lang(), lang,
                                                 from_id, chat_id,
                                                 "teacher") == 5:
                self.case5(chat_id, from_id, txt, lang, topic, chat_type)
            elif self.singleton_id.check_time_id(chat_type,
                                                 self.tree.get_lang(), lang,
                                                 from_id, chat_id,
                                                 "teacher") == 6:
                self.case6(chat_id, from_id, txt, lang, topic, chat_type)
            elif self.singleton_id.check_time_id(chat_type,
                                                 self.tree.get_lang(), lang,
                                                 from_id, chat_id,
                                                 "teacher") == 7:
                self.singleton_id.del_time_id(chat_type, self.tree.get_lang(),
                                              lang, from_id, chat_id,
                                              "teacher")
                self.case7(chat_id, from_id, txt, lang, topic, chat_type)