Exemplo n.º 1
0
def command_anarquia(update: Update, context: CallbackContext):
    bot = context.bot
    try:
        #Send message of executing command
        cid = update.message.chat_id
        #Check if there is a current game
        game = get_game(cid)

        if game:
            uid = update.message.from_user.id
            if uid in game.playerlist:
                # Se pregunta a los jugadores si irian a anarquia,
                # esto se hace para no tener que estar pasando 3 formular y esperar que todos voten
                # SI, mitad + 1 de jugadores decide ir por anarquia.
                # Se hace y se indica quienes quisieron ir a anarquia
                MainController.decide_anarquia(bot, game)
            else:
                bot.send_message(
                    cid,
                    "Debes ser un jugador del partido para preguntar por anarquia."
                )

        else:
            bot.send_message(
                cid,
                "No hay juego en este chat. Crea un nuevo juego con /newgame")
    except Exception as e:
        bot.send_message(cid, str(e))
        log.error("Unknown error: " + str(e))
Exemplo n.º 2
0
def command_startgame(bot, update):
    log.info('command_startgame called')
    groupName = update.message.chat.title
    cid = update.message.chat_id
    game = get_game(cid)
    if not game:
        bot.send_message(
            cid,
            "There is no game in this chat. Create a new game with /newgame")
    #elif game.board:
    #	bot.send_message(cid, "The game is already running!")
    elif update.message.from_user.id not in ADMIN and update.message.from_user.id != game.initiator and bot.getChatMember(
            cid, update.message.from_user.id).status not in ("administrator",
                                                             "creator"):
        bot.send_message(
            game.cid,
            "Solo el creador del juego o un admin puede iniciar con /startgame"
        )
    elif game.board:
        bot.send_message(cid, "El juego ya empezo!")

    else:

        # Verifico si la configuracion ha terminado y se han unido los jugadores necesarios
        min_jugadores = MODULOS_DISPONIBES[game.tipo][
            game.modo]["min_jugadores"]

        if len(game.playerlist) >= min_jugadores:
            save(bot, game.cid)
            MainController.init_game(bot, game)
        else:
            bot.send_message(
                game.cid, "Falta el numero mínimo de jugadores. Faltan: %s " %
                (str(min_jugadores - len(game.playerlist))))
Exemplo n.º 3
0
def DEL_command_calltokill(bot, update):
    try:
        #Send message of executing command
        cid = update.message.chat_id
        #bot.send_message(cid, "Looking for history...")
        #Check if there is a current game
        if cid in GamesController.games.keys():
            game = GamesController.games.get(cid, None)
            if not game.dateinitvote:
                # If date of init vote is null, then the voting didnt start
                bot.send_message(cid, "The voting didn't start yet.")
            else:
                #If there is a time, compare it and send history of votes.
                start = game.dateinitvote
                stop = datetime.datetime.now()
                elapsed = stop - start
                if elapsed > datetime.timedelta(minutes=1):
                    # Only remember to vote to players that are still in the game
                    for player in game.player_sequence:
                        # If the player is not in last_votes send him reminder
                        if player.uid in game.board.state.last_votes:
                            MainController.choose_kill(bot, update, player.uid)
                else:
                    bot.send_message(cid,
                                     "10 minutes must pass to kill lazies")
        else:
            bot.send_message(
                cid,
                "There is no game in this chat. Create a new game with /newgame"
            )
    except Exception as e:
        bot.send_message(cid, str(e))
Exemplo n.º 4
0
def command_retry(bot, update):
    log.info('command_retry called')
    cid = update.message.chat_id
    user = update.message.from_user
    if cid in GamesController.games.keys():
        game = GamesController.games[cid]
        if game.last_action['depth'] == 0:
            bot.send_message(game.cid,
                             "There was no repeatable action executed yet!")
        else:
            status = bot.getChatMember(cid, user.id).status
            if user.id == game.initiator or status in ("administrator",
                                                       "creator"):
                bot.send_message(game.cid, (
                    "Attempt to repeat one of the 3 last actions was initiated by %s. The game will be reset to that action's state, please wait.\n"
                    "%s, please go to our private chat and choose an action to retry."
                ) % (user.first_name, user.first_name))
                MainController.retry_last_command(bot, game, user.id)
            else:
                bot.send_message(
                    cid,
                    "Only the initiator of the game or a group admin can reset the game's last action with /retry"
                )
    else:
        bot.send_message(
            cid,
            "There is no game in this chat. Create a new game with /newgame")
Exemplo n.º 5
0
    def create_button_clicked(self):

        alert = QMessageBox()
        alert.setText("Account created successfully.")
        alert.exec_()

        student_info.append(self.firstName_Text.text())
        student_info.append(self.lastName_Text.text())
        student_info.append(self.studentID_Text.text())
        student_info.append(self.comboBox_course.currentText())

        with open("/home/pi/Desktop/ProfMate/student_info.txt",
                  'w+') as filehandler:
            for listitem in student_info:
                filehandler.write('%s\n' % listitem)
            filehandler.close()
        # *******************Modified*************************

        try:
            MainController.registration_controller()
        except Exception as e:

            log('Reason: ', e)

        print('Finished')
Exemplo n.º 6
0
def command_nein(bot, update):	
	uid = update.message.from_user.id
	if uid == ADMIN:
		cid = update.message.chat_id
		game = GamesController.games.get(cid, None)
		answer = "Nein"
		for uid in game.playerlist:
			game.board.state.last_votes[uid] = answer
		MainController.count_votes(bot, game)
Exemplo n.º 7
0
def command_nein(update: Update, context: CallbackContext):
	bot = context.bot	
	uid = update.message.from_user.id
	if uid == ADMIN:
		cid = update.message.chat_id
		game = get_game(cid)
		answer = "Nein"
		for uid in game.playerlist:
			game.board.state.last_votes[uid] = answer
		MainController.count_votes(bot, game)
Exemplo n.º 8
0
def command_cancelgame(bot, update):
    log.info('command_cancelgame called')
    cid = update.message.chat_id
    if cid in GamesController.games.keys():
        game = GamesController.games[cid]
        status = bot.getChatMember(cid, update.message.from_user.id).status
        if update.message.from_user.id == game.initiator or status in ("administrator", "creator"):
            MainController.end_game(bot, game, 99)
        else:
            bot.send_message(cid, "Only the initiator of the game or a group admin can cancel the game with /cancelgame")
    else:
        bot.send_message(cid, "There is no game in this chat. Create a new game with /newgame")
Exemplo n.º 9
0
def command_cancelarjogo(bot, update):
    log.info('command_cancelgame called')
    cid = update.message.chat_id
    if cid in GamesController.games.keys():
        game = GamesController.games[cid]
        status = bot.getChatMember(cid, update.message.from_user.id).status
        if update.message.from_user.id == game.initiator or status in ("administrator", "creator"):
            MainController.end_game(bot, game, 99)
        else:
            bot.send_message(cid, "Só quem começou o jogo ou o admin do grupo podem cancelar o jogo com /cancelgame, o resto é golpe")
    else:
        bot.send_message(cid, "Não há nenhum jogo neste chat. Crie um novo jogo com /novojogo")
Exemplo n.º 10
0
def command_cancelgame(bot, update):
	log.info('command_cancelgame called')
	cid = update.message.chat_id	
	#Always try to delete in DB
	delete_game(cid)
	if cid in GamesController.games.keys():
		game = GamesController.games[cid]
		status = bot.getChatMember(cid, update.message.from_user.id).status
		if update.message.from_user.id == game.initiator or status in ("administrator", "creator"):
			MainController.end_game(bot, game, 99)
		else:
			bot.send_message(cid, "Solo el creador del juego o el adminsitrador del grupo pueden cancelar el juego con /cancelgame")
	else:
		bot.send_message(cid, "No hay juego en este chat. Crea un nuevo juego con /newgame")
Exemplo n.º 11
0
def command_spectate(bot, update):
    log.info('command_spectate called')
    cid = update.message.chat_id
    if cid in GamesController.games.keys():
        game = GamesController.games[cid]
        if game.board:
            uid = update.message.from_user.id
            fname = update.message.from_user.first_name
            if uid in game.playerlist and not game.playerlist[uid].is_dead:
                bot.send_message(cid, "No cheating, %s!" % fname)
            elif uid in game.spectators:
                bot.send_message(
                    cid,
                    "You're already a spectator, %s. Wait for new actions" %
                    fname)
            else:
                bot.send_message(uid, MainController.join_spectate(game, uid))
        else:
            bot.send_message(
                cid,
                "There is no running game in this chat. Please start the game with /startgame or /startrebalanced"
            )
    else:
        bot.send_message(
            cid,
            "There is no game in this chat. Create a new game with /newgame")
Exemplo n.º 12
0
def command_info(update: Update, context: CallbackContext):
	bot = context.bot
	cid, uid, groupType = update.message.chat_id, update.message.from_user.id, update.message.chat.type
	
	if groupType not in ['group', 'supergroup']:
		# En caso de no estar en un grupo y en privado con el bot muestro todos los juegos donde esta el jugador.
		# Independeinte de si pide todos, tengo que obtenerlos a todos para preguntarle cualquier quiere tener info
		all_games_unfiltered = MainController.getGamesByTipo("Todos")	
		# Me improtan los juegos que; Este el jugador, hayan sido iniciados, datinivote no sea null y que cumpla reglas del tipo de juego en particular
		all_games = {key: "{}: {}".format(game.groupName, game.tipo) for key, game in all_games_unfiltered.items() if uid in game.playerlist and game.board != None }
		msg = "Elija el juego para obtener /info en privado"
		simple_choose_buttons(bot, cid, uid, uid, "chooseGameInfo", msg, all_games)
	else:
		groupName = update.message.chat.title
		game = get_game(cid)
		if game:
			if uid in game.playerlist:								
				player = game.playerlist[uid]
				msg = "--- *Info del grupo {}* ---\n".format(groupName)
				msg += player.get_private_info(game)
				bot.send_message(uid, msg, ParseMode.MARKDOWN)				
			else:
				bot.send_message(cid, "Debes ser un jugador del partido para obtener informacion.")
		else:
			bot.send_message(cid, "No hay juego creado en este chat")
Exemplo n.º 13
0
def command_change_stats(update: Update, context: CallbackContext):
	bot = context.bot
	args = context.args
	cid, uid = update.message.chat_id, update.message.from_user.id
	
	if len(args) > 1:
		stat_name = args[0].replace('_', ' ')
		amount = int(args[1])
	else:
		stat_name = "Partidas Jugadas"
		amount = 6
	try:
		MainController.change_stats(uid, "SecretHitler", stat_name, amount)
		bot.send_message(cid, "Stats actualizados")
	except Exception as e:
		bot.send_message(cid, 'No se ejecuto el comando debido a: '+str(e))
Exemplo n.º 14
0
def command_myturn(bot, update, args):
    uid = update.message.from_user.id
    cid = update.message.chat_id

    # Independeinte de si pide todos, tengo que obtenerlos a todos para saber cual es el de menos tiempo.
    all_games_unfiltered = MainController.getGamesByTipo("Todos")
    # Me improtan los juegos que; Este el jugador, hayan sido iniciados, datinivote no sea null y que cumpla reglas del tipo de juego en particular
    all_games = {
        key: game
        for key, game in all_games_unfiltered.items() if uid in game.playerlist
        and game.board != None and verify_my_turn(game, uid)
    }

    # Le recuerdo solo el juego que mas tiempo lo viene esperando
    #chat_id = min(all_games, key=lambda key: all_games[key].dateinitvote)
    try:
        chat_id = min(all_games,
                      key=lambda key: datetime.datetime.now() if all_games[key]
                      .dateinitvote == None else all_games[key].dateinitvote)
        game_pendiente = all_games[chat_id]
        bot.send_message(uid, myturn_message(bot, game_pendiente, uid),
                         ParseMode.MARKDOWN)
    except Exception as e:
        bot.send_message(uid, "*NO* tienes partidos pendientes",
                         ParseMode.MARKDOWN)
Exemplo n.º 15
0
def main():
    root = Tk()
    controller = MainController(root)
    
    #make the window not resizable
    root.resizable(width = False, height = False)
    
    root.mainloop()
Exemplo n.º 16
0
def command_cancelgame(update: Update, context: CallbackContext):
	bot = context.bot
	log.info('command_cancelgame called')
	cid = update.message.chat_id	
	#Always try to delete in DB
	
	game = get_game(cid)
	
	#delete_game(cid)
	if game:		
		status = bot.getChatMember(cid, update.message.from_user.id).status
		if update.message.from_user.id == game.initiator or status in ("administrator", "creator"):
			MainController.end_game(bot, game, 99)
		else:
			bot.send_message(cid, "Yalnızca bu oyunu kuran kişi (veya yönetici) /oyuniptal ile oyunu iptal edebilir")
	else:
		bot.send_message(cid, "Bu odada henüz bir oyun kurulmamış, lütfen /yenioyun ile bir oyun açın")
Exemplo n.º 17
0
def command_calltopunish(bot, update):
    log.info('command_calltopunish called')
    try:
        cid = update.message.chat_id
        if cid in GamesController.games.keys():
            game = GamesController.games.get(cid, None)
            if not game.dateinitvote:
                # If date of init vote is null, then the voting didnt start
                bot.send_message(cid, "The voting didn't start yet.")
            else:
                # If there is a time, compare it and start punishment voting
                start = game.dateinitvote
                stop = datetime.datetime.now()
                elapsed = stop - start
                if elapsed < datetime.timedelta(hours=1):
                    bot.send_message(
                        cid, "One hour must pass to punish inactive voters")
                elif game.board.state.punish_players:
                    voters_text = "There's already a punish vote going.\n"
                    # list the people that still need to vote for punishment to pass
                    for p_uid in game.board.state.punish_players:
                        voters_text += "Votes for punishing %s:\n" % game.playerlist[
                            p_uid].name
                        for uid in game.board.state.punish_players[p_uid]:
                            vote = game.board.state.punish_players[p_uid][uid]
                            if vote == "Ja" or vote == "Nein":
                                voters_text += "  %s registered a vote!\n" % game.playerlist[
                                    uid].name
                            else:
                                voters_text += "  %s didn't register a vote\n" % game.playerlist[
                                    uid].name
                    bot.send_message(cid, voters_text)
                else:
                    MainController.vote_punish(bot, game)
                    bot.send_message(
                        cid,
                        "A vote to punish inactive voter(s) was initiated.")
        else:
            bot.send_message(
                cid,
                "There is no game in this chat. Create a new game with /newgame"
            )
    except Exception as e:
        log.error("command_calltopunish error: " + str(e))
Exemplo n.º 18
0
def command_show_stats(update: Update, context: CallbackContext):
	bot = context.bot
	args = context.args
	cid, uid = update.message.chat_id, update.message.from_user.id
	user_stats = MainController.load_player_stats(uid)
	if user_stats:
		jsonStr = jsonpickle.encode(user_stats)
		jsonbeuty = json.loads(jsonStr)		
		bot.send_message(cid, json.dumps(jsonbeuty, sort_keys=True, indent=4))
	else:
		bot.send_message(cid, "El usuario no tiene stats")
Exemplo n.º 19
0
def command_comecarjogo(bot, update):
    log.info('command_startgame called')
    cid = update.message.chat_id
    game = GamesController.games.get(cid, None)
    if not game:
        bot.send_message(cid, "Não há nenhum jogo neste chat. Crie um novo jogo com /novojogo")
    elif game.board:
        bot.send_message(cid, "O jogo já começou!")
    elif update.message.from_user.id != game.initiator and bot.getChatMember(cid, update.message.from_user.id).status not in ("administrator", "creator"):
            bot.send_message(cid, "Só quem começou o jogo ou o admin do grupo podem comecar o jogo com /comecarjogo, o resto é golpe")
    elif len(game.playerlist) < 5:
        bot.send_message(game.cid, "Não têm jogadores o suficiente na partida (min. 5, máx. 10). Entre no jogo com /participar")
    else:
        player_number = len(game.playerlist)
        MainController.inform_players(bot, game, game.cid, player_number)
        MainController.inform_fascists(bot, game, player_number)
        game.board = Board(player_number, game)
        log.info(game.board)
        log.info("len(games) Command_startgame: " + str(len(GamesController.games)))
        game.shuffle_player_sequence()
        game.board.state.player_counter = 0
        bot.send_message(game.cid, game.board.print_board())
        #group_name = update.message.chat.title
        #bot.send_message(ADMIN, "Game of Secret Hitler started in group %s (%d)" % (group_name, cid))
        MainController.start_round(bot, game)
Exemplo n.º 20
0
def command_startgame(bot, update):
	log.info('command_startgame called')
	groupName = update.message.chat.title
	cid = update.message.chat_id
	game = GamesController.games.get(cid, None)
	if not game:
		bot.send_message(cid, "No hay juego en este chat. Crea un nuevo juego con /newgame")
	elif game.board:
		bot.send_message(cid, "El juego ya ha comenzado!")
	elif update.message.from_user.id != game.initiator and bot.getChatMember(cid, update.message.from_user.id).status not in ("administrator", "creator"):
		bot.send_message(game.cid, "Solo el creador del juego or el admisnitrador del grupo pueden comenzar el juego con /startgame")
	elif len(game.playerlist) < 5:
		bot.send_message(game.cid, "No hay suficientes jugadores (min. 5, max. 10). Uneté al juego con /join")
	else:
		player_number = len(game.playerlist)
		MainController.inform_players(bot, game, game.cid, player_number)
		MainController.inform_fascists(bot, game, player_number)
		game.board = Board(player_number, game)
		log.info(game.board)
		log.info("len(games) Command_startgame: " + str(len(GamesController.games)))
		game.shuffle_player_sequence()
		game.board.state.player_counter = 0
		#print_board(bot, game, cid)
		#group_name = update.message.chat.title
		#bot.send_message(ADMIN, "Game of Secret Hitler started in group %s (%d)" % (group_name, cid))		
		MainController.start_round(bot, game)
Exemplo n.º 21
0
def command_startgame(bot, update):
    log.info('command_startgame called')
    cid = update.message.chat_id
    game = GamesController.games.get(cid, None)
    if not game:
        bot.send_message(cid, "There is no game in this chat. Create a new game with /newgame")
    elif game.board:
        bot.send_message(cid, "The game is already running!")
    elif update.message.from_user.id != game.initiator and bot.getChatMember(cid, update.message.from_user.id).status not in ("administrator", "creator"):
        bot.send_message(game.cid, "Only the initiator of the game or a group admin can start the game with /startgame")
    elif len(game.playerlist) < 5:
        bot.send_message(game.cid, "There are not enough players (min. 5, max. 10). Join the game with /join")
    else:
        player_number = len(game.playerlist)
        MainController.inform_players(bot, game, game.cid, player_number)
        MainController.inform_fascists(bot, game, player_number)
        game.board = Board(player_number, game)
        log.info(game.board)
        log.info("len(games) Command_startgame: " + str(len(GamesController.games)))
        game.shuffle_player_sequence()
        game.board.state.player_counter = 0
        bot.send_message(game.cid, game.board.print_board())
        #group_name = update.message.chat.title
        #bot.send_message(ADMIN, "Game of Secret Hitler started in group %s (%d)" % (group_name, cid))
        MainController.start_round(bot, game)
Exemplo n.º 22
0
def command_reloadgame(bot, update):  
	cid = update.message.chat_id
		
	try:
		game = GamesController.games.get(cid, None)
		groupType = update.message.chat.type
		if groupType not in ['group', 'supergroup']:
			bot.send_message(cid, "Tienes que agregarme a un grupo primero y escribir /reloadgame allá!")		
		else:			
			#Search game in DB
			game = load_game(cid)			
			if game:
				GamesController.games[cid] = game
				bot.send_message(cid, "Hay un juego comenzado en este chat. Si quieres terminarlo escribe /cancelgame!")				
				
				if not game.board:
					return
				
				# Ask the president to choose a chancellor								
				if game.board.state.nominated_chancellor:
					if len(game.board.state.last_votes) == len(game.player_sequence):
						print_board(bot, game, cid)
						MainController.count_votes(bot, game)
					else:
						print_board(bot, game, cid)
						MainController.vote(bot, game)
						bot.send_message(cid, "Hay una votación en progreso utiliza /calltovote para decirles a los otros jugadores. ")
				else:
					MainController.start_round(bot, game)
			else:				
				bot.send_message(cid, "No hay juego que recargar! Crea un nuevo juego con /newgame!")
			
			
	except Exception as e:
		bot.send_message(cid, str(e))
Exemplo n.º 23
0
def command_startgame(update: Update, context: CallbackContext):
	bot = context.bot
	args = context.args
	log.info('command_startgame called')
	groupName = update.message.chat.title
	cid = update.message.chat_id
	game = get_game(cid)
	if not game:
		bot.send_message(cid, "Bu odada henüz bir oyun kurulmamış, lütfen /yenioyun ile bir oyun açın")
	elif game.board:
		bot.send_message(cid, "Oyun çoktan başladı!")
	elif update.message.from_user.id != game.initiator and bot.getChatMember(cid, update.message.from_user.id).status not in ("administrator", "creator"):
		bot.send_message(game.cid, "Yalnızca bu oyunu kuran kişi (veya yönetici) /oyunubaslat ile oyunu başlatabilir")
	elif len(game.playerlist) < 5:
		bot.send_message(game.cid, "Yeterli sayıda oyuncu yok (min. 5, max. 10). Oyuna /katil ile katılabilirsiniz.")
	else:
		player_number = len(game.playerlist)
		MainController.inform_players(bot, game, game.cid, player_number)
		MainController.inform_fascists(bot, game, player_number)
		game.board = Board(player_number, game)
		log.info(game.board)
		log.info("len(games) Command_startgame: " + str(len(GamesController.games)))
		game.shuffle_player_sequence()
		game.board.state.player_counter = 0
		#print_board(bot, game, cid)
		#group_name = update.message.chat.title
		#bot.send_message(ADMIN, "Game of Secret Hitler started in group %s (%d)" % (group_name, cid))		
		MainController.start_round(bot, game)
Exemplo n.º 24
0
def command_cancelgame(update: Update, context: CallbackContext):
    bot = context.bot
    log.info('command_cancelgame called')
    cid = update.message.chat_id
    #Always try to delete in DB

    game = get_game(cid)

    #delete_game(cid)
    if game:
        status = bot.getChatMember(cid, update.message.from_user.id).status
        if update.message.from_user.id == game.initiator or status in (
                "administrator", "creator"):
            MainController.end_game(bot, game, 99)
        else:
            bot.send_message(
                cid,
                "Solo el creador del juego o el administrador del grupo pueden cancelar el juego con /cancelgame"
            )
    else:
        bot.send_message(
            cid, "No hay juego en este chat. Crea un nuevo juego con /newgame")
Exemplo n.º 25
0
def command_startgame(bot, update, rebalance=False):
    log.info('command_startgame called')
    log.info(bot)
    log.info(update)
    cid = update.message.chat_id
    game = GamesController.games.get(cid, None)
    if not game:
        bot.send_message(
            cid,
            "There is no game in this chat. Create a new game with /newgame")
    elif game.board:
        bot.send_message(cid, "The game is already running!")
    elif update.message.from_user.id != game.initiator and bot.getChatMember(
            cid, update.message.from_user.id).status not in ("administrator",
                                                             "creator"):
        bot.send_message(
            game.cid,
            "Only the initiator of the game or a group admin can start the game with /startgame or /startrebalanced"
        )
    elif len(game.playerlist) < 5:
        bot.send_message(
            game.cid,
            "There are not enough players (min. 5, max. 10). Join the game with /join"
        )
    else:
        player_number = len(game.playerlist)
        MainController.inform_players(bot, game, game.cid, player_number)
        MainController.inform_fascists(bot, game, player_number)
        if rebalance and len(game.playerlist) == 6:
            bot.send_message(
                cid,
                "Game started in rebalanced mode. One F will be played at the start to help the poor helpless fascists."
            )
            game.board = Board(player_number, game)
            game.board.state.player_claims.append(
                ['F elected at start of game'])
            game.board.state.fascist_track += 1
        elif rebalance and len(game.playerlist) in [7, 9]:
            removeF = 1 if len(game.playerlist) == 7 else 2
            label = "policy" if removeF == 1 else "policies"
            bot.send_message(
                cid,
                "Game started in rebalanced mode. %d F %s will be removed from the deck for this game, so the liberals at least have a chancce now."
                % (removeF, label))
            game.board = Board(player_number, game, removeF)
            game.board.state.player_claims.append(
                ["%d F %s removed from deck" % (removeF, label)])
        else:
            game.board = Board(player_number, game)
        log.info(game.board)
        log.info("len(games) Command_startgame: " +
                 str(len(GamesController.games)))
        game.shuffle_player_sequence()
        game.board.state.player_counter = 0
        bot.send_message(game.cid, game.board.print_board())
        #group_name = update.message.chat.title
        #bot.send_message(ADMIN, "Game of Secret Hitler started in group %s (%d)" % (group_name, cid))
        MainController.start_round(bot, game)
Exemplo n.º 26
0
def GenerateAnswer(x, y):

    if (CalcType == 1):
        print(x, "+", y)
        xy = x + y
    elif (CalcType == 2):
        print(x, "-", y)
        xy = x - y

    inputAnswer = input("Qual é resposta: ")

    if (inputAnswer == "sair" or inputAnswer == "exit"):
        MainController.ResetValuesAtStart()
    else:
        CheckAnswer(inputAnswer, xy)
Exemplo n.º 27
0
def command_myturns(bot, update):
    uid = update.message.from_user.id
    cid = update.message.chat_id

    # Independeinte de si pide todos, tengo que obtenerlos a todos para saber cual es el de menos tiempo.
    all_games_unfiltered = MainController.getGamesByTipo("Todos")
    # Me improtan los juegos que; Este el jugador, hayan sido iniciados, datinivote no sea null y que cumpla reglas del tipo de juego en particular
    all_games = {
        key: game
        for key, game in all_games_unfiltered.items() if uid in game.playerlist
        and game.board != None and verify_my_turn(game, uid)
    }
    for game_chat_id, game in all_games.items():
        bot.send_message(uid, myturn_message(bot, game, uid),
                         ParseMode.MARKDOWN)
    if len(all_games) == 0:
        bot.send_message(uid, "*NO* tienes partidos pendientes",
                         ParseMode.MARKDOWN)
def run(userId):
    # url = get_url_config()
    mac_address = get_mac_address()
    mac_address = mac_address.upper()
    print(mac_address, '===============')
    # mac_address = '00:0C:29:21:5C:D9'
    params = {'userid': userId, 'mac_address': mac_address}
    r = requests.get(url='https://erp.suffescom.com/modules/access/api',
                     params=params)
    json = r.json()

    try:
        result = MainController.action_controller(json)
        if result is None or result == "image_search_complete":
            result = "Finished"
        elif result == "image_search_complete_not_found":
            result = "Please don't touch mouse/keyboard when app is running"
        return result
    except Exception as e:
        return e
Exemplo n.º 29
0
def command_pick(bot, update, args):
    try:
        log.info('command_pick called')
        #Send message of executing command
        cid = update.message.chat_id
        uid = update.message.from_user.id
        game = Commands.get_game(cid)
        games_tipo = MainController.getGamesByTipo('SayAnything')

        elegido = -1 if check_invalid_pick(args) else args[0]

        btns, cid = get_choose_game_buttons(
            games_tipo,
            uid,
            allow_only="active_player",
            restrict="",
            fase_actual='Adivinando',
            button_value=elegido,
            callback_command='choosegamepickSA')
        if len(btns) != 0:
            if len(btns) == 0:
                #Si es solo 1 juego lo hago automatico
                game = Commands.get_game(cid)
                pick_resp(bot, game, uid, elegido)
            else:
                txtBoton = "Cancel"
                datos = "-1*choosegameclue*" + "prop" + "*" + str(uid)
                btns.append(
                    [InlineKeyboardButton(txtBoton, callback_data=datos)])
                btnMarkup = InlineKeyboardMarkup(btns)
                bot.send_message(
                    uid,
                    "¿En cual de estos grupos queres elegir respuesta?",
                    reply_markup=btnMarkup)
        else:
            mensaje_error = "No hay partidas en las que puedas hacer /resp"
            bot.send_message(uid, mensaje_error)

    except Exception as e:
        bot.send_message(uid, str(e))
        log.error("Unknown error: " + str(e))
Exemplo n.º 30
0
def command_propose(bot, update, args, user_data):
    try:
        cid = update.message.chat_id
        uid = update.message.from_user.id
        if len(args) > 0:
            # Obtengo todos los juegos de base de datos de los que usan clue
            mensaje_error = ""
            games_tipo = MainController.getGamesByTipo('SayAnything')
            btns, cid = get_choose_game_buttons(
                games_tipo,
                uid,
                allow_only="",
                restrict="active_player",
                fase_actual='Proponiendo Pistas',
                button_value='prop',
                callback_command='choosegamepropSA')
            user_data[uid] = ' '.join(args)

            if len(btns) != 0:
                if len(btns) == 1:
                    #Si es solo 1 juego lo hago automatico
                    game = Commands.get_game(cid)
                    add_propose(bot, game, uid, ' '.join(args))
                else:
                    txtBoton = "Cancel"
                    datos = "-1*choosegameclue*" + "prop" + "*" + str(uid)
                    btns.append(
                        [InlineKeyboardButton(txtBoton, callback_data=datos)])
                    btnMarkup = InlineKeyboardMarkup(btns)
                    bot.send_message(
                        uid,
                        "En cual de estos grupos queres mandar la pista?",
                        reply_markup=btnMarkup)
            else:
                mensaje_error = "No hay partidas en las que puedas hacer /resp"
                bot.send_message(uid, mensaje_error)
    except Exception as e:
        bot.send_message(uid, str(e))
        log.error("Unknown error: " + str(e))