Exemplo n.º 1
0
def banish_user(update, context):
    """
    Function that executes from the /banish command. Adds specified user to the block list if not already blocked.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #if invalid user, the validate_user function will prompt to register with /war command
    if um.validate_user(update, context, update.message.chat_id, update.message.from_user.username) is False:
        return None
    else:
        #if valid user, load in user data
        user1 = um.load_user_data([update.message.from_user.username])
    #prompt usage if no context.args provided
    if context.args == []:
        context.bot.send_message(chat_id=user1["userid"], text='Usage: <b>/banish &lt;username&gt;</b>', parse_mode=ParseMode.HTML)
        return None
    else:
        username2 = context.args[0]
    #check if specified user exist(registered user)
    if um.check_exist_user("./userinfo/" + username2 + ".json") is False:
        context.bot.send_message(chat_id=user1["userid"], text="User cannot be found!")
        return None
    else:
        user2 = um.load_user_data([username2])
    #check if user is already blocked
    if user2["userid"] in user1["block_list"]:
        context.bot.send_message(chat_id=user1["userid"], text="<b>" + username2 + "</b> is already banished!", parse_mode=ParseMode.HTML)
    else:
        #if not blocked, add to block list
        user1["block_list"].append(user2["userid"])
        um.save_user_data([user1])
        context.bot.send_message(chat_id=user1["userid"], text="You have banished <b>" + username2 + "</b>! (To unbanish, use /unbanish)", parse_mode=ParseMode.HTML)
    return None
Exemplo n.º 2
0
def initiate_fight_user(update, context):
    """
    Function that executes from the /fight command. Initiates a battle request against another user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #if invalid user, the validate_user function will prompt to register with /war command
    if um.validate_user(update, context, update.message.chat_id, update.message.from_user.username) is False:
        return None
    else:
        #if valid user, load in user data
        user1 = um.load_user_data([update.message.from_user.username])
    #prompt usage if no context.args provided, else check user current status to make sure eligibility for making request
    if context.args == []:
        context.bot.send_message(chat_id=user1["userid"], text="Usage: <b>/fight &lt;username&gt;</b>", parse_mode=ParseMode.HTML)
        return None
    elif user1["user_status"] == "1":
        context.bot.send_message(chat_id=user1["userid"], text="You already have a pending request!")
        return None
    elif user1["user_status"] == "2" or user1["user_status"] == "3":
        context.bot.send_message(chat_id=user1["userid"], text="You are in the midst of a war!")
        return None
    else:
        username2 = context.args[0]
    #check if specified user exist(registered user)
    if um.check_exist_user("./userinfo/" + username2 + ".json") is False:
        context.bot.send_message(chat_id=user1["userid"], text="User cannot be found!")
        return None
    else:
        user2 = um.load_user_data([username2])
    #refuse the request if specified user has blocked requesting user
    if user1["userid"] in user2["block_list"]:
        context.bot.send_message(chat_id=user1["userid"], text="<b>" + user2["username"] + "</b> is unavailable for war!", parse_mode=ParseMode.HTML)
    elif user2["user_status"] == "1":
        context.bot.send_message(chat_id=user1["userid"], text="<b>" + user2["username"] + "</b> has a pending request!", parse_mode=ParseMode.HTML)
    elif user2["user_status"] == "2" or user1["user_status"] == "3":  
        context.bot.send_message(chat_id=user1["userid"], text="<b>" + user2["username"] + "</b> is in the midst of a war!", parse_mode=ParseMode.HTML)
    else:
        #switch user statuses to pending and send out battle declaration
        user1["user_status"], user2["user_status"] = "1", "1"
        um.save_user_data([user1, user2])
        reply_markup = mc.show_user_options(user1["username"], user2["username"], 2, ["Yes", "No"], ["accept", "decline"])
        context.bot.send_message(chat_id=user1["userid"], text="Enemy Detected...")
        context.bot.send_message(chat_id=user1["userid"], text="Declaring Battle...")
        declare_war = context.bot.send_message(chat_id=user2["userid"], text="<b>" + user1["username"] + "</b> has declared battle! Are you ready?", reply_markup=reply_markup, parse_mode=ParseMode.HTML)
        #start a thread to enforce a 30 second timeout rule
        threading.Thread(target=um.connect_users, args=(context.bot, user1, user2, declare_war.message_id, 0.5)).start()
    return None
Exemplo n.º 3
0
def decline_fight(update, context):
    """
    Function that takes in no response from user in declining a fight.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #answer query and loads user
    context.bot.answer_callback_query(update.callback_query.id)
    data = update.callback_query.data
    usernames = re.match(r'-decline-(\S+)-(\S+)', data)
    username1, username2 = usernames.group(1), usernames.group(2)
    user1, user2 = um.load_user_data([username1, username2])
    #ensure context.both users are at status 1 before declining the battle
    if user1["user_status"] == "1" and user2["user_status"] == "1":
        um.switch_user_status(user1, user2, "0", "0")
        context.bot.send_message(chat_id=user1["userid"],
                                 text="<b>" + user2["username"] +
                                 "</b> declined your request for war!",
                                 parse_mode=ParseMode.HTML)
        context.bot.editMessageText(
            chat_id=user2["userid"],
            message_id=update.callback_query.message.message_id,
            text="You declined the request for war from " + user1["username"] +
            "!")
    return None
Exemplo n.º 4
0
def launch_attack(update, context):
    """
    Function that takes in the attack response from user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #answer query and load users
    context.bot.answer_callback_query(update.callback_query.id)
    data = update.callback_query.data
    usernames = re.match(r'-1-(\S+)-(\S+)', data)
    username1, username2 = usernames.group(1), usernames.group(2)
    user1, user2 = um.load_user_data([username1, username2])
    #prevent user from executing if status is not 2
    if user1["user_status"] != "2":
        return None
    #switch user status and execute the attack
    um.switch_user_status(user1, user2, "3", "2")
    context.bot.deleteMessage(
        chat_id=user1["userid"],
        message_id=update.callback_query.message.message_id)
    context.bot.send_message(chat_id=user1["userid"],
                             text="You chose to attack!")
    gm.attack(context.bot, user1["username"], user2["username"])
    return None
Exemplo n.º 5
0
def reshow_main_options(update, context):
    """
    Function that takes in the back response from user to show the main prompt again.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #answer query and load users
    context.bot.answer_callback_query(update.callback_query.id)
    data = update.callback_query.data
    usernames = re.match(r'-reshow_main-(\S+)-(\S+)', data)
    username1, username2 = usernames.group(1), usernames.group(2)
    user1, user2 = um.load_user_data([username1, username2])
    #prevent user from executing if status is not 2
    if user1["user_status"] != "2":
        return None
    reply_markup = mc.show_user_options(user1["username"], user2["username"],
                                        4,
                                        ["Attack", "Repair", "Hire", "Flee"],
                                        ["1", "2", "3", "flee"])
    context.bot.editMessageText(
        chat_id=user1["userid"],
        message_id=update.callback_query.message.message_id,
        text="What will you do?",
        reply_markup=reply_markup)
    return None
Exemplo n.º 6
0
def reset_user(update, context):
    """
    Function that executes from the /reset command to reset user state to 0. Only admins have the right to execute this command.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #if invalid user, the validate_user function will prompt to register with /war command
    if um.validate_user(update, context, update.message.chat_id, update.message.from_user.username) is False:
        return None
    else:
        #if valid user, load in user data
        user1 = um.load_user_data([update.message.from_user.username])
    #only admin users can execute resets
    if user1["user_group"] == "admin":
        user2 = um.load_user_data([context.args[0]])
        user2["user_status"] = "0"
        um.save_user_data([user2])
        context.bot.send_message(chat_id=user1["userid"], text="User reset successful!")
    else:
        context.bot.send_message(chat_id=user1["userid"], text="You do not have the permission!")
    return None
Exemplo n.º 7
0
def run_code(update, context):
    """
    Run the code snippet of the user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    executing_code = False

    def load_animation(user, update, message):
        """
        Function that provides loading animation during code execution.
        Args:
            user: user running the code
            update: default telegram arg
            context: default telegram arg
        """
        lg.logbook(user, "run_code")
        while executing_code:
            message.edit_text(text="<b>Executing Code /</b>",
                              parse_mode=ParseMode.HTML)
            message.edit_text(text="<b>Executing Code -</b>",
                              parse_mode=ParseMode.HTML)
            message.edit_text(text="<b>Executing Code \\</b>",
                              parse_mode=ParseMode.HTML)
            message.edit_text(text="<b>Executing Code |</b>",
                              parse_mode=ParseMode.HTML)
        message.edit_text(text="<b>Execution Complete:</b>",
                          parse_mode=ParseMode.HTML)
        return None

    if not um.check_exist_user(update.message.chat_id):
        update.message.reply_text(
            "You are not registered. Try <b>/register</b>",
            parse_mode=ParseMode.HTML)
    else:
        executing_code = True
        executing = update.message.reply_text("<b>Executing Code |</b>",
                                              parse_mode=ParseMode.HTML)
        user = um.load_user_data(update.message.chat_id)
        threading.Thread(target=load_animation,
                         args=(user, update, executing)).start()
        with open("./config/endpoint.json", "r") as file:
            endpoint = json.load(file)["endpoint"]
        res = requests.post(endpoint, data={"userid": user["userid"]})
        output = res.content.decode('utf-8')[1:-1]
        executing_code = False
        update.message.reply_text(output)
    return None
Exemplo n.º 8
0
def retrieve_specified_log(update, context):
    """
    Function that retrieves specific log for user.
    Args:
        bot: from telegram bot
        update: from telegram update
    """
    context.bot.answer_callback_query(update.callback_query.id)
    data = update.callback_query.data
    match_file = re.match(r'get_logs_(\S+)_(\S+)', data)
    filename, userid = match_file.group(1), match_file.group(2)
    user = um.load_user_data(userid)
    with open("./logs/" + filename, "r") as file:
        content = file.read()
    context.bot.send_message(chat_id=user["userid"], text=content)
    return None
Exemplo n.º 9
0
def clear_code(update, context):
    """
    Clear the code snippet of the user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    if not um.check_exist_user(update.message.chat_id):
        update.message.reply_text(
            "You are not registered. Try <b>/register</b>",
            parse_mode=ParseMode.HTML)
    else:
        user = um.load_user_data(update.message.chat_id)
        user["code_snippet"] = ""
        um.save_user_data(user)
        update.message.reply_text("<b>Code Cleared</b>",
                                  parse_mode=ParseMode.HTML)
    return None
Exemplo n.º 10
0
def check_mode(update, context):
    """
    Function to check mode of user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    if not um.check_exist_user(update.message.chat_id):
        update.message.reply_text(
            "You are not registered. Try <b>/register</b>",
            parse_mode=ParseMode.HTML)
    else:
        user = um.load_user_data(update.message.chat_id)
        mode = user["mode"]
        if mode == "0":
            track_code(update.message.text, user)
        else:
            update.message.reply_text(
                "Invalid input. Use /code to toggle code mode.")
    return None
Exemplo n.º 11
0
def view_code(update, context):
    """
    View the current code of the user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    if not um.check_exist_user(update.message.chat_id):
        update.message.reply_text(
            "You are not registered. Try <b>/register</b>",
            parse_mode=ParseMode.HTML)
    else:
        user = um.load_user_data(update.message.chat_id)
        code = jsbeautifier.beautify(user["code_snippet"])
        if code == "":
            code = "<b>No Existing Code Found.</b>"
            update.message.reply_text(code, parse_mode=ParseMode.HTML)
        else:
            update.message.reply_text(code)
    return None
Exemplo n.º 12
0
def flee(update, context):
    """
    Function that takes in the flee response from user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #answer query and load users
    context.bot.answer_callback_query(update.callback_query.id)
    data = update.callback_query.data
    usernames = re.match(r'-flee-(\S+)-(\S+)', data)
    username1, username2 = usernames.group(1), usernames.group(2)
    user1, user2 = um.load_user_data([username1, username2])
    #prevent user from executing if status is not 2
    if user1["user_status"] != "2":
        return None
    context.bot.deleteMessage(
        chat_id=user1["userid"],
        message_id=update.callback_query.message.message_id)
    gm.flee(context.bot, user1["username"], user2["username"])
    return None
Exemplo n.º 13
0
def quit(update, context):
    """
    Function that takes in quit response at end of match.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #answer query and load users
    context.bot.answer_callback_query(update.callback_query.id)
    data = update.callback_query.data
    username = re.match(r'-quit-(\S+)-(\S+)', data)
    username = username.group(1)
    user = um.load_user_data([username])
    #set user status to 0
    user["user_status"] = "0"
    um.save_user_data([user])
    context.bot.edit_message_reply_markup(
        chat_id=user["userid"],
        message_id=update.callback_query.message.message_id,
        reply_markup=None)
    context.bot.send_message(chat_id=user["userid"], text="Match ended.")
    return None
Exemplo n.º 14
0
def toggle_code(update, context):
    """
    Function to toggle coding mode for user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    if not um.check_exist_user(update.message.chat_id):
        update.message.reply_text(
            "You are not registered. Try <b>/register</b>",
            parse_mode=ParseMode.HTML)
    else:
        user = um.load_user_data(update.message.chat_id)
        if user["mode"] == "0":
            user["mode"] = "1"
            update.message.reply_text("<b>Code Mode Disabled</b>",
                                      parse_mode=ParseMode.HTML)
        else:
            user["mode"] = "0"
            update.message.reply_text("<b>Code Mode Enabled</b>",
                                      parse_mode=ParseMode.HTML)
        um.save_user_data(user)
    return None
Exemplo n.º 15
0
def view_logs(update, context):
    """
    View the logs of the bot (admin only)
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    if not um.check_exist_user(update.message.chat_id):
        update.message.reply_text(
            "You are not registered. Try <b>/register</b>",
            parse_mode=ParseMode.HTML)
    else:
        user = um.load_user_data(update.message.chat_id)
    if not um.check_user_permission(user, "0"):
        update.message.reply_text("<b>Insufficient Permission.</b>",
                                  parse_mode=ParseMode.HTML)
    else:
        list_of_logs = os.listdir("./logs")
        retrieved_logs = show_logs(len(list_of_logs), list_of_logs, user)
        update.message.reply_text("<b>Please select a log:</b>",
                                  reply_markup=retrieved_logs,
                                  parse_mode=ParseMode.HTML)
    return None
Exemplo n.º 16
0
def repair(update, context):
    """
    Function that takes in the repair response from user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #answer query and load users
    context.bot.answer_callback_query(update.callback_query.id)
    data = update.callback_query.data
    usernames = re.match(r'-2\S*-(\S+)-(\S+)', data)
    username1, username2 = usernames.group(1), usernames.group(2)
    user1, user2 = um.load_user_data([username1, username2])
    #prevent user from executing if status is not 2
    if user1["user_status"] != "2":
        return None
    #variable to control actions
    approved_action = []
    #list of possible actions to take depending on button pressed (callback_query.data)
    if "-2-" in data and gm.check_gold(context.bot, user1["username"],
                                       int(config['castle']['repair_1'])):
        reply_markup = mc.show_user_options(
            user1["username"], user2["username"], 5,
            ["100 Gold", "200 Gold", "300 Gold", "Flee", "Back"],
            ["2.1", "2.2", "2.3", "flee", "reshow_main"])
        context.bot.editMessageText(
            chat_id=user1["userid"],
            message_id=update.callback_query.message.message_id,
            text="How much do you wish to repair? (1 Gold repairs 1 Health)",
            reply_markup=reply_markup)
    elif "-2.1-" in data and gm.check_gold(context.bot, user1["username"],
                                           int(config['castle']['repair_1'])):
        approved_action = [
            "-2.1-",
            "You chose to repair <b>100</b> Health with <b>100</b> Gold!"
        ]
    elif "-2.2-" in data and gm.check_gold(context.bot, user1["username"],
                                           int(config['castle']['repair_2'])):
        approved_action = [
            "-2.2-",
            "You chose to repair <b>200</b> Health with <b>200</b> Gold!"
        ]
    elif "-2.3-" in data and gm.check_gold(context.bot, user1["username"],
                                           int(config['castle']['repair_3'])):
        approved_action = [
            "-2.3-",
            "You chose to repair <b>300</b> Health with <b>300</b> Gold!"
        ]
    if approved_action != []:
        um.switch_user_status(user1, user2, "3", "2")
        context.bot.deleteMessage(
            chat_id=user1["userid"],
            message_id=update.callback_query.message.message_id)
        context.bot.send_message(chat_id=user1["userid"],
                                 text=approved_action[1],
                                 parse_mode=ParseMode.HTML)
        gm.repair(context.bot, user1["username"], user2["username"],
                  approved_action[0][1:4])
    elif "-2-" in data:
        pass
    else:
        context.bot.send_message(chat_id=user1["userid"],
                                 text="You do not have enough gold!")
    return None
Exemplo n.º 17
0
def hire(update, context):
    """
    Function that takes in the hire response from user.
    Args:
        update: default telegram arg
        context: default telegram arg
    """
    #answer query and load users
    context.bot.answer_callback_query(update.callback_query.id)
    data = update.callback_query.data
    usernames = re.match(r'-3\S*-(\S+)-(\S+)', data)
    username1, username2 = usernames.group(1), usernames.group(2)
    user1, user2 = um.load_user_data([username1, username2])
    #prevent user from executing if status is not 2
    if user1["user_status"] != "2":
        return None
    #variable to control actions
    approved_action = []
    #list of possible actions to take depending on button pressed (callback_query.data)
    if "-3-" in data and gm.check_gold(context.bot, user1["username"],
                                       5 * int(config['soldier']['price'])):
        reply_markup = mc.show_user_options(
            user1["username"], user2["username"], 5,
            ["Soldiers", "Warriors", "Knights", "Flee", "Back"],
            ["3.1", "3.2", "3.3", "flee", "reshow_main"])
        context.bot.editMessageText(
            chat_id=user1["userid"],
            message_id=update.callback_query.message.message_id,
            text="Which unit do you wish to hire?",
            reply_markup=reply_markup)
    elif "-3.1-" in data and gm.check_gold(context.bot, user1["username"], 5 *
                                           int(config['soldier']['price'])):
        reply_markup = mc.show_user_options(
            user1["username"], user2["username"], 5,
            ["5", "10", "15", "Flee", "Back"],
            ["3.1.1", "3.1.2", "3.1.3", "flee", "3"])
        context.bot.editMessageText(
            chat_id=user1["userid"],
            message_id=update.callback_query.message.message_id,
            text=
            "How many Soldiers do you wish to hire? (20 Gold, 5 Attack Damage each)",
            reply_markup=reply_markup)
    elif "-3.2-" in data and gm.check_gold(context.bot, user1["username"], 5 *
                                           int(config['warrior']['price'])):
        reply_markup = mc.show_user_options(
            user1["username"], user2["username"], 5,
            ["5", "10", "15", "Flee", "Back"],
            ["3.2.1", "3.2.2", "3.2.3", "flee", "3"])
        context.bot.editMessageText(
            chat_id=user1["userid"],
            message_id=update.callback_query.message.message_id,
            text=
            "How many Warriors do you wish to hire? (50 Gold, 10 Attack Damage each)",
            reply_markup=reply_markup)
    elif "-3.3-" in data and gm.check_gold(context.bot, user1["username"],
                                           5 * int(config['knight']['price'])):
        reply_markup = mc.show_user_options(
            user1["username"], user2["username"], 5,
            ["5", "10", "15", "Flee", "Back"],
            ["3.3.1", "3.3.2", "3.3.3", "flee", "3"])
        context.bot.editMessageText(
            chat_id=user1["userid"],
            message_id=update.callback_query.message.message_id,
            text=
            "How many Knights do you wish to hire? (100 Gold, 20 Attack Damage each)",
            reply_markup=reply_markup)
    elif "-3.1.1-" in data and gm.check_gold(
            context.bot, user1["username"],
            5 * int(config['soldier']['price'])):
        approved_action = ["-3.1.1-", "You chose to hire <b>5</b> Soldiers!"]
    elif "-3.1.2-" in data and gm.check_gold(
            context.bot, user1["username"],
            10 * int(config['soldier']['price'])):
        approved_action = ["-3.1.2-", "You chose to hire <b>10</b> Soldiers!"]
    elif "-3.1.3-" in data and gm.check_gold(
            context.bot, user1["username"],
            15 * int(config['soldier']['price'])):
        approved_action = ["-3.1.3-", "You chose to hire <b>15</b> Soldiers!"]
    elif "-3.2.1-" in data and gm.check_gold(
            context.bot, user1["username"],
            5 * int(config['warrior']['price'])):
        approved_action = ["-3.2.1-", "You chose to hire <b>5</b> Warriors!"]
    elif "-3.2.2-" in data and gm.check_gold(
            context.bot, user1["username"],
            10 * int(config['warrior']['price'])):
        approved_action = ["-3.2.2-", "You chose to hire <b>10</b> Warriors!"]
    elif "-3.2.3-" in data and gm.check_gold(
            context.bot, user1["username"],
            15 * int(config['warrior']['price'])):
        approved_action = ["-3.2.3-", "You chose to hire <b>15</b> Warriors!"]
    elif "-3.3.1-" in data and gm.check_gold(
            context.bot, user1["username"],
            5 * int(config['knight']['price'])):
        approved_action = ["-3.3.1-", "You chose to hire <b>5</b> Knights!"]
    elif "-3.3.2-" in data and gm.check_gold(
            context.bot, user1["username"],
            10 * int(config['knight']['price'])):
        approved_action = ["-3.3.2-", "You chose to hire <b>10</b> Knights!"]
    elif "-3.3.3-" in data and gm.check_gold(
            context.bot, user1["username"],
            15 * int(config['knight']['price'])):
        approved_action = ["-3.3.3-", "You chose to hire <b>15</b> Knights!"]
    if approved_action != []:
        um.switch_user_status(user1, user2, "3", "2")
        context.bot.deleteMessage(
            chat_id=user1["userid"],
            message_id=update.callback_query.message.message_id)
        context.bot.send_message(chat_id=user1["userid"],
                                 text=approved_action[1],
                                 parse_mode=ParseMode.HTML)
        gm.hire(context.bot, user1["username"], user2["username"],
                approved_action[0][1:6])
    elif "-3-" in data or "-3.1-" in data or "-3.2" in data or "-3.3-" in data:
        pass
    else:
        context.bot.send_message(chat_id=user1["userid"],
                                 text="You do not have enough gold!")
    return None